tsdb-reader 0.3.0

Read-only, zero-copy Prometheus TSDB block reader: index v1-v3, all chunk encodings, integer histograms, postings and label matchers, tombstones
Documentation
//! One chunk segment file: record layout and zero-copy record access.

use crate::error::{Error, Result};
use crate::varint;

/// Magic number at the start of every chunk segment.
pub(crate) const MAGIC_CHUNKS: u32 = 0x85BD_40DD;
/// Size of a chunk segment header: magic(4) + version(1) + padding(3).
pub const SEGMENT_HEADER_SIZE: usize = 8;
/// Largest varint the chunk length field can occupy (`binary.MaxVarintLen32`).
pub(crate) const MAX_LEN_FIELD: usize = 5;

/// A zero-copy view of one chunk record inside a segment.
///
/// `data` borrows straight out of the mapped segment, so the slice is only
/// valid while the owning [`super::ChunkReader`] is alive.
#[derive(Debug)]
pub struct ChunkSlice<'a> {
    /// Chunk encoding, i.e. one of the `ENC_*` constants in [`crate::chunkenc`].
    pub encoding: u8,
    /// Compressed chunk body, with the encoding byte already stripped.
    pub data: &'a [u8],
    /// Segment the record lives in (the high 32 bits of a chunk reference).
    pub segment: u32,
    /// Byte offset of the record inside that segment.
    pub offset: u32,
    /// Length of the chunk body as stored on disk. Excludes the encoding byte
    /// and the trailing CRC.
    pub encoded_len: u32,
}

/// Where one record starts and ends inside a segment.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct RecordBounds {
    pub encoding: usize,
    pub data_start: usize,
    pub data_end: usize,
    pub crc_end: usize,
    pub body_len: u32,
}

/// Validates the segment header (magic + format version).
pub(crate) fn check_header(seg: &[u8], seq: u64) -> Result<()> {
    if seg.len() < SEGMENT_HEADER_SIZE {
        return Err(Error::format(format!(
            "chunk segment {seq} too small: {} bytes",
            seg.len()
        )));
    }
    let magic = u32::from_be_bytes([seg[0], seg[1], seg[2], seg[3]]);
    if magic != MAGIC_CHUNKS {
        return Err(Error::format(format!(
            "invalid chunk segment magic 0x{magic:08x} in segment {seq}"
        )));
    }
    if seg[4] != 1 {
        return Err(Error::Unsupported(format!(
            "chunk segment format version {}",
            seg[4]
        )));
    }
    Ok(())
}

/// Computes the extent of the record at `offset` without reading its body.
///
/// Mirrors `chunks.Reader.ChunkOrIterable`: the length prefix excludes the
/// encoding byte and the trailing CRC.
pub(crate) fn record_bounds(seg: &[u8], offset: u32) -> Result<RecordBounds> {
    let start = offset as usize;
    if start < SEGMENT_HEADER_SIZE {
        return Err(Error::format(format!(
            "chunk offset {start} points into the segment header"
        )));
    }
    if start + MAX_LEN_FIELD > seg.len() {
        return Err(Error::format(format!(
            "chunk offset {start} leaves no room for the length field"
        )));
    }
    let mut p = start;
    let body_len = varint::uvarint(seg, &mut p)?;
    if body_len == 0 {
        return Err(Error::format("chunk length is zero"));
    }
    let body_len = u32::try_from(body_len)
        .map_err(|_| Error::format(format!("chunk length {body_len} does not fit in u32")))?;
    let data_start = p
        .checked_add(1)
        .ok_or_else(|| Error::format("chunk length overflow"))?;
    let data_end = data_start
        .checked_add(body_len as usize)
        .ok_or_else(|| Error::format("chunk length overflow"))?;
    let crc_end = data_end
        .checked_add(4)
        .ok_or_else(|| Error::format("chunk length overflow"))?;
    if crc_end > seg.len() {
        return Err(Error::format(format!(
            "chunk at offset {start} is truncated: needs {crc_end} bytes, segment has {}",
            seg.len()
        )));
    }
    Ok(RecordBounds {
        encoding: p,
        data_start,
        data_end,
        crc_end,
        body_len,
    })
}