1use crate::{Store, StoreError, now_ms};
4use rusqlite::params;
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7use std::path::PathBuf;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
12#[serde(rename_all = "snake_case")]
13pub enum OperationKind {
14 Apply,
16 Undo,
18}
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
22#[serde(rename_all = "snake_case")]
23pub enum OperationState {
24 Applying,
26 Applied,
28 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
44pub struct FileWrite {
45 pub path: PathBuf,
47 pub before_hash: Option<String>,
49 pub after_hash: Option<String>,
51 #[serde(default)]
53 pub merged: bool,
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
58pub struct ConflictRegion {
59 pub start: usize,
61 pub end: usize,
63}
64
65#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
69pub struct MergeConflict {
70 pub path: PathBuf,
72 pub base: String,
74 pub planned: String,
76 pub current: String,
78 pub current_fingerprint: String,
80 pub regions: Vec<ConflictRegion>,
82}
83
84#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
86pub struct Restores {
87 pub since: String,
89 pub operations: Vec<String>,
91}
92
93#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
95pub struct Operation {
96 pub id: String,
98 pub kind: OperationKind,
100 pub plan: Option<String>,
102 pub undoes: Option<String>,
104 pub state: OperationState,
106 pub purpose: String,
108 pub files: Vec<FileWrite>,
110 pub conflicts: Vec<PathBuf>,
112 pub reason: Option<String>,
114 #[serde(default)]
116 pub recovered: bool,
117 #[serde(default)]
119 pub absorbed: Vec<PathBuf>,
120 #[serde(default)]
122 pub absorb_purpose: Option<String>,
123 #[serde(default)]
125 pub merge_conflicts: Vec<MergeConflict>,
126 #[serde(default)]
128 pub restores: Option<Restores>,
129 pub created_at: i64,
131}
132
133impl Operation {
134 #[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 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 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 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 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 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 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}