Module: OpenTrace::Serializer
- Defined in:
- lib/opentrace/serializer.rb
Overview
Handles serialization of documents for the wire format. Uses MessagePack by default (5-10x faster, 30% smaller). Falls back to JSON if msgpack is unavailable or for debugging.
Constant Summary collapse
- MSGPACK_CONTENT_TYPE =
"application/msgpack"- JSON_CONTENT_TYPE =
"application/json"
Class Method Summary collapse
-
.decode(bytes, content_type: MSGPACK_CONTENT_TYPE) ⇒ Object
Decode bytes received from the wire.
-
.encode(data, format: :msgpack) ⇒ Object
Serialize a document (Hash or Array) for transmission.
-
.estimate_size(data) ⇒ Object
Estimate byte size of a document without full serialization.
Class Method Details
.decode(bytes, content_type: MSGPACK_CONTENT_TYPE) ⇒ Object
Decode bytes received from the wire. content_type determines the decoder.
38 39 40 41 42 43 44 45 46 47 |
# File 'lib/opentrace/serializer.rb', line 38 def decode(bytes, content_type: MSGPACK_CONTENT_TYPE) case content_type when MSGPACK_CONTENT_TYPE MessagePack.unpack(bytes) when JSON_CONTENT_TYPE JSON.parse(bytes) else JSON.parse(bytes) # default to JSON for unknown types end end |
.encode(data, format: :msgpack) ⇒ Object
Serialize a document (Hash or Array) for transmission. Returns [encoded_bytes, content_type]
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/opentrace/serializer.rb', line 18 def encode(data, format: :msgpack) case format when :msgpack [MessagePack.pack(data), MSGPACK_CONTENT_TYPE] when :json [JSON.generate(data), JSON_CONTENT_TYPE] else raise ArgumentError, "Unknown serialization format: #{format}" end rescue StandardError => e # If msgpack fails (e.g., unsupported type), fall back to JSON if format == :msgpack [JSON.generate(data), JSON_CONTENT_TYPE] else raise end end |
.estimate_size(data) ⇒ Object
Estimate byte size of a document without full serialization. Used for buffer tracking — rough estimate is fine.
51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/opentrace/serializer.rb', line 51 def estimate_size(data) case data when String then data.bytesize when Hash then data.sum { |k, v| k.to_s.bytesize + estimate_size(v) } + 2 when Array then data.sum { |v| estimate_size(v) } + 2 when Numeric then 8 when NilClass, TrueClass, FalseClass then 1 else data.to_s.bytesize end end |