Diffinery

homeflare/celldpublic

542 lines · 20.9 KBRaw History
1#![warn(
2 clippy::disallowed_macros,
3 clippy::disallowed_methods,
4 clippy::disallowed_types
5)]
6
7//! `celld-ltx` — embeddable streaming replication of a SQLite database to
8//! object storage, with point-in-time restore and object-storage lease fencing.
9//!
10//! A from-scratch Rust reimplementation of **Litestream v0.5** (pinned
11//! `v0.5.11`). The public surface includes `Db`, `Replica`, and `restore`.
12//!
13//! # Core position/identity helpers (T4)
14//!
15//! Ported from [email protected] litestream.go:18-203 and
16//! [email protected] ltx.go:66-145.
17
18pub mod bundle;
19pub mod client;
20mod codec;
21pub mod compaction_level;
22pub mod compactor;
23pub mod db;
24pub mod error;
25pub mod host;
26pub mod ltx;
27mod lz4_block;
28pub mod replica;
29pub mod replica_compactor;
30pub mod replica_url;
31pub mod wal;
32
33// ── Crate-root re-exports — the ergonomic public surface ────────────────
34//
35// These `pub use` aliases let a host use `celld_ltx::Db`, `celld_ltx::Replica`,
36// and `celld_ltx::restore` without naming the owning module. The original module
37// paths, such as `celld_ltx::db::Db`, remain valid.
38
39// Re-export the error model at the crate root.
40pub use error::{new_ltx_error, Error, LTXError, Result};
41pub use host::{
42 DirectFileSystem, FileSystem, HostDirEntry, HostFile, HostFileIo, HostMetadata, HostTaskError,
43 LtxHost,
44};
45
46/// A SQLite database managed for replication (WAL-mode checkpoint takeover plus
47/// the WAL→LTX capture loop). Re-exported from [`crate::db::Db`].
48pub use db::Db;
49
50/// SQLite checkpoint mode used by [`Db`] when it checkpoints the WAL.
51/// Re-exported from [`crate::db::CheckpointMode`].
52pub use db::CheckpointMode;
53
54/// Connects a managed [`Db`] to a replication destination and drives the
55/// single-replica sync loop. Re-exported from [`crate::replica::Replica`].
56pub use replica::Replica;
57
58/// Restores a database from a [`ReplicaClient`] into a fresh file, optionally up
59/// to a target [`TXID`]. Re-exported from [`crate::replica::restore`].
60pub use replica::restore;
61
62/// The storage abstraction every replica backend implements.
63/// Re-exported from [`crate::client::ReplicaClient`].
64pub use client::ReplicaClient;
65
66/// Metadata describing a single LTX file on a replica (the value type returned by
67/// [`ReplicaClient`] listings). Re-exported from [`crate::ltx::FileInfo`].
68pub use ltx::FileInfo;
69
70/// A [`ReplicaClient`] that stores LTX files on the local filesystem.
71/// Re-exported from [`crate::client::file::FileReplicaClient`].
72pub use client::file::FileReplicaClient;
73
74/// The bundle overlay (celld-original, self-contained).
75/// Re-exported from [`crate::client::bundle`].
76pub use client::bundle::BundleFetcher;
77pub use client::bundle::BundleOverlayClient;
78pub use client::bundle::LocatedRow;
79
80/// The S3/R2/MinIO [`ReplicaClient`], behind the `s3` feature.
81/// Re-exported from [`crate::client::object_store::ObjectStoreClient`].
82#[cfg(feature = "s3")]
83pub use client::object_store::ObjectStoreClient;
84
85/// Configuration for the S3/R2/MinIO backend, behind the `s3` feature.
86/// Re-exported from [`crate::client::object_store::ObjectStoreConfig`].
87#[cfg(feature = "s3")]
88pub use client::object_store::ObjectStoreConfig;
89
90/// Which object-metadata name carries an LTX header timestamp, behind the
91/// `s3` feature. Re-exported from
92/// [`crate::client::object_store::TimestampMetadataKey`].
93#[cfg(feature = "s3")]
94pub use client::object_store::TimestampMetadataKey;
95
96/// The underlying `object_store` crate, re-exported so a host can name the
97/// shared `Arc<dyn ObjectStore>` that [`ObjectStoreConfig::build_store`] returns
98/// and hand it to [`ObjectStoreClient::with_store`].
99pub use object_store;
100
101// ── Naming constants ──────────────────────────────────────────────────────────
102
103/// Suffix appended to a database path to obtain the Litestream metadata
104/// directory.
105///
106/// Ported from [email protected] litestream.go:19 (`MetaDirSuffix`).
107pub const META_DIR_SUFFIX: &str = "-litestream";
108
109// ── SQLite checkpoint modes ───────────────────────────────────────────────────
110//
111// Ported from [email protected] litestream.go:22-28.
112
113pub const CHECKPOINT_MODE_PASSIVE: &str = "PASSIVE";
114pub const CHECKPOINT_MODE_FULL: &str = "FULL";
115pub const CHECKPOINT_MODE_RESTART: &str = "RESTART";
116pub const CHECKPOINT_MODE_TRUNCATE: &str = "TRUNCATE";
117
118// ── SQLite WAL size constants ─────────────────────────────────────────────────
119//
120// Ported from [email protected] litestream.go:95-128.
121
122/// Size of a SQLite WAL file header, in bytes.
123pub const WAL_HEADER_SIZE: usize = 32;
124
125/// Size of a SQLite WAL frame header, in bytes.
126pub const WAL_FRAME_HEADER_SIZE: usize = 24;
127
128/// Byte offset of the checksum pair inside a WAL header.
129pub const WAL_HEADER_CHECKSUM_OFFSET: usize = 24;
130
131/// Byte offset of the checksum pair inside a WAL frame header.
132pub const WAL_FRAME_HEADER_CHECKSUM_OFFSET: usize = 16;
133
134// ── TXID ──────────────────────────────────────────────────────────────────────
135
136/// A monotonically increasing transaction identifier.
137///
138/// Represented as a `u64` and formatted as a zero-padded 16-character
139/// lowercase hex string (e.g. `"0000000000000001"`). This matches the
140/// on-disk LTX filename convention and `ltx.TXID.String()` in
141/// [email protected] ltx.go:142-144.
142#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
143pub struct TXID(pub u64);
144
145impl TXID {
146 /// The zero TXID.
147 pub const ZERO: TXID = TXID(0);
148
149 /// Returns the raw `u64` value.
150 #[inline]
151 pub fn get(self) -> u64 {
152 self.0
153 }
154}
155
156impl std::fmt::Display for TXID {
157 /// Formats as a 16-digit lowercase hex string, zero-padded.
158 ///
159 /// Ported from `TXID.String()` in [email protected] ltx.go:142.
160 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
161 write!(f, "{:016x}", self.0)
162 }
163}
164
165/// Parses a TXID from its canonical 16-character lowercase hex representation.
166///
167/// Returns an error if the string is not exactly 16 hex characters or contains
168/// any character outside `[0-9a-fA-F]`.
169///
170/// Ported from `ParseTXID` in [email protected] ltx.go:130-138.
171///
172/// Note: Go's `strconv.ParseUint(s, 16, 64)` rejects sign prefixes (`+`, `-`).
173/// Rust's `u64::from_str_radix` accepts a leading `+`, which would be a
174/// behavioural divergence. We pre-validate that every byte is a valid hex
175/// digit to match Go's stricter contract.
176pub fn parse_txid(s: &str) -> Result<TXID> {
177 if s.len() != 16 {
178 return Err(Error::Other(
179 format!("invalid formatted transaction id length: {:?}", s).into(),
180 ));
181 }
182 // Reject any character outside [0-9a-fA-F]. This matches Go's
183 // strconv.ParseUint which rejects sign prefixes ('+'/'-') and any
184 // non-hex byte, whereas Rust's from_str_radix would accept a leading '+'.
185 if !s.bytes().all(|b| b.is_ascii_hexdigit()) {
186 return Err(Error::Other(
187 format!("invalid transaction id format: {:?}", s).into(),
188 ));
189 }
190 let v = u64::from_str_radix(s, 16)
191 .map_err(|_| Error::Other(format!("invalid transaction id format: {:?}", s).into()))?;
192 Ok(TXID(v))
193}
194
195impl From<u64> for TXID {
196 fn from(v: u64) -> Self {
197 TXID(v)
198 }
199}
200
201impl From<TXID> for u64 {
202 fn from(t: TXID) -> Self {
203 t.0
204 }
205}
206
207// ── Checksum ──────────────────────────────────────────────────────────────────
208
209/// A 64-bit LTX rolling / file checksum.
210///
211/// The high bit is the `ChecksumFlag` sentinel used by the LTX format to
212/// distinguish a real checksum from an absent one.
213///
214/// Ported from [email protected] ltx.go (type alias `Checksum uint64`).
215pub type Checksum = u64;
216
217/// Flag bit set on every valid non-zero LTX checksum.
218///
219/// Ported from `ChecksumFlag` in [email protected] ltx.go:55.
220pub const CHECKSUM_FLAG: Checksum = 1 << 63;
221
222// ── Pos ──────────────────────────────────────────────────────────────────────
223
224/// Replication position — the TXID plus a rolling post-apply checksum.
225///
226/// Together these two values uniquely identify the state of a database at a
227/// point in the replication log.
228///
229/// Ported from `Pos` / `ParsePos` / `Pos.String` in [email protected] ltx.go:66-109.
230#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
231pub struct Pos {
232 /// Transaction ID at this position.
233 pub txid: TXID,
234 /// Rolling CRC checksum of the database state after applying the
235 /// transaction at `txid`.
236 pub post_apply_checksum: Checksum,
237}
238
239impl Pos {
240 /// The zero position (no transactions applied yet).
241 pub const ZERO: Pos = Pos {
242 txid: TXID::ZERO,
243 post_apply_checksum: 0,
244 };
245
246 /// Constructs a new `Pos`.
247 ///
248 /// Ported from `NewPos` in [email protected] ltx.go:72.
249 pub fn new(txid: TXID, post_apply_checksum: Checksum) -> Self {
250 Pos {
251 txid,
252 post_apply_checksum,
253 }
254 }
255
256 /// Returns `true` when this is the zero position.
257 ///
258 /// Ported from `Pos.IsZero` in [email protected] ltx.go:107.
259 pub fn is_zero(self) -> bool {
260 self == Pos::ZERO
261 }
262}
263
264impl std::fmt::Display for Pos {
265 /// Formats as `"<txid>/<checksum>"` — e.g. `"0000000000000001/8000000000000001"`.
266 ///
267 /// Ported from `Pos.String` in [email protected] ltx.go:102.
268 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
269 write!(f, "{}/{:016x}", self.txid, self.post_apply_checksum)
270 }
271}
272
273/// Parses a `Pos` from its canonical `"<txid>/<checksum>"` string form.
274///
275/// The string must be exactly 33 characters: 16 hex digits, a slash, and
276/// 16 hex digits.
277///
278/// Ported from `ParsePos` in [email protected] ltx.go:80-99.
279pub fn parse_pos(s: &str) -> Result<Pos> {
280 if s.len() != 33 {
281 return Err(Error::Other(
282 format!("invalid formatted position length: {:?}", s).into(),
283 ));
284 }
285 let txid = parse_txid(&s[..16])
286 .map_err(|_| Error::Other(format!("invalid position txid: {:?}", &s[..16]).into()))?;
287 // DECISION: We validate that byte 16 is '/' (the separator) even though
288 // Go's ParsePos ([email protected] ltx.go:80-99) blindly slices s[:16] and s[17:]
289 // without checking the separator byte, so Go would accept e.g.
290 // "0000000000000001X8000000000000001". We keep the stricter check because:
291 // (a) the '/' is mandated by the format doc and Pos.String() always emits it,
292 // (b) silently accepting a malformed separator would hide caller bugs, and
293 // (c) no production caller requires compatibility with the malformed form.
294 // This is the conservative interpretation because it rejects bad input.
295 if s.as_bytes()[16] != b'/' {
296 return Err(Error::Other(
297 format!("invalid formatted position (missing /): {:?}", s).into(),
298 ));
299 }
300 // Same sign-prefix pre-validation as parse_txid: reject non-hex characters
301 // so we match Go's strconv.ParseUint contract for the checksum field too.
302 let checksum_str = &s[17..];
303 if !checksum_str.bytes().all(|b| b.is_ascii_hexdigit()) {
304 return Err(Error::Other(
305 format!("invalid position checksum: {:?}", checksum_str).into(),
306 ));
307 }
308 let checksum = u64::from_str_radix(checksum_str, 16).map_err(|_| {
309 Error::Other(format!("invalid position checksum: {:?}", checksum_str).into())
310 })?;
311 Ok(Pos {
312 txid,
313 post_apply_checksum: checksum,
314 })
315}
316
317// ── SQLite checksum ───────────────────────────────────────────────────────────
318
319/// Computes a running SQLite WAL checksum over a byte slice.
320///
321/// The slice length **must** be a multiple of 8 bytes (the function panics
322/// otherwise, matching the `assert` in the Go source).
323///
324/// `s0` / `s1` are the running checksum values (pass `(0, 0)` for the first
325/// call, then thread the result through subsequent calls for incremental
326/// checksumming).
327///
328/// `big_endian` selects the byte order used to read 32-bit words from `b`:
329/// `true` = big-endian (WAL headers with magic `0x377f0683`),
330/// `false` = little-endian (WAL headers with magic `0x377f0682`).
331///
332/// Ported from `Checksum` in [email protected] litestream.go:110-119.
333///
334/// # Panics
335/// Panics if `b.len() % 8 != 0`.
336pub fn wal_checksum(big_endian: bool, s0: u32, s1: u32, b: &[u8]) -> (u32, u32) {
337 assert!(b.len().is_multiple_of(8), "misaligned checksum byte slice");
338
339 let mut s0 = s0;
340 let mut s1 = s1;
341
342 // Iterate over 8-byte units and compute checksum.
343 // Matches litestream.go Checksum loop exactly.
344 let mut i = 0usize;
345 while i < b.len() {
346 let w0 = if big_endian {
347 u32::from_be_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]])
348 } else {
349 u32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]])
350 };
351 let w1 = if big_endian {
352 u32::from_be_bytes([b[i + 4], b[i + 5], b[i + 6], b[i + 7]])
353 } else {
354 u32::from_le_bytes([b[i + 4], b[i + 5], b[i + 6], b[i + 7]])
355 };
356 s0 = s0.wrapping_add(w0).wrapping_add(s1);
357 s1 = s1.wrapping_add(w1).wrapping_add(s0);
358 i += 8;
359 }
360 (s0, s1)
361}
362
363// ── Forward-slash path cleaning (Go stdlib `path`) ────────────────────────────
364//
365// The LTX path helpers below build object-store keys with Go's `path.Join`
366// (NOT `filepath.Join`): the OS-independent, always-`/` package in
367// `go/src/path/path.go`. `path.Join` concatenates non-empty elements with a
368// single `/` then runs the result through `path.Clean`, which collapses
369// repeated separators, resolves `.`/`..`, and strips trailing slashes. A
370// naive `format!("{}/ltx", root)` skips this cleaning, so a root carrying a
371// trailing slash (e.g. an S3 prefix `"backups/"`) would yield a DIFFERENT
372// object key than the real binary (`"backups//ltx"` vs `"backups/ltx"`),
373// breaking the differential oracle. We port `Clean`/`Join` byte-for-byte.
374
375/// Lexically cleans a slash-separated path.
376///
377/// A faithful port of `Clean` in the Go standard library `path` package
378/// (`go/src/path/path.go`, `func Clean`). It applies these rules iteratively
379/// until no further processing is possible:
380/// 1. Replace multiple slashes with a single slash.
381/// 2. Eliminate each `.` path-name element (the current directory).
382/// 3. Eliminate each inner `..` element along with the non-`..` element
383/// preceding it.
384/// 4. Eliminate `..` elements that begin a rooted path (i.e. `/..` → `/`).
385///
386/// The returned path ends in a slash only if it is the root `"/"`. An empty
387/// input returns `"."`.
388///
389/// `pub(crate)` so `replica_url::clean_replica_url_path` (T3) can reuse Go's
390/// `path.Clean` semantics rather than reimplementing them.
391pub(crate) fn path_clean(path: &str) -> String {
392 if path.is_empty() {
393 return ".".to_string();
394 }
395
396 let bytes = path.as_bytes();
397 let rooted = bytes[0] == b'/';
398 let n = bytes.len();
399
400 // Mirror Go's `lazybuf` with an explicit write cursor `w` over a fully
401 // allocated buffer (we do not bother with Go's lazy aliasing optimisation,
402 // but we DO preserve its cursor semantics, which the previous Vec-length
403 // port got wrong). `dotdot` marks the index below which `..` elements may
404 // not backtrack. The output is `buf[..w]`, so the byte at index `w` is the
405 // next byte to be written — and is logically NOT part of the output yet.
406 //
407 // The backtrack loop must read `buf[w]` (the byte the cursor lands on),
408 // NOT `buf[w-1]`: when it stops on a separator, that separator sits at
409 // index `w` and is therefore EXCLUDED from `buf[..w]`. A Vec-length model
410 // that inspects `out.last()` (i.e. `buf[w-1]`) instead leaves the surviving
411 // separator in the buffer, doubling it before the next element — the bug
412 // this rewrite fixes. See `go/src/path/path.go` `func Clean` / `lazybuf`.
413 let mut buf: Vec<u8> = vec![0u8; n];
414 let mut w = 0usize;
415 let mut r = 0usize;
416 let mut dotdot = 0usize;
417 if rooted {
418 buf[w] = b'/';
419 w += 1;
420 r = 1;
421 dotdot = 1;
422 }
423
424 while r < n {
425 if bytes[r] == b'/' {
426 // empty path element
427 r += 1;
428 } else if bytes[r] == b'.' && (r + 1 == n || bytes[r + 1] == b'/') {
429 // `.` element
430 r += 1;
431 } else if bytes[r] == b'.'
432 && r + 1 < n
433 && bytes[r + 1] == b'.'
434 && (r + 2 == n || bytes[r + 2] == b'/')
435 {
436 // `..` element: remove to last `/`
437 r += 2;
438 if w > dotdot {
439 // can backtrack: step back over the just-ended element body,
440 // then keep stepping while the byte at the cursor is not '/'.
441 // When this stops on a '/', the cursor rests AT that '/', so it
442 // is excluded from `buf[..w]` (matching Go's `out.w` semantics).
443 w -= 1;
444 while w > dotdot && buf[w] != b'/' {
445 w -= 1;
446 }
447 } else if !rooted {
448 // cannot backtrack, but not rooted, so append `..` element.
449 if w > 0 {
450 buf[w] = b'/';
451 w += 1;
452 }
453 buf[w] = b'.';
454 w += 1;
455 buf[w] = b'.';
456 w += 1;
457 dotdot = w;
458 }
459 } else {
460 // real path element; add slash if needed
461 if (rooted && w != 1) || (!rooted && w != 0) {
462 buf[w] = b'/';
463 w += 1;
464 }
465 // copy element
466 while r < n && bytes[r] != b'/' {
467 buf[w] = bytes[r];
468 w += 1;
469 r += 1;
470 }
471 }
472 }
473
474 // Turn empty string into "."
475 if w == 0 {
476 return ".".to_string();
477 }
478 buf.truncate(w);
479 // SAFETY-free: `buf` is built only from ASCII `/`, `.`, and bytes copied
480 // verbatim from the valid-UTF-8 `path`, so it is always valid UTF-8.
481 String::from_utf8(buf).expect("path_clean produced valid UTF-8")
482}
483
484/// Joins any number of path elements into a single slash-separated path,
485/// cleaning the result.
486///
487/// A faithful port of `Join` in the Go standard library `path` package
488/// (`go/src/path/path.go`, `func Join`): empty elements are ignored, and the
489/// joined string is passed through [`path_clean`].
490fn path_join(elem: &[&str]) -> String {
491 // Go returns "" when the total length of all elements is zero (which, since
492 // empty elements are skipped, means every element is empty).
493 if elem.iter().all(|e| e.is_empty()) {
494 return String::new();
495 }
496 let mut buf = String::new();
497 for &e in elem {
498 if !buf.is_empty() || !e.is_empty() {
499 if !buf.is_empty() {
500 buf.push('/');
501 }
502 buf.push_str(e);
503 }
504 }
505 path_clean(&buf)
506}
507
508// ── LTX path helpers ──────────────────────────────────────────────────────────
509//
510// Ported from [email protected] litestream.go:184-197.
511
512/// Returns the path to the LTX directory under a given root.
513///
514/// Ported from `LTXDir` in [email protected] litestream.go:185:
515/// `return path.Join(root, "ltx")`.
516pub fn ltx_dir(root: &str) -> String {
517 path_join(&[root, "ltx"])
518}
519
520/// Returns the path to the LTX level sub-directory.
521///
522/// Ported from `LTXLevelDir` in [email protected] litestream.go:190-191:
523/// `return path.Join(LTXDir(root), strconv.Itoa(level))`. Note the
524/// composition over the already-cleaned `LTXDir(root)`, which we preserve so
525/// `..` resolution matches Go exactly.
526pub fn ltx_level_dir(root: &str, level: u32) -> String {
527 path_join(&[&ltx_dir(root), &level.to_string()])
528}
529
530/// Returns the path to a single LTX file for a given transaction range.
531///
532/// The filename follows the convention `<minTXID>-<maxTXID>.ltx` with both
533/// TXIDs formatted as 16-digit lowercase hex.
534///
535/// Ported from `LTXFilePath` in [email protected] litestream.go:195-196:
536/// `return path.Join(LTXLevelDir(root, level), ltx.FormatFilename(minTXID, maxTXID))`
537/// and `FormatFilename` in [email protected] ltx.go:487
538/// (`fmt.Sprintf("%s-%s.ltx", minTXID.String(), maxTXID.String())`).
539pub fn ltx_file_path(root: &str, level: u32, min_txid: TXID, max_txid: TXID) -> String {
540 let filename = format!("{}-{}.ltx", min_txid, max_txid);
541 path_join(&[&ltx_level_dir(root, level), &filename])
542}