Skip to main content

tsdb_reader/chunks/
segment.rs

1//! One chunk segment file: record layout and zero-copy record access.
2
3use crate::error::{Error, Result};
4use crate::varint;
5
6/// Magic number at the start of every chunk segment.
7pub(crate) const MAGIC_CHUNKS: u32 = 0x85BD_40DD;
8/// Size of a chunk segment header: magic(4) + version(1) + padding(3).
9pub const SEGMENT_HEADER_SIZE: usize = 8;
10/// Largest varint the chunk length field can occupy (`binary.MaxVarintLen32`).
11pub(crate) const MAX_LEN_FIELD: usize = 5;
12
13/// A zero-copy view of one chunk record inside a segment.
14///
15/// `data` borrows straight out of the mapped segment, so the slice is only
16/// valid while the owning [`super::ChunkReader`] is alive.
17#[derive(Debug)]
18pub struct ChunkSlice<'a> {
19    /// Chunk encoding, i.e. one of the `ENC_*` constants in [`crate::chunkenc`].
20    pub encoding: u8,
21    /// Compressed chunk body, with the encoding byte already stripped.
22    pub data: &'a [u8],
23    /// Segment the record lives in (the high 32 bits of a chunk reference).
24    pub segment: u32,
25    /// Byte offset of the record inside that segment.
26    pub offset: u32,
27    /// Length of the chunk body as stored on disk. Excludes the encoding byte
28    /// and the trailing CRC.
29    pub encoded_len: u32,
30}
31
32/// Where one record starts and ends inside a segment.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub(crate) struct RecordBounds {
35    pub encoding: usize,
36    pub data_start: usize,
37    pub data_end: usize,
38    pub crc_end: usize,
39    pub body_len: u32,
40}
41
42/// Validates the segment header (magic + format version).
43pub(crate) fn check_header(seg: &[u8], seq: u64) -> Result<()> {
44    if seg.len() < SEGMENT_HEADER_SIZE {
45        return Err(Error::format(format!(
46            "chunk segment {seq} too small: {} bytes",
47            seg.len()
48        )));
49    }
50    let magic = u32::from_be_bytes([seg[0], seg[1], seg[2], seg[3]]);
51    if magic != MAGIC_CHUNKS {
52        return Err(Error::format(format!(
53            "invalid chunk segment magic 0x{magic:08x} in segment {seq}"
54        )));
55    }
56    if seg[4] != 1 {
57        return Err(Error::Unsupported(format!(
58            "chunk segment format version {}",
59            seg[4]
60        )));
61    }
62    Ok(())
63}
64
65/// Computes the extent of the record at `offset` without reading its body.
66///
67/// Mirrors `chunks.Reader.ChunkOrIterable`: the length prefix excludes the
68/// encoding byte and the trailing CRC.
69pub(crate) fn record_bounds(seg: &[u8], offset: u32) -> Result<RecordBounds> {
70    let start = offset as usize;
71    if start < SEGMENT_HEADER_SIZE {
72        return Err(Error::format(format!(
73            "chunk offset {start} points into the segment header"
74        )));
75    }
76    if start + MAX_LEN_FIELD > seg.len() {
77        return Err(Error::format(format!(
78            "chunk offset {start} leaves no room for the length field"
79        )));
80    }
81    let mut p = start;
82    let body_len = varint::uvarint(seg, &mut p)?;
83    if body_len == 0 {
84        return Err(Error::format("chunk length is zero"));
85    }
86    let body_len = u32::try_from(body_len)
87        .map_err(|_| Error::format(format!("chunk length {body_len} does not fit in u32")))?;
88    let data_start = p
89        .checked_add(1)
90        .ok_or_else(|| Error::format("chunk length overflow"))?;
91    let data_end = data_start
92        .checked_add(body_len as usize)
93        .ok_or_else(|| Error::format("chunk length overflow"))?;
94    let crc_end = data_end
95        .checked_add(4)
96        .ok_or_else(|| Error::format("chunk length overflow"))?;
97    if crc_end > seg.len() {
98        return Err(Error::format(format!(
99            "chunk at offset {start} is truncated: needs {crc_end} bytes, segment has {}",
100            seg.len()
101        )));
102    }
103    Ok(RecordBounds {
104        encoding: p,
105        data_start,
106        data_end,
107        crc_end,
108        body_len,
109    })
110}