Skip to main content

tsdb_reader/index/
series.rs

1//! Series records: label sets, chunk metadata and the sequential iterator.
2
3use std::sync::Arc;
4
5use crate::error::Result;
6
7/// Where one chunk lives and which time range it covers.
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub struct ChunkMeta {
10    /// Packed chunk reference: high 32 bits segment index, low 32 bits offset.
11    pub reference: u64,
12    /// First timestamp in the chunk, in milliseconds since the Unix epoch.
13    pub min_time: i64,
14    /// Last timestamp in the chunk, in milliseconds since the Unix epoch.
15    pub max_time: i64,
16}
17
18impl ChunkMeta {
19    /// Segment index encoded in [`Self::reference`].
20    pub fn segment(&self) -> u32 {
21        (self.reference >> 32) as u32
22    }
23
24    /// Byte offset of the record inside [`Self::segment`].
25    pub fn offset(&self) -> u32 {
26        self.reference as u32
27    }
28}
29
30/// One series: its label set and the chunks that hold its samples.
31///
32/// Despite the name this is an owned record, not a reference into the file:
33/// label strings are resolved through the symbol table once, then shared as
34/// `Arc<str>` so a caller can keep them after the iterator moves on.
35#[derive(Debug, Clone)]
36pub struct SeriesRef {
37    /// Reference as stored in the index (v2/v3: byte offset / 16). This is the
38    /// same value tombstones use to identify a series.
39    pub id: u64,
40    /// Byte offset of the series record in the index file.
41    pub offset: u64,
42    /// Labels in lexicographic order, exactly as stored in the index.
43    pub labels: Vec<(Arc<str>, Arc<str>)>,
44    /// Chunks in ascending time order.
45    pub chunks: Vec<ChunkMeta>,
46}
47
48impl SeriesRef {
49    /// Looks up a label value by name.
50    pub fn label(&self, name: &str) -> Option<&str> {
51        self.labels
52            .iter()
53            .find(|(n, _)| n.as_ref() == name)
54            .map(|(_, v)| v.as_ref())
55    }
56
57    /// Metric name (`__name__`), if the series carries one.
58    pub fn metric_name(&self) -> Option<&str> {
59        self.label("__name__")
60    }
61
62    /// First timestamp covered by the series, `None` when it has no chunks.
63    pub fn min_time(&self) -> Option<i64> {
64        self.chunks.first().map(|c| c.min_time)
65    }
66
67    /// Last timestamp covered by the series, `None` when it has no chunks.
68    pub fn max_time(&self) -> Option<i64> {
69        self.chunks.last().map(|c| c.max_time)
70    }
71}
72
73/// Series and chunk counts, plus the byte range they were read from.
74///
75/// [`Self::end_series_offset`] is what a resumed run stores in its checkpoint
76/// so it can continue from the same byte.
77#[derive(Debug, Clone, Copy, Default)]
78pub struct IndexStats {
79    /// Number of series records.
80    pub series: u64,
81    /// Number of chunks referenced by those series.
82    pub chunks: u64,
83    /// Byte offset where the series section starts.
84    pub min_series_offset: u64,
85    /// Byte offset just past the last series record that was read.
86    pub end_series_offset: u64,
87}
88
89/// Iterator over the series section, in on-disk (label-sorted) order.
90///
91/// Yields `Result<SeriesRef>`: a malformed record stops the iteration after
92/// reporting the error, so callers can checkpoint at the last good offset.
93pub struct SeriesIter<'a> {
94    pub(crate) index: &'a super::IndexReader,
95    pub(crate) pos: usize,
96    pub(crate) done: bool,
97}
98
99impl SeriesIter<'_> {
100    /// Current byte offset in the index; the start of the next series.
101    pub fn position(&self) -> u64 {
102        self.pos as u64
103    }
104
105    /// True once the iterator has passed the end of the section.
106    pub fn is_done(&self) -> bool {
107        self.done || self.pos >= self.index.series_end
108    }
109}
110
111impl Iterator for SeriesIter<'_> {
112    type Item = Result<SeriesRef>;
113
114    fn next(&mut self) -> Option<Self::Item> {
115        if self.done {
116            return None;
117        }
118        if self.pos >= self.index.series_end {
119            self.done = true;
120            return None;
121        }
122        // Series sections are zero padded before the next section starts.
123        if self.index.mmap.get(self.pos).copied().unwrap_or(0) == 0 {
124            self.done = true;
125            return None;
126        }
127        match self.index.parse_series(self.pos) {
128            Ok((series, next)) => {
129                self.pos = next;
130                Some(Ok(series))
131            }
132            Err(e) => {
133                self.done = true;
134                Some(Err(e))
135            }
136        }
137    }
138}