Diffinery

homeflare/celldpublic

celld/crates/ltx/src/replica_compactor.rs
225 lines · 7.9 KBRaw History
1//! Additive LTX compaction through a [`ReplicaClient`].
2//!
3//! This module ports the storage-independent part of Litestream v0.5.16's
4//! `Compactor`. It creates a destination object but never deletes a source.
5
6use crate::client::ReplicaClient;
7use crate::compaction_level::SNAPSHOT_LEVEL;
8use crate::compactor::Compactor;
9use crate::error::{Error, Result};
10use crate::ltx::{FileInfo, HEADER_FLAG_NO_CHECKSUM};
11use crate::ltx_file_path;
12use crate::LtxHost;
13use crate::TXID;
14use std::io::Cursor;
15use std::path::Path;
16use std::path::PathBuf;
17
18/// The immutable object and source volume from one compaction attempt.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct CompactionOutput {
21 /// The published destination object.
22 pub info: FileInfo,
23 /// The number of source objects in the merge.
24 pub input_files: usize,
25 /// The sum of the source object sizes.
26 pub input_bytes: u64,
27 /// The number of source objects read from the local LTX directory.
28 pub local_input_files: usize,
29}
30
31/// Compacts LTX objects between two adjacent replica levels.
32pub struct ReplicaCompactor<'a, C> {
33 client: &'a C,
34 verify: bool,
35 max_files: usize,
36 max_input_bytes: u64,
37 local_path: Option<PathBuf>,
38 host: LtxHost,
39}
40
41impl<'a, C: ReplicaClient> ReplicaCompactor<'a, C> {
42 pub fn new(client: &'a C) -> Self {
43 Self {
44 client,
45 verify: false,
46 max_files: usize::MAX,
47 max_input_bytes: u64::MAX,
48 local_path: None,
49 host: LtxHost::default(),
50 }
51 }
52
53 /// Enables a destination-level continuity check after publication.
54 pub fn with_verification(mut self, verify: bool) -> Self {
55 self.verify = verify;
56 self
57 }
58
59 /// Limits one compaction attempt to a contiguous source prefix.
60 pub fn with_limits(mut self, max_files: usize, max_input_bytes: u64) -> Self {
61 self.max_files = max_files;
62 self.max_input_bytes = max_input_bytes;
63 self
64 }
65
66 /// Uses the local LTX directory before it reads an object from the replica.
67 pub fn with_local_path(mut self, path: impl AsRef<Path>) -> Self {
68 self.local_path = Some(path.as_ref().to_path_buf());
69 self
70 }
71
72 /// Uses an injected clock and executor host.
73 pub fn with_host(mut self, host: LtxHost) -> Self {
74 self.host = host;
75 self
76 }
77
78 /// Compacts one new object prefix from `destination_level - 1`.
79 ///
80 /// The method returns `Ok(None)` when the destination already covers every
81 /// available source object. It publishes one immutable destination object
82 /// and leaves every source object intact.
83 pub async fn compact(&self, destination_level: i32) -> Result<Option<CompactionOutput>> {
84 if !(1..SNAPSHOT_LEVEL).contains(&destination_level) {
85 return Err(invalid("the destination compaction level is invalid"));
86 }
87 if self.max_files == 0 || self.max_input_bytes == 0 {
88 return Err(invalid("the compaction limits must be positive"));
89 }
90
91 let destination = self.client.ltx_files(destination_level, TXID(0)).await?;
92 let previous_max = destination
93 .iter()
94 .map(|file| file.max_txid)
95 .max()
96 .unwrap_or(TXID(0));
97 let seek = TXID(previous_max.0.wrapping_add(1));
98 let source_level = destination_level - 1;
99 let available = self
100 .client
101 .ltx_files_bounded(source_level, seek, self.max_files)
102 .await?;
103 let mut source = Vec::new();
104 let mut input_bytes = 0u64;
105 for file in available {
106 let size = u64::try_from(file.size)
107 .map_err(|_| invalid("a compaction source has a negative size"))?;
108 if source.len() == self.max_files {
109 break;
110 }
111 let total = input_bytes
112 .checked_add(size)
113 .ok_or_else(|| invalid("the compaction source size overflows"))?;
114 if total > self.max_input_bytes {
115 if source.is_empty() {
116 return Err(invalid("a compaction source exceeds the byte limit"));
117 }
118 break;
119 }
120 input_bytes = total;
121 source.push(file);
122 }
123 if source.is_empty() {
124 return Ok(None);
125 }
126
127 let min_txid = source
128 .iter()
129 .map(|file| file.min_txid)
130 .min()
131 .ok_or_else(|| invalid("the compaction source is empty"))?;
132 let max_txid = source
133 .iter()
134 .map(|file| file.max_txid)
135 .max()
136 .ok_or_else(|| invalid("the compaction source is empty"))?;
137 if min_txid != seek {
138 return Err(invalid(
139 "the compaction source does not continue the destination level",
140 ));
141 }
142 let mut readers = Vec::with_capacity(source.len());
143 let mut local_input_files = 0usize;
144 for file in &source {
145 let bytes = match &self.local_path {
146 Some(path) => {
147 let filename = ltx_file_path(
148 &path.to_string_lossy(),
149 file.level as u32,
150 file.min_txid,
151 file.max_txid,
152 );
153 match self.host.read_file(filename).await {
154 Ok(bytes) => {
155 local_input_files += 1;
156 bytes
157 }
158 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
159 self.client
160 .open_ltx_file(file.level, file.min_txid, file.max_txid)
161 .await?
162 }
163 Err(error) => return Err(Error::Io(error)),
164 }
165 }
166 None => {
167 self.client
168 .open_ltx_file(file.level, file.min_txid, file.max_txid)
169 .await?
170 }
171 };
172 readers.push(Cursor::new(bytes));
173 }
174
175 // The merge is pure CPU over as much as 64 MiB and must not hold a
176 // runtime worker: a restart drain runs rounds back-to-back, and on a
177 // 4-vCPU node two pegged workers starved co-owned cells' durable
178 // writes (2026-08-12 fleet roll).
179 let (header, output) = self
180 .host
181 .run_blocking(move || {
182 let mut compactor = Compactor::new(Vec::new(), readers);
183 compactor.header_flags = HEADER_FLAG_NO_CHECKSUM;
184 compactor.compact()?;
185 Ok::<_, Error>((compactor.header(), compactor.into_writer()))
186 })
187 .await
188 .map_err(|_| invalid("the compaction merge task panicked"))??;
189 if header.min_txid != min_txid || header.max_txid != max_txid {
190 return Err(invalid(
191 "a compaction source key does not match its LTX header",
192 ));
193 }
194 let info = self
195 .client
196 .write_ltx_file(destination_level, min_txid, max_txid, &output)
197 .await?;
198
199 if self.verify {
200 self.verify_level(destination_level).await?;
201 }
202 Ok(Some(CompactionOutput {
203 info,
204 input_files: source.len(),
205 input_bytes,
206 local_input_files,
207 }))
208 }
209
210 /// Verifies that a destination level has neither gaps nor overlaps.
211 pub async fn verify_level(&self, level: i32) -> Result<()> {
212 let files = self.client.ltx_files(level, TXID(0)).await?;
213 for pair in files.windows(2) {
214 let expected = pair[0].max_txid.0.wrapping_add(1);
215 if pair[1].min_txid != TXID(expected) {
216 return Err(invalid("the compaction level is not contiguous"));
217 }
218 }
219 Ok(())
220 }
221}
222
223fn invalid(message: &'static str) -> Error {
224 Error::Other(message.into())
225}