From e508a64cf1f26cb63f1c401a2b1e91b8e5df8d5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BB=98=E5=85=B8?= Date: Thu, 3 Dec 2026 09:18:28 +0800 Subject: [PATCH] Add Avro single-object encoding for writing (#172) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 付典 --- avro/README.md | 15 +- .../dataformat/avro/AvroGenerator.java | 45 +++- .../dataformat/avro/AvroWriteFeature.java | 13 +- .../dataformat/avro/ser/RootContext.java | 47 +++- .../avro/SingleObjectWrite172Test.java | 237 ++++++++++++++++++ release-notes/CREDITS | 10 + release-notes/VERSION | 4 + 7 files changed, 344 insertions(+), 27 deletions(-) create mode 100644 avro/src/test/java/tools/jackson/dataformat/avro/SingleObjectWrite172Test.java diff --git a/avro/README.md b/avro/README.md index 5382e4c92..420fd9c0b 100644 --- a/avro/README.md +++ b/avro/README.md @@ -129,7 +129,20 @@ byte[] avroData = mapper.writer(schema) .writeValueAsBytes(empl); ``` -and that's about it, for now. +### Writing Single Object Encoding + +Since 3.4, enable `AvroWriteFeature.WRITE_SINGLE_OBJECT_ENCODING` to write messages for +Apache Avro's `BinaryMessageDecoder` or Jackson's `READ_SINGLE_OBJECT_ENCODING` reader. + +```java +byte[] message = mapper.writer(schema) + .with(AvroWriteFeature.WRITE_SINGLE_OBJECT_ENCODING) + .writeValueAsBytes(empl); +``` + +Each root value gets its own header, including each value written by a `SequenceWriter`. +The default writer produces raw Avro data. Use `AVRO_FILE_OUTPUT` separately for Avro +object container files. ## Avro Logical Types diff --git a/avro/src/main/java/tools/jackson/dataformat/avro/AvroGenerator.java b/avro/src/main/java/tools/jackson/dataformat/avro/AvroGenerator.java index aa83ff939..94e800990 100644 --- a/avro/src/main/java/tools/jackson/dataformat/avro/AvroGenerator.java +++ b/avro/src/main/java/tools/jackson/dataformat/avro/AvroGenerator.java @@ -12,6 +12,7 @@ import tools.jackson.core.*; import tools.jackson.core.base.GeneratorBase; +import tools.jackson.core.io.GuardedOutputStream; import tools.jackson.core.io.IOContext; import tools.jackson.core.util.JacksonFeatureSet; import tools.jackson.dataformat.avro.apacheimpl.ApacheCodecRecycler; @@ -45,6 +46,8 @@ public class AvroGenerator extends GeneratorBase protected final AvroSchema _rootSchema; + private boolean _singleObjectEncodingRequested; + /* /********************************************************************** /* Output state @@ -89,14 +92,17 @@ public AvroGenerator(ObjectWriteContext writeCtxt, IOContext ioCtxt, { super(writeCtxt, ioCtxt, streamWriteFeatures); _formatWriteFeatures = avroFeatures; + _singleObjectEncodingRequested = isEnabled(AvroWriteFeature.WRITE_SINGLE_OBJECT_ENCODING); _output = output; _streamWriteContext = AvroWriteContext.nullContext(); _apacheCodecRecycler = apacheCodecRecycler; final boolean buffering = isEnabled(AvroWriteFeature.AVRO_BUFFERING); + OutputStream encoderOutput = isEnabled(StreamWriteFeature.FLUSH_PASSED_TO_STREAM) + ? output : new GuardedOutputStream(output); BinaryEncoder encoderToReuse = apacheCodecRecycler.acquireEncoder(); _encoder = buffering - ? ENCODER_FACTORY.binaryEncoder(output, encoderToReuse) - : ENCODER_FACTORY.directBinaryEncoder(output, encoderToReuse); + ? ENCODER_FACTORY.binaryEncoder(encoderOutput, encoderToReuse) + : ENCODER_FACTORY.directBinaryEncoder(encoderOutput, encoderToReuse); _rootSchema = Objects.requireNonNull(schema, "Can not pass `null` 'schema'"); // start with temporary root... _streamWriteContext = _rootContext = AvroWriteContext.createRootContext(this, @@ -182,6 +188,9 @@ public JacksonFeatureSet streamWriteCapabilities() { public AvroGenerator enable(AvroWriteFeature f) { _formatWriteFeatures |= f.getMask(); + if (f == AvroWriteFeature.WRITE_SINGLE_OBJECT_ENCODING) { + _singleObjectEncodingRequested = true; + } return this; } @@ -256,17 +265,32 @@ public JsonGenerator writePropertyId(long id) throws JacksonException { @Override public final void flush() { - if (isEnabled(StreamWriteFeature.FLUSH_PASSED_TO_STREAM)) { - try { + try { + if (_singleObjectEncodingRequested && _encoder != null) { + _encoder.flush(); + } else if (isEnabled(StreamWriteFeature.FLUSH_PASSED_TO_STREAM)) { _output.flush(); - } catch (IOException e) { - throw _wrapIOFailure(e); } + } catch (IOException e) { + throw _wrapIOFailure(e); } } @Override protected void _closeInput() throws IOException + { + boolean closeTarget = _ioContext.isResourceManaged() + || isEnabled(StreamWriteFeature.AUTO_CLOSE_TARGET); + try (OutputStream ownedTarget = closeTarget ? _output : null) { + _finishContent(); + if (ownedTarget == null && _output != null + && isEnabled(StreamWriteFeature.FLUSH_PASSED_TO_STREAM)) { + _output.flush(); + } + } + } + + private void _finishContent() throws IOException { if (isEnabled(StreamWriteFeature.AUTO_CLOSE_CONTENT)) { AvroWriteContext ctxt; @@ -296,13 +320,8 @@ protected void _closeInput() throws IOException e); } } - if (_output != null) { - if (_ioContext.isResourceManaged() || isEnabled(StreamWriteFeature.AUTO_CLOSE_TARGET)) { - _output.close(); - } else if (isEnabled(StreamWriteFeature.FLUSH_PASSED_TO_STREAM)) { - // If we can't close it, we should at least flush - _output.flush(); - } + if (_encoder.bytesBuffered() > 0) { + _encoder.flush(); } } diff --git a/avro/src/main/java/tools/jackson/dataformat/avro/AvroWriteFeature.java b/avro/src/main/java/tools/jackson/dataformat/avro/AvroWriteFeature.java index 32230eccd..c0cad75b4 100644 --- a/avro/src/main/java/tools/jackson/dataformat/avro/AvroWriteFeature.java +++ b/avro/src/main/java/tools/jackson/dataformat/avro/AvroWriteFeature.java @@ -41,7 +41,18 @@ public enum AvroWriteFeature * @since 3.0 * */ - ADD_NULL_AS_DEFAULT_VALUE_IN_SCHEMA(false) + ADD_NULL_AS_DEFAULT_VALUE_IN_SCHEMA(false), + + /** + * Write each root value in Avro Single Object Encoding, with the two-byte marker + * and the little-endian CRC-64-AVRO fingerprint of the writer schema. This allows + * Apache Avro's {@code BinaryMessageDecoder} to read the value. + *

+ * Disabled by default. Writing a value with {@link #AVRO_FILE_OUTPUT} also enabled fails. + * + * @since 3.4 + */ + WRITE_SINGLE_OBJECT_ENCODING(false) ; private final boolean _defaultState; diff --git a/avro/src/main/java/tools/jackson/dataformat/avro/ser/RootContext.java b/avro/src/main/java/tools/jackson/dataformat/avro/ser/RootContext.java index 42256289d..3c3a49650 100644 --- a/avro/src/main/java/tools/jackson/dataformat/avro/ser/RootContext.java +++ b/avro/src/main/java/tools/jackson/dataformat/avro/ser/RootContext.java @@ -2,6 +2,8 @@ import java.io.IOException; import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; import org.apache.avro.Schema; import org.apache.avro.file.DataFileWriter; @@ -10,6 +12,7 @@ import org.apache.avro.io.BinaryEncoder; import org.apache.avro.io.DatumWriter; +import tools.jackson.core.exc.StreamWriteException; import tools.jackson.dataformat.avro.AvroGenerator; import tools.jackson.dataformat.avro.AvroWriteFeature; @@ -30,6 +33,8 @@ class RootContext */ private NonBSGenericDatumWriter _writer; + private byte[] _singleObjectHeader; + public RootContext(AvroGenerator generator, Schema schema, BinaryEncoder encoder) { super(TYPE_ROOT, null, generator, schema, null); _encoder = encoder; @@ -84,22 +89,35 @@ public final AvroWriteContext createChildObjectContext(Object currValue) { @Override public void writeValue(Object value) throws IOException { - // 19-Jan-2017, tatu: Implemented to allow/support root-level scalars, esp. - // for Avro streams - _writer().write(value, _encoder); + if (_generator.isEnabled(AvroWriteFeature.WRITE_SINGLE_OBJECT_ENCODING)) { + _writeSingleObject(value); + } else { + _writer().write(value, _encoder); + } } @Override public void writeString(String value) throws IOException { - // 19-Jan-2017, tatu: Implemented to allow/support root-level scalars, esp. - // for Avro streams - _writer().write(value, _encoder); + writeValue(value); } @Override public void writeNull() throws IOException { - // 19-Jan-2017, tatu: ... is this even legal? - _writer().write(null, _encoder); + writeValue(null); + } + + private void _writeSingleObject(Object value) throws IOException { + if (_generator.isEnabled(AvroWriteFeature.AVRO_FILE_OUTPUT)) { + throw new StreamWriteException(_generator, + "WRITE_SINGLE_OBJECT_ENCODING cannot be combined with AVRO_FILE_OUTPUT"); + } + if (_singleObjectHeader == null) { + _singleObjectHeader = ByteBuffer.allocate(10).order(ByteOrder.LITTLE_ENDIAN) + .put((byte) 0xC3).put((byte) 0x01) + .putLong(_generator.getSchema().getWriterFingerprint()).array(); + } + _encoder.writeFixed(_singleObjectHeader); + _writer().write(value, _encoder); } @SuppressWarnings("resource") @@ -108,9 +126,16 @@ public void complete() throws IOException { final Object rootValue = _rootValue; _rootValue = null; - // 21-Feb-2017, tatu: As per [dataformats-binary#15], need to ensure schema gets - // written, if using "File" format (not raw "rpc" one) + if (_generator.isEnabled(AvroWriteFeature.WRITE_SINGLE_OBJECT_ENCODING)) { + if (rootValue != null) { + _writeSingleObject(rootValue); + } + return; + } if (_generator.isEnabled(AvroWriteFeature.AVRO_FILE_OUTPUT)) { + if (_encoder.bytesBuffered() > 0) { + _encoder.flush(); + } OutputStream outputStream = (OutputStream) _generator.streamWriteOutputTarget(); DatumWriter datumWriter = new NonBSGenericDatumWriter<>(_schema); DataFileWriter dataFileWriter = new DataFileWriter<>(datumWriter); @@ -120,8 +145,6 @@ public void complete() throws IOException { dataFileWriter.close(); return; } - // 19-Jan-2017, tatu: Gets also called for root-level scalar, in which - // case nothing (more) to output. if (rootValue != null) { _writer().write(rootValue, _encoder); } diff --git a/avro/src/test/java/tools/jackson/dataformat/avro/SingleObjectWrite172Test.java b/avro/src/test/java/tools/jackson/dataformat/avro/SingleObjectWrite172Test.java new file mode 100644 index 000000000..b34a8a3f1 --- /dev/null +++ b/avro/src/test/java/tools/jackson/dataformat/avro/SingleObjectWrite172Test.java @@ -0,0 +1,237 @@ +package tools.jackson.dataformat.avro; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import org.apache.avro.Schema; +import org.apache.avro.file.DataFileStream; +import org.apache.avro.generic.GenericData; +import org.apache.avro.generic.GenericDatumReader; +import org.apache.avro.generic.GenericRecord; +import org.apache.avro.message.BinaryMessageDecoder; +import org.apache.avro.message.BinaryMessageEncoder; +import org.junit.jupiter.api.Test; + +import tools.jackson.core.JacksonException; +import tools.jackson.core.StreamWriteFeature; +import tools.jackson.core.exc.StreamWriteException; +import tools.jackson.databind.ObjectWriter; +import tools.jackson.databind.SequenceWriter; +import tools.jackson.databind.SerializationFeature; + +import static org.junit.jupiter.api.Assertions.*; + +public class SingleObjectWrite172Test extends AvroTestBase +{ + private static final AvroSchema RECORD = schema("{'type':'record','name':'Batch'," + + "'fields':[{'name':'ids','type':{'type':'array','items':'int'}}]}"); + + @Test + public void recordIsReadableByApacheAvro() throws Exception { + List ids = List.of(3, 5); + byte[] bytes = singleObjectWriter(RECORD).writeValueAsBytes(Map.of("ids", ids)); + GenericRecord result = new BinaryMessageDecoder( + GenericData.get(), RECORD.getAvroSchema()).decode(bytes); + assertEquals(ids, result.get("ids")); + + GenericRecord expected = new GenericData.Record(RECORD.getAvroSchema()); + expected.put("ids", ids); + assertArrayEquals(apacheMessages(RECORD, expected), bytes); + } + + @Test + public void mixedRootSequence() throws Exception { + AvroSchema union = schema("['null','int','string',{'type':'array','items':'int'}]"); + List values = Arrays.asList(7, List.of(1, 2), "last", null); + byte[] expected = apacheMessages(union, values.toArray()); + ObjectWriter writer = singleObjectWriter(union); + for (ObjectWriter configured : List.of(writer, + writer.without(AvroWriteFeature.AVRO_BUFFERING))) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try (SequenceWriter sequence = configured.writeValues(out)) { + sequence.writeAll(values); + } + assertArrayEquals(expected, out.toByteArray()); + } + } + + @Test + public void zeroByteDatumsAndEmptySequence() throws Exception { + AvroSchema schema = schema("'null'"); + ObjectWriter writer = singleObjectWriter(schema); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try (SequenceWriter sequence = writer.writeValues(out)) { + sequence.write(null); + sequence.write(null); + } + assertArrayEquals(apacheMessages(schema, null, null), out.toByteArray()); + + out.reset(); + writer.writeValues(out).close(); + assertEquals(0, out.size()); + } + + @Test + public void headerUsesOriginalWriterSchema() throws Exception { + AvroSchema original = schema("{'type':'record','name':'Before','fields':[]}"); + AvroSchema renamed = schema( + "{'type':'record','name':'After','aliases':['Before'],'fields':[]}"); + byte[] expected = apacheMessages(original, new GenericData.Record(original.getAvroSchema())); + assertArrayEquals(expected, singleObjectWriter(original.withReaderSchema(renamed)) + .writeValueAsBytes(Map.of())); + } + + @Test + public void encoderFlushRespectsTargetSettings() throws Exception { + class Output extends ByteArrayOutputStream { + int flushes; + + @Override + public void flush() { + ++flushes; + } + } + AvroSchema schema = schema("'int'"); + byte[] message = apacheMessages(schema, 7); + for (boolean passFlush : List.of(false, true)) { + Output out = new Output(); + ObjectWriter writer = singleObjectWriter(schema) + .without(SerializationFeature.FLUSH_AFTER_WRITE_VALUE) + .without(StreamWriteFeature.AUTO_CLOSE_TARGET); + writer = passFlush ? writer.with(StreamWriteFeature.FLUSH_PASSED_TO_STREAM) + : writer.without(StreamWriteFeature.FLUSH_PASSED_TO_STREAM); + try (SequenceWriter sequence = writer.writeValues(out)) { + sequence.write(7); + assertEquals(0, out.size()); + assertEquals(0, out.flushes); + sequence.flush(); + assertArrayEquals(message, out.toByteArray()); + assertEquals(passFlush ? 1 : 0, out.flushes); + } + if (!passFlush) { + assertEquals(0, out.flushes); + } + } + } + + @Test + public void closeDrainsScalarAfterFramedArray() throws Exception { + AvroSchema union = schema("[{'type':'array','items':'int'},'int']"); + ByteArrayOutputStream expected = new ByteArrayOutputStream(); + expected.write(apacheMessages(union, List.of(1))); + expected.write(getMapper().writer(union).writeValueAsBytes(7)); + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try (AvroGenerator gen = (AvroGenerator) getMapper().writer(union).createGenerator(out)) { + gen.enable(AvroWriteFeature.WRITE_SINGLE_OBJECT_ENCODING); + gen.writeStartArray(); + gen.writeNumber(1); + gen.writeEndArray(); + gen.disable(AvroWriteFeature.WRITE_SINGLE_OBJECT_ENCODING); + gen.flush(); + assertArrayEquals(apacheMessages(union, List.of(1)), out.toByteArray()); + gen.writeNumber(7); + } + assertArrayEquals(expected.toByteArray(), out.toByteArray()); + } + + @Test + public void writeFailurePreservesTargetOwnership() { + class FailingOutput extends OutputStream { + boolean closed; + + @Override + public void write(int value) throws IOException { + throw new IOException("write failed"); + } + + @Override + public void close() throws IOException { + closed = true; + throw new IOException("close failed"); + } + } + for (boolean closeTarget : List.of(true, false)) { + FailingOutput out = new FailingOutput(); + ObjectWriter writer = singleObjectWriter(schema("'int'")) + .without(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); + writer = closeTarget ? writer.with(StreamWriteFeature.AUTO_CLOSE_TARGET) + : writer.without(StreamWriteFeature.AUTO_CLOSE_TARGET); + SequenceWriter sequence = writer.writeValues(out); + sequence.write(7); + JacksonException e = assertThrows(JacksonException.class, sequence::close); + verifyException(e, "write failed"); + assertEquals(closeTarget, out.closed); + if (closeTarget) { + assertEquals("close failed", e.getCause().getSuppressed()[0].getMessage()); + } + } + } + + @Test + public void pendingMessagePrecedesFileOutput() throws Exception { + AvroSchema record = schema("{'type':'record','name':'Result'," + + "'fields':[{'name':'id','type':'int'}]}"); + GenericRecord datum = new GenericData.Record(record.getAvroSchema()); + datum.put("id", 7); + byte[] first = apacheMessages(record, datum); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try (AvroGenerator gen = (AvroGenerator) singleObjectWriter(record).createGenerator(out)) { + gen.writeStartObject(); + gen.writeNumberProperty("id", 7); + gen.writeEndObject(); + gen.disable(AvroWriteFeature.WRITE_SINGLE_OBJECT_ENCODING); + gen.enable(AvroWriteFeature.AVRO_FILE_OUTPUT); + gen.writeStartObject(); + gen.writeNumberProperty("id", 8); + gen.writeEndObject(); + } + byte[] bytes = out.toByteArray(); + assertArrayEquals(first, Arrays.copyOf(bytes, first.length)); + try (DataFileStream file = new DataFileStream<>( + new ByteArrayInputStream(bytes, first.length, bytes.length - first.length), + new GenericDatumReader<>())) { + assertEquals(8, file.next().get("id")); + assertFalse(file.hasNext()); + } + } + + @Test + public void fileOutputConflictsBeforeWriting() { + ObjectWriter writer = singleObjectWriter(RECORD).with(AvroWriteFeature.AVRO_FILE_OUTPUT); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + StreamWriteException e = assertThrows(StreamWriteException.class, + () -> writer.writeValue(out, Map.of("ids", List.of(1)))); + verifyException(e, "AVRO_FILE_OUTPUT"); + assertEquals(0, out.size()); + } + + @Test + public void rawOutputRemainsTheDefault() { + AvroSchema schema = schema("'int'"); + assertArrayEquals(new byte[] { 14 }, getMapper().writer(schema).writeValueAsBytes(7)); + } + + private ObjectWriter singleObjectWriter(AvroSchema schema) { + return getMapper().writer(schema).with(AvroWriteFeature.WRITE_SINGLE_OBJECT_ENCODING); + } + + private static AvroSchema schema(String json) { + return new AvroSchema(new Schema.Parser().parse(a2q(json))); + } + + private static byte[] apacheMessages(AvroSchema schema, Object... values) throws Exception { + BinaryMessageEncoder encoder = new BinaryMessageEncoder<>(GenericData.get(), + schema.getAvroSchema()); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (Object value : values) { + encoder.encode(value, out); + } + return out.toByteArray(); + } +} diff --git a/release-notes/CREDITS b/release-notes/CREDITS index a0b8fe4b8..14379c009 100644 --- a/release-notes/CREDITS +++ b/release-notes/CREDITS @@ -148,3 +148,13 @@ Vineet Singh (@Vineet829) * Contributed #343: (avro) Support Avro "single-object encoding" decoding with `AvroReadFeature.READ_SINGLE_OBJECT_ENCODING` (3.4.0) + +@salt-tony + +* Requested #172: (avro) Support Avro Single Object Encoding + (3.4.0) + +@fudianchn + +* Contributed #172: (avro) Add `AvroWriteFeature.WRITE_SINGLE_OBJECT_ENCODING` + (3.4.0) diff --git a/release-notes/VERSION b/release-notes/VERSION index 452aad4e5..a6de66b53 100644 --- a/release-notes/VERSION +++ b/release-notes/VERSION @@ -16,6 +16,10 @@ implementations) 3.4.0 (not yet released) +#172: (avro) Add `AvroWriteFeature.WRITE_SINGLE_OBJECT_ENCODING` for writing + single-object messages + (requested by @salt-tony) + (contributed by @fudianchn) #343: (avro) Support Avro "single-object encoding" decoding with `AvroReadFeature.READ_SINGLE_OBJECT_ENCODING` (reported by @birTiwana)