Skip to main content

surjection_core/store/
mod.rs

1//! The versioned store `<SURJECTION_HOME>/store` (SPEC 9.1): a normal git
2//! repository on branch `main`, readable by any git client.
3//!
4//! Local operations use `git2` with a vendored libgit2 and no network
5//! features (SPEC 4.2), so the store works offline without a git binary.
6//! Commits carry an explicit author and committer (`surjection <label>` /
7//! `<machine-id>@surjection.invalid`); Surjection never asks git for an identity
8//! and never writes git configuration. Every mutation goes through
9//! [`Store::transaction`], which validates, writes and commits once.
10//!
11//! The working tree is the source of truth for reads, so hand edits are
12//! seen before they are committed. git types stay private to this module.
13//!
14//! History views live in [`diff`] (semantic and raw diffs) and [`tags`];
15//! [`restore`] restores a past revision as a new commit and client files
16//! from apply backups (SPEC 9.3 to 9.5).
17
18mod bootstrap;
19pub mod diff;
20mod lock;
21mod log;
22pub mod merge;
23pub mod restore;
24mod revision;
25pub mod tags;
26mod trailers;
27mod transaction;
28
29use std::fmt;
30use std::path::{Path, PathBuf};
31use std::sync::Arc;
32use std::time::{SystemTime, UNIX_EPOCH};
33
34use git2::{Commit, Repository, RepositoryInitOptions, Signature};
35use schemars::JsonSchema;
36use serde::{Deserialize, Serialize};
37use toml::value::{Date, Datetime, Offset, Time};
38
39use crate::brand;
40use crate::env::Env;
41use crate::error::{CoreError, ErrorCode};
42use crate::fs::Fs;
43use crate::model::ids::{self, IdKind};
44use crate::model::server::Server;
45use crate::model::{SCHEMA_VERSION, StoreModel, TomlDocument};
46use crate::paths::SurjectionHome;
47use crate::secrets::scanner::SecretMemory;
48
49pub use bootstrap::{bare_commit_subject, bare_refs, bare_store_id, check_bare, export_store_id};
50pub use lock::{LOCK_FILE, LOCK_TIMEOUT, StoreLock};
51pub use log::{HistoryFinding, LogEntry, LogFilter, entity_paths};
52pub use revision::Revision;
53pub use trailers::{ApplyRef, MachineRef, Scope, Trailers, compose_message, message_summary};
54pub use transaction::{Committed, Operation, Transaction};
55
56/// Read access to store files: the working tree ([`Store`]), the working
57/// tree plus staged changes ([`Transaction`]) or a past commit
58/// ([`Revision`]).
59pub trait StoreRead {
60    /// A store file as text; `None` if it does not exist.
61    fn read_file(&self, relative: &str) -> Result<Option<String>, CoreError>;
62
63    /// Names of the files (not directories) directly in the store-relative
64    /// directory `dir`, sorted; empty if it does not exist.
65    fn list_files(&self, dir: &str) -> Result<Vec<String>, CoreError>;
66}
67
68impl StoreRead for Store<'_> {
69    fn read_file(&self, relative: &str) -> Result<Option<String>, CoreError> {
70        self.read_to_string(relative)
71    }
72
73    fn list_files(&self, dir: &str) -> Result<Vec<String>, CoreError> {
74        let path = self.path(dir)?;
75        if !self.fs.is_dir(&path) {
76            return Ok(Vec::new());
77        }
78        let entries = self
79            .fs
80            .read_dir(&path)
81            .map_err(|err| io_error("cannot list directory", &path, &err))?;
82        let mut names: Vec<String> = entries
83            .iter()
84            .filter(|entry| !self.fs.is_dir(entry))
85            .filter_map(|entry| entry.file_name()?.to_str().map(str::to_owned))
86            .collect();
87        names.sort();
88        Ok(names)
89    }
90}
91
92/// The store branch.
93pub const BRANCH: &str = "main";
94/// Store identity file at the store root.
95pub const IDENTITY_FILE: &str = "loadout.toml";
96/// Machine identity file in `state/`.
97pub const MACHINE_FILE: &str = "machine.toml";
98/// Written by `init`: store files are versioned byte for byte, whatever
99/// `core.autocrlf` a git client uses on the store.
100const GITATTRIBUTES: (&str, &str) = (".gitattributes", "* -text\n");
101
102/// `store/loadout.toml`: ties remotes and machines to one logical store.
103#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
104#[schemars(title = "Surjection store identity (store/loadout.toml)")]
105pub struct StoreIdentity {
106    /// Schema version; always 1.
107    pub schema: i64,
108    /// ULID.
109    pub store_id: String,
110    #[schemars(with = "String")]
111    pub created_at: Datetime,
112    #[serde(flatten)]
113    #[schemars(skip)]
114    pub extra: toml::Table,
115}
116
117impl StoreModel for StoreIdentity {
118    const SCHEMA_NAME: &'static str = "store-identity";
119}
120
121/// This machine (`state/machine.toml`): the commit author and the
122/// `Surjection-Machine` trailer. Created on the first mutation.
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct Machine {
125    /// ULID; never changes.
126    pub id: String,
127    /// Human label, cleaned so it fits a git signature and a trailer.
128    pub label: String,
129}
130
131#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
132#[schemars(title = "Surjection machine identity (state/machine.toml)")]
133struct MachineFile {
134    schema: i64,
135    machine_id: String,
136    label: String,
137    #[serde(flatten)]
138    #[schemars(skip)]
139    extra: toml::Table,
140}
141
142impl StoreModel for MachineFile {
143    const SCHEMA_NAME: &'static str = "machine-identity";
144}
145
146/// Label used when the host name is unknown.
147const DEFAULT_LABEL: &str = "machine";
148
149impl Machine {
150    /// Reads `state/machine.toml`, if it exists.
151    pub fn load(fs: &dyn Fs, state_dir: &Path) -> Result<Option<Self>, CoreError> {
152        let path = state_dir.join(MACHINE_FILE);
153        if !fs.exists(&path) {
154            return Ok(None);
155        }
156        let file = TomlDocument::<MachineFile>::load(fs, &path)?.into_value();
157        ids::check(IdKind::Machine, &file.machine_id).map_err(|err| err.with_path(&path))?;
158        Ok(Some(Self {
159            id: file.machine_id,
160            label: clean_label(&file.label),
161        }))
162    }
163
164    /// Reads `state/machine.toml`, creating it with a new ULID and the host
165    /// name as label on first use.
166    pub fn load_or_create(env: &Env, fs: &dyn Fs, state_dir: &Path) -> Result<Self, CoreError> {
167        if let Some(machine) = Self::load(fs, state_dir)? {
168            return Ok(machine);
169        }
170        let machine = Self {
171            id: ids::new_ulid(env.now())?,
172            label: clean_label(env.hostname().unwrap_or(DEFAULT_LABEL)),
173        };
174        let path = state_dir.join(MACHINE_FILE);
175        fs.create_dir_all(state_dir)
176            .map_err(|err| io_error("cannot create directory", state_dir, &err))?;
177        TomlDocument::new(MachineFile {
178            schema: SCHEMA_VERSION,
179            machine_id: machine.id.clone(),
180            label: machine.label.clone(),
181            extra: toml::Table::new(),
182        })
183        .save(fs, &path)?;
184        Ok(machine)
185    }
186
187    /// `surjection <label>` / `<machine-id>@surjection.invalid` at `time`.
188    fn signature(&self, time: SystemTime) -> Result<Signature<'static>, CoreError> {
189        let seconds = time
190            .duration_since(UNIX_EPOCH)
191            .map_or(0, |elapsed| elapsed.as_secs());
192        Signature::new(
193            &format!("{} {}", brand::COMMIT_AUTHOR_NAME, self.label),
194            &format!("{}@{}", self.id, brand::COMMIT_EMAIL_DOMAIN),
195            &git2::Time::new(i64::try_from(seconds).unwrap_or(i64::MAX), 0),
196        )
197        .map_err(git_error)
198    }
199}
200
201/// Drops characters a git signature or a trailer cannot hold (`<`, `>`,
202/// control characters) and collapses whitespace.
203fn clean_label(raw: &str) -> String {
204    let cleaned = raw
205        .chars()
206        .map(|c| if c.is_control() { ' ' } else { c })
207        .filter(|c| !matches!(c, '<' | '>'))
208        .collect::<String>()
209        .split_whitespace()
210        .collect::<Vec<_>>()
211        .join(" ");
212    if cleaned.is_empty() {
213        DEFAULT_LABEL.to_owned()
214    } else {
215        cleaned
216    }
217}
218
219/// A store commit id (full lower-case hex).
220#[derive(Debug, Clone, PartialEq, Eq, Hash)]
221pub struct CommitId(String);
222
223impl CommitId {
224    fn from_oid(oid: git2::Oid) -> Self {
225        Self(oid.to_string())
226    }
227
228    /// A full commit id from text (40 hex digits, any case).
229    pub fn from_text(text: &str) -> Result<Self, CoreError> {
230        git2::Oid::from_str(text)
231            .ok()
232            .filter(|_| text.len() == 40)
233            .map(Self::from_oid)
234            .ok_or_else(|| {
235                CoreError::new(
236                    ErrorCode::InvalidValue,
237                    format!("{text:?} is not a commit id"),
238                )
239            })
240    }
241
242    pub fn as_str(&self) -> &str {
243        &self.0
244    }
245
246    /// The first 7 hex digits.
247    pub fn short(&self) -> &str {
248        &self.0[..self.0.len().min(7)]
249    }
250}
251
252impl fmt::Display for CommitId {
253    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254        f.write_str(&self.0)
255    }
256}
257
258/// One server file as listed by [`Store::servers`]: the parsed and
259/// validated document, or why it could not be used.
260#[derive(Debug)]
261pub struct ServerEntry {
262    /// The file name without `.toml`.
263    pub id: String,
264    pub document: Result<TomlDocument<Server>, CoreError>,
265}
266
267/// An open store.
268pub struct Store<'a> {
269    env: Env,
270    fs: &'a dyn Fs,
271    root: PathBuf,
272    state_dir: PathBuf,
273    repo: Repository,
274    identity: StoreIdentity,
275    client: String,
276    /// Values resolved in this process; every commit is scanned for them.
277    secrets: Arc<SecretMemory>,
278}
279
280impl fmt::Debug for Store<'_> {
281    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282        f.debug_struct("Store")
283            .field("root", &self.root)
284            .field("store_id", &self.identity.store_id)
285            .field("client", &self.client)
286            .finish_non_exhaustive()
287    }
288}
289
290impl<'a> Store<'a> {
291    /// A store over an open repository (bootstrap paths).
292    fn from_parts(
293        env: &Env,
294        fs: &'a dyn Fs,
295        home: &SurjectionHome,
296        client: &str,
297        repo: Repository,
298        identity: StoreIdentity,
299    ) -> Result<Self, CoreError> {
300        Ok(Self {
301            env: env.clone(),
302            fs,
303            root: home.store_dir(),
304            state_dir: home.state_dir(),
305            repo,
306            identity,
307            client: client.to_owned(),
308            secrets: Arc::new(SecretMemory::new()?),
309        })
310    }
311
312    /// Opens the store in `home`, or `None` when it has not been created
313    /// yet. Creates nothing. `client` names the calling program and version
314    /// for the `Surjection-Client` trailer (`surject-cli/0.1.0`).
315    pub fn open(
316        env: &Env,
317        fs: &'a dyn Fs,
318        home: &SurjectionHome,
319        client: &str,
320    ) -> Result<Option<Self>, CoreError> {
321        let root = home.store_dir();
322        if !fs.exists(&root.join(".git")) {
323            return Ok(None);
324        }
325        let repo = Repository::open(&root).map_err(git_error)?;
326        if repo.head().is_err() {
327            // Initialized but never committed (an interrupted init).
328            return Ok(None);
329        }
330        let path = root.join(IDENTITY_FILE);
331        let identity = TomlDocument::<StoreIdentity>::load(fs, &path)?.into_value();
332        ids::check(IdKind::Store, &identity.store_id).map_err(|err| err.with_path(&path))?;
333        Ok(Some(Self {
334            env: env.clone(),
335            fs,
336            root,
337            state_dir: home.state_dir(),
338            repo,
339            identity,
340            client: client.to_owned(),
341            secrets: Arc::new(SecretMemory::new()?),
342        }))
343    }
344
345    /// [`Store::open`] without reading `loadout.toml` through the typed
346    /// model, so a store whose files are at an older schema can be opened
347    /// to migrate them (`crate::versions`). Commits made through it carry
348    /// the store id as written.
349    pub(crate) fn open_raw(
350        env: &Env,
351        fs: &'a dyn Fs,
352        home: &SurjectionHome,
353        client: &str,
354    ) -> Result<Option<Self>, CoreError> {
355        let root = home.store_dir();
356        if !fs.exists(&root.join(".git")) {
357            return Ok(None);
358        }
359        let repo = Repository::open(&root).map_err(git_error)?;
360        if repo.head().is_err() {
361            return Ok(None);
362        }
363        let path = root.join(IDENTITY_FILE);
364        let text = fs
365            .read_to_string(&path)
366            .map_err(|err| io_error("cannot read file", &path, &err))?;
367        let table: toml::Table =
368            text.trim_start_matches('\u{feff}')
369                .parse()
370                .map_err(|err: toml::de::Error| {
371                    CoreError::new(ErrorCode::ParseError, err.message().to_owned()).with_path(&path)
372                })?;
373        let identity = StoreIdentity {
374            schema: table
375                .get("schema")
376                .and_then(toml::Value::as_integer)
377                .unwrap_or(SCHEMA_VERSION),
378            store_id: table
379                .get("store_id")
380                .and_then(toml::Value::as_str)
381                .unwrap_or_default()
382                .to_owned(),
383            created_at: table
384                .get("created_at")
385                .and_then(toml::Value::as_datetime)
386                .copied()
387                .unwrap_or_else(|| utc_datetime(env.now())),
388            extra: toml::Table::new(),
389        };
390        Self::from_parts(env, fs, home, client, repo, identity).map(Some)
391    }
392
393    /// Opens the store in `home`, creating it first if needed: a git
394    /// repository on `main` whose initial commit `init: store <store_id>`
395    /// holds `loadout.toml`.
396    pub fn open_or_init(
397        env: &Env,
398        fs: &'a dyn Fs,
399        home: &SurjectionHome,
400        client: &str,
401    ) -> Result<Self, CoreError> {
402        if let Some(store) = Self::open(env, fs, home, client)? {
403            return Ok(store);
404        }
405        let state_dir = home.state_dir();
406        let _lock = StoreLock::acquire(fs, &state_dir, LOCK_TIMEOUT)?;
407        // Another process may have created it while this one waited.
408        if let Some(store) = Self::open(env, fs, home, client)? {
409            return Ok(store);
410        }
411        let machine = Machine::load_or_create(env, fs, &state_dir)?;
412        let root = home.store_dir();
413        // Through `fs` first, so a confined test fails before libgit2 writes.
414        fs.create_dir_all(&root)
415            .map_err(|err| io_error("cannot create directory", &root, &err))?;
416        let repo = if fs.exists(&root.join(".git")) {
417            Repository::open(&root)
418        } else {
419            let mut options = RepositoryInitOptions::new();
420            options
421                .bare(false)
422                .no_reinit(true)
423                .mkdir(true)
424                .external_template(false)
425                .initial_head(BRANCH);
426            Repository::init_opts(&root, &options)
427        }
428        .map_err(git_error)?;
429
430        // Reuse the identity of an interrupted init, if it is intact.
431        let identity_path = root.join(IDENTITY_FILE);
432        let identity = TomlDocument::<StoreIdentity>::load(fs, &identity_path)
433            .ok()
434            .map(TomlDocument::into_value)
435            .filter(|identity| ids::is_valid(IdKind::Store, &identity.store_id));
436        let identity = match identity {
437            Some(identity) => identity,
438            None => StoreIdentity {
439                schema: SCHEMA_VERSION,
440                store_id: ids::new_ulid(env.now())?,
441                created_at: utc_datetime(env.now()),
442                extra: toml::Table::new(),
443            },
444        };
445        let identity_text = TomlDocument::new(identity.clone()).to_text()?;
446        let store = Self {
447            env: env.clone(),
448            fs,
449            root,
450            state_dir,
451            repo,
452            identity,
453            client: client.to_owned(),
454            secrets: Arc::new(SecretMemory::new()?),
455        };
456        let operation = Operation::new(
457            "store.init",
458            format!("init: store {}", store.identity.store_id),
459        );
460        let changes = [
461            (IDENTITY_FILE.to_owned(), Some(identity_text.into_bytes())),
462            (GITATTRIBUTES.0.to_owned(), Some(GITATTRIBUTES.1.into())),
463        ]
464        .into_iter()
465        .collect();
466        store.commit_changes(&machine, &operation, changes)?;
467        Ok(store)
468    }
469
470    /// The store working tree.
471    pub fn root(&self) -> &Path {
472        &self.root
473    }
474
475    /// The file system the store was opened with.
476    pub fn fs(&self) -> &'a dyn Fs {
477        self.fs
478    }
479
480    /// `<SURJECTION_HOME>/state`.
481    pub fn state_dir(&self) -> &Path {
482        &self.state_dir
483    }
484
485    /// Whether commit `id` is HEAD or in HEAD's history.
486    pub fn contains(&self, id: &CommitId) -> bool {
487        let (Ok(head), Ok(oid)) = (self.head(), git2::Oid::from_str(id.as_str())) else {
488            return false;
489        };
490        let Ok(head) = git2::Oid::from_str(head.as_str()) else {
491            return false;
492        };
493        head == oid || self.repo.graph_descendant_of(head, oid).unwrap_or(false)
494    }
495
496    /// The commit reference `name` (`refs/remotes/<name>/main`) points at;
497    /// `None` when there is no such reference.
498    pub fn reference_target(&self, name: &str) -> Result<Option<CommitId>, CoreError> {
499        match self.repo.find_reference(name) {
500            Ok(reference) => {
501                let commit = reference.peel_to_commit().map_err(git_error)?;
502                Ok(Some(CommitId::from_oid(commit.id())))
503            }
504            Err(err) if err.code() == git2::ErrorCode::NotFound => Ok(None),
505            Err(err) => Err(git_error(err)),
506        }
507    }
508
509    /// The environment the store was opened with.
510    pub fn env(&self) -> &Env {
511        &self.env
512    }
513
514    /// Hashes of the secret values this process resolved. Share it with
515    /// every [`crate::secrets::providers::Resolver`] of the process, so
516    /// commits holding a resolved value are refused (SPEC 11.8).
517    pub fn secret_memory(&self) -> &Arc<SecretMemory> {
518        &self.secrets
519    }
520
521    pub fn identity(&self) -> &StoreIdentity {
522        &self.identity
523    }
524
525    pub fn store_id(&self) -> &str {
526        &self.identity.store_id
527    }
528
529    /// The commit `main` points at.
530    pub fn head(&self) -> Result<CommitId, CoreError> {
531        Ok(CommitId::from_oid(self.head_commit()?.id()))
532    }
533
534    /// Absolute path of a store-relative path (`servers/github.toml`).
535    pub fn path(&self, relative: &str) -> Result<PathBuf, CoreError> {
536        check_relative(relative)?;
537        Ok(relative
538            .split('/')
539            .fold(self.root.clone(), |path, part| path.join(part)))
540    }
541
542    /// Reads a store file from the working tree; `None` if it does not exist.
543    pub fn read_to_string(&self, relative: &str) -> Result<Option<String>, CoreError> {
544        let path = self.path(relative)?;
545        if !self.fs.exists(&path) {
546            return Ok(None);
547        }
548        self.fs
549            .read_to_string(&path)
550            .map(Some)
551            .map_err(|err| io_error("cannot read file", &path, &err))
552    }
553
554    /// The server `id`, parsed but not validated; `None` if it does not exist.
555    pub fn server(&self, id: &str) -> Result<Option<TomlDocument<Server>>, CoreError> {
556        let path = self.path(&server_path(id)?)?;
557        if !self.fs.exists(&path) {
558            return Ok(None);
559        }
560        TomlDocument::load(self.fs, &path).map(Some)
561    }
562
563    /// Every `servers/*.toml`, sorted by id, parsed and validated.
564    pub fn servers(&self) -> Result<Vec<ServerEntry>, CoreError> {
565        let dir = self.root.join("servers");
566        if !self.fs.is_dir(&dir) {
567            return Ok(Vec::new());
568        }
569        let paths = self
570            .fs
571            .read_dir(&dir)
572            .map_err(|err| io_error("cannot list directory", &dir, &err))?;
573        let entries = paths
574            .into_iter()
575            .filter_map(|path| {
576                let id = path
577                    .file_name()?
578                    .to_str()?
579                    .strip_suffix(".toml")?
580                    .to_owned();
581                Some((id, path))
582            })
583            .map(|(id, path)| {
584                let document =
585                    TomlDocument::<Server>::load(self.fs, &path).and_then(|doc| {
586                        match doc.value().validate(Some(&id)).first_error(Some(&path)) {
587                            Some(err) => Err(err),
588                            None => Ok(doc),
589                        }
590                    });
591                ServerEntry { id, document }
592            })
593            .collect();
594        Ok(entries)
595    }
596
597    fn head_commit(&self) -> Result<Commit<'_>, CoreError> {
598        self.repo
599            .head()
600            .and_then(|head| head.peel_to_commit())
601            .map_err(git_error)
602    }
603}
604
605/// `servers/<id>.toml`, after checking `id`.
606pub fn server_path(id: &str) -> Result<String, CoreError> {
607    ids::check(IdKind::Server, id)?;
608    Ok(format!("servers/{id}.toml"))
609}
610
611/// Store-relative paths use `/`, name no parent or current directory and
612/// never reach into `.git`.
613fn check_relative(relative: &str) -> Result<(), CoreError> {
614    let valid = !relative.is_empty()
615        && relative.split('/').all(|part| {
616            !part.is_empty() && part != "." && part != ".." && !part.contains(['\\', ':'])
617        })
618        && !relative
619            .split('/')
620            .next()
621            .is_some_and(|first| first.eq_ignore_ascii_case(".git"));
622    if valid {
623        Ok(())
624    } else {
625        Err(CoreError::new(
626            ErrorCode::InvalidPath,
627            format!("{relative:?} is not a store-relative path"),
628        ))
629    }
630}
631
632/// `time` as a TOML offset date-time in UTC, whole seconds.
633pub fn utc_datetime(time: SystemTime) -> Datetime {
634    let seconds = time
635        .duration_since(UNIX_EPOCH)
636        .map_or(0, |elapsed| elapsed.as_secs());
637    let seconds = i64::try_from(seconds).unwrap_or(i64::MAX);
638    let (year, month, day) = civil_from_days(seconds.div_euclid(86_400));
639    let of_day = seconds.rem_euclid(86_400);
640    Datetime {
641        date: Some(Date {
642            year: u16::try_from(year).unwrap_or(u16::MAX),
643            month,
644            day,
645        }),
646        time: Some(Time {
647            hour: (of_day / 3600) as u8,
648            minute: (of_day % 3600 / 60) as u8,
649            second: Some((of_day % 60) as u8),
650            nanosecond: None,
651        }),
652        offset: Some(Offset::Z),
653    }
654}
655
656/// Proleptic Gregorian date of a day count since 1970-01-01 (Howard
657/// Hinnant's `civil_from_days`).
658fn civil_from_days(days: i64) -> (i64, u8, u8) {
659    let z = days + 719_468;
660    let era = z.div_euclid(146_097);
661    let doe = z.rem_euclid(146_097);
662    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
663    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
664    let mp = (5 * doy + 2) / 153;
665    let day = (doy - (153 * mp + 2) / 5 + 1) as u8;
666    let month = if mp < 10 { mp + 3 } else { mp - 9 } as u8;
667    let year = yoe + era * 400 + i64::from(month <= 2);
668    (year, month, day)
669}
670
671fn git_error(err: git2::Error) -> CoreError {
672    CoreError::new(ErrorCode::GitError, err.message().to_owned())
673}
674
675fn io_error(what: &str, path: &Path, err: &std::io::Error) -> CoreError {
676    CoreError::new(ErrorCode::IoError, format!("{what}: {err}")).with_path(path)
677}