Skip to main content

saluki_components/encoders/datadog/service_checks/
mod.rs

1use async_trait::async_trait;
2use http::{uri::PathAndQuery, HeaderValue, Method, Uri};
3use saluki_core::accounting::{MemoryBounds, MemoryBoundsBuilder};
4use saluki_core::{
5    components::{encoders::*, BuildContext},
6    data_model::{
7        event::{service_check::ServiceCheck, Event, EventType},
8        payload::{HttpPayload, Payload, PayloadMetadata, PayloadType},
9    },
10    observability::ComponentMetricsExt as _,
11    topology::PayloadsDispatcher,
12};
13use saluki_error::{ErrorContext as _, GenericError};
14use saluki_io::compression::CompressionScheme;
15use saluki_metrics::MetricsBuilder;
16use tracing::{debug, error, warn};
17
18use crate::common::datadog::{
19    clamp_payload_limits,
20    io::RB_BUFFER_CHUNK_SIZE,
21    request_builder::{EndpointEncoder, RequestBuilder},
22    telemetry::ComponentTelemetry,
23    DEFAULT_SERIALIZER_COMPRESSED_SIZE_LIMIT, DEFAULT_SERIALIZER_UNCOMPRESSED_SIZE_LIMIT,
24};
25
26const MAX_SERVICE_CHECKS_PER_PAYLOAD: usize = 100;
27
28static CONTENT_TYPE_JSON: HeaderValue = HeaderValue::from_static("application/json");
29
30/// Datadog Service Checks incremental encoder.
31///
32/// Generates Datadog Service Checks payloads for the Datadog platform.
33#[derive(Debug)]
34pub struct DatadogServiceChecksConfiguration {
35    /// Maximum compressed size, in bytes, of a service check payload.
36    ///
37    /// This matches the Datadog Agent's generic payload limit for service checks. The effective value is
38    /// clamped to the Agent's default intake-safe limit of 2,621,440 bytes, so larger configured values do not allow
39    /// payloads that intake may reject. If set to `0`, every non-empty compressed payload exceeds the limit and is
40    /// dropped during flush.
41    ///
42    /// Defaults to 2,621,440 bytes.
43    pub max_payload_size: usize,
44
45    /// Maximum uncompressed size, in bytes, of a service check payload.
46    ///
47    /// This matches the Datadog Agent's generic payload limit for service checks. The effective value is
48    /// clamped to the Agent's default intake-safe limit of 4,194,304 bytes, so larger configured values do not allow
49    /// payloads that intake may reject. Values smaller than the minimum endpoint framing size prevent the request
50    /// builder from starting.
51    ///
52    /// Defaults to 4,194,304 bytes.
53    pub max_uncompressed_payload_size: usize,
54
55    /// Compression kind to use for the request payloads.
56    ///
57    /// Defaults to `zstd`.
58    pub compressor_kind: String,
59
60    /// The compression level to use when `zstd` is the algorithm.
61    ///
62    /// Ignored for algorithms other than `zstd`.
63    pub zstd_level: i32,
64
65    /// Whether to log service check payload contents before encoding.
66    ///
67    /// This logs decoded service check objects, not the encoded HTTP body.
68    ///
69    /// Defaults to `false`.
70    pub log_payloads: bool,
71}
72
73#[async_trait]
74impl IncrementalEncoderBuilder for DatadogServiceChecksConfiguration {
75    type Output = DatadogServiceChecks;
76
77    fn input_event_type(&self) -> EventType {
78        EventType::ServiceCheck
79    }
80
81    fn output_payload_type(&self) -> PayloadType {
82        PayloadType::Http
83    }
84
85    async fn build(&self, context: BuildContext) -> Result<Self::Output, GenericError> {
86        let metrics_builder = MetricsBuilder::from_component_context(context.component_context());
87        let telemetry = ComponentTelemetry::from_builder(&metrics_builder);
88        let compression_scheme = CompressionScheme::new(&self.compressor_kind, self.zstd_level);
89
90        // Create our request builder.
91        let mut request_builder =
92            RequestBuilder::new(ServiceChecksEndpointEncoder, compression_scheme, RB_BUFFER_CHUNK_SIZE).await?;
93        let (uncompressed_limit, compressed_limit) = clamp_payload_limits(
94            self.max_uncompressed_payload_size,
95            self.max_payload_size,
96            DEFAULT_SERIALIZER_UNCOMPRESSED_SIZE_LIMIT,
97            DEFAULT_SERIALIZER_COMPRESSED_SIZE_LIMIT,
98        );
99        request_builder.with_len_limits(uncompressed_limit, compressed_limit)?;
100        request_builder.with_max_inputs_per_payload(MAX_SERVICE_CHECKS_PER_PAYLOAD);
101
102        Ok(DatadogServiceChecks {
103            request_builder,
104            telemetry,
105            log_payloads: self.log_payloads,
106        })
107    }
108}
109
110impl MemoryBounds for DatadogServiceChecksConfiguration {
111    fn specify_bounds(&self, builder: &mut MemoryBoundsBuilder) {
112        // TODO: How do we properly represent the requests we can generate that may be sitting around in-flight?
113        //
114        // Theoretically, we'll end up being limited by the size of the downstream forwarder's interconnect, and however
115        // many payloads it will buffer internally... so realistically the firm limit boils down to the forwarder itself
116        // but we'll have a hard time in the forwarder knowing the maximum size of any given payload being sent in, which
117        // then makes it hard to calculate a proper firm bound even though we know the rest of the values required to
118        // calculate the firm bound.
119        builder
120            .minimum()
121            .with_single_value::<DatadogServiceChecks>("component struct");
122
123        builder
124            .firm()
125            // Capture the size of the "split re-encode" buffer in the request builder, which is where we keep owned
126            // versions of events that we encode in case we need to actually re-encode them during a split operation.
127            .with_array::<ServiceCheck>("service checks split re-encode buffer", MAX_SERVICE_CHECKS_PER_PAYLOAD);
128    }
129}
130
131pub struct DatadogServiceChecks {
132    request_builder: RequestBuilder<ServiceChecksEndpointEncoder>,
133    telemetry: ComponentTelemetry,
134    log_payloads: bool,
135}
136
137#[async_trait]
138impl IncrementalEncoder for DatadogServiceChecks {
139    async fn process_event(&mut self, event: Event) -> Result<ProcessResult, GenericError> {
140        let service_check = match event.try_into_service_check() {
141            Some(eventd) => eventd,
142            None => return Ok(ProcessResult::Continue),
143        };
144
145        if self.log_payloads {
146            debug!(?service_check, "Flushing service check.");
147        }
148
149        match self.request_builder.encode(service_check).await {
150            Ok(None) => Ok(ProcessResult::Continue),
151            Ok(Some(service_check)) => Ok(ProcessResult::FlushRequired(Event::ServiceCheck(service_check))),
152            Err(e) => {
153                if e.is_recoverable() {
154                    warn!(error = %e, "Failed to encode Datadog service check due to recoverable error. Continuing...");
155
156                    // TODO: Get the actual number of events dropped from the error itself.
157                    self.telemetry.events_dropped_encoder().increment(1);
158
159                    Ok(ProcessResult::Continue)
160                } else {
161                    Err(e).error_context("Failed to encode Datadog service check due to unrecoverable error.")
162                }
163            }
164        }
165    }
166
167    async fn flush(&mut self, dispatcher: &PayloadsDispatcher) -> Result<usize, FlushError> {
168        let mut dispatched_events = 0;
169        let pending_events = self.request_builder.pending_inputs();
170
171        let maybe_requests = self.request_builder.flush().await;
172        for maybe_request in maybe_requests {
173            match maybe_request {
174                Ok((events, _data_points, _uncompressed_len, request)) => {
175                    let payload_meta = PayloadMetadata::from_event_count(events);
176                    let http_payload = HttpPayload::new(payload_meta, request);
177                    let payload = Payload::Http(http_payload);
178
179                    dispatcher
180                        .dispatch(payload)
181                        .await
182                        .map_err(|source| FlushError::new(dispatched_events, source))?;
183                    dispatched_events += events;
184                }
185                Err(e) => error!(error = %e, "Failed to build Datadog service checks payload. Continuing..."),
186            }
187        }
188
189        // Events that were queued but not dispatched were in a payload that couldn't be built, such as one that exceeded
190        // the size limit and couldn't be split. They're gone, so report them as dropped.
191        let dropped_events = pending_events.saturating_sub(dispatched_events);
192        if dropped_events > 0 {
193            self.telemetry.events_dropped_encoder().increment(dropped_events as u64);
194        }
195
196        Ok(dispatched_events)
197    }
198}
199
200#[derive(Debug)]
201struct ServiceChecksEndpointEncoder;
202
203impl EndpointEncoder for ServiceChecksEndpointEncoder {
204    type Input = ServiceCheck;
205    type EncodeError = serde_json::Error;
206
207    fn encoder_name() -> &'static str {
208        "service_check"
209    }
210
211    fn compressed_size_limit(&self) -> usize {
212        DEFAULT_SERIALIZER_COMPRESSED_SIZE_LIMIT
213    }
214
215    fn uncompressed_size_limit(&self) -> usize {
216        DEFAULT_SERIALIZER_UNCOMPRESSED_SIZE_LIMIT
217    }
218
219    fn encode(&mut self, input: &Self::Input, buffer: &mut Vec<u8>) -> Result<(), Self::EncodeError> {
220        serde_json::to_writer(buffer, input)
221    }
222
223    fn get_payload_prefix(&self) -> Option<&'static [u8]> {
224        Some(b"[")
225    }
226
227    fn get_payload_suffix(&self) -> Option<&'static [u8]> {
228        Some(b"]")
229    }
230
231    fn get_input_separator(&self) -> Option<&'static [u8]> {
232        Some(b",")
233    }
234
235    fn endpoint_uri(&self) -> Uri {
236        PathAndQuery::from_static("/api/v1/check_run").into()
237    }
238
239    fn endpoint_method(&self) -> Method {
240        Method::POST
241    }
242
243    fn content_type(&self) -> HeaderValue {
244        CONTENT_TYPE_JSON.clone()
245    }
246}
247
248#[cfg(test)]
249mod tests {
250    use std::time::Duration;
251
252    use saluki_core::{
253        components::test_util::TestComponentDriver,
254        data_model::event::service_check::{CheckStatus, ServiceCheck},
255    };
256    use serde_json::Value as JsonValue;
257
258    use super::*;
259    use crate::common::datadog::test_util::{decompressed_bodies, incompressible_string};
260    use crate::encoders::BufferedIncrementalConfiguration;
261
262    /// Returns the default service checks encoder settings.
263    fn service_checks_configuration() -> DatadogServiceChecksConfiguration {
264        DatadogServiceChecksConfiguration {
265            max_payload_size: DEFAULT_SERIALIZER_COMPRESSED_SIZE_LIMIT,
266            max_uncompressed_payload_size: DEFAULT_SERIALIZER_UNCOMPRESSED_SIZE_LIMIT,
267            compressor_kind: "zstd".to_string(),
268            zstd_level: 3,
269            log_payloads: false,
270        }
271    }
272
273    /// Encodes `checks` with the encoder set up as the topology sets it up, and returns the decompressed request
274    /// bodies.
275    ///
276    /// `checks` must fit in a single event buffer, so that the requests depend only on the checks and not on timing.
277    async fn encode_service_checks(checks: Vec<ServiceCheck>) -> Vec<(usize, Vec<u8>)> {
278        assert!(checks.len() <= 1024, "service checks must fit in a single event buffer");
279
280        // The default encoder flush timeout.
281        let config = BufferedIncrementalConfiguration::new(service_checks_configuration(), Duration::from_secs(2));
282        let (control, mut payloads) = TestComponentDriver::encoder(config)
283            .await
284            .expect("service checks encoder should build");
285        control.send_events(checks.into_iter().map(Event::ServiceCheck)).await;
286        control
287            .shutdown()
288            .await
289            .expect("service checks encoder should stop cleanly");
290
291        decompressed_bodies(payloads.collect().await).await
292    }
293
294    fn service_check(index: usize, message: String) -> ServiceCheck {
295        ServiceCheck::new(format!("check.{:03}", index), CheckStatus::Ok).with_message(Some(message.into()))
296    }
297
298    /// Asserts that every request body is a JSON array holding as many service checks as its metadata counts, and
299    /// that the requests hold `expected_checks` service checks in total.
300    fn assert_valid_json_requests(requests: &[(usize, Vec<u8>)], expected_checks: usize) {
301        for (index, (event_count, body)) in requests.iter().enumerate() {
302            let tail = String::from_utf8_lossy(&body[body.len().saturating_sub(16)..]);
303            let checks = serde_json::from_slice::<Vec<JsonValue>>(body).unwrap_or_else(|e| {
304                panic!(
305                    "request {} isn't a valid JSON array ({}), it ends with {:?}",
306                    index, e, tail
307                )
308            });
309            assert_eq!(
310                *event_count,
311                checks.len(),
312                "request {} metadata should count its service checks",
313                index
314            );
315        }
316        assert_eq!(requests.iter().map(|(count, _)| count).sum::<usize>(), expected_checks);
317    }
318
319    #[tokio::test]
320    async fn requests_split_at_compressed_size_estimate_are_valid_json() {
321        // About 3.8 MB of content that barely compresses, so the compressed size estimate rejects a service check
322        // before the 100-check cap or the uncompressed limit is reached.
323        let checks = (0..95)
324            .map(|index| service_check(index, incompressible_string(40_000, index as u64)))
325            .collect::<Vec<_>>();
326
327        let requests = encode_service_checks(checks).await;
328        assert!(requests.len() > 1, "the service checks should be split across requests");
329        assert_valid_json_requests(&requests, 95);
330    }
331
332    #[tokio::test]
333    async fn requests_split_at_uncompressed_size_limit_are_valid_json() {
334        // About 4.75 MB of content that compresses to almost nothing, so the 4 MiB uncompressed limit rejects a
335        // service check before the 100-check cap or the compressed size estimate is reached.
336        let checks = (0..95)
337            .map(|index| service_check(index, "a".repeat(50_000)))
338            .collect::<Vec<_>>();
339
340        let requests = encode_service_checks(checks).await;
341        assert!(requests.len() > 1, "the service checks should be split across requests");
342        assert_valid_json_requests(&requests, 95);
343    }
344
345    #[tokio::test]
346    async fn request_after_a_check_that_cannot_fit_with_the_framing_is_valid_json() {
347        // A service check whose encoding fits under the uncompressed limit by itself, but not once the `[` and `]`
348        // around it are added, is rejected even by an empty payload, and dropped after the retry.
349        let limit = service_checks_configuration().max_uncompressed_payload_size;
350        let base_len = serde_json::to_vec(&service_check(0, "a".to_string())).unwrap().len();
351        let oversized = service_check(0, "a".repeat(limit - base_len));
352        assert_eq!(serde_json::to_vec(&oversized).unwrap().len(), limit - 1);
353
354        let requests = encode_service_checks(vec![oversized, service_check(1, "after".to_string())]).await;
355        assert_valid_json_requests(&requests, 1);
356    }
357}