Skip to main content

saluki_core/data_model/event/trace/
model_traits.rs

1//! Trait implementations that let Saluki's trace types be used by shared trace-processing logic.
2//!
3//! The traits describe what a span, span event, span link and trace chunk are, without saying how they are stored.
4//! Logic written against them (obfuscation, tag replacement, trace filtering) therefore runs directly on [`Span`],
5//! [`SpanEvent`], [`SpanLink`] and [`Trace`], with no conversion into another representation and no per-type copy of the
6//! logic.
7//!
8//! The write traits hand out mutable references to the attribute value type, so Saluki stores that type, parameterized
9//! with its own string type ([`MetaString`]). See [`SalukiValues`].
10//!
11//! # Promoted tags
12//!
13//! The span traits expose `env`, `version`, `component` and `span.kind` through dedicated accessors.
14//! Those accessors also reach values stored in the attribute map. The attribute traits hide these tags, so each
15//! replacement rule visits them once. Trace origin, sampling priority and sampling mechanism use their fields.
16
17use std::sync::Arc;
18
19use libdd_trace_model as model;
20use libdd_trace_model::{AttributeRef, ValueMap, ValueMapMut};
21use saluki_common::collections::FastHashMap;
22use stringtheory::MetaString;
23
24use super::{Span, SpanEvent, SpanLink, Trace};
25
26/// Selects the concrete types behind attribute values: text is a [`MetaString`], bytes are a `Vec<u8>`, arrays are a
27/// `Vec<AttributeValue>`, and key/value lists are a [`KeyValueList`].
28///
29/// It is only used as a type parameter, so it has no values.
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub enum SalukiValues {}
32
33/// Payload of [`AttributeValue::KeyValueList`].
34pub type KeyValueList = Vec<(MetaString, AttributeValue)>;
35
36impl model::ValueTypes for SalukiValues {
37    type Text = MetaString;
38    type Bytes = Vec<u8>;
39    type Array = Vec<AttributeValue>;
40    type Map = KeyValueList;
41}
42
43/// Typed value for attributes at every level of the trace model.
44pub type AttributeValue = model::AttributeValue<SalukiValues>;
45
46/// Returns `true` if a later list entry has the same key.
47fn is_shadowed(entries: &KeyValueList, index: usize) -> bool {
48    let key = &entries[index].0;
49    entries[index + 1..].iter().any(|(later, _)| later == key)
50}
51
52/// Keep only each key's last entry, preserving the order of the surviving entries.
53fn remove_shadowed(entries: &mut KeyValueList) {
54    let mut index = 0;
55    while index < entries.len() {
56        if is_shadowed(entries, index) {
57            Vec::remove(entries, index);
58        } else {
59            index += 1;
60        }
61    }
62}
63
64/// Key/value lists preserve decoded order and can contain duplicate keys; the last value wins.
65impl ValueMap<SalukiValues> for KeyValueList {
66    fn get(&self, key: &str) -> Option<&AttributeValue> {
67        self.as_slice()
68            .iter()
69            .rev()
70            .find(|(k, _)| k.as_ref() == key)
71            .map(|(_, v)| v)
72    }
73    fn len(&self) -> usize {
74        (0..self.as_slice().len()).filter(|&i| !is_shadowed(self, i)).count()
75    }
76    fn iter<'a>(&'a self) -> impl Iterator<Item = (&'a str, &'a AttributeValue)>
77    where
78        SalukiValues: 'a,
79    {
80        self.as_slice()
81            .iter()
82            .enumerate()
83            .filter(|(i, _)| !is_shadowed(self, *i))
84            .map(|(_, (k, v))| (k.as_ref(), v))
85    }
86}
87
88impl ValueMapMut<SalukiValues> for KeyValueList {
89    fn get_mut(&mut self, key: &str) -> Option<&mut AttributeValue> {
90        self.as_mut_slice()
91            .iter_mut()
92            .rev()
93            .find(|(k, _)| k.as_ref() == key)
94            .map(|(_, v)| v)
95    }
96    fn insert(&mut self, key: MetaString, value: AttributeValue) -> Option<AttributeValue> {
97        match self
98            .as_mut_slice()
99            .iter_mut()
100            .rev()
101            .find(|(k, _)| k.as_ref() == key.as_ref())
102        {
103            Some((_, current)) => Some(std::mem::replace(current, value)),
104            None => {
105                self.push((key, value));
106                None
107            }
108        }
109    }
110    fn remove(&mut self, key: &str) -> Option<AttributeValue> {
111        let last = self.as_slice().iter().rposition(|(k, _)| k.as_ref() == key)?;
112        let (_, value) = Vec::remove(self, last);
113        self.retain(|(k, _)| &**k != key);
114        Some(value)
115    }
116    fn retain(&mut self, mut f: impl FnMut(&str, &mut AttributeValue) -> bool) {
117        remove_shadowed(self);
118        Vec::retain_mut(self, |(k, v)| f(k.as_ref(), v));
119    }
120    fn iter_mut<'a>(&'a mut self) -> impl Iterator<Item = (&'a str, &'a mut AttributeValue)>
121    where
122        SalukiValues: 'a,
123    {
124        remove_shadowed(self);
125        self.as_mut_slice().iter_mut().map(|(k, v)| {
126            let k: &'a MetaString = k;
127            (k.as_ref(), v)
128        })
129    }
130}
131
132/// Saluki's accessors for [`AttributeValue`].
133///
134/// [`AttributeValue`] is a type alias for a generic type from another crate, so these accessors are on a trait. Import
135/// the trait to call them.
136pub trait AttributeValueExt {
137    /// Returns the inner string if this is a `String` variant.
138    fn as_string(&self) -> Option<&MetaString>;
139
140    /// Returns the inner float if this is a `Float` variant.
141    ///
142    /// Returns `Some` only when the stored variant is `Float`. For numeric semantic tags where the source may store an
143    /// integer (for example, sampling priority, `_sample_rate`, `_top_level`), use [`as_num`][Self::as_num] instead.
144    fn as_float(&self) -> Option<f64>;
145
146    /// Returns the inner bool if this is a `Bool` variant.
147    fn as_bool(&self) -> Option<bool>;
148
149    /// Returns the inner integer if this is an `Int` variant.
150    fn as_int(&self) -> Option<i64>;
151
152    /// Returns a numeric value as `f64` for either `Float` or `Int` variants.
153    ///
154    /// Use this when the caller only needs a number and doesn't care whether the stored type is integral or
155    /// floating-point (for example, sampling priority).
156    fn as_num(&self) -> Option<f64>;
157
158    /// Returns the inner bytes if this is a `Bytes` variant.
159    fn as_bytes(&self) -> Option<&[u8]>;
160}
161
162impl AttributeValueExt for AttributeValue {
163    fn as_string(&self) -> Option<&MetaString> {
164        if let Self::String(s) = self {
165            Some(s)
166        } else {
167            None
168        }
169    }
170    fn as_float(&self) -> Option<f64> {
171        if let Self::Float(f) = self {
172            Some(*f)
173        } else {
174            None
175        }
176    }
177    fn as_bool(&self) -> Option<bool> {
178        if let Self::Bool(b) = self {
179            Some(*b)
180        } else {
181            None
182        }
183    }
184    fn as_int(&self) -> Option<i64> {
185        if let Self::Int(i) = self {
186            Some(*i)
187        } else {
188            None
189        }
190    }
191    fn as_num(&self) -> Option<f64> {
192        self.as_f64()
193    }
194    fn as_bytes(&self) -> Option<&[u8]> {
195        if let Self::Bytes(b) = self {
196            Some(b)
197        } else {
198            None
199        }
200    }
201}
202
203type AttrMap = FastHashMap<MetaString, AttributeValue>;
204
205fn str_of<'a>(m: &'a AttrMap, k: &str) -> Option<&'a str> {
206    m.get(k).and_then(|v| v.as_str())
207}
208fn f64_of(m: &AttrMap, k: &str) -> Option<f64> {
209    m.get(k).and_then(|v| v.as_f64())
210}
211fn i64_of(m: &AttrMap, k: &str) -> Option<i64> {
212    m.get(k).and_then(|v| v.as_i64())
213}
214
215macro_rules! impl_attributes {
216    ($ty:ty, $excluded:expr, |$s:ident| $map:expr, |$m:ident| $map_mut:expr) => {
217        impl model::Attributes for $ty {
218            type Text = MetaString;
219            type Bytes = Vec<u8>;
220            type Values = SalukiValues;
221            fn attribute_str(&self, key: &str) -> Option<&str> {
222                let $s = self;
223                if $excluded.contains(&key) {
224                    None
225                } else {
226                    str_of($map, key)
227                }
228            }
229            fn attribute_f64(&self, key: &str) -> Option<f64> {
230                let $s = self;
231                if $excluded.contains(&key) {
232                    None
233                } else {
234                    f64_of($map, key)
235                }
236            }
237            fn attribute_i64(&self, key: &str) -> Option<i64> {
238                let $s = self;
239                if $excluded.contains(&key) {
240                    None
241                } else {
242                    i64_of($map, key)
243                }
244            }
245            fn has_attribute(&self, key: &str) -> bool {
246                let $s = self;
247                !$excluded.contains(&key) && $map.contains_key(key)
248            }
249        }
250        impl model::AttributesIter for $ty {
251            fn attributes(&self) -> impl Iterator<Item = (&str, AttributeRef<'_, SalukiValues>)> {
252                let $s = self;
253                $map.iter()
254                    .filter(|(k, _)| !$excluded.contains(&k.as_ref()))
255                    .map(|(k, v)| (k.as_ref(), AttributeRef::from(v)))
256            }
257        }
258        impl model::AttributesMut for $ty {
259            fn retain_attributes(&mut self, mut f: impl FnMut(&str, &mut AttributeValue) -> bool) {
260                let $m = self;
261                $map_mut.retain(|k, v| $excluded.contains(&k.as_ref()) || f(k.as_ref(), v));
262            }
263            fn attribute_mut(&mut self, key: &str) -> Option<&mut AttributeValue> {
264                let $m = self;
265                if $excluded.contains(&key) {
266                    None
267                } else {
268                    $map_mut.get_mut(key)
269                }
270            }
271            fn set_attribute(&mut self, key: MetaString, value: AttributeValue) {
272                let $m = self;
273                if !$excluded.contains(&key.as_ref()) {
274                    $map_mut.insert(key, value);
275                }
276            }
277            fn remove_attribute(&mut self, key: &str) -> Option<AttributeValue> {
278                let $m = self;
279                if $excluded.contains(&key) {
280                    None
281                } else {
282                    $map_mut.remove(key)
283                }
284            }
285        }
286    };
287}
288
289impl_attributes!(Span, model::PROMOTED_SPAN_TAGS, |s| &s.attributes, |m| &mut m
290    .attributes);
291impl_attributes!(SpanEvent, [], |s| &s.attributes, |m| &mut m.attributes);
292impl_attributes!(SpanLink, [], |s| &s.attributes, |m| &mut m.attributes);
293// Trace-level attributes are behind an `Arc`: every write is copy-on-write.
294impl_attributes!(Trace, [], |s| &*s.attributes, |m| Arc::make_mut(&mut m.attributes));
295
296fn non_empty(s: &MetaString) -> Option<&str> {
297    (!s.is_empty()).then_some(s.as_ref())
298}
299
300/// Updates the stored tag and keeps an existing dedicated field consistent with it.
301fn set_promoted_text(field: &mut MetaString, attributes: &mut AttrMap, key: &str, value: MetaString) {
302    if let Some(attribute) = attributes.get_mut(key) {
303        *attribute = AttributeValue::String(value.clone());
304        if field.is_empty() {
305            return;
306        }
307    }
308    *field = value;
309}
310
311fn start_to_i64(value: u64) -> i64 {
312    i64::try_from(value).unwrap_or(i64::MAX)
313}
314
315fn duration_to_i64(value: u64) -> i64 {
316    i64::try_from(value).unwrap_or(-1)
317}
318
319fn from_i64(value: i64) -> u64 {
320    u64::try_from(value).unwrap_or(0)
321}
322
323fn span_kind_name(kind: u32) -> Option<&'static str> {
324    match kind {
325        1 => Some("internal"),
326        2 => Some("server"),
327        3 => Some("client"),
328        4 => Some("producer"),
329        5 => Some("consumer"),
330        _ => None,
331    }
332}
333
334fn span_kind_from_name(name: &str) -> u32 {
335    match name {
336        "internal" => 1,
337        "server" => 2,
338        "client" => 3,
339        "producer" => 4,
340        "consumer" => 5,
341        _ => 0,
342    }
343}
344
345impl model::SpanEvent for SpanEvent {
346    fn name(&self) -> &str {
347        &self.name
348    }
349    fn time_unix_nano(&self) -> u64 {
350        self.time_unix_nano
351    }
352}
353
354impl model::SpanLink for SpanLink {
355    fn trace_id(&self) -> u128 {
356        (u128::from(self.trace_id_high) << 64) | u128::from(self.trace_id)
357    }
358    fn span_id(&self) -> u64 {
359        self.span_id
360    }
361    fn tracestate(&self) -> &str {
362        &self.tracestate
363    }
364    fn flags(&self) -> u32 {
365        self.flags & !model::SPAN_LINK_FLAGS_SET_SENTINEL
366    }
367}
368
369impl model::Span for Span {
370    type SpanEvent = SpanEvent;
371    type SpanLink = SpanLink;
372    fn service(&self) -> &str {
373        &self.service
374    }
375    fn resource(&self) -> &str {
376        &self.resource
377    }
378    fn name(&self) -> &str {
379        &self.name
380    }
381    fn typ(&self) -> &str {
382        &self.span_type
383    }
384    fn span_id(&self) -> u64 {
385        self.span_id
386    }
387    fn parent_id(&self) -> u64 {
388        self.parent_id
389    }
390    fn start(&self) -> i64 {
391        start_to_i64(self.start)
392    }
393    fn duration(&self) -> i64 {
394        duration_to_i64(self.duration)
395    }
396    fn is_error(&self) -> bool {
397        self.error != 0
398    }
399    fn span_kind(&self) -> Option<&str> {
400        span_kind_name(self.kind).or_else(|| str_of(&self.attributes, "span.kind").filter(|value| !value.is_empty()))
401    }
402    fn env(&self) -> Option<&str> {
403        non_empty(&self.env).or_else(|| str_of(&self.attributes, "env").filter(|value| !value.is_empty()))
404    }
405    fn version(&self) -> Option<&str> {
406        non_empty(&self.version).or_else(|| str_of(&self.attributes, "version").filter(|value| !value.is_empty()))
407    }
408    fn component(&self) -> Option<&str> {
409        non_empty(&self.component).or_else(|| str_of(&self.attributes, "component").filter(|value| !value.is_empty()))
410    }
411    fn span_events(&self) -> impl Iterator<Item = &SpanEvent> {
412        self.span_events.iter()
413    }
414    fn span_links(&self) -> impl Iterator<Item = &SpanLink> {
415        self.span_links.iter()
416    }
417}
418
419impl model::SpanMut for Span {
420    fn set_service(&mut self, value: MetaString) {
421        self.service = value;
422    }
423    fn set_resource(&mut self, value: MetaString) {
424        self.resource = value;
425    }
426    fn set_name(&mut self, value: MetaString) {
427        self.name = value;
428    }
429    fn set_type(&mut self, value: MetaString) {
430        self.span_type = value;
431    }
432    fn set_parent_id(&mut self, value: u64) {
433        self.parent_id = value;
434    }
435    fn set_start(&mut self, value: i64) {
436        self.start = from_i64(value);
437    }
438    fn set_duration(&mut self, value: i64) {
439        self.duration = from_i64(value);
440    }
441    fn set_error(&mut self, value: bool) {
442        self.error = i32::from(value);
443    }
444    fn set_span_kind(&mut self, value: &str) {
445        let kind = span_kind_from_name(value);
446        if kind == 0 {
447            self.attributes.remove("span.kind");
448        } else if let Some(attribute) = self.attributes.get_mut("span.kind") {
449            *attribute = AttributeValue::String(value.to_owned().into());
450            if self.kind == 0 {
451                return;
452            }
453        }
454        self.kind = kind;
455    }
456    fn set_env(&mut self, value: MetaString) {
457        set_promoted_text(&mut self.env, &mut self.attributes, "env", value);
458    }
459    fn set_version(&mut self, value: MetaString) {
460        set_promoted_text(&mut self.version, &mut self.attributes, "version", value);
461    }
462    fn set_component(&mut self, value: MetaString) {
463        set_promoted_text(&mut self.component, &mut self.attributes, "component", value);
464    }
465    fn span_events_mut(&mut self) -> impl Iterator<Item = &mut SpanEvent> {
466        self.span_events.iter_mut()
467    }
468    fn span_links_mut(&mut self) -> impl Iterator<Item = &mut SpanLink> {
469        self.span_links.iter_mut()
470    }
471}
472
473impl model::TraceChunk for Trace {
474    type Span = Span;
475    fn trace_id(&self) -> u128 {
476        (u128::from(self.trace_id_high) << 64) | u128::from(self.trace_id_low)
477    }
478    fn origin(&self) -> &str {
479        &self.origin
480    }
481    fn spans(&self) -> impl Iterator<Item = &Span> {
482        self.spans.iter()
483    }
484    fn priority(&self) -> Option<i32> {
485        self.priority
486    }
487    fn sampling_mechanism(&self) -> Option<u32> {
488        // Saluki carries both a numeric mechanism and a `decision_maker` string.
489        (self.sampling_mechanism != 0).then_some(self.sampling_mechanism)
490    }
491    fn dropped_trace(&self) -> bool {
492        self.dropped_trace
493    }
494}
495
496impl model::TraceChunkMut for Trace {
497    fn set_origin(&mut self, value: MetaString) {
498        self.origin = value;
499    }
500    fn set_priority(&mut self, priority: i32) {
501        self.priority = Some(priority);
502    }
503    fn set_sampling_mechanism(&mut self, mechanism: u32) {
504        self.sampling_mechanism = mechanism;
505    }
506    fn set_dropped_trace(&mut self, value: bool) {
507        self.dropped_trace = value;
508    }
509    fn spans_mut(&mut self) -> impl Iterator<Item = &mut Span> {
510        self.spans.iter_mut()
511    }
512    fn retain_spans(&mut self, mut f: impl FnMut(&mut Span) -> bool) {
513        // Saluki's own `retain_spans` keeps the trace untouched when nothing matches; this does not.
514        self.spans.retain_mut(|s| f(s));
515    }
516}
517
518#[cfg(test)]
519mod tests {
520    use model::{Attributes as _, AttributesIter as _, AttributesMut as _, Span as _};
521
522    use super::*;
523    use crate::data_model::event::trace::TraceIngestInfo;
524
525    fn string(value: &str) -> AttributeValue {
526        AttributeValue::String(value.into())
527    }
528
529    /// Fails to compile if one of the traits that shared trace logic relies on stops being implemented.
530    #[test]
531    fn implements_the_shared_trace_traits() {
532        fn assert_span<S: model::SpanMut>() {}
533        fn assert_chunk<C: model::TraceChunkMut>() {}
534        fn assert_iter<A: model::AttributesIter>() {}
535
536        assert_span::<Span>();
537        assert_chunk::<Trace>();
538        assert_iter::<SpanEvent>();
539        assert_iter::<SpanLink>();
540    }
541
542    #[test]
543    fn span_kind_maps_otel_kinds_and_unsets_unknown_values() {
544        let kinds = [
545            (0, None),
546            (1, Some("internal")),
547            (2, Some("server")),
548            (3, Some("client")),
549            (4, Some("producer")),
550            (5, Some("consumer")),
551        ];
552        for (kind, expected) in kinds {
553            let span = Span::default().with_kind(kind);
554            assert_eq!(span.span_kind(), expected, "kind {kind}");
555        }
556
557        let mut span = Span::default();
558        model::SpanMut::set_span_kind(&mut span, "internal");
559        assert_eq!(span.kind, 1);
560        model::SpanMut::set_span_kind(&mut span, "not-a-kind");
561        assert_eq!(span.kind, 0, "an unrecognized kind unsets it");
562    }
563
564    #[test]
565    fn trait_time_fields_handle_values_outside_the_signed_range() {
566        let mut span = Span::default().with_start(u64::MAX).with_duration(u64::MAX);
567        assert_eq!(
568            (model::Span::start(&span), model::Span::duration(&span)),
569            (i64::MAX, -1)
570        );
571
572        model::SpanMut::set_start(&mut span, -1);
573        model::SpanMut::set_duration(&mut span, -1);
574        assert_eq!((model::Span::start(&span), model::Span::duration(&span)), (0, 0));
575    }
576
577    #[test]
578    fn promoted_fields_read_as_unset_when_empty() {
579        let span = Span::default();
580        assert_eq!((span.env(), span.version(), span.component()), (None, None, None));
581
582        let span = Span::default()
583            .with_env("prod")
584            .with_version("1.2")
585            .with_component("net/http");
586        assert_eq!(
587            (span.env(), span.version(), span.component()),
588            (Some("prod"), Some("1.2"), Some("net/http"))
589        );
590    }
591
592    #[test]
593    fn promoted_tags_are_never_read_from_or_written_to_the_attribute_map() {
594        let mut span = Span::default().with_env("prod");
595        assert_eq!(span.attribute_str("env"), None, "getters only see the attribute map");
596
597        model::SpanMut::set_env(&mut span, "staging".into());
598        assert_eq!(span.env(), Some("staging"));
599        assert!(
600            span.attributes.is_empty(),
601            "setting a promoted field doesn't create an attribute"
602        );
603
604        // The compat view is what bridges the two.
605        assert_eq!(span.compat().attribute_str("env"), Some("staging"));
606    }
607
608    #[test]
609    fn map_backed_promoted_tags_use_the_dedicated_trait_view() {
610        let mut span = Span::default().with_attributes(FastHashMap::from_iter([
611            ("env".into(), string("prod")),
612            ("version".into(), string("private")),
613            ("component".into(), string("private")),
614            ("span.kind".into(), string("client")),
615        ]));
616        assert_eq!(span.env(), Some("prod"));
617        assert_eq!(span.version(), Some("private"));
618        assert_eq!(span.component(), Some("private"));
619        assert_eq!(span.span_kind(), Some("client"));
620        assert_eq!(span.attributes().count(), 0);
621        for key in model::PROMOTED_SPAN_TAGS {
622            assert!(!span.has_attribute(key));
623            assert!(span.attribute_str(key).is_none());
624            assert!(span.attribute_mut(key).is_none());
625        }
626        span.retain_attributes(|_, _| panic!("promoted tags use their own setters"));
627
628        model::SpanMut::set_component(&mut span, "redacted".into());
629        model::SpanMut::set_version(&mut span, "redacted".into());
630        model::SpanMut::set_span_kind(&mut span, "server");
631        assert_eq!(span.attributes.get("component"), Some(&string("redacted")));
632        assert_eq!(span.attributes.get("version"), Some(&string("redacted")));
633        assert_eq!(span.attributes.get("span.kind"), Some(&string("server")));
634        model::SpanMut::set_span_kind(&mut span, "redacted");
635        assert_eq!(span.span_kind(), None);
636        assert!(!span.attributes.contains_key("span.kind"));
637    }
638
639    #[test]
640    fn span_fields_round_trip_through_the_traits() {
641        let mut span = Span::new("svc", "op", "res", "web", 7, 3, 1_000, 50, 1);
642        assert_eq!(
643            (span.service(), span.name(), span.resource(), span.typ()),
644            ("svc", "op", "res", "web")
645        );
646        assert_eq!(
647            (span.span_id(), span.parent_id(), span.start(), span.duration()),
648            (7, 3, 1_000, 50)
649        );
650        assert!(span.is_error());
651        assert!(!span.is_trace_root());
652
653        model::SpanMut::set_resource(&mut span, "new".into());
654        model::SpanMut::set_type(&mut span, "sql".into());
655        model::SpanMut::set_start(&mut span, 2_000);
656        model::SpanMut::set_duration(&mut span, 75);
657        model::SpanMut::set_error(&mut span, false);
658        model::SpanMut::set_parent_id(&mut span, 0);
659        assert_eq!(
660            (span.resource(), span.typ(), span.start(), span.duration()),
661            ("new", "sql", 2_000, 75)
662        );
663        assert!(!span.is_error());
664        assert!(span.is_trace_root());
665    }
666
667    #[test]
668    fn attributes_read_write_remove_and_retain() {
669        let mut span = Span::default();
670        span.set_attribute("a".into(), string("x"));
671        span.set_attribute("n".into(), AttributeValue::Int(2));
672        span.set_attribute("f".into(), AttributeValue::Float(2.5));
673        span.set_attribute("nested".into(), AttributeValue::Array(vec![string("y")]));
674
675        assert_eq!(span.attribute_str("a"), Some("x"));
676        assert_eq!(span.attribute_str("n"), None, "a number isn't a string");
677        assert_eq!(span.attribute_f64("n"), Some(2.0));
678        assert_eq!(span.attribute_i64("n"), Some(2));
679        assert_eq!(span.attribute_i64("f"), None, "2.5 isn't exactly an integer");
680        assert!(span.has_attribute("nested"));
681        assert!(!span.has_attribute("missing"));
682
683        if let Some(AttributeValue::String(s)) = span.attribute_mut("a") {
684            *s = "changed".into();
685        }
686        assert_eq!(span.attribute_str("a"), Some("changed"));
687
688        assert_eq!(span.remove_attribute("a"), Some(string("changed")));
689        assert_eq!(span.remove_attribute("a"), None);
690
691        span.retain_attributes(|key, _| key != "n");
692        assert!(!span.has_attribute("n"));
693        assert!(span.has_attribute("f"));
694    }
695
696    #[test]
697    fn iterating_attributes_yields_each_key_once() {
698        let mut span = Span::default();
699        span.set_attribute("a".into(), string("x"));
700        span.set_attribute("b".into(), AttributeValue::Bool(true));
701        span.set_attribute("c".into(), AttributeValue::Array(vec![string("y")]));
702
703        let mut keys: Vec<_> = span.attributes().map(|(k, _)| k.to_string()).collect();
704        keys.sort();
705        assert_eq!(keys, ["a", "b", "c"]);
706    }
707
708    #[test]
709    fn key_value_lists_support_the_map_traits() {
710        let mut list: KeyValueList = Vec::new();
711        assert_eq!(ValueMapMut::insert(&mut list, "k".into(), string("v")), None);
712        assert_eq!(
713            ValueMapMut::insert(&mut list, "k".into(), string("w")),
714            Some(string("v")),
715            "insert replaces"
716        );
717        assert_eq!(list.len(), 1);
718        assert_eq!(ValueMap::get(&list, "k"), Some(&string("w")));
719        assert_eq!(ValueMapMut::remove(&mut list, "k"), Some(string("w")));
720        assert!(ValueMap::is_empty(&list));
721    }
722
723    #[test]
724    fn key_value_lists_treat_the_last_duplicate_as_the_value() {
725        let mut list = vec![
726            ("a".into(), string("first")),
727            ("b".into(), string("only")),
728            ("a".into(), string("last")),
729        ];
730
731        assert_eq!(ValueMap::get(&list, "a"), Some(&string("last")));
732        assert_eq!(ValueMap::len(&list), 2);
733        let entries: Vec<_> = ValueMap::iter(&list).map(|(k, v)| (k, v.as_str().unwrap())).collect();
734        assert_eq!(entries, [("b", "only"), ("a", "last")]);
735
736        let mut visited = Vec::new();
737        ValueMapMut::retain(&mut list, |key, _| {
738            visited.push(key.to_owned());
739            key != "b"
740        });
741        assert_eq!(visited, ["b", "a"]);
742        assert_eq!(list.len(), 1);
743        assert_eq!(ValueMapMut::remove(&mut list, "a"), Some(string("last")));
744        assert!(list.is_empty());
745    }
746
747    #[test]
748    fn span_links_combine_trace_id_halves_and_mask_the_flags_sentinel() {
749        let link = SpanLink::new(1, 9)
750            .with_trace_id_high(2)
751            .with_flags(model::SPAN_LINK_FLAGS_SET_SENTINEL | 1);
752        assert_eq!(model::SpanLink::trace_id(&link), (2u128 << 64) | 1);
753        assert_eq!(model::SpanLink::flags(&link), 1);
754    }
755
756    #[test]
757    fn trace_attributes_are_copy_on_write() {
758        let mut first = Trace::new(Vec::new(), TraceIngestInfo::Datadog);
759        first.set_attribute("k".into(), string("v"));
760        let mut second = first.clone();
761
762        second.set_attribute("k".into(), string("changed"));
763        assert_eq!(
764            first.attribute_str("k"),
765            Some("v"),
766            "the clone's write must not reach the original"
767        );
768        assert_eq!(second.attribute_str("k"), Some("changed"));
769    }
770
771    #[test]
772    fn trace_chunk_fields_and_span_retention() {
773        let spans = vec![
774            Span::default().with_resource("keep"),
775            Span::default().with_resource("drop"),
776        ];
777        let mut trace = Trace::new(spans, TraceIngestInfo::Datadog);
778        trace.trace_id_high = 1;
779        trace.trace_id_low = 2;
780
781        assert_eq!(model::TraceChunk::trace_id(&trace), (1u128 << 64) | 2);
782        assert_eq!(model::TraceChunk::priority(&trace), None);
783        assert_eq!(
784            model::TraceChunk::sampling_mechanism(&trace),
785            None,
786            "0 means no mechanism"
787        );
788
789        model::TraceChunkMut::set_priority(&mut trace, 2);
790        model::TraceChunkMut::set_sampling_mechanism(&mut trace, 4);
791        model::TraceChunkMut::set_origin(&mut trace, "lambda".into());
792        model::TraceChunkMut::set_dropped_trace(&mut trace, true);
793        assert_eq!(
794            (
795                model::TraceChunk::priority(&trace),
796                model::TraceChunk::sampling_mechanism(&trace),
797                model::TraceChunk::origin(&trace)
798            ),
799            (Some(2), Some(4), "lambda")
800        );
801        assert!(model::TraceChunk::dropped_trace(&trace));
802
803        model::TraceChunkMut::retain_spans(&mut trace, |span| model::Span::resource(span) == "keep");
804        assert_eq!(trace.spans().len(), 1);
805    }
806}