Skip to main content

libdd_trace_utils/msgpack_encoder/v04/
mod.rs

1// Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::span::v04::Span;
5use crate::span::v1::TracerPayload;
6use crate::span::TraceData;
7use libdd_common::ResultInfallibleExt;
8use rmp::encode::{write_array_len, ByteBuf, RmpWrite, ValueWriteError};
9
10const fn msgpack_string_encoding_len(s: &str) -> usize {
11    const U16_MAX: usize = u16::MAX as usize;
12    let length_marker_len = match s.len() {
13        0..32 => 1,
14        32..256 => 2,
15        256..=U16_MAX => 3,
16        _ => 5,
17    };
18    length_marker_len + s.len()
19}
20
21// Compute the encoding of a string to msgpack in a const manner
22const fn msgpack_const_string_encoding<const ENCODING_LEN: usize>(s: &str) -> [u8; ENCODING_LEN] {
23    // copy_to_slice is not const yet, so we make a helper
24    const fn copy_to_slice(dest: &mut [u8], src: &[u8], n: usize) {
25        let mut i = 0;
26        while i < n {
27            dest[i] = src[i];
28            i += 1;
29        }
30    }
31
32    let mut storage = [0; ENCODING_LEN];
33    let len = s.len() as u64;
34    let len_bytes = if len < 32 {
35        storage[0] = 0xa0 | (len as u8 & 0x1f);
36        0
37    } else if len < 256 {
38        storage[0] = 0xd9;
39        1
40    } else if len <= (u16::MAX as u64) {
41        storage[0] = 0xda;
42        2
43    } else {
44        storage[0] = 0xdb;
45        4
46    };
47    let len_be_bytes = len.to_be_bytes();
48    // `len_be_bytes` holds `len` as 8 big-endian bytes; the marker only needs the low-order
49    // `len_bytes` of those (e.g. for a str8 length of 200, that's byte `[200]`, not `[0]`), so
50    // skip the leading zero bytes rather than copying from the front.
51    copy_to_slice(
52        storage.split_at_mut(1).1,
53        len_be_bytes.split_at(8 - len_bytes).1,
54        len_bytes,
55    );
56    copy_to_slice(storage.split_at_mut(1 + len_bytes).1, s.as_bytes(), s.len());
57    storage
58}
59
60macro_rules! write_const_msgpack_str {
61    ($writer:expr, $str:expr) => {{
62        use rmp::encode::ValueWriteError;
63        const STRING_ENCODING_LEN: usize = super::msgpack_string_encoding_len($str);
64        const STRING_ENCODING: [u8; STRING_ENCODING_LEN] =
65            super::msgpack_const_string_encoding($str);
66
67        $writer
68            .write_bytes(&STRING_ENCODING)
69            .map_err(ValueWriteError::InvalidDataWrite)
70    }};
71}
72
73mod span_v04;
74mod span_v1;
75
76#[inline(always)]
77fn to_writer<W: RmpWrite, T: TraceData, S: AsRef<[Span<T>]>>(
78    writer: &mut W,
79    traces: &[S],
80) -> Result<(), ValueWriteError<W::Error>> {
81    write_array_len(writer, traces.len() as u32)?;
82    for trace in traces {
83        write_array_len(writer, trace.as_ref().len() as u32)?;
84        for span in trace.as_ref() {
85            span_v04::encode_span(writer, span)?;
86        }
87    }
88
89    Ok(())
90}
91
92/// Encodes a collection of traces into a slice of bytes.
93///
94/// # Arguments
95///
96/// * `slice` - A mutable reference to a byte slice.
97/// * `traces` - A reference to a slice of spans.
98///
99/// # Returns
100///
101/// * `Ok(())` - If encoding succeeds.
102/// * `Err(ValueWriteError)` - If encoding fails.
103///
104/// # Errors
105///
106/// This function will return an error if:
107/// - The array length for trace count or span count cannot be written.
108/// - Any span cannot be encoded.
109///
110/// # Examples
111///
112/// ```
113/// use libdd_trace_utils::msgpack_encoder::v04::write_to_slice_from_v04;
114/// use libdd_trace_utils::span::v04::SpanSlice;
115///
116/// let mut buffer = vec![0u8; 1024];
117/// let span = SpanSlice {
118///     name: "test-span",
119///     ..Default::default()
120/// };
121/// let traces = vec![vec![span]];
122///
123/// write_to_slice_from_v04(&mut &mut buffer[..], &traces).expect("Encoding failed");
124/// ```
125pub fn write_to_slice_from_v04<T: TraceData, S: AsRef<[Span<T>]>>(
126    slice: &mut &mut [u8],
127    traces: &[S],
128) -> Result<(), ValueWriteError> {
129    to_writer(slice, traces)
130}
131
132/// Serializes traces into a vector of bytes with a default capacity of 0.
133///
134/// # Arguments
135///
136/// * `traces` - A reference to a slice of spans.
137///
138/// # Returns
139///
140/// * `Vec<u8>` - A vector containing encoded traces.
141///
142/// # Examples
143///
144/// ```
145/// use libdd_trace_utils::msgpack_encoder::v04::to_vec_from_v04;
146/// use libdd_trace_utils::span::v04::SpanSlice;
147///
148/// let span = SpanSlice {
149///     name: "test-span",
150///     ..Default::default()
151/// };
152/// let traces = vec![vec![span]];
153/// let encoded = to_vec_from_v04(&traces);
154///
155/// assert!(!encoded.is_empty());
156/// ```
157pub fn to_vec_from_v04<T: TraceData, S: AsRef<[Span<T>]>>(traces: &[S]) -> Vec<u8> {
158    to_vec_with_capacity_from_v04(traces, 0)
159}
160
161/// Serializes traces into a vector of bytes with specified capacity.
162///
163/// # Arguments
164///
165/// * `traces` - A reference to a slice of spans.
166/// * `capacity` - Desired initial capacity of the resulting vector.
167///
168/// # Returns
169///
170/// * `Vec<u8>` - A vector containing encoded traces.
171///
172/// # Examples
173///
174/// ```
175/// use libdd_trace_utils::msgpack_encoder::v04::to_vec_with_capacity_from_v04;
176/// use libdd_trace_utils::span::v04::SpanSlice;
177///
178/// let span = SpanSlice {
179///     name: "test-span",
180///     ..Default::default()
181/// };
182/// let traces = vec![vec![span]];
183/// let encoded = to_vec_with_capacity_from_v04(&traces, 1024);
184///
185/// assert!(encoded.capacity() >= 1024);
186/// ```
187pub fn to_vec_with_capacity_from_v04<T: TraceData, S: AsRef<[Span<T>]>>(
188    traces: &[S],
189    capacity: u32,
190) -> Vec<u8> {
191    let mut buf = ByteBuf::with_capacity(capacity as usize);
192    to_writer(&mut buf, traces)
193        .map_err(super::flatten_value_write_infallible)
194        .unwrap_infallible();
195    buf.into_vec()
196}
197
198/// Computes the number of bytes required to encode the given traces.
199///
200/// This does not allocate any actual buffer, but simulates writing in order to measure
201/// the encoded size of the traces.
202///
203/// # Arguments
204///
205/// * `traces` - A reference to a slice of spans.
206///
207/// # Returns
208///
209/// * `u32` - The number of bytes that would be written by the encoder.
210///
211/// # Examples
212///
213/// ```
214/// use libdd_trace_utils::msgpack_encoder::v04::to_encoded_byte_len_from_v04;
215/// use libdd_trace_utils::span::v04::SpanSlice;
216///
217/// let span = SpanSlice {
218///     name: "test-span",
219///     ..Default::default()
220/// };
221/// let traces = vec![vec![span]];
222/// let encoded_len = to_encoded_byte_len_from_v04(&traces);
223///
224/// assert!(encoded_len > 0);
225/// ```
226pub fn to_encoded_byte_len_from_v04<T: TraceData, S: AsRef<[Span<T>]>>(traces: &[S]) -> u32 {
227    let mut counter = super::CountLength(0);
228    // `CountLength` impls `std::io::Write` (whose error type is `std::io::Error`, not
229    // `Infallible`), so we can't statically prove infallibility via `unwrap_infallible`
230    // the way we do for `ByteBuf`. In practice `CountLength::write*` only ever return
231    // `Ok`, so the error path here is unreachable today; should `CountLength` ever grow
232    // a fallible code path, fuzz tests on the msgpack encoded length would catch it.
233    let _ = to_writer(&mut counter, traces);
234    counter.0
235}
236
237/// Encodes a [`TracerPayload`] in the v0.4 wire format (downgrade path used when the agent
238/// does not advertise `/v1.0/traces`). The output is a msgpack array of traces, where each
239/// trace is itself a msgpack array of v0.4-shaped spans — matching the existing v0.4 wire
240/// format produced by [`to_vec_from_v04`]. Payload-level `env`/`app_version`/`attributes` are
241/// propagated into every span (see [`span_v1`]'s mapping table); `payload.hostname` has no v0.4
242/// body equivalent (the agent gets hostname from the `Datadog-Meta-Hostname` header instead) and is
243/// intentionally dropped here.
244fn encode_payload_from_v1<W: RmpWrite, T: TraceData>(
245    writer: &mut W,
246    payload: &TracerPayload<T>,
247) -> Result<(), ValueWriteError<W::Error>> {
248    use span_v1::{encode_span, ChunkContext};
249
250    write_array_len(writer, payload.chunks.len() as u32)?;
251    for chunk in &payload.chunks {
252        // v0.4 has no wire-level equivalent of `dropped_trace`; the closest historical signal
253        // is `USER_REJECT` (priority -1), which tells the agent the sampler rejected this trace
254        // without dropping the spans themselves. Only force it when the chunk doesn't already
255        // carry a negative (reject-like) priority.
256        let priority = if chunk.dropped_trace {
257            Some(chunk.priority.filter(|&p| p < 0).unwrap_or(-1))
258        } else {
259            chunk.priority
260        };
261        let ctx = ChunkContext::new(
262            &chunk.trace_id,
263            priority,
264            &chunk.origin,
265            chunk.sampling_mechanism,
266            &chunk.attributes,
267            &payload.env,
268            &payload.app_version,
269            &payload.attributes,
270        );
271        write_array_len(writer, chunk.spans.len() as u32)?;
272        for span in &chunk.spans {
273            encode_span(writer, span, &ctx)?;
274        }
275    }
276    Ok(())
277}
278
279/// Serializes a [`TracerPayload`] (V1 data model) as a v0.4 msgpack payload.
280///
281/// Used by the trace exporter when the agent has not advertised `/v1.0/traces` via `/info`.
282/// The output is byte-compatible with [`to_vec_from_v04`] for equivalent data — chunk-level fields
283/// are propagated to every span and typed attributes are bucketed into the v0.4 `meta` /
284/// `metrics` / `meta_struct` maps per [`span_v1`]'s mapping table.
285pub fn to_vec_from_v1<T: TraceData>(payload: &TracerPayload<T>) -> Vec<u8> {
286    to_vec_with_capacity_from_v1(payload, 0)
287}
288
289/// Serializes a [`TracerPayload`] as a v0.4 msgpack payload with a caller-supplied initial
290/// capacity. Use this when you can size the buffer up front (e.g. from
291/// [`to_encoded_byte_len_from_v1`]) to avoid reallocations.
292pub fn to_vec_with_capacity_from_v1<T: TraceData>(
293    payload: &TracerPayload<T>,
294    capacity: u32,
295) -> Vec<u8> {
296    let mut buf = ByteBuf::with_capacity(capacity as usize);
297    encode_payload_from_v1(&mut buf, payload)
298        .map_err(super::flatten_value_write_infallible)
299        .unwrap_infallible();
300    buf.into_vec()
301}
302
303/// Encodes a [`TracerPayload`] as v0.4 msgpack into the provided slice. Useful for callers
304/// that own a pre-sized buffer (e.g. for FFI / zero-copy paths).
305///
306/// # Errors
307///
308/// Returns any [`ValueWriteError`] from the underlying writer (typically buffer-too-small).
309pub fn write_to_slice_from_v1<T: TraceData>(
310    slice: &mut &mut [u8],
311    payload: &TracerPayload<T>,
312) -> Result<(), ValueWriteError> {
313    encode_payload_from_v1(slice, payload)
314}
315
316/// Returns the exact number of bytes [`to_vec_from_v1`] would write for `payload`. Walks
317/// the payload through a counting writer without allocating an output buffer.
318pub fn to_encoded_byte_len_from_v1<T: TraceData>(payload: &TracerPayload<T>) -> u32 {
319    let mut counter = super::CountLength(0);
320    let _ = encode_payload_from_v1(&mut counter, payload);
321    counter.0
322}
323
324#[cfg(test)]
325mod tests {
326    //! Regression tests for [`msgpack_const_string_encoding`] across every msgpack string
327    //! length-marker boundary (fixstr / str8 / str16), since the length only fits in the
328    //! low-order bytes of `len.to_be_bytes()` and it's easy to accidentally copy from the
329    //! high-order (zero) end instead.
330    use super::msgpack_const_string_encoding;
331
332    fn encode<const N: usize>(s: &str) -> [u8; N] {
333        msgpack_const_string_encoding::<N>(s)
334    }
335
336    #[test]
337    fn fixstr_boundary_31_bytes() {
338        let s = "a".repeat(31);
339        let bytes: [u8; 32] = encode(&s);
340        let value = rmpv::decode::read_value(&mut &bytes[..]).expect("decode failed");
341        assert_eq!(value.as_str(), Some(s.as_str()));
342    }
343
344    #[test]
345    fn str8_boundary_200_bytes() {
346        let s = "b".repeat(200);
347        let bytes: [u8; 202] = encode(&s);
348        let value = rmpv::decode::read_value(&mut &bytes[..]).expect("decode failed");
349        assert_eq!(value.as_str(), Some(s.as_str()));
350    }
351
352    #[test]
353    fn str16_boundary_300_bytes() {
354        let s = "c".repeat(300);
355        let bytes: [u8; 303] = encode(&s);
356        let value = rmpv::decode::read_value(&mut &bytes[..]).expect("decode failed");
357        assert_eq!(value.as_str(), Some(s.as_str()));
358    }
359}