1use std::collections::HashMap;
2use std::sync::Arc;
3
4use async_trait::async_trait;
5use saluki_api::{
6 extract::{Query, State},
7 routing::{get, Router},
8 APIHandler, StatusCode,
9};
10use saluki_common::time::get_coarse_unix_timestamp;
11use saluki_core::{
12 accounting::{MemoryBounds, MemoryBoundsBuilder},
13 components::{
14 destinations::{Destination, DestinationBuilder, DestinationContext},
15 BuildContext,
16 },
17 data_model::{
18 event::{metric::Metric, EventType},
19 tags::TagSet,
20 },
21};
22use saluki_error::GenericError;
23use serde::{Deserialize, Serialize, Serializer};
24use serde_json;
25use stringtheory::MetaString;
26use tokio::time::{sleep, Duration, Instant};
27use tokio::{
28 pin,
29 sync::{Mutex, OwnedMutexGuard},
30};
31use tokio::{
32 select,
33 sync::{mpsc, oneshot, watch},
34};
35
36type StatsRequestReceiver = mpsc::Receiver<(oneshot::Sender<StatsResponse>, u64)>;
37
38#[derive(Debug, Default, Clone, Serialize)]
39pub struct MetricSample {
40 count: u64,
41 last_seen: u64,
42}
43#[derive(Serialize)]
44enum StatsResponse {
45 AlreadyRunning {
47 try_after: u64,
49 },
50
51 Statistics(CollectedStatistics),
52}
53
54#[derive(Serialize)]
55struct CollectedStatistics {
56 start_time_unix: u64,
58
59 end_time_unix: u64,
61
62 stats: FlattenedStats,
64}
65
66#[derive(Serialize)]
67struct FlattenedMetricStat<'a> {
68 #[serde(flatten)]
69 context: &'a ContextNoOrigin,
70
71 #[serde(flatten)]
72 stats: &'a MetricSample,
73}
74
75struct FlattenedStats(HashMap<ContextNoOrigin, MetricSample>);
76
77impl Serialize for FlattenedStats {
78 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
79 where
80 S: Serializer,
81 {
82 serializer.collect_seq(
83 self.0
84 .iter()
85 .map(|(context, stats)| FlattenedMetricStat { context, stats }),
86 )
87 }
88}
89
90#[derive(Clone)]
92pub struct DogStatsDStatisticsConfiguration {
93 api_handler: DogStatsDStatsAPIHandler,
94 rx: Arc<Mutex<StatsRequestReceiver>>,
95 collection_active: Arc<watch::Sender<bool>>,
96}
97#[derive(Clone)]
99pub struct DogStatsDStatsAPIHandlerState {
100 tx: Arc<mpsc::Sender<(oneshot::Sender<StatsResponse>, u64)>>,
101}
102
103#[derive(Clone)]
105pub struct DogStatsDStatsAPIHandler {
106 state: DogStatsDStatsAPIHandlerState,
107}
108
109pub struct DogStatsDStats {
111 rx: OwnedMutexGuard<StatsRequestReceiver>,
112 collection_active: Arc<watch::Sender<bool>>,
113}
114
115#[async_trait::async_trait]
116impl Destination for DogStatsDStats {
117 async fn run(mut self: Box<Self>, mut context: DestinationContext) -> Result<(), GenericError> {
118 let mut health = context.take_health_handle();
119 let mut collection_active = false;
120 let mut stats_response_tx: Option<tokio::sync::oneshot::Sender<StatsResponse>> = None;
121 let mut current_stats: Option<HashMap<ContextNoOrigin, MetricSample>> = None;
122 let mut stats_collection_start_time = 0;
123 let mut stats_collection_end_time: u64 = 0;
124 let collection_done = sleep(std::time::Duration::ZERO);
125 pin!(collection_done);
126
127 health.mark_ready();
128
129 loop {
130 select! {
131 _ = health.live() => {
132 continue
133 },
134 Some((response_tx, collection_period_secs)) = self.rx.recv() => {
135 if collection_active {
136 let now = get_coarse_unix_timestamp();
139 saluki_antithesis::always_or_unreachable!(
140 now >= stats_collection_start_time,
141 "dsd_stats collection clock did not move backward",
142 { "now": now, "start_time": stats_collection_start_time }
143 );
144 let try_after = stats_collection_end_time.saturating_sub(now);
145
146 let _ = response_tx.send(StatsResponse::AlreadyRunning { try_after });
148 } else {
149 self.collection_active.send_replace(true);
152 collection_active = true;
153 stats_collection_start_time = get_coarse_unix_timestamp();
154 stats_collection_end_time = stats_collection_start_time + collection_period_secs;
155 stats_response_tx = Some(response_tx);
156 current_stats = Some(HashMap::new());
157 collection_done.as_mut().reset(Instant::now() + Duration::from_secs(collection_period_secs));
158 }
159 },
160 maybe_events = context.events().next() => match maybe_events {
161 Some(events) => {
162 if let Some(stats) = current_stats.as_mut() {
163 for metric in events.into_events::<Metric>() {
165 let context = metric.context();
166 let new_context = ContextNoOrigin {
167 name: context.name().clone(),
168 tags: context.tags().clone(),
169 };
170
171 let timestamp = get_coarse_unix_timestamp();
172 let sample = stats.entry(new_context).or_default();
173 sample.count += 1;
174 sample.last_seen = timestamp;
175 }
176 }},
177 None => break,
178 },
179 _ = &mut collection_done, if collection_active => {
180 collection_active = false;
181 self.collection_active.send_replace(false);
182
183 let stats = match current_stats.take() {
185 Some(stats) => stats,
186 None => continue,
187 };
188
189 let response = StatsResponse::Statistics(CollectedStatistics {
190 start_time_unix: stats_collection_start_time,
191 end_time_unix: stats_collection_end_time,
192 stats: FlattenedStats(stats),
193 });
194
195 let response_tx = match stats_response_tx.take() {
196 Some(tx) => tx,
197 None => continue,
198 };
199
200 let _ = response_tx.send(response);
202 }
203
204 }
205 }
206 Ok(())
207 }
208}
209
210#[derive(Eq, Hash, PartialEq, Serialize)]
211struct ContextNoOrigin {
212 name: MetaString,
213 tags: TagSet,
214}
215#[derive(Deserialize)]
216struct StatsQueryParams {
217 collection_duration_secs: u64,
218}
219
220impl DogStatsDStatsAPIHandler {
221 async fn stats_handler(
222 State(state): State<DogStatsDStatsAPIHandlerState>, Query(query): Query<StatsQueryParams>,
223 ) -> (StatusCode, String) {
224 const MAXIMUM_COLLECTION_DURATION_SECS: u64 = 600;
225 if query.collection_duration_secs > MAXIMUM_COLLECTION_DURATION_SECS {
226 return (
227 StatusCode::BAD_REQUEST,
228 format!(
229 "Collection duration cannot be greater than {} seconds.",
230 MAXIMUM_COLLECTION_DURATION_SECS
231 ),
232 );
233 }
234
235 let (oneshot_tx, oneshot_rx) = oneshot::channel();
236
237 state
238 .tx
239 .send((oneshot_tx, query.collection_duration_secs))
240 .await
241 .unwrap(); match oneshot_rx.await {
244 Ok(stats) => match stats {
245 StatsResponse::Statistics(collected_stats) => match serde_json::to_string(&collected_stats) {
246 Ok(json) => (StatusCode::OK, json),
247 Err(e) => (
248 StatusCode::INTERNAL_SERVER_ERROR,
249 format!("Failed to serialize stats: {}", e),
250 ),
251 },
252 StatsResponse::AlreadyRunning { try_after } => (
253 StatusCode::TOO_MANY_REQUESTS,
254 format!(
255 "Statistics collection already active. Please try again in {} seconds.",
256 try_after
257 ),
258 ),
259 },
260 Err(_) => (
261 StatusCode::INTERNAL_SERVER_ERROR,
262 "Failed to collect statistics.".to_string(),
263 ),
264 }
265 }
266}
267
268impl APIHandler for DogStatsDStatsAPIHandler {
269 type State = DogStatsDStatsAPIHandlerState;
270
271 fn generate_initial_state(&self) -> Self::State {
272 self.state.clone()
273 }
274
275 fn generate_routes(&self) -> Router<Self::State> {
276 Router::new().route("/dogstatsd/stats", get(Self::stats_handler))
277 }
278}
279
280impl DogStatsDStatisticsConfiguration {
281 pub fn new() -> Self {
283 let (tx, rx) = mpsc::channel(4);
284 let state = DogStatsDStatsAPIHandlerState { tx: Arc::new(tx) };
285 let handler = DogStatsDStatsAPIHandler { state };
286
287 Self {
288 api_handler: handler,
289 rx: Arc::new(Mutex::new(rx)),
290 collection_active: Arc::new(watch::channel(false).0),
291 }
292 }
293
294 pub fn api_handler(&self) -> DogStatsDStatsAPIHandler {
296 self.api_handler.clone()
297 }
298
299 pub fn collection_active(&self) -> watch::Receiver<bool> {
304 self.collection_active.subscribe()
305 }
306}
307
308#[async_trait]
309impl DestinationBuilder for DogStatsDStatisticsConfiguration {
310 fn input_event_type(&self) -> EventType {
311 EventType::Metric
312 }
313
314 async fn build(&self, _context: BuildContext) -> Result<Box<dyn Destination + Send>, GenericError> {
315 let rx = self.rx.clone().try_lock_owned()?;
316 Ok(Box::new(DogStatsDStats {
317 rx,
318 collection_active: Arc::clone(&self.collection_active),
319 }))
320 }
321}
322
323impl MemoryBounds for DogStatsDStatisticsConfiguration {
324 fn specify_bounds(&self, builder: &mut MemoryBoundsBuilder) {
325 builder
326 .minimum()
327 .with_single_value::<DogStatsDStats>("component struct");
328 }
329}
330
331#[cfg(test)]
332mod tests {
333 use std::collections::BTreeSet;
334
335 use saluki_core::data_model::{event::Event, tags::Tag};
336 use serde_json::json;
337
338 use super::*;
339
340 fn tag_set<const N: usize>(tags: [&'static str; N]) -> TagSet {
341 tags.into_iter().map(Tag::from_static).collect()
342 }
343
344 #[test]
345 fn collected_statistics_serialize_as_flat_metric_entries() {
346 let mut stats = HashMap::new();
349 stats.insert(
350 ContextNoOrigin {
351 name: MetaString::from("my.counter"),
352 tags: tag_set(["env:prod", "service:web"]),
353 },
354 MetricSample {
355 count: 3,
356 last_seen: 100,
357 },
358 );
359
360 let collected = CollectedStatistics {
361 start_time_unix: 10,
362 end_time_unix: 70,
363 stats: FlattenedStats(stats),
364 };
365 let json = serde_json::to_value(&collected).expect("collected statistics should serialize");
366
367 assert_eq!(json!(10), json["start_time_unix"]);
368 assert_eq!(json!(70), json["end_time_unix"]);
369
370 let entries = json["stats"].as_array().expect("stats should serialize as an array");
371 assert_eq!(1, entries.len());
372 let entry = &entries[0];
373 assert_eq!(json!("my.counter"), entry["name"]);
374 assert_eq!(json!(3), entry["count"]);
375 assert_eq!(json!(100), entry["last_seen"]);
376 let tags = entry["tags"]
377 .as_array()
378 .expect("tags should serialize as an array")
379 .iter()
380 .map(|tag| tag.as_str().expect("each tag should be a string"))
381 .collect::<BTreeSet<_>>();
382 assert_eq!(BTreeSet::from(["env:prod", "service:web"]), tags);
383 }
384
385 #[tokio::test]
386 async fn stats_handler_rejects_excessive_collection_duration() {
387 let config = DogStatsDStatisticsConfiguration::new();
390 let state = config.api_handler.state.clone();
391
392 let (status, body) = DogStatsDStatsAPIHandler::stats_handler(
393 State(state),
394 Query(StatsQueryParams {
395 collection_duration_secs: 601,
396 }),
397 )
398 .await;
399
400 assert_eq!(StatusCode::BAD_REQUEST, status);
401 assert_eq!("Collection duration cannot be greater than 600 seconds.", body);
402 }
403
404 #[tokio::test]
405 async fn collection_request_accumulates_metrics_then_responds_on_timeout() {
406 use saluki_core::components::test_util::TestComponentDriver;
407 use tokio::time::timeout;
408
409 let config = DogStatsDStatisticsConfiguration::new();
411 let request_tx = config.api_handler.state.tx.clone();
412 let control = TestComponentDriver::destination(config)
413 .await
414 .expect("dsd_stats destination should build");
415
416 let (response_tx, response_rx) = oneshot::channel();
420 request_tx
421 .send((response_tx, 1))
422 .await
423 .expect("collection request should be accepted");
424 tokio::task::yield_now().await;
425
426 control
428 .send_events([
429 Event::Metric(Metric::counter("dsd.stats.repeated", 1.0)),
430 Event::Metric(Metric::counter("dsd.stats.repeated", 1.0)),
431 Event::Metric(Metric::counter("dsd.stats.single", 1.0)),
432 ])
433 .await;
434 control.wait_until_input_drained().await;
435
436 let response = timeout(Duration::from_secs(5), response_rx)
439 .await
440 .expect("collection response should arrive before timeout")
441 .expect("collection response channel should remain open");
442
443 let collected = match response {
444 StatsResponse::Statistics(collected) => collected,
445 StatsResponse::AlreadyRunning { .. } => panic!("first request should not report an active collection"),
446 };
447 let samples = collected.stats.0;
448 assert_eq!(2, samples.len(), "each distinct context should have its own sample");
449
450 let repeated = samples
451 .iter()
452 .find(|(ctx, _)| ctx.name.as_ref() == "dsd.stats.repeated")
453 .map(|(_, sample)| sample)
454 .expect("repeated context should be collected");
455 assert_eq!(2, repeated.count, "the repeated context should be counted twice");
456
457 let single = samples
458 .iter()
459 .find(|(ctx, _)| ctx.name.as_ref() == "dsd.stats.single")
460 .map(|(_, sample)| sample)
461 .expect("single context should be collected");
462 assert_eq!(1, single.count);
463
464 control.shutdown().await.expect("run should complete cleanly");
466 }
467}