Skip to main content

saluki_components/sources/dogstatsd/replay/
reader.rs

1//! Reader for Datadog DogStatsD capture files.
2//!
3//! Decodes a `.dog` or `.dog.zstd` capture file into the sequence of `UnixDogstatsdMsg` records it
4//! contains, plus the optional `TaggerState` trailer.
5
6use std::{
7    fs,
8    io::{BufRead as _, BufReader, Read},
9    path::Path,
10};
11
12use datadog_protos::agent::{TaggerState, UnixDogstatsdMsg};
13use prost::Message;
14use saluki_error::{generic_error, GenericError};
15
16use super::file_header::{file_version, valid_header, DATADOG_HEADER, MIN_NANO_VERSION, MIN_STATE_VERSION};
17
18const ZSTD_MAGIC: [u8; 4] = [0x28, 0xB5, 0x2F, 0xFD];
19const LENGTH_PREFIX_SIZE: usize = 4;
20
21/// Timestamp resolution recorded in a capture file.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum TimestampResolution {
24    /// Timestamps are recorded in whole seconds (file version < 3).
25    Seconds,
26    /// Timestamps are recorded in nanoseconds (file version >= 3).
27    Nanoseconds,
28}
29
30/// Reads back a DogStatsD traffic capture file.
31#[derive(Debug)]
32pub struct TrafficCaptureReader {
33    contents: Vec<u8>,
34    version: u8,
35    offset: usize,
36}
37
38impl TrafficCaptureReader {
39    /// Opens a capture file at the given path.
40    ///
41    /// Detects zstd-compressed inputs by magic bytes and decompresses transparently. Validates the
42    /// Datadog capture header and parses the file version.
43    pub fn from_path(path: &Path) -> Result<Self, GenericError> {
44        let file = fs::File::open(path)
45            .map_err(|e| generic_error!("Failed to read capture file '{}': {}", path.display(), e))?;
46        Self::read_capture(file, &format!("capture file '{}'", path.display()))
47    }
48
49    /// Reads a capture from an already-open source, such as a file descriptor.
50    ///
51    /// Detects zstd-compressed inputs by magic bytes and decompresses transparently. Validates the
52    /// Datadog capture header and parses the file version.
53    ///
54    /// Compressed input is decoded as it is read, so a failing reader also stops decompression.
55    pub fn from_reader(reader: impl Read) -> Result<Self, GenericError> {
56        Self::read_capture(reader, "capture file")
57    }
58
59    fn read_capture(reader: impl Read, source: &str) -> Result<Self, GenericError> {
60        let mut input = BufReader::new(reader);
61        let is_compressed = input
62            .fill_buf()
63            .map_err(|e| generic_error!("Failed to read {source}: {e}"))?
64            .starts_with(&ZSTD_MAGIC);
65
66        let mut contents = Vec::new();
67        if is_compressed {
68            zstd::stream::read::Decoder::with_buffer(input)
69                .and_then(|mut decoder| decoder.read_to_end(&mut contents))
70                .map_err(|e| generic_error!("Failed to decompress {source}: {e}"))?;
71        } else {
72            input
73                .read_to_end(&mut contents)
74                .map_err(|e| generic_error!("Failed to read {source}: {e}"))?;
75        }
76
77        if !valid_header(&contents) {
78            return Err(generic_error!(
79                "{source} does not begin with a valid Datadog capture header."
80            ));
81        }
82
83        let version = file_version(&contents)?;
84
85        Ok(Self {
86            contents,
87            version,
88            offset: DATADOG_HEADER.len(),
89        })
90    }
91
92    /// Returns the capture file version.
93    pub fn version(&self) -> u8 {
94        self.version
95    }
96
97    /// Returns the timestamp resolution implied by the file version.
98    pub fn timestamp_resolution(&self) -> TimestampResolution {
99        if self.version < MIN_NANO_VERSION {
100            TimestampResolution::Seconds
101        } else {
102            TimestampResolution::Nanoseconds
103        }
104    }
105
106    /// Rewinds the record sequence to the first captured DogStatsD record.
107    pub fn rewind(&mut self) {
108        self.offset = DATADOG_HEADER.len();
109    }
110
111    /// Reads the next captured DogStatsD record from the file.
112    ///
113    /// Returns `Ok(None)` when the stream of records is exhausted: at EOF, at the four-byte state
114    /// separator that introduces the tagger trailer, or at a truncated record boundary.
115    pub fn read_next(&mut self) -> Result<Option<UnixDogstatsdMsg>, GenericError> {
116        if self.offset + LENGTH_PREFIX_SIZE > self.contents.len() {
117            return Ok(None);
118        }
119
120        let size_bytes = &self.contents[self.offset..self.offset + LENGTH_PREFIX_SIZE];
121        let size = u32::from_le_bytes(size_bytes.try_into().expect("length prefix is 4 bytes")) as usize;
122        self.offset += LENGTH_PREFIX_SIZE;
123
124        // The writer emits a zero-length prefix to mark the start of the tagger state trailer; treat
125        // that (and any size that would overrun the buffer) as the end of the record stream.
126        if size == 0 || self.offset + size > self.contents.len() {
127            // A zero-length prefix is the legitimate trailer marker. A non-zero `size` that overruns the buffer is a
128            // corrupt/oversized length prefix being silently read as clean EOF, which drops every following
129            // well-formed record. Surface the corrupt case as distinct from a real trailer.
130            saluki_antithesis::always_or_unreachable!(
131                size == 0,
132                "replay read_next stopped at the real trailer, not on a corrupt length prefix",
133                { "size": size, "offset": self.offset, "len": self.contents.len() }
134            );
135
136            return Ok(None);
137        }
138
139        let msg = UnixDogstatsdMsg::decode(&self.contents[self.offset..self.offset + size])
140            .map_err(|e| generic_error!("Failed to decode captured DogStatsD record: {}", e))?;
141        self.offset += size;
142
143        Ok(Some(msg))
144    }
145
146    /// After `read_next` returns `None`, returns whether it stopped at the zero-length state separator.
147    #[cfg(test)]
148    pub(super) fn stopped_at_state_separator(&self) -> bool {
149        self.offset >= DATADOG_HEADER.len() + LENGTH_PREFIX_SIZE
150            && self.contents[self.offset - LENGTH_PREFIX_SIZE..self.offset] == [0; LENGTH_PREFIX_SIZE]
151    }
152
153    /// Reads the tagger state trailer from the end of the capture file.
154    ///
155    /// Returns `Ok(None)` if the file version predates state support, or if the trailer is empty.
156    /// Does not modify the read offset, so it can be called independently of `read_next`.
157    pub fn read_state(&self) -> Result<Option<TaggerState>, GenericError> {
158        if self.version < MIN_STATE_VERSION {
159            return Ok(None);
160        }
161
162        let len = self.contents.len();
163        if len < LENGTH_PREFIX_SIZE {
164            return Ok(None);
165        }
166
167        let size_bytes = &self.contents[len - LENGTH_PREFIX_SIZE..len];
168        let size = u32::from_le_bytes(size_bytes.try_into().expect("length suffix is 4 bytes")) as usize;
169        if size == 0 {
170            return Ok(None);
171        }
172
173        if size + LENGTH_PREFIX_SIZE > len {
174            return Err(generic_error!(
175                "Tagger state trailer size ({}) exceeds capture file length ({}).",
176                size,
177                len
178            ));
179        }
180
181        let state_start = len - LENGTH_PREFIX_SIZE - size;
182        let state = TaggerState::decode(&self.contents[state_start..len - LENGTH_PREFIX_SIZE])
183            .map_err(|e| generic_error!("Failed to decode tagger state trailer: {}", e))?;
184        Ok(Some(state))
185    }
186}
187
188#[cfg(test)]
189mod tests {
190    use std::fs;
191
192    use super::super::test_support::{run_capture, temp_dir};
193    use super::*;
194    use crate::sources::dogstatsd::replay::writer::{CaptureRecord, TrafficCaptureWriter};
195
196    #[test]
197    fn plain_capture_round_trip() {
198        let (_dir, path) = run_capture(
199            &TrafficCaptureWriter::new(1),
200            false,
201            [sample_record(100, b"metric.a:1|c", 11)],
202        );
203
204        let mut reader = TrafficCaptureReader::from_path(&path).expect("reader should open");
205        assert_eq!(reader.version(), 3);
206        assert_eq!(reader.timestamp_resolution(), TimestampResolution::Nanoseconds);
207
208        let msg = reader.read_next().expect("read should succeed").expect("first record");
209        assert_eq!(msg.timestamp, 100);
210        assert_eq!(msg.payload, b"metric.a:1|c");
211        assert_eq!(msg.payload_size, msg.payload.len() as i32);
212        assert_eq!(msg.pid, 11);
213
214        assert!(reader.read_next().expect("read should succeed").is_none());
215    }
216
217    #[test]
218    fn compressed_capture_round_trip() {
219        let (_dir, path) = run_capture(
220            &TrafficCaptureWriter::new(1),
221            true,
222            [
223                sample_record(1, b"metric.a:1|c", 1),
224                sample_record(2, b"metric.b:2|c", 1),
225                sample_record(3, b"metric.c:3|c", 1),
226            ],
227        );
228
229        let mut reader = TrafficCaptureReader::from_path(&path).expect("reader should open");
230
231        for expected_ts in [1, 2, 3] {
232            let msg = reader.read_next().expect("read should succeed").expect("record");
233            assert_eq!(msg.timestamp, expected_ts);
234        }
235
236        assert!(reader.read_next().expect("read should succeed").is_none());
237
238        reader.rewind();
239        let msg = reader
240            .read_next()
241            .expect("read should succeed")
242            .expect("first record after rewind");
243        assert_eq!(msg.timestamp, 1);
244    }
245
246    #[test]
247    fn from_reader_reads_the_opened_capture_after_path_changes() {
248        let (_dir, path) = run_capture(
249            &TrafficCaptureWriter::new(1),
250            false,
251            [sample_record(100, b"metric.a:1|c", 11)],
252        );
253        let file = fs::File::open(&path).expect("capture should open");
254        let replacement = path.with_extension("replacement");
255        fs::write(&replacement, b"not a capture file").expect("replacement capture should be written");
256        fs::rename(&replacement, &path).expect("capture path should be replaced");
257
258        let mut reader = TrafficCaptureReader::from_reader(file).expect("reader should use the opened capture");
259        let msg = reader.read_next().expect("read should succeed").expect("record");
260
261        assert_eq!(msg.payload, b"metric.a:1|c");
262    }
263
264    #[test]
265    fn from_reader_surfaces_input_errors_during_decompression() {
266        let (_dir, path) = run_capture(
267            &TrafficCaptureWriter::new(1),
268            true,
269            [sample_record(1, b"metric.a:1|c", 1)],
270        );
271        let compressed = fs::read(&path).expect("capture readable");
272        let reader = std::io::Read::chain(
273            &compressed[..ZSTD_MAGIC.len() + 1],
274            FailingReader("input failed during decompression"),
275        );
276
277        let error = TrafficCaptureReader::from_reader(reader).expect_err("input failure should stop the read");
278
279        assert!(error.to_string().contains("Failed to decompress"), "{error:#}");
280        assert!(
281            error.to_string().contains("input failed during decompression"),
282            "{error:#}"
283        );
284    }
285
286    #[test]
287    fn read_next_stops_at_state_separator() {
288        let (_dir, path) = run_capture(&TrafficCaptureWriter::new(1), false, [sample_record(7, b"x:1|c", 5)]);
289
290        let mut reader = TrafficCaptureReader::from_path(&path).expect("reader should open");
291        assert!(reader.read_next().expect("first record").is_some());
292
293        // Subsequent calls must yield None rather than attempting to decode the trailer as a record.
294        assert!(reader.read_next().expect("trailer boundary").is_none());
295        assert!(reader.read_next().expect("idempotent EOF").is_none());
296    }
297
298    #[test]
299    fn read_next_reads_records_then_stops_cleanly_when_trailer_is_truncated() {
300        // The previous name ("truncated_record_returns_none") mischaracterized this test: dropping the final bytes
301        // truncates the tagger-state *trailer*, not a record. The single record stays intact, so `read_next` must
302        // still return it and then terminate cleanly at the zero-length separator, rather than erroring on the
303        // damaged trailer.
304        let (_dir, path) = run_capture(
305            &TrafficCaptureWriter::new(1),
306            false,
307            [sample_record(1, b"metric.a:1|c", 7)],
308        );
309
310        let bytes = fs::read(&path).expect("capture readable");
311        let truncated_path = path.with_extension("truncated");
312        fs::write(&truncated_path, &bytes[..bytes.len().saturating_sub(8)]).expect("write truncated");
313
314        let mut reader = TrafficCaptureReader::from_path(&truncated_path).expect("reader should open");
315        let record = reader
316            .read_next()
317            .expect("record read should succeed")
318            .expect("intact record should still be recovered");
319        assert_eq!(record.payload, b"metric.a:1|c");
320        assert_eq!(record.pid, 7);
321        assert!(reader.read_next().expect("clean EOF after truncated trailer").is_none());
322    }
323
324    #[test]
325    fn read_next_treats_corrupt_length_prefix_as_end_of_stream() {
326        // Regression coverage for read_next's documented corrupt/oversized-length branch: a *non-zero* length prefix
327        // that overruns the buffer must be treated as a clean end-of-stream (`Ok(None)`) rather than decoding past the
328        // end of the buffer. This is distinct from the legitimate zero-length trailer marker (covered by
329        // `read_next_stops_at_state_separator`).
330        let (_dir, path) = run_capture(
331            &TrafficCaptureWriter::new(1),
332            false,
333            [sample_record(1, b"metric.a:1|c", 1)],
334        );
335
336        let mut bytes = fs::read(&path).expect("capture readable");
337        // Overwrite the first record's 4-byte little-endian length prefix (immediately after the 8-byte header) with a
338        // value far larger than the remaining file.
339        let prefix_start = DATADOG_HEADER.len();
340        bytes[prefix_start..prefix_start + LENGTH_PREFIX_SIZE].copy_from_slice(&u32::MAX.to_le_bytes());
341        let corrupt_path = path.with_extension("corrupt");
342        fs::write(&corrupt_path, &bytes).expect("write corrupt capture");
343
344        let mut reader = TrafficCaptureReader::from_path(&corrupt_path).expect("reader should open");
345        assert!(
346            reader
347                .read_next()
348                .expect("corrupt length prefix should read as clean EOF")
349                .is_none(),
350            "an oversized length prefix must terminate the record stream, not decode past the buffer"
351        );
352    }
353
354    #[test]
355    fn bad_header_is_rejected() {
356        let dir = temp_dir();
357        let tmp = dir.path().join("bad-header");
358        fs::write(&tmp, b"this is not a capture file").expect("write garbage");
359
360        let err = TrafficCaptureReader::from_path(&tmp).expect_err("bad header should fail");
361        assert!(err.to_string().contains("Datadog capture header"));
362    }
363
364    fn sample_record(timestamp_ns: i64, payload: &[u8], pid: i32) -> CaptureRecord {
365        CaptureRecord {
366            timestamp_ns,
367            payload: payload.to_vec(),
368            pid: Some(pid),
369            container_id: Some(format!("container_id://container-{}", pid)),
370        }
371    }
372
373    struct FailingReader(&'static str);
374
375    impl Read for FailingReader {
376        fn read(&mut self, _buf: &mut [u8]) -> std::io::Result<usize> {
377            Err(std::io::Error::other(self.0))
378        }
379    }
380}