Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions avro/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,32 @@ public enum AvroReadFeature
*<p>
* 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()}).
*<p>
* 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.
*<p>
* 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;
Expand Down
82 changes: 75 additions & 7 deletions avro/src/main/java/tools/jackson/dataformat/avro/AvroSchema.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -40,6 +41,21 @@ public class AvroSchema implements FormatSchema
*/
protected final AtomicReference<AvroStructureReader> _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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -333,7 +399,8 @@ public String toString() {

@Override
public int hashCode() {
return super.hashCode() ^ _readerSchema.hashCode();
return super.hashCode() ^ _readerSchema.hashCode()
^ _originalWriterSchema.hashCode();
}

@Override
Expand All @@ -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);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand All @@ -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
Expand Down Expand Up @@ -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);
}

/*
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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();
}

Expand Down
Loading