Skip to main content

surjection_core/store/
transaction.rs

1//! `Store::transaction` (SPEC 4.1, 9.2): every core mutation stages its
2//! file changes, then validates, writes and commits exactly once under the
3//! cross-process lock.
4
5use std::collections::BTreeMap;
6use std::path::Path;
7
8use git2::{Commit, IndexEntry, IndexTime, Oid, Tree};
9
10use crate::error::{CoreError, ErrorCode};
11use crate::model::server::Server;
12use crate::model::{StoreDocument, StoreFile, TomlDocument, validate_store_file};
13use crate::secrets::scanner::{ALLOWLIST_FILE, Allowlist, leak_error, scan_text};
14use crate::store::lock::{LOCK_TIMEOUT, StoreLock};
15use crate::store::trailers::{ApplyRef, MachineRef, Scope, Trailers, compose_message};
16use crate::store::{
17    CommitId, Machine, Store, StoreRead, check_relative, git_error, io_error, server_path,
18};
19
20/// What a transaction does, for its commit message and trailers.
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct Operation {
23    op: String,
24    summary: String,
25    entities: Vec<String>,
26    scope: Scope,
27    apply: Option<ApplyRef>,
28}
29
30impl Operation {
31    /// `op` is the `Surjection-Op` value (`server.add`); `summary` the commit
32    /// subject (`server: add github`). The scope defaults to `system`.
33    pub fn new(op: impl Into<String>, summary: impl Into<String>) -> Self {
34        Self {
35            op: op.into(),
36            summary: summary.into(),
37            entities: Vec::new(),
38            scope: Scope::System,
39            apply: None,
40        }
41    }
42
43    /// Adds a `Surjection-Entity` (`server/github`). A bulk change adds one per
44    /// entity.
45    pub fn entity(mut self, entity: impl Into<String>) -> Self {
46        self.entities.push(entity.into());
47        self
48    }
49
50    pub fn scope(mut self, scope: Scope) -> Self {
51        self.scope = scope;
52        self
53    }
54
55    fn check(&self) -> Result<(), CoreError> {
56        let op_ok = !self.op.is_empty()
57            && self
58                .op
59                .bytes()
60                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"._-".contains(&b));
61        if !op_ok {
62            return Err(CoreError::new(
63                ErrorCode::InvalidValue,
64                format!("invalid operation name {:?}", self.op),
65            ));
66        }
67        if self.summary.trim().is_empty() {
68            return Err(CoreError::new(
69                ErrorCode::InvalidValue,
70                "a commit summary must not be empty",
71            ));
72        }
73        Ok(())
74    }
75
76    fn trailers(&self, machine: &Machine, client: &str) -> Trailers {
77        Trailers {
78            op: Some(self.op.clone()),
79            entities: self.entities.clone(),
80            scope: Some(self.scope.clone()),
81            machine: Some(MachineRef {
82                id: machine.id.clone(),
83                label: machine.label.clone(),
84            }),
85            client: Some(client.to_owned()),
86            apply: self.apply.clone(),
87            other: Vec::new(),
88        }
89    }
90}
91
92/// Result of [`Store::transaction`].
93#[derive(Debug)]
94pub struct Committed<T> {
95    /// What the closure returned.
96    pub value: T,
97    /// The new commit; `None` when the staged changes left the tree as it was.
98    pub commit: Option<CommitId>,
99}
100
101/// Staged changes, keyed by store-relative path; `None` removes the file.
102pub(crate) type Changes = BTreeMap<String, Option<Vec<u8>>>;
103
104/// Changes staged inside [`Store::transaction`]. Reads see staged changes.
105pub struct Transaction<'a> {
106    store: &'a Store<'a>,
107    machine: Machine,
108    operation: Operation,
109    changes: Changes,
110}
111
112impl Transaction<'_> {
113    /// The store this transaction commits to.
114    pub fn store(&self) -> &Store<'_> {
115        self.store
116    }
117
118    /// The machine making the change (the commit author).
119    pub fn machine(&self) -> &Machine {
120        &self.machine
121    }
122
123    /// Replaces the commit subject (an apply run names its files only once
124    /// it has run).
125    pub fn set_summary(&mut self, summary: impl Into<String>) {
126        self.operation.summary = summary.into();
127    }
128
129    /// Adds a `Surjection-Entity` trailer, once per entity.
130    pub fn add_entity(&mut self, entity: impl Into<String>) {
131        let entity = entity.into();
132        if !self.operation.entities.contains(&entity) {
133            self.operation.entities.push(entity);
134        }
135    }
136
137    /// Sets the `Surjection-Apply: <apply-id> <outcome>` trailer.
138    pub fn set_apply(&mut self, apply: ApplyRef) {
139        self.operation.apply = Some(apply);
140    }
141
142    /// Whether anything is staged.
143    pub fn has_changes(&self) -> bool {
144        !self.changes.is_empty()
145    }
146
147    /// Validates and leak-scans what is staged so far, as the commit will
148    /// (SPEC 5, 11.8), without writing anything. For work inside the
149    /// transaction that has effects outside the store (an instant apply).
150    pub fn check(&self) -> Result<(), CoreError> {
151        self.store.validate_changes(&self.changes)?;
152        let message = compose_message(
153            &self.operation.summary,
154            &self.operation.trailers(&self.machine, &self.store.client),
155        );
156        self.store.scan_changes(&self.changes, &message)
157    }
158
159    /// A store file as this transaction sees it; `None` if absent.
160    pub fn read_to_string(&self, relative: &str) -> Result<Option<String>, CoreError> {
161        check_relative(relative)?;
162        match self.changes.get(relative) {
163            Some(Some(bytes)) => String::from_utf8(bytes.clone()).map(Some).map_err(|_| {
164                CoreError::new(ErrorCode::InvalidValue, "staged file is not UTF-8")
165                    .with_path(relative)
166            }),
167            Some(None) => Ok(None),
168            None => self.store.read_to_string(relative),
169        }
170    }
171
172    pub fn exists(&self, relative: &str) -> Result<bool, CoreError> {
173        check_relative(relative)?;
174        match self.changes.get(relative) {
175            Some(change) => Ok(change.is_some()),
176            None => Ok(self.store.fs.exists(&self.store.path(relative)?)),
177        }
178    }
179
180    /// Stages `contents` for `relative`.
181    pub fn write(&mut self, relative: &str, contents: impl Into<Vec<u8>>) -> Result<(), CoreError> {
182        check_relative(relative)?;
183        self.changes
184            .insert(relative.to_owned(), Some(contents.into()));
185        Ok(())
186    }
187
188    /// Stages the removal of `relative`.
189    pub fn remove(&mut self, relative: &str) -> Result<(), CoreError> {
190        check_relative(relative)?;
191        self.changes.insert(relative.to_owned(), None);
192        Ok(())
193    }
194
195    /// Stages a new server; `already_exists` if the id is taken.
196    pub fn add_server(&mut self, server: Server) -> Result<(), CoreError> {
197        let relative = server_path(&server.id)?;
198        if self.exists(&relative)? {
199            return Err(CoreError::new(
200                ErrorCode::AlreadyExists,
201                format!("server {:?} already exists", server.id),
202            )
203            .with_path(self.store.path(&relative)?));
204        }
205        let text = TomlDocument::new(server).to_text()?;
206        self.write(&relative, text)
207    }
208
209    /// Stages the removal of a server; `not_found` if there is none.
210    pub fn remove_server(&mut self, id: &str) -> Result<(), CoreError> {
211        let relative = server_path(id)?;
212        if !self.exists(&relative)? {
213            return Err(CoreError::new(
214                ErrorCode::NotFound,
215                format!("server {id:?} does not exist"),
216            ));
217        }
218        self.remove(&relative)
219    }
220}
221
222impl StoreRead for Transaction<'_> {
223    fn read_file(&self, relative: &str) -> Result<Option<String>, CoreError> {
224        self.read_to_string(relative)
225    }
226
227    fn list_files(&self, dir: &str) -> Result<Vec<String>, CoreError> {
228        let mut names = self.store.list_files(dir)?;
229        let prefix = format!("{dir}/");
230        for (relative, change) in &self.changes {
231            let Some(name) = relative.strip_prefix(&prefix) else {
232                continue;
233            };
234            if name.contains('/') {
235                continue;
236            }
237            match change {
238                Some(_) if !names.iter().any(|known| known == name) => names.push(name.to_owned()),
239                Some(_) => {}
240                None => names.retain(|known| known != name),
241            }
242        }
243        names.sort();
244        Ok(names)
245    }
246}
247
248impl Store<'_> {
249    /// Runs one mutation: takes the cross-process lock (waiting up to
250    /// [`LOCK_TIMEOUT`]), lets `f` stage changes, validates every staged
251    /// store file, runs the leak scanner (SPEC 11.8) over the staged files
252    /// and the commit message, writes them to the working tree and creates
253    /// exactly one commit with the [`Operation`]'s trailers. When `f`,
254    /// validation or the scanner fails nothing is written and nothing is
255    /// committed.
256    pub fn transaction<'s, T>(
257        &'s self,
258        operation: Operation,
259        f: impl FnOnce(&mut Transaction<'s>) -> Result<T, CoreError>,
260    ) -> Result<Committed<T>, CoreError> {
261        operation.check()?;
262        let _lock = StoreLock::acquire(self.fs, &self.state_dir, LOCK_TIMEOUT)?;
263        let machine = Machine::load_or_create(&self.env, self.fs, &self.state_dir)?;
264        let mut tx = Transaction {
265            store: self,
266            machine,
267            operation,
268            changes: Changes::new(),
269        };
270        let value = f(&mut tx)?;
271        tx.operation.check()?;
272        let commit = self.commit_changes(&tx.machine, &tx.operation, tx.changes)?;
273        Ok(Committed { value, commit })
274    }
275
276    /// Store files edited, added or removed in the working tree since HEAD
277    /// (hand edits), store-relative and sorted. A nested repository (shown
278    /// by git as a directory) is not a store file and is left out.
279    pub fn worktree_changes(&self) -> Result<Vec<String>, CoreError> {
280        let mut options = git2::StatusOptions::new();
281        options
282            .include_untracked(true)
283            .recurse_untracked_dirs(true)
284            .include_ignored(false)
285            .exclude_submodules(true);
286        let statuses = self.repo.statuses(Some(&mut options)).map_err(git_error)?;
287        let mut files: Vec<String> = statuses
288            .iter()
289            .filter(|entry| !entry.status().is_ignored())
290            .filter_map(|entry| entry.path().ok().map(|path| path.replace('\\', "/")))
291            .filter(|path| !path.ends_with('/'))
292            .collect();
293        files.sort();
294        files.dedup();
295        Ok(files)
296    }
297
298    /// Commits the working tree's hand edits ([`Store::worktree_changes`],
299    /// read under the lock) as one commit with their entities as trailers,
300    /// after the same validation and leak scan as every transaction.
301    /// Returns the commit (`None` when the working tree is clean) and the
302    /// files it holds.
303    pub fn commit_worktree(
304        &self,
305        operation: Operation,
306    ) -> Result<(Option<CommitId>, Vec<String>), CoreError> {
307        operation.check()?;
308        let _lock = StoreLock::acquire(self.fs, &self.state_dir, LOCK_TIMEOUT)?;
309        let machine = Machine::load_or_create(&self.env, self.fs, &self.state_dir)?;
310        let files = self.worktree_changes()?;
311        let mut operation = operation;
312        for entity in crate::store::diff::trailer_entities(&files) {
313            operation = operation.entity(entity);
314        }
315        let mut changes = Changes::new();
316        for relative in &files {
317            let path = self.path(relative)?;
318            let bytes = if self.fs.exists(&path) {
319                Some(
320                    self.fs
321                        .read(&path)
322                        .map_err(|err| io_error("cannot read file", &path, &err))?,
323                )
324            } else {
325                None
326            };
327            changes.insert(relative.clone(), bytes);
328        }
329        let commit = self.commit_changes(&machine, &operation, changes)?;
330        Ok((commit, files))
331    }
332
333    /// Validates, scans, writes and commits `changes`. The caller holds the
334    /// lock. The scanner runs before the first blob reaches the object
335    /// database.
336    pub(crate) fn commit_changes(
337        &self,
338        machine: &Machine,
339        operation: &Operation,
340        changes: Changes,
341    ) -> Result<Option<CommitId>, CoreError> {
342        if changes.is_empty() {
343            return Ok(None);
344        }
345        self.commit_with(machine, operation, changes, None, CommitMode::Normal)
346    }
347
348    /// Commits the files a schema migration rewrote (`crate::versions`),
349    /// from HEAD's blobs, without touching the working tree: the caller
350    /// writes it after the commit, so a crash in between leaves old files
351    /// the next run upgrades. The caller holds the lock. `validate` is false
352    /// only when the files were upgraded past the version this build reads
353    /// (the test hook's migrations); the leak scanner always runs.
354    pub(crate) fn commit_migration(
355        &self,
356        operation: &Operation,
357        files: crate::store::merge::Files,
358        validate: bool,
359    ) -> Result<Option<CommitId>, CoreError> {
360        let machine = Machine::load_or_create(&self.env, self.fs, &self.state_dir)?;
361        let changes: Changes = files
362            .into_iter()
363            .map(|(relative, bytes)| (relative, Some(bytes)))
364            .collect();
365        if changes.is_empty() {
366            return Ok(None);
367        }
368        operation.check()?;
369        self.commit_with(
370            &machine,
371            operation,
372            changes,
373            None,
374            CommitMode::Migration { validate },
375        )
376    }
377
378    /// A merge commit of HEAD and `merged` with `changes` over HEAD's tree
379    /// (SPEC 9.9 step 4): validated, scanned, and made even when the tree
380    /// equals HEAD's, so the incoming history is recorded. The caller
381    /// holds the lock.
382    pub(crate) fn commit_merge(
383        &self,
384        machine: &Machine,
385        operation: &Operation,
386        changes: Changes,
387        merged: Oid,
388    ) -> Result<CommitId, CoreError> {
389        let merged = self.repo.find_commit(merged).map_err(git_error)?;
390        self.commit_with(
391            machine,
392            operation,
393            changes,
394            Some(&merged),
395            CommitMode::Normal,
396        )?
397        .ok_or_else(|| CoreError::new(ErrorCode::GitError, "the merge commit was not made"))
398    }
399
400    fn commit_with(
401        &self,
402        machine: &Machine,
403        operation: &Operation,
404        changes: Changes,
405        merged: Option<&Commit<'_>>,
406        mode: CommitMode,
407    ) -> Result<Option<CommitId>, CoreError> {
408        if !matches!(mode, CommitMode::Migration { validate: false }) {
409            self.validate_changes(&changes)?;
410        }
411        let message = compose_message(
412            &operation.summary,
413            &operation.trailers(machine, &self.client),
414        );
415        self.scan_changes(&changes, &message)?;
416
417        let parent = match self.repo.head() {
418            Ok(head) => Some(head.peel_to_commit().map_err(git_error)?),
419            Err(_) => None,
420        };
421        // The new tree is HEAD's tree plus exactly the staged changes, built
422        // from the bytes in memory: no worktree scan, no filters.
423        let mut index = self.repo.index().map_err(git_error)?;
424        match &parent {
425            Some(parent) => index.read_tree(&parent.tree().map_err(git_error)?),
426            None => index.clear(),
427        }
428        .map_err(git_error)?;
429        for (relative, change) in &changes {
430            match change {
431                Some(bytes) => index.add_frombuffer(&index_entry(relative), bytes),
432                None if index.get_path(Path::new(relative), 0).is_some() => {
433                    index.remove_path(Path::new(relative))
434                }
435                None => Ok(()),
436            }
437            .map_err(git_error)?;
438        }
439        let tree_id = index.write_tree().map_err(git_error)?;
440
441        if mode == CommitMode::Normal {
442            self.write_worktree(&changes)?;
443        }
444        if merged.is_none()
445            && parent
446                .as_ref()
447                .is_some_and(|parent| parent.tree_id() == tree_id)
448        {
449            return Ok(None);
450        }
451
452        let tree = self.repo.find_tree(tree_id).map_err(git_error)?;
453        let oid = self.commit(machine, &message, &tree, parent.as_ref(), merged)?;
454        index.write().map_err(git_error)?;
455        Ok(Some(CommitId::from_oid(oid)))
456    }
457
458    /// The leak scanner over every staged file and the commit message.
459    fn scan_changes(&self, changes: &Changes, message: &str) -> Result<(), CoreError> {
460        let allow_text = match changes.get(ALLOWLIST_FILE) {
461            Some(Some(bytes)) => Some(String::from_utf8_lossy(bytes).into_owned()),
462            Some(None) => None,
463            None => self.read_to_string(ALLOWLIST_FILE)?,
464        };
465        let allow = Allowlist::parse(allow_text.as_deref().unwrap_or_default());
466        let mut findings = Vec::new();
467        for (relative, change) in changes {
468            if let Some(bytes) = change {
469                let toml = relative.ends_with(".toml");
470                findings.extend(scan_text(relative, bytes, toml, &self.secrets, &allow));
471            }
472        }
473        findings.extend(scan_text(
474            "commit message",
475            message.as_bytes(),
476            false,
477            &self.secrets,
478            &allow,
479        ));
480        match leak_error(&findings) {
481            Some(err) => Err(err),
482            None => Ok(()),
483        }
484    }
485
486    /// Schema validation of every staged store file (SPEC 5); the first
487    /// error aborts. Warnings pass.
488    fn validate_changes(&self, changes: &Changes) -> Result<(), CoreError> {
489        for (relative, change) in changes {
490            let Some(bytes) = change else {
491                continue;
492            };
493            let Some(file) = StoreFile::classify(Path::new(relative)) else {
494                continue;
495            };
496            let path = self.path(relative)?;
497            let text = std::str::from_utf8(bytes).map_err(|_| {
498                CoreError::new(ErrorCode::InvalidValue, "store files must be UTF-8")
499                    .with_path(&path)
500            })?;
501            let shared_id = match &file {
502                StoreFile::Project { id, local: true } => {
503                    self.shared_project_id(changes, &format!("projects/{id}/project.toml"))?
504                }
505                _ => None,
506            };
507            if let Some(err) =
508                validate_store_file(&file, text, shared_id.as_deref()).first_error(Some(&path))
509            {
510                return Err(err);
511            }
512        }
513        Ok(())
514    }
515
516    /// The id in the `project.toml` next to a staged `project.local.toml`.
517    fn shared_project_id(
518        &self,
519        changes: &Changes,
520        relative: &str,
521    ) -> Result<Option<String>, CoreError> {
522        let text = match changes.get(relative) {
523            Some(Some(bytes)) => Some(String::from_utf8_lossy(bytes).into_owned()),
524            Some(None) => None,
525            None => self.read_to_string(relative)?,
526        };
527        let file = StoreFile::Project {
528            id: String::new(),
529            local: false,
530        };
531        Ok(text
532            .and_then(|text| StoreDocument::parse(&file, &text).ok())
533            .and_then(|doc| match doc {
534                StoreDocument::Project(doc) => doc.into_value().id,
535                _ => None,
536            }))
537    }
538
539    pub(crate) fn write_worktree(&self, changes: &Changes) -> Result<(), CoreError> {
540        for (relative, change) in changes {
541            let path = self.path(relative)?;
542            match change {
543                Some(bytes) => {
544                    if let Some(dir) = path.parent() {
545                        self.fs
546                            .create_dir_all(dir)
547                            .map_err(|err| io_error("cannot create directory", dir, &err))?;
548                    }
549                    self.fs
550                        .write(&path, bytes)
551                        .map_err(|err| io_error("cannot write file", &path, &err))?;
552                }
553                None if self.fs.exists(&path) => self
554                    .fs
555                    .remove_file(&path)
556                    .map_err(|err| io_error("cannot remove file", &path, &err))?,
557                None => {}
558            }
559        }
560        Ok(())
561    }
562
563    /// Commits `tree` on HEAD (plus `merged`, for a merge commit) with the
564    /// machine's signature. libgit2 signs the reflog entries of a commit
565    /// with its committer, so no identity from git configuration reaches
566    /// `.git/logs` either.
567    fn commit(
568        &self,
569        machine: &Machine,
570        message: &str,
571        tree: &Tree<'_>,
572        parent: Option<&Commit<'_>>,
573        merged: Option<&Commit<'_>>,
574    ) -> Result<Oid, CoreError> {
575        let signature = machine.signature(self.env.now())?;
576        let parents: Vec<&Commit<'_>> = parent.into_iter().chain(merged).collect();
577        let oid = self
578            .repo
579            .commit(
580                Some("HEAD"),
581                &signature,
582                &signature,
583                message,
584                tree,
585                &parents,
586            )
587            .map_err(git_error)?;
588        let id = oid.to_string();
589        crate::diagnostics::log::event("store.commit", &[("commit", &&id[..id.len().min(7)])]);
590        Ok(oid)
591    }
592}
593
594fn index_entry(relative: &str) -> IndexEntry {
595    IndexEntry {
596        ctime: IndexTime::new(0, 0),
597        mtime: IndexTime::new(0, 0),
598        dev: 0,
599        ino: 0,
600        mode: 0o100_644,
601        uid: 0,
602        gid: 0,
603        file_size: 0,
604        id: Oid::ZERO_SHA1,
605        flags: 0,
606        flags_extended: 0,
607        path: relative.as_bytes().to_vec(),
608    }
609}
610
611/// How [`Store::commit_with`] treats the staged files.
612#[derive(Debug, Clone, Copy, PartialEq, Eq)]
613enum CommitMode {
614    /// Validated, written to the working tree, committed.
615    Normal,
616    /// A schema migration: committed only; validated unless the files are
617    /// past the version this build reads.
618    Migration { validate: bool },
619}