Diffinery

homeflare/celldpublic

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