Skip to main content

tsdb_reader/
block.rs

1//! A single TSDB block: index + chunk segments + tombstones.
2
3use std::path::{Path, PathBuf};
4
5use crate::chunks::{ChunkReader, ChunkSlice};
6use crate::error::{Error, Result};
7use crate::index::{ChunkMeta, IndexReader, IndexStats, SeriesIter};
8#[cfg(feature = "meta")]
9use crate::meta::read_meta;
10use crate::meta::{BlockInfo, BlockMeta};
11use crate::tombstones::Tombstones;
12
13/// Knobs applied when opening a block.
14///
15/// The defaults are what you want for a normal export: checksums on, sequential
16/// read-ahead on.
17#[derive(Debug, Clone, Copy)]
18pub struct ReaderOptions {
19    /// Validate CRC32C checksums for index TOC, series records, chunks and
20    /// tombstones. Disabling improves throughput but hides corruption.
21    pub verify_crc: bool,
22    /// Apply `madvise(SEQUENTIAL)` to chunk segment mappings.
23    pub mmap_advise: bool,
24}
25
26impl Default for ReaderOptions {
27    fn default() -> Self {
28        Self {
29            verify_crc: true,
30            mmap_advise: true,
31        }
32    }
33}
34
35/// A block opened for reading: index, chunk segments and tombstones.
36///
37/// The reader owns the underlying mappings or buffers. On unix with the `mmap`
38/// feature the files stay mapped for the lifetime of the reader, which means
39/// they must not be truncated by another process while it is in use.
40///
41/// `BlockReader` is `Send` but not `Sync`: the symbol cache is a `RefCell`, so
42/// index traversal belongs to one thread. Chunk segments are shared freely via
43/// [`BlockReader::chunk_reader`] or [`BlockReader::into_parts`].
44pub struct BlockReader {
45    info: BlockInfo,
46    index: IndexReader,
47    chunks: ChunkReader,
48    tombstones: Tombstones,
49}
50
51impl BlockReader {
52    /// Opens a block directory: parses `meta.json`, then the index, chunk
53    /// segments and tombstones.
54    ///
55    /// Available with the `meta` feature. Without it, use
56    /// [`BlockReader::open_with_meta`] or [`BlockReader::open_info`].
57    #[cfg(feature = "meta")]
58    pub fn open(path: &Path, opts: ReaderOptions) -> Result<Self> {
59        let meta_path = path.join("meta.json");
60        if !meta_path.is_file() {
61            return Err(Error::format(format!(
62                "not a block directory (missing meta.json): {}",
63                path.display()
64            )));
65        }
66        let meta = read_meta(&meta_path)?;
67        Self::open_with_meta(path, meta, opts)
68    }
69
70    /// Opens a block whose `meta.json` the caller already parsed.
71    ///
72    /// This is the entry point for builds without the `meta` feature and for
73    /// callers that keep block metadata in their own store.
74    pub fn open_with_meta(path: &Path, mut meta: BlockMeta, opts: ReaderOptions) -> Result<Self> {
75        if meta.ulid.is_empty() {
76            meta.ulid = path
77                .file_name()
78                .and_then(|s| s.to_str())
79                .unwrap_or("")
80                .to_string();
81        }
82        let index = IndexReader::open(&path.join("index"), opts.verify_crc)?;
83        let chunks = ChunkReader::open(&path.join("chunks"), opts.verify_crc, opts.mmap_advise)?;
84        let tombstones = Tombstones::open(path, opts.verify_crc)?;
85
86        let index_bytes = std::fs::metadata(path.join("index"))
87            .map(|m| m.len())
88            .unwrap_or(0);
89        let tombstones_bytes = std::fs::metadata(path.join("tombstones"))
90            .map(|m| m.len())
91            .unwrap_or(0);
92        let info = BlockInfo {
93            path: path.to_path_buf(),
94            tenant: String::new(),
95            remote: false,
96            meta,
97            index_bytes,
98            chunks_bytes: chunks.bytes(),
99            tombstones_bytes,
100            warnings: Vec::new(),
101        };
102        Ok(Self {
103            info,
104            index,
105            chunks,
106            tombstones,
107        })
108    }
109
110    /// Opens a block reusing metadata that was already discovered.
111    ///
112    /// The passed [`BlockInfo`] stays authoritative: `tenant`, `remote` and
113    /// `warnings` cannot be derived from the block directory, so they are never
114    /// overwritten. Only the byte counts measured while opening are refreshed,
115    /// and `meta` is filled from disk when the caller left its ULID empty.
116    pub fn open_info(info: BlockInfo, opts: ReaderOptions) -> Result<Self> {
117        let mut reader = Self::open_with_meta(&info.path, info.meta.clone(), opts)?;
118        let mut merged = info;
119        merged.index_bytes = reader.info.index_bytes;
120        merged.chunks_bytes = reader.info.chunks_bytes;
121        merged.tombstones_bytes = reader.info.tombstones_bytes;
122        if merged.meta.ulid.is_empty() {
123            merged.meta = reader.info.meta;
124        }
125        merged.warnings.extend(reader.info.warnings);
126        reader.info = merged;
127        Ok(reader)
128    }
129
130    /// Directory this block was opened from.
131    pub fn path(&self) -> &Path {
132        &self.info.path
133    }
134
135    /// Metadata plus the sizes measured when the block was opened.
136    pub fn info(&self) -> &BlockInfo {
137        &self.info
138    }
139
140    /// Parsed `meta.json`.
141    pub fn meta(&self) -> &BlockMeta {
142        &self.info.meta
143    }
144
145    /// Block ULID, taken from `meta.json` or the directory name.
146    pub fn block_id(&self) -> &str {
147        &self.info.meta.ulid
148    }
149
150    /// The index reader backing this block.
151    pub fn index(&self) -> &IndexReader {
152        &self.index
153    }
154
155    /// Deletion intervals loaded for this block.
156    pub fn tombstones(&self) -> &Tombstones {
157        &self.tombstones
158    }
159
160    /// Iterates series in lexicographic label order.
161    ///
162    /// `start_offset` is a byte offset previously reported by
163    /// [`crate::SeriesIter::position`]; pass `0` to start at the beginning.
164    pub fn series(&self, start_offset: u64) -> SeriesIter<'_> {
165        self.index.series(start_offset)
166    }
167
168    /// Reads the chunk described by `meta`, verifying its checksum when the
169    /// reader was opened with `verify_crc`.
170    pub fn chunk(&self, meta: &ChunkMeta) -> Result<ChunkSlice<'_>> {
171        self.chunks.chunk(meta.reference)
172    }
173
174    /// Shared chunk reader for decode workers (immutable, thread-safe).
175    /// Shared chunk reader, safe to hand to several decode threads.
176    pub fn chunk_reader(&self) -> &ChunkReader {
177        &self.chunks
178    }
179
180    /// Total size of the chunk segments in bytes.
181    pub fn chunk_bytes(&self) -> u64 {
182        self.chunks.bytes()
183    }
184
185    /// Series/chunk totals derived from `meta.json` (cheap, may be zero for
186    /// blocks written by old versions or custom tooling).
187    pub fn stats_from_meta(&self) -> IndexStats {
188        let s = &self.meta().stats;
189        IndexStats {
190            series: s.num_series,
191            chunks: s.num_chunks,
192            min_series_offset: self.index.series_start(),
193            end_series_offset: self.index.series_end(),
194        }
195    }
196
197    /// Exact totals by scanning the index series section (no label resolution).
198    pub fn scan_stats(&self) -> Result<IndexStats> {
199        self.index.scan_stats()
200    }
201
202    /// Splits the reader so that the index can be moved into a single reader
203    /// thread while chunk segments and tombstones are shared with workers.
204    pub fn into_parts(self) -> (IndexReader, ChunkReader, Tombstones, BlockInfo) {
205        (self.index, self.chunks, self.tombstones, self.info)
206    }
207
208    /// Ensures the tombstone refs look plausible for this block. Prometheus
209    /// block tombstones use the same series refs as the index.
210    pub fn validate_tombstones(&self) -> Result<()> {
211        if self.tombstones.series_count() == 0 {
212            return Ok(());
213        }
214        // A quick structural check: refs must be < 2^32 for v2/v3 (series id
215        // is offset/16 and index files stay below 64 GiB).
216        for (r, _) in self.tombstones.iter_raw() {
217            if *r > u32::MAX as u64 {
218                return Err(Error::format(format!(
219                    "tombstone series ref {r} out of range"
220                )));
221            }
222        }
223        Ok(())
224    }
225}
226
227impl std::fmt::Debug for BlockReader {
228    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
229        f.debug_struct("BlockReader")
230            .field("path", &self.info.path)
231            .field("ulid", &self.info.meta.ulid)
232            .finish()
233    }
234}
235
236/// Convenience for callers that only have a directory name.
237pub fn block_dir(root: &Path, ulid: &str) -> PathBuf {
238    root.join(ulid)
239}
240
241#[cfg(all(test, feature = "meta"))]
242mod tests {
243    use super::*;
244    use crate::meta::{BlockMeta, BlockMetaCompaction, BlockStats};
245
246    fn fixture_block_dir() -> PathBuf {
247        PathBuf::from(env!("CARGO_MANIFEST_DIR"))
248            .join("tests/data/block/01M70C8VV61N5H5VWXB17HQQ1R")
249    }
250
251    fn info_with(tenant: &str, remote: bool, ulid: &str) -> BlockInfo {
252        BlockInfo {
253            path: fixture_block_dir(),
254            tenant: tenant.to_string(),
255            remote,
256            meta: BlockMeta {
257                ulid: ulid.to_string(),
258                min_time: 0,
259                max_time: 0,
260                stats: BlockStats::default(),
261                compaction: BlockMetaCompaction::default(),
262                version: 2,
263            },
264            index_bytes: 0,
265            chunks_bytes: 0,
266            tombstones_bytes: 0,
267            warnings: vec!["discovery note".to_string()],
268        }
269    }
270
271    #[test]
272    fn open_info_keeps_caller_metadata() {
273        let info = info_with("tenant-a", true, "01M70C8VV61N5H5VWXB17HQQ1R");
274        let reader = BlockReader::open_info(info, ReaderOptions::default()).unwrap();
275
276        assert_eq!(reader.info().tenant, "tenant-a");
277        assert!(reader.info().remote);
278        assert_eq!(reader.info().warnings, vec!["discovery note"]);
279        assert_eq!(reader.block_id(), "01M70C8VV61N5H5VWXB17HQQ1R");
280        // Sizes must come from disk, not from the caller's zeros.
281        assert!(reader.info().index_bytes > 0);
282        assert!(reader.info().chunks_bytes > 0);
283    }
284
285    #[test]
286    fn open_info_falls_back_to_the_directory_name() {
287        let info = info_with("", false, "");
288        let reader = BlockReader::open_info(info, ReaderOptions::default()).unwrap();
289
290        assert_eq!(
291            reader.block_id(),
292            "01M70C8VV61N5H5VWXB17HQQ1R",
293            "an empty ULID must be taken from the directory name"
294        );
295        // The rest of the caller's meta is authoritative, even when meta.json
296        // on disk says something else.
297        assert_eq!(reader.meta().version, 2);
298        assert_eq!(reader.meta().min_time, 0);
299    }
300
301    #[test]
302    fn open_info_matches_open_for_a_local_block() {
303        let dir = fixture_block_dir();
304        let direct = BlockReader::open(&dir, ReaderOptions::default()).unwrap();
305        let via_info = BlockReader::open_info(
306            BlockInfo {
307                path: dir.clone(),
308                tenant: String::new(),
309                remote: false,
310                meta: direct.meta().clone(),
311                index_bytes: 0,
312                chunks_bytes: 0,
313                tombstones_bytes: 0,
314                warnings: Vec::new(),
315            },
316            ReaderOptions::default(),
317        )
318        .unwrap();
319
320        assert_eq!(direct.info().index_bytes, via_info.info().index_bytes);
321        assert_eq!(direct.info().chunks_bytes, via_info.info().chunks_bytes);
322        assert_eq!(
323            direct.info().tombstones_bytes,
324            via_info.info().tombstones_bytes
325        );
326        assert_eq!(direct.block_id(), via_info.block_id());
327        assert_eq!(
328            direct.scan_stats().unwrap().series,
329            via_info.scan_stats().unwrap().series
330        );
331    }
332
333    #[test]
334    fn open_rejects_a_non_block_directory() {
335        let error = BlockReader::open(&std::env::temp_dir(), ReaderOptions::default())
336            .expect_err("temp dir is not a block");
337        assert!(error.to_string().contains("meta.json"), "{error}");
338    }
339
340    #[test]
341    fn block_dir_joins_the_ulid() {
342        assert_eq!(
343            block_dir(Path::new("/data"), "01ABC"),
344            PathBuf::from("/data/01ABC")
345        );
346    }
347}