Skip to main content

saluki_core/data_model/event/trace/
mod.rs

1//! Traces.
2
3use std::sync::Arc;
4
5use saluki_common::collections::FastHashMap;
6use stringtheory::MetaString;
7
8mod model_traits;
9pub use self::model_traits::{AttributeValue, AttributeValueExt, KeyValueList, SalukiValues};
10
11/// Payload-level metadata promoted from the tracer payload or OTLP resource.
12///
13/// These fields are common to all chunks within a single tracer payload and describe
14/// the tracer and its environment rather than any individual trace or span.
15#[derive(Clone, Debug, PartialEq, Default)]
16pub struct PayloadFields {
17    /// Container ID associated with the tracer.
18    pub container_id: MetaString,
19    /// Tracer language name (for example, `"go"`, `"python"`).
20    pub language_name: MetaString,
21    /// Tracer language runtime version.
22    pub language_version: MetaString,
23    /// Tracer library version.
24    pub tracer_version: MetaString,
25    /// Tracer runtime ID.
26    pub runtime_id: MetaString,
27    /// Deployment environment (for example, `"production"`, `"staging"`).
28    pub env: MetaString,
29    /// Hostname of the tracer host.
30    pub hostname: MetaString,
31    /// Application version string.
32    pub app_version: MetaString,
33    /// Container tags resolved from the payload's source, as `key:value` tags.
34    ///
35    /// `None` when the source resolved none, in which case consumers derive them from [`Trace::attributes`]. A thin
36    /// pointer keeps this field to a single word, because `Trace` sizes every `Event`.
37    pub container_tags: Option<Arc<Vec<MetaString>>>,
38    /// Per-chunk weight from `Datadog-Client-Dropped-P0-Traces` header. Zero if absent.
39    pub client_dropped_p0s_weight: f64,
40}
41
42impl PayloadFields {
43    /// Returns the container tags the payload's source resolved, as `key:value` tags.
44    pub fn resolved_container_tags(&self) -> &[MetaString] {
45        self.container_tags.as_deref().map_or(&[], Vec::as_slice)
46    }
47}
48
49/// The protocol a trace chunk was ingested through.
50///
51/// Set once when the trace is constructed. Span attributes can be rewritten or removed downstream, so they cannot
52/// reliably identify the input protocol.
53#[derive(Clone, Copy, Debug, PartialEq)]
54pub enum TraceIngestInfo {
55    /// Received in a Datadog tracer payload.
56    Datadog,
57
58    /// Translated from OTLP.
59    Otlp {
60        /// The OTLP receiver's configured sampling rate, normalized to `(0, 1]`.
61        ///
62        /// This is the receiver's configuration, not an estimate of sampling performed upstream of it. The value is
63        /// not validated here; the producer normalizes it.
64        receiver_sampling_rate: f64,
65    },
66}
67
68/// A trace event.
69///
70/// A trace is a collection of spans that represent a distributed trace.
71#[derive(Clone, Debug, PartialEq)]
72pub struct Trace {
73    /// The spans that make up this trace.
74    spans: Vec<Span>,
75    /// Upper 8 bytes of the 128-bit trace ID (big-endian). Zero for 64-bit-only sources.
76    pub trace_id_high: u64,
77    /// Lower 8 bytes of the 128-bit trace ID (big-endian).
78    pub trace_id_low: u64,
79    /// Trace origin string (for example, `"lambda"`, `"rum"`).
80    pub origin: MetaString,
81    /// Payload-level metadata (promoted from the tracer payload or OTLP resource).
82    pub payload: PayloadFields,
83    /// Trace chunk-level or resource-level attributes.
84    pub attributes: Arc<FastHashMap<MetaString, AttributeValue>>,
85    /// Sampling priority set by the tracer or a sampler.
86    pub priority: Option<i32>,
87    /// Whether this trace was dropped during sampling.
88    pub dropped_trace: bool,
89    /// The mechanism by which the sampling decision was made.
90    pub sampling_mechanism: u32,
91    /// Identifier of the component that made the final sampling decision.
92    pub decision_maker: Option<MetaString>,
93    /// The protocol this trace was ingested through.
94    ingest_info: TraceIngestInfo,
95}
96
97impl Trace {
98    /// Creates a new `Trace` with the given spans, ingested through the protocol described by `ingest_info`.
99    ///
100    /// All other unified fields default to empty / zero. Callers should set them
101    /// directly after construction.
102    pub fn new(spans: Vec<Span>, ingest_info: TraceIngestInfo) -> Self {
103        Self {
104            spans,
105            trace_id_high: 0,
106            trace_id_low: 0,
107            origin: MetaString::empty(),
108            payload: PayloadFields::default(),
109            attributes: Arc::new(FastHashMap::default()),
110            priority: None,
111            dropped_trace: false,
112            sampling_mechanism: 0,
113            decision_maker: None,
114            ingest_info,
115        }
116    }
117
118    /// Returns the protocol this trace was ingested through.
119    ///
120    /// Fixed at construction, so later changes to spans or attributes cannot reclassify the trace.
121    pub fn ingest_info(&self) -> TraceIngestInfo {
122        self.ingest_info
123    }
124
125    /// Returns a reference to the spans in this trace.
126    pub fn spans(&self) -> &[Span] {
127        &self.spans
128    }
129
130    /// Returns a mutable reference to the spans in this trace.
131    pub fn spans_mut(&mut self) -> &mut [Span] {
132        &mut self.spans
133    }
134
135    /// Replaces the spans in this trace with the given spans.
136    pub fn set_spans(&mut self, spans: Vec<Span>) {
137        self.spans = spans;
138    }
139
140    /// Retains only the spans specified by the predicate.
141    ///
142    /// Returns the number of spans retained. If no spans match, the trace is left unchanged.
143    pub fn retain_spans<F>(&mut self, mut f: F) -> usize
144    where
145        F: FnMut(&Trace, &Span) -> bool,
146    {
147        if self.spans.is_empty() {
148            return 0;
149        }
150
151        let mut has_match = false;
152        for span in self.spans.iter() {
153            if f(self, span) {
154                has_match = true;
155                break;
156            }
157        }
158
159        if !has_match {
160            return 0;
161        }
162
163        let mut spans = std::mem::take(&mut self.spans);
164        spans.retain(|span| f(self, span));
165        spans.shrink_to_fit();
166        let _ = std::mem::replace(&mut self.spans, spans);
167
168        self.spans.len()
169    }
170
171    /// Remove spans only the spans specified by the predicate return true.
172    pub fn remove_spans<F>(&mut self, mut f: F)
173    where
174        F: FnMut(&Trace, &Span) -> bool,
175    {
176        if self.spans.is_empty() {
177            return;
178        }
179
180        let mut spans = std::mem::take(&mut self.spans);
181        spans.retain(|span| !f(self, span));
182        spans.shrink_to_fit();
183        let _ = std::mem::replace(&mut self.spans, spans);
184    }
185}
186
187/// A span event.
188#[derive(Clone, Debug, PartialEq, Default)]
189pub struct Span {
190    /// The name of the service associated with this span.
191    service: MetaString,
192    /// The operation name of this span.
193    name: MetaString,
194    /// The resource associated with this span.
195    resource: MetaString,
196    /// The unique identifier of this span.
197    span_id: u64,
198    /// The identifier of this span's parent, if any.
199    parent_id: u64,
200    /// The start timestamp of this span in nanoseconds since Unix epoch.
201    start: u64,
202    /// The duration of this span in nanoseconds.
203    duration: u64,
204    /// Error flag represented as 0 (no error) or 1 (error).
205    error: i32,
206    /// Span type classification (for example, web, db, lambda).
207    span_type: MetaString,
208    /// Links describing relationships to other spans.
209    span_links: Vec<SpanLink>,
210    /// Events associated with this span.
211    span_events: Vec<SpanEvent>,
212    /// Per-span environment override. Overrides `Trace.payload.env` when non-empty.
213    pub env: MetaString,
214    /// Per-span application version.
215    pub version: MetaString,
216    /// Instrumentation component name.
217    pub component: MetaString,
218    /// Span kind (OTel values): 0=unspecified, 1=internal, 2=server, 3=client, 4=producer, 5=consumer.
219    pub kind: u32,
220    /// Typed span-level attributes.
221    pub attributes: FastHashMap<MetaString, AttributeValue>,
222}
223
224impl Span {
225    /// Creates a new `Span` with all required fields.
226    #[allow(clippy::too_many_arguments)]
227    pub fn new(
228        service: impl Into<MetaString>, name: impl Into<MetaString>, resource: impl Into<MetaString>,
229        span_type: impl Into<MetaString>, span_id: u64, parent_id: u64, start: u64, duration: u64, error: i32,
230    ) -> Self {
231        Self {
232            service: service.into(),
233            name: name.into(),
234            resource: resource.into(),
235            span_type: span_type.into(),
236            span_id,
237            parent_id,
238            start,
239            duration,
240            error,
241            ..Self::default()
242        }
243    }
244
245    /// Sets the service name.
246    pub fn with_service(mut self, service: impl Into<MetaString>) -> Self {
247        self.service = service.into();
248        self
249    }
250
251    /// Sets the operation name.
252    pub fn with_name(mut self, name: impl Into<MetaString>) -> Self {
253        self.name = name.into();
254        self
255    }
256
257    /// Sets the resource name.
258    pub fn with_resource(mut self, resource: impl Into<MetaString>) -> Self {
259        self.resource = resource.into();
260        self
261    }
262
263    /// Sets the span identifier.
264    pub fn with_span_id(mut self, span_id: u64) -> Self {
265        self.span_id = span_id;
266        self
267    }
268
269    /// Sets the parent span identifier.
270    pub fn with_parent_id(mut self, parent_id: u64) -> Self {
271        self.parent_id = parent_id;
272        self
273    }
274
275    /// Sets the start timestamp.
276    pub fn with_start(mut self, start: u64) -> Self {
277        self.start = start;
278        self
279    }
280
281    /// Sets the span duration.
282    pub fn with_duration(mut self, duration: u64) -> Self {
283        self.duration = duration;
284        self
285    }
286
287    /// Sets the error flag.
288    pub fn with_error(mut self, error: i32) -> Self {
289        self.error = error;
290        self
291    }
292
293    /// Sets the span type (for example, web, db, lambda).
294    pub fn with_span_type(mut self, span_type: impl Into<MetaString>) -> Self {
295        self.span_type = span_type.into();
296        self
297    }
298
299    /// Replaces the span attributes map.
300    pub fn with_attributes(mut self, attributes: impl Into<Option<FastHashMap<MetaString, AttributeValue>>>) -> Self {
301        self.attributes = attributes.into().unwrap_or_default();
302        self
303    }
304
305    /// Replaces the span links collection.
306    pub fn with_span_links(mut self, span_links: impl Into<Option<Vec<SpanLink>>>) -> Self {
307        self.span_links = span_links.into().unwrap_or_default();
308        self
309    }
310
311    /// Replaces the span events collection.
312    pub fn with_span_events(mut self, span_events: impl Into<Option<Vec<SpanEvent>>>) -> Self {
313        self.span_events = span_events.into().unwrap_or_default();
314        self
315    }
316
317    /// Sets the per-span environment override.
318    pub fn with_env(mut self, env: impl Into<MetaString>) -> Self {
319        self.env = env.into();
320        self
321    }
322
323    /// Sets the per-span application version.
324    pub fn with_version(mut self, version: impl Into<MetaString>) -> Self {
325        self.version = version.into();
326        self
327    }
328
329    /// Sets the instrumentation component.
330    pub fn with_component(mut self, component: impl Into<MetaString>) -> Self {
331        self.component = component.into();
332        self
333    }
334
335    /// Sets the span kind.
336    pub fn with_kind(mut self, kind: u32) -> Self {
337        self.kind = kind;
338        self
339    }
340
341    /// Returns the service name.
342    pub fn service(&self) -> &str {
343        &self.service
344    }
345
346    /// Returns the operation name.
347    pub fn name(&self) -> &str {
348        &self.name
349    }
350
351    /// Returns the resource name.
352    pub fn resource(&self) -> &str {
353        &self.resource
354    }
355
356    /// Sets the resource name.
357    pub fn set_resource(&mut self, resource: impl Into<MetaString>) {
358        self.resource = resource.into();
359    }
360
361    /// Returns the span identifier.
362    pub fn span_id(&self) -> u64 {
363        self.span_id
364    }
365
366    /// Returns the parent span identifier.
367    pub fn parent_id(&self) -> u64 {
368        self.parent_id
369    }
370
371    /// Returns the start timestamp.
372    pub fn start(&self) -> u64 {
373        self.start
374    }
375
376    /// Returns the span duration.
377    pub fn duration(&self) -> u64 {
378        self.duration
379    }
380
381    /// Returns the error flag.
382    pub fn error(&self) -> i32 {
383        self.error
384    }
385
386    /// Returns the span type.
387    pub fn span_type(&self) -> &str {
388        &self.span_type
389    }
390
391    /// Returns the span links collection.
392    pub fn span_links(&self) -> &[SpanLink] {
393        &self.span_links
394    }
395
396    /// Returns a mutable reference to the span links collection.
397    pub fn span_links_mut(&mut self) -> &mut Vec<SpanLink> {
398        &mut self.span_links
399    }
400
401    /// Returns the span events collection.
402    pub fn span_events(&self) -> &[SpanEvent] {
403        &self.span_events
404    }
405
406    /// Returns a mutable reference to the span events collection.
407    pub fn span_events_mut(&mut self) -> &mut Vec<SpanEvent> {
408        &mut self.span_events
409    }
410}
411
412/// A link between spans describing a causal relationship.
413#[derive(Clone, Debug, PartialEq, Default)]
414pub struct SpanLink {
415    /// Trace identifier for the linked span.
416    trace_id: u64,
417    /// High bits of the trace identifier when 128-bit IDs are used.
418    trace_id_high: u64,
419    /// Span identifier for the linked span.
420    span_id: u64,
421    /// Additional attributes attached to the link.
422    attributes: FastHashMap<MetaString, AttributeValue>,
423    /// W3C tracestate value.
424    tracestate: MetaString,
425    /// W3C trace flags where the high bit must be set when provided.
426    flags: u32,
427}
428
429impl SpanLink {
430    /// Creates a new span link for the provided identifiers.
431    pub fn new(trace_id: u64, span_id: u64) -> Self {
432        Self {
433            trace_id,
434            span_id,
435            ..Self::default()
436        }
437    }
438
439    /// Sets the trace identifier.
440    pub fn with_trace_id(mut self, trace_id: u64) -> Self {
441        self.trace_id = trace_id;
442        self
443    }
444
445    /// Sets the high bits of the trace identifier.
446    pub fn with_trace_id_high(mut self, trace_id_high: u64) -> Self {
447        self.trace_id_high = trace_id_high;
448        self
449    }
450
451    /// Sets the span identifier.
452    pub fn with_span_id(mut self, span_id: u64) -> Self {
453        self.span_id = span_id;
454        self
455    }
456
457    /// Replaces the attributes map.
458    pub fn with_attributes(mut self, attributes: impl Into<Option<FastHashMap<MetaString, AttributeValue>>>) -> Self {
459        self.attributes = attributes.into().unwrap_or_default();
460        self
461    }
462
463    /// Sets the W3C tracestate value.
464    pub fn with_tracestate(mut self, tracestate: impl Into<MetaString>) -> Self {
465        self.tracestate = tracestate.into();
466        self
467    }
468
469    /// Sets the W3C trace flags.
470    pub fn with_flags(mut self, flags: u32) -> Self {
471        self.flags = flags;
472        self
473    }
474
475    /// Returns the trace identifier.
476    pub fn trace_id(&self) -> u64 {
477        self.trace_id
478    }
479
480    /// Returns the high bits of the trace identifier.
481    pub fn trace_id_high(&self) -> u64 {
482        self.trace_id_high
483    }
484
485    /// Returns the span identifier.
486    pub fn span_id(&self) -> u64 {
487        self.span_id
488    }
489
490    /// Returns the attributes map.
491    pub fn attributes(&self) -> &FastHashMap<MetaString, AttributeValue> {
492        &self.attributes
493    }
494
495    /// Returns the W3C tracestate value.
496    pub fn tracestate(&self) -> &str {
497        &self.tracestate
498    }
499
500    /// Returns the W3C trace flags.
501    pub fn flags(&self) -> u32 {
502        self.flags
503    }
504}
505
506/// An event associated with a span.
507#[derive(Clone, Debug, PartialEq, Default)]
508pub struct SpanEvent {
509    /// Event timestamp in nanoseconds since Unix epoch.
510    time_unix_nano: u64,
511    /// Event name.
512    name: MetaString,
513    /// Arbitrary attributes describing the event.
514    attributes: FastHashMap<MetaString, AttributeValue>,
515}
516
517impl SpanEvent {
518    /// Creates a new span event with the given timestamp and name.
519    pub fn new(time_unix_nano: u64, name: impl Into<MetaString>) -> Self {
520        Self {
521            time_unix_nano,
522            name: name.into(),
523            ..Self::default()
524        }
525    }
526
527    /// Sets the event timestamp.
528    pub fn with_time_unix_nano(mut self, time_unix_nano: u64) -> Self {
529        self.time_unix_nano = time_unix_nano;
530        self
531    }
532
533    /// Sets the event name.
534    pub fn with_name(mut self, name: impl Into<MetaString>) -> Self {
535        self.name = name.into();
536        self
537    }
538
539    /// Replaces the attributes map.
540    pub fn with_attributes(mut self, attributes: impl Into<Option<FastHashMap<MetaString, AttributeValue>>>) -> Self {
541        self.attributes = attributes.into().unwrap_or_default();
542        self
543    }
544
545    /// Returns the event timestamp.
546    pub fn time_unix_nano(&self) -> u64 {
547        self.time_unix_nano
548    }
549
550    /// Returns the event name.
551    pub fn name(&self) -> &str {
552        &self.name
553    }
554
555    /// Returns the attributes map.
556    pub fn attributes(&self) -> &FastHashMap<MetaString, AttributeValue> {
557        &self.attributes
558    }
559
560    /// Returns a mutable reference to the attributes map.
561    pub fn attributes_mut(&mut self) -> &mut FastHashMap<MetaString, AttributeValue> {
562        &mut self.attributes
563    }
564}