1use std::fmt;
16use std::path::{Path, PathBuf};
17use std::time::Instant;
18
19use waratah_storage::{
20 COMPACTION_READAHEAD_BYTES, MAIN_REPOSITORY_ID, PartitionAxis, REGISTRY_BLOCK_SIZE_BYTES,
21 Registry, RocksDbTuning, blob_index_dir, blob_store_dir, hexastore_data_dir,
22 iterator_readahead_bytes, registry_data_dir,
23};
24
25use crate::error::DevError;
26use crate::import::{open_hexastore, status};
27
28#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
30pub enum CompactTarget {
31 #[value(alias = "S")]
33 S,
34 #[value(alias = "P")]
36 P,
37 #[value(alias = "O")]
39 O,
40 #[value(alias = "Registry")]
42 Registry,
43}
44
45impl CompactTarget {
46 fn label(self) -> &'static str {
48 match self {
49 Self::S => "S",
50 Self::P => "P",
51 Self::O => "O",
52 Self::Registry => "registry",
53 }
54 }
55}
56
57const CANONICAL_ORDER: [CompactTarget; 4] = [
58 CompactTarget::S,
59 CompactTarget::P,
60 CompactTarget::O,
61 CompactTarget::Registry,
62];
63
64pub fn run(data_dir: PathBuf, targets: &[CompactTarget]) -> Result<(), DevError> {
69 let selected: Vec<CompactTarget> = if targets.is_empty() {
70 CANONICAL_ORDER.to_vec()
71 } else {
72 CANONICAL_ORDER
73 .into_iter()
74 .filter(|target| targets.contains(target))
75 .collect()
76 };
77 if selected.is_empty() {
78 return Ok(());
79 }
80
81 status!(
82 "compacting {} on {} (compaction readahead {} MiB; registry query-time \
83 iterator readahead {} KiB, override with WARATAH_ITERATOR_READAHEAD_SIZE=<KiB>)",
84 selected
85 .iter()
86 .map(|target| target.label())
87 .collect::<Vec<_>>()
88 .join(", "),
89 data_dir.display(),
90 COMPACTION_READAHEAD_BYTES / (1024 * 1024),
91 iterator_readahead_bytes() / 1024,
92 );
93
94 for target in selected {
95 match target {
96 CompactTarget::S => compact_axis(&data_dir, PartitionAxis::S, "S")?,
97 CompactTarget::P => compact_axis(&data_dir, PartitionAxis::P, "P")?,
98 CompactTarget::O => compact_axis(&data_dir, PartitionAxis::O, "O")?,
99 CompactTarget::Registry => compact_registry(&data_dir)?,
100 }
101 }
102 status!("all targets compacted");
103 Ok(())
104}
105
106fn compact_axis(data_dir: &Path, axis: PartitionAxis, label: &str) -> Result<(), DevError> {
111 let path = hexastore_data_dir(data_dir, MAIN_REPOSITORY_ID, axis);
112 status!("{label} axis: opening (stats collectors attached)");
113 let tuning = RocksDbTuning {
114 disable_auto_compactions: true,
115 disable_wal: false,
116 ..RocksDbTuning::bulk_ingest(false)
117 };
118 let store = open_hexastore(path.clone(), axis, tuning, true)?;
119
120 status!("{label} axis: flushing memtables");
121 store.flush_memtables()?;
122 let before = SstStats::of(&path);
123
124 status!("{label} axis: compacting {before} (stats land in the new SSTs)");
125 let started = Instant::now();
126 store.compact_range();
127 let after = SstStats::of(&path);
128 status!(
129 "{label} axis: compacted in {:.1}s ({before} -> {after})",
130 started.elapsed().as_secs_f64()
131 );
132 Ok(())
133}
134
135fn compact_registry(data_dir: &Path) -> Result<(), DevError> {
141 let path = registry_data_dir(data_dir, MAIN_REPOSITORY_ID);
142 status!(
143 "registry: opening (block size {} KiB; compaction rewrites files at this size)",
144 REGISTRY_BLOCK_SIZE_BYTES / 1024
145 );
146 let registry = Registry::open_rocksdb(&path, RocksDbTuning::registry_node())?;
147
148 status!("registry: flushing memtables");
149 registry.flush_memtables()?;
150 let before = SstStats::of(&path);
151
152 status!("registry: compacting {before} (transient free space of that order is needed)");
153 let started = Instant::now();
154 registry.compact_range();
155 let after = SstStats::of(&path);
156 status!(
157 "registry: compacted in {:.1}s ({before} -> {after})",
158 started.elapsed().as_secs_f64()
159 );
160
161 let blob_root = blob_store_dir(data_dir, MAIN_REPOSITORY_ID);
167 if blob_root.exists() {
168 let blobs = waratah_registry::BlobStore::open(&blob_root)?;
169 status!("blobs: flushing the index memtable");
170 blobs.flush()?;
171 let blob_path = blob_index_dir(&blob_root);
172 let blob_before = SstStats::of(&blob_path);
173 status!("blobs: compacting {blob_before}");
174 let started = Instant::now();
175 blobs.compact_range()?;
176 let blob_after = SstStats::of(&blob_path);
177 status!(
178 "blobs: compacted in {:.1}s ({blob_before} -> {blob_after})",
179 started.elapsed().as_secs_f64()
180 );
181 }
182 Ok(())
183}
184
185#[derive(Debug, Clone, Copy, Default)]
187struct SstStats {
188 files: u64,
189 bytes: u64,
190}
191
192impl SstStats {
193 fn of(dir: &Path) -> Self {
195 let mut stats = Self::default();
196 let Ok(entries) = std::fs::read_dir(dir) else {
197 return stats;
198 };
199 for entry in entries.flatten() {
200 let Ok(meta) = entry.metadata() else {
201 continue;
202 };
203 if meta.is_file() && entry.file_name().to_string_lossy().ends_with(".sst") {
204 stats.files += 1;
205 stats.bytes += meta.len();
206 }
207 }
208 stats
209 }
210}
211
212impl fmt::Display for SstStats {
213 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214 const GIB: u64 = 1024 * 1024 * 1024;
215 const MIB: u64 = 1024 * 1024;
216 let size = if self.bytes >= GIB {
217 format!("{:.2} GiB", self.bytes as f64 / GIB as f64)
218 } else if self.bytes >= MIB {
219 format!("{:.1} MiB", self.bytes as f64 / MIB as f64)
220 } else {
221 format!("{} KiB", self.bytes / 1024)
222 };
223 write!(f, "{} SSTs / {size}", self.files)
224 }
225}