1use std::time::Duration;
4
5use async_trait::async_trait;
6use datadog_protos::traces::{
7 ClientGroupedStats as ProtoClientGroupedStats, ClientStatsBucket as ProtoClientStatsBucket,
8 ClientStatsPayload as ProtoClientStatsPayload, StatsPayload as ProtoStatsPayload, Trilean,
9};
10use http::{uri::PathAndQuery, HeaderValue, Method, Uri};
11use metrics::Counter;
12use saluki_core::accounting::{MemoryBounds, MemoryBoundsBuilder};
13use saluki_core::runtime;
14use saluki_core::{
15 components::{encoders::*, BuildContext},
16 data_model::{
17 event::{
18 trace_stats::{ClientGroupedStats, ClientStatsBucket, ClientStatsPayload, TraceStats},
19 EventType,
20 },
21 payload::{HttpPayload, Payload, PayloadMetadata, PayloadType},
22 },
23 observability::ComponentMetricsExt as _,
24 topology::{EventsBuffer, PayloadsBuffer},
25};
26use saluki_env::{host::providers::BoxedHostProvider, EnvironmentProvider, HostProvider};
27use saluki_error::{generic_error, ErrorContext as _, GenericError};
28use saluki_io::compression::CompressionScheme;
29use saluki_metrics::MetricsBuilder;
30use stringtheory::MetaString;
31use tokio::{
32 pin, select,
33 sync::mpsc::{self, Receiver, Sender},
34 time::sleep,
35};
36use tracing::{debug, error};
37
38use crate::common::datadog::{
39 io::RB_BUFFER_CHUNK_SIZE,
40 request_builder::{EndpointEncoder, RequestBuilder},
41 telemetry::ComponentTelemetry,
42 DEFAULT_INTAKE_COMPRESSED_SIZE_LIMIT, DEFAULT_INTAKE_UNCOMPRESSED_SIZE_LIMIT,
43};
44use crate::config::AgentEnv;
45
46const MAX_STATS_PER_PAYLOAD: usize = 4000;
47static CONTENT_TYPE_MSGPACK: HeaderValue = HeaderValue::from_static("application/msgpack");
48
49pub struct DatadogApmStatsEncoderConfiguration {
51 flush_timeout: Duration,
52 agent_hostname: Option<String>,
53 agent_version: String,
54 agent_env: AgentEnv,
55}
56
57impl DatadogApmStatsEncoderConfiguration {
58 pub fn new(flush_timeout: Duration, agent_env: AgentEnv) -> Self {
63 let app_details = saluki_metadata::get_app_details();
64 Self {
65 flush_timeout,
66 agent_hostname: None,
67 agent_version: format!("agent-data-plane/{}", app_details.version().raw()),
68 agent_env,
69 }
70 }
71
72 pub async fn with_environment_provider<E>(mut self, environment_provider: E) -> Result<Self, GenericError>
74 where
75 E: EnvironmentProvider<Host = BoxedHostProvider>,
76 {
77 let host_provider = environment_provider.host();
78 let hostname = host_provider.get_hostname().await?;
79 self.agent_hostname = Some(hostname);
80 Ok(self)
81 }
82
83 fn endpoint_encoder(&self) -> StatsEndpointEncoder {
84 StatsEndpointEncoder::new(
85 MetaString::from(self.agent_hostname.clone().unwrap_or_default()),
86 MetaString::from(self.agent_version.clone()),
87 self.agent_env.clone().into(),
88 )
89 }
90}
91
92#[async_trait]
93impl EncoderBuilder for DatadogApmStatsEncoderConfiguration {
94 fn input_event_type(&self) -> EventType {
95 EventType::TraceStats
96 }
97
98 fn output_payload_type(&self) -> PayloadType {
99 PayloadType::Http
100 }
101
102 async fn build(&self, context: BuildContext) -> Result<Box<dyn Encoder + Send>, GenericError> {
103 let metrics_builder = MetricsBuilder::from_component_context(context.component_context());
104 let telemetry = ComponentTelemetry::from_builder(&metrics_builder);
105 let payload_telemetry = StatsPayloadTelemetry::from_builder(&metrics_builder);
106 let compression_scheme = CompressionScheme::gzip_default();
107
108 let mut stats_rb =
109 RequestBuilder::new(self.endpoint_encoder(), compression_scheme, RB_BUFFER_CHUNK_SIZE).await?;
110 stats_rb.with_max_inputs_per_payload(MAX_STATS_PER_PAYLOAD);
111
112 let flush_timeout = if self.flush_timeout.is_zero() {
113 Duration::from_millis(10)
116 } else {
117 self.flush_timeout
118 };
119
120 Ok(Box::new(DatadogStats {
121 stats_rb,
122 telemetry,
123 payload_telemetry,
124 flush_timeout,
125 }))
126 }
127}
128
129impl MemoryBounds for DatadogApmStatsEncoderConfiguration {
130 fn specify_bounds(&self, builder: &mut MemoryBoundsBuilder) {
131 builder
132 .minimum()
133 .with_single_value::<DatadogStats>("component struct")
134 .with_array::<EventsBuffer>("request builder events channel", 8)
135 .with_array::<PayloadsBuffer>("request builder payloads channel", 8);
136
137 builder
138 .firm()
139 .with_array::<TraceStats>("stats split re-encode buffer", MAX_STATS_PER_PAYLOAD);
140 }
141}
142
143pub struct DatadogStats {
144 stats_rb: RequestBuilder<StatsEndpointEncoder>,
145 telemetry: ComponentTelemetry,
146 payload_telemetry: StatsPayloadTelemetry,
147 flush_timeout: Duration,
148}
149
150struct StatsPayloadTelemetry {
152 client_payloads: Counter,
153 buckets: Counter,
154 entries: Counter,
155 bytes_uncompressed: Counter,
156}
157
158impl StatsPayloadTelemetry {
159 fn from_builder(builder: &MetricsBuilder) -> Self {
160 Self {
161 client_payloads: builder.register_counter("component_stats_client_payloads_encoded_total"),
162 buckets: builder.register_counter("component_stats_buckets_encoded_total"),
163 entries: builder.register_counter("component_stats_entries_encoded_total"),
164 bytes_uncompressed: builder.register_counter("component_bytes_uncompressed_total"),
165 }
166 }
167
168 fn track_stats(&self, counts: StatsCounts) {
170 self.client_payloads.increment(counts.client_payloads);
171 self.buckets.increment(counts.buckets);
172 self.entries.increment(counts.entries);
173 }
174
175 fn track_payload(&self, uncompressed_len: usize) {
177 self.bytes_uncompressed.increment(uncompressed_len as u64);
178 }
179}
180
181#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
183struct StatsCounts {
184 client_payloads: u64,
185 buckets: u64,
186 entries: u64,
187}
188
189impl StatsCounts {
190 fn from_trace_stats(stats: &TraceStats) -> Self {
192 let client_payloads = stats.stats();
193 let buckets = client_payloads.iter().flat_map(|client_payload| client_payload.stats());
194 Self {
195 client_payloads: client_payloads.len() as u64,
196 buckets: buckets.clone().count() as u64,
197 entries: buckets.map(|bucket| bucket.stats().len() as u64).sum(),
198 }
199 }
200}
201
202#[async_trait]
203impl Encoder for DatadogStats {
204 async fn run(mut self: Box<Self>, mut context: EncoderContext) -> Result<(), GenericError> {
205 let Self {
206 stats_rb,
207 telemetry,
208 payload_telemetry,
209 flush_timeout,
210 } = *self;
211
212 let mut health = context.take_health_handle();
213
214 let (events_tx, events_rx) = mpsc::channel(8);
215 let (payloads_tx, mut payloads_rx) = mpsc::channel(8);
216
217 let request_builder_fut = run_request_builder(
222 stats_rb,
223 telemetry,
224 payload_telemetry,
225 events_rx,
226 payloads_tx,
227 flush_timeout,
228 );
229 runtime::worker("request_builder", request_builder_fut)
230 .on_runtime(context.topology_context().global_thread_pool().clone())
231 .needed()
232 .spawn();
233
234 health.mark_ready();
235 debug!("Datadog APM Stats encoder started.");
236
237 loop {
238 select! {
239 biased;
240
241 _ = health.live() => continue,
242 maybe_payload = payloads_rx.recv() => match maybe_payload {
243 Some(payload) => {
244 if let Err(e) = context.dispatcher().dispatch(payload).await {
245 error!("Failed to dispatch payload: {}", e);
246 }
247 }
248 None => break,
249 },
250 maybe_event_buffer = context.events().next() => match maybe_event_buffer {
251 Some(event_buffer) => events_tx.send(event_buffer).await
252 .error_context("Failed to send event buffer to request builder task.")?,
253 None => break,
254 },
255 }
256 }
257
258 drop(events_tx);
259
260 while let Some(payload) = payloads_rx.recv().await {
262 if let Err(e) = context.dispatcher().dispatch(payload).await {
263 error!("Failed to dispatch payload: {}", e);
264 }
265 }
266
267 debug!("Datadog APM Stats encoder stopped.");
270
271 Ok(())
272 }
273}
274
275async fn run_request_builder(
276 mut stats_request_builder: RequestBuilder<StatsEndpointEncoder>, telemetry: ComponentTelemetry,
277 payload_telemetry: StatsPayloadTelemetry, mut events_rx: Receiver<EventsBuffer>,
278 payloads_tx: Sender<PayloadsBuffer>, flush_timeout: std::time::Duration,
279) -> Result<(), GenericError> {
280 let mut pending_flush = false;
281 let pending_flush_timeout = sleep(flush_timeout);
282 pin!(pending_flush_timeout);
283
284 loop {
285 select! {
286 Some(event_buffer) = events_rx.recv() => {
287 for trace_stats in event_buffer.into_events::<TraceStats>() {
288
289 let stats_counts = StatsCounts::from_trace_stats(&trace_stats);
292 let stats_to_retry = match stats_request_builder.encode(trace_stats).await {
293 Ok(None) => {
294 payload_telemetry.track_stats(stats_counts);
295 continue;
296 }
297 Ok(Some(stats)) => stats,
298 Err(e) => {
299 error!(error = %e, "Failed to encode stats.");
300 telemetry.events_dropped_encoder().increment(1);
301 continue;
302 }
303 };
304
305 let maybe_requests = stats_request_builder.flush().await;
306 if maybe_requests.is_empty() {
307 panic!("builder told us to flush, but gave us nothing");
308 }
309
310 for maybe_request in maybe_requests {
311 match maybe_request {
312 Ok((events, _data_points, uncompressed_len, request)) => {
313 payload_telemetry.track_payload(uncompressed_len);
314 let payload_meta = PayloadMetadata::from_event_count(events);
315 let http_payload = HttpPayload::new(payload_meta, request);
316 let payload = Payload::Http(http_payload);
317
318 payloads_tx.send(payload).await
319 .map_err(|_| generic_error!("Failed to send payload to encoder."))?;
320 },
321 Err(e) => if e.is_recoverable() {
322 continue;
323 } else {
324 return Err(GenericError::from(e).context("Failed to flush request."));
325 }
326 }
327 }
328
329 match stats_request_builder.encode(stats_to_retry).await {
330 Ok(None) => payload_telemetry.track_stats(stats_counts),
331 Ok(Some(_)) => {
332 error!("Stats did not fit in a request after flushing; dropping them.");
333 telemetry.events_dropped_encoder().increment(1);
334 }
335 Err(e) => {
336 error!(error = %e, "Failed to encode stats.");
337 telemetry.events_dropped_encoder().increment(1);
338 }
339 }
340 }
341
342 debug!("Processed event buffer.");
343
344 if !pending_flush {
346 pending_flush_timeout.as_mut().reset(tokio::time::Instant::now() + flush_timeout);
347 pending_flush = true;
348 }
349 },
350 _ = &mut pending_flush_timeout, if pending_flush => {
351 debug!("Flushing pending request(s).");
352
353 pending_flush = false;
354
355 let maybe_stats_requests = stats_request_builder.flush().await;
356 for maybe_request in maybe_stats_requests {
357 match maybe_request {
358 Ok((events, _data_points, uncompressed_len, request)) => {
359 payload_telemetry.track_payload(uncompressed_len);
360 let payload_meta = PayloadMetadata::from_event_count(events);
361 let http_payload = HttpPayload::new(payload_meta, request);
362 let payload = Payload::Http(http_payload);
363
364 payloads_tx.send(payload).await
365 .map_err(|_| generic_error!("Failed to send payload to encoder."))?;
366 },
367 Err(e) => if e.is_recoverable() {
368 continue;
369 } else {
370 return Err(GenericError::from(e).context("Failed to flush request."));
371 }
372 }
373 }
374
375 debug!("All flushed requests sent to I/O task. Waiting for next event buffer...");
376 },
377
378 else => break,
379 }
380 }
381
382 Ok(())
383}
384
385#[derive(Debug)]
386struct StatsEndpointEncoder {
387 agent_hostname: MetaString,
388 agent_version: MetaString,
389 agent_env: MetaString,
390}
391
392impl StatsEndpointEncoder {
393 fn new(agent_hostname: MetaString, agent_version: MetaString, agent_env: MetaString) -> Self {
394 Self {
395 agent_hostname,
396 agent_version,
397 agent_env,
398 }
399 }
400
401 fn to_proto_stats_payload(&self, stats: &TraceStats) -> ProtoStatsPayload {
402 let mut payload = ProtoStatsPayload::new();
403 payload.set_agentHostname(self.agent_hostname.to_string());
404 payload.set_agentEnv(self.agent_env.to_string());
405 payload.set_agentVersion(self.agent_version.to_string());
406 payload.set_clientComputed(false);
407 payload.set_splitPayload(stats.is_split_payload());
408 payload.set_stats(stats.stats().iter().map(convert_client_stats_payload).collect());
409
410 payload
411 }
412}
413
414fn convert_client_stats_payload(client_payload: &ClientStatsPayload) -> ProtoClientStatsPayload {
415 let mut proto_client = ProtoClientStatsPayload::new();
416 proto_client.set_hostname(client_payload.hostname().to_string());
417 proto_client.set_env(client_payload.env().to_string());
418 proto_client.set_version(client_payload.version().to_string());
419 proto_client.set_lang(client_payload.lang().to_string());
420 proto_client.set_tracerVersion(client_payload.tracer_version().to_string());
421 proto_client.set_runtimeID(client_payload.runtime_id().to_string());
422 proto_client.set_sequence(client_payload.sequence());
423 proto_client.set_agentAggregation(client_payload.agent_aggregation().to_string());
424 proto_client.set_service(client_payload.service().to_string());
425 proto_client.set_containerID(client_payload.container_id().to_string());
426 proto_client.set_tags(client_payload.tags().into_iter().map(|s| s.to_string()).collect());
427 proto_client.set_git_commit_sha(client_payload.git_commit_sha().to_string());
428 proto_client.set_image_tag(client_payload.image_tag().to_string());
429 proto_client.set_process_tags_hash(client_payload.process_tags_hash());
430 proto_client.set_process_tags(client_payload.process_tags().to_string());
431 proto_client.set_stats(client_payload.stats().iter().map(convert_client_stats_bucket).collect());
432 proto_client
433}
434
435fn convert_client_stats_bucket(bucket: &ClientStatsBucket) -> ProtoClientStatsBucket {
436 let mut proto_bucket = ProtoClientStatsBucket::new();
437 proto_bucket.set_start(bucket.start());
438 proto_bucket.set_duration(bucket.duration());
439 proto_bucket.set_agentTimeShift(bucket.agent_time_shift());
440 proto_bucket.set_stats(bucket.stats().iter().map(convert_client_grouped_stats).collect());
441 proto_bucket
442}
443
444fn convert_client_grouped_stats(grouped: &ClientGroupedStats) -> ProtoClientGroupedStats {
445 let mut proto_grouped = ProtoClientGroupedStats::new();
446 proto_grouped.set_service(grouped.service().to_string());
447 proto_grouped.set_name(grouped.name().to_string());
448 proto_grouped.set_resource(grouped.resource().to_string());
449 proto_grouped.set_HTTP_status_code(grouped.http_status_code());
450 proto_grouped.set_type(grouped.span_type().to_string());
451 proto_grouped.set_DB_type(grouped.db_type().to_string());
452 proto_grouped.set_hits(grouped.hits());
453 proto_grouped.set_errors(grouped.errors());
454 proto_grouped.set_duration(grouped.duration());
455 proto_grouped.set_okSummary(grouped.ok_summary().to_vec());
456 proto_grouped.set_errorSummary(grouped.error_summary().to_vec());
457 proto_grouped.set_synthetics(grouped.synthetics());
458 proto_grouped.set_topLevelHits(grouped.top_level_hits());
459 proto_grouped.set_span_kind(grouped.span_kind().to_string());
460 proto_grouped.set_peer_tags(grouped.peer_tags().iter().map(|s| s.to_string()).collect());
461 proto_grouped.set_is_trace_root(match grouped.is_trace_root() {
462 None => Trilean::NOT_SET,
463 Some(true) => Trilean::TRUE,
464 Some(false) => Trilean::FALSE,
465 });
466 proto_grouped.set_GRPC_status_code(grouped.grpc_status_code().to_string());
467 proto_grouped.set_HTTP_method(grouped.http_method().to_string());
468 proto_grouped.set_HTTP_endpoint(grouped.http_endpoint().to_string());
469 proto_grouped
470}
471
472#[derive(Debug)]
474pub struct StatsEncodeError(rmp_serde::encode::Error);
475
476impl std::fmt::Display for StatsEncodeError {
477 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
478 write!(f, "failed to encode stats as MessagePack: {}", self.0)
479 }
480}
481
482impl std::error::Error for StatsEncodeError {
483 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
484 Some(&self.0)
485 }
486}
487
488impl EndpointEncoder for StatsEndpointEncoder {
489 type Input = TraceStats;
490 type EncodeError = StatsEncodeError;
491
492 fn encoder_name() -> &'static str {
493 "stats"
494 }
495
496 fn compressed_size_limit(&self) -> usize {
497 DEFAULT_INTAKE_COMPRESSED_SIZE_LIMIT
498 }
499
500 fn uncompressed_size_limit(&self) -> usize {
501 DEFAULT_INTAKE_UNCOMPRESSED_SIZE_LIMIT
502 }
503
504 fn encode(&mut self, stats: &Self::Input, buffer: &mut Vec<u8>) -> Result<(), Self::EncodeError> {
505 let payload = self.to_proto_stats_payload(stats);
506 rmp_serde::encode::write_named(buffer, &payload).map_err(StatsEncodeError)?;
507 Ok(())
508 }
509
510 fn endpoint_uri(&self) -> Uri {
511 PathAndQuery::from_static("/api/v0.2/stats").into()
512 }
513
514 fn endpoint_method(&self) -> Method {
515 Method::POST
516 }
517
518 fn content_type(&self) -> HeaderValue {
519 CONTENT_TYPE_MSGPACK.clone()
520 }
521}
522
523#[cfg(test)]
524mod tests {
525 use saluki_core::data_model::event::Event;
526 use saluki_metrics::test::TestRecorder;
527
528 use super::*;
529
530 #[test]
531 fn stats_payload_agent_env_is_the_agent_env() {
532 let cases = [
535 (AgentEnv::resolve(None, Some("Prod"), &[], &[]), "prod"),
536 (AgentEnv::resolve(Some("!!!"), None, &[], &[]), ""),
537 ];
538 for (agent_env, expected) in cases {
539 let config = DatadogApmStatsEncoderConfiguration::new(Duration::from_secs(2), agent_env);
540 let mut buf = Vec::new();
541 config
542 .endpoint_encoder()
543 .encode(&TraceStats::new(Vec::new()), &mut buf)
544 .expect("encode should succeed");
545
546 let payload: ProtoStatsPayload = rmp_serde::from_slice(&buf).expect("StatsPayload should decode");
547 assert_eq!(payload.agentEnv(), expected);
548 }
549 }
550
551 #[test]
552 fn stats_payload_split_flag_follows_trace_stats() {
553 for is_split in [false, true] {
554 let config = DatadogApmStatsEncoderConfiguration::new(
555 Duration::from_secs(2),
556 AgentEnv::resolve(None, Some("prod"), &[], &[]),
557 );
558 let mut buf = Vec::new();
559 config
560 .endpoint_encoder()
561 .encode(&TraceStats::new(Vec::new()).with_split_payload(is_split), &mut buf)
562 .expect("encode should succeed");
563
564 let payload: ProtoStatsPayload = rmp_serde::from_slice(&buf).expect("StatsPayload should decode");
565 assert_eq!(payload.splitPayload(), is_split);
566 }
567 }
568
569 fn make_client_payload(entries_per_bucket: &[usize]) -> ClientStatsPayload {
570 let buckets = entries_per_bucket
571 .iter()
572 .map(|&entries| {
573 let stats = (0..entries)
574 .map(|i| ClientGroupedStats::new("svc", "op", format!("res-{i}")))
575 .collect();
576 ClientStatsBucket::new(1000, 10_000_000_000, stats)
577 })
578 .collect();
579 ClientStatsPayload::new("host", "env", "1.0.0").with_stats(buckets)
580 }
581
582 #[test]
583 fn stats_counts_count_client_payloads_buckets_and_entries() {
584 let stats = TraceStats::new(vec![make_client_payload(&[2, 3]), make_client_payload(&[1])]);
585 assert_eq!(
586 StatsCounts::from_trace_stats(&stats),
587 StatsCounts {
588 client_payloads: 2,
589 buckets: 3,
590 entries: 6,
591 }
592 );
593 assert_eq!(
594 StatsCounts::from_trace_stats(&TraceStats::new(Vec::new())),
595 StatsCounts::default()
596 );
597 }
598
599 #[tokio::test]
600 async fn request_builder_tracks_written_stats_and_uncompressed_bytes() {
601 let recorder = TestRecorder::default();
602 let _recorder_guard = metrics::set_default_local_recorder(&recorder);
603 let metrics_builder = MetricsBuilder::default();
604 let config = DatadogApmStatsEncoderConfiguration::new(
605 Duration::from_secs(2),
606 AgentEnv::resolve(None, Some("prod"), &[], &[]),
607 );
608
609 let all_stats = vec![
610 TraceStats::new(vec![make_client_payload(&[2, 3]), make_client_payload(&[1])]),
611 TraceStats::new(vec![make_client_payload(&[4])]),
612 ];
613
614 let expected_uncompressed_len = all_stats
616 .iter()
617 .map(|stats| {
618 let mut buf = Vec::new();
619 config
620 .endpoint_encoder()
621 .encode(stats, &mut buf)
622 .expect("encode should succeed");
623 buf.len() as u64
624 })
625 .sum::<u64>();
626
627 let request_builder = RequestBuilder::new(
628 config.endpoint_encoder(),
629 CompressionScheme::noop(),
630 RB_BUFFER_CHUNK_SIZE,
631 )
632 .await
633 .expect("request builder should be created");
634 let (events_tx, events_rx) = mpsc::channel(1);
635 let (payloads_tx, mut payloads_rx) = mpsc::channel(8);
636
637 let mut events = EventsBuffer::default();
638 for stats in all_stats {
639 assert!(events.try_push(Event::TraceStats(stats)).is_none());
640 }
641 events_tx.send(events).await.expect("events should be sent");
642 drop(events_tx);
643
644 run_request_builder(
645 request_builder,
646 ComponentTelemetry::from_builder(&metrics_builder),
647 StatsPayloadTelemetry::from_builder(&metrics_builder),
648 events_rx,
649 payloads_tx,
650 Duration::from_millis(1),
651 )
652 .await
653 .expect("request builder should run to completion");
654
655 let mut payloads = 0;
656 while payloads_rx.recv().await.is_some() {
657 payloads += 1;
658 }
659 assert_eq!(payloads, 1);
660
661 assert_eq!(
662 recorder.counter("component_stats_client_payloads_encoded_total"),
663 Some(3)
664 );
665 assert_eq!(recorder.counter("component_stats_buckets_encoded_total"), Some(4));
666 assert_eq!(recorder.counter("component_stats_entries_encoded_total"), Some(10));
667 assert_eq!(
668 recorder.counter("component_bytes_uncompressed_total"),
669 Some(expected_uncompressed_len)
670 );
671 }
672}