1use std::collections::{BTreeMap, HashSet};
26use std::fmt;
27
28use futures::TryStreamExt;
29use object_store::path::Path;
30use object_store::{ObjectMeta, ObjectStore};
31
32use crate::document::Schema;
33use crate::error::{ItzmaError, Result};
34use crate::gc::{self, Found};
35use crate::manifest::{self, IndexEntry, Manifest, SparseIndexEntry};
36use crate::namespace::validate_id;
37use crate::{schema_object, segment, wal_codec};
38
39#[derive(Debug, Clone, PartialEq)]
41pub struct Report {
42 pub namespace: String,
44 pub schema: Option<Schema>,
47 pub manifest: Option<Manifest>,
49 pub wal: WalReport,
51 pub segments: Vec<SegmentReport>,
53 pub problems: Vec<String>,
55}
56
57#[derive(Debug, Clone, PartialEq, Eq, Default)]
59pub struct WalReport {
60 pub objects: usize,
62 pub first: Option<u64>,
64 pub last: Option<u64>,
66 pub bytes: u64,
68 pub fenced: usize,
70 pub tail: usize,
73 pub gaps: Vec<(u64, u64)>,
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct SegmentReport {
81 pub id: String,
83 pub lo: u64,
85 pub hi: u64,
87 pub bytes: u64,
89 pub state: SegmentState,
94 pub index: Option<IndexInfo>,
96 pub stray_indexes: Vec<u32>,
100 pub has_sparse_data: bool,
103 pub sparse_index: Option<SparseIndexInfo>,
105 pub stray_sparse_indexes: Vec<u32>,
109}
110
111#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct IndexInfo {
114 pub generation: u32,
116 pub kind: String,
118 pub bytes: Option<u64>,
121}
122
123#[derive(Debug, Clone, PartialEq, Eq)]
125pub struct SparseIndexInfo {
126 pub generation: u32,
128 pub bytes: Option<u64>,
131}
132
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
135pub enum SegmentState {
136 Live,
138 Dead,
142 Orphan,
146}
147
148impl fmt::Display for SegmentState {
149 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150 f.pad(match self {
151 Self::Live => "live",
152 Self::Dead => "dead",
153 Self::Orphan => "orphan",
154 })
155 }
156}
157
158pub async fn report(store: &dyn ObjectStore, namespace: &str) -> Result<Report> {
189 validate_id(namespace)?;
190 let mut problems = Vec::new();
191
192 let manifest = match manifest::load(store, namespace).await {
193 Ok((manifest, _)) => Some(manifest),
194 Err(e) => {
195 problems.push(unreadable("manifest", e)?);
196 None
197 }
198 };
199 let schema = match schema_object::read(store, namespace).await {
200 Ok(schema) => schema,
201 Err(e) => {
202 problems.push(unreadable("schema.json", e)?);
203 None
204 }
205 };
206 if let (Some(manifest), Some(schema)) = (&manifest, &schema) {
207 if &manifest.schema != schema {
208 problems.push(format!(
209 "schema.json holds {schema:?} but the manifest holds {:?}",
210 manifest.schema
211 ));
212 }
213 }
214
215 let prefix = Path::from(format!("{namespace}/segments"));
216 let listing: Vec<ObjectMeta> = store.list(Some(&prefix)).try_collect().await?;
217 let found = gc::group(&prefix, listing);
218 let wal_objects = gc::list_wal(store, namespace).await?;
219
220 let folded = manifest.as_ref().map_or(0, |m| m.wal_folded_through);
221 let wal = summarize_wal(
222 wal_objects.iter().map(|o| (o.seq, o.size)).collect(),
223 folded,
224 );
225 for &(from, to) in &wal.gaps {
226 problems.push(if from == to {
227 format!("WAL seq {from} is missing")
228 } else {
229 format!("WAL seqs {from} through {to} are missing")
230 });
231 }
232
233 let mut segments = Vec::new();
234 if let Some(manifest) = &manifest {
235 if let Err(e) = segment::validate_chain(&manifest.live_segments, folded) {
236 problems.push(e.to_string());
237 }
238 for id in &manifest.live_segments {
239 let data = segment::segment_path(namespace, id);
240 let there = found
241 .get(id)
242 .is_some_and(|f| f.objects.iter().any(|(path, _)| *path == data));
243 if !there {
244 problems.push(format!("live segment {id} has no data object"));
245 }
246 }
247 let live: HashSet<&str> = manifest.live_segments.iter().map(String::as_str).collect();
248 segments = found
249 .iter()
250 .map(|(id, f)| {
251 segment_report(
252 id,
253 f,
254 folded,
255 &live,
256 &manifest.indexes,
257 &manifest.sparse_indexes,
258 )
259 })
260 .collect();
261 for report in &segments {
262 if let Some(index) = &report.index {
263 if index.bytes.is_none() {
264 problems.push(format!(
265 "segment {} is listed with index generation {} but has no such index object",
266 report.id, index.generation
267 ));
268 }
269 }
270 if let Some(index) = &report.sparse_index {
271 if index.bytes.is_none() {
272 problems.push(format!(
273 "segment {} is listed with sparse index generation {} but has no such object",
274 report.id, index.generation
275 ));
276 }
277 }
278 }
279 for id in manifest.indexes.keys() {
280 if !live.contains(id.as_str()) {
281 problems.push(format!(
282 "the manifest lists an index for {id}, which is not a live segment"
283 ));
284 }
285 }
286 for id in manifest.sparse_indexes.keys() {
287 if !live.contains(id.as_str()) {
288 problems.push(format!(
289 "the manifest lists a sparse index for {id}, which is not a live segment"
290 ));
291 }
292 }
293 } else {
294 segments.extend(found.iter().map(|(id, f)| {
295 segment_report(
296 id,
297 f,
298 0,
299 &HashSet::new(),
300 &BTreeMap::new(),
301 &BTreeMap::new(),
302 )
303 }));
304 }
305
306 Ok(Report {
307 namespace: namespace.to_string(),
308 schema,
309 manifest,
310 wal,
311 segments,
312 problems,
313 })
314}
315
316fn unreadable(what: &str, err: ItzmaError) -> Result<String> {
319 match err {
320 ItzmaError::NamespaceNotFound(_) => Ok(format!("{what} is missing")),
321 ItzmaError::Serde { .. }
322 | ItzmaError::UnsupportedFormat { .. }
323 | ItzmaError::WalFormatTooNew { .. }
324 | ItzmaError::SegmentFormatTooNew { .. } => Ok(format!("{what} cannot be read: {err}")),
325 other => Err(other),
326 }
327}
328
329fn segment_report(
330 id: &str,
331 found: &Found,
332 folded: u64,
333 live: &HashSet<&str>,
334 indexes: &BTreeMap<String, IndexEntry>,
335 sparse_indexes: &BTreeMap<String, SparseIndexEntry>,
336) -> SegmentReport {
337 let state = if live.contains(id) {
338 SegmentState::Live
339 } else if gc::is_dead(folded, live, id, found) {
340 SegmentState::Dead
341 } else {
342 SegmentState::Orphan
343 };
344 let named = indexes.get(id).filter(|_| state == SegmentState::Live);
345 let index = named.map(|entry| IndexInfo {
346 generation: entry.generation,
347 kind: entry.kind.clone(),
348 bytes: found
349 .indexes
350 .iter()
351 .find(|object| object.generation == entry.generation)
352 .map(|object| object.size),
353 });
354 let mut stray_indexes: Vec<u32> = found
355 .indexes
356 .iter()
357 .map(|object| object.generation)
358 .filter(|generation| Some(*generation) != named.map(|entry| entry.generation))
359 .collect();
360 stray_indexes.sort_unstable();
361 let named_sparse = sparse_indexes
362 .get(id)
363 .filter(|_| state == SegmentState::Live);
364 let sparse_index = named_sparse.map(|entry| SparseIndexInfo {
365 generation: entry.generation,
366 bytes: found
367 .sparse_indexes
368 .iter()
369 .find(|object| object.generation == entry.generation)
370 .map(|object| object.size),
371 });
372 let mut stray_sparse_indexes: Vec<u32> = found
373 .sparse_indexes
374 .iter()
375 .map(|object| object.generation)
376 .filter(|generation| Some(*generation) != named_sparse.map(|entry| entry.generation))
377 .collect();
378 stray_sparse_indexes.sort_unstable();
379 let has_sparse_data = found
380 .objects
381 .iter()
382 .any(|(path, _)| path.filename() == Some("sparse.bin"));
383 SegmentReport {
384 id: id.to_string(),
385 lo: found.lo,
386 hi: found.hi,
387 bytes: found.objects.iter().map(|(_, size)| size).sum(),
388 state,
389 index,
390 stray_indexes,
391 has_sparse_data,
392 sparse_index,
393 stray_sparse_indexes,
394 }
395}
396
397fn summarize_wal(mut objects: Vec<(u64, u64)>, folded: u64) -> WalReport {
399 objects.sort_unstable();
400 let mut gaps = Vec::new();
401 let mut prev = 0u64;
402 for &(seq, _) in &objects {
403 if seq > prev.saturating_add(1) {
404 gaps.push((prev + 1, seq - 1));
405 }
406 prev = prev.max(seq);
407 }
408 if folded > prev {
409 gaps.push((prev + 1, folded));
410 }
411 WalReport {
412 objects: objects.len(),
413 first: objects.first().map(|&(seq, _)| seq),
414 last: objects.last().map(|&(seq, _)| seq),
415 bytes: objects.iter().map(|&(_, size)| size).sum(),
416 fenced: objects
417 .iter()
418 .filter(|&&(_, size)| size == wal_codec::FENCE_LEN as u64)
419 .count(),
420 tail: objects.iter().filter(|&&(seq, _)| seq > folded).count(),
421 gaps,
422 }
423}
424
425impl fmt::Display for Report {
426 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
427 writeln!(f, "namespace {}", self.namespace)?;
428 match &self.schema {
429 Some(schema) => writeln!(f, "schema.json dim {}, {:?}", schema.dim, schema.metric)?,
430 None => writeln!(f, "schema.json none")?,
431 }
432 match &self.manifest {
433 Some(m) => writeln!(
434 f,
435 "manifest wal_format {}, segment_format {}, folded through {}, {} live segments",
436 m.wal_format,
437 m.segment_format,
438 m.wal_folded_through,
439 m.live_segments.len()
440 )?,
441 None => writeln!(f, "manifest none")?,
442 }
443 let wal = &self.wal;
444 write!(f, "wal {} objects", wal.objects)?;
445 if let (Some(first), Some(last)) = (wal.first, wal.last) {
446 write!(f, ", seq {first} through {last}")?;
447 }
448 writeln!(
449 f,
450 ", {} bytes, {} fenced, {} in the tail",
451 wal.bytes, wal.fenced, wal.tail
452 )?;
453 writeln!(f, "segments {} on disk", self.segments.len())?;
454 for s in &self.segments {
455 write!(f, " {} {:<6} {} bytes", s.id, s.state, s.bytes)?;
456 if let Some(index) = &s.index {
457 match index.bytes {
458 Some(bytes) => {
459 write!(
460 f,
461 " index {} {} {bytes} bytes",
462 index.generation, index.kind
463 )?;
464 }
465 None => write!(f, " index {} {} missing", index.generation, index.kind)?,
466 }
467 }
468 if !s.stray_indexes.is_empty() {
469 write!(f, " unnamed indexes {:?}", s.stray_indexes)?;
470 }
471 if s.has_sparse_data {
472 write!(f, " sparse")?;
473 }
474 if let Some(index) = &s.sparse_index {
475 match index.bytes {
476 Some(bytes) => write!(f, " sparse index {} {bytes} bytes", index.generation)?,
477 None => write!(f, " sparse index {} missing", index.generation)?,
478 }
479 }
480 if !s.stray_sparse_indexes.is_empty() {
481 write!(f, " unnamed sparse indexes {:?}", s.stray_sparse_indexes)?;
482 }
483 writeln!(f)?;
484 }
485 if self.problems.is_empty() {
486 writeln!(f, "problems none")
487 } else {
488 writeln!(f, "problems {}", self.problems.len())?;
489 for problem in &self.problems {
490 writeln!(f, " {problem}")?;
491 }
492 Ok(())
493 }
494 }
495}
496
497#[cfg(test)]
498mod tests {
499 use super::*;
500
501 fn seqs(list: &[(u64, u64)], folded: u64) -> WalReport {
502 summarize_wal(list.to_vec(), folded)
503 }
504
505 #[test]
506 fn an_empty_wal_has_no_gaps() {
507 assert_eq!(seqs(&[], 0), WalReport::default());
508 }
509
510 #[test]
511 fn a_contiguous_run_has_no_gaps() {
512 let r = seqs(&[(1, 100), (2, 50), (3, 8)], 2);
513 assert_eq!(r.objects, 3);
514 assert_eq!((r.first, r.last), (Some(1), Some(3)));
515 assert_eq!(r.bytes, 158);
516 assert_eq!(r.fenced, 1);
517 assert_eq!(r.tail, 1);
518 assert!(r.gaps.is_empty());
519 }
520
521 #[test]
522 fn the_input_order_does_not_matter() {
523 let r = seqs(&[(3, 20), (1, 20), (2, 20)], 0);
524 assert!(r.gaps.is_empty());
525 assert_eq!((r.first, r.last), (Some(1), Some(3)));
526 }
527
528 #[test]
529 fn a_missing_start_and_a_missing_middle_are_gaps() {
530 let r = seqs(&[(3, 20), (4, 20), (8, 20)], 0);
531 assert_eq!(r.gaps, vec![(1, 2), (5, 7)]);
532 }
533
534 #[test]
535 fn a_fold_point_past_the_last_object_is_a_gap() {
536 let r = seqs(&[(1, 20), (2, 20)], 5);
537 assert_eq!(r.gaps, vec![(3, 5)]);
538 assert_eq!(r.tail, 0);
539 }
540
541 #[test]
542 fn a_fold_point_at_the_last_object_is_not() {
543 assert!(seqs(&[(1, 20), (2, 20)], 2).gaps.is_empty());
544 }
545
546 #[test]
547 fn a_seq_listed_twice_is_not_a_gap() {
548 let r = seqs(&[(1, 20), (1, 20), (2, 20)], 0);
549 assert!(r.gaps.is_empty());
550 }
551}