Skip to main content

libdd_common/
mutable_metadata.rs

1// Copyright 2026-Present Datadog, Inc. https://www.datadoghq.com/
2// SPDX-License-Identifier: Apache-2.0
3
4//! Runtime metadata that the host tracer may update after startup.
5//!
6//! Runtime identity, instrumentation session ancestry, and process tags may change
7//! while exporters and workers are already running. They live in a single
8//! [`MutableMetadata`] struct shared through an [`ArcSwap`]; every component holds a
9//! [`MutableMetadataHandle`] and reads the values through it at use time, so an update
10//! by the host SDK propagates to all components.
11//!
12//! # Protocol
13//!
14//! - **Writers** (the host SDK via FFI, or the library itself) call
15//!   [`MutableMetadataHandle::set_runtime_id`] / [`MutableMetadataHandle::set_process_tags`] /
16//!   [`MutableMetadataHandle::update`] to modify the current snapshot.
17//! - **Readers** call [`MutableMetadataHandle::load`] at the point of use, which returns a
18//!   lock-free snapshot. The snapshot is consistent for a single read only; values are **not**
19//!   consistent across multiple `load()` calls.
20
21use alloc::sync::Arc;
22
23use arc_swap::ArcSwap;
24
25/// The tracer metadata values that may be updated after startup.
26///
27/// Both fields use the same formats as the rest of the tracing stack:
28/// - `runtime_id`: a runtime UUID,
29/// - `process_tags`: comma-separated `key:value` pairs, e.g. `"k1:v1,k2:v2"`.
30#[derive(Clone, Default, Debug, PartialEq, Eq)]
31#[non_exhaustive]
32pub struct MutableMetadata {
33    /// Runtime UUID. Uniquely identifies the runtime within the host process.
34    pub runtime_id: String,
35    /// Comma-separated `key:value` process tags of the instrumented application.
36    pub process_tags: String,
37    /// Instrumentation session headers. `None` uses the worker's static configuration.
38    pub session: Option<InstrumentationSession>,
39}
40
41/// Instrumentation session ancestry, published together with the runtime ID.
42#[derive(Clone, Default, Debug, PartialEq, Eq)]
43pub struct InstrumentationSession {
44    pub id: String,
45    pub root_id: String,
46    pub parent_id: String,
47}
48
49/// A shared handle to a [`MutableMetadata`].
50///
51/// This is a cheap-to-clone `Arc<ArcSwap<MutableMetadata>>`: all clones observe the same
52/// underlying value. See the
53/// [module documentation](self) for the write/read protocol.
54#[derive(Clone, Default, Debug)]
55pub struct MutableMetadataHandle(Arc<ArcSwap<MutableMetadata>>);
56
57impl MutableMetadataHandle {
58    /// Publish a coherent runtime and session identity, preserving process tags.
59    ///
60    /// After a fork, call while workers are paused, before the child runtime restarts.
61    /// This does not discard pending observations or reset worker sequence counters.
62    pub fn set_identity(&self, runtime_id: String, session: InstrumentationSession) {
63        self.update(|mut metadata| {
64            metadata.runtime_id = runtime_id.clone();
65            metadata.session = Some(session.clone());
66            metadata
67        });
68    }
69
70    /// Load the value of the handle
71    pub fn load(&self) -> arc_swap::Guard<Arc<MutableMetadata>> {
72        self.0.load()
73    }
74
75    /// Load the value of the handle, cloned into an owning [`Arc`].
76    pub fn load_full(&self) -> Arc<MutableMetadata> {
77        self.0.load_full()
78    }
79
80    /// Set the runtime_id value
81    pub fn set_runtime_id(&self, runtime_id: String) {
82        self.update(|mut metadata| {
83            metadata.runtime_id = runtime_id.clone();
84            metadata
85        });
86    }
87
88    /// Set the process tags value
89    pub fn set_process_tags(&self, process_tags: String) {
90        self.update(|mut metadata| {
91            metadata.process_tags = process_tags.clone();
92            metadata
93        });
94    }
95
96    /// Update the handle value with the result of `f`.
97    ///
98    /// Use this method to update multiple fields at once. Modify the supplied snapshot
99    /// rather than replacing it with a previously loaded value. The closure may run
100    /// more than once when another writer updates the handle concurrently.
101    pub fn update<F>(&self, mut f: F)
102    where
103        F: FnMut(MutableMetadata) -> MutableMetadata,
104    {
105        self.0.rcu(|current| {
106            let next = (**current).clone();
107            f(next)
108        });
109    }
110}
111
112impl From<MutableMetadata> for MutableMetadataHandle {
113    fn from(value: MutableMetadata) -> Self {
114        MutableMetadataHandle(Arc::new(ArcSwap::from_pointee(value)))
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    fn initial_handle() -> MutableMetadataHandle {
123        let handle = MutableMetadataHandle::default();
124        handle.set_runtime_id("rt-1".into());
125        handle.set_process_tags("k1:v1".into());
126        handle
127    }
128
129    #[test]
130    fn handle_propagates_updates_to_all_clones() {
131        let handle = initial_handle();
132        let clone = handle.clone();
133
134        // Readers see the initial values through both clones.
135        let snapshot = handle.load();
136        assert_eq!(snapshot.runtime_id, "rt-1");
137        assert_eq!(snapshot.process_tags, "k1:v1");
138        drop(snapshot);
139
140        // Updating through one clone propagates to the other.
141        clone.update(|mut metadata| {
142            metadata.runtime_id = "rt-2".into();
143            metadata.process_tags = "k2:v2".into();
144            metadata
145        });
146        let snapshot = handle.load();
147        assert_eq!(snapshot.runtime_id, "rt-2");
148        assert_eq!(snapshot.process_tags, "k2:v2");
149    }
150
151    #[test]
152    fn field_updates_keep_the_other_field() {
153        let handle = initial_handle();
154
155        handle.set_runtime_id("rt-2".into());
156        let snapshot = handle.load();
157        assert_eq!(snapshot.runtime_id, "rt-2");
158        assert_eq!(snapshot.process_tags, "k1:v1");
159        drop(snapshot);
160
161        handle.set_process_tags("k2:v2".into());
162        let snapshot = handle.load();
163        assert_eq!(snapshot.runtime_id, "rt-2");
164        assert_eq!(snapshot.process_tags, "k2:v2");
165    }
166
167    #[test]
168    fn default_handle_yields_empty_values() {
169        let handle = MutableMetadataHandle::default();
170        let snapshot = handle.load();
171        assert!(snapshot.runtime_id.is_empty());
172        assert!(snapshot.process_tags.is_empty());
173    }
174
175    #[test]
176    fn update_modifies_the_current_snapshot() {
177        let handle = initial_handle();
178
179        handle.update(|mut m| {
180            m.runtime_id = "rt-2".into();
181            m
182        });
183        let snapshot = handle.load();
184        assert_eq!(snapshot.runtime_id, "rt-2");
185        assert_eq!(snapshot.process_tags, "k1:v1");
186    }
187
188    #[test]
189    fn update_retries_without_losing_concurrent_changes() {
190        use core::sync::atomic::{AtomicBool, Ordering};
191        use std::sync::Barrier;
192
193        let handle = initial_handle();
194        let snapshot_loaded = Barrier::new(2);
195        let concurrent_update_done = Barrier::new(2);
196        let first_attempt = AtomicBool::new(true);
197
198        std::thread::scope(|scope| {
199            let writer = scope.spawn(|| {
200                handle.update(|mut metadata| {
201                    if first_attempt.swap(false, Ordering::SeqCst) {
202                        snapshot_loaded.wait();
203                        concurrent_update_done.wait();
204                    }
205                    metadata.runtime_id = "rt-2".into();
206                    metadata
207                });
208            });
209            snapshot_loaded.wait();
210            handle.set_process_tags("k2:v2".into());
211            concurrent_update_done.wait();
212            writer.join().unwrap();
213        });
214
215        let snapshot = handle.load();
216        assert_eq!(snapshot.runtime_id, "rt-2");
217        assert_eq!(snapshot.process_tags, "k2:v2");
218    }
219
220    #[test]
221    fn load_full_returns_an_owning_arc() {
222        let handle = initial_handle();
223        let snapshot = handle.load_full();
224        assert_eq!(snapshot.runtime_id, "rt-1");
225        assert_eq!(snapshot.process_tags, "k1:v1");
226    }
227
228    #[test]
229    fn identity_is_published_as_one_snapshot() {
230        let handle = initial_handle();
231        let parent = handle.load_full();
232        let clone = handle.clone();
233        let session = InstrumentationSession {
234            id: "child".into(),
235            root_id: "root".into(),
236            parent_id: "parent".into(),
237        };
238        handle.set_identity("child".into(), session.clone());
239        let child = clone.load();
240        assert_eq!(child.runtime_id, "child");
241        assert_eq!(child.session, Some(session));
242        assert_eq!(child.process_tags, "k1:v1");
243        assert_eq!(parent.runtime_id, "rt-1");
244        assert_eq!(parent.session, None);
245    }
246}