Skip to main content

core_api/
restore.rs

1//! Seeding a store directory from a backup.
2//!
3//! The mirror of [`GraphDb::backup_to`](crate::GraphDb::backup_to), and it
4//! lives beside it for the same reason: a restore is a file-level copy of a
5//! store directory followed by an open that proves the copy is a store.
6//!
7//! This was the CLI's `--restore-from` implementation until v0.6.10, when the
8//! Python binding needed it too. `cli::restore_if_empty` is now a thin wrapper
9//! over [`restore_if_empty`] here, with the CLI's error type; the semantics are
10//! unchanged.
11
12use crate::{GraphDb, GraphError, Result};
13use std::path::{Path, PathBuf};
14
15/// What [`restore_if_empty`] did.
16#[derive(Debug, PartialEq, Eq)]
17pub enum RestoreOutcome {
18    /// `db_dir` already holds a store; nothing was copied.
19    AlreadyPresent,
20    /// Seeded from `from`.
21    Restored {
22        from: PathBuf,
23        files: Vec<String>,
24        bytes: u64,
25    },
26    /// `from` held no backup: nothing under it looks like a store.
27    Empty,
28}
29
30/// Every file [`GraphDb::backup_to`](crate::GraphDb::backup_to) copies that is
31/// not a WAL archive.
32///
33/// Kept in the same order, so a restore writes them the way a backup wrote
34/// them. Archives are found by name at copy time, since their count varies.
35const RESTORE_FILES: [&str; 7] = [
36    "snapshot.bin",
37    "snapshot.bin.bak",
38    "wal.bin",
39    "wal.floor",
40    "wal.genesis",
41    "roles.json",
42    "commit_times.bin",
43];
44
45/// Is there a store in `dir` already?
46///
47/// A store is "present" when `dir` holds `snapshot.bin` or a non-empty
48/// `wal.bin`. An empty `wal.bin` is what a crashed first boot leaves behind,
49/// and seeding over it is the whole point of `--restore-from`.
50pub fn holds_a_store(dir: &Path) -> bool {
51    if dir.join("snapshot.bin").is_file() {
52        return true;
53    }
54    std::fs::metadata(dir.join("wal.bin"))
55        .map(|m| m.is_file() && m.len() > 0)
56        .unwrap_or(false)
57}
58
59/// How recently a backup directory was written: the newest mtime among the
60/// files that make it a store.
61///
62/// `snapshot.bin` alone is not enough to rank by, because a store that has
63/// never snapshotted backs up as `wal.bin` and nothing else — which is exactly
64/// what `mushroomdb demo` then `mushroomdb backup` produces.
65fn backup_mtime(dir: &Path) -> Option<std::time::SystemTime> {
66    ["snapshot.bin", "wal.bin"]
67        .iter()
68        .filter_map(|n| {
69            std::fs::metadata(dir.join(n))
70                .and_then(|m| m.modified())
71                .ok()
72        })
73        .max()
74}
75
76/// Pick the backup under `from`, if there is one.
77///
78/// `from` is either a backup directory itself (it holds a store) or a
79/// directory of them, in which case the immediate subdirectory named `latest`
80/// wins outright if it holds one — so a symlink or a rolling copy can name
81/// itself — and otherwise the newest by mtime wins.
82///
83/// "Holds a store" is [`holds_a_store`], the same predicate that decides
84/// whether `db_dir` needs seeding. A backup of a never-snapshotted store is
85/// `wal.bin` and nothing else, and it carries every commit; ranking on
86/// `snapshot.bin` alone would skip it and start empty.
87fn choose_backup(from: &Path) -> Option<PathBuf> {
88    if holds_a_store(from) {
89        return Some(from.to_path_buf());
90    }
91    let entries = std::fs::read_dir(from).ok()?;
92    let mut best: Option<(std::time::SystemTime, PathBuf)> = None;
93    for entry in entries.flatten() {
94        let dir = entry.path();
95        if !holds_a_store(&dir) {
96            continue;
97        }
98        if dir.file_name().map(|n| n == "latest").unwrap_or(false) {
99            return Some(dir);
100        }
101        let Some(mtime) = backup_mtime(&dir) else {
102            continue;
103        };
104        // Ties break on the path, so a vault of same-second backups still
105        // picks the same one on every boot.
106        let better = match &best {
107            None => true,
108            Some((best_mtime, best_dir)) => (mtime, &dir) > (*best_mtime, best_dir),
109        };
110        if better {
111            best = Some((mtime, dir));
112        }
113    }
114    best.map(|(_, dir)| dir)
115}
116
117/// Seed `db_dir` from the newest backup under `from`, if `db_dir` has no store.
118///
119/// A store is "present" when `db_dir` holds `snapshot.bin` or a non-empty
120/// `wal.bin`. `from` is either a backup directory itself (it holds a store by
121/// that same test) or a directory of them, in which case the immediate
122/// subdirectory named `latest` wins if it holds one, else the newest by mtime.
123///
124/// The restore is all-or-nothing. The backup is copied into a staging
125/// directory **inside** `db_dir` and opened there — the same CRC and replay
126/// checks any open runs — and only a copy that opened is moved into place. Any
127/// *error* removes the staging directory (or, once files have started moving,
128/// undoes the moves already made) and leaves `db_dir` exactly as it was, so
129/// the error names the paths, the operator can fix the backup, and the next
130/// boot restores rather than reporting [`RestoreOutcome::AlreadyPresent`] over
131/// a half-written store. That unwind is process-local: a crash between the
132/// two renames that install the staged files (not a returned error, but the
133/// process dying) can leave `db_dir` holding one file but not the other. The
134/// next boot sees that partial store as already present and reports
135/// [`RestoreOutcome::AlreadyPresent`] rather than restoring over it — clear
136/// the directory and restore again.
137///
138/// Staging lives inside `db_dir` on purpose: `db_dir` is typically the mount
139/// point, so a sibling directory could land on another filesystem and turn the
140/// final moves into cross-device copies.
141///
142/// # Errors
143///
144/// Whatever creating `db_dir`, copying a file, opening the staged copy, or
145/// moving it into place returned, as [`GraphError::Io`] carrying the message
146/// verbatim — the paths are in the message, and a caller that must tell the
147/// causes apart has them in the text rather than in the variant.
148pub fn restore_if_empty(db_dir: &Path, from: &Path) -> Result<RestoreOutcome> {
149    if holds_a_store(db_dir) {
150        return Ok(RestoreOutcome::AlreadyPresent);
151    }
152    let Some(backup) = choose_backup(from) else {
153        return Ok(RestoreOutcome::Empty);
154    };
155
156    std::fs::create_dir_all(db_dir)
157        .map_err(|e| failed(format!("restore into {}: {e}", db_dir.display())))?;
158
159    // Named for this process, so two `serve` processes racing onto one fresh
160    // volume stage into separate directories rather than over each other.
161    let staging = db_dir.join(format!(".restore-{}", std::process::id()));
162    let _ = std::fs::remove_dir_all(&staging); // a previous run that was killed
163    std::fs::create_dir_all(&staging)
164        .map_err(|e| failed(format!("restore into {}: {e}", staging.display())))?;
165
166    let outcome = stage_and_install(db_dir, &staging, &backup);
167    // Whether it worked or not: the staging directory never outlives the call.
168    // On success it holds only what opening the copy created (`LOCK`), since
169    // the restored files were moved out of it.
170    let _ = std::fs::remove_dir_all(&staging);
171    outcome
172}
173
174/// A restore failure, carrying `msg` and nothing else.
175///
176/// `std::io::Error::other` displays as its message alone, so the text a caller
177/// sees is the text built here — which is what lets the CLI keep printing the
178/// messages it always has.
179fn failed(msg: String) -> GraphError {
180    GraphError::Io(std::io::Error::other(msg))
181}
182
183/// Copy `backup` into `staging`, prove it opens, then move it into `db_dir`.
184///
185/// Split out of [`restore_if_empty`] so every early return runs through one
186/// cleanup of `staging` at the call site.
187fn stage_and_install(db_dir: &Path, staging: &Path, backup: &Path) -> Result<RestoreOutcome> {
188    let mut names: Vec<String> = RESTORE_FILES.iter().map(|n| n.to_string()).collect();
189    let mut archives: Vec<String> = std::fs::read_dir(backup)
190        .map_err(|e| failed(format!("restore from {}: {e}", backup.display())))?
191        .flatten()
192        .filter_map(|e| e.file_name().into_string().ok())
193        .filter(|n| n.starts_with("wal.") && n.ends_with(".archive"))
194        .collect();
195    archives.sort();
196    names.extend(archives);
197
198    let mut files = Vec::new();
199    let mut bytes = 0u64;
200    for name in names {
201        let src = backup.join(&name);
202        if !src.is_file() {
203            continue;
204        }
205        let n = std::fs::copy(&src, staging.join(&name))
206            .map_err(|e| failed(format!("restore {} from {}: {e}", name, backup.display())))?;
207        bytes += n;
208        files.push(name);
209    }
210
211    // Prove the copy opens before `serve` gets it. A copy that does not open is
212    // a hard failure, not a silent empty start — and because it opened in
213    // staging, nothing of it reaches `db_dir`.
214    GraphDb::<core_storage::fs::RealFs>::open(staging).map_err(|e| {
215        failed(format!(
216            "restore into {} from {} failed: the copy does not open: {e}",
217            db_dir.display(),
218            backup.display()
219        ))
220    })?;
221
222    // The copy is good. Move it in. A rename within one directory tree is the
223    // closest thing to atomic the filesystem offers; if one still fails, undo
224    // the moves already made so `db_dir` is left as it was found.
225    let mut moved: Vec<&String> = Vec::new();
226    for name in &files {
227        if let Err(e) = std::fs::rename(staging.join(name), db_dir.join(name)) {
228            for done in &moved {
229                let _ = std::fs::remove_file(db_dir.join(done));
230            }
231            return Err(failed(format!(
232                "restore into {} from {}: installing {name}: {e}",
233                db_dir.display(),
234                backup.display()
235            )));
236        }
237        moved.push(name);
238    }
239
240    Ok(RestoreOutcome::Restored {
241        from: backup.to_path_buf(),
242        files,
243        bytes,
244    })
245}