Skip to main content

surjection_core/eject/
record.rs

1//! `state/eject.json`: the record of every eject run on this machine (its
2//! journal, what rollback needs) and the marker that keeps Surjection away from
3//! what was ejected while a run is active.
4
5use std::path::Path;
6
7use serde::{Deserialize, Serialize};
8
9use crate::apply::ledger::LedgerEntry;
10use crate::apply::write_atomic;
11use crate::error::{CoreError, ErrorCode};
12use crate::fs::Fs;
13use crate::skills::link::SkillLink;
14
15/// The record file in `state/`.
16pub const EJECT_FILE: &str = "eject.json";
17pub(crate) const EJECT_SCHEMA: u32 = 1;
18/// Runs kept; the oldest inactive ones go first.
19const KEEP_RUNS: usize = 20;
20
21/// `state/eject.json`.
22#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
23pub struct EjectFile {
24    pub schema: u32,
25    #[serde(default)]
26    pub runs: Vec<EjectRun>,
27    /// Keys a newer build wrote, kept on rewrite.
28    #[serde(flatten)]
29    pub extra: serde_json::Map<String, serde_json::Value>,
30}
31
32impl Default for EjectFile {
33    fn default() -> Self {
34        Self {
35            schema: EJECT_SCHEMA,
36            runs: Vec::new(),
37            extra: serde_json::Map::new(),
38        }
39    }
40}
41
42/// One eject run.
43#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
44pub struct EjectRun {
45    /// A ULID, like apply ids (its backups are `backups/files/<ts>-<id>/`).
46    pub id: String,
47    /// RFC 3339, UTC.
48    pub time: String,
49    /// The clients the run covered; `None` for every client.
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub clients: Option<Vec<String>>,
52    /// The project the run covered; `None` for user files and every project.
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub project_id: Option<String>,
55    /// The run got to its end (a crash leaves it `false`; it still counts as
56    /// active).
57    #[serde(default)]
58    pub finished: bool,
59    /// The user started managing again ([`super::resume`]).
60    #[serde(default)]
61    pub resumed: bool,
62    #[serde(default)]
63    pub rolled_back: bool,
64    /// Client files written, with what was written.
65    #[serde(default)]
66    pub files: Vec<EjectedFile>,
67    /// The ledger rows the run dropped, as they were.
68    #[serde(default)]
69    pub ledger: Vec<LedgerEntry>,
70    /// The skill rows the run dropped, as they were.
71    #[serde(default)]
72    pub skill_links: Vec<SkillLink>,
73    /// Links replaced by copies: the copy's content hash.
74    #[serde(default)]
75    pub copied: Vec<CopiedSkill>,
76    /// Owned copies whose marker file was removed.
77    #[serde(default)]
78    pub unmarked: Vec<String>,
79    #[serde(flatten)]
80    pub extra: serde_json::Map<String, serde_json::Value>,
81}
82
83impl EjectRun {
84    /// Whether the run still keeps Surjection away from what it ejected.
85    pub fn active(&self) -> bool {
86        !self.resumed && !self.rolled_back
87    }
88}
89
90/// A client file an eject run wrote.
91#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
92pub struct EjectedFile {
93    /// Absolute, as on this machine.
94    pub file: String,
95    /// The backup of the content before the run.
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub backup: Option<String>,
98    /// `sha256:<hex>` of the bytes the run wrote.
99    pub written: String,
100}
101
102/// A skill link an eject run replaced by a copy.
103#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
104pub struct CopiedSkill {
105    pub path: String,
106    /// [`crate::skills::content_hash`] of the copy.
107    pub hash: String,
108}
109
110impl EjectFile {
111    /// Reads the record; an absent file is an empty record. A record that
112    /// does not parse is an error (losing it would let Surjection manage what
113    /// the user handed back).
114    pub fn load(fs: &dyn Fs, state_dir: &Path) -> Result<Self, CoreError> {
115        let path = state_dir.join(EJECT_FILE);
116        if !fs.exists(&path) {
117            return Ok(Self::default());
118        }
119        let text = fs.read_to_string(&path).map_err(|err| {
120            CoreError::new(
121                ErrorCode::IoError,
122                format!("cannot read the eject record: {err}"),
123            )
124            .with_path(&path)
125        })?;
126        let file: Self = serde_json::from_str(&text).map_err(|err| {
127            CoreError::new(
128                ErrorCode::ParseError,
129                format!("the eject record does not parse: {err}"),
130            )
131            .with_path(&path)
132        })?;
133        if file.schema != EJECT_SCHEMA {
134            return Err(CoreError::new(
135                ErrorCode::UnsupportedSchema,
136                format!(
137                    "eject record schema {} is not supported; this build reads schema {EJECT_SCHEMA}",
138                    file.schema
139                ),
140            )
141            .with_path(&path));
142        }
143        Ok(file)
144    }
145
146    /// Writes the record atomically, keeping the newest [`KEEP_RUNS`] runs
147    /// (active runs are never dropped).
148    pub fn save(&mut self, fs: &dyn Fs, state_dir: &Path) -> Result<(), CoreError> {
149        while self.runs.len() > KEEP_RUNS {
150            match self.runs.iter().position(|run| !run.active()) {
151                Some(index) => {
152                    self.runs.remove(index);
153                }
154                None => break,
155            }
156        }
157        let mut text = serde_json::to_string_pretty(self).map_err(|err| {
158            CoreError::new(
159                ErrorCode::InvalidValue,
160                format!("cannot serialize the eject record: {err}"),
161            )
162        })?;
163        text.push('\n');
164        fs.create_dir_all(state_dir).map_err(|err| {
165            CoreError::new(
166                ErrorCode::IoError,
167                format!("cannot create directory: {err}"),
168            )
169            .with_path(state_dir)
170        })?;
171        write_atomic(fs, &state_dir.join(EJECT_FILE), text.as_bytes())
172    }
173}
174
175/// What the active eject runs cover.
176#[derive(Debug, Clone, PartialEq, Eq)]
177pub struct Ejected {
178    pub runs: Vec<ActiveRun>,
179}
180
181/// One active run ([`EjectRun::active`]).
182#[derive(Debug, Clone, PartialEq, Eq)]
183pub struct ActiveRun {
184    pub id: String,
185    pub time: String,
186    pub clients: Option<Vec<String>>,
187    pub project_id: Option<String>,
188    /// `false` for a run that stopped partway (roll it back).
189    pub finished: bool,
190}
191
192impl Ejected {
193    /// Whether `client`'s entries in the target of `project_id` (`None` for
194    /// user files) were handed back.
195    pub fn covers(&self, client: &str, project_id: Option<&str>) -> bool {
196        self.runs.iter().any(|run| {
197            run.clients
198                .as_ref()
199                .is_none_or(|clients| clients.iter().any(|id| id == client))
200                && run
201                    .project_id
202                    .as_deref()
203                    .is_none_or(|id| Some(id) == project_id)
204        })
205    }
206
207    /// Whether a run covered everything: this machine is not managed.
208    pub fn all(&self) -> bool {
209        self.runs
210            .iter()
211            .any(|run| run.clients.is_none() && run.project_id.is_none())
212    }
213
214    /// A run that stopped partway, if any: roll it back before ejecting
215    /// again.
216    pub fn unfinished(&self) -> Option<&ActiveRun> {
217        self.runs.iter().find(|run| !run.finished)
218    }
219}
220
221/// The active runs of the record in `state_dir`, `None` when there are
222/// none (or no record).
223pub fn status_at(fs: &dyn Fs, state_dir: &Path) -> Result<Option<Ejected>, CoreError> {
224    if !fs.exists(&state_dir.join(EJECT_FILE)) {
225        return Ok(None);
226    }
227    let runs: Vec<ActiveRun> = EjectFile::load(fs, state_dir)?
228        .runs
229        .into_iter()
230        .filter(EjectRun::active)
231        .map(|run| ActiveRun {
232            id: run.id,
233            time: run.time,
234            clients: run.clients,
235            project_id: run.project_id,
236            finished: run.finished,
237        })
238        .collect();
239    Ok((!runs.is_empty()).then_some(Ejected { runs }))
240}