Skip to main content

saluki_components/forwarders/datadog/
mod.rs

1use std::{collections::HashMap, sync::Arc};
2
3use async_trait::async_trait;
4use http::Uri;
5use saluki_common::buf::FrozenChunkedBytesBuffer;
6use saluki_common::sync::live::Live;
7use saluki_core::accounting::{MemoryBounds, MemoryBoundsBuilder, UsageExpr};
8use saluki_core::{
9    components::{forwarders::*, BuildContext},
10    data_model::payload::{PayloadMetadata, PayloadType},
11    observability::ComponentMetricsExt as _,
12};
13use saluki_error::{ErrorContext as _, GenericError};
14use saluki_metrics::MetricsBuilder;
15use stringtheory::MetaString;
16use tokio::select;
17use tracing::debug;
18
19use crate::common::datadog::{
20    api_key::{ApiKeyView, LiveApiKeys},
21    config::ForwarderConfiguration,
22    endpoints::{EndpointRoute, SingleDestination},
23    io::{LiveForwarderConfiguration, TransactionForwarder, ENDPOINT_CHANNEL_CAPACITY},
24    protocol::MetricsPayloadInfo,
25    routing::{MetricsRoutingTargets, RoutingTargetCatalog},
26    sketch_shadow::SketchShadowMetadata,
27    telemetry::ComponentTelemetry,
28    transaction::{Metadata, Transaction},
29    validation::ValidationReadiness,
30    DEFAULT_INTAKE_COMPRESSED_SIZE_LIMIT, DEFAULT_SERIALIZER_COMPRESSED_SIZE_LIMIT, METRICS_SERIES_V3_BETA_PATH,
31    METRICS_SERIES_V3_PATH, METRICS_SKETCHES_V3_PATH,
32};
33
34/// Datadog forwarder.
35///
36/// Forwards Datadog-specific payloads to the Datadog platform. Handles the standard Datadog Agent configuration,
37/// in terms of specifying additional endpoints, adding the necessary HTTP request headers for authentication,
38/// identification, and more.
39pub struct DatadogForwarderConfiguration {
40    /// Forwarder configuration settings.
41    ///
42    /// See [`ForwarderConfiguration`] for more information about the available settings.
43    forwarder_config: ForwarderConfiguration,
44
45    /// Live views the endpoints take their API keys from.
46    api_keys: LiveApiKeys,
47
48    /// Whether secret resolution might replace a rejected API key, which the retry policy's gate reads.
49    secrets_in_use: Live<bool>,
50}
51
52impl DatadogForwarderConfiguration {
53    /// Creates a new `DatadogForwarderConfiguration` that forwards to the endpoints of `forwarder`.
54    ///
55    /// `api_key` and `additional_endpoints` are the live views the endpoints take their API keys from, so that a key an
56    /// operator rotates while the process runs reaches the next request. `secrets_in_use` is the live view the retry
57    /// policy's gate reads to decide whether a rejected key is worth retrying.
58    pub fn new(
59        forwarder: ForwarderConfiguration, api_key: Live<String>,
60        additional_endpoints: Live<HashMap<String, Vec<String>>>, secrets_in_use: Live<bool>,
61    ) -> Self {
62        Self {
63            forwarder_config: forwarder,
64            api_keys: LiveApiKeys {
65                primary: Some(ApiKeyView::Required(api_key)),
66                additional: Some(additional_endpoints),
67            },
68            secrets_in_use,
69        }
70    }
71
72    /// Creates a new `DatadogForwarderConfiguration` that forwards to a single endpoint override.
73    ///
74    /// The override replaces the endpoints of `forwarder` entirely, and `api_key_view` is the live view its key comes
75    /// from. Multi-Region Failover needs this: it has its own key, not the primary one, and configuration can leave
76    /// that key unset. `secrets_in_use` serves the same purpose as in [`new`](Self::new): it decides whether the
77    /// override's rejected key is worth retrying.
78    pub fn for_endpoint_override(
79        forwarder: ForwarderConfiguration, dd_url: String, api_key: String, api_key_view: Live<Option<String>>,
80        secrets_in_use: Live<bool>,
81    ) -> Self {
82        let destination = SingleDestination {
83            url: dd_url,
84            api_key,
85            accepts_v3_series: true,
86        };
87
88        Self {
89            forwarder_config: forwarder.for_single_destination(&destination),
90            api_keys: LiveApiKeys {
91                primary: Some(ApiKeyView::Optional(api_key_view)),
92                additional: None,
93            },
94            secrets_in_use,
95        }
96    }
97
98    /// Sets the routing targets that metrics payloads sent to this forwarder may be addressed to.
99    ///
100    /// Every encoder that addresses its payloads with [`MetricsRoutingTargets`] must share this catalog, and the catalog
101    /// must be built from the same endpoint configuration as this forwarder. Without a catalog, a payload addressed to
102    /// specific targets reaches no endpoint.
103    pub fn with_routing_targets(mut self, routing_targets: Arc<RoutingTargetCatalog>) -> Self {
104        self.forwarder_config.routing_targets = Some(routing_targets);
105        self
106    }
107}
108
109#[async_trait]
110impl ForwarderBuilder for DatadogForwarderConfiguration {
111    fn input_payload_type(&self) -> PayloadType {
112        PayloadType::Http
113    }
114
115    async fn build(&self, context: BuildContext) -> Result<Box<dyn Forwarder + Send>, GenericError> {
116        let metrics_builder = MetricsBuilder::from_component_context(context.component_context());
117        let telemetry = ComponentTelemetry::from_builder(&metrics_builder);
118        let forwarder = TransactionForwarder::from_config(
119            context.component_context().clone(),
120            self.forwarder_config.clone(),
121            LiveForwarderConfiguration {
122                api_keys: self.api_keys.clone(),
123                secrets_in_use: self.secrets_in_use.clone(),
124            },
125            get_dd_endpoint_name,
126            telemetry.clone(),
127            metrics_builder,
128        )?;
129
130        Ok(Box::new(Datadog { forwarder }))
131    }
132}
133
134impl MemoryBounds for DatadogForwarderConfiguration {
135    fn specify_bounds(&self, builder: &mut MemoryBoundsBuilder) {
136        builder
137            .minimum()
138            .with_single_value::<Datadog>("component struct")
139            .with_array::<Transaction<FrozenChunkedBytesBuffer>>("requests channel", 8);
140
141        builder
142            .firm()
143            // TODO: This is a little wonky because we're accounting for the firm bound portion of connected encoders here, as this
144            // is the only place where we can calculate how many requests we'll hold on to in memory, which is what ultimately influences
145            // the firm usage.
146            //
147            // We're also cheating by knowing what the largest possible payload is that we'll potentially see, based on the limits on the
148            // Datadog encoders. This won't necessarily hold up for future sources/encoders, but is good enough for now.
149            .with_expr(UsageExpr::sum(
150                "in-flight requests",
151                UsageExpr::config(
152                    "forwarder_retry_queue_payloads_max_size",
153                    self.forwarder_config.retry.queue_max_size_bytes as usize,
154                ),
155                UsageExpr::product(
156                    "high priority queue",
157                    UsageExpr::config(
158                        "forwarder_high_prio_buffer_size",
159                        self.forwarder_config.endpoint_buffer_size,
160                    ),
161                    // TODO: The default compressed size limit just so happens to be the biggest one we currently default with on our side,
162                    // but it's not clear that this will always be the case.
163                    UsageExpr::constant("maximum compressed payload size", DEFAULT_INTAKE_COMPRESSED_SIZE_LIMIT),
164                ),
165            ));
166
167        // Count the same eligible workers used for dispatch, including separate additional API keys.
168        let Ok(endpoints) = self.forwarder_config.build_routable_endpoints() else {
169            return;
170        };
171        let has_metrics_primary = endpoints
172            .iter()
173            .any(|endpoint| endpoint.route() == EndpointRoute::MetricsPrimary);
174        let shadow_endpoint_count = endpoints
175            .iter()
176            .filter(|endpoint| {
177                self.forwarder_config
178                    .endpoint_supports_sketch_shadow(endpoint, has_metrics_primary)
179            })
180            .count();
181        if shadow_endpoint_count != 0 {
182            // Shadow workers run with a reduced configuration, so size them from that configuration.
183            let shadow_config = self.forwarder_config.for_sketch_shadow();
184            let request_slots = shadow_config
185                .endpoint_buffer_size
186                .saturating_add(ENDPOINT_CHANNEL_CAPACITY)
187                .saturating_add(shadow_config.effective_endpoint_concurrency());
188            let per_endpoint_bytes = (shadow_config.retry.queue_max_size_bytes as usize)
189                .saturating_add(request_slots.saturating_mul(DEFAULT_SERIALIZER_COMPRESSED_SIZE_LIMIT));
190            builder.firm().with_fixed_amount(
191                "sketch shadow queues and in-flight payloads",
192                shadow_endpoint_count.saturating_mul(per_endpoint_bytes),
193            );
194        }
195    }
196}
197
198pub struct Datadog {
199    forwarder: TransactionForwarder<FrozenChunkedBytesBuffer>,
200}
201
202#[async_trait]
203impl Forwarder for Datadog {
204    async fn run(mut self: Box<Self>, mut context: ForwarderContext) -> Result<(), GenericError> {
205        let Self { forwarder } = *self;
206
207        let mut health = context.take_health_handle();
208
209        // Both of these calls spawn supervised children of this component. When this run-future returns, the children
210        // stop, and their drain has a time limit.
211        let mut validation = forwarder
212            .api_key_validator()
213            .error_context("Failed to create API key validation client.")?
214            .spawn();
215        let forwarder = forwarder.spawn();
216
217        debug!("Datadog forwarder started.");
218
219        loop {
220            select! {
221                _ = health.live() => continue,
222                readiness = validation.wait_for_change() => match readiness {
223                    ValidationReadiness::Ready => health.mark_ready(),
224                    ValidationReadiness::NotReady => health.mark_not_ready(),
225                },
226                maybe_payload = context.payloads().next() => match maybe_payload {
227                    Some(payload) => if let Some(http_payload) = payload.try_into_http_payload() {
228                        let (payload_meta, request) = http_payload.into_parts();
229                        let transaction_meta = transaction_metadata_from_payload_metadata(&payload_meta);
230                        let transaction = Transaction::from_original(transaction_meta, request);
231
232                        forwarder.send_transaction(transaction).await?;
233                    }
234                    None => break,
235                },
236            }
237        }
238
239        // Start the forwarder's drain. Dropping `validation` stops API key validation the same way. This component does
240        // not wait for either of them here. But this component does not finish until its children finish. The shutdown
241        // timeout of the component bounds this wait.
242        forwarder.shutdown();
243        drop(validation);
244
245        debug!("Datadog forwarder stopped.");
246
247        Ok(())
248    }
249}
250
251fn transaction_metadata_from_payload_metadata(payload_meta: &PayloadMetadata) -> Metadata {
252    let mut transaction_meta =
253        Metadata::from_event_and_data_point_count(payload_meta.event_count(), payload_meta.data_point_count());
254    transaction_meta.sketch_shadow = payload_meta.get::<SketchShadowMetadata>().cloned();
255    if transaction_meta
256        .sketch_shadow
257        .as_ref()
258        .is_some_and(|shadow| shadow.is_shadow)
259    {
260        // Validation copies must not count as delivered or dropped metric data.
261        transaction_meta.event_count = 0;
262        transaction_meta.data_point_count = 0;
263    }
264    transaction_meta.payload_info = payload_meta.get::<MetricsPayloadInfo>().copied();
265    transaction_meta.metrics_routing_targets = payload_meta.get::<Arc<MetricsRoutingTargets>>().cloned();
266    transaction_meta
267}
268
269fn get_dd_endpoint_name(uri: &Uri) -> Option<MetaString> {
270    match uri.path() {
271        "/api/v2/logs" => Some(MetaString::from_static("logs_v2")),
272        "/api/v1/series" => Some(MetaString::from_static("series_v1")),
273        "/api/v2/series" => Some(MetaString::from_static("series_v2")),
274        METRICS_SERIES_V3_PATH => Some(MetaString::from_static("series_v3")),
275        METRICS_SERIES_V3_BETA_PATH => Some(MetaString::from_static("series_v3beta")),
276        "/api/beta/sketches" => Some(MetaString::from_static("sketches_v2")),
277        METRICS_SKETCHES_V3_PATH => Some(MetaString::from_static("sketches_v3")),
278        "/api/intake/metrics/v3beta/sketches" => Some(MetaString::from_static("sketches_v3beta")),
279        "/api/v1/check_run" => Some(MetaString::from_static("check_run_v1")),
280        "/api/v1/events_batch" => Some(MetaString::from_static("events_batch_v1")),
281        "/api/v0.2/traces" => Some(MetaString::from_static("traces_v0.2")),
282        "/api/v0.2/stats" => Some(MetaString::from_static("stats_v0.2")),
283        _ => None,
284    }
285}
286
287#[cfg(test)]
288mod tests {
289    use saluki_core::runtime::test_util::TestSupervisor;
290
291    use super::*;
292    use crate::common::datadog::{
293        api_key::ApiKeyRefresher,
294        sketch_shadow::SketchShadowDestination,
295        test_util::{forwarder_configuration, LiveConfiguration, LiveRoot},
296    };
297
298    #[test]
299    fn dd_endpoint_names_map_from_request_path() {
300        // Each intake path maps to the telemetry endpoint name the forwarder tags transactions with; the query and
301        // authority are ignored (only the path matters), and unknown paths map to `None`.
302        let cases: [(Uri, Option<&str>); 13] = [
303            (Uri::from_static("/api/v2/logs"), Some("logs_v2")),
304            (Uri::from_static("/api/v1/series"), Some("series_v1")),
305            (Uri::from_static("/api/v2/series"), Some("series_v2")),
306            (Uri::from_static(METRICS_SERIES_V3_PATH), Some("series_v3")),
307            (Uri::from_static(METRICS_SERIES_V3_BETA_PATH), Some("series_v3beta")),
308            (Uri::from_static("/api/beta/sketches"), Some("sketches_v2")),
309            (Uri::from_static(METRICS_SKETCHES_V3_PATH), Some("sketches_v3")),
310            (Uri::from_static("/api/v1/check_run"), Some("check_run_v1")),
311            (Uri::from_static("/api/v1/events_batch"), Some("events_batch_v1")),
312            (Uri::from_static("/api/v0.2/traces"), Some("traces_v0.2")),
313            (Uri::from_static("/api/v0.2/stats"), Some("stats_v0.2")),
314            (
315                Uri::from_static("https://app.datadoghq.com/api/v2/series"),
316                Some("series_v2"),
317            ),
318            (Uri::from_static("/api/v1/unknown"), None),
319        ];
320
321        for (uri, expected) in cases {
322            assert_eq!(
323                expected,
324                get_dd_endpoint_name(&uri).as_deref(),
325                "get_dd_endpoint_name({})",
326                uri.path()
327            );
328        }
329    }
330
331    #[test]
332    fn transaction_metadata_carries_counts_and_metrics_payload_info() {
333        // A non-metrics payload propagates the counts and leaves metrics metadata unset.
334        let payload_meta = PayloadMetadata::from_event_and_data_point_count(3, 11);
335        let transaction_meta = transaction_metadata_from_payload_metadata(&payload_meta);
336        assert_eq!(3, transaction_meta.event_count);
337        assert_eq!(11, transaction_meta.data_point_count);
338        assert_eq!(None, transaction_meta.payload_info);
339        assert_eq!(None, transaction_meta.metrics_routing_targets);
340
341        // A metrics payload preserves protocol info and shares routing through dispatch and transaction clones.
342        let catalog = RoutingTargetCatalog::new("https://primary.example.com", &HashMap::new()).unwrap();
343        let routing_targets = Arc::new(MetricsRoutingTargets::new(catalog.select(|_| true)));
344        let payload_meta = PayloadMetadata::from_event_and_data_point_count(2, 7)
345            .with(MetricsPayloadInfo::v3_series())
346            .with(Arc::clone(&routing_targets));
347        let transaction_meta = transaction_metadata_from_payload_metadata(&payload_meta);
348        assert_eq!(2, transaction_meta.event_count);
349        assert_eq!(7, transaction_meta.data_point_count);
350        assert_eq!(Some(MetricsPayloadInfo::v3_series()), transaction_meta.payload_info);
351        assert!(Arc::ptr_eq(
352            transaction_meta.metrics_routing_targets.as_ref().unwrap(),
353            &routing_targets
354        ));
355        let cloned_meta = transaction_meta.clone();
356        assert!(Arc::ptr_eq(
357            cloned_meta.metrics_routing_targets.as_ref().unwrap(),
358            &routing_targets
359        ));
360
361        for is_shadow in [false, true] {
362            let payload_meta = PayloadMetadata::from_event_and_data_point_count(2, 7).with(SketchShadowMetadata {
363                sampled_destinations: vec![SketchShadowDestination {
364                    configured_endpoint: Arc::from("https://primary.example.com"),
365                    batch_id: "batch-id".parse().unwrap(),
366                }]
367                .into(),
368                request_index: 1,
369                request_count: 3,
370                is_shadow,
371            });
372            let transaction_meta = transaction_metadata_from_payload_metadata(&payload_meta);
373            assert_eq!(
374                (transaction_meta.event_count, transaction_meta.data_point_count),
375                if is_shadow { (0, 0) } else { (2, 7) },
376            );
377            assert_eq!((payload_meta.event_count(), payload_meta.data_point_count()), (2, 7));
378            let shadow = transaction_meta.sketch_shadow.unwrap();
379            assert_eq!(
380                (shadow.is_shadow, shadow.request_index, shadow.request_count),
381                (is_shadow, 1, 3)
382            );
383            assert_eq!(shadow.batch_id("https://primary.example.com").unwrap(), "batch-id");
384        }
385    }
386
387    #[tokio::test]
388    async fn primary_v3_sketches_and_additional_shadow_pairs_reach_only_their_destinations() {
389        use axum::{
390            body::Bytes,
391            http::{HeaderMap, StatusCode},
392            routing::post,
393            Router,
394        };
395        use saluki_core::{
396            components::test_util::TestComponentDriver,
397            data_model::event::{metric::Metric, Event},
398        };
399        use tokio::{net::TcpListener, sync::mpsc};
400
401        use crate::common::datadog::{
402            endpoints::EndpointConfiguration, test_util::datadog_metrics_configuration, METRICS_SKETCHES_PATH,
403        };
404
405        const PRIMARY: &str = "http://app.datadoghq.com";
406        const ADDITIONAL: &str = "http://app.datadoghq.eu";
407        const BETA: &str = "/api/intake/metrics/v3beta/sketches";
408        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
409        let proxy = format!("http://{}", listener.local_addr().unwrap());
410        let (requests_tx, mut requests_rx) = mpsc::unbounded_channel();
411        let app = Router::new().fallback(post(move |uri: Uri, headers: HeaderMap, _: Bytes| {
412            requests_tx.send((uri, headers)).unwrap();
413            async { StatusCode::OK }
414        }));
415        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
416        let _ = saluki_tls::initialize_default_crypto_provider();
417        let live = LiveConfiguration::new(LiveRoot {
418            api_key: "0".repeat(32), // Synthetic key skips API-key validation.
419            additional_endpoints: HashMap::from([(ADDITIONAL.into(), vec!["0".repeat(32)])]),
420            ..Default::default()
421        });
422        let mut metrics = datadog_metrics_configuration();
423        metrics.primary_endpoint = PRIMARY.into();
424        metrics.additional_endpoints = live.source.load().additional_endpoints.clone();
425        let sketches = &mut metrics.v3_api.sketches;
426        sketches.endpoints = vec![PRIMARY.into()];
427        sketches.shadow_sites = vec!["datadoghq.com".into(), "datadoghq.eu".into()];
428        sketches.shadow_sample_rate = 1.0;
429        sketches.beta_route = BETA.into();
430        let mut forwarder = forwarder_configuration();
431        forwarder.endpoint =
432            EndpointConfiguration::new("0".repeat(32), PRIMARY.into(), metrics.additional_endpoints.clone());
433        forwarder.proxy.http = proxy;
434        forwarder.skip_ssl_validation = true;
435        forwarder.v3_api = metrics.v3_api.clone();
436        let forwarder_config = DatadogForwarderConfiguration::new(
437            forwarder,
438            live.source.live(|root| &root.api_key),
439            live.source.live(|root| &root.additional_endpoints),
440            live.source.live(|root| &root.secrets_in_use),
441        );
442        let (encoder, mut output) = TestComponentDriver::encoder(metrics).await.unwrap();
443        encoder
444            .send_events([Event::Metric(Metric::distribution("mixed.sketch", [(123, 4.0)]))])
445            .await;
446        let (result, payloads) = tokio::join!(encoder.shutdown(), output.collect());
447        result.unwrap();
448        let forwarder = TestComponentDriver::forwarder(forwarder_config).await.unwrap();
449        for payload in payloads {
450            forwarder.send(payload).await;
451        }
452        forwarder
453            .wait_until(|| requests_rx.len() >= 3, || "three sketch requests".into())
454            .await;
455        forwarder.shutdown().await.unwrap();
456        server.abort();
457        let mut received: Vec<_> = std::iter::from_fn(|| requests_rx.try_recv().ok()).collect();
458        assert_eq!(received.len(), 3, "no extra requests");
459        received.sort_by(|a, b| a.0.path().cmp(b.0.path()));
460
461        let correlation = |headers: &HeaderMap| {
462            ["X-Metrics-Request-ID", "X-Metrics-Request-Seq", "X-Metrics-Request-Len"]
463                .map(|key| headers.get(key).cloned())
464        };
465        let baseline = correlation(&received[0].1);
466        assert!(baseline.iter().all(Option::is_some));
467        // Primary gets only authoritative V3; the additional endpoint gets the correlated V2/V3beta pair.
468        for ((uri, headers), (path, site, expected)) in received.iter().zip([
469            (METRICS_SKETCHES_PATH, ".datadoghq.eu", baseline.clone()),
470            (METRICS_SKETCHES_V3_PATH, ".datadoghq.com", [None, None, None]),
471            (BETA, ".datadoghq.eu", baseline),
472        ]) {
473            assert_eq!(uri.path(), path);
474            assert!(uri.host().unwrap().ends_with(site));
475            assert_eq!(correlation(headers), expected);
476        }
477    }
478
479    #[tokio::test]
480    async fn an_endpoint_override_follows_the_failover_key_and_not_the_primary_one() {
481        let mut live_config = LiveRoot {
482            api_key: "primary-api-key".to_string(),
483            override_api_key: Some("mrf-api-key".to_string()),
484            ..LiveRoot::default()
485        };
486        let mut live = LiveConfiguration::new(live_config.clone());
487
488        let config = DatadogForwarderConfiguration::for_endpoint_override(
489            forwarder_configuration(),
490            "http://mrf.example.test".to_string(),
491            "mrf-api-key".to_string(),
492            live.source.live(|root| &root.override_api_key),
493            live.source.live(|root| &root.secrets_in_use),
494        );
495
496        let endpoints = config
497            .forwarder_config
498            .build_routable_endpoints()
499            .expect("endpoint should resolve");
500        assert_eq!(endpoints.len(), 1);
501        assert_eq!("mrf-api-key", &*endpoints[0].endpoint().api_key());
502
503        let refresher = ApiKeyRefresher::new(&endpoints, &config.api_keys)
504            .expect("the destination should follow the failover view");
505
506        // The refresher spawns on the ambient supervisor, and the supervisor is what keeps it running for the rest of
507        // the test.
508        let supervisor = TestSupervisor::start("test_forwarder").await;
509        supervisor.scope(async move { refresher.spawn() }).await;
510
511        // Rotate the primary key first: the override does not follow it.
512        live_config.api_key = "rotated-primary-api-key".to_string();
513        live.publisher.publish(live_config.clone());
514
515        live_config.override_api_key = Some("rotated-mrf-api-key".to_string());
516        live.publisher.publish(live_config);
517
518        let endpoint = endpoints[0].endpoint();
519        tokio::time::timeout(std::time::Duration::from_secs(2), async {
520            while &*endpoint.api_key() != "rotated-mrf-api-key" {
521                tokio::task::yield_now().await;
522            }
523        })
524        .await
525        .expect("the endpoint override should follow the failover key");
526    }
527}