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