Skip to main content

hyperfile_cleaner/
lib.rs

1//! `hyperfile-cleaner` enumerates and removes unreferenced
2//! segments from a [hyperfile](https://crates.io/crates/hyperfile).
3//!
4//! ## Model
5//!
6//! A hyperfile is stored on S3 as a single inode object plus a
7//! sequence of segment objects. Each segment is keyed by a
8//! monotonically increasing `SegmentId` and contains both the
9//! data blocks written in that flush and the metadata B+tree
10//! nodes that index them.
11//!
12//! Because hyperfile is copy-on-write, segments accumulate as
13//! the file is modified. Once a segment is no longer referenced
14//! by the latest published checkpoint's metadata tree, its
15//! storage can be reclaimed.
16//!
17//! The [`Cleaner`] trait provides two operations:
18//!
19//! - [`Cleaner::collect`] walks the metadata tree of the latest
20//!   (or a caller-specified) checkpoint and returns
21//!   `(referenced, unreferenced)` segment lists for a
22//!   `[low, high]` segid range. Useful for dry-run / inspection.
23//! - [`Cleaner::prune`] performs the same walk and additionally
24//!   deletes the unreferenced segments via S3 `DeleteObjects`.
25//!
26//! ## Concurrency caveat
27//!
28//! `prune` takes every object the newest version, and a compaction attached to
29//! it, do not point into. Readers holding an older version, and a compaction
30//! beside the writer that has not yet attached its copies, need objects neither
31//! names: use [`s3::S3Cleaner::prune_with`] with a grace for those.
32//!
33//! The cleaner does not coordinate with in-flight writers. It
34//! takes a snapshot of the inode at the start of the call and
35//! operates on that. New segments published after that point are
36//! always outside the configured range (because `high` was fixed
37//! at snapshot time), so the prune is safe against concurrent
38//! appends. It is, however, the caller's responsibility to ensure
39//! `low` is not also being actively reused.
40//!
41//! ## Example
42//!
43//! ```no_run
44//! use hyperfile_cleaner::{Cleaner, s3::S3Cleaner};
45//!
46//! # async fn run() -> std::io::Result<()> {
47//! let cleaner = S3Cleaner::new("s3://my-bucket/path/to/file").await?;
48//!
49//! // Inspect what would be deleted (dry-run): pass high=0 to
50//! // mean "use the latest checkpoint".
51//! let (refed, unrefed) = cleaner.collect(1, 0).await?;
52//! println!("referenced  : {:?}", refed);
53//! println!("unreferenced: {:?}", unrefed);
54//!
55//! // Actually delete the unreferenced range.
56//! cleaner.prune(1, 0).await?;
57//! # Ok(())
58//! # }
59//! ```
60
61#[cfg(all(feature = "blocking", feature = "reactor"))]
62compile_error!(
63    "features `blocking` and `reactor` are mutually exclusive: they select \
64     hyperfile builds that link btree-ondisk `rc` and `arc` respectively. \
65     For `reactor`, set `default-features = false`."
66);
67#[cfg(not(any(feature = "blocking", feature = "reactor")))]
68compile_error!(
69    "select a hyperfile build: feature `blocking` (the default) or `reactor`"
70);
71
72use std::io::Result;
73use hyperfile::{Cno, SegmentId};
74
75pub mod compact;
76pub mod s3;
77
78/// Operations supported by a hyperfile cleaner backend.
79///
80/// Both methods take a `[low, high]` range of **checkpoint numbers**
81/// ([`Cno`]). `high == 0` is a sentinel meaning "use the latest published
82/// checkpoint (`Inode::get_last_cno`)". `low` is inclusive; a typical value
83/// is `1` to cover the entire file history.
84///
85/// The range is inclusive at *both* ends, so `low == high` is valid and
86/// answered normally — which is what `collect(1, 0)` resolves to on a file with
87/// a single checkpoint. Only `low > high` is an error, and that also covers a
88/// file that has never been flushed (`get_last_cno() == 0`), since there is no
89/// metadata tree to walk.
90///
91/// What the methods *report and delete* is [`SegmentId`], which names a stored
92/// object rather than a checkpoint: a checkpoint written under
93/// `BlockPtrFormat::PartedSegment` is several objects — `<cno>.0`, `<cno>.1`, …
94/// — and they are not reclaimable together. Under every other format an object
95/// and a checkpoint are the same thing and a `SegmentId` prints as the plain
96/// number.
97pub trait Cleaner {
98    /// Walk the metadata tree of the checkpoint identified by `high`
99    /// (or the latest if `high == 0`) and return
100    /// `(referenced, unreferenced)` lists of segment objects, the
101    /// unreferenced one limited to checkpoints within `[low, high]`.
102    ///
103    /// Useful for dry-run inspection before invoking [`Cleaner::prune`].
104    fn collect(
105        &self,
106        low: Cno,
107        high: Cno,
108    ) -> impl Future<Output = Result<(Vec<SegmentId>, Vec<SegmentId>)>> + Send;
109
110    /// Walk the metadata tree as in [`Cleaner::collect`] and then
111    /// delete the unreferenced segment objects from the underlying
112    /// store.
113    ///
114    /// Errors if any individual delete batch fails; in that case
115    /// previously-deleted batches stay deleted (S3 has no
116    /// transactional batch). The returned error message mentions
117    /// the failed object count and a sample failed key.
118    fn prune(
119        &self,
120        low: Cno,
121        high: Cno,
122    ) -> impl Future<Output = Result<()>> + Send;
123}