Skip to main content

surjection_core/apply/
journal.rs

1//! Apply journals (SPEC 8.4 step 6): `state/journal/<apply-id>.json` grows
2//! by one record per file while a run executes. A finished run moves to
3//! `state/applies/<apply-id>.json` (the last 200 are kept). A journal left
4//! behind by a crash is reported with its per-file outcomes; nothing is
5//! replayed.
6
7use std::path::{Path, PathBuf};
8
9use serde::{Deserialize, Serialize};
10
11use crate::apply::write_atomic;
12use crate::error::{CoreError, ErrorCode};
13use crate::fs::Fs;
14use crate::model::applied::{ApplyOutcome, ApplyTrigger, Scope};
15
16/// Unfinished runs, in `state/`.
17pub const JOURNAL_DIR: &str = "journal";
18/// Finished runs, in `state/`.
19pub const APPLIES_DIR: &str = "applies";
20/// Finished runs kept in [`APPLIES_DIR`].
21const KEEP_APPLIES: usize = 200;
22pub(crate) const JOURNAL_SCHEMA: u32 = 1;
23
24/// One apply run.
25#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
26pub struct Journal {
27    pub schema: u32,
28    pub apply_id: String,
29    pub trigger: ApplyTrigger,
30    /// RFC 3339, UTC.
31    pub started_at: String,
32    pub finished: bool,
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub outcome: Option<ApplyOutcome>,
35    #[serde(default)]
36    pub files: Vec<FileRecord>,
37}
38
39/// What one file got.
40#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
41pub struct FileRecord {
42    pub clients: Vec<String>,
43    pub scope: Scope,
44    /// Absolute path on this machine (the journal is machine-local).
45    pub file: String,
46    pub outcome: ApplyOutcome,
47    pub create: u32,
48    pub update: u32,
49    pub remove: u32,
50    pub disable: u32,
51    /// Whether the file was written.
52    pub written: bool,
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub backup: Option<String>,
55    /// The backup holds a value an import moved to a secret (M35): the old
56    /// value, which the client file no longer holds.
57    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
58    pub old_values: bool,
59    /// The backup was removed on request because it held old secret values
60    /// (M35): the file's content from before this run is no longer kept.
61    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
62    pub backup_removed: bool,
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub error: Option<RecordedError>,
65}
66
67/// An error code and its message.
68#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
69pub struct RecordedError {
70    pub code: String,
71    pub message: String,
72}
73
74impl From<&CoreError> for RecordedError {
75    fn from(err: &CoreError) -> Self {
76        Self {
77            code: err.code().as_str().to_owned(),
78            message: err.to_string(),
79        }
80    }
81}
82
83impl Journal {
84    /// Starts the journal of a run and writes it.
85    pub fn start(
86        fs: &dyn Fs,
87        state_dir: &Path,
88        apply_id: &str,
89        trigger: ApplyTrigger,
90        started_at: String,
91    ) -> Result<Self, CoreError> {
92        let journal = Self {
93            schema: JOURNAL_SCHEMA,
94            apply_id: apply_id.to_owned(),
95            trigger,
96            started_at,
97            finished: false,
98            outcome: None,
99            files: Vec::new(),
100        };
101        journal.save(fs, &journal_path(state_dir, apply_id))?;
102        Ok(journal)
103    }
104
105    /// Appends a file's outcome and rewrites the journal.
106    pub fn record(
107        &mut self,
108        fs: &dyn Fs,
109        state_dir: &Path,
110        file: FileRecord,
111    ) -> Result<(), CoreError> {
112        self.files.push(file);
113        self.save(fs, &journal_path(state_dir, &self.apply_id))
114    }
115
116    /// Marks the run finished: writes `applies/<apply-id>.json`, deletes
117    /// the journal and keeps the last 200 results.
118    pub fn finish(
119        mut self,
120        fs: &dyn Fs,
121        state_dir: &Path,
122        outcome: ApplyOutcome,
123    ) -> Result<Self, CoreError> {
124        self.finished = true;
125        self.outcome = Some(outcome);
126        self.save(fs, &result_path(state_dir, &self.apply_id))?;
127        let journal = journal_path(state_dir, &self.apply_id);
128        if fs.exists(&journal) {
129            fs.remove_file(&journal)
130                .map_err(|err| io("cannot remove journal", &journal, &err))?;
131        }
132        prune(fs, &state_dir.join(APPLIES_DIR))?;
133        Ok(self)
134    }
135
136    /// Rewrites the result of a finished run (`applies/<apply-id>.json`)
137    /// after its file records changed (M35).
138    pub fn save_result(&self, fs: &dyn Fs, state_dir: &Path) -> Result<(), CoreError> {
139        self.save(fs, &result_path(state_dir, &self.apply_id))
140    }
141
142    fn save(&self, fs: &dyn Fs, path: &Path) -> Result<(), CoreError> {
143        let mut text = serde_json::to_string_pretty(self).map_err(|err| {
144            CoreError::new(
145                ErrorCode::InvalidValue,
146                format!("cannot serialize journal: {err}"),
147            )
148        })?;
149        text.push('\n');
150        write_atomic(fs, path, text.as_bytes())
151    }
152}
153
154/// Journals of runs that never finished, oldest first.
155pub fn unfinished(fs: &dyn Fs, state_dir: &Path) -> Result<Vec<Journal>, CoreError> {
156    read_all(fs, &state_dir.join(JOURNAL_DIR))
157}
158
159/// The result of a finished run, if it is still kept. An id that is not a
160/// ULID's letters and digits names no run.
161pub fn result(fs: &dyn Fs, state_dir: &Path, apply_id: &str) -> Result<Option<Journal>, CoreError> {
162    if apply_id.is_empty() || !apply_id.chars().all(|c| c.is_ascii_alphanumeric()) {
163        return Ok(None);
164    }
165    let path = result_path(state_dir, apply_id);
166    if !fs.exists(&path) {
167        return Ok(None);
168    }
169    read(fs, &path).map(Some)
170}
171
172fn journal_path(state_dir: &Path, apply_id: &str) -> PathBuf {
173    state_dir.join(JOURNAL_DIR).join(format!("{apply_id}.json"))
174}
175
176fn result_path(state_dir: &Path, apply_id: &str) -> PathBuf {
177    state_dir.join(APPLIES_DIR).join(format!("{apply_id}.json"))
178}
179
180fn read_all(fs: &dyn Fs, dir: &Path) -> Result<Vec<Journal>, CoreError> {
181    if !fs.is_dir(dir) {
182        return Ok(Vec::new());
183    }
184    let paths = fs
185        .read_dir(dir)
186        .map_err(|err| io("cannot list journals", dir, &err))?;
187    paths
188        .iter()
189        .filter(|path| path.extension().is_some_and(|ext| ext == "json"))
190        .map(|path| read(fs, path))
191        .collect()
192}
193
194fn read(fs: &dyn Fs, path: &Path) -> Result<Journal, CoreError> {
195    let text = fs
196        .read_to_string(path)
197        .map_err(|err| io("cannot read journal", path, &err))?;
198    serde_json::from_str(&text).map_err(|err| {
199        CoreError::new(
200            ErrorCode::ParseError,
201            format!("journal does not parse: {err}"),
202        )
203        .with_path(path)
204    })
205}
206
207/// Keeps the newest [`KEEP_APPLIES`] results (apply ids are ULIDs, so the
208/// name order is the time order).
209fn prune(fs: &dyn Fs, dir: &Path) -> Result<(), CoreError> {
210    let paths: Vec<PathBuf> = fs
211        .read_dir(dir)
212        .map_err(|err| io("cannot list apply results", dir, &err))?
213        .into_iter()
214        .filter(|path| path.extension().is_some_and(|ext| ext == "json"))
215        .collect();
216    let excess = paths.len().saturating_sub(KEEP_APPLIES);
217    for path in paths.iter().take(excess) {
218        fs.remove_file(path)
219            .map_err(|err| io("cannot prune apply results", path, &err))?;
220    }
221    Ok(())
222}
223
224fn io(what: &str, path: &Path, err: &std::io::Error) -> CoreError {
225    CoreError::new(ErrorCode::IoError, format!("{what}: {err}")).with_path(path)
226}