Path: redb-route/redb.Route.DataFormats.Avro/AvroDataFormat.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.DataFormats.Avro/AvroDataFormat.cs ---- using System.Buffers.Binary; using System.Collections.Concurrent; using System.Reflection; using Chr.Avro.Abstract; using Chr.Avro.Representation; using Chr.Avro.Serialization; using redb.Route.Abstractions; namespace redb.Route.DataFormats.Avro; /// /// Apache Avro binary (Chr.Avro). The schema comes from /// or is built from the CLR type; serializer and deserializer /// delegates are built once per type and cached. Optional Confluent Schema Registry framing. /// public sealed class AvroDataFormat : IMessageSerializer { /// Content type the format is registered under. public const string DefaultContentType = "application/avro"; /// The name the format answers to in markup, <marshal format="avro"/>, as Apache Camel names it; AddAvroDataFormat() registers it. public const string Name = "avro"; private readonly AvroDataFormatOptions _options; private readonly ConcurrentDictionary _schemas = new(); private readonly ConcurrentDictionary _serializers = new(); private readonly ConcurrentDictionary _deserializers = new(); private readonly Lazy _explicitSchema; /// Creates the format with the given options (defaults when null). public AvroDataFormat(AvroDataFormatOptions? options = null) { _options = options ?? new AvroDataFormatOptions(); _explicitSchema = new Lazy(() => _options.Schema is null ? null : new JsonSchemaReader().Read(_options.Schema)); } /// The options in effect. public AvroDataFormatOptions Options => _options; /// public string ContentType => DefaultContentType; /// public IReadOnlyCollection MediaTypes => [DefaultContentType, "avro/binary", "application/vnd.apache.avro+binary"]; /// The schema used for (explicit or built from the type). public Schema SchemaFor(Type type) => _explicitSchema.Value ?? _schemas.GetOrAdd(type, static t => new SchemaBuilder().BuildSchema(t)); /// public byte[] Serialize(T value) { switch (value) { case null: return []; case byte[] bytes: return bytes; } try { var serialize = (BinarySerializer)_serializers.GetOrAdd(typeof(T), t => new BinarySerializerBuilder().BuildDelegate(SchemaFor(t))); using var stream = new MemoryStream(); using (var writer = new Chr.Avro.Serialization.BinaryWriter(stream)) serialize(value, writer); var payload = stream.ToArray(); return _options.ConfluentWireFormat ? Frame(payload) : payload; } catch (Exception ex) when (ex is not InvalidOperationException) { throw new InvalidOperationException($"Avro data format: cannot marshal {typeof(T).Name} ({ex.Message}).", ex); } } /// public T? Deserialize(byte[] data) { ArgumentNullException.ThrowIfNull(data); if (typeof(T) == typeof(byte[])) return (T)(object)data; var payload = _options.ConfluentWireFormat ? Unframe(data) : data.AsMemory(); try { var deserialize = (BinaryDeserializer)_deserializers.GetOrAdd(typeof(T), t => new BinaryDeserializerBuilder().BuildDelegate(SchemaFor(t))); var reader = new Chr.Avro.Serialization.BinaryReader(payload.Span); return deserialize(ref reader); } catch (Exception ex) when (ex is not InvalidOperationException) { throw new InvalidOperationException($"Avro data format: the body is not a valid {typeof(T).Name} ({ex.Message}).", ex); } } /// public object? Deserialize(byte[] data, Type type) { ArgumentNullException.ThrowIfNull(type); var method = typeof(AvroDataFormat).GetMethod(nameof(Deserialize), BindingFlags.Public | BindingFlags.Instance, [typeof(byte[])])!; try { return method.MakeGenericMethod(type).Invoke(this, [data]); } catch (TargetInvocationException ex) when (ex.InnerException is not null) { throw ex.InnerException; } } private byte[] Frame(byte[] payload) { var framed = new byte[5 + payload.Length]; framed[0] = 0; BinaryPrimitives.WriteInt32BigEndian(framed.AsSpan(1, 4), _options.SchemaId); payload.CopyTo(framed, 5); return framed; } private static ReadOnlyMemory Unframe(byte[] data) { if (data.Length < 5 || data[0] != 0) throw new InvalidOperationException("Avro data format: the body is not in Confluent wire format (magic byte 0 + schema id expected)."); return data.AsMemory(5); } }