Diffinery

homeflare/celldpublic

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