Skip to main content

surjection_core/store/
bootstrap.rs

1//! Moving store history to and from other repositories without a git
2//! transport (SPEC 4.2: git2 local operations only):
3//!
4//! - [`Store::export_bare`]: HEAD and every tag into a bare repository (a
5//!   folder remote's `store.git`), objects first, refs after.
6//! - [`Store::import_history`]: the objects reachable from given ids, and
7//!   the given tags, out of a bare repository; a missing object is
8//!   `remote_incomplete`.
9//! - [`Store::init_from_bare`] and [`Store::init_from_files`]: a new store
10//!   on a new machine from another machine's history, or from an exported
11//!   tree (mirror, zip).
12//!
13//! Objects are read and written through the object databases directly, so
14//! only the ids a manifest lists are ever followed, never a ref a sync
15//! tool may have duplicated.
16
17use std::collections::{BTreeMap, HashSet};
18use std::path::Path;
19
20use git2::{ObjectType, Oid, Repository, RepositoryInitOptions};
21
22use crate::env::Env;
23use crate::error::{CoreError, ErrorCode};
24use crate::fs::Fs;
25use crate::model::TomlDocument;
26use crate::model::ids::{self, IdKind};
27use crate::paths::SurjectionHome;
28use crate::store::merge::Files;
29use crate::store::transaction::Changes;
30use crate::store::{
31    BRANCH, CommitId, IDENTITY_FILE, LOCK_TIMEOUT, Machine, Operation, Store, StoreIdentity,
32    StoreLock, git_error, io_error,
33};
34
35/// Copies every object reachable from `start` that `dst` lacks. A missing
36/// source object fails with `missing` (its id).
37fn copy_reachable(src: &Repository, dst: &Repository, start: &[Oid]) -> Result<(), Oid> {
38    let src_odb = src.odb().map_err(|_| Oid::ZERO_SHA1)?;
39    let dst_odb = dst.odb().map_err(|_| Oid::ZERO_SHA1)?;
40    let mut seen: HashSet<Oid> = HashSet::new();
41    let mut stack: Vec<Oid> = start.to_vec();
42    while let Some(oid) = stack.pop() {
43        if !seen.insert(oid) {
44            continue;
45        }
46        let object = src_odb.read(oid).map_err(|_| oid)?;
47        let kind = object.kind();
48        if !dst_odb.exists(oid) {
49            dst_odb.write(kind, object.data()).map_err(|_| oid)?;
50        }
51        match kind {
52            ObjectType::Commit => {
53                let commit = src.find_commit(oid).map_err(|_| oid)?;
54                stack.push(commit.tree_id());
55                stack.extend(commit.parent_ids());
56            }
57            ObjectType::Tree => {
58                let tree = src.find_tree(oid).map_err(|_| oid)?;
59                for entry in tree.iter() {
60                    if matches!(entry.kind(), Some(ObjectType::Tree | ObjectType::Blob)) {
61                        stack.push(entry.id());
62                    }
63                }
64            }
65            ObjectType::Tag => {
66                let tag = src.find_tag(oid).map_err(|_| oid)?;
67                stack.push(tag.target_id());
68            }
69            _ => {}
70        }
71    }
72    Ok(())
73}
74
75fn open_bare(path: &Path) -> Result<Repository, CoreError> {
76    Repository::open_bare(path).map_err(|err| {
77        CoreError::new(
78            ErrorCode::RemoteIncomplete,
79            format!("cannot open the repository: {}", err.message()),
80        )
81        .with_path(path)
82    })
83}
84
85fn parse_oid(text: &str) -> Result<Oid, CoreError> {
86    Oid::from_str(text).map_err(|_| {
87        CoreError::new(
88            ErrorCode::InvalidValue,
89            format!("{text:?} is not a commit id"),
90        )
91    })
92}
93
94fn incomplete(path: &Path, missing: Oid) -> CoreError {
95    CoreError::new(
96        ErrorCode::RemoteIncomplete,
97        format!(
98            "object {missing} has not arrived yet (a sync tool may still be copying); try again later"
99        ),
100    )
101    .with_path(path)
102}
103
104/// The subject of commit `oid` in the bare repository at `path`, if it is
105/// readable.
106pub fn bare_commit_subject(path: &Path, oid: &str) -> Option<String> {
107    let repo = Repository::open_bare(path).ok()?;
108    let commit = repo.find_commit(Oid::from_str(oid).ok()?).ok()?;
109    commit.summary().ok().flatten().map(str::to_owned)
110}
111
112/// `main` and the tags (`name -> id`) of the bare repository at `path`,
113/// for a restore from a repository given directly (no `machine.json`).
114pub fn bare_refs(path: &Path) -> Option<(String, BTreeMap<String, String>)> {
115    let repo = Repository::open_bare(path).ok()?;
116    let head = repo
117        .find_reference(&format!("refs/heads/{BRANCH}"))
118        .ok()?
119        .target()?
120        .to_string();
121    let mut tags = BTreeMap::new();
122    for name in repo.tag_names(None).ok()?.iter().flatten().flatten() {
123        if let Some(oid) = repo
124            .find_reference(&format!("refs/tags/{name}"))
125            .ok()
126            .and_then(|reference| reference.target())
127        {
128            tags.insert(name.to_owned(), oid.to_string());
129        }
130    }
131    Some((head, tags))
132}
133
134/// The store id in `loadout.toml` of commit `head` in the bare repository
135/// at `path`, if readable.
136pub fn bare_store_id(path: &Path, head: &str) -> Option<String> {
137    let repo = Repository::open_bare(path).ok()?;
138    identity_at(&repo, Oid::from_str(head).ok()?)
139        .ok()
140        .map(|identity| identity.store_id)
141}
142
143/// [`crate::versions::check_store_files`] over commit `head` of the bare
144/// repository at `path`: a restore refuses a source a newer Surjection wrote
145/// before it creates or changes anything. A commit that cannot be read is
146/// left to the restore itself to report.
147pub fn check_bare(path: &Path, head: &str, origin: &str) -> Result<(), CoreError> {
148    let Ok(repo) = Repository::open_bare(path) else {
149        return Ok(());
150    };
151    let Some(tree) = Oid::from_str(head)
152        .ok()
153        .and_then(|oid| repo.find_commit(oid).ok())
154        .and_then(|commit| commit.tree().ok())
155    else {
156        return Ok(());
157    };
158    let mut files = Files::new();
159    tree.walk(git2::TreeWalkMode::PreOrder, |dir, entry| {
160        if entry.kind() == Some(ObjectType::Blob)
161            && let Ok(name) = entry.name()
162        {
163            let relative = format!("{dir}{name}");
164            if crate::versions::is_store_schema_file(&relative)
165                && let Ok(blob) = repo.find_blob(entry.id())
166            {
167                files.insert(relative, blob.content().to_vec());
168            }
169        }
170        git2::TreeWalkResult::Ok
171    })
172    .map_err(git_error)?;
173    crate::versions::check_store_files(
174        files
175            .iter()
176            .map(|(path, bytes)| (path.as_str(), bytes.as_slice())),
177        origin,
178    )
179}
180
181impl Store<'_> {
182    /// How many commits reachable from `head` in the bare repository at
183    /// `path` are not in HEAD's history (at most `limit`); `None` when the
184    /// repository or a commit cannot be read (a sync tool may still be
185    /// copying). Reads the bare repository only.
186    pub fn bare_incoming(&self, path: &Path, head: &str, limit: usize) -> Option<usize> {
187        let repo = Repository::open_bare(path).ok()?;
188        let mut pending = vec![Oid::from_str(head).ok()?];
189        let mut seen = HashSet::new();
190        let mut count = 0;
191        while let Some(oid) = pending.pop() {
192            if count >= limit {
193                break;
194            }
195            if !seen.insert(oid) || self.contains(&CommitId::from_oid(oid)) {
196                continue;
197            }
198            count += 1;
199            pending.extend(repo.find_commit(oid).ok()?.parent_ids());
200        }
201        Some(count)
202    }
203}
204
205/// The store id in an exported tree's `loadout.toml`.
206pub fn export_store_id(files: &Files) -> Option<String> {
207    let text = std::str::from_utf8(files.get(IDENTITY_FILE)?).ok()?;
208    let identity = TomlDocument::<StoreIdentity>::parse(text)
209        .ok()?
210        .into_value();
211    Some(identity.store_id)
212}
213
214impl Store<'_> {
215    /// Writes HEAD and every tag into the bare repository `path`, created
216    /// when absent: objects first, then `main` and the tags; tags the store
217    /// no longer has are deleted (single writer). Returns HEAD and the tags
218    /// as `name -> id`.
219    pub(crate) fn export_bare(
220        &self,
221        path: &Path,
222    ) -> Result<(CommitId, BTreeMap<String, String>), CoreError> {
223        let bare = if self.fs.exists(&path.join("HEAD")) {
224            Repository::open_bare(path).map_err(git_error)?
225        } else {
226            self.fs
227                .create_dir_all(path)
228                .map_err(|err| io_error("cannot create directory", path, &err))?;
229            let mut options = RepositoryInitOptions::new();
230            options
231                .bare(true)
232                .external_template(false)
233                .initial_head(BRANCH);
234            Repository::init_opts(path, &options).map_err(git_error)?
235        };
236        let head = self.head()?;
237        let head_oid = parse_oid(head.as_str())?;
238        let mut tags = BTreeMap::new();
239        let mut starts = vec![head_oid];
240        for name in self
241            .repo
242            .tag_names(None)
243            .map_err(git_error)?
244            .iter()
245            .flatten()
246            .flatten()
247        {
248            if let Ok(reference) = self.repo.find_reference(&format!("refs/tags/{name}"))
249                && let Some(oid) = reference.target()
250            {
251                tags.insert(name.to_owned(), oid.to_string());
252                starts.push(oid);
253            }
254        }
255        copy_reachable(&self.repo, &bare, &starts).map_err(|missing| {
256            CoreError::new(
257                ErrorCode::GitError,
258                format!("object {missing} is missing from the store"),
259            )
260        })?;
261        bare.reference(&format!("refs/heads/{BRANCH}"), head_oid, true, "push")
262            .map_err(git_error)?;
263        for (name, oid) in &tags {
264            bare.reference(&format!("refs/tags/{name}"), parse_oid(oid)?, true, "push")
265                .map_err(git_error)?;
266        }
267        let stale: Vec<String> = bare
268            .tag_names(None)
269            .map_err(git_error)?
270            .iter()
271            .flatten()
272            .flatten()
273            .filter(|name| !tags.contains_key(*name))
274            .map(str::to_owned)
275            .collect();
276        for name in stale {
277            bare.tag_delete(&name).map_err(git_error)?;
278        }
279        Ok((head, tags))
280    }
281
282    /// Copies the objects reachable from `ids` out of the bare repository
283    /// `path`. Fails with `remote_incomplete` when one has not arrived.
284    pub(crate) fn import_objects(&self, path: &Path, ids: &[String]) -> Result<(), CoreError> {
285        let bare = open_bare(path)?;
286        let starts = ids
287            .iter()
288            .map(|id| parse_oid(id))
289            .collect::<Result<Vec<_>, _>>()?;
290        copy_reachable(&bare, &self.repo, &starts).map_err(|missing| incomplete(path, missing))
291    }
292
293    /// The history behind `ids` and the tags of `tags` out of the bare
294    /// repository `path` (`remote_incomplete` when an object is missing).
295    /// Returns the tags created.
296    pub fn import_history(
297        &self,
298        path: &Path,
299        ids: &[String],
300        tags: &BTreeMap<String, String>,
301    ) -> Result<Vec<String>, CoreError> {
302        self.import_objects(path, ids)?;
303        self.import_tags(tags)
304    }
305
306    /// Creates the tags of `tags` (`name -> id`) the store lacks; existing
307    /// names are left as they are. Returns the names created.
308    pub(crate) fn import_tags(
309        &self,
310        tags: &BTreeMap<String, String>,
311    ) -> Result<Vec<String>, CoreError> {
312        let mut created = Vec::new();
313        for (name, oid) in tags {
314            let refname = format!("refs/tags/{name}");
315            if !git2::Reference::is_valid_name(&refname) || self.tag_exists(name) {
316                continue;
317            }
318            let oid = parse_oid(oid)?;
319            if self.repo.find_object(oid, None).is_err() {
320                continue;
321            }
322            self.repo
323                .reference(&refname, oid, false, "pull")
324                .map_err(git_error)?;
325            created.push(name.clone());
326        }
327        Ok(created)
328    }
329
330    /// A new store in `home` holding the history of `head` from the bare
331    /// repository `bare` (another machine's `store.git`). The working tree
332    /// is checked out; this machine gets its own identity. On failure
333    /// nothing is left behind, so a retry (after `remote_incomplete`)
334    /// starts over.
335    pub fn init_from_bare<'a>(
336        env: &Env,
337        fs: &'a dyn Fs,
338        home: &SurjectionHome,
339        client: &str,
340        bare: &Path,
341        head: &str,
342        tags: &BTreeMap<String, String>,
343    ) -> Result<Store<'a>, CoreError> {
344        let source = open_bare(bare)?;
345        let head_oid = parse_oid(head)?;
346        let (repo, state_dir, lock) = create_repo(fs, home)?;
347        let built = (|| {
348            let mut starts = vec![head_oid];
349            starts.extend(tags.values().filter_map(|oid| Oid::from_str(oid).ok()));
350            copy_reachable(&source, &repo, &starts).map_err(|missing| incomplete(bare, missing))?;
351            // Not a Surjection store: refused before any ref points at it.
352            let identity = identity_at(&repo, head_oid)?;
353            repo.reference(&format!("refs/heads/{BRANCH}"), head_oid, true, "restore")
354                .map_err(git_error)?;
355            Machine::load_or_create(env, fs, &state_dir)?;
356            let store = Store::from_parts(env, fs, home, client, repo, identity)?;
357            store.import_tags(tags)?;
358            let files = store.files_at(&CommitId::from_oid(head_oid))?;
359            let changes: Changes = files.into_iter().map(|(k, v)| (k, Some(v))).collect();
360            store.write_worktree(&changes)?;
361            {
362                let tree = store
363                    .repo
364                    .find_commit(head_oid)
365                    .and_then(|commit| commit.tree())
366                    .map_err(git_error)?;
367                let mut index = store.repo.index().map_err(git_error)?;
368                index.read_tree(&tree).map_err(git_error)?;
369                index.write().map_err(git_error)?;
370            }
371            Ok(store)
372        })();
373        if built.is_err() {
374            discard_repo(fs, home);
375        }
376        drop(lock);
377        built
378    }
379
380    /// A new store in `home` whose first commit holds `files` (an exported
381    /// tree: a mirror or a zip). The store identity is the one in `files`.
382    /// On failure (validation, the leak scan) nothing is left behind.
383    pub fn init_from_files<'a>(
384        env: &Env,
385        fs: &'a dyn Fs,
386        home: &SurjectionHome,
387        client: &str,
388        files: Files,
389        summary: &str,
390    ) -> Result<Store<'a>, CoreError> {
391        let text = files
392            .get(IDENTITY_FILE)
393            .and_then(|bytes| std::str::from_utf8(bytes).ok())
394            .ok_or_else(|| {
395                CoreError::new(
396                    ErrorCode::MissingField,
397                    format!("the export has no {IDENTITY_FILE}, so it is not a Surjection store"),
398                )
399            })?;
400        let identity = TomlDocument::<StoreIdentity>::parse(text)
401            .map_err(|diagnostic| diagnostic.to_core_error(Some(Path::new(IDENTITY_FILE))))?
402            .into_value();
403        ids::check(IdKind::Store, &identity.store_id)?;
404        let (repo, state_dir, lock) = create_repo(fs, home)?;
405        let built = (|| {
406            let machine = Machine::load_or_create(env, fs, &state_dir)?;
407            let store = Store::from_parts(env, fs, home, client, repo, identity)?;
408            let changes: Changes = files.into_iter().map(|(k, v)| (k, Some(v))).collect();
409            store.commit_changes(&machine, &Operation::new("store.restore", summary), changes)?;
410            Ok(store)
411        })();
412        if built.is_err() {
413            discard_repo(fs, home);
414        }
415        drop(lock);
416        built
417    }
418}
419
420/// An empty, non-bare repository on `main` in `home`'s store folder,
421/// with the lock held. Fails with `already_exists` when a store is there,
422/// or when the folder holds other files. A repository without any ref (a
423/// bootstrap that was cut off) is started over.
424fn create_repo(
425    fs: &dyn Fs,
426    home: &SurjectionHome,
427) -> Result<(Repository, std::path::PathBuf, StoreLock), CoreError> {
428    let state_dir = home.state_dir();
429    let lock = StoreLock::acquire(fs, &state_dir, LOCK_TIMEOUT)?;
430    let root = home.store_dir();
431    let dot_git = root.join(".git");
432    if fs.exists(&dot_git) {
433        let unborn = Repository::open(&root).is_ok_and(|repo| {
434            repo.head().is_err()
435                && repo
436                    .references()
437                    .is_ok_and(|mut refs| refs.next().is_none())
438        });
439        if !unborn {
440            return Err(
441                CoreError::new(ErrorCode::AlreadyExists, "a store exists here already")
442                    .with_path(&root),
443            );
444        }
445        fs.remove_dir_all(&dot_git)
446            .map_err(|err| io_error("cannot remove directory", &dot_git, &err))?;
447    }
448    if fs.read_dir(&root).is_ok_and(|entries| !entries.is_empty()) {
449        return Err(CoreError::new(
450            ErrorCode::AlreadyExists,
451            "the store folder holds files but no store; move them away first",
452        )
453        .with_path(&root));
454    }
455    fs.create_dir_all(&root)
456        .map_err(|err| io_error("cannot create directory", &root, &err))?;
457    let mut options = RepositoryInitOptions::new();
458    options
459        .bare(false)
460        .no_reinit(true)
461        .mkdir(true)
462        .external_template(false)
463        .initial_head(BRANCH);
464    let repo = Repository::init_opts(&root, &options).map_err(git_error)?;
465    Ok((repo, state_dir, lock))
466}
467
468/// Removes the store folder a failed bootstrap filled. `create_repo` only
469/// proceeds into an absent or empty folder, so nothing else is in it.
470fn discard_repo(fs: &dyn Fs, home: &SurjectionHome) {
471    let _ = fs.remove_dir_all(&home.store_dir());
472}
473
474/// The store identity in `loadout.toml` of commit `oid`.
475fn identity_at(repo: &Repository, oid: Oid) -> Result<StoreIdentity, CoreError> {
476    let tree = repo
477        .find_commit(oid)
478        .and_then(|commit| commit.tree())
479        .map_err(git_error)?;
480    let entry = tree.get_path(Path::new(IDENTITY_FILE)).map_err(|_| {
481        CoreError::new(
482            ErrorCode::MissingField,
483            format!("the history has no {IDENTITY_FILE}, so it is not a Surjection store"),
484        )
485    })?;
486    let blob = repo.find_blob(entry.id()).map_err(git_error)?;
487    let text = std::str::from_utf8(blob.content())
488        .map_err(|_| CoreError::new(ErrorCode::ParseError, "loadout.toml is not UTF-8"))?;
489    let identity = TomlDocument::<StoreIdentity>::parse(text)
490        .map_err(|diagnostic| diagnostic.to_core_error(Some(Path::new(IDENTITY_FILE))))?
491        .into_value();
492    ids::check(IdKind::Store, &identity.store_id)?;
493    Ok(identity)
494}