diff --git a/avro/README.md b/avro/README.md index ab8b63591..5382e4c92 100644 --- a/avro/README.md +++ b/avro/README.md @@ -101,6 +101,25 @@ Employee empl = mapper.reader(Employee.class) .readValue(avroData); ``` +### Reading Single Object Encoding + +Avro "Single Object Encoding" (written by Avro's `BinaryMessageEncoder`, and by `toByteBuffer()` +of classes compiled from Avro schemas) adds a 10-byte header before each value: a 2-byte marker +and the fingerprint of the writer schema. To read such values, enable +`AvroReadFeature.READ_SINGLE_OBJECT_ENCODING` (since 3.4): + +```java +byte[] message = ... ; // as written by BinaryMessageEncoder +Employee empl = mapper.readerFor(Employee.class) + .with(schema) + .with(AvroReadFeature.READ_SINGLE_OBJECT_ENCODING) + .readValue(message); +``` + +The header of each value is verified: reading fails if its fingerprint is not that of the +writer schema used for reading. The feature needs to be enabled explicitly because the header +can not be reliably detected from content. + ## Writing avro data Writing Avro-encoded data follows similar pattern: diff --git a/avro/src/main/java/tools/jackson/dataformat/avro/AvroReadFeature.java b/avro/src/main/java/tools/jackson/dataformat/avro/AvroReadFeature.java index 5a1af1fcb..c653b2c08 100644 --- a/avro/src/main/java/tools/jackson/dataformat/avro/AvroReadFeature.java +++ b/avro/src/main/java/tools/jackson/dataformat/avro/AvroReadFeature.java @@ -16,7 +16,32 @@ public enum AvroReadFeature *

* Enabled by default to preserve the existing behavior. */ - AVRO_BUFFERING(true) + AVRO_BUFFERING(true), + + /** + * Feature that tells parser that each root-level value is in Avro "Single Object + * Encoding" (as written by {@code BinaryMessageEncoder} of Apache Avro lib): + * preceded by a header of 2-byte marker ({@code 0xC3 0x01}) and 8-byte + * fingerprint of the writer schema. Parser fails with + * {@link tools.jackson.core.exc.StreamReadException} if the marker is wrong, or the + * fingerprint is not that of the writer schema used for reading + * (see {@link AvroSchema#getWriterFingerprint()}). + *

+ * Note that the check is strict: schema used for reading (or, with + * {@link AvroSchema#withReaderSchema}, the writer schema given) must be the exact + * schema used for writing, as determined by its "Parsing Canonical Form", and + * not just a compatible one. For example, a schema generated with + * {@link AvroMapper#schemaFor} that differs from the writer schema in name or + * namespace of a named type will fail the check, even if the content itself could be + * decoded with it. Unlike Avro's {@code BinaryMessageDecoder} there is no + * lookup of alternate writer schemas by fingerprint. + *

+ * Disabled by default, since the header can not be reliably detected: + * "raw" content may start with the same two bytes. + * + * @since 3.4 + */ + READ_SINGLE_OBJECT_ENCODING(false) ; private final boolean _defaultState; diff --git a/avro/src/main/java/tools/jackson/dataformat/avro/AvroSchema.java b/avro/src/main/java/tools/jackson/dataformat/avro/AvroSchema.java index e2881c623..4f493f701 100644 --- a/avro/src/main/java/tools/jackson/dataformat/avro/AvroSchema.java +++ b/avro/src/main/java/tools/jackson/dataformat/avro/AvroSchema.java @@ -11,6 +11,7 @@ import org.apache.avro.SchemaCompatibility; import org.apache.avro.SchemaCompatibility.SchemaCompatibilityType; import org.apache.avro.SchemaCompatibility.SchemaPairCompatibility; +import org.apache.avro.SchemaNormalization; import tools.jackson.core.FormatSchema; import tools.jackson.core.JsonParser; @@ -40,6 +41,21 @@ public class AvroSchema implements FormatSchema */ protected final AtomicReference _reader = new AtomicReference<>(); + /** + * Lazily calculated fingerprint of the writer schema; only valid once + * {@link #_writerFingerprintSet} is {@code true}. + * + * @since 3.4 + */ + private long _writerFingerprint; + + /** + * Written after {@link #_writerFingerprint} and read before it, to make it visible. + * + * @since 3.4 + */ + private volatile boolean _writerFingerprintSet; + /** * Outcomes of resolving type ids (as used by {@link AvroStructureReader}s of * this schema) into names of Java classes, separately for each ClassLoader @@ -119,7 +135,7 @@ public AvroSchema withReaderSchema(AvroSchema readerSchema) throw DatabindException.from((JsonParser) null, String.format("Incompatible writer/reader schemas: %s", comp.getDescription())); } - return Resolving.create(w, r); + return Resolving.create(w, r, _fingerprintSchema()); } private boolean _schemaNamesEqual(Schema w, Schema r) @@ -157,7 +173,7 @@ public AvroSchema withUnsafeReaderSchema(AvroSchema readerSchema) return this; } w = Schema.applyAliases(w, r); - return Resolving.create(w, r); + return Resolving.create(w, r, _fingerprintSchema()); } @Override @@ -170,6 +186,33 @@ public String getSchemaType() { */ public Schema getAvroSchema() { return _writerSchema; } + /** + * Accessor for the 64-bit ("CRC-64-AVRO") fingerprint of the writer schema: the one + * that the header of Avro "Single Object Encoding" contains. With a reader schema, + * it is that of the writer schema as given (without aliases of the reader schema). + * + * @since 3.4 + */ + public long getWriterFingerprint() + { + // Racy but benign: concurrent calls would calculate the same value + if (!_writerFingerprintSet) { + _writerFingerprint = SchemaNormalization.parsingFingerprint64(_fingerprintSchema()); + _writerFingerprintSet = true; + } + return _writerFingerprint; + } + + /** + * Accessor for the writer schema whose fingerprint {@link #getWriterFingerprint()} + * returns. + * + * @since 3.4 + */ + Schema _fingerprintSchema() { + return _writerSchema; + } + /* /********************************************************************** /* Factory methods @@ -305,14 +348,37 @@ private final static class Resolving extends AvroSchema { private final Schema _readerSchema; - public Resolving(Schema writer, Schema reader) + /** + * Writer schema as given, before aliases of the reader schema were applied: + * needed for calculating its fingerprint. + * + * @since 3.4 + */ + private final Schema _originalWriterSchema; + + /** + * @since 3.4 + */ + public Resolving(Schema writer, Schema reader, Schema originalWriter) { super(writer); _readerSchema = reader; + _originalWriterSchema = originalWriter; } - public static Resolving create(Schema writer, Schema reader) { - return new Resolving(writer, reader); + /** + * @since 3.4 + */ + public static Resolving create(Schema writer, Schema reader, Schema originalWriter) { + return new Resolving(writer, reader, originalWriter); + } + + /** + * @since 3.4 + */ + @Override + Schema _fingerprintSchema() { + return _originalWriterSchema; } @Override @@ -333,7 +399,8 @@ public String toString() { @Override public int hashCode() { - return super.hashCode() ^ _readerSchema.hashCode(); + return super.hashCode() ^ _readerSchema.hashCode() + ^ _originalWriterSchema.hashCode(); } @Override @@ -342,7 +409,8 @@ public boolean equals(Object o) { if ((o == null) || o.getClass() != getClass()) return false; Resolving other = (Resolving) o; return _writerSchema.equals(other._writerSchema) - && _readerSchema.equals(other._readerSchema); + && _readerSchema.equals(other._readerSchema) + && _originalWriterSchema.equals(other._originalWriterSchema); } } } diff --git a/avro/src/main/java/tools/jackson/dataformat/avro/deser/AvroParserImpl.java b/avro/src/main/java/tools/jackson/dataformat/avro/deser/AvroParserImpl.java index 544986e0c..0366352a3 100644 --- a/avro/src/main/java/tools/jackson/dataformat/avro/deser/AvroParserImpl.java +++ b/avro/src/main/java/tools/jackson/dataformat/avro/deser/AvroParserImpl.java @@ -9,6 +9,7 @@ import tools.jackson.core.io.IOContext; import tools.jackson.core.sym.PropertyNameMatcher; import tools.jackson.dataformat.avro.AvroParser; +import tools.jackson.dataformat.avro.AvroReadFeature; import tools.jackson.dataformat.avro.AvroSchema; /** @@ -28,6 +29,14 @@ public abstract class AvroParserImpl */ protected final static int LONGEST_NON_CHUNKED_BINARY_READ = 250_000; + /** + * Length of the Avro "Single Object Encoding" header: 2-byte marker followed by + * 8-byte schema fingerprint. + * + * @since 3.4 + */ + private final static int SINGLE_OBJECT_HEADER_LENGTH = 10; + /* /********************************************************************** /* Decoding state @@ -227,7 +236,10 @@ public int nextNameMatch(PropertyNameMatcher matcher) throws JacksonException @Override public final void _initSchema(AvroSchema schema) throws JacksonException { - _avroContext = new RootReader(this, schema.getReader()); + Long singleObjectFingerprint = isEnabled(AvroReadFeature.READ_SINGLE_OBJECT_ENCODING) + ? schema.getWriterFingerprint() + : null; + _avroContext = new RootReader(this, schema.getReader(), singleObjectFingerprint); } /* @@ -554,6 +566,33 @@ public long getRemainingElements() */ } + /** + * Method called to read and verify the Avro "Single Object Encoding" header + * preceding a root-level value. + * + * @since 3.4 + */ + final void _readSingleObjectHeader(long expectedFingerprint) throws IOException + { + decodeFixed(SINGLE_OBJECT_HEADER_LENGTH); + final byte[] header = _binaryValue; + _binaryValue = null; + if ((header[0] != (byte) 0xC3) || (header[1] != (byte) 0x01)) { + _reportError(String.format( +"Invalid Avro Single Object Encoding header: expected marker bytes 0xC3 0x01, got 0x%02X 0x%02X", + header[0] & 0xFF, header[1] & 0xFF)); + } + long fingerprint = 0L; + for (int i = SINGLE_OBJECT_HEADER_LENGTH - 1; i >= 2; --i) { + fingerprint = (fingerprint << 8) | (header[i] & 0xFFL); + } + if (fingerprint != expectedFingerprint) { + _reportError(String.format( +"Avro Single Object Encoding schema fingerprint mismatch: value has 0x%016X, writer schema used for reading has 0x%016X", + fingerprint, expectedFingerprint)); + } + } + /* /********************************************************************** /* Methods for AvroReadContext implementations: decoding int diff --git a/avro/src/main/java/tools/jackson/dataformat/avro/deser/RootReader.java b/avro/src/main/java/tools/jackson/dataformat/avro/deser/RootReader.java index e6b5d6418..ca3dda630 100644 --- a/avro/src/main/java/tools/jackson/dataformat/avro/deser/RootReader.java +++ b/avro/src/main/java/tools/jackson/dataformat/avro/deser/RootReader.java @@ -14,12 +14,36 @@ public class RootReader extends AvroReadContext private final AvroParserImpl _parser; private final AvroStructureReader _valueReader; + /** + * Fingerprint of the writer schema, if each root-level value is expected to + * have Avro "Single Object Encoding" header; {@code null} if not. + * + * @since 3.4 + */ + private final Long _singleObjectFingerprint; + + /** + * @deprecated Since 3.4 use {@link #RootReader(AvroParserImpl, AvroStructureReader, Long)} + */ + @Deprecated // since 3.4 public RootReader(AvroParserImpl parser, AvroStructureReader valueReader) { + this(parser, valueReader, null); + } + + /** + * @param singleObjectFingerprint Fingerprint of the writer schema, if each root-level + * value is expected to have Avro "Single Object Encoding" header; {@code null} if not + * + * @since 3.4 + */ + public RootReader(AvroParserImpl parser, + AvroStructureReader valueReader, Long singleObjectFingerprint) { super(null, null); _type = TYPE_ROOT; _parser = parser; _valueReader = valueReader; + _singleObjectFingerprint = singleObjectFingerprint; } @Override @@ -29,10 +53,14 @@ public JsonToken nextToken() throws IOException { if (_parser.checkInputEnd()) { // 26-Aug-2019, tatu: As per [dataformats-binary#177], 0-field Records consume // no content, and if so we MUST NOT indicate end-of-content: - if (!_valueReader.consumesNoContent()) { + // [dataformats-binary#343]: unless each value has a header + if ((_singleObjectFingerprint != null) || !_valueReader.consumesNoContent()) { return null; } } + if (_singleObjectFingerprint != null) { + _parser._readSingleObjectHeader(_singleObjectFingerprint); + } return _valueReader.newReader(this, _parser).nextToken(); } diff --git a/avro/src/test/java/tools/jackson/dataformat/avro/SingleObjectEncoding343Test.java b/avro/src/test/java/tools/jackson/dataformat/avro/SingleObjectEncoding343Test.java new file mode 100644 index 000000000..bb312c4c6 --- /dev/null +++ b/avro/src/test/java/tools/jackson/dataformat/avro/SingleObjectEncoding343Test.java @@ -0,0 +1,423 @@ +package tools.jackson.dataformat.avro; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.EOFException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import org.apache.avro.Schema; +import org.apache.avro.SchemaNormalization; +import org.apache.avro.generic.GenericData; +import org.apache.avro.generic.GenericDatumWriter; +import org.apache.avro.generic.GenericRecord; +import org.apache.avro.generic.GenericRecordBuilder; +import org.apache.avro.io.BinaryEncoder; +import org.apache.avro.io.EncoderFactory; +import org.apache.avro.message.BinaryMessageEncoder; +import org.junit.jupiter.api.Test; + +import tools.jackson.core.JacksonException; +import tools.jackson.core.JsonParser; +import tools.jackson.core.JsonToken; +import tools.jackson.core.StreamReadConstraints; +import tools.jackson.core.exc.StreamConstraintsException; +import tools.jackson.core.exc.StreamReadException; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.MappingIterator; +import tools.jackson.databind.ObjectReader; +import tools.jackson.dataformat.avro.testsupport.ThrottledInputStream; + +import static org.junit.jupiter.api.Assertions.*; + +// [dataformats-binary#343]: reading Avro "Single Object Encoding" +public class SingleObjectEncoding343Test extends AvroTestBase +{ + private final static Schema SCHEMA = schema( + "{'type':'record','name':'SampleRecord','fields':[{'name':'name','type':'string'}]}"); + + private final static String INVALID_HEADER = "Invalid Avro Single Object Encoding header"; + + private final AvroMapper[] MAPPERS = Arrays.stream(builders()) + .map(b -> new AvroMapper(b.build())) + .toArray(AvroMapper[]::new); + + @Test + public void testReadSingleObjectEncoding() throws Exception + { + // Single Object Encoding is what `SpecificRecord.toByteBuffer()` uses (Avro 1.8+) + byte[] bytes = encodeSingleObject(SCHEMA, record("apm")); + assertEquals((byte) 0xC3, bytes[0]); + assertEquals((byte) 0x01, bytes[1]); + + for (AvroMapper mapper : MAPPERS) { + ObjectReader r = singleObjectReader(mapper, SCHEMA); + assertEquals("apm", r.readTree(bytes).get("name").asString()); + assertEquals("apm", r.readTree(new ByteArrayInputStream(bytes)).get("name").asString()); + } + } + + @Test + public void testReadSequenceOfSingleObjectValues() throws Exception + { + byte[] bytes = concat(encodeSingleObject(SCHEMA, record("a")), + encodeSingleObject(SCHEMA, record("bc"))); + + for (AvroMapper mapper : MAPPERS) { + ObjectReader r = singleObjectReader(mapper, SCHEMA).forType(JsonNode.class); + assertNames(r.readValues(bytes), "a", "bc"); + assertNames(r.readValues(new ThrottledInputStream(bytes, 3)), "a", "bc"); + } + } + + @Test + public void testReadWithReaderSchema() throws Exception + { + Schema readerSchema = schema("{'type':'record','name':'SampleRecord','fields':[" + + "{'name':'name','type':'string'}," + + "{'name':'count','type':'int','default':7}]}"); + AvroSchema resolving = new AvroSchema(SCHEMA).withReaderSchema(new AvroSchema(readerSchema)); + byte[] bytes = encodeSingleObject(SCHEMA, record("apm")); + + for (AvroMapper mapper : MAPPERS) { + JsonNode result = singleObjectReader(mapper, resolving).readTree(bytes); + assertEquals("apm", result.get("name").asString()); + assertEquals(7, result.get("count").asInt()); + } + } + + // Aliases of reader schema are applied to writer schema, but must not change + // its fingerprint + @Test + public void testReadWithReaderSchemaAliases() throws Exception + { + Schema writerSchema = schema("{'type':'record','name':'OldRecord','fields':[" + + "{'name':'oldName','type':'string'}]}"); + AvroSchema reader = new AvroSchema(schema( + "{'type':'record','name':'NewRecord','aliases':['OldRecord'],'fields':[" + + "{'name':'newName','type':'string','aliases':['oldName']}]}")); + AvroSchema otherReader = new AvroSchema(schema( + "{'type':'record','name':'NewRecord','aliases':['OldRecord'],'fields':[" + + "{'name':'newName','type':'string','aliases':['oldName']}," + + "{'name':'count','type':'int','default':7}]}")); + GenericRecord record = new GenericData.Record(writerSchema); + record.put("oldName", "apm"); + byte[] bytes = encodeSingleObject(writerSchema, record); + + AvroSchema writer = new AvroSchema(writerSchema); + AvroSchema[] schemas = new AvroSchema[] { + writer.withReaderSchema(reader), + writer.withUnsafeReaderSchema(reader), + writer.withReaderSchema(reader).withReaderSchema(otherReader), + writer.withReaderSchema(reader).withUnsafeReaderSchema(otherReader) + }; + for (AvroSchema schema : schemas) { + assertEquals(writer.getWriterFingerprint(), schema.getWriterFingerprint()); + } + // Writer schema that equals the aliased one has a different fingerprint, + // and so the resolving schemas must not be equal either + AvroSchema renamed = new AvroSchema(schema("{'type':'record','name':'NewRecord','fields':[" + + "{'name':'newName','type':'string'}]}")).withReaderSchema(otherReader); + assertNotEquals(writer.getWriterFingerprint(), renamed.getWriterFingerprint()); + assertNotEquals(writer.withReaderSchema(otherReader), renamed); + + for (AvroMapper mapper : MAPPERS) { + for (AvroSchema schema : schemas) { + assertEquals("apm", singleObjectReader(mapper, schema).readTree(bytes) + .get("newName").asString()); + } + assertEquals(7, singleObjectReader(mapper, schemas[2]).readTree(bytes) + .get("count").asInt()); + } + } + + // 0-field records consume no content, but their headers do + @Test + public void testReadEmptyRecords() throws Exception + { + Schema emptySchema = schema("{'type':'record','name':'Empty','fields':[]}"); + byte[] value = encodeSingleObject(emptySchema, new GenericData.Record(emptySchema)); + byte[] bytes = concat(value, value); + assertEquals(20, bytes.length); + + for (AvroMapper mapper : MAPPERS) { + try (MappingIterator it = singleObjectReader(mapper, emptySchema) + .forType(JsonNode.class).readValues(bytes)) { + assertEquals(0, it.nextValue().size()); + assertEquals(0, it.nextValue().size()); + assertFalse(it.hasNextValue()); + } + } + } + + @Test + public void testFailForTruncatedHeader() throws Exception + { + byte[] bytes = Arrays.copyOf(encodeSingleObject(SCHEMA, record("apm")), 6); + + for (AvroMapper mapper : MAPPERS) { + JacksonException e = assertThrows(JacksonException.class, + () -> singleObjectReader(mapper, SCHEMA).readTree(bytes)); + // Apache decoder reports end-of-input as `EOFException`, wrapped + if (!(e.getCause() instanceof EOFException)) { + verifyException(e, "end-of-input"); + } + } + } + + @Test + public void testFailForMissingHeader() throws Exception + { + byte[] otherVersion = encodeSingleObject(SCHEMA, record("apm")); + otherVersion[1] = 0x02; + byte[] otherMarker = encodeSingleObject(SCHEMA, record("apm")); + otherMarker[0] = (byte) 0xC2; + byte[] noHeader = encodeBinary(record("no header in this one")); + + for (AvroMapper mapper : MAPPERS) { + ObjectReader r = singleObjectReader(mapper, SCHEMA); + verifyException(assertThrows(StreamReadException.class, () -> r.readTree(noHeader)), + INVALID_HEADER); + verifyException(assertThrows(StreamReadException.class, () -> r.readTree(otherVersion)), + INVALID_HEADER + ": expected marker bytes 0xC3 0x01, got 0xC3 0x02"); + verifyException(assertThrows(StreamReadException.class, () -> r.readTree(otherMarker)), + INVALID_HEADER + ": expected marker bytes 0xC3 0x01, got 0xC2 0x01"); + } + } + + @Test + public void testFailForFingerprintMismatch() throws Exception + { + Schema otherSchema = schema( + "{'type':'record','name':'OtherRecord','fields':[{'name':'name','type':'string'}]}"); + byte[] bytes = encodeSingleObject(otherSchema, record("apm")); + String fingerprints = String.format( + "value has 0x%016X, writer schema used for reading has 0x%016X", + SchemaNormalization.parsingFingerprint64(otherSchema), + SchemaNormalization.parsingFingerprint64(SCHEMA)); + + for (AvroMapper mapper : MAPPERS) { + StreamReadException e = assertThrows(StreamReadException.class, + () -> singleObjectReader(mapper, SCHEMA).readTree(bytes)); + verifyException(e, "schema fingerprint mismatch"); + verifyException(e, fingerprints); + } + } + + @Test + public void testFailForValueWithoutHeaderInSequence() throws Exception + { + byte[] bytes = concat(encodeSingleObject(SCHEMA, record("a")), + encodeBinary(record("no header in this one"))); + + for (AvroMapper mapper : MAPPERS) { + try (MappingIterator it = singleObjectReader(mapper, SCHEMA) + .forType(JsonNode.class).readValues(bytes)) { + assertEquals("a", it.nextValue().get("name").asString()); + verifyException(assertThrows(StreamReadException.class, it::nextValue), + INVALID_HEADER); + } + } + } + + @Test + public void testHeadersCountForMaxDocumentLength() throws Exception + { + byte[] value = encodeSingleObject(SCHEMA, record("abc")); + byte[] bytes = concat(value, value, value); + assertEquals(42, bytes.length); + + for (int maxLength : new int[] { 41, 42 }) { + StreamReadConstraints constraints = StreamReadConstraints.builder() + .maxDocumentLength(maxLength).build(); + for (AvroFactoryBuilder b : builders()) { + AvroMapper mapper = new AvroMapper(b.streamReadConstraints(constraints).build()); + try (MappingIterator it = singleObjectReader(mapper, SCHEMA) + .forType(JsonNode.class).readValues(new ByteArrayInputStream(bytes))) { + if (maxLength < bytes.length) { + assertThrows(StreamConstraintsException.class, it::readAll); + } else { + assertEquals(3, it.readAll().size()); + } + } + } + } + } + + // Fingerprint must be calculated the same way as by Apache Avro lib, for + // schema using all kinds of attributes that are not part of Parsing Canonical Form + @Test + public void testWriterFingerprintSameAsApache() throws Exception + { + Schema schema = schema("{" + +"'type':'record','name':'Order','namespace':'com.example.orders'," + +"'doc':'An order','aliases':['OldOrder'],'custom':'value'," + +"'fields':[" + +" {'name':'id','type':{'type':'string','logicalType':'uuid'}," + +" 'default':'00000000-0000-0000-0000-000000000000','doc':'Id','aliases':['key']}," + +" {'name':'created','type':{'type':'long','logicalType':'timestamp-millis'},'default':0}," + +" {'name':'amount','type':{'type':'bytes','logicalType':'decimal','precision':9,'scale':2}," + +" 'default':''}," + +" {'name':'status','type':{'type':'enum','name':'Status','namespace':'com.example.common'," + +" 'symbols':['NEW','DONE'],'default':'NEW'},'default':'DONE','order':'descending'}," + +" {'name':'code','type':{'type':'fixed','name':'Code','size':2},'default':'ab'}," + +" {'name':'tags','type':{'type':'map'," + +" 'values':{'type':'array','items':'com.example.common.Status'}},'default':{}}," + +" {'name':'next','type':['null','Order'],'default':null}," + +" {'name':'line','type':{'type':'record','name':'Line'," + +" 'fields':[{'name':'qty','type':'int','default':1}]},'default':{'qty':2}}" + +"]}"); + byte[] bytes = encodeSingleObject(schema, new GenericRecordBuilder(schema).build()); + long fingerprint = ByteBuffer.wrap(bytes, 2, 8).order(ByteOrder.LITTLE_ENDIAN).getLong(); + assertEquals(fingerprint, new AvroSchema(schema).getWriterFingerprint()); + + for (AvroMapper mapper : MAPPERS) { + JsonNode result = singleObjectReader(mapper, schema).readTree(bytes); + assertEquals("DONE", result.get("status").asString()); + assertEquals(2, result.get("line").get("qty").asInt()); + } + } + + @Test + public void testReadNonRecordRoots() throws Exception + { + final Object[][] cases = new Object[][] { + { "'string'", "abc", "\"abc\"" }, + { "'long'", 123L, "123" }, + { "'null'", null, "null" }, + { "['null','string']", "x", "\"x\"" }, + { "{'type':'array','items':'int'}", List.of(1, 2), "[1,2]" }, + { "{'type':'map','values':'int'}", Map.of("k", 3), "{\"k\":3}" }, + { "{'type':'enum','name':'Size','symbols':['S','M']}", + new GenericData.EnumSymbol(null, "M"), "\"M\"" }, + { "{'type':'fixed','name':'Pair','size':2}", + new GenericData.Fixed(null, new byte[] { 1, 2 }), "\"AQI=\"" } + }; + for (Object[] c : cases) { + final Schema schema = schema((String) c[0]); + final byte[] value = encodeSingleObject(schema, c[1]); + final byte[] bytes = concat(value, value); + + for (AvroMapper mapper : MAPPERS) { + ObjectReader r = singleObjectReader(mapper, schema) + .without(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + for (boolean stream : new boolean[] { false, true }) { + try (JsonParser p = stream + ? r.createParser(new ThrottledInputStream(bytes, 3)) + : r.createParser(bytes)) { + assertEquals(c[2], r.readTree(p).toString()); + assertEquals(c[2], r.readTree(p).toString()); + assertNull(p.nextToken()); + } + } + } + } + } + + @Test + public void testHeaderNotExposedAsBinaryValue() throws Exception + { + byte[] bytes = encodeSingleObject(SCHEMA, record("apm")); + Schema stringSchema = Schema.create(Schema.Type.STRING); + byte[] base64 = encodeSingleObject(stringSchema, "AQI="); + + for (AvroMapper mapper : MAPPERS) { + try (JsonParser p = singleObjectReader(mapper, SCHEMA).createParser(bytes)) { + assertToken(JsonToken.START_OBJECT, p.nextToken()); + assertNull(p.getEmbeddedObject()); + } + byte[] value = singleObjectReader(mapper, stringSchema) + .forType(byte[].class) + .readValue(base64); + assertArrayEquals(new byte[] { 1, 2 }, value); + } + } + + // Contrast: regular Avro binary encoding (NOT Single Object Encoding) works as before + @Test + public void testReadRegularBinaryEncoding() throws Exception + { + byte[] bytes = encodeBinary(record("apm")); + // First byte is length of String (3 as zigzag VarInt), not 0xC3 + assertEquals((byte) 0x06, bytes[0]); + + for (AvroMapper mapper : MAPPERS) { + JsonNode result = mapper.reader(new AvroSchema(SCHEMA)).readTree(bytes); + assertEquals("apm", result.get("name").asString()); + } + } + + /* + /********************************************************************** + /* Helper methods + /********************************************************************** + */ + + private static AvroFactoryBuilder[] builders() { + return new AvroFactoryBuilder[] { + AvroFactory.builderWithNativeDecoder(), + AvroFactory.builderWithApacheDecoder(), + AvroFactory.builderWithApacheDecoder().disable(AvroReadFeature.AVRO_BUFFERING) + }; + } + + private static ObjectReader singleObjectReader(AvroMapper mapper, Schema schema) { + return singleObjectReader(mapper, new AvroSchema(schema)); + } + + private static ObjectReader singleObjectReader(AvroMapper mapper, AvroSchema schema) { + return mapper.reader(schema) + .with(AvroReadFeature.READ_SINGLE_OBJECT_ENCODING); + } + + private static void assertNames(MappingIterator it, String... names) throws Exception + { + try (it) { + List values = it.readAll(); + assertEquals(names.length, values.size()); + for (int i = 0; i < names.length; ++i) { + assertEquals(names[i], values.get(i).get("name").asString()); + } + } + } + + private static Schema schema(String json) { + return new Schema.Parser().parse(a2q(json)); + } + + private static GenericRecord record(String name) { + GenericRecord record = new GenericData.Record(SCHEMA); + record.put("name", name); + return record; + } + + private static byte[] encodeSingleObject(Schema schema, Object datum) throws Exception + { + ByteBuffer buf = new BinaryMessageEncoder(GenericData.get(), schema).encode(datum); + byte[] bytes = new byte[buf.remaining()]; + buf.get(bytes); + return bytes; + } + + private static byte[] encodeBinary(GenericRecord record) throws Exception + { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null); + new GenericDatumWriter(record.getSchema()).write(record, encoder); + encoder.flush(); + return out.toByteArray(); + } + + private static byte[] concat(byte[]... parts) throws Exception + { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (byte[] part : parts) { + out.write(part); + } + return out.toByteArray(); + } +} diff --git a/avro/src/test/java/tools/jackson/dataformat/avro/tofix/SingleObjectEncoding343Test.java b/avro/src/test/java/tools/jackson/dataformat/avro/tofix/SingleObjectEncoding343Test.java deleted file mode 100644 index 20ad613a1..000000000 --- a/avro/src/test/java/tools/jackson/dataformat/avro/tofix/SingleObjectEncoding343Test.java +++ /dev/null @@ -1,107 +0,0 @@ -package tools.jackson.dataformat.avro.tofix; - -import java.io.ByteArrayOutputStream; -import java.nio.ByteBuffer; - -import org.apache.avro.Schema; -import org.apache.avro.generic.GenericData; -import org.apache.avro.generic.GenericDatumWriter; -import org.apache.avro.generic.GenericRecord; -import org.apache.avro.io.BinaryEncoder; -import org.apache.avro.io.DatumWriter; -import org.apache.avro.io.EncoderFactory; -import org.apache.avro.message.BinaryMessageEncoder; - -import org.junit.jupiter.api.Test; - -import tools.jackson.databind.JsonNode; -import tools.jackson.dataformat.avro.AvroMapper; -import tools.jackson.dataformat.avro.AvroSchema; -import tools.jackson.dataformat.avro.testutil.failure.JacksonTestFailureExpected; - -import static org.junit.jupiter.api.Assertions.*; - -/** - * Reproducer for [dataformats-binary#343]: decoding data encoded with Apache Avro's - * Single Object Encoding (magic bytes 0xC3 0x01 + 8-byte schema fingerprint + payload) - * fails with "Invalid length indicator for String: -98". - */ -public class SingleObjectEncoding343Test -{ - private static final String SCHEMA_JSON = "{" - + "\"type\": \"record\"," - + "\"name\": \"SampleRecord\"," - + "\"fields\": [" - + " {\"name\": \"name\", \"type\": \"string\"}" - + "]}"; - - private final AvroMapper MAPPER = new AvroMapper(); - - /** - * Test showing the failure: data encoded with Apache Avro's BinaryMessageEncoder - * (Single Object Encoding) cannot be decoded by Jackson's AvroMapper. - * The first two bytes are the magic 0xC3 0x01 which decode as zigzag VarInt -98, - * causing "Invalid length indicator for String: -98". - */ - @JacksonTestFailureExpected - @Test - public void testReadSingleObjectEncoding() throws Exception - { - Schema apacheSchema = new Schema.Parser().parse(SCHEMA_JSON); - AvroSchema jacksonSchema = new AvroSchema(apacheSchema); - - // Encode using Apache Avro's Single Object Encoding (BinaryMessageEncoder), - // which is what SpecificRecord.toByteBuffer() uses in Apache Avro 1.8+. - // The encoded bytes start with magic: 0xC3 0x01 - BinaryMessageEncoder encoder = - new BinaryMessageEncoder<>(GenericData.get(), apacheSchema); - GenericRecord record = new GenericData.Record(apacheSchema); - record.put("name", "apm"); - ByteBuffer encoded = encoder.encode(record); - byte[] bytes = toByteArray(encoded); - - // Verify the magic bytes are present (the root cause of the failure) - assertEquals((byte) 0xC3, bytes[0], "First magic byte should be 0xC3"); - assertEquals((byte) 0x01, bytes[1], "Second magic byte should be 0x01"); - - // This currently fails with: - // "Invalid length indicator for String: -98" - // because Jackson tries to decode 0xC3 0x01 as a zigzag VarInt string length - JsonNode result = MAPPER.reader(jacksonSchema).readTree(bytes); - assertNotNull(result); - assertEquals("apm", result.get("name").asString()); - } - - /** - * Contrast: regular Avro binary encoding (NOT Single Object Encoding) works fine. - */ - @Test - public void testReadRegularBinaryEncoding() throws Exception - { - Schema apacheSchema = new Schema.Parser().parse(SCHEMA_JSON); - AvroSchema jacksonSchema = new AvroSchema(apacheSchema); - - // Encode using regular binary encoder (no SOE header) - ByteArrayOutputStream out = new ByteArrayOutputStream(); - BinaryEncoder binaryEncoder = EncoderFactory.get().binaryEncoder(out, null); - DatumWriter writer = new GenericDatumWriter<>(apacheSchema); - GenericRecord record = new GenericData.Record(apacheSchema); - record.put("name", "apm"); - writer.write(record, binaryEncoder); - binaryEncoder.flush(); - byte[] bytes = out.toByteArray(); - - // First byte should be 0x06 (zigzag VarInt for length 3), not 0xC3 - assertEquals((byte) 0x06, bytes[0]); - - JsonNode result = MAPPER.reader(jacksonSchema).readTree(bytes); - assertNotNull(result); - assertEquals("apm", result.get("name").asString()); - } - - private static byte[] toByteArray(ByteBuffer buf) { - byte[] bytes = new byte[buf.remaining()]; - buf.get(bytes); - return bytes; - } -} diff --git a/release-notes/CREDITS b/release-notes/CREDITS index 3e01b3011..a0b8fe4b8 100644 --- a/release-notes/CREDITS +++ b/release-notes/CREDITS @@ -136,3 +136,15 @@ Dhanraj E (@Dhanu-dynamic) * Contributed #912: (cbor) Do not read 32-bit lengths of 2^31 or more as indefinite length (3.1.9) + +@birTiwana + +* Reported #343: (avro) Support Avro "single-object encoding" decoding with + `AvroReadFeature.READ_SINGLE_OBJECT_ENCODING` + (3.4.0) + +Vineet Singh (@Vineet829) + +* Contributed #343: (avro) Support Avro "single-object encoding" decoding with + `AvroReadFeature.READ_SINGLE_OBJECT_ENCODING` + (3.4.0) diff --git a/release-notes/VERSION b/release-notes/VERSION index f36930879..452aad4e5 100644 --- a/release-notes/VERSION +++ b/release-notes/VERSION @@ -14,6 +14,13 @@ implementations) === Releases === ------------------------------------------------------------------------ +3.4.0 (not yet released) + +#343: (avro) Support Avro "single-object encoding" decoding with + `AvroReadFeature.READ_SINGLE_OBJECT_ENCODING` + (reported by @birTiwana) + (contributed by @Vineet829) + 3.3.1 (not yet released) #906: (avro) Do not initialize class named by Avro schema when resolving its full name;