1use std::path::PathBuf;
4
5use serde::{Deserialize, Serialize};
6#[cfg(feature = "meta")]
7use std::path::Path;
8
9#[cfg(feature = "meta")]
10use crate::error::{Error, Result};
11
12pub const META_VERSION: i32 = 1;
19
20fn default_version() -> i32 {
21 META_VERSION
22}
23
24#[derive(Debug, Clone, Default, Serialize, Deserialize)]
31pub struct BlockStats {
32 #[serde(rename = "numSamples", default)]
34 pub num_samples: u64,
35 #[serde(rename = "numFloatSamples", default)]
37 pub num_float_samples: u64,
38 #[serde(rename = "numHistogramSamples", default)]
40 pub num_histogram_samples: u64,
41 #[serde(rename = "numSeries", default)]
43 pub num_series: u64,
44 #[serde(rename = "numChunks", default)]
46 pub num_chunks: u64,
47 #[serde(rename = "numTombstones", default)]
49 pub num_tombstones: u64,
50}
51
52#[derive(Debug, Clone, Default, Serialize, Deserialize)]
57pub struct BlockMetaCompaction {
58 #[serde(default)]
60 pub level: i32,
61 #[serde(default)]
63 pub sources: Vec<String>,
64 #[serde(default)]
66 pub parents: Vec<ParentMeta>,
67 #[serde(default)]
69 pub deletable: bool,
70 #[serde(default)]
72 pub failed: bool,
73 #[serde(default)]
75 pub hints: Vec<String>,
76}
77
78#[derive(Debug, Clone, Default, Serialize, Deserialize)]
80pub struct ParentMeta {
81 #[serde(default)]
83 pub ulid: String,
84 #[serde(default)]
86 pub min_time: i64,
87 #[serde(default)]
89 pub max_time: i64,
90}
91
92#[derive(Debug, Clone, Serialize, Deserialize)]
94pub struct BlockMeta {
95 #[serde(default)]
98 pub ulid: String,
99 #[serde(rename = "minTime", default)]
101 pub min_time: i64,
102 #[serde(rename = "maxTime", default)]
104 pub max_time: i64,
105 #[serde(default)]
107 pub stats: BlockStats,
108 #[serde(default)]
110 pub compaction: BlockMetaCompaction,
111 #[serde(default = "default_version")]
116 pub version: i32,
117}
118
119impl BlockMeta {
120 pub fn samples_hint(&self) -> u64 {
122 if self.stats.num_samples > 0 {
123 self.stats.num_samples
124 } else {
125 self.stats.num_float_samples + self.stats.num_histogram_samples
126 }
127 }
128}
129
130#[derive(Debug, Clone)]
132pub struct BlockInfo {
133 pub path: PathBuf,
135 pub tenant: String,
137 pub remote: bool,
139 pub meta: BlockMeta,
141 pub index_bytes: u64,
143 pub chunks_bytes: u64,
145 pub tombstones_bytes: u64,
147 pub warnings: Vec<String>,
149}
150
151impl BlockInfo {
152 pub fn ulid(&self) -> &str {
154 &self.meta.ulid
155 }
156
157 pub fn key(&self) -> String {
159 if self.tenant.is_empty() {
160 self.meta.ulid.clone()
161 } else {
162 format!("{}/{}", self.tenant, self.meta.ulid)
163 }
164 }
165
166 pub fn tenant_opt(&self) -> Option<&str> {
168 if self.tenant.is_empty() {
169 None
170 } else {
171 Some(&self.tenant)
172 }
173 }
174
175 pub fn size_bytes(&self) -> u64 {
177 self.index_bytes + self.chunks_bytes + self.tombstones_bytes
178 }
179}
180
181#[cfg(feature = "meta")]
183pub fn read_meta(path: &Path) -> Result<BlockMeta> {
184 let data = std::fs::read(path)?;
185 serde_json::from_slice(&data)
186 .map_err(|e| Error::format(format!("parse {}: {e}", path.display())))
187}
188
189#[cfg(feature = "meta")]
190fn dir_size(path: &Path) -> u64 {
191 let Ok(rd) = std::fs::read_dir(path) else {
192 return 0;
193 };
194 let mut total = 0;
195 for entry in rd.flatten() {
196 let p = entry.path();
197 match entry.metadata() {
198 Ok(md) if md.is_file() => total += md.len(),
199 Ok(md) if md.is_dir() => total += dir_size(&p),
200 _ => {}
201 }
202 }
203 total
204}
205
206#[cfg(feature = "meta")]
207fn looks_like_block(dir: &Path) -> bool {
208 dir.join("meta.json").is_file() && dir.join("index").is_file() && dir.join("chunks").is_dir()
209}
210
211#[cfg(feature = "meta")]
216pub fn discover_blocks(root: &Path) -> Result<Vec<BlockInfo>> {
217 if !root.exists() {
218 return Err(Error::format(format!(
219 "data directory does not exist: {}",
220 root.display()
221 )));
222 }
223
224 let mut dirs = Vec::new();
225 if looks_like_block(root) {
226 dirs.push(root.to_path_buf());
227 } else {
228 let rd = std::fs::read_dir(root)?;
229 for entry in rd.flatten() {
230 let p = entry.path();
231 if p.is_dir() && looks_like_block(&p) {
232 dirs.push(p);
233 }
234 }
235 }
236
237 let mut blocks = Vec::with_capacity(dirs.len());
238 for dir in dirs {
239 let meta = read_meta(&dir.join("meta.json"))?;
240 let index_bytes = std::fs::metadata(dir.join("index"))
241 .map(|m| m.len())
242 .unwrap_or(0);
243 let chunks_bytes = dir_size(&dir.join("chunks"));
244 let tombstones_bytes = std::fs::metadata(dir.join("tombstones"))
245 .map(|m| m.len())
246 .unwrap_or(0);
247 let mut warnings = Vec::new();
248 if meta.stats.num_series == 0 && meta.stats.num_samples == 0 {
249 warnings.push(
250 "meta.json has no stats; series/chunk totals require an index prepass".into(),
251 );
252 }
253 if meta.version > 3 {
254 warnings.push(format!("unknown index version {}", meta.version));
255 }
256 blocks.push(BlockInfo {
257 path: dir,
258 tenant: String::new(),
259 remote: false,
260 meta,
261 index_bytes,
262 chunks_bytes,
263 tombstones_bytes,
264 warnings,
265 });
266 }
267
268 blocks.sort_by(|a, b| {
269 a.meta
270 .min_time
271 .cmp(&b.meta.min_time)
272 .then_with(|| a.meta.ulid.cmp(&b.meta.ulid))
273 });
274
275 for i in 1..blocks.len() {
278 let (prev_max, cur_min) = (blocks[i - 1].meta.max_time, blocks[i].meta.min_time);
279 if prev_max > cur_min {
280 let msg = format!(
281 "overlaps with block {} (prev maxTime {} > minTime {})",
282 blocks[i - 1].meta.ulid,
283 prev_max,
284 cur_min
285 );
286 blocks[i].warnings.push(msg.clone());
287 let msg2 = format!(
288 "overlaps with block {} (maxTime {} > next minTime {})",
289 blocks[i].meta.ulid, prev_max, cur_min
290 );
291 blocks[i - 1].warnings.push(msg2);
292 }
293 }
294
295 Ok(blocks)
296}
297
298#[cfg(test)]
299mod tests {
300 use super::*;
301
302 #[test]
303 fn stats_hint_falls_back_to_parts() {
304 let m = BlockMeta {
305 ulid: "x".into(),
306 min_time: 0,
307 max_time: 1,
308 stats: BlockStats {
309 num_float_samples: 3,
310 num_histogram_samples: 4,
311 ..Default::default()
312 },
313 compaction: Default::default(),
314 version: 2,
315 };
316 assert_eq!(m.samples_hint(), 7);
317 }
318}