Skip to main content

saluki_components/sources/dogstatsd/replay/
replay_api.rs

1//! HTTP API handler for DogStatsD replay sessions.
2//!
3//! A replay client starts a session before sending replay packets and finishes the same session when replay ends. The
4//! ADP process keeps the captured tagger snapshot only for the active session.
5
6use axum::body::Bytes;
7use datadog_protos::agent::TaggerState;
8use prost::Message as _;
9use saluki_api::{
10    extract::{Path, State},
11    routing::{delete, post, Router},
12    APIHandler, Json, StatusCode,
13};
14use serde::{Deserialize, Serialize};
15
16use super::{DogStatsDReplayControl, ReplayControlError};
17
18/// Route for starting a replay session (`POST`). Append `/{session_id}` to finish it (`DELETE`).
19pub const REPLAY_SESSION_ROUTE: &str = "/dogstatsd/replay/session";
20
21/// API handler for the DogStatsD replay session control surface.
22#[derive(Clone)]
23pub struct DogStatsDReplayAPIHandler {
24    replay_control: DogStatsDReplayControl,
25}
26
27impl DogStatsDReplayAPIHandler {
28    /// Creates a new handler bound to the given replay control.
29    pub fn new(replay_control: DogStatsDReplayControl) -> Self {
30        Self { replay_control }
31    }
32
33    async fn start_session_handler(
34        State(replay_control): State<DogStatsDReplayControl>, body: Bytes,
35    ) -> Result<Json<ReplaySessionResponseBody>, (StatusCode, String)> {
36        let state = if body.is_empty() {
37            None
38        } else {
39            Some(
40                TaggerState::decode(body)
41                    .map_err(|e| (StatusCode::BAD_REQUEST, format!("Invalid tagger state: {}", e)))?,
42            )
43        };
44
45        let session = replay_control.start_session(state).map_err(map_replay_control_error)?;
46
47        Ok(Json(ReplaySessionResponseBody { session_id: session.id }))
48    }
49
50    async fn finish_session_handler(
51        State(replay_control): State<DogStatsDReplayControl>, Path(session_id): Path<String>,
52    ) -> Result<StatusCode, (StatusCode, String)> {
53        replay_control
54            .finish_session(&session_id)
55            .map_err(map_replay_control_error)?;
56
57        Ok(StatusCode::NO_CONTENT)
58    }
59}
60
61/// Response body for `POST /dogstatsd/replay/session`.
62#[derive(Debug, Deserialize, Serialize)]
63pub struct ReplaySessionResponseBody {
64    /// Opaque session identifier the replay client must use when finishing the replay.
65    pub session_id: String,
66}
67
68fn map_replay_control_error(err: ReplayControlError) -> (StatusCode, String) {
69    let status = match err {
70        ReplayControlError::Unavailable => StatusCode::PRECONDITION_FAILED,
71        ReplayControlError::AlreadyInProgress | ReplayControlError::NotOwner { .. } => StatusCode::CONFLICT,
72    };
73    (status, err.to_string())
74}
75
76impl APIHandler for DogStatsDReplayAPIHandler {
77    type State = DogStatsDReplayControl;
78
79    fn generate_initial_state(&self) -> Self::State {
80        self.replay_control.clone()
81    }
82
83    fn generate_routes(&self) -> Router<Self::State> {
84        Router::new()
85            .route(REPLAY_SESSION_ROUTE, post(Self::start_session_handler))
86            .route(
87                &format!("{REPLAY_SESSION_ROUTE}/{{session_id}}"),
88                delete(Self::finish_session_handler),
89            )
90    }
91}
92
93#[cfg(test)]
94mod tests {
95    use std::collections::HashMap;
96
97    use datadog_protos::agent::{Entity as ProtoEntity, TaggerState};
98    use prost::Message as _;
99    use saluki_core::data_model::origin::OriginTagCardinality;
100
101    use super::*;
102    use crate::sources::dogstatsd::replay::CapturedTaggerHandle;
103
104    fn make_state() -> TaggerState {
105        let entity = ProtoEntity {
106            low_cardinality_tags: vec!["env:prod".into()],
107            ..Default::default()
108        };
109
110        let mut entities = HashMap::new();
111        entities.insert("container_id://container-xyz".to_string(), entity);
112
113        let mut pid_map = HashMap::new();
114        pid_map.insert(99, "container_id://container-xyz".to_string());
115
116        TaggerState {
117            state: entities,
118            pid_map,
119            duration: 0,
120        }
121    }
122
123    #[tokio::test]
124    async fn start_session_rejects_invalid_protobuf() {
125        let control = DogStatsDReplayControl::new();
126        let err = DogStatsDReplayAPIHandler::start_session_handler(State(control), Bytes::from_static(b"bad"))
127            .await
128            .expect_err("invalid protobuf should fail");
129
130        assert_eq!(err.0, StatusCode::BAD_REQUEST);
131        assert!(
132            err.1.starts_with("Invalid tagger state: "),
133            "unexpected body: {}",
134            err.1
135        );
136    }
137
138    #[tokio::test]
139    async fn unbound_control_is_precondition_failed() {
140        let control = DogStatsDReplayControl::new();
141        let expected_message = "DogStatsD replay control is unavailable because the source is not running.";
142
143        let err = DogStatsDReplayAPIHandler::start_session_handler(State(control.clone()), Bytes::new())
144            .await
145            .expect_err("unbound start should fail");
146        assert_eq!(err, (StatusCode::PRECONDITION_FAILED, expected_message.to_string()));
147
148        let err = DogStatsDReplayAPIHandler::finish_session_handler(State(control), Path("any".to_string()))
149            .await
150            .expect_err("unbound finish should fail");
151        assert_eq!(err, (StatusCode::PRECONDITION_FAILED, expected_message.to_string()));
152    }
153
154    #[tokio::test]
155    async fn start_and_finish_session_update_control() {
156        let captured_tagger = CapturedTaggerHandle::new();
157        let control = DogStatsDReplayControl::new();
158        control.bind(captured_tagger.clone());
159
160        let body = Bytes::from(make_state().encode_to_vec());
161        let Json(session) = DogStatsDReplayAPIHandler::start_session_handler(State(control.clone()), body)
162            .await
163            .expect("session should start");
164        assert!(!session.session_id.is_empty());
165
166        let store = captured_tagger.current().expect("state should be set");
167        assert!(store.lookup(99, OriginTagCardinality::Low).is_some());
168
169        let finish_status = DogStatsDReplayAPIHandler::finish_session_handler(State(control), Path(session.session_id))
170            .await
171            .expect("finish should succeed");
172        assert_eq!(finish_status, StatusCode::NO_CONTENT);
173        assert!(captured_tagger.current().is_none());
174    }
175
176    #[tokio::test]
177    async fn start_session_rejects_concurrent_session() {
178        let captured_tagger = CapturedTaggerHandle::new();
179        let control = DogStatsDReplayControl::new();
180        control.bind(captured_tagger);
181
182        let body = Bytes::from(make_state().encode_to_vec());
183        let _ = DogStatsDReplayAPIHandler::start_session_handler(State(control.clone()), body)
184            .await
185            .expect("first session should start");
186
187        let err =
188            DogStatsDReplayAPIHandler::start_session_handler(State(control), Bytes::from(make_state().encode_to_vec()))
189                .await
190                .expect_err("second session should fail");
191        assert_eq!(
192            err,
193            (
194                StatusCode::CONFLICT,
195                "DogStatsD replay already in progress.".to_string()
196            )
197        );
198    }
199
200    #[tokio::test]
201    async fn finish_session_rejects_non_owner() {
202        let captured_tagger = CapturedTaggerHandle::new();
203        let control = DogStatsDReplayControl::new();
204        control.bind(captured_tagger.clone());
205
206        let body = Bytes::from(make_state().encode_to_vec());
207        let Json(session) = DogStatsDReplayAPIHandler::start_session_handler(State(control.clone()), body)
208            .await
209            .expect("session should start");
210
211        let err = DogStatsDReplayAPIHandler::finish_session_handler(State(control.clone()), Path("wrong".to_string()))
212            .await
213            .expect_err("non-owner should fail");
214        let expected_message = format!(
215            "DogStatsD replay session 'wrong' does not own active replay session '{}'.",
216            session.session_id
217        );
218        assert_eq!(err, (StatusCode::CONFLICT, expected_message));
219        assert!(captured_tagger.current().is_some());
220
221        DogStatsDReplayAPIHandler::finish_session_handler(State(control), Path(session.session_id))
222            .await
223            .expect("owner should finish");
224        assert!(captured_tagger.current().is_none());
225    }
226}