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 /// Resolved symbols for this cursor; see the threading notes on
98 /// [`super::IndexReader`].
99 pub(crate) cache: super::symbols::SymbolCache,
100}
101
102impl SeriesIter<'_> {
103 /// Current byte offset in the index; the start of the next series.
104 pub fn position(&self) -> u64 {
105 self.pos as u64
106 }
107
108 /// True once the iterator has passed the end of the section.
109 pub fn is_done(&self) -> bool {
110 self.done || self.pos >= self.index.series_end
111 }
112}
113
114impl Iterator for SeriesIter<'_> {
115 type Item = Result<SeriesRef>;
116
117 fn next(&mut self) -> Option<Self::Item> {
118 if self.done {
119 return None;
120 }
121 if self.pos >= self.index.series_end {
122 self.done = true;
123 return None;
124 }
125 // Series sections are zero padded before the next section starts.
126 if self.index.mmap.get(self.pos).copied().unwrap_or(0) == 0 {
127 self.done = true;
128 return None;
129 }
130 match self.index.parse_series(self.pos, &mut self.cache) {
131 Ok((series, next)) => {
132 self.pos = next;
133 Some(Ok(series))
134 }
135 Err(e) => {
136 self.done = true;
137 Some(Err(e))
138 }
139 }
140 }
141}