Skip to main content

saluki_components/encoders/datadog/logs/
mod.rs

1use async_trait::async_trait;
2use http::{uri::PathAndQuery, HeaderMap, HeaderName, HeaderValue, Method, Uri};
3use saluki_common::iter::ReusableDeduplicator;
4use saluki_common::time::Timestamp;
5use saluki_core::{
6    accounting::{MemoryBounds, MemoryBoundsBuilder},
7    components::{encoders::*, BuildContext},
8    data_model::{
9        event::{log::Log, Event, EventType},
10        payload::{HttpPayload, Payload, PayloadMetadata, PayloadType},
11        tags::Tag,
12    },
13    observability::ComponentMetricsExt as _,
14    topology::PayloadsDispatcher,
15};
16use saluki_error::{ErrorContext as _, GenericError};
17use saluki_io::compression::CompressionScheme;
18use saluki_metrics::MetricsBuilder;
19use stringtheory::MetaString;
20use tracing::{error, warn};
21
22use crate::common::datadog::{
23    io::RB_BUFFER_CHUNK_SIZE,
24    middleware::formatted_app_name,
25    request_builder::{EndpointEncoder, RequestBuilder},
26    telemetry::ComponentTelemetry,
27    DEFAULT_INTAKE_COMPRESSED_SIZE_LIMIT, DEFAULT_INTAKE_UNCOMPRESSED_SIZE_LIMIT,
28};
29
30const MAX_LOGS_PER_PAYLOAD: usize = 1000;
31
32/// The most tags buffer capacity that the encoder keeps between logs.
33///
34/// The encoder keeps the capacity of the longest tags it has written, so one log with enormous tags would otherwise
35/// stay held for the encoder's lifetime. The limit sits well above the tags of an ordinary log: such a log keeps its
36/// reuse, and a log past it has the excess released before the next log is encoded.
37const TAGS_BUFFER_RETENTION_LIMIT_BYTES: usize = 64 * 1024;
38
39/// The envelope status of a log that has none.
40const DEFAULT_STATUS: &str = "info";
41
42static CONTENT_TYPE_JSON: HeaderValue = HeaderValue::from_static("application/json");
43
44static DD_PROTOCOL_HEADER: HeaderName = HeaderName::from_static("dd-protocol");
45static DD_EVP_ORIGIN_HEADER: HeaderName = HeaderName::from_static("dd-evp-origin");
46static DD_EVP_ORIGIN_VERSION_HEADER: HeaderName = HeaderName::from_static("dd-evp-origin-version");
47static DD_MESSAGE_TIMESTAMP_HEADER: HeaderName = HeaderName::from_static("dd-message-timestamp");
48
49/// The `DD-PROTOCOL` value of the JSON envelope, under which the intake reads only the envelope fields.
50static AGENT_JSON_PROTOCOL: HeaderValue = HeaderValue::from_static("agent-json");
51
52/// Datadog Logs incremental encoder.
53#[derive(Debug)]
54pub struct DatadogLogsConfiguration {
55    /// Compression kind for Logs payloads.
56    compressor_kind: String,
57
58    /// The compression level to use when `zstd` is the algorithm.
59    ///
60    /// Ignored for algorithms other than `zstd`.
61    zstd_level: i32,
62
63    /// Hostname for the envelope of a log that has none.
64    default_hostname: MetaString,
65
66    /// Name of the sender, for the `DD-EVP-ORIGIN` header.
67    origin: String,
68
69    /// Version of the sender, for the `DD-EVP-ORIGIN-VERSION` header.
70    ///
71    /// This is the bare version, such as `1.9.0`: the intake drops a value with characters such as `/` in it.
72    origin_version: String,
73
74    /// Source of the current time, for the envelope `timestamp`.
75    clock: Clock,
76}
77
78impl DatadogLogsConfiguration {
79    /// Creates a new `DatadogLogsConfiguration`.
80    ///
81    /// The `DD-EVP-ORIGIN` and `DD-EVP-ORIGIN-VERSION` headers name the application, from its registered details.
82    pub fn new(compressor_kind: impl Into<String>, zstd_level: i32) -> Self {
83        let app_details = saluki_metadata::get_app_details();
84        Self {
85            compressor_kind: compressor_kind.into(),
86            zstd_level,
87            default_hostname: MetaString::empty(),
88            origin: formatted_app_name(app_details),
89            origin_version: app_details.version().raw().to_string(),
90            clock: Timestamp::now,
91        }
92    }
93
94    /// Sets the values of the `DD-EVP-ORIGIN` and `DD-EVP-ORIGIN-VERSION` headers, so tests can pin them.
95    #[cfg(test)]
96    pub(crate) fn with_origin(mut self, origin: impl Into<String>, origin_version: impl Into<String>) -> Self {
97        self.origin = origin.into();
98        self.origin_version = origin_version.into();
99        self
100    }
101
102    /// Sets the hostname for the envelope of a log that has none.
103    ///
104    /// Only the envelope uses it: a log's rendered content is left as it is. Defaults to an empty hostname.
105    pub fn with_default_hostname(mut self, default_hostname: impl Into<MetaString>) -> Self {
106        self.default_hostname = default_hostname.into();
107        self
108    }
109
110    /// Sets the source of the current time, so tests can pin the envelope `timestamp`.
111    #[cfg(test)]
112    pub(crate) fn with_clock(mut self, clock: Clock) -> Self {
113        self.clock = clock;
114        self
115    }
116}
117
118#[async_trait]
119impl IncrementalEncoderBuilder for DatadogLogsConfiguration {
120    type Output = DatadogLogs;
121
122    fn input_event_type(&self) -> EventType {
123        EventType::Log
124    }
125
126    fn output_payload_type(&self) -> PayloadType {
127        PayloadType::Http
128    }
129
130    async fn build(&self, context: BuildContext) -> Result<Self::Output, GenericError> {
131        let metrics_builder = MetricsBuilder::from_component_context(context.component_context());
132        let telemetry = ComponentTelemetry::from_builder(&metrics_builder);
133        let compression_scheme = CompressionScheme::new(&self.compressor_kind, self.zstd_level);
134
135        let origin =
136            HeaderValue::from_str(&self.origin).error_context("Invalid origin for the `DD-EVP-ORIGIN` header.")?;
137        let origin_version = HeaderValue::from_str(&self.origin_version)
138            .error_context("Invalid origin version for the `DD-EVP-ORIGIN-VERSION` header.")?;
139        let headers = vec![
140            (DD_PROTOCOL_HEADER.clone(), AGENT_JSON_PROTOCOL.clone()),
141            (DD_EVP_ORIGIN_HEADER.clone(), origin),
142            (DD_EVP_ORIGIN_VERSION_HEADER.clone(), origin_version),
143        ];
144
145        let mut request_builder = RequestBuilder::new(
146            LogsEndpointEncoder::new(self.default_hostname.clone(), headers, self.clock),
147            compression_scheme,
148            RB_BUFFER_CHUNK_SIZE,
149        )
150        .await?;
151        request_builder.with_max_inputs_per_payload(MAX_LOGS_PER_PAYLOAD);
152
153        Ok(DatadogLogs {
154            request_builder,
155            telemetry,
156        })
157    }
158}
159
160impl MemoryBounds for DatadogLogsConfiguration {
161    fn specify_bounds(&self, builder: &mut MemoryBoundsBuilder) {
162        // TODO: How do we properly represent the requests we can generate that may be sitting around in-flight?
163
164        builder
165            .minimum()
166            .with_single_value::<DatadogLogs>("component struct")
167            .with_fixed_amount("tags buffer", TAGS_BUFFER_RETENTION_LIMIT_BYTES);
168        builder.firm().with_array::<Log>("logs buffer", MAX_LOGS_PER_PAYLOAD);
169    }
170}
171
172pub struct DatadogLogs {
173    request_builder: RequestBuilder<LogsEndpointEncoder>,
174    telemetry: ComponentTelemetry,
175}
176
177#[async_trait]
178impl IncrementalEncoder for DatadogLogs {
179    async fn process_event(&mut self, event: Event) -> Result<ProcessResult, GenericError> {
180        let log: Log = match event {
181            Event::Log(log) => log,
182            _ => return Ok(ProcessResult::Continue),
183        };
184        match self.request_builder.encode(log).await {
185            Ok(None) => Ok(ProcessResult::Continue),
186            Ok(Some(log)) => Ok(ProcessResult::FlushRequired(Event::Log(log))),
187            Err(e) => {
188                if e.is_recoverable() {
189                    warn!(error = %e, "Failed to encode Datadog log due to recoverable error. Continuing...");
190
191                    // TODO: Get the actual number of events dropped from the error itself.
192                    self.telemetry.events_dropped_encoder().increment(1);
193                    Ok(ProcessResult::Continue)
194                } else {
195                    Err(e).error_context("Failed to encode Datadog log due to unrecoverable error.")
196                }
197            }
198        }
199    }
200
201    async fn flush(&mut self, dispatcher: &PayloadsDispatcher) -> Result<usize, FlushError> {
202        let mut dispatched_events = 0;
203        let pending_events = self.request_builder.pending_inputs();
204
205        let maybe_requests = self.request_builder.flush().await;
206        for maybe_request in maybe_requests {
207            match maybe_request {
208                Ok((events, _data_points, _uncompressed_len, request)) => {
209                    let payload_meta = PayloadMetadata::from_event_count(events);
210                    let http_payload = HttpPayload::new(payload_meta, request);
211                    let payload = Payload::Http(http_payload);
212                    dispatcher
213                        .dispatch(payload)
214                        .await
215                        .map_err(|source| FlushError::new(dispatched_events, source))?;
216                    dispatched_events += events;
217                }
218                Err(e) => error!(error = %e, "Failed to build Datadog logs payload. Continuing..."),
219            }
220        }
221
222        // Events that were queued but not dispatched were in a payload that couldn't be built, such as one that exceeded
223        // the size limit and couldn't be split. They're gone, so report them as dropped.
224        let dropped_events = pending_events.saturating_sub(dispatched_events);
225        if dropped_events > 0 {
226            self.telemetry.events_dropped_encoder().increment(dropped_events as u64);
227        }
228
229        Ok(dispatched_events)
230    }
231}
232
233/// Source of the current time, which fails when the system clock is out of range.
234type Clock = fn() -> Result<Timestamp, GenericError>;
235
236#[derive(Debug)]
237struct LogsEndpointEncoder {
238    tags_deduplicator: ReusableDeduplicator<Tag>,
239    tags_buffer: String,
240    default_hostname: MetaString,
241    headers: Vec<(HeaderName, HeaderValue)>,
242    clock: Clock,
243}
244
245impl LogsEndpointEncoder {
246    fn new(default_hostname: MetaString, headers: Vec<(HeaderName, HeaderValue)>, clock: Clock) -> Self {
247        Self {
248            tags_deduplicator: ReusableDeduplicator::new(),
249            tags_buffer: String::new(),
250            default_hostname,
251            headers,
252            clock,
253        }
254    }
255
256    /// Writes the envelope of a log.
257    ///
258    /// The envelope has the same fields, in the same order, as the logs intake's JSON envelope: the message, the
259    /// status, the time the log was encoded in milliseconds, the hostname, the service, the source, and the tags. Every
260    /// field is present, empty when the log has no value for it, except that a log without a hostname gets the
261    /// default hostname, and the time is left out when the system clock is out of range. The message is written as it
262    /// is: a log's producer renders whatever content the message should carry, such as a JSON object holding the log's
263    /// properties, so the log's additional properties aren't written.
264    fn write_envelope(&mut self, log: &Log, buffer: &mut Vec<u8>) -> Result<(), serde_json::Error> {
265        // A log without a status is sent as `info`.
266        let status = if log.status().is_empty() {
267            DEFAULT_STATUS
268        } else {
269            log.status()
270        };
271        let source = log.source().as_deref().unwrap_or_default();
272
273        buffer.extend_from_slice(b"{\"message\":");
274        serde_json::to_writer(&mut *buffer, log.message())?;
275        buffer.extend_from_slice(b",\"status\":");
276        serde_json::to_writer(&mut *buffer, status)?;
277        if let Ok(timestamp) = (self.clock)() {
278            buffer.extend_from_slice(b",\"timestamp\":");
279            buffer.extend_from_slice(itoa::Buffer::new().format(timestamp.as_unix_millis()).as_bytes());
280        }
281        buffer.extend_from_slice(b",\"hostname\":");
282        // A log without a hostname gets the default hostname, in the envelope only.
283        let hostname = if log.hostname().is_empty() {
284            &*self.default_hostname
285        } else {
286            log.hostname()
287        };
288        serde_json::to_writer(&mut *buffer, hostname)?;
289        buffer.extend_from_slice(b",\"service\":");
290        serde_json::to_writer(&mut *buffer, log.service())?;
291        buffer.extend_from_slice(b",\"ddsource\":");
292        serde_json::to_writer(&mut *buffer, source)?;
293
294        // ddtags: comma-separated, deduplicated
295        buffer.extend_from_slice(b",\"ddtags\":");
296        self.tags_buffer.clear();
297        for (index, tag) in self.tags_deduplicator.deduplicated(log.tags().into_iter()).enumerate() {
298            if index > 0 {
299                self.tags_buffer.push(',');
300            }
301            self.tags_buffer.push_str(tag.as_str());
302        }
303        let written = serde_json::to_writer(&mut *buffer, &self.tags_buffer);
304        if self.tags_buffer.capacity() > TAGS_BUFFER_RETENTION_LIMIT_BYTES {
305            self.tags_buffer.clear();
306            self.tags_buffer.shrink_to(TAGS_BUFFER_RETENTION_LIMIT_BYTES);
307        }
308        written?;
309        buffer.push(b'}');
310        Ok(())
311    }
312}
313
314impl EndpointEncoder for LogsEndpointEncoder {
315    type Input = Log;
316    type EncodeError = serde_json::Error;
317
318    fn encoder_name() -> &'static str {
319        "logs"
320    }
321
322    fn compressed_size_limit(&self) -> usize {
323        DEFAULT_INTAKE_COMPRESSED_SIZE_LIMIT
324    }
325
326    fn uncompressed_size_limit(&self) -> usize {
327        DEFAULT_INTAKE_UNCOMPRESSED_SIZE_LIMIT
328    }
329
330    fn get_payload_prefix(&self) -> Option<&'static [u8]> {
331        Some(b"[")
332    }
333
334    fn get_payload_suffix(&self) -> Option<&'static [u8]> {
335        Some(b"]")
336    }
337
338    fn get_input_separator(&self) -> Option<&'static [u8]> {
339        Some(b",")
340    }
341
342    fn encode(&mut self, input: &Self::Input, buffer: &mut Vec<u8>) -> Result<(), Self::EncodeError> {
343        self.write_envelope(input, buffer)
344    }
345
346    fn endpoint_uri(&self) -> Uri {
347        PathAndQuery::from_static("/api/v2/logs").into()
348    }
349
350    fn endpoint_method(&self) -> Method {
351        Method::POST
352    }
353
354    fn content_type(&self) -> HeaderValue {
355        CONTENT_TYPE_JSON.clone()
356    }
357
358    fn additional_headers(&self) -> &[(HeaderName, HeaderValue)] {
359        &self.headers
360    }
361
362    fn add_input_headers(&self, inputs: &[Self::Input], headers: &mut HeaderMap) {
363        // `dd-message-timestamp` is when the last log of the request entered the pipeline, in milliseconds. It's left
364        // out when that log's source didn't record it.
365        if let Some(timestamp_ns) = inputs.last().and_then(Log::ingestion_timestamp) {
366            let timestamp_ms = timestamp_ns / 1_000_000;
367            headers.insert(DD_MESSAGE_TIMESTAMP_HEADER.clone(), HeaderValue::from(timestamp_ms));
368        }
369    }
370}
371
372#[cfg(test)]
373mod characterization;
374
375#[cfg(test)]
376mod tests {
377    use std::collections::HashMap;
378
379    use saluki_common::time::Timestamp;
380    use saluki_core::data_model::{
381        event::log::Log,
382        tags::{Tag, TagSet},
383    };
384    use saluki_error::{generic_error, GenericError};
385    use serde_json::json;
386    use stringtheory::MetaString;
387
388    use super::{LogsEndpointEncoder, TAGS_BUFFER_RETENTION_LIMIT_BYTES};
389
390    /// The encoder's clock in these tests, and the envelope `timestamp` it gives.
391    const NOW: &str = "2026-01-02T03:04:05.678Z";
392    const NOW_MS: i64 = 1_767_323_045_678;
393
394    fn fixed_clock() -> Result<Timestamp, GenericError> {
395        Ok(NOW.parse().expect("NOW should be RFC3339"))
396    }
397
398    fn envelope(log: &Log) -> String {
399        let mut encoder = LogsEndpointEncoder::new(MetaString::empty(), Vec::new(), fixed_clock);
400        let mut buffer = Vec::new();
401        encoder
402            .write_envelope(log, &mut buffer)
403            .expect("envelope should serialize");
404        String::from_utf8(buffer).expect("envelope should be UTF-8")
405    }
406
407    fn tag_set<const N: usize>(tags: [&'static str; N]) -> TagSet {
408        tags.into_iter().map(Tag::from_static).collect()
409    }
410
411    #[test]
412    fn releases_the_excess_of_an_oversized_tags_buffer() {
413        let mut encoder = LogsEndpointEncoder::new(MetaString::empty(), Vec::new(), fixed_clock);
414        let mut buffer = Vec::new();
415
416        let ordinary = Log::new("m").with_tags(tag_set(["env:prod"]));
417        encoder
418            .write_envelope(&ordinary, &mut buffer)
419            .expect("envelope should serialize");
420        let ordinary_capacity = encoder.tags_buffer.capacity();
421        assert!(ordinary_capacity >= "env:prod".len());
422        assert!(ordinary_capacity <= TAGS_BUFFER_RETENTION_LIMIT_BYTES);
423
424        // An ordinary log keeps the buffer it grew.
425        encoder
426            .write_envelope(&ordinary, &mut buffer)
427            .expect("envelope should serialize");
428        assert_eq!(encoder.tags_buffer.capacity(), ordinary_capacity);
429
430        // An oversized log is written in full, then has the excess released.
431        let tag = format!("big:{}", "x".repeat(2 * TAGS_BUFFER_RETENTION_LIMIT_BYTES));
432        let oversized = Log::new("m").with_tags([Tag::from(tag.clone())].into_iter().collect::<TagSet>());
433        encoder
434            .write_envelope(&oversized, &mut buffer)
435            .expect("envelope should serialize");
436        assert!(String::from_utf8_lossy(&buffer).contains(&tag));
437        assert!(encoder.tags_buffer.capacity() <= TAGS_BUFFER_RETENTION_LIMIT_BYTES);
438    }
439
440    #[test]
441    fn the_default_clock_writes_the_current_time_in_milliseconds() {
442        let since_epoch_ms = || {
443            std::time::SystemTime::now()
444                .duration_since(std::time::UNIX_EPOCH)
445                .expect("clock should be after the epoch")
446                .as_millis()
447        };
448
449        let mut encoder = LogsEndpointEncoder::new(MetaString::empty(), Vec::new(), Timestamp::now);
450        let mut buffer = Vec::new();
451        let before = since_epoch_ms();
452        encoder
453            .write_envelope(&Log::new("m"), &mut buffer)
454            .expect("envelope should serialize");
455        let after = since_epoch_ms();
456
457        let envelope: serde_json::Value = serde_json::from_slice(&buffer).expect("envelope should be JSON");
458        let timestamp = u128::from(envelope["timestamp"].as_u64().expect("timestamp should be a number"));
459        assert!(
460            (before..=after).contains(&timestamp),
461            "{} not in {}..={}",
462            timestamp,
463            before,
464            after
465        );
466    }
467
468    #[test]
469    fn writes_every_envelope_field_in_order() {
470        assert_eq!(fixed_clock().expect("clock should be fixed").as_unix_millis(), NOW_MS);
471        let log = Log::new("hello world")
472            .with_status("Err")
473            .with_source(MetaString::from_static("nginx"))
474            .with_hostname(MetaString::from_static("host-a"))
475            .with_service(MetaString::from_static("web"))
476            .with_tags(tag_set(["env:prod", "team:core", "env:prod"]));
477
478        assert_eq!(
479            envelope(&log),
480            format!(
481                r#"{{"message":"hello world","status":"Err","timestamp":{},"hostname":"host-a","service":"web","ddsource":"nginx","ddtags":"env:prod,team:core"}}"#,
482                NOW_MS
483            )
484        );
485    }
486
487    #[test]
488    fn writes_empty_fields_and_the_default_status() {
489        assert_eq!(
490            envelope(&Log::new("bare")),
491            format!(
492                r#"{{"message":"bare","status":"info","timestamp":{},"hostname":"","service":"","ddsource":"","ddtags":""}}"#,
493                NOW_MS
494            )
495        );
496    }
497
498    #[test]
499    fn leaves_out_the_timestamp_when_the_clock_is_out_of_range() {
500        fn broken_clock() -> Result<Timestamp, GenericError> {
501            Err(generic_error!("System clock is outside of the supported range."))
502        }
503
504        let mut encoder = LogsEndpointEncoder::new(MetaString::empty(), Vec::new(), broken_clock);
505        let mut buffer = Vec::new();
506        encoder
507            .write_envelope(&Log::new("bare"), &mut buffer)
508            .expect("envelope should serialize");
509        assert_eq!(
510            String::from_utf8(buffer).expect("envelope should be UTF-8"),
511            r#"{"message":"bare","status":"info","hostname":"","service":"","ddsource":"","ddtags":""}"#
512        );
513    }
514
515    #[test]
516    fn uses_the_default_hostname_only_when_the_log_has_none() {
517        let mut encoder = LogsEndpointEncoder::new(MetaString::from_static("default-host"), Vec::new(), fixed_clock);
518        let content = r#"{"message":"hi","status":""}"#;
519        let mut write = |log: &Log| {
520            let mut buffer = Vec::new();
521            encoder
522                .write_envelope(log, &mut buffer)
523                .expect("envelope should serialize");
524            serde_json::from_slice::<serde_json::Value>(&buffer).expect("envelope should be JSON")
525        };
526
527        // The default hostname goes only into the envelope: the rendered content is sent as it is.
528        let without_host = write(&Log::new(content));
529        assert_eq!(without_host["hostname"], json!("default-host"));
530        assert_eq!(without_host["message"], json!(content));
531
532        let with_host = write(&Log::new("hello").with_hostname(MetaString::from_static("log-host")));
533        assert_eq!(with_host["hostname"], json!("log-host"));
534    }
535
536    #[test]
537    fn writes_the_message_as_it_is_without_properties() {
538        // The producer renders the content; the encoder neither wraps it nor adds the properties or an `@timestamp`.
539        let mut properties = HashMap::new();
540        properties.insert(MetaString::from_static("custom"), json!(42));
541        let log = Log::new("ignored")
542            .with_additional_properties(properties)
543            .with_message(r#"{"custom":42,"message":"hi"}"#)
544            .with_status("debug");
545
546        assert_eq!(
547            envelope(&log),
548            format!(
549                r#"{{"message":"{{\"custom\":42,\"message\":\"hi\"}}","status":"debug","timestamp":{},"hostname":"","service":"","ddsource":"","ddtags":""}}"#,
550                NOW_MS
551            )
552        );
553    }
554
555    #[test]
556    fn escapes_strings_as_serde_json_does() {
557        // `serde_json` doesn't escape `<`, `>`, `&`, or U+2028, which Go escapes (`gap/json-encoding`).
558        let log = Log::new("<a href=\"x\">&amp;</a> \u{2028} \t")
559            .with_service(MetaString::from_static("s<v>c"))
560            .with_tags(tag_set(["a&b"]));
561
562        assert_eq!(
563            envelope(&log),
564            format!(
565                "{{\"message\":\"<a href=\\\"x\\\">&amp;</a> \u{2028} \\t\",\"status\":\"info\",\"timestamp\":{},\"hostname\":\"\",\"service\":\"s<v>c\",\"ddsource\":\"\",\"ddtags\":\"a&b\"}}",
566                NOW_MS
567            )
568        );
569    }
570}