Skip to main content

saluki_components/sources/dogstatsd/replay/
replay_control.rs

1//! Replay session control surface for the DogStatsD source.
2//!
3//! The ADP process owns only the active replay session and its captured tagger snapshot. A separate replay client is
4//! responsible for reading capture files and sending replay packets into the DogStatsD UDS listener.
5
6use std::sync::{Arc, Mutex};
7
8use datadog_protos::agent::TaggerState;
9use rand::RngExt as _;
10use snafu::Snafu;
11
12use super::{CapturedTaggerHandle, CapturedTaggerStore};
13
14/// Error returned by [`DogStatsDReplayControl`] operations.
15#[derive(Debug, Eq, PartialEq, Snafu)]
16pub enum ReplayControlError {
17    /// The DogStatsD source hasn't been built and bound to the control handle yet.
18    #[snafu(display("DogStatsD replay control is unavailable because the source is not running."))]
19    Unavailable,
20
21    /// Another replay session is already active.
22    #[snafu(display("DogStatsD replay already in progress."))]
23    AlreadyInProgress,
24
25    /// The given session doesn't own the active replay session.
26    #[snafu(display(
27        "DogStatsD replay session '{}' does not own active replay session '{}'.",
28        session_id,
29        active_session_id
30    ))]
31    NotOwner {
32        /// Session that tried to finish the replay.
33        session_id: String,
34
35        /// Session that owns the active replay.
36        active_session_id: String,
37    },
38}
39
40/// Default number of times to replay a capture file when the CLI omits an explicit count.
41pub const DEFAULT_REPLAY_LOOPS: u32 = 1;
42
43/// Active DogStatsD replay session.
44#[derive(Clone, Debug, Eq, PartialEq)]
45pub struct ReplaySession {
46    /// Opaque identifier the replay client must use to finish the session.
47    pub id: String,
48}
49
50/// Shared control handle for DogStatsD replay sessions.
51///
52/// Created before the source is built and bound to the live captured tagger handle during source construction. The
53/// HTTP API handler holds a clone of this handle so a replay client can acquire and release the single active session.
54#[derive(Clone, Default)]
55pub struct DogStatsDReplayControl {
56    inner: Arc<Mutex<ReplayControlState>>,
57}
58
59#[derive(Default)]
60struct ReplayControlState {
61    captured_tagger: Option<CapturedTaggerHandle>,
62    active_session_id: Option<String>,
63}
64
65impl DogStatsDReplayControl {
66    /// Creates a new, unbound replay control handle.
67    pub fn new() -> Self {
68        Self::default()
69    }
70
71    /// Binds the control handle to the captured tagger store used by the running DogStatsD source.
72    pub(crate) fn bind(&self, captured_tagger: CapturedTaggerHandle) {
73        let mut state = self.inner.lock().expect("replay control mutex poisoned");
74        state.captured_tagger = Some(captured_tagger);
75    }
76
77    /// Starts a replay session and sets the captured tagger state for replay-origin resolution.
78    ///
79    /// # Errors
80    ///
81    /// Returns an error if the DogStatsD source hasn't been built and bound to this control handle yet, or if another
82    /// replay session is already active.
83    pub fn start_session(&self, tagger_state: Option<TaggerState>) -> Result<ReplaySession, ReplayControlError> {
84        let mut state = self.inner.lock().expect("replay control mutex poisoned");
85        let captured_tagger = state.captured_tagger.clone().ok_or(ReplayControlError::Unavailable)?;
86
87        if state.active_session_id.is_some() {
88            return Err(ReplayControlError::AlreadyInProgress);
89        }
90
91        let session = ReplaySession {
92            id: new_replay_session_id(),
93        };
94
95        let captured_store = tagger_state.map(CapturedTaggerStore::from_tagger_state);
96        captured_tagger.set_current(captured_store);
97        state.active_session_id = Some(session.id.clone());
98
99        Ok(session)
100    }
101
102    /// Finishes a replay session and removes the captured tagger state it owns.
103    ///
104    /// # Errors
105    ///
106    /// Returns an error if the DogStatsD source hasn't been built and bound to this control handle yet, or if the given
107    /// session does not own the active replay.
108    pub fn finish_session(&self, session_id: &str) -> Result<(), ReplayControlError> {
109        let mut state = self.inner.lock().expect("replay control mutex poisoned");
110        let captured_tagger = state.captured_tagger.clone().ok_or(ReplayControlError::Unavailable)?;
111
112        match state.active_session_id.as_deref() {
113            Some(active_session_id) if active_session_id == session_id => {
114                captured_tagger.set_current(None);
115                state.active_session_id = None;
116                Ok(())
117            }
118            Some(active_session_id) => Err(ReplayControlError::NotOwner {
119                session_id: session_id.to_string(),
120                active_session_id: active_session_id.to_string(),
121            }),
122            None => Ok(()),
123        }
124    }
125}
126
127fn new_replay_session_id() -> String {
128    format!("{:032x}", rand::rng().random::<u128>())
129}
130
131#[cfg(test)]
132mod tests {
133    use std::collections::HashMap;
134
135    use datadog_protos::agent::{Entity as ProtoEntity, TaggerState};
136    use saluki_core::data_model::origin::OriginTagCardinality;
137
138    use super::*;
139
140    fn make_state() -> TaggerState {
141        let entity = ProtoEntity {
142            low_cardinality_tags: vec!["env:prod".into()],
143            ..Default::default()
144        };
145
146        let mut entities = HashMap::new();
147        entities.insert("container_id://container-xyz".to_string(), entity);
148
149        let mut pid_map = HashMap::new();
150        pid_map.insert(99, "container_id://container-xyz".to_string());
151
152        TaggerState {
153            state: entities,
154            pid_map,
155            duration: 0,
156        }
157    }
158
159    #[test]
160    fn control_requires_bound_store() {
161        let control = DogStatsDReplayControl::new();
162        let err = control
163            .start_session(Some(make_state()))
164            .expect_err("unbound control should fail");
165        assert_eq!(err, ReplayControlError::Unavailable);
166        assert_eq!(
167            err.to_string(),
168            "DogStatsD replay control is unavailable because the source is not running."
169        );
170
171        let err = control.finish_session("any").expect_err("unbound control should fail");
172        assert_eq!(err, ReplayControlError::Unavailable);
173    }
174
175    #[test]
176    fn session_start_and_finish_update_bound_store() {
177        let captured_tagger = CapturedTaggerHandle::new();
178        let control = DogStatsDReplayControl::new();
179        control.bind(captured_tagger.clone());
180
181        let session = control.start_session(Some(make_state())).expect("session should start");
182        let store = captured_tagger.current().expect("state should be set");
183        assert!(store.lookup(99, OriginTagCardinality::Low).is_some());
184
185        control
186            .finish_session(&session.id)
187            .expect("matching session should finish");
188        assert!(captured_tagger.current().is_none());
189    }
190
191    #[test]
192    fn session_rejects_concurrent_start() {
193        let captured_tagger = CapturedTaggerHandle::new();
194        let control = DogStatsDReplayControl::new();
195        control.bind(captured_tagger);
196
197        let _session = control
198            .start_session(Some(make_state()))
199            .expect("first session should start");
200        let err = control
201            .start_session(Some(make_state()))
202            .expect_err("second session should fail");
203        assert_eq!(err, ReplayControlError::AlreadyInProgress);
204        assert_eq!(err.to_string(), "DogStatsD replay already in progress.");
205    }
206
207    #[test]
208    fn finish_session_rejects_non_owner() {
209        let captured_tagger = CapturedTaggerHandle::new();
210        let control = DogStatsDReplayControl::new();
211        control.bind(captured_tagger.clone());
212
213        let session = control.start_session(Some(make_state())).expect("session should start");
214        let err = control
215            .finish_session("wrong-session")
216            .expect_err("non-owner should fail");
217        assert_eq!(
218            err,
219            ReplayControlError::NotOwner {
220                session_id: "wrong-session".to_string(),
221                active_session_id: session.id.clone(),
222            }
223        );
224        assert_eq!(
225            err.to_string(),
226            format!(
227                "DogStatsD replay session 'wrong-session' does not own active replay session '{}'.",
228                session.id
229            )
230        );
231
232        assert!(captured_tagger.current().is_some());
233        control
234            .finish_session(&session.id)
235            .expect("matching session should finish");
236        assert!(captured_tagger.current().is_none());
237    }
238}