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
//! Series records: label sets, chunk metadata and the sequential iterator.

use std::sync::Arc;

use crate::error::Result;

/// Where one chunk lives and which time range it covers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ChunkMeta {
    /// Packed chunk reference: high 32 bits segment index, low 32 bits offset.
    pub reference: u64,
    /// First timestamp in the chunk, in milliseconds since the Unix epoch.
    pub min_time: i64,
    /// Last timestamp in the chunk, in milliseconds since the Unix epoch.
    pub max_time: i64,
}

impl ChunkMeta {
    /// Segment index encoded in [`Self::reference`].
    pub fn segment(&self) -> u32 {
        (self.reference >> 32) as u32
    }

    /// Byte offset of the record inside [`Self::segment`].
    pub fn offset(&self) -> u32 {
        self.reference as u32
    }
}

/// One series: its label set and the chunks that hold its samples.
///
/// Despite the name this is an owned record, not a reference into the file:
/// label strings are resolved through the symbol table once, then shared as
/// `Arc<str>` so a caller can keep them after the iterator moves on.
#[derive(Debug, Clone)]
pub struct SeriesRef {
    /// Reference as stored in the index (v2/v3: byte offset / 16). This is the
    /// same value tombstones use to identify a series.
    pub id: u64,
    /// Byte offset of the series record in the index file.
    pub offset: u64,
    /// Labels in lexicographic order, exactly as stored in the index.
    pub labels: Vec<(Arc<str>, Arc<str>)>,
    /// Chunks in ascending time order.
    pub chunks: Vec<ChunkMeta>,
}

impl SeriesRef {
    /// Looks up a label value by name.
    pub fn label(&self, name: &str) -> Option<&str> {
        self.labels
            .iter()
            .find(|(n, _)| n.as_ref() == name)
            .map(|(_, v)| v.as_ref())
    }

    /// Metric name (`__name__`), if the series carries one.
    pub fn metric_name(&self) -> Option<&str> {
        self.label("__name__")
    }

    /// First timestamp covered by the series, `None` when it has no chunks.
    pub fn min_time(&self) -> Option<i64> {
        self.chunks.first().map(|c| c.min_time)
    }

    /// Last timestamp covered by the series, `None` when it has no chunks.
    pub fn max_time(&self) -> Option<i64> {
        self.chunks.last().map(|c| c.max_time)
    }
}

/// Series and chunk counts, plus the byte range they were read from.
///
/// [`Self::end_series_offset`] is what a resumed run stores in its checkpoint
/// so it can continue from the same byte.
#[derive(Debug, Clone, Copy, Default)]
pub struct IndexStats {
    /// Number of series records.
    pub series: u64,
    /// Number of chunks referenced by those series.
    pub chunks: u64,
    /// Byte offset where the series section starts.
    pub min_series_offset: u64,
    /// Byte offset just past the last series record that was read.
    pub end_series_offset: u64,
}

/// Iterator over the series section, in on-disk (label-sorted) order.
///
/// Yields `Result<SeriesRef>`: a malformed record stops the iteration after
/// reporting the error, so callers can checkpoint at the last good offset.
pub struct SeriesIter<'a> {
    pub(crate) index: &'a super::IndexReader,
    pub(crate) pos: usize,
    pub(crate) done: bool,
    /// Resolved symbols for this cursor; see the threading notes on
    /// [`super::IndexReader`].
    pub(crate) cache: super::symbols::SymbolCache,
}

impl SeriesIter<'_> {
    /// Current byte offset in the index; the start of the next series.
    pub fn position(&self) -> u64 {
        self.pos as u64
    }

    /// True once the iterator has passed the end of the section.
    pub fn is_done(&self) -> bool {
        self.done || self.pos >= self.index.series_end
    }
}

impl Iterator for SeriesIter<'_> {
    type Item = Result<SeriesRef>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }
        if self.pos >= self.index.series_end {
            self.done = true;
            return None;
        }
        // Series sections are zero padded before the next section starts.
        if self.index.mmap.get(self.pos).copied().unwrap_or(0) == 0 {
            self.done = true;
            return None;
        }
        match self.index.parse_series(self.pos, &mut self.cache) {
            Ok((series, next)) => {
                self.pos = next;
                Some(Ok(series))
            }
            Err(e) => {
                self.done = true;
                Some(Err(e))
            }
        }
    }
}