Skip to main content

surjection_core/store/
restore.rs

1//! Restore (SPEC 9.5).
2//!
3//! - **Store restore** ([`restore`]): tag `auto/pre-restore/<ts>`, then one
4//!   new commit whose files equal another revision's, for the whole store
5//!   or only some entities. History is never rewritten, so a restore is
6//!   undone by restoring its tag. Other machines' `machines/*` files and
7//!   this machine's apply record are never changed (single-writer rule).
8//!   A restored project manifest is written back to the project folder:
9//!   `project.local.toml` always, the shared `project.toml` only when
10//!   confirmed, since a team may share it.
11//! - **Client-file restore** ([`restore_files`]): the bytes an apply run
12//!   backed up, written back through the same atomic compare-and-swap
13//!   write as an apply, with the current bytes backed up first and the
14//!   ledger updated to what the files hold now.
15
16use std::path::{Path, PathBuf};
17
18use crate::adapters::adapter;
19use crate::apply::exec::{ApplyReport, ApplyRequest, apply_in, swap_file};
20use crate::apply::ledger::{EntryKind, Ledger};
21use crate::apply::plan::{PlanOptions, read_target};
22use crate::apply::{ApplyEnv, backup};
23use crate::error::{CoreError, ErrorCode};
24use crate::formats::Document;
25use crate::model::TomlDocument;
26use crate::model::applied::ApplyTrigger;
27use crate::model::machine::MachineOverlay;
28use crate::secrets::catalog::overlay_path;
29use crate::store::diff::trailer_entities;
30use crate::store::merge::Files;
31use crate::store::{
32    CommitId, LOCK_TIMEOUT, Machine, Operation, Store, StoreLock, StoreRead, entity_paths,
33};
34
35/// Manifest file names in `projects/<id>/` and `<P>/.surjection/`.
36const SHARED_MANIFEST: &str = "project.toml";
37const LOCAL_MANIFEST: &str = "project.local.toml";
38
39/// What to restore.
40#[derive(Debug, Clone)]
41pub struct RestoreRequest {
42    pub target: CommitId,
43    /// Only these entities (`server/github`, `secrets`, `project/<id>`);
44    /// empty: the whole store.
45    pub entities: Vec<String>,
46    /// Write a restored shared `project.toml` back to its project folder.
47    pub confirmed: bool,
48    /// Apply in the same commit.
49    pub apply: bool,
50}
51
52/// A project manifest a restore writes back to its folder.
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct ManifestWrite {
55    pub project: String,
56    /// Store-relative manifest.
57    pub relative: String,
58    /// `<P>/.surjection/project[.local].toml`.
59    pub path: PathBuf,
60    /// The shared `project.toml` (needs confirmation).
61    pub shared: bool,
62}
63
64/// What a restore changes. Read-only.
65#[derive(Debug, Clone)]
66pub struct RestorePlan {
67    pub target: CommitId,
68    /// HEAD the plan was made against.
69    pub head: CommitId,
70    /// Store files restored (store-relative).
71    pub files: Vec<String>,
72    /// Manifests written back to project folders.
73    pub manifests: Vec<ManifestWrite>,
74    /// Restored manifests of projects this machine has no folder for.
75    pub unplaced: Vec<String>,
76}
77
78impl RestorePlan {
79    pub fn needs_confirmation(&self) -> bool {
80        self.manifests.iter().any(|manifest| manifest.shared)
81    }
82}
83
84/// The result of a store restore.
85#[derive(Debug)]
86pub struct RestoreReport {
87    pub plan: RestorePlan,
88    /// The `auto/pre-restore/<ts>` tag; `None` when nothing changed.
89    pub tag: Option<String>,
90    pub commit: Option<CommitId>,
91    /// Manifests written back.
92    pub written: Vec<PathBuf>,
93    pub apply: Option<ApplyReport>,
94}
95
96/// Whether a restore may change `file` on machine `machine_id`: every
97/// file but other machines' `machines/*` files and this machine's apply
98/// record.
99fn restorable(file: &str, machine_id: &str) -> bool {
100    match file.strip_prefix("machines/") {
101        Some(name) => name == format!("{machine_id}.toml"),
102        None => true,
103    }
104}
105
106/// Works out what restoring `request` changes. Read-only.
107pub fn prepare(
108    store: &Store<'_>,
109    machine_id: &str,
110    request: &RestoreRequest,
111) -> Result<RestorePlan, CoreError> {
112    let mut selected: Vec<String> = Vec::new();
113    for entity in &request.entities {
114        let paths = entity_paths(entity);
115        if paths.is_empty() {
116            return Err(CoreError::new(
117                ErrorCode::InvalidValue,
118                format!(
119                    "unknown entity {entity:?}; expected server/<id>, skill/<id>, project/<id>, \
120                     machine/<id>, secrets, clients, settings or sources"
121                ),
122            ));
123        }
124        if entity
125            .strip_prefix("machine/")
126            .is_some_and(|id| id != machine_id)
127        {
128            return Err(CoreError::new(
129                ErrorCode::InvalidValue,
130                format!("{entity} belongs to another machine; only that machine writes its files"),
131            ));
132        }
133        selected.extend(paths);
134    }
135    let head = store.head()?;
136    let files: Vec<String> = store
137        .changed_files(&head, &request.target)?
138        .into_iter()
139        .filter(|file| restorable(file, machine_id))
140        .filter(|file| {
141            selected.is_empty()
142                || selected
143                    .iter()
144                    .any(|path| file == path || file.starts_with(&format!("{path}/")))
145        })
146        .collect();
147
148    let target = store.revision(&request.target)?;
149    // Where projects live on this machine, after the restore.
150    let overlay_file = overlay_path(machine_id)?;
151    let overlay_text = if files.contains(&overlay_file) {
152        target.read_file(&overlay_file)?
153    } else {
154        store.read_file(&overlay_file)?
155    };
156    let overlay = overlay_text
157        .and_then(|text| TomlDocument::<MachineOverlay>::parse(&text).ok())
158        .map(TomlDocument::into_value);
159    let mut manifests = Vec::new();
160    let mut unplaced = Vec::new();
161    for file in &files {
162        let Some((project, name)) = manifest_parts(file) else {
163            continue;
164        };
165        let Some(bytes) = target.read_bytes(file)? else {
166            // A manifest removed by the restore stays in the project folder.
167            continue;
168        };
169        // Only an existing, absolute project folder: a relative or stale
170        // path never makes the restore write elsewhere or create folders.
171        let folder = overlay
172            .as_ref()
173            .and_then(|overlay| overlay.projects.as_ref())
174            .and_then(|projects| projects.get(project))
175            .map(|project| PathBuf::from(&project.path))
176            .filter(|folder| folder.is_absolute() && store.fs.is_dir(folder));
177        let Some(folder) = folder else {
178            unplaced.push(file.clone());
179            continue;
180        };
181        let path = crate::layering::manifest::manifest_dir(store.fs, &folder).join(name);
182        if read_target(store.fs, &path)?.as_deref() == Some(bytes.as_slice()) {
183            continue;
184        }
185        manifests.push(ManifestWrite {
186            project: project.to_owned(),
187            relative: file.clone(),
188            path,
189            shared: name == SHARED_MANIFEST,
190        });
191    }
192    Ok(RestorePlan {
193        target: request.target.clone(),
194        head,
195        files,
196        manifests,
197        unplaced,
198    })
199}
200
201/// `projects/<id>/project[.local].toml` as `(id, file name)`.
202fn manifest_parts(file: &str) -> Option<(&str, &str)> {
203    let rest = file.strip_prefix("projects/")?;
204    let (id, name) = rest.split_once('/')?;
205    matches!(name, SHARED_MANIFEST | LOCAL_MANIFEST).then_some((id, name))
206}
207
208/// Restores `request`: tag, one commit (with the apply when asked), then
209/// the manifest write-back. Fails with `confirmation_required` before
210/// changing anything when a shared manifest would be written back without
211/// [`RestoreRequest::confirmed`].
212pub fn restore(
213    store: &Store<'_>,
214    ax: &ApplyEnv<'_>,
215    request: &RestoreRequest,
216) -> Result<RestoreReport, CoreError> {
217    let summary = format!("restore: {}", request.target.short());
218    restore_as(store, ax, request, "store.restore", summary, None)
219}
220
221/// [`restore`] committed with operation `op` and `summary` (Discard
222/// pending is a restore of selected entities, `store.discard`). With
223/// `expected_head`, the store must still be at that commit when the plan is
224/// made (the caller worked out what to restore from it), else
225/// `file_changed_during_apply` before anything changes; the transaction
226/// checks the plan's HEAD again under the lock.
227pub(crate) fn restore_as(
228    store: &Store<'_>,
229    ax: &ApplyEnv<'_>,
230    request: &RestoreRequest,
231    op: &str,
232    summary: String,
233    expected_head: Option<&CommitId>,
234) -> Result<RestoreReport, CoreError> {
235    let machine = Machine::load_or_create(ax.env, ax.fs, &ax.home.state_dir())?;
236    let plan = prepare(store, &machine.id, request)?;
237    if expected_head.is_some_and(|head| *head != plan.head) {
238        return Err(CoreError::new(
239            ErrorCode::FileChangedDuringApply,
240            "the store changed since the pending changes were read; review them again",
241        ));
242    }
243    if plan.needs_confirmation() && !request.confirmed {
244        let files: Vec<String> = plan
245            .manifests
246            .iter()
247            .filter(|manifest| manifest.shared)
248            .map(|manifest| manifest.path.display().to_string())
249            .collect();
250        return Err(CoreError::new(
251            ErrorCode::ConfirmationRequired,
252            format!(
253                "the restore writes shared project manifests a team may use ({}); confirm to \
254                 write them back",
255                files.join(", ")
256            ),
257        ));
258    }
259    if plan.files.is_empty() {
260        return Ok(RestoreReport {
261            plan,
262            tag: None,
263            commit: None,
264            written: Vec::new(),
265            apply: None,
266        });
267    }
268    let mut operation = Operation::new(op, summary);
269    for entity in trailer_entities(&plan.files) {
270        operation = operation.entity(entity);
271    }
272    let committed = store.transaction(operation, |tx| {
273        // The plan was made without the lock: another process may have
274        // committed since, and then the files to restore differ.
275        if tx.store().head()? != plan.head {
276            return Err(CoreError::new(
277                ErrorCode::FileChangedDuringApply,
278                "the store changed while the restore was being prepared; run it again",
279            ));
280        }
281        let source = tx.store().revision(&plan.target)?;
282        let mut contents = Vec::with_capacity(plan.files.len());
283        for file in &plan.files {
284            contents.push((file.clone(), source.read_bytes(file)?));
285        }
286        drop(source);
287        for (file, content) in contents {
288            match content {
289                Some(bytes) => tx.write(&file, bytes)?,
290                None => tx.remove(&file)?,
291            }
292        }
293        if request.apply {
294            let request = ApplyRequest {
295                options: PlanOptions::default(),
296                trigger: ApplyTrigger::Restore,
297            };
298            apply_in(tx, ax, &request).map(Some)
299        } else {
300            Ok(None)
301        }
302    })?;
303    // Tagged once the restore is in, on the commit it replaced.
304    let tag = store.create_auto_tag_at("pre-restore", &plan.head)?;
305
306    let target = store.revision(&plan.target)?;
307    let mut written = Vec::new();
308    for manifest in &plan.manifests {
309        let Some(bytes) = target.read_bytes(&manifest.relative)? else {
310            continue;
311        };
312        crate::apply::write_atomic(ax.fs, &manifest.path, &bytes)?;
313        written.push(manifest.path.clone());
314    }
315    Ok(RestoreReport {
316        plan,
317        tag: Some(tag),
318        commit: committed.commit,
319        written,
320        apply: committed.value,
321    })
322}
323
324/// Restores an exported tree (a mirror or a zip of this store) as one new
325/// commit, like [`restore`] does a revision: files the export holds are
326/// written, files it lacks are removed, never another machine's
327/// `machines/*` files or this machine's apply record. The `auto/pre-restore`
328/// tag marks the replaced HEAD. Manifests are not written back.
329pub fn restore_tree(
330    store: &Store<'_>,
331    ax: &ApplyEnv<'_>,
332    files: &Files,
333    label: &str,
334    apply: bool,
335) -> Result<RestoreReport, CoreError> {
336    let machine = Machine::load_or_create(ax.env, ax.fs, &ax.home.state_dir())?;
337    let head = store.head()?;
338    let current = store.files_at(&head)?;
339    let changed: Vec<String> = current
340        .keys()
341        .chain(files.keys())
342        .filter(|file| restorable(file, &machine.id))
343        .filter(|file| current.get(*file) != files.get(*file))
344        .cloned()
345        .collect::<std::collections::BTreeSet<_>>()
346        .into_iter()
347        .collect();
348    let plan = RestorePlan {
349        target: head.clone(),
350        head: head.clone(),
351        files: changed,
352        manifests: Vec::new(),
353        unplaced: Vec::new(),
354    };
355    if plan.files.is_empty() {
356        return Ok(RestoreReport {
357            plan,
358            tag: None,
359            commit: None,
360            written: Vec::new(),
361            apply: None,
362        });
363    }
364    let mut operation = Operation::new("store.restore", format!("restore: from {label}"));
365    for entity in trailer_entities(&plan.files) {
366        operation = operation.entity(entity);
367    }
368    let committed = store.transaction(operation, |tx| {
369        if tx.store().head()? != plan.head {
370            return Err(CoreError::new(
371                ErrorCode::FileChangedDuringApply,
372                "the store changed while the restore was being prepared; run it again",
373            ));
374        }
375        for file in &plan.files {
376            match files.get(file) {
377                Some(bytes) => tx.write(file, bytes.clone())?,
378                None => tx.remove(file)?,
379            }
380        }
381        if apply {
382            let request = ApplyRequest {
383                options: PlanOptions::default(),
384                trigger: ApplyTrigger::Restore,
385            };
386            apply_in(tx, ax, &request).map(Some)
387        } else {
388            Ok(None)
389        }
390    })?;
391    let tag = store.create_auto_tag_at("pre-restore", &plan.head)?;
392    Ok(RestoreReport {
393        plan,
394        tag: Some(tag),
395        commit: committed.commit,
396        written: Vec::new(),
397        apply: committed.value,
398    })
399}
400
401/// What restoring one client file did.
402#[derive(Debug)]
403pub enum FileOutcome {
404    /// The backed-up bytes are back; the bytes it had are in `previous`.
405    Restored { previous: Option<PathBuf> },
406    /// The file already holds the backed-up bytes.
407    Unchanged,
408    /// Not restored (`file_changed_during_apply`, `file_locked`, I/O).
409    Failed(CoreError),
410    /// Not restored: its backup held old secret values and was removed on
411    /// request (M35), so the content it had before the run is no longer
412    /// kept.
413    Removed,
414}
415
416/// One client file of a [`restore_files`] run.
417#[derive(Debug)]
418pub struct FileRestore {
419    pub file: PathBuf,
420    pub outcome: FileOutcome,
421}
422
423/// Restores the client files a backup run holds
424/// (`backups/files/<ts>-<apply-id>/`), all of them or only `only`. `run`
425/// is the run's exact directory name (`<ts>-<apply-id>`, what the app
426/// lists), or an apply id, which names that apply's newest run. Each
427/// file's current bytes go to a new run `<ts>-restore-<apply-id>-<ulid>`
428/// first (unique, so restoring twice never makes two runs of one id), so
429/// this is undoable the same way. A file whose backup was removed because
430/// it held old secret values is reported [`FileOutcome::Removed`]. Holds
431/// the store lock.
432pub fn restore_files(
433    ax: &ApplyEnv<'_>,
434    run: &str,
435    only: Option<&Path>,
436) -> Result<Vec<FileRestore>, CoreError> {
437    let fs = ax.fs;
438    let state_dir = ax.home.state_dir();
439    let _lock = StoreLock::acquire(fs, &state_dir, LOCK_TIMEOUT)?;
440    let apply_id = run;
441    // A run result that cannot be read only leaves the removed backups
442    // unreported; the backups on disk still restore.
443    let removed: Vec<PathBuf> = backup::removed_backups(fs, &state_dir, run_apply_id(run))
444        .unwrap_or_default()
445        .into_iter()
446        .filter(|file| only.is_none_or(|only| same_path(ax, file, only)))
447        .collect();
448    // A run whose every backup was removed has no directory any more.
449    let run = match find_run(ax, run) {
450        Ok(run) => Some(run),
451        Err(err) if err.code() == ErrorCode::NotFound && !removed.is_empty() => None,
452        Err(err) => return Err(err),
453    };
454    let entries = match &run {
455        Some(run) => fs.read_dir(run).map_err(|err| {
456            CoreError::new(ErrorCode::IoError, format!("cannot list backups: {err}")).with_path(run)
457        })?,
458        None => Vec::new(),
459    };
460    let mut files: Vec<(PathBuf, PathBuf)> = entries
461        .into_iter()
462        .filter_map(|backup| {
463            let name = backup.file_name()?.to_str()?.to_owned();
464            let original = PathBuf::from(backup::decode_path(&name)?);
465            Some((original, backup))
466        })
467        .filter(|(original, _)| only.is_none_or(|only| same_path(ax, original, only)))
468        // The record wins over the listing: a backup recorded as removed may
469        // still be on disk, zeroed, and is never written back.
470        .filter(|(original, _)| !removed.iter().any(|file| same_path(ax, original, file)))
471        .collect();
472    files.sort();
473    if files.is_empty() && removed.is_empty() {
474        return Err(CoreError::new(
475            ErrorCode::NotFound,
476            match only {
477                Some(only) => format!("apply {apply_id} has no backup of {}", only.display()),
478                None => format!("apply {apply_id} has no file backups"),
479            },
480        ));
481    }
482    let mut results: Vec<FileRestore> = removed
483        .into_iter()
484        .map(|file| FileRestore {
485            file,
486            outcome: FileOutcome::Removed,
487        })
488        .collect();
489    let Some(run) = run else {
490        return Ok(results);
491    };
492    // `restore-<apply id>-<ulid>`, with the apply id the run goes back to
493    // (a restore of a restore names the original apply), so names never
494    // grow.
495    let run_id = run
496        .file_name()
497        .and_then(|name| name.to_str())
498        .and_then(|name| name.split_once('-'))
499        .map_or(apply_id, |(_, id)| id);
500    let base = run_id
501        .strip_prefix("restore-")
502        .and_then(|rest| rest.split('-').next())
503        .unwrap_or(run_id);
504    let undo_id = format!(
505        "restore-{base}-{}",
506        crate::model::ids::new_ulid(ax.env.now())?
507    );
508    let undo_dir = backup::run_dir(ax.home, ax.env.now(), &undo_id);
509    let mut ledger = Ledger::load(fs, &state_dir)?;
510    for (file, saved) in files {
511        // A failed file never prevents the others; the ledger is saved
512        // after each restored file (SPEC 8.4 step 5).
513        let outcome = restore_one(ax, &undo_dir, &file, &saved).and_then(|outcome| {
514            if matches!(outcome, FileOutcome::Restored { .. }) {
515                refresh_ledger(ax, &mut ledger, &file)?;
516                ledger.save(fs, &state_dir)?;
517            }
518            Ok(outcome)
519        });
520        let outcome = outcome.unwrap_or_else(|err| FileOutcome::Failed(err.with_path(&file)));
521        results.push(FileRestore { file, outcome });
522    }
523    Ok(results)
524}
525
526/// The apply id a run argument names: the id in `<ts>-<apply id>`, else the
527/// argument itself.
528fn run_apply_id(run: &str) -> &str {
529    match run.get(..16).and_then(backup::parse_timestamp) {
530        Some(_) if run.as_bytes().get(16) == Some(&b'-') => &run[17..],
531        _ => run,
532    }
533}
534
535/// The backup run directory named `run` exactly, else the newest run of
536/// apply id `run`.
537fn find_run(ax: &ApplyEnv<'_>, run: &str) -> Result<PathBuf, CoreError> {
538    let root = ax.home.backups_dir().join(backup::FILES_DIR);
539    let runs = if ax.fs.is_dir(&root) {
540        ax.fs.read_dir(&root).map_err(|err| {
541            CoreError::new(ErrorCode::IoError, format!("cannot list backups: {err}"))
542                .with_path(&root)
543        })?
544    } else {
545        Vec::new()
546    };
547    let runs: Vec<(String, PathBuf)> = runs
548        .into_iter()
549        .filter(|dir| ax.fs.is_dir(dir))
550        .filter_map(|dir| Some((dir.file_name()?.to_str()?.to_owned(), dir)))
551        .collect();
552    if let Some((_, dir)) = runs.iter().find(|(name, _)| name == run) {
553        return Ok(dir.clone());
554    }
555    // Directory names start with a sortable timestamp: the greatest is the
556    // newest.
557    runs.into_iter()
558        .filter(|(name, _)| {
559            name.split_once('-')
560                .is_some_and(|(_, id)| id.eq_ignore_ascii_case(run))
561        })
562        .max_by(|a, b| a.0.cmp(&b.0))
563        .map(|(_, dir)| dir)
564        .ok_or_else(|| {
565            CoreError::new(
566                ErrorCode::NotFound,
567                format!("no file backups of {run:?} on this machine"),
568            )
569        })
570}
571
572fn same_path(ax: &ApplyEnv<'_>, a: &Path, b: &Path) -> bool {
573    match ax.env.os() {
574        crate::env::Os::Windows => a
575            .to_string_lossy()
576            .eq_ignore_ascii_case(&b.to_string_lossy()),
577        _ => a == b,
578    }
579}
580
581/// Writes the backed-up bytes of `file` back: current bytes saved to
582/// `undo_dir`, temp file, compare-and-swap check, replace.
583fn restore_one(
584    ax: &ApplyEnv<'_>,
585    undo_dir: &Path,
586    file: &Path,
587    saved: &Path,
588) -> Result<FileOutcome, CoreError> {
589    let fs = ax.fs;
590    let bytes = fs.read(saved).map_err(|err| {
591        CoreError::new(ErrorCode::IoError, format!("cannot read backup: {err}")).with_path(saved)
592    })?;
593    let current = read_target(fs, file)?;
594    if current.as_deref() == Some(bytes.as_slice()) {
595        return Ok(FileOutcome::Unchanged);
596    }
597    let previous = match &current {
598        Some(current) => Some(backup::save(fs, ax.home, undo_dir, file, current)?),
599        None => None,
600    };
601    if !swap_file(fs, file, current.as_deref(), &bytes)? {
602        return Err(CoreError::new(
603            ErrorCode::FileChangedDuringApply,
604            "the file changed while it was being restored; nothing was written",
605        ));
606    }
607    Ok(FileOutcome::Restored { previous })
608}
609
610/// After a restore, owned entries that are no longer in `file` are no
611/// longer owned. Every other entry keeps its ledger record as it is, hash
612/// included: what the file holds now is compared with what Surjection wrote,
613/// so a restored hand edit plans as drift and a restored foreign entry as
614/// a collision, never as Surjection's own. A file that does not parse keeps
615/// every record. Only MCP entries are checked (see the M11 note).
616fn refresh_ledger(ax: &ApplyEnv<'_>, ledger: &mut Ledger, file: &Path) -> Result<(), CoreError> {
617    let name = file.to_string_lossy().into_owned();
618    let bytes = read_target(ax.fs, file)?;
619    let owned: Vec<_> = ledger
620        .entries
621        .iter()
622        .filter(|entry| entry.file == name && entry.kind == EntryKind::McpEntry)
623        .cloned()
624        .collect();
625    for entry in owned {
626        let present = match &bytes {
627            None => false,
628            Some(bytes) => {
629                let Some(format) = adapter(&entry.client)
630                    .and_then(|spec| spec.mcp.as_ref())
631                    .map(|mcp| mcp.format)
632                else {
633                    continue;
634                };
635                let Ok(doc) = Document::parse(bytes, format) else {
636                    continue;
637                };
638                let keys = pointer_keys(&entry.container);
639                let keys: Vec<&str> = keys.iter().map(String::as_str).collect();
640                !matches!(doc.get(&keys, &entry.key), Ok(None))
641            }
642        };
643        if !present {
644            ledger.remove(&entry.slot(), &entry.key);
645        }
646    }
647    Ok(())
648}
649
650/// The keys of an RFC 6901 pointer (`/projects/C:~1code/mcpServers`).
651fn pointer_keys(pointer: &str) -> Vec<String> {
652    pointer
653        .split('/')
654        .skip(1)
655        .map(|key| key.replace("~1", "/").replace("~0", "~"))
656        .collect()
657}