Diffinery

homeflare/celldpublic

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