saluki_components/sources/dogstatsd/replay/
capture_api.rs1use std::path::Path;
6
7use saluki_api::{
8 extract::State,
9 routing::{post, Router},
10 APIHandler, Json, StatusCode,
11};
12use saluki_config::parse_duration;
13use serde::{Deserialize, Serialize};
14
15use super::DogStatsDCaptureControl;
16
17pub const CAPTURE_TRIGGER_ROUTE: &str = "/dogstatsd/capture/trigger";
19
20#[derive(Deserialize, Serialize)]
22pub struct CaptureTriggerBody {
23 pub duration: String,
25
26 #[serde(default, skip_serializing_if = "Option::is_none")]
29 pub path: Option<String>,
30
31 #[serde(default)]
33 pub compressed: bool,
34}
35
36#[derive(Deserialize, Serialize)]
38pub struct CaptureTriggerResponseBody {
39 pub path: String,
41}
42
43#[derive(Clone)]
45pub struct DogStatsDCaptureAPIHandler {
46 capture_control: DogStatsDCaptureControl,
47}
48
49impl DogStatsDCaptureAPIHandler {
50 pub fn new(capture_control: DogStatsDCaptureControl) -> Self {
52 Self { capture_control }
53 }
54
55 async fn trigger_handler(
56 State(capture_control): State<DogStatsDCaptureControl>, Json(body): Json<CaptureTriggerBody>,
57 ) -> Result<Json<CaptureTriggerResponseBody>, (StatusCode, String)> {
58 let duration = parse_duration(&body.duration).map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;
59 let requested_dir = body.path.as_deref().map(Path::new);
60
61 let capture_path = capture_control
62 .start_capture(requested_dir, duration, body.compressed)
63 .map_err(|e| (StatusCode::PRECONDITION_FAILED, e.to_string()))?;
64
65 Ok(Json(CaptureTriggerResponseBody {
66 path: capture_path.display().to_string(),
67 }))
68 }
69}
70
71impl APIHandler for DogStatsDCaptureAPIHandler {
72 type State = DogStatsDCaptureControl;
73
74 fn generate_initial_state(&self) -> Self::State {
75 self.capture_control.clone()
76 }
77
78 fn generate_routes(&self) -> Router<Self::State> {
79 Router::new().route(CAPTURE_TRIGGER_ROUTE, post(Self::trigger_handler))
80 }
81}
82
83#[cfg(test)]
84mod tests {
85 use super::super::test_support::{temp_dir, wait_until_inactive};
86 use super::*;
87 use crate::sources::dogstatsd::replay::TrafficCapture;
88
89 fn trigger_body(duration: &str) -> CaptureTriggerBody {
90 CaptureTriggerBody {
91 duration: duration.to_string(),
92 path: None,
93 compressed: false,
94 }
95 }
96
97 #[tokio::test]
98 async fn trigger_rejects_unbound_control() {
99 let control = DogStatsDCaptureControl::new();
102
103 let err = DogStatsDCaptureAPIHandler::trigger_handler(State(control), Json(trigger_body("50ms")))
104 .await
105 .err()
106 .expect("unbound control should fail");
107
108 assert_eq!(err.0, StatusCode::PRECONDITION_FAILED);
109 }
110
111 #[tokio::test]
112 async fn trigger_rejects_invalid_duration() {
113 let control = DogStatsDCaptureControl::new();
115 let target_dir = temp_dir();
116 control.bind(TrafficCapture::new(target_dir.path().to_path_buf(), 1));
117
118 let err = DogStatsDCaptureAPIHandler::trigger_handler(State(control), Json(trigger_body("not-a-duration")))
119 .await
120 .err()
121 .expect("invalid duration should fail");
122
123 assert_eq!(err.0, StatusCode::BAD_REQUEST);
124 }
125
126 #[tokio::test]
127 async fn trigger_starts_capture_and_returns_path() {
128 let target_dir = temp_dir();
129 let control = DogStatsDCaptureControl::new();
130 control.bind(TrafficCapture::new(target_dir.path().to_path_buf(), 1));
131
132 let Json(response) =
133 DogStatsDCaptureAPIHandler::trigger_handler(State(control.clone()), Json(trigger_body("100ms")))
134 .await
135 .expect("capture should start");
136 assert!(
137 response
138 .path
139 .starts_with(target_dir.path().to_str().expect("path should be utf-8")),
140 "returned path {:?} should be inside the configured directory {:?}",
141 response.path,
142 target_dir.path()
143 );
144 assert!(response.path.contains("datadog-capture"));
145 assert!(control.is_ongoing().expect("control should be bound"));
146
147 wait_until_inactive(|| control.is_ongoing().expect("control should be bound"));
148 }
149
150 #[tokio::test]
151 async fn trigger_rejects_concurrent_capture() {
152 let target_dir = temp_dir();
153 let control = DogStatsDCaptureControl::new();
154 control.bind(TrafficCapture::new(target_dir.path().to_path_buf(), 1));
155
156 let _ = DogStatsDCaptureAPIHandler::trigger_handler(State(control.clone()), Json(trigger_body("1s")))
157 .await
158 .expect("first capture should start");
159
160 let err = DogStatsDCaptureAPIHandler::trigger_handler(State(control.clone()), Json(trigger_body("1s")))
161 .await
162 .err()
163 .expect("second concurrent capture should fail");
164 assert_eq!(err.0, StatusCode::PRECONDITION_FAILED);
165 assert!(
166 err.1.contains("capture already in progress"),
167 "unexpected error: {}",
168 err.1
169 );
170
171 control.stop_capture().expect("stop should succeed");
172 wait_until_inactive(|| control.is_ongoing().expect("control should be bound"));
173 }
174
175 #[test]
176 fn trigger_body_wire_format_omits_absent_path() {
177 let mut body = trigger_body("10s");
178 assert_eq!(
179 serde_json::to_string(&body).expect("body should serialize"),
180 r#"{"duration":"10s","compressed":false}"#
181 );
182
183 body.path = Some("/tmp/capture".to_string());
184 body.compressed = true;
185 let json = serde_json::to_string(&body).expect("body should serialize");
186 assert_eq!(json, r#"{"duration":"10s","path":"/tmp/capture","compressed":true}"#);
187
188 let decoded: CaptureTriggerBody = serde_json::from_str(&json).expect("body should deserialize");
189 assert_eq!(decoded.path.as_deref(), Some("/tmp/capture"));
190 assert!(decoded.compressed);
191 }
192}