1use 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#[derive(Debug, Clone, Copy)]
18pub struct ReaderOptions {
19 pub verify_crc: bool,
22 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
35pub struct BlockReader {
45 info: BlockInfo,
46 index: IndexReader,
47 chunks: ChunkReader,
48 tombstones: Tombstones,
49}
50
51impl BlockReader {
52 #[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 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 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 pub fn path(&self) -> &Path {
132 &self.info.path
133 }
134
135 pub fn info(&self) -> &BlockInfo {
137 &self.info
138 }
139
140 pub fn meta(&self) -> &BlockMeta {
142 &self.info.meta
143 }
144
145 pub fn block_id(&self) -> &str {
147 &self.info.meta.ulid
148 }
149
150 pub fn index(&self) -> &IndexReader {
152 &self.index
153 }
154
155 pub fn tombstones(&self) -> &Tombstones {
157 &self.tombstones
158 }
159
160 pub fn series(&self, start_offset: u64) -> SeriesIter<'_> {
165 self.index.series(start_offset)
166 }
167
168 pub fn chunk(&self, meta: &ChunkMeta) -> Result<ChunkSlice<'_>> {
171 self.chunks.chunk(meta.reference)
172 }
173
174 pub fn chunk_reader(&self) -> &ChunkReader {
177 &self.chunks
178 }
179
180 pub fn chunk_bytes(&self) -> u64 {
182 self.chunks.bytes()
183 }
184
185 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 pub fn scan_stats(&self) -> Result<IndexStats> {
199 self.index.scan_stats()
200 }
201
202 pub fn into_parts(self) -> (IndexReader, ChunkReader, Tombstones, BlockInfo) {
205 (self.index, self.chunks, self.tombstones, self.info)
206 }
207
208 pub fn validate_tombstones(&self) -> Result<()> {
211 if self.tombstones.series_count() == 0 {
212 return Ok(());
213 }
214 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
236pub 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 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 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}