Diffinery

homeflare/celldpublic

celld/crates/ltx/src/replica.rs
1024 lines · 38.2 KBRaw History
1//! replica.rs — single-replica sync loop + restore orchestration.
2//! Ported from [email protected] `replica.go`.
3//!
4//! A [`Replica`] connects a managed [`crate::db::Db`] to a replication
5//! destination via a [`ReplicaClient`]. It drives two halves of replication:
6//!
7//! * **sync** (`replica.go:132-180`): copy each new L0 LTX file the capture loop
8//! wrote locally up to the remote replica, advancing the replicated position
9//! one TXID at a time. `calc_pos` (`replica.go:208-214`) recovers the starting
10//! position from the newest file already on the replica.
11//! * **restore** (`replica.go:533-725`): download the LTX files from the replica
12//! in TXID order, merge them (the compactor in `ltx.NewCompactor`,
13//! [email protected] compactor.go), and reconstruct the SQLite database file the way
14//! `Decoder.DecodeDatabaseTo` ([email protected] decoder.go:223-268) does — pages
15//! `1..=commit`, lock page zero-filled, written verbatim — to a temp file that
16//! is fsync'd and atomically renamed into place.
17//!
18//! ## Scope: L0-only, single replica
19//! The real `litestream v0.5.11` L0-only architecture stores **everything at
20//! level 0** — the snapshot (MinTXID==1) and every incremental — under
21//! `ltx/0/`. The snapshot level (`SnapshotLevel = 9`,
22//! compaction_level.go:9) is empty without compaction. [`calc_restore_plan`] is
23//! ported faithfully (snapshot anchor at `SnapshotLevel` + per-level cursors so
24//! adding compaction later "just works"), but in this scope the plan is the
25//! contiguous L0 chain `1..=N`.
26//!
27//! ## Deferred work that needs a background runtime or additional scope
28//! * **Follow mode** (`replica.go:730-987`, `applyLTXFile`/`fillFollowGap`): the
29//! continuous tail-restore loop. The current API performs one restore.
30//! * **The background monitor goroutine + backoff** (`replica.go:326-441`) and
31//! `Start`/`Stop`: need a Tokio task owning the `Db`; the
32//! synchronous `sync()` primitive it would call is implemented here.
33//! * **V3 (v0.3.x generation) restore** (`RestoreV3`, replica.go:990-1096) is not
34//! included because celld has no earlier replica generation to support.
35//! * **Timestamp / `-txid` targeted restore plumbing through the public API**:
36//! [`calc_restore_plan`] honors a target TXID, but the
37//! timestamp path and `RestoreOptions` surface stay minimal for the one-shot.
38
39// Restore phase durations are diagnostics in this stand-alone public crate.
40// celld injects its scheduling facilities at the engine boundary.
41#![allow(clippy::disallowed_methods)]
42
43use crate::client::ReplicaClient;
44use crate::db::Db;
45use crate::error::{new_ltx_error, Error, Result};
46use crate::ltx::{self, FileInfo};
47use crate::{Pos, TXID};
48use futures_util::stream;
49use futures_util::StreamExt;
50use futures_util::TryStreamExt;
51use std::collections::{BTreeMap, HashMap, HashSet};
52use std::path::{Path, PathBuf};
53use std::sync::Arc;
54use std::time::Instant;
55use tokio::sync::Semaphore;
56
57/// Keep enough reads in flight to hide an object store's round-trip latency,
58/// while the caller's semaphore bounds aggregate restore traffic.
59const RESTORE_DOWNLOAD_CONCURRENCY: usize = 64;
60
61/// The compaction level which full snapshots are held at.
62///
63/// Ported from `SnapshotLevel` (compaction_level.go:9). In the L0-only one-shot
64/// scope no files land here (snapshots are written at L0), but
65/// [`calc_restore_plan`] still probes it first so the algorithm stays a faithful
66/// port that works the moment compaction is added.
67pub use crate::compaction_level::SNAPSHOT_LEVEL;
68
69/// The number of compaction levels that one restore-plan calculation can list
70/// concurrently. A caller-supplied semaphore still bounds all remote requests.
71const RESTORE_PLAN_CONCURRENCY: usize = SNAPSHOT_LEVEL as usize + 1;
72
73/// Whether a sync error means the cached replica position can no longer be
74/// trusted and must be re-derived from the store on the next sync.
75///
76/// True only for errors that say the local/replica state itself diverged. A
77/// transient store or IO error is not one of these: a fenced single writer's
78/// position is still valid, and its re-upload is an idempotent overwrite. See
79/// [`Replica::sync`] for why celld narrows Litestream's clear-on-any-error.
80fn pos_untrustworthy(err: &Error) -> bool {
81 matches!(
82 err,
83 Error::NoSnapshots
84 | Error::ChecksumMismatch
85 | Error::LTXCorrupted
86 | Error::LTXMissing
87 | Error::TxNotAvailable
88 )
89}
90
91/// Connects a database to a replication destination via a [`ReplicaClient`].
92///
93/// Ported from `Replica` (replica.go:30-59). The Go type also owns the
94/// background-monitor machinery (`wg`/`cancel`/`f`) and tunables
95/// (`SyncInterval`/`MonitorEnabled`); those drive the deferred monitor loop and
96/// are intentionally omitted here (see module docs).
97pub struct Replica<C: ReplicaClient> {
98 /// The database being replicated. `None` for a restore-only replica (the Go
99 /// `NewReplicaWithClient(nil, client)` restore-only shape).
100 db: Option<Db>,
101
102 /// Client used to connect to the remote replica.
103 pub client: C,
104
105 /// Current replicated position (`replica.go:33-34` `pos`).
106 pos: Pos,
107
108 /// Whether `pos` is known and needs no `calc_pos` listing to re-derive.
109 /// Seeded true at activation (see [`Self::seed_pos`]); reset false only when
110 /// a divergence error says the position can no longer be trusted. Upstream
111 /// has no equivalent -- it lists whenever `pos` is zero -- which is the
112 /// listing celld's fencing lets it skip.
113 pos_known: bool,
114}
115
116impl<C: ReplicaClient> Replica<C> {
117 /// Creates a replica that owns `db` and replicates through `client`.
118 ///
119 /// Ported from `NewReplicaWithClient` (replica.go:73-77).
120 pub fn new(db: Db, client: C) -> Self {
121 Replica {
122 db: Some(db),
123 client,
124 pos: Pos::ZERO,
125 pos_known: false,
126 }
127 }
128
129 /// Creates a restore-only replica with no attached database (Go's
130 /// `NewReplicaWithClient(nil, client)`).
131 pub fn new_client_only(client: C) -> Self {
132 Replica {
133 db: None,
134 client,
135 pos: Pos::ZERO,
136 pos_known: false,
137 }
138 }
139
140 /// Returns a reference to the attached database, if any.
141 /// Ported from `Replica.DB` (replica.go:89).
142 pub fn db(&self) -> Option<&Db> {
143 self.db.as_ref()
144 }
145
146 /// Consumes the replica and returns the attached database, if any. Lets a
147 /// host perform a clean [`Db::close`] (which consumes the `Db`) after a final
148 /// sync — the shutdown ordering the deferred monitor loop would otherwise own
149 /// (replica.go `Stop` → `db.Close`).
150 pub fn into_db(self) -> Option<Db> {
151 self.db
152 }
153
154 /// Returns a mutable reference to the attached database, if any. Lets a
155 /// caller drive `db.sync()` (the local capture half) before `replica.sync()`
156 /// (the upload half) — the `SyncAndWait` ordering (db.go:500-512).
157 pub fn db_mut(&mut self) -> Option<&mut Db> {
158 self.db.as_mut()
159 }
160
161 /// The current replicated position. Ported from `Replica.Pos`
162 /// (replica.go:237-241).
163 pub fn pos(&self) -> Pos {
164 self.pos
165 }
166
167 /// Sets the current replicated position. Ported from `Replica.SetPos`
168 /// (replica.go:244-248).
169 fn set_pos(&mut self, pos: Pos) {
170 self.pos = pos;
171 }
172
173 /// Seed the replicated position from the caller's known-durable state and
174 /// mark it known, so the next sync skips the `calc_pos` listing. A fresh
175 /// cell seeds 0; a just-restored cell seeds its restored max. celld always
176 /// knows this at activation -- local equals remote under epoch fencing --
177 /// so the listing that only existed to re-discover the position, and that
178 /// storms a rate-limiting store, is not issued on the activation path.
179 pub fn seed_pos(&mut self, pos: Pos) {
180 self.pos = pos;
181 self.pos_known = true;
182 }
183
184 /// Copies new L0 LTX files from the local capture directory to the replica.
185 ///
186 /// Ported from `Replica.Sync` (replica.go:132-180). On any error the cached
187 /// position is cleared so the next sync recomputes it from the replica
188 /// (replica.go:137-143). Requires an attached database.
189 pub async fn sync(&mut self) -> Result<()> {
190 match self.sync_inner().await {
191 Ok(()) => Ok(()),
192 Err(e) => {
193 // Litestream clears the cached position on *any* error so the
194 // next sync re-derives it with a `calc_pos` listing
195 // (replica.go:137-143) -- safe there only because it is single-
196 // node with no fencing. celld fences one writer per epoch
197 // through the store, so within an epoch a transient store/IO
198 // error does not invalidate our own position; re-uploads are
199 // idempotent overwrites. Forget the position only when the
200 // error says the state itself diverged, else a rate-limiting or
201 // slow store turns every write into a listing.
202 if pos_untrustworthy(&e) {
203 self.pos = Pos::ZERO;
204 self.pos_known = false;
205 }
206 Err(e)
207 }
208 }
209 }
210
211 async fn sync_inner(&mut self) -> Result<()> {
212 // Re-derive the replica position with a listing only when it is not
213 // already known (replica.go:146-152). celld seeds it at activation from
214 // local state that equals the remote under epoch fencing, so a listing
215 // -- which only ever re-discovered a position the owner already knows --
216 // never runs on the hot path, and a fresh cell's pointless list of an
217 // empty prefix is skipped entirely.
218 if !self.pos_known {
219 let pos = self
220 .calc_pos()
221 .await
222 .map_err(|e| Error::Other(format!("calc pos: {e}").into()))?;
223 self.set_pos(pos);
224 self.pos_known = true;
225 }
226
227 // Find current position of the database (replica.go:155-160).
228 let dpos = {
229 let db = self
230 .db
231 .as_mut()
232 .ok_or_else(|| Error::Other("no database attached to replica".into()))?;
233 db.pos().map_err(|e| {
234 Error::Other(format!("cannot determine current position: {e}").into())
235 })?
236 };
237 if dpos.is_zero() {
238 return Err(Error::Other("no position, waiting for data".into()));
239 }
240
241 // Replicate all L0 LTX files since the last replica position
242 // (replica.go:169-174). Each successful upload advances pos by one TXID;
243 // re-reading `self.pos()` each iteration mirrors the Go loop exactly.
244 loop {
245 let tx_id = TXID(self.pos().txid.0 + 1);
246 if tx_id > dpos.txid {
247 break;
248 }
249 self.upload_ltx_file(0, tx_id, tx_id).await?;
250 self.set_pos(Pos::new(tx_id, 0));
251 }
252
253 Ok(())
254 }
255
256 /// Uploads a single local LTX file to the replica.
257 ///
258 /// Ported from `Replica.uploadLTXFile` (replica.go:182-205). A failure to
259 /// open the local file is wrapped as an `LTXError{op:"open"}` so the monitor
260 /// can classify auto-recoverable corruption (replica.go:186). The write
261 /// itself is delegated to the client.
262 async fn upload_ltx_file(&mut self, level: i32, min_txid: TXID, max_txid: TXID) -> Result<()> {
263 let db = self
264 .db
265 .as_ref()
266 .ok_or_else(|| Error::Other("no database attached to replica".into()))?;
267 let filename = db.ltx_path(level as u32, min_txid, max_txid);
268
269 let data = match db.read_ltx_file(level as u32, min_txid, max_txid) {
270 Ok(b) => b,
271 Err(e) => {
272 return Err(Error::Ltx(Box::new(new_ltx_error(
273 "open", &filename, level, min_txid.0, max_txid.0, e,
274 ))));
275 }
276 };
277
278 self.client
279 .write_ltx_file(level, min_txid, max_txid, &data)
280 .await
281 .map_err(|e| Error::Other(format!("write ltx file: {e}").into()))?;
282
283 Ok(())
284 }
285
286 /// Returns the last position saved to the replica for level 0.
287 ///
288 /// Ported from `Replica.calcPos` (replica.go:208-214) + `MaxLTXFileInfo`
289 /// (replica.go:218-233): scans the L0 listing for the highest `max_txid`.
290 async fn calc_pos(&self) -> Result<Pos> {
291 let info = self
292 .max_ltx_file_info(0)
293 .await
294 .map_err(|e| Error::Other(format!("max ltx file: {e}").into()))?;
295 Ok(Pos::new(info.max_txid, info.post_apply_checksum))
296 }
297
298 /// Metadata about the last LTX file for a given level (highest `max_txid`),
299 /// or a zero `FileInfo` if none exist. Ported from `Replica.MaxLTXFileInfo`
300 /// (replica.go:218-233).
301 async fn max_ltx_file_info(&self, level: i32) -> Result<FileInfo> {
302 let files = self.client.ltx_files(level, TXID(0)).await?;
303 let mut info = FileInfo::default();
304 for item in files {
305 if item.max_txid > info.max_txid {
306 info = item;
307 }
308 }
309 Ok(info)
310 }
311
312 /// Restores the database from this replica's client into `output_path`.
313 ///
314 /// Convenience wrapper over [`restore`] using this replica's client and the
315 /// most-recent state (no target TXID). Mirrors the common
316 /// `Replica.Restore(ctx, opt)` call with `OutputPath` set and no TXID
317 /// (replica.go:533).
318 pub async fn restore(&self, output_path: impl AsRef<Path>) -> Result<RestorePlanStats> {
319 restore(&self.client, output_path, TXID(0)).await
320 }
321
322 /// Detects when the local database has been restored to an earlier state
323 /// than the replica (a lower TXID) and, if so, seeds the local L0 directory
324 /// with the replica's newest L0 file so the next sync snapshots forward.
325 ///
326 /// Ported from `DB.checkDatabaseBehindReplica` (db.go:1211-1294), issue #781.
327 /// In upstream this runs inside `DB.init()` because the `DB` owns its
328 /// `Replica`; our synchronous `Db` does not, so the orchestration lives here
329 /// on `Replica` and a host calls it once after [`Db::open`], before the first
330 /// sync. The file-writing tail is [`Db::seed_l0_baseline`].
331 ///
332 /// Without this, a hard recovery (restore an old snapshot, reopen, write new
333 /// data) would silently drop the new writes: the fresh local DB snapshots at
334 /// TXID 1, but [`Replica::sync`] computes the replica position from the
335 /// remote's higher `MaxTXID`, so its upload loop (`pos+1 ..= db.pos`) never
336 /// runs (`pos+1` already exceeds the local DB's TXID). Seeding the remote
337 /// baseline makes the next [`Db::sync`] see a continuity break and snapshot at
338 /// the current (post-restore-plus-writes) state, which then uploads.
339 ///
340 /// No-op (returns `Ok`) when there is no remote data, when the database is at
341 /// or ahead of the replica, or when there is no attached database.
342 pub async fn check_database_behind_replica(&mut self) -> Result<()> {
343 // Replica position from remote (db.go:1224-1230). Done first so a
344 // restore-only replica with no DB is a clean no-op.
345 let replica_info = self.max_ltx_file_info(0).await?;
346 if replica_info.max_txid == TXID(0) {
347 return Ok(()); // no remote replica data yet
348 }
349
350 let db = match self.db.as_mut() {
351 Some(db) => db,
352 None => return Ok(()),
353 };
354
355 // Database position from local L0 files (db.go:1218-1222).
356 let db_pos = db
357 .pos()
358 .map_err(|e| Error::Other(format!("get database position: {e}").into()))?;
359
360 // If the database is ahead or equal, nothing to do (db.go:1232-1235).
361 if db_pos.txid >= replica_info.max_txid {
362 return Ok(());
363 }
364
365 // Fetch the latest L0 LTX file from the replica (db.go:1251-1257).
366 let min_txid = replica_info.min_txid;
367 let max_txid = replica_info.max_txid;
368 let data = self
369 .client
370 .open_ltx_file(0, min_txid, max_txid)
371 .await
372 .map_err(|e| Error::Other(format!("open remote L0 file: {e}").into()))?;
373
374 // Seed it as the local baseline (db.go:1259-1293).
375 db.seed_l0_baseline(min_txid, max_txid, &data)?;
376
377 // Drop the now-stale cached replica position so the next sync recomputes
378 // it from the remote (mirrors clearing pos on a state change).
379 self.pos = Pos::ZERO;
380 Ok(())
381 }
382}
383
384/// Restores a database from `client` into `output_path`, optionally up to a
385/// target `txid` (`TXID(0)` = most recent state).
386///
387/// Ported from `Replica.Restore` (replica.go:533-725), LTX path only. Steps:
388/// 1. refuse to overwrite an existing output (replica.go:591-595);
389/// 2. [`calc_restore_plan`] → the ordered snapshot+incremental file list;
390/// 3. download + merge them (compactor semantics) and reconstruct the database
391/// image the way `Decoder.DecodeDatabaseTo` does;
392/// 4. write to `<output>.tmp`, fsync, and atomically rename (replica.go:657-694).
393///
394/// The V3 generation path and follow mode are out of scope (see module docs).
395pub async fn restore<C: ReplicaClient>(
396 client: &C,
397 output_path: impl AsRef<Path>,
398 txid: TXID,
399) -> Result<RestorePlanStats> {
400 restore_with_host_and_download_slots(
401 client,
402 output_path,
403 txid,
404 crate::LtxHost::default(),
405 Arc::new(Semaphore::new(1)),
406 )
407 .await
408}
409
410/// What a restore read: the plan's shape, for the caller's telemetry.
411#[derive(Debug, Clone)]
412pub struct RestorePlanStats {
413 pub objects: usize,
414 pub bytes: u64,
415 /// Object count per compaction level, ordered by level.
416 pub by_level: BTreeMap<i32, usize>,
417}
418
419/// Wall-clock phases for one successful restore.
420#[derive(Debug, Clone)]
421pub struct RestoreTimingStats {
422 pub plan: RestorePlanStats,
423 pub plan_us: u64,
424 pub download_us: u64,
425 pub apply_us: u64,
426}
427
428/// Restores a database like [`restore`], but downloads independent LTX files
429/// concurrently. All restores that share `download_slots` share one hard I/O
430/// ceiling, so a cold cohort cannot multiply the limit per cell.
431pub async fn restore_with_download_slots<C: ReplicaClient>(
432 client: &C,
433 output_path: impl AsRef<Path>,
434 txid: TXID,
435 download_slots: Arc<Semaphore>,
436) -> Result<RestorePlanStats> {
437 restore_with_host_and_download_slots(
438 client,
439 output_path,
440 txid,
441 crate::LtxHost::default(),
442 download_slots,
443 )
444 .await
445}
446
447/// Restores a database through an injected local filesystem.
448pub async fn restore_with_host_and_download_slots<C: ReplicaClient>(
449 client: &C,
450 output_path: impl AsRef<Path>,
451 txid: TXID,
452 host: crate::LtxHost,
453 download_slots: Arc<Semaphore>,
454) -> Result<RestorePlanStats> {
455 Ok(
456 restore_timed_with_host_and_download_slots(client, output_path, txid, host, download_slots)
457 .await?
458 .plan,
459 )
460}
461
462/// Restores a database and reports the plan, download, and local apply times.
463pub async fn restore_timed_with_download_slots<C: ReplicaClient>(
464 client: &C,
465 output_path: impl AsRef<Path>,
466 txid: TXID,
467 download_slots: Arc<Semaphore>,
468) -> Result<RestoreTimingStats> {
469 restore_timed_with_host_and_download_slots(
470 client,
471 output_path,
472 txid,
473 crate::LtxHost::default(),
474 download_slots,
475 )
476 .await
477}
478
479/// Restores a database through an injected local filesystem and reports the
480/// plan, download, and local apply times.
481pub async fn restore_timed_with_host_and_download_slots<C: ReplicaClient>(
482 client: &C,
483 output_path: impl AsRef<Path>,
484 txid: TXID,
485 host: crate::LtxHost,
486 download_slots: Arc<Semaphore>,
487) -> Result<RestoreTimingStats> {
488 let output_path = output_path.as_ref();
489 ensure_restore_output_absent(&host, output_path)?;
490 let plan_started = Instant::now();
491 let infos = calc_restore_plan_with_slots(client, txid, download_slots.clone()).await?;
492 let plan_us = plan_started.elapsed().as_micros() as u64;
493 restore_from_plan_inner(client, output_path, infos, host, download_slots, plan_us).await
494}
495
496/// Restores a database from a plan which [`calc_restore_plan`] produced.
497///
498/// This path lets a caller reuse the exact plan that fixed an epoch seal. It
499/// therefore avoids a second remote listing before it downloads the files.
500pub async fn restore_from_plan_with_download_slots<C: ReplicaClient>(
501 client: &C,
502 output_path: impl AsRef<Path>,
503 plan: Vec<FileInfo>,
504 download_slots: Arc<Semaphore>,
505) -> Result<RestoreTimingStats> {
506 let output_path = output_path.as_ref();
507 let host = crate::LtxHost::default();
508 ensure_restore_output_absent(&host, output_path)?;
509 restore_from_plan_inner(client, output_path, plan, host, download_slots, 0).await
510}
511
512fn ensure_restore_output_absent(host: &crate::LtxHost, output_path: &Path) -> Result<()> {
513 // Ensure output path does not already exist (replica.go:591-595).
514 match host.metadata(output_path) {
515 Ok(_) => {
516 return Err(Error::Other(
517 format!(
518 "cannot restore, output path already exists: {}",
519 output_path.display()
520 )
521 .into(),
522 ));
523 }
524 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
525 Err(e) => return Err(e.into()),
526 }
527 Ok(())
528}
529
530async fn restore_from_plan_inner<C: ReplicaClient>(
531 client: &C,
532 output_path: &Path,
533 infos: Vec<FileInfo>,
534 host: crate::LtxHost,
535 download_slots: Arc<Semaphore>,
536 plan_us: u64,
537) -> Result<RestoreTimingStats> {
538 // Validate the whole plan before starting I/O. An invalid later entry must
539 // not cause a partial download burst before the restore fails.
540 for info in &infos {
541 if info.size < ltx::HEADER_SIZE as i64 {
542 return Err(Error::Other(
543 format!(
544 "invalid ltx file: level={} min={} max={} has size {} bytes (minimum {})",
545 info.level,
546 info.min_txid,
547 info.max_txid,
548 info.size,
549 ltx::HEADER_SIZE
550 )
551 .into(),
552 ));
553 }
554 }
555
556 let mut stats = RestorePlanStats {
557 objects: infos.len(),
558 bytes: infos.iter().map(|info| info.size.max(0) as u64).sum(),
559 by_level: BTreeMap::new(),
560 };
561 for info in &infos {
562 *stats.by_level.entry(info.level).or_insert(0) += 1;
563 }
564
565 // Files are independent reads. `buffered` overlaps them but yields them in
566 // plan order, which preserves the compactor input contract. The shared
567 // semaphore is the node-level ceiling across every concurrent restore.
568 let download_started = Instant::now();
569 let files: Vec<Vec<u8>> = stream::iter(infos)
570 .map(|info| {
571 let download_slots = download_slots.clone();
572 async move {
573 let _permit = download_slots
574 .acquire_owned()
575 .await
576 .expect("restore download semaphore closed");
577 client
578 .open_ltx_file(info.level, info.min_txid, info.max_txid)
579 .await
580 .map_err(|e| Error::Other(format!("open ltx file: {e}").into()))
581 }
582 })
583 .buffered(RESTORE_DOWNLOAD_CONCURRENCY)
584 .try_collect()
585 .await?;
586 let download_us = download_started.elapsed().as_micros() as u64;
587
588 if files.is_empty() {
589 return Err(Error::Other("no matching backup files available".into()));
590 }
591
592 // Merge the files (compactor) and reconstruct the SQLite database image.
593 let apply_started = Instant::now();
594 let image = build_database_image(&files)?;
595
596 // Create the parent directory if needed (replica.go:649-655).
597 if let Some(parent) = output_path.parent() {
598 if !parent.as_os_str().is_empty() {
599 host.create_dir_all(parent)?;
600 }
601 }
602
603 // Output to a temp file & atomically rename (replica.go:657-694).
604 let tmp_output_path = append_ext(output_path, "tmp");
605 write_file_atomic(&host, &tmp_output_path, output_path, &image)?;
606 let apply_us = apply_started.elapsed().as_micros() as u64;
607
608 Ok(RestoreTimingStats {
609 plan: stats,
610 plan_us,
611 download_us,
612 apply_us,
613 })
614}
615
616/// Returns the ordered list of LTX files needed to restore the database at
617/// `txid` (`TXID(0)` = latest).
618///
619/// Ported from `CalcRestorePlan` (replica.go:1419-1536). Anchors on the latest
620/// snapshot at or before the target, then walks compaction levels
621/// `SnapshotLevel-1 ..= 0` with per-level cursors, repeatedly choosing the file
622/// that extends the longest contiguous TXID range. In the L0-only scope the
623/// snapshot anchor lives at L0 (MinTXID==1) and the only cursor with files is
624/// level 0, so the result is the contiguous chain `1..=N` (capped at `txid`).
625pub async fn calc_restore_plan<C: ReplicaClient>(client: &C, txid: TXID) -> Result<Vec<FileInfo>> {
626 calc_restore_plan_with_slots(
627 client,
628 txid,
629 Arc::new(Semaphore::new(RESTORE_PLAN_CONCURRENCY)),
630 )
631 .await
632}
633
634/// Calculates a restore plan while a shared semaphore bounds remote listings.
635pub async fn calc_restore_plan_with_slots<C: ReplicaClient>(
636 client: &C,
637 txid: TXID,
638 request_slots: Arc<Semaphore>,
639) -> Result<Vec<FileInfo>> {
640 let mut infos: Vec<FileInfo> = Vec::new();
641
642 // Every level is independent. List them together instead of paying ten
643 // object-store round trips in series. The shared request slots keep a cold
644 // cohort from multiplying this fan-out by its activation count.
645 let levels: Vec<(i32, Vec<FileInfo>)> = stream::iter((0..=SNAPSHOT_LEVEL).rev())
646 .map(|level| {
647 let request_slots = request_slots.clone();
648 async move {
649 let _permit = request_slots
650 .acquire_owned()
651 .await
652 .expect("restore request semaphore closed");
653 Ok::<_, Error>((level, client.ltx_files(level, TXID(0)).await?))
654 }
655 })
656 .buffered(RESTORE_PLAN_CONCURRENCY)
657 .try_collect()
658 .await?;
659 let mut levels = levels.into_iter().collect::<BTreeMap<_, _>>();
660
661 // Start with the latest snapshot before the target TXID (replica.go:1430-1452).
662 let snapshot_files = levels.remove(&SNAPSHOT_LEVEL).unwrap_or_default();
663 let mut snapshot: Option<FileInfo> = None;
664 for info in snapshot_files {
665 if txid != TXID(0) && info.max_txid > txid {
666 continue;
667 }
668 snapshot = Some(info);
669 }
670 if let Some(s) = snapshot {
671 infos.push(s);
672 }
673
674 // Collect candidates across all compaction levels and pick the next file
675 // from any level that extends the longest contiguous TXID range
676 // (replica.go:1454-1515).
677 let max_level = SNAPSHOT_LEVEL - 1;
678 let start_txid = slice_max_txid(&infos);
679 let mut current_max = start_txid;
680 if txid != TXID(0) && current_max >= txid {
681 return Ok(infos);
682 }
683
684 // Build a cursor per level, highest level first (replica.go:1463-1473).
685 let mut cursors: Vec<RestoreLevelCursor> = Vec::with_capacity((max_level + 1) as usize);
686 for level in (0..=max_level).rev() {
687 let files = levels.remove(&level).unwrap_or_default();
688 cursors.push(RestoreLevelCursor::new(files));
689 }
690
691 loop {
692 // Choose the best candidate across all level cursors (replica.go:1483-1494).
693 let mut next_idx: Option<usize> = None;
694 for i in 0..cursors.len() {
695 cursors[i].refresh(current_max, txid);
696 if cursors[i].candidate.is_none() {
697 continue;
698 }
699 match next_idx {
700 None => next_idx = Some(i),
701 Some(ni) => {
702 let cand = cursors[i].candidate.as_ref().unwrap();
703 let best = cursors[ni].candidate.as_ref().unwrap();
704 if restore_candidate_better(best, cand) {
705 next_idx = Some(i);
706 }
707 }
708 }
709 }
710
711 let ni = match next_idx {
712 Some(ni) => ni,
713 None => break,
714 };
715
716 // Take the chosen candidate (replica.go:1500-1510).
717 let cand = cursors[ni].candidate.take().unwrap();
718 if cand.max_txid <= current_max {
719 continue;
720 }
721 current_max = cand.max_txid;
722 infos.push(cand);
723
724 if txid != TXID(0) && current_max >= txid {
725 break;
726 }
727 }
728
729 // For a latest/most-recent restore, verify the tail is contiguous
730 // (replica.go:1517-1526).
731 if !infos.is_empty() && txid == TXID(0) {
732 for cursor in cursors.iter_mut() {
733 cursor.ensure_current();
734 if let Some(cur) = &cursor.current {
735 if cur.min_txid.0 > current_max.0 + 1 {
736 return Err(Error::Other(
737 format!(
738 "non-contiguous ltx files: have up to {} but next file starts at {}",
739 current_max, cur.min_txid
740 )
741 .into(),
742 ));
743 }
744 }
745 }
746 }
747
748 if infos.is_empty() {
749 return Err(Error::TxNotAvailable);
750 }
751 if txid != TXID(0) && slice_max_txid(&infos) < txid {
752 return Err(Error::TxNotAvailable);
753 }
754
755 Ok(infos)
756}
757
758/// A single level's streaming view during restore planning.
759///
760/// Ported from `restoreLevelCursor` (replica.go:1538-1603). The Go version
761/// streams from a `FileIterator`; here the client already returns a sorted
762/// `Vec<FileInfo>`, so the "iterator" is the slice plus a read index.
763struct RestoreLevelCursor {
764 /// Files for this level, sorted ascending (the `LTXFiles` contract).
765 files: Vec<FileInfo>,
766 /// Read index into `files` (the iterator cursor).
767 idx: usize,
768 /// Last item read but not yet evaluated (`current`, replica.go:1542).
769 current: Option<FileInfo>,
770 /// Best eligible file at this level for the current `current_max`
771 /// (`candidate`, replica.go:1544).
772 candidate: Option<FileInfo>,
773 /// True once the iterator is exhausted (`done`, replica.go:1546).
774 done: bool,
775}
776
777impl RestoreLevelCursor {
778 fn new(files: Vec<FileInfo>) -> Self {
779 RestoreLevelCursor {
780 files,
781 idx: 0,
782 current: None,
783 candidate: None,
784 done: false,
785 }
786 }
787
788 /// Advances the iterator while files could be contiguous with `current_max`,
789 /// keeping the best eligible candidate. Ported from `refresh`
790 /// (replica.go:1549-1587).
791 fn refresh(&mut self, current_max: TXID, txid: TXID) {
792 if self.done {
793 return;
794 }
795 if let Some(c) = &self.candidate {
796 if c.max_txid <= current_max {
797 self.candidate = None;
798 }
799 }
800
801 loop {
802 self.ensure_current();
803 if self.done {
804 return;
805 }
806
807 let info = self.current.clone().unwrap();
808 if info.min_txid.0 > current_max.0 + 1 {
809 return;
810 }
811 self.current = None;
812
813 if info.max_txid <= current_max {
814 continue;
815 }
816 if txid != TXID(0) && info.max_txid > txid {
817 continue;
818 }
819
820 match &self.candidate {
821 None => self.candidate = Some(info),
822 Some(c) => {
823 if restore_candidate_better(c, &info) {
824 self.candidate = Some(info);
825 }
826 }
827 }
828 }
829 }
830
831 /// Populates `current` with the next item, or marks `done`. Ported from
832 /// `ensureCurrent` (replica.go:1589-1603).
833 fn ensure_current(&mut self) {
834 if self.done || self.current.is_some() {
835 return;
836 }
837 if self.idx >= self.files.len() {
838 self.done = true;
839 return;
840 }
841 self.current = Some(self.files[self.idx].clone());
842 self.idx += 1;
843 }
844}
845
846/// True if `next` is a strictly better restore candidate than `curr`: longer
847/// reach first (`MaxTXID`), then a smaller `MinTXID` (more coverage), then a
848/// higher level (more compacted), then an earlier `created_at`.
849///
850/// Ported from `restoreCandidateBetter` (replica.go:1605-1616).
851fn restore_candidate_better(curr: &FileInfo, next: &FileInfo) -> bool {
852 if next.max_txid != curr.max_txid {
853 return next.max_txid > curr.max_txid;
854 }
855 if next.min_txid != curr.min_txid {
856 return next.min_txid < curr.min_txid;
857 }
858 if next.level != curr.level {
859 return next.level > curr.level;
860 }
861 // CreatedAt.Before(curr): an unknown (None) timestamp is treated as not
862 // earlier, matching Go's zero-time comparison being false here.
863 match (next.created_at, curr.created_at) {
864 (Some(n), Some(c)) => n < c,
865 _ => false,
866 }
867}
868
869/// Maximum `max_txid` across a slice, `TXID(0)` if empty. Mirrors
870/// `FileInfoSlice.MaxTXID` (ltx.go:612-619); the slice here is already in plan
871/// (ascending) order, but we scan defensively rather than assume.
872fn slice_max_txid(infos: &[FileInfo]) -> TXID {
873 infos.iter().map(|f| f.max_txid).max().unwrap_or(TXID(0))
874}
875
876/// Merges the LTX `files` (a snapshot followed by incrementals, in plan order)
877/// and reconstructs the full SQLite database image.
878///
879/// This replaces Go's `ltx.NewCompactor(pw, rdrs)` + `Decoder.DecodeDatabaseTo`
880/// (replica.go:667-682). The compactor's contract ([email protected] compactor.go):
881/// * page sizes must match across inputs;
882/// * the **last** input's `Commit` is the final database size;
883/// * for each page number, the **latest** input that carries it wins
884/// (compactor.go:198-228 iterates inputs newest-first);
885/// * pages numbered beyond the final `Commit` are dropped (truncation).
886///
887/// `DecodeDatabaseTo` then writes pages `1..=Commit`, zero-filling the lock page
888/// (decoder.go:236-254). Every input is fully decoded and checksum-verified, so
889/// a corrupt download is caught here.
890fn build_database_image(files: &[Vec<u8>]) -> Result<Vec<u8>> {
891 let mut page_size = None;
892 let mut commit = None;
893 let mut merged: HashMap<u32, Vec<u8>> = HashMap::new();
894
895 for data in files {
896 let (decoded, pages) = ltx::decode_file_with_pages(data)?;
897 let header = decoded.header;
898 if let Some(expected) = page_size {
899 if header.page_size != expected {
900 return Err(Error::Other(
901 format!(
902 "input files have mismatched page sizes: {} != {}",
903 expected, header.page_size
904 )
905 .into(),
906 ));
907 }
908 } else {
909 page_size = Some(header.page_size);
910 }
911 let previous_commit = commit.unwrap_or(0);
912 if header.commit > previous_commit {
913 let present: HashSet<u32> = pages.iter().map(|(pgno, _)| *pgno).collect();
914 let lock = ltx::lock_pgno(header.page_size);
915 for pgno in (previous_commit + 1)..=header.commit {
916 if pgno != lock && !present.contains(&pgno) && !merged.contains_key(&pgno) {
917 return Err(Error::Other(
918 format!(
919 "missing newly committed page {pgno} in LTX transaction {} (database grew from {previous_commit} to {} pages)",
920 header.max_txid, header.commit,
921 )
922 .into(),
923 ));
924 }
925 }
926 }
927
928 // Inputs arrive oldest to newest, so moving each page into the map makes
929 // the latest input win without a second staging collection or clone.
930 for (pgno, data) in pages {
931 merged.insert(pgno, data);
932 }
933 commit = Some(header.commit);
934 }
935
936 let (Some(page_size), Some(commit)) = (page_size, commit) else {
937 return Err(Error::Other(
938 "cannot build a database from no LTX files".into(),
939 ));
940 };
941 merged.retain(|pgno, _| *pgno <= commit);
942
943 let page_size_usize = page_size as usize;
944 let lock = ltx::lock_pgno(page_size);
945
946 // Reconstruct the database image: pages 1..=commit, lock page zero-filled
947 // (decoder.go:236-254). A non-lock page missing from the merge means the
948 // backup chain is incomplete.
949 let mut image = Vec::with_capacity(commit as usize * page_size_usize);
950 let zero_page = vec![0u8; page_size_usize];
951 for pgno in 1..=commit {
952 if pgno == lock {
953 image.extend_from_slice(&zero_page);
954 continue;
955 }
956 match merged.get(&pgno) {
957 Some(data) => image.extend_from_slice(data),
958 None => {
959 return Err(Error::Other(
960 format!("missing page {pgno} in restore plan (incomplete backup)").into(),
961 ));
962 }
963 }
964 }
965
966 Ok(image)
967}
968
969/// Appends `ext` to `path` as a literal suffix (`p` → `p.tmp`), the way Go's
970/// `opt.OutputPath + ".tmp"` does (NOT `Path::set_extension`, which would replace
971/// an existing extension).
972fn append_ext(path: &Path, ext: &str) -> PathBuf {
973 let mut s = path.as_os_str().to_owned();
974 s.push(".");
975 s.push(ext);
976 PathBuf::from(s)
977}
978
979/// Writes `data` to `tmp_path`, fsyncs, then renames onto `final_path` — the
980/// crash-consistent atomic-write idiom (replica.go:661-694). On any failure the
981/// temp file is removed.
982fn write_file_atomic(
983 host: &crate::LtxHost,
984 tmp_path: &Path,
985 final_path: &Path,
986 data: &[u8],
987) -> Result<()> {
988 let result = (|| -> Result<()> {
989 let mut file = host.create(tmp_path)?;
990 file.write_all(data)?;
991 file.sync_all()?;
992 drop(file);
993 host.rename(tmp_path, final_path)?;
994 Ok(())
995 })();
996 if result.is_err() {
997 let _ = host.remove_file(tmp_path);
998 }
999 result
1000}
1001
1002#[doc(hidden)]
1003pub mod internal {
1004 use super::*;
1005
1006 pub const RESTORE_PLAN_CONCURRENCY: usize = super::RESTORE_PLAN_CONCURRENCY;
1007
1008 pub async fn upload_ltx_file<C: ReplicaClient>(
1009 replica: &mut Replica<C>,
1010 level: i32,
1011 min_txid: TXID,
1012 max_txid: TXID,
1013 ) -> Result<()> {
1014 replica.upload_ltx_file(level, min_txid, max_txid).await
1015 }
1016
1017 pub fn build_database_image(files: &[Vec<u8>]) -> Result<Vec<u8>> {
1018 super::build_database_image(files)
1019 }
1020
1021 pub fn pos_untrustworthy(error: &Error) -> bool {
1022 super::pos_untrustworthy(error)
1023 }
1024}