Skip to main content

surjection_core/remote/
restore.rs

1//! `restore --from` and the app's "Restore from remote..." (SPEC 9.5,
2//! 9.6, 11.9): a store from a folder remote's machine, a bare repository,
3//! a mirror or a zip.
4//!
5//! - No store on this machine: the store is created from the source (its
6//!   history, or the exported tree as one commit).
7//! - A store of the same id: a repository merges like a pull (tagged
8//!   `auto/pre-restore/<ts>`, conflicts recorded in `state/merge/`), an
9//!   export restores as one new commit.
10//! - Another store id: refused; restore into a fresh `SURJECTION_HOME`.
11//!
12//! Client files change only when `apply` is asked.
13
14use crate::apply::{self, ApplyEnv, ApplyReport, ApplyRequest, PlanOptions};
15use crate::brand;
16use crate::error::{CoreError, ErrorCode};
17use crate::model::applied::ApplyTrigger;
18use crate::remote::folder::{self, MachineEntry, Source};
19use crate::remote::sync_artifacts::Artifact;
20use crate::store::merge::{MergeOutcome, PendingMerge, RecordedConflict, write_merge_state};
21use crate::store::restore::{self, RestoreReport};
22use crate::store::{CommitId, Store, bare_store_id, check_bare, export_store_id};
23
24/// An apply run and its commit.
25pub type Applied = (ApplyReport, Option<CommitId>);
26
27/// What a restore from a source did.
28#[derive(Debug)]
29pub enum FromOutcome {
30    /// The store did not exist and was created from the source.
31    Created {
32        store_id: String,
33        head: CommitId,
34        apply: Option<Applied>,
35    },
36    /// The source's history merged into the existing store.
37    Merged {
38        outcome: MergeOutcome,
39        /// `auto/pre-restore/<ts>`, when the source brought commits.
40        tag: Option<String>,
41        head: CommitId,
42        apply: Option<Applied>,
43    },
44    /// An exported tree restored as one commit of the existing store.
45    Restored(RestoreReport),
46}
47
48#[derive(Debug)]
49pub struct FromReport {
50    pub outcome: FromOutcome,
51    /// Sync tool artifacts skipped in an exported tree, never read.
52    pub artifacts: Vec<Artifact>,
53}
54
55impl FromReport {
56    /// Conflicting fields of a merge (nothing merged then).
57    pub fn conflicts(&self) -> usize {
58        match &self.outcome {
59            FromOutcome::Merged {
60                outcome: MergeOutcome::Conflicts { conflicts, .. },
61                ..
62            } => conflicts.len(),
63            _ => 0,
64        }
65    }
66
67    pub fn apply(&self) -> Option<&ApplyReport> {
68        match &self.outcome {
69            FromOutcome::Created { apply, .. } | FromOutcome::Merged { apply, .. } => {
70                apply.as_ref().map(|(report, _)| report)
71            }
72            FromOutcome::Restored(report) => report.apply.as_ref(),
73        }
74    }
75}
76
77fn run_apply(store: &Store<'_>, ax: &ApplyEnv<'_>) -> Result<Applied, CoreError> {
78    let request = ApplyRequest {
79        options: PlanOptions::default(),
80        trigger: ApplyTrigger::Restore,
81    };
82    apply::run(store, ax, &request)
83}
84
85/// Restores from `source` (opened with [`folder::open_source`]); `machine`
86/// is the folder remote machine it comes from, `label` names the source
87/// in commit summaries and recorded merges.
88pub fn restore_from(
89    ax: &ApplyEnv<'_>,
90    client: &str,
91    source: &Source,
92    machine: Option<&MachineEntry>,
93    label: &str,
94    apply: bool,
95) -> Result<FromReport, CoreError> {
96    let (env, fs, home) = (ax.env, ax.fs, ax.home);
97    let mut artifacts = Vec::new();
98    // A source a newer Surjection wrote is refused before anything is created
99    // or changed.
100    let origin = format!("The restore source \"{label}\"");
101    let (source_store_id, files) = match source {
102        Source::Repo { bare, head, .. } => {
103            check_bare(bare, head, &origin)?;
104            (bare_store_id(bare, head), None)
105        }
106        export => {
107            let export = folder::export_files(fs, export)?;
108            artifacts = export.artifacts;
109            crate::versions::check_store_files(
110                export
111                    .files
112                    .iter()
113                    .map(|(path, bytes)| (path.as_str(), bytes.as_slice())),
114                &origin,
115            )?;
116            (export_store_id(&export.files), Some(export.files))
117        }
118    };
119    let Some(store) = Store::open(env, fs, home, client)? else {
120        let store = match (source, files) {
121            (Source::Repo { bare, head, tags }, _) => {
122                Store::init_from_bare(env, fs, home, client, bare, head, tags)?
123            }
124            (_, Some(files)) => Store::init_from_files(
125                env,
126                fs,
127                home,
128                client,
129                files,
130                &format!("restore: from {label}"),
131            )?,
132            (_, None) => unreachable!("exports have files"),
133        };
134        let head = store.head()?;
135        let apply = apply.then(|| run_apply(&store, ax)).transpose()?;
136        return Ok(FromReport {
137            outcome: FromOutcome::Created {
138                store_id: store.store_id().to_owned(),
139                head,
140                apply,
141            },
142            artifacts,
143        });
144    };
145
146    if source_store_id.as_deref() != Some(store.store_id()) {
147        return Err(CoreError::new(
148            ErrorCode::InvalidValue,
149            format!(
150                "the source holds another store ({}) than this machine's ({}); restore into a \
151                 fresh {} instead",
152                source_store_id.as_deref().unwrap_or("unknown"),
153                store.store_id(),
154                brand::HOME_ENV_VAR
155            ),
156        ));
157    }
158    let outcome = match (source, files) {
159        (Source::Repo { bare, head, tags }, _) => {
160            let mut ids = vec![head.clone()];
161            ids.extend(tags.values().cloned());
162            store.import_history(bare, &ids, tags)?;
163            let incoming = CommitId::from_text(head)?;
164            let tag = (!store.contains(&incoming))
165                .then(|| store.create_auto_tag("pre-restore"))
166                .transpose()?;
167            let outcome = store.merge_incoming(&incoming, &format!("restore from {label}"))?;
168            // Recorded like a pull's (SPEC 9.9), so the conflicts survive.
169            let source_name = format!(
170                "restore/{}",
171                machine.map_or(label, |entry| entry.machine_id.as_str())
172            );
173            let pending: Vec<PendingMerge> = match &outcome {
174                MergeOutcome::Conflicts { base, conflicts } => vec![PendingMerge {
175                    source: source_name.clone(),
176                    incoming: head.clone(),
177                    base: base.as_ref().map(ToString::to_string),
178                    conflicts: conflicts.iter().map(RecordedConflict::from).collect(),
179                }],
180                _ => Vec::new(),
181            };
182            write_merge_state(fs, store.state_dir(), &[source_name], &pending)?;
183            let apply = (apply && !matches!(outcome, MergeOutcome::Conflicts { .. }))
184                .then(|| run_apply(&store, ax))
185                .transpose()?;
186            FromOutcome::Merged {
187                outcome,
188                tag,
189                head: store.head()?,
190                apply,
191            }
192        }
193        (_, Some(files)) => {
194            FromOutcome::Restored(restore::restore_tree(&store, ax, &files, label, apply)?)
195        }
196        (_, None) => unreachable!("exports have files"),
197    };
198    Ok(FromReport { outcome, artifacts })
199}