Path: redb-route/redb.Route.DataFormats.Protobuf/ProtobufDataFormat.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.Protobuf/ProtobufDataFormat.cs ---- using System.Buffers.Binary; using System.Collections.Concurrent; using System.Reflection; using Google.Protobuf; using redb.Route.Abstractions; using ProtoMessage = Google.Protobuf.IMessage; namespace redb.Route.DataFormats.Protobuf; /// /// Protocol Buffers (Google.Protobuf). Marshals any ; /// unmarshals to a generated message type through its static Parser. Optional Confluent /// Schema Registry framing (). /// public sealed class ProtobufDataFormat : IMessageSerializer { /// Content type the format is registered under. public const string DefaultContentType = "application/x-protobuf"; /// The name the format answers to in markup, <marshal format="protobuf"/>, as Apache Camel names it; AddProtobufDataFormat() registers it. public const string Name = "protobuf"; // Weak per type: a message type of an unloadable module (collectible load context) does not stay alive in this cache. private static readonly System.Runtime.CompilerServices.ConditionalWeakTable Parsers = new(); private readonly ProtobufDataFormatOptions _options; /// Creates the format with the given options (defaults when null). public ProtobufDataFormat(ProtobufDataFormatOptions? options = null) => _options = options ?? new ProtobufDataFormatOptions(); /// The options in effect. public ProtobufDataFormatOptions Options => _options; /// public string ContentType => DefaultContentType; /// public IReadOnlyCollection MediaTypes => [DefaultContentType, "application/protobuf", "application/vnd.google.protobuf"]; /// public byte[] Serialize(T value) { switch (value) { case null: return []; case byte[] bytes: return bytes; case ProtoMessage message: var payload = message.ToByteArray(); return _options.ConfluentWireFormat ? Frame(payload) : payload; default: throw new InvalidOperationException( $"Protobuf data format: the body must be a Google.Protobuf IMessage, not {value.GetType().Name}."); } } /// public T? Deserialize(byte[] data) => (T?)Deserialize(data, typeof(T)); /// public object? Deserialize(byte[] data, Type type) { ArgumentNullException.ThrowIfNull(data); ArgumentNullException.ThrowIfNull(type); if (type == typeof(byte[])) return data; if (!typeof(ProtoMessage).IsAssignableFrom(type)) throw new InvalidOperationException( $"Protobuf data format: unmarshal target must be a Google.Protobuf IMessage type, not {type.Name}."); var payload = _options.ConfluentWireFormat ? Unframe(data) : data; try { return ParserFor(type).ParseFrom(payload); } catch (InvalidProtocolBufferException ex) { throw new InvalidOperationException($"Protobuf data format: the body is not a valid {type.Name} ({ex.Message}).", ex); } } private static MessageParser ParserFor(Type type) => Parsers.GetValue(type, static t => t.GetProperty("Parser", BindingFlags.Public | BindingFlags.Static)?.GetValue(null) as MessageParser ?? throw new InvalidOperationException($"Protobuf data format: {t.Name} has no static Parser property; is it a protoc-generated message?")); /// Confluent framing: 0x00, schema id big-endian, message index list [0] encoded as a single zero byte. private byte[] Frame(byte[] payload) { var framed = new byte[6 + payload.Length]; framed[0] = 0; BinaryPrimitives.WriteInt32BigEndian(framed.AsSpan(1, 4), _options.SchemaId); framed[5] = 0; payload.CopyTo(framed, 6); return framed; } private static ReadOnlySpan Unframe(byte[] data) { if (data.Length < 6 || data[0] != 0) throw new InvalidOperationException("Protobuf data format: the body is not in Confluent wire format (magic byte 0 + schema id expected)."); var offset = 5; var count = ReadVarint(data, ref offset); // message-index list length; a single 0 byte means [0] for (var i = 0L; i < count; i++) ReadVarint(data, ref offset); return data.AsSpan(offset); } private static long ReadVarint(byte[] data, ref int offset) { long result = 0; var shift = 0; while (offset < data.Length) { var b = data[offset++]; result |= (long)(b & 0x7F) << shift; if ((b & 0x80) == 0) return result; shift += 7; } throw new InvalidOperationException("Protobuf data format: truncated Confluent wire-format header."); } }