Diffinery

homeflare/celldpublic

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