Diffinery

homeflare/celldpublic

celld/crates/ltx/src/replica.rs
1035 lines · 38.7 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
530/// Maps a download failure during restore. A planned object that is gone
531/// becomes [`Error::LTXMissing`], so a caller that owns the listing can build
532/// a fresh plan: epoch GC can delete an object between plan selection and its
533/// download. Every other failure stays opaque and aborts the restore.
534fn classify_restore_open_error(e: Error) -> Error {
535 match &e {
536 Error::Io(io) if io.kind() == std::io::ErrorKind::NotFound => Error::LTXMissing,
537 _ => Error::Other(format!("open ltx file: {e}").into()),
538 }
539}
540
541async fn restore_from_plan_inner<C: ReplicaClient>(
542 client: &C,
543 output_path: &Path,
544 infos: Vec<FileInfo>,
545 host: crate::LtxHost,
546 download_slots: Arc<Semaphore>,
547 plan_us: u64,
548) -> Result<RestoreTimingStats> {
549 // Validate the whole plan before starting I/O. An invalid later entry must
550 // not cause a partial download burst before the restore fails.
551 for info in &infos {
552 if info.size < ltx::HEADER_SIZE as i64 {
553 return Err(Error::Other(
554 format!(
555 "invalid ltx file: level={} min={} max={} has size {} bytes (minimum {})",
556 info.level,
557 info.min_txid,
558 info.max_txid,
559 info.size,
560 ltx::HEADER_SIZE
561 )
562 .into(),
563 ));
564 }
565 }
566
567 let mut stats = RestorePlanStats {
568 objects: infos.len(),
569 bytes: infos.iter().map(|info| info.size.max(0) as u64).sum(),
570 by_level: BTreeMap::new(),
571 };
572 for info in &infos {
573 *stats.by_level.entry(info.level).or_insert(0) += 1;
574 }
575
576 // Files are independent reads. `buffered` overlaps them but yields them in
577 // plan order, which preserves the compactor input contract. The shared
578 // semaphore is the node-level ceiling across every concurrent restore.
579 let download_started = Instant::now();
580 let files: Vec<Vec<u8>> = stream::iter(infos)
581 .map(|info| {
582 let download_slots = download_slots.clone();
583 async move {
584 let _permit = download_slots
585 .acquire_owned()
586 .await
587 .expect("restore download semaphore closed");
588 client
589 .open_ltx_file(info.level, info.min_txid, info.max_txid)
590 .await
591 .map_err(classify_restore_open_error)
592 }
593 })
594 .buffered(RESTORE_DOWNLOAD_CONCURRENCY)
595 .try_collect()
596 .await?;
597 let download_us = download_started.elapsed().as_micros() as u64;
598
599 if files.is_empty() {
600 return Err(Error::Other("no matching backup files available".into()));
601 }
602
603 // Merge the files (compactor) and reconstruct the SQLite database image.
604 let apply_started = Instant::now();
605 let image = build_database_image(&files)?;
606
607 // Create the parent directory if needed (replica.go:649-655).
608 if let Some(parent) = output_path.parent() {
609 if !parent.as_os_str().is_empty() {
610 host.create_dir_all(parent)?;
611 }
612 }
613
614 // Output to a temp file & atomically rename (replica.go:657-694).
615 let tmp_output_path = append_ext(output_path, "tmp");
616 write_file_atomic(&host, &tmp_output_path, output_path, &image)?;
617 let apply_us = apply_started.elapsed().as_micros() as u64;
618
619 Ok(RestoreTimingStats {
620 plan: stats,
621 plan_us,
622 download_us,
623 apply_us,
624 })
625}
626
627/// Returns the ordered list of LTX files needed to restore the database at
628/// `txid` (`TXID(0)` = latest).
629///
630/// Ported from `CalcRestorePlan` (replica.go:1419-1536). Anchors on the latest
631/// snapshot at or before the target, then walks compaction levels
632/// `SnapshotLevel-1 ..= 0` with per-level cursors, repeatedly choosing the file
633/// that extends the longest contiguous TXID range. In the L0-only scope the
634/// snapshot anchor lives at L0 (MinTXID==1) and the only cursor with files is
635/// level 0, so the result is the contiguous chain `1..=N` (capped at `txid`).
636pub async fn calc_restore_plan<C: ReplicaClient>(client: &C, txid: TXID) -> Result<Vec<FileInfo>> {
637 calc_restore_plan_with_slots(
638 client,
639 txid,
640 Arc::new(Semaphore::new(RESTORE_PLAN_CONCURRENCY)),
641 )
642 .await
643}
644
645/// Calculates a restore plan while a shared semaphore bounds remote listings.
646pub async fn calc_restore_plan_with_slots<C: ReplicaClient>(
647 client: &C,
648 txid: TXID,
649 request_slots: Arc<Semaphore>,
650) -> Result<Vec<FileInfo>> {
651 let mut infos: Vec<FileInfo> = Vec::new();
652
653 // Every level is independent. List them together instead of paying ten
654 // object-store round trips in series. The shared request slots keep a cold
655 // cohort from multiplying this fan-out by its activation count.
656 let levels: Vec<(i32, Vec<FileInfo>)> = stream::iter((0..=SNAPSHOT_LEVEL).rev())
657 .map(|level| {
658 let request_slots = request_slots.clone();
659 async move {
660 let _permit = request_slots
661 .acquire_owned()
662 .await
663 .expect("restore request semaphore closed");
664 Ok::<_, Error>((level, client.ltx_files(level, TXID(0)).await?))
665 }
666 })
667 .buffered(RESTORE_PLAN_CONCURRENCY)
668 .try_collect()
669 .await?;
670 let mut levels = levels.into_iter().collect::<BTreeMap<_, _>>();
671
672 // Start with the latest snapshot before the target TXID (replica.go:1430-1452).
673 let snapshot_files = levels.remove(&SNAPSHOT_LEVEL).unwrap_or_default();
674 let mut snapshot: Option<FileInfo> = None;
675 for info in snapshot_files {
676 if txid != TXID(0) && info.max_txid > txid {
677 continue;
678 }
679 snapshot = Some(info);
680 }
681 if let Some(s) = snapshot {
682 infos.push(s);
683 }
684
685 // Collect candidates across all compaction levels and pick the next file
686 // from any level that extends the longest contiguous TXID range
687 // (replica.go:1454-1515).
688 let max_level = SNAPSHOT_LEVEL - 1;
689 let start_txid = slice_max_txid(&infos);
690 let mut current_max = start_txid;
691 if txid != TXID(0) && current_max >= txid {
692 return Ok(infos);
693 }
694
695 // Build a cursor per level, highest level first (replica.go:1463-1473).
696 let mut cursors: Vec<RestoreLevelCursor> = Vec::with_capacity((max_level + 1) as usize);
697 for level in (0..=max_level).rev() {
698 let files = levels.remove(&level).unwrap_or_default();
699 cursors.push(RestoreLevelCursor::new(files));
700 }
701
702 loop {
703 // Choose the best candidate across all level cursors (replica.go:1483-1494).
704 let mut next_idx: Option<usize> = None;
705 for i in 0..cursors.len() {
706 cursors[i].refresh(current_max, txid);
707 if cursors[i].candidate.is_none() {
708 continue;
709 }
710 match next_idx {
711 None => next_idx = Some(i),
712 Some(ni) => {
713 let cand = cursors[i].candidate.as_ref().unwrap();
714 let best = cursors[ni].candidate.as_ref().unwrap();
715 if restore_candidate_better(best, cand) {
716 next_idx = Some(i);
717 }
718 }
719 }
720 }
721
722 let ni = match next_idx {
723 Some(ni) => ni,
724 None => break,
725 };
726
727 // Take the chosen candidate (replica.go:1500-1510).
728 let cand = cursors[ni].candidate.take().unwrap();
729 if cand.max_txid <= current_max {
730 continue;
731 }
732 current_max = cand.max_txid;
733 infos.push(cand);
734
735 if txid != TXID(0) && current_max >= txid {
736 break;
737 }
738 }
739
740 // For a latest/most-recent restore, verify the tail is contiguous
741 // (replica.go:1517-1526).
742 if !infos.is_empty() && txid == TXID(0) {
743 for cursor in cursors.iter_mut() {
744 cursor.ensure_current();
745 if let Some(cur) = &cursor.current {
746 if cur.min_txid.0 > current_max.0 + 1 {
747 return Err(Error::Other(
748 format!(
749 "non-contiguous ltx files: have up to {} but next file starts at {}",
750 current_max, cur.min_txid
751 )
752 .into(),
753 ));
754 }
755 }
756 }
757 }
758
759 if infos.is_empty() {
760 return Err(Error::TxNotAvailable);
761 }
762 if txid != TXID(0) && slice_max_txid(&infos) < txid {
763 return Err(Error::TxNotAvailable);
764 }
765
766 Ok(infos)
767}
768
769/// A single level's streaming view during restore planning.
770///
771/// Ported from `restoreLevelCursor` (replica.go:1538-1603). The Go version
772/// streams from a `FileIterator`; here the client already returns a sorted
773/// `Vec<FileInfo>`, so the "iterator" is the slice plus a read index.
774struct RestoreLevelCursor {
775 /// Files for this level, sorted ascending (the `LTXFiles` contract).
776 files: Vec<FileInfo>,
777 /// Read index into `files` (the iterator cursor).
778 idx: usize,
779 /// Last item read but not yet evaluated (`current`, replica.go:1542).
780 current: Option<FileInfo>,
781 /// Best eligible file at this level for the current `current_max`
782 /// (`candidate`, replica.go:1544).
783 candidate: Option<FileInfo>,
784 /// True once the iterator is exhausted (`done`, replica.go:1546).
785 done: bool,
786}
787
788impl RestoreLevelCursor {
789 fn new(files: Vec<FileInfo>) -> Self {
790 RestoreLevelCursor {
791 files,
792 idx: 0,
793 current: None,
794 candidate: None,
795 done: false,
796 }
797 }
798
799 /// Advances the iterator while files could be contiguous with `current_max`,
800 /// keeping the best eligible candidate. Ported from `refresh`
801 /// (replica.go:1549-1587).
802 fn refresh(&mut self, current_max: TXID, txid: TXID) {
803 if self.done {
804 return;
805 }
806 if let Some(c) = &self.candidate {
807 if c.max_txid <= current_max {
808 self.candidate = None;
809 }
810 }
811
812 loop {
813 self.ensure_current();
814 if self.done {
815 return;
816 }
817
818 let info = self.current.clone().unwrap();
819 if info.min_txid.0 > current_max.0 + 1 {
820 return;
821 }
822 self.current = None;
823
824 if info.max_txid <= current_max {
825 continue;
826 }
827 if txid != TXID(0) && info.max_txid > txid {
828 continue;
829 }
830
831 match &self.candidate {
832 None => self.candidate = Some(info),
833 Some(c) => {
834 if restore_candidate_better(c, &info) {
835 self.candidate = Some(info);
836 }
837 }
838 }
839 }
840 }
841
842 /// Populates `current` with the next item, or marks `done`. Ported from
843 /// `ensureCurrent` (replica.go:1589-1603).
844 fn ensure_current(&mut self) {
845 if self.done || self.current.is_some() {
846 return;
847 }
848 if self.idx >= self.files.len() {
849 self.done = true;
850 return;
851 }
852 self.current = Some(self.files[self.idx].clone());
853 self.idx += 1;
854 }
855}
856
857/// True if `next` is a strictly better restore candidate than `curr`: longer
858/// reach first (`MaxTXID`), then a smaller `MinTXID` (more coverage), then a
859/// higher level (more compacted), then an earlier `created_at`.
860///
861/// Ported from `restoreCandidateBetter` (replica.go:1605-1616).
862fn restore_candidate_better(curr: &FileInfo, next: &FileInfo) -> bool {
863 if next.max_txid != curr.max_txid {
864 return next.max_txid > curr.max_txid;
865 }
866 if next.min_txid != curr.min_txid {
867 return next.min_txid < curr.min_txid;
868 }
869 if next.level != curr.level {
870 return next.level > curr.level;
871 }
872 // CreatedAt.Before(curr): an unknown (None) timestamp is treated as not
873 // earlier, matching Go's zero-time comparison being false here.
874 match (next.created_at, curr.created_at) {
875 (Some(n), Some(c)) => n < c,
876 _ => false,
877 }
878}
879
880/// Maximum `max_txid` across a slice, `TXID(0)` if empty. Mirrors
881/// `FileInfoSlice.MaxTXID` (ltx.go:612-619); the slice here is already in plan
882/// (ascending) order, but we scan defensively rather than assume.
883fn slice_max_txid(infos: &[FileInfo]) -> TXID {
884 infos.iter().map(|f| f.max_txid).max().unwrap_or(TXID(0))
885}
886
887/// Merges the LTX `files` (a snapshot followed by incrementals, in plan order)
888/// and reconstructs the full SQLite database image.
889///
890/// This replaces Go's `ltx.NewCompactor(pw, rdrs)` + `Decoder.DecodeDatabaseTo`
891/// (replica.go:667-682). The compactor's contract ([email protected] compactor.go):
892/// * page sizes must match across inputs;
893/// * the **last** input's `Commit` is the final database size;
894/// * for each page number, the **latest** input that carries it wins
895/// (compactor.go:198-228 iterates inputs newest-first);
896/// * pages numbered beyond the final `Commit` are dropped (truncation).
897///
898/// `DecodeDatabaseTo` then writes pages `1..=Commit`, zero-filling the lock page
899/// (decoder.go:236-254). Every input is fully decoded and checksum-verified, so
900/// a corrupt download is caught here.
901fn build_database_image(files: &[Vec<u8>]) -> Result<Vec<u8>> {
902 let mut page_size = None;
903 let mut commit = None;
904 let mut merged: HashMap<u32, Vec<u8>> = HashMap::new();
905
906 for data in files {
907 let (decoded, pages) = ltx::decode_file_with_pages(data)?;
908 let header = decoded.header;
909 if let Some(expected) = page_size {
910 if header.page_size != expected {
911 return Err(Error::Other(
912 format!(
913 "input files have mismatched page sizes: {} != {}",
914 expected, header.page_size
915 )
916 .into(),
917 ));
918 }
919 } else {
920 page_size = Some(header.page_size);
921 }
922 let previous_commit = commit.unwrap_or(0);
923 if header.commit > previous_commit {
924 let present: HashSet<u32> = pages.iter().map(|(pgno, _)| *pgno).collect();
925 let lock = ltx::lock_pgno(header.page_size);
926 for pgno in (previous_commit + 1)..=header.commit {
927 if pgno != lock && !present.contains(&pgno) && !merged.contains_key(&pgno) {
928 return Err(Error::Other(
929 format!(
930 "missing newly committed page {pgno} in LTX transaction {} (database grew from {previous_commit} to {} pages)",
931 header.max_txid, header.commit,
932 )
933 .into(),
934 ));
935 }
936 }
937 }
938
939 // Inputs arrive oldest to newest, so moving each page into the map makes
940 // the latest input win without a second staging collection or clone.
941 for (pgno, data) in pages {
942 merged.insert(pgno, data);
943 }
944 commit = Some(header.commit);
945 }
946
947 let (Some(page_size), Some(commit)) = (page_size, commit) else {
948 return Err(Error::Other(
949 "cannot build a database from no LTX files".into(),
950 ));
951 };
952 merged.retain(|pgno, _| *pgno <= commit);
953
954 let page_size_usize = page_size as usize;
955 let lock = ltx::lock_pgno(page_size);
956
957 // Reconstruct the database image: pages 1..=commit, lock page zero-filled
958 // (decoder.go:236-254). A non-lock page missing from the merge means the
959 // backup chain is incomplete.
960 let mut image = Vec::with_capacity(commit as usize * page_size_usize);
961 let zero_page = vec![0u8; page_size_usize];
962 for pgno in 1..=commit {
963 if pgno == lock {
964 image.extend_from_slice(&zero_page);
965 continue;
966 }
967 match merged.get(&pgno) {
968 Some(data) => image.extend_from_slice(data),
969 None => {
970 return Err(Error::Other(
971 format!("missing page {pgno} in restore plan (incomplete backup)").into(),
972 ));
973 }
974 }
975 }
976
977 Ok(image)
978}
979
980/// Appends `ext` to `path` as a literal suffix (`p` → `p.tmp`), the way Go's
981/// `opt.OutputPath + ".tmp"` does (NOT `Path::set_extension`, which would replace
982/// an existing extension).
983fn append_ext(path: &Path, ext: &str) -> PathBuf {
984 let mut s = path.as_os_str().to_owned();
985 s.push(".");
986 s.push(ext);
987 PathBuf::from(s)
988}
989
990/// Writes `data` to `tmp_path`, fsyncs, then renames onto `final_path` — the
991/// crash-consistent atomic-write idiom (replica.go:661-694). On any failure the
992/// temp file is removed.
993fn write_file_atomic(
994 host: &crate::LtxHost,
995 tmp_path: &Path,
996 final_path: &Path,
997 data: &[u8],
998) -> Result<()> {
999 let result = (|| -> Result<()> {
1000 let mut file = host.create(tmp_path)?;
1001 file.write_all(data)?;
1002 file.sync_all()?;
1003 drop(file);
1004 host.rename(tmp_path, final_path)?;
1005 Ok(())
1006 })();
1007 if result.is_err() {
1008 let _ = host.remove_file(tmp_path);
1009 }
1010 result
1011}
1012
1013#[doc(hidden)]
1014pub mod internal {
1015 use super::*;
1016
1017 pub const RESTORE_PLAN_CONCURRENCY: usize = super::RESTORE_PLAN_CONCURRENCY;
1018
1019 pub async fn upload_ltx_file<C: ReplicaClient>(
1020 replica: &mut Replica<C>,
1021 level: i32,
1022 min_txid: TXID,
1023 max_txid: TXID,
1024 ) -> Result<()> {
1025 replica.upload_ltx_file(level, min_txid, max_txid).await
1026 }
1027
1028 pub fn build_database_image(files: &[Vec<u8>]) -> Result<Vec<u8>> {
1029 super::build_database_image(files)
1030 }
1031
1032 pub fn pos_untrustworthy(error: &Error) -> bool {
1033 super::pos_untrustworthy(error)
1034 }
1035}