Diffinery

homeflare/celldpublic

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