Skip to main content

saluki_components/decoders/datadog/
mod.rs

1//! Decoder for the Datadog v1.0 APM trace wire format (also called the `idx`/`etp` format).
2//!
3//! The v1.0 trace API (`Content-Type: application/msgpack`, endpoint `v1.0`) sends a tracer payload
4//! in a custom MessagePack layout rather than protobuf-over-msgpack. Its defining traits:
5//!
6//! - A **streaming string table**: a string appears once as a literal, then by `uint32` index
7//!   thereafter.
8//! - **Structs are maps keyed by field number** (`uint32`), not by name.
9//! - **Attribute maps are flat arrays** with three slots per entry (`key`, `type`, `value`).
10//! - **`AnyValue`** is a `uint32` type discriminant followed by the value.
11//!
12//! [`decode_v1_payload`](datadog::decode_v1_payload) decodes one tracer payload into the unified
13//! `Trace` model, producing one `Trace` per trace chunk. String references are resolved to owned
14//! strings during decode.
15
16use std::sync::Arc;
17
18use saluki_common::collections::FastHashMap;
19use saluki_core::data_model::event::trace::{
20    AttributeValue, PayloadFields, Span, SpanEvent, SpanLink, Trace, TraceIngestInfo,
21};
22use stringtheory::MetaString;
23
24mod error;
25mod read;
26mod string_table;
27mod value;
28
29#[cfg(test)]
30mod tests;
31
32pub use self::error::DecodeError;
33use self::string_table::StringTable;
34
35/// Plausible minimum average wire size of a trace chunk containing a span list and 16-byte trace ID.
36const MIN_BYTES_PER_TRACE_CHUNK: u32 = 22;
37
38/// Plausible minimum average wire size of a span containing a random span ID and epoch-nanosecond start time.
39const MIN_BYTES_PER_SPAN: u32 = 21;
40
41/// Decodes a single v1.0 tracer payload into unified trace events.
42///
43/// Each trace chunk in the payload becomes one [`Trace`]. Payload-level metadata (container ID,
44/// tracer language, environment, and so on) is cloned onto every trace, and payload-level
45/// attributes are merged into each trace's attributes with per-chunk attributes taking precedence.
46///
47/// # Errors
48///
49/// Returns a [`DecodeError`] if the input is not a well-formed v1.0 tracer payload (truncated,
50/// malformed MessagePack, oversized headers, out-of-range string references, and so on).
51pub fn decode_v1_payload(bytes: &[u8]) -> Result<Vec<Trace>, DecodeError> {
52    let mut reader = bytes;
53    let payload = decode_tracer_payload(&mut reader)?;
54    if !reader.is_empty() {
55        return Err(DecodeError::TrailingBytes { len: reader.len() });
56    }
57
58    let payload_fields = PayloadFields {
59        container_id: payload.container_id,
60        language_name: payload.language_name,
61        language_version: payload.language_version,
62        tracer_version: payload.tracer_version,
63        runtime_id: payload.runtime_id,
64        env: payload.env,
65        hostname: payload.hostname,
66        app_version: payload.app_version,
67        container_tags: None,
68        client_dropped_p0s_weight: 0.0,
69    };
70
71    let mut traces = Vec::with_capacity(payload.chunks.len());
72    for chunk in payload.chunks {
73        // Payload-level attributes form the base; per-chunk attributes override on key conflict.
74        let mut attributes = payload.attributes.clone();
75        attributes.extend(chunk.attributes);
76
77        let mut trace = Trace::new(chunk.spans, TraceIngestInfo::Datadog);
78        trace.trace_id_high = chunk.trace_id_high;
79        trace.trace_id_low = chunk.trace_id_low;
80        trace.origin = chunk.origin;
81        trace.payload = payload_fields.clone();
82        trace.attributes = Arc::new(attributes);
83        trace.priority = chunk.priority;
84        trace.dropped_trace = chunk.dropped_trace;
85        trace.sampling_mechanism = chunk.sampling_mechanism;
86        traces.push(trace);
87    }
88
89    Ok(traces)
90}
91
92/// Intermediate representation of a decoded tracer payload before chunks are lifted into `Trace`s.
93struct DecodedPayload {
94    container_id: MetaString,
95    language_name: MetaString,
96    language_version: MetaString,
97    tracer_version: MetaString,
98    runtime_id: MetaString,
99    env: MetaString,
100    hostname: MetaString,
101    app_version: MetaString,
102    attributes: FastHashMap<MetaString, AttributeValue>,
103    chunks: Vec<DecodedChunk>,
104}
105
106/// Intermediate representation of a decoded trace chunk.
107struct DecodedChunk {
108    priority: Option<i32>,
109    origin: MetaString,
110    attributes: FastHashMap<MetaString, AttributeValue>,
111    spans: Vec<Span>,
112    dropped_trace: bool,
113    trace_id_high: u64,
114    trace_id_low: u64,
115    sampling_mechanism: u32,
116}
117
118/// Splits a big-endian trace ID byte string into its high and low 64-bit halves.
119///
120/// IDs longer than 16 bytes use the final 16 bytes, matching `normalizeTraceChunkV1` in the
121/// reference decoder; shorter IDs are right-aligned (high-order bytes treated as zero).
122fn split_trace_id(id: &[u8]) -> (u64, u64) {
123    let mut buf = [0u8; 16];
124    if id.len() >= 16 {
125        buf.copy_from_slice(&id[id.len() - 16..]);
126    } else {
127        buf[16 - id.len()..].copy_from_slice(id);
128    }
129    let high = u64::from_be_bytes(buf[0..8].try_into().unwrap());
130    let low = u64::from_be_bytes(buf[8..16].try_into().unwrap());
131    (high, low)
132}
133
134/// Decodes the top-level `TracerPayload` map.
135fn decode_tracer_payload(r: &mut &[u8]) -> Result<DecodedPayload, DecodeError> {
136    let mut strings = StringTable::new();
137    let mut payload = DecodedPayload {
138        container_id: MetaString::empty(),
139        language_name: MetaString::empty(),
140        language_version: MetaString::empty(),
141        tracer_version: MetaString::empty(),
142        runtime_id: MetaString::empty(),
143        env: MetaString::empty(),
144        hostname: MetaString::empty(),
145        app_version: MetaString::empty(),
146        attributes: FastHashMap::default(),
147        chunks: Vec::new(),
148    };
149
150    let num_fields = read::read_map_len(r, "tracer payload")?;
151    for _ in 0..num_fields {
152        let field = read::read_u32(r, "tracer payload field")?;
153        match field {
154            1 => {
155                // The string table must arrive first so later references resolve. Anything beyond
156                // the seeded empty string means fields were decoded before it.
157                if strings.len() > 1 {
158                    return Err(DecodeError::StringsNotFirst);
159                }
160                decode_string_table(r, &mut strings)?;
161            }
162            2 => payload.container_id = value::read_streaming_string(r, &mut strings, "container ID")?,
163            3 => payload.language_name = value::read_streaming_string(r, &mut strings, "language name")?,
164            4 => payload.language_version = value::read_streaming_string(r, &mut strings, "language version")?,
165            5 => payload.tracer_version = value::read_streaming_string(r, &mut strings, "tracer version")?,
166            6 => payload.runtime_id = value::read_streaming_string(r, &mut strings, "runtime ID")?,
167            7 => payload.env = value::read_streaming_string(r, &mut strings, "env")?,
168            8 => payload.hostname = value::read_streaming_string(r, &mut strings, "hostname")?,
169            9 => payload.app_version = value::read_streaming_string(r, &mut strings, "app version")?,
170            10 => payload.attributes = value::read_attributes_map(r, &mut strings, "tracer payload attributes")?,
171            11 => payload.chunks = decode_chunk_list(r, &mut strings)?,
172            _ => value::harvest_unknown_field(r, &mut strings, "tracer payload field")?,
173        }
174    }
175
176    Ok(payload)
177}
178
179/// Decodes the string table array (field 1 of the tracer payload).
180///
181/// Empty strings are skipped: index 0 is always the pre-seeded empty string, matching the reference
182/// encoder which never emits duplicate or additional empty strings.
183fn decode_string_table(r: &mut &[u8], strings: &mut StringTable) -> Result<(), DecodeError> {
184    let num_strings = read::read_array_len(r, "string table")?;
185    for _ in 0..num_strings {
186        let s = read::read_str(r, "string table entry")?;
187        if s.is_empty() {
188            continue;
189        }
190        strings.add(s);
191    }
192    Ok(())
193}
194
195/// Decodes the list of trace chunks (field 11 of the tracer payload).
196fn decode_chunk_list(r: &mut &[u8], strings: &mut StringTable) -> Result<Vec<DecodedChunk>, DecodeError> {
197    let num_chunks = read::read_array_len_with_minimum(r, MIN_BYTES_PER_TRACE_CHUNK, "trace chunk list")?;
198    let mut chunks = Vec::with_capacity(num_chunks as usize);
199    for _ in 0..num_chunks {
200        chunks.push(decode_chunk(r, strings)?);
201    }
202    Ok(chunks)
203}
204
205/// Decodes a single `TraceChunk` map.
206fn decode_chunk(r: &mut &[u8], strings: &mut StringTable) -> Result<DecodedChunk, DecodeError> {
207    let mut priority = None;
208    let mut origin = MetaString::empty();
209    let mut attributes = FastHashMap::default();
210    let mut spans = Vec::new();
211    let mut dropped_trace = false;
212    let mut trace_id_high = 0;
213    let mut trace_id_low = 0;
214    let mut sampling_mechanism = 0;
215
216    let num_fields = read::read_map_len(r, "trace chunk")?;
217    for _ in 0..num_fields {
218        let field = read::read_u32(r, "trace chunk field")?;
219        match field {
220            1 => priority = Some(read::read_i32(r, "trace chunk priority")?),
221            2 => origin = value::read_streaming_string(r, strings, "trace chunk origin")?,
222            3 => attributes = value::read_attributes_map(r, strings, "trace chunk attributes")?,
223            4 => spans = decode_span_list(r, strings)?,
224            5 => dropped_trace = read::read_bool(r, "trace chunk droppedTrace")?,
225            6 => {
226                let id = read::read_bytes(r, "trace chunk traceID")?;
227                (trace_id_high, trace_id_low) = split_trace_id(&id);
228            }
229            7 => sampling_mechanism = read::read_u32(r, "trace chunk samplingMechanism")?,
230            _ => value::harvest_unknown_field(r, strings, "trace chunk field")?,
231        }
232    }
233
234    Ok(DecodedChunk {
235        priority,
236        origin,
237        attributes,
238        spans,
239        dropped_trace,
240        trace_id_high,
241        trace_id_low,
242        sampling_mechanism,
243    })
244}
245
246/// Decodes the list of spans within a trace chunk (field 4).
247fn decode_span_list(r: &mut &[u8], strings: &mut StringTable) -> Result<Vec<Span>, DecodeError> {
248    let num_spans = read::read_array_len_with_minimum(r, MIN_BYTES_PER_SPAN, "span list")?;
249    let mut spans = Vec::with_capacity(num_spans as usize);
250    for _ in 0..num_spans {
251        spans.push(decode_span(r, strings)?);
252    }
253    Ok(spans)
254}
255
256/// Decodes a single `Span` map.
257fn decode_span(r: &mut &[u8], strings: &mut StringTable) -> Result<Span, DecodeError> {
258    let mut service = MetaString::empty();
259    let mut name = MetaString::empty();
260    let mut resource = MetaString::empty();
261    let mut span_id = 0;
262    let mut parent_id = 0;
263    let mut start = 0;
264    let mut duration = 0;
265    let mut error = 0;
266    let mut attributes = FastHashMap::default();
267    let mut span_type = MetaString::empty();
268    let mut links = Vec::new();
269    let mut events = Vec::new();
270    let mut env = MetaString::empty();
271    let mut version = MetaString::empty();
272    let mut component = MetaString::empty();
273    let mut kind = 0;
274
275    let num_fields = read::read_map_len(r, "span")?;
276    for _ in 0..num_fields {
277        let field = read::read_u32(r, "span field")?;
278        match field {
279            1 => service = value::read_streaming_string(r, strings, "span service")?,
280            2 => name = value::read_streaming_string(r, strings, "span name")?,
281            3 => resource = value::read_streaming_string(r, strings, "span resource")?,
282            4 => span_id = read::read_u64(r, "span spanID")?,
283            5 => parent_id = read::read_u64(r, "span parentID")?,
284            6 => start = read::read_u64(r, "span start")?,
285            7 => duration = read::read_u64(r, "span duration")?,
286            8 => error = i32::from(read::read_bool(r, "span error")?),
287            9 => attributes = value::read_attributes_map(r, strings, "span attributes")?,
288            10 => span_type = value::read_streaming_string(r, strings, "span type")?,
289            11 => links = decode_span_link_list(r, strings)?,
290            12 => events = decode_span_event_list(r, strings)?,
291            13 => env = value::read_streaming_string(r, strings, "span env")?,
292            14 => version = value::read_streaming_string(r, strings, "span version")?,
293            15 => component = value::read_streaming_string(r, strings, "span component")?,
294            16 => kind = read::read_u32(r, "span kind")?,
295            _ => value::harvest_unknown_field(r, strings, "span field")?,
296        }
297    }
298
299    Ok(Span::new(
300        service, name, resource, span_type, span_id, parent_id, start, duration, error,
301    )
302    .with_attributes(attributes)
303    .with_span_links(links)
304    .with_span_events(events)
305    .with_env(env)
306    .with_version(version)
307    .with_component(component)
308    .with_kind(kind))
309}
310
311/// Decodes the list of span links within a span (field 11).
312fn decode_span_link_list(r: &mut &[u8], strings: &mut StringTable) -> Result<Vec<SpanLink>, DecodeError> {
313    let num_links = read::read_array_len(r, "span link list")?;
314    let mut links = Vec::with_capacity(num_links as usize);
315    for _ in 0..num_links {
316        links.push(decode_span_link(r, strings)?);
317    }
318    Ok(links)
319}
320
321/// Decodes a single `SpanLink` map.
322fn decode_span_link(r: &mut &[u8], strings: &mut StringTable) -> Result<SpanLink, DecodeError> {
323    let mut trace_id_high = 0;
324    let mut trace_id_low = 0;
325    let mut span_id = 0;
326    let mut attributes = FastHashMap::default();
327    let mut tracestate = MetaString::empty();
328    let mut flags = 0;
329
330    let num_fields = read::read_map_len(r, "span link")?;
331    for _ in 0..num_fields {
332        let field = read::read_u32(r, "span link field")?;
333        match field {
334            1 => {
335                let id = read::read_bytes(r, "span link traceID")?;
336                (trace_id_high, trace_id_low) = split_trace_id(&id);
337            }
338            2 => span_id = read::read_u64(r, "span link spanID")?,
339            3 => attributes = value::read_attributes_map(r, strings, "span link attributes")?,
340            4 => tracestate = value::read_streaming_string(r, strings, "span link tracestate")?,
341            5 => flags = read::read_u32(r, "span link flags")?,
342            _ => value::harvest_unknown_field(r, strings, "span link field")?,
343        }
344    }
345
346    Ok(SpanLink::new(trace_id_low, span_id)
347        .with_trace_id_high(trace_id_high)
348        .with_attributes(attributes)
349        .with_tracestate(tracestate)
350        .with_flags(flags))
351}
352
353/// Decodes the list of span events within a span (field 12).
354fn decode_span_event_list(r: &mut &[u8], strings: &mut StringTable) -> Result<Vec<SpanEvent>, DecodeError> {
355    let num_events = read::read_array_len(r, "span event list")?;
356    let mut events = Vec::with_capacity(num_events as usize);
357    for _ in 0..num_events {
358        events.push(decode_span_event(r, strings)?);
359    }
360    Ok(events)
361}
362
363/// Decodes a single `SpanEvent` map.
364fn decode_span_event(r: &mut &[u8], strings: &mut StringTable) -> Result<SpanEvent, DecodeError> {
365    let mut time = 0;
366    let mut name = MetaString::empty();
367    let mut attributes = FastHashMap::default();
368
369    let num_fields = read::read_map_len(r, "span event")?;
370    for _ in 0..num_fields {
371        let field = read::read_u32(r, "span event field")?;
372        match field {
373            1 => time = read::read_u64(r, "span event time")?,
374            2 => name = value::read_streaming_string(r, strings, "span event name")?,
375            3 => attributes = value::read_attributes_map(r, strings, "span event attributes")?,
376            _ => value::harvest_unknown_field(r, strings, "span event field")?,
377        }
378    }
379
380    Ok(SpanEvent::new(time, name).with_attributes(attributes))
381}