Skip to main content

griz_store/
journal.rs

1//! Operations: every apply and undo, recorded before and after it writes.
2
3use crate::{Store, StoreError, now_ms};
4use rusqlite::params;
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7use std::path::PathBuf;
8
9/// What an operation did.
10/// What an operation did.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
12#[serde(rename_all = "snake_case")]
13pub enum OperationKind {
14    /// Wrote a plan.
15    Apply,
16    /// Restored the files of an earlier operation.
17    Undo,
18}
19
20/// Where an operation is in its life.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
22#[serde(rename_all = "snake_case")]
23pub enum OperationState {
24    /// Journaled; renames may be partly done. Recovery finishes it.
25    Applying,
26    /// Every file write is done.
27    Applied,
28    /// Refused before writing anything.
29    Failed,
30}
31
32impl OperationState {
33    fn as_str(self) -> &'static str {
34        match self {
35            Self::Applying => "applying",
36            Self::Applied => "applied",
37            Self::Failed => "failed",
38        }
39    }
40}
41
42/// One file an operation writes.
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
44pub struct FileWrite {
45    /// File path.
46    pub path: PathBuf,
47    /// Fingerprint on disk just before the write; absent when the file did not exist.
48    pub before_hash: Option<String>,
49    /// Fingerprint written; absent when the write deletes the file.
50    pub after_hash: Option<String>,
51    /// Written through a three-way merge onto a file that had moved on.
52    #[serde(default)]
53    pub merged: bool,
54}
55
56/// A conflicting line range in `current`, 1-based and inclusive.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
58pub struct ConflictRegion {
59    /// First conflicting line.
60    pub start: usize,
61    /// Last conflicting line.
62    pub end: usize,
63}
64
65/// One file a merge attempt could not resolve, carrying every text a caller
66/// needs to look at: `base`, `planned`, and `current` are blob identifiers
67/// readable with `get`.
68#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
69pub struct MergeConflict {
70    /// File path.
71    pub path: PathBuf,
72    /// Blob identifier of the text the plan was computed against.
73    pub base: String,
74    /// Blob identifier of the text the plan wanted to write.
75    pub planned: String,
76    /// Blob identifier of the text found on disk.
77    pub current: String,
78    /// Fingerprint of the text found on disk, in the form other commands use.
79    pub current_fingerprint: String,
80    /// Conflicting line ranges in the current text.
81    pub regions: Vec<ConflictRegion>,
82}
83
84/// The span an undo restored in one operation.
85#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
86pub struct Restores {
87    /// Oldest operation restored, inclusive.
88    pub since: String,
89    /// Every operation the restore absorbed, oldest first.
90    pub operations: Vec<String>,
91}
92
93/// One apply or undo.
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
95pub struct Operation {
96    /// Identifier.
97    pub id: String,
98    /// Apply or undo.
99    pub kind: OperationKind,
100    /// Plan applied, for an apply.
101    pub plan: Option<String>,
102    /// Operation restored, for an undo.
103    pub undoes: Option<String>,
104    /// Life-cycle state.
105    pub state: OperationState,
106    /// Why the caller asked for it.
107    pub purpose: String,
108    /// Every file written, in write order.
109    pub files: Vec<FileWrite>,
110    /// Files left alone because they no longer matched what was expected.
111    pub conflicts: Vec<PathBuf>,
112    /// Why the operation failed, when it did.
113    pub reason: Option<String>,
114    /// Finished by recovery after an interruption.
115    #[serde(default)]
116    pub recovered: bool,
117    /// Files whose later changes, such as a formatter's, were absorbed.
118    #[serde(default)]
119    pub absorbed: Vec<PathBuf>,
120    /// Why the latest absorb happened.
121    #[serde(default)]
122    pub absorb_purpose: Option<String>,
123    /// Files whose merge attempt conflicted; each also appears in `conflicts`.
124    #[serde(default)]
125    pub merge_conflicts: Vec<MergeConflict>,
126    /// The span this operation restored, when it is a `since` restore.
127    #[serde(default)]
128    pub restores: Option<Restores>,
129    /// Creation time in Unix milliseconds.
130    pub created_at: i64,
131}
132
133impl Operation {
134    /// A new operation with no files yet.
135    #[must_use]
136    pub fn new(kind: OperationKind, purpose: &str) -> Self {
137        Self {
138            id: crate::new_id("op"),
139            kind,
140            plan: None,
141            undoes: None,
142            state: OperationState::Applying,
143            purpose: purpose.to_string(),
144            files: Vec::new(),
145            conflicts: Vec::new(),
146            reason: None,
147            recovered: false,
148            absorbed: Vec::new(),
149            absorb_purpose: None,
150            merge_conflicts: Vec::new(),
151            restores: None,
152            created_at: now_ms(),
153        }
154    }
155}
156
157impl Store {
158    /// Inserts or replaces an operation record.
159    ///
160    /// # Errors
161    /// Returns an error when the record cannot be written.
162    pub fn save_operation(&self, op: &Operation) -> Result<(), StoreError> {
163        let body = serde_json::to_string(op)?;
164        self.with(|conn| {
165            conn.execute(
166                "INSERT INTO operations (id, created_at, state, body) VALUES (?1, ?2, ?3, ?4)
167                 ON CONFLICT(id) DO UPDATE SET state = excluded.state, body = excluded.body",
168                params![op.id, op.created_at, op.state.as_str(), body],
169            )?;
170            Ok(())
171        })
172    }
173
174    /// Reads one operation.
175    ///
176    /// # Errors
177    /// Returns `NotFound` when no operation has this identifier.
178    pub fn operation(&self, id: &str) -> Result<Operation, StoreError> {
179        let sql = "SELECT body FROM operations WHERE id = ?1";
180        let body = self.with(|conn| crate::body_by_id(conn, sql, id))?;
181        let body = body.ok_or_else(|| StoreError::NotFound(format!("operation {id}")))?;
182        Ok(serde_json::from_str(&body)?)
183    }
184
185    /// Operations in reverse journal order, starting before `before` when given.
186    ///
187    /// # Errors
188    /// Returns an error when the records cannot be read.
189    pub fn operations(
190        &self,
191        limit: usize,
192        before: Option<&str>,
193    ) -> Result<Vec<Operation>, StoreError> {
194        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
195        let bodies = self.with(|conn| match before {
196            Some(before) => crate::bodies(
197                conn,
198                "SELECT body FROM operations WHERE sequence < (SELECT sequence FROM operations WHERE id = ?1) ORDER BY sequence DESC LIMIT ?2",
199                params![before, limit],
200            ),
201            None => crate::bodies(
202                conn,
203                "SELECT body FROM operations ORDER BY sequence DESC LIMIT ?1",
204                params![limit],
205            ),
206        })?;
207        bodies
208            .iter()
209            .map(|body| Ok(serde_json::from_str(body)?))
210            .collect()
211    }
212
213    /// Operations left `applying` by an interrupted process.
214    ///
215    /// # Errors
216    /// Returns an error when the records cannot be read.
217    pub fn unfinished_operations(&self) -> Result<Vec<Operation>, StoreError> {
218        let bodies = self.with(|conn| {
219            crate::bodies(
220                conn,
221                "SELECT body FROM operations WHERE state = 'applying' ORDER BY sequence",
222                [],
223            )
224        })?;
225        bodies
226            .iter()
227            .map(|body| Ok(serde_json::from_str(body)?))
228            .collect()
229    }
230
231    /// Reloads exactly the selected records in their original order.
232    pub(crate) fn reload_operations(
233        &self,
234        selected: &[String],
235    ) -> Result<Vec<Operation>, StoreError> {
236        let ids = serde_json::to_string(selected)?;
237        let bodies = self.with(|conn| {
238            crate::bodies(
239                conn,
240                "SELECT operations.body FROM json_each(?1) AS selected
241                 JOIN operations ON operations.id = selected.value ORDER BY selected.key",
242                params![ids],
243            )
244        })?;
245        if bodies.len() != selected.len() {
246            return Err(StoreError::NotFound(
247                "an operation from the selected restore span".into(),
248            ));
249        }
250        bodies
251            .iter()
252            .map(|body| Ok(serde_json::from_str(body)?))
253            .collect()
254    }
255
256    /// Applied operations from `since` through the newest, oldest first, for
257    /// `restore_since` to fold into one span.
258    ///
259    /// # Errors
260    /// Returns an error when the records cannot be read.
261    pub fn operations_since(&self, since: &str) -> Result<Vec<Operation>, StoreError> {
262        let bodies = self.with(|conn| {
263            crate::bodies(
264                conn,
265                "SELECT body FROM operations WHERE sequence >= (SELECT sequence FROM operations WHERE id = ?1) AND state = 'applied' ORDER BY sequence ASC",
266                params![since],
267            )
268        })?;
269        bodies
270            .iter()
271            .map(|body| Ok(serde_json::from_str(body)?))
272            .collect()
273    }
274}