1use serde::{Deserialize, Serialize};
4use sha2::{Digest, Sha256};
5
6use super::row::Row;
7use super::{StateError, Store};
8
9const RETIRABLE: &str = "input_retired = 0
10 AND status NOT IN ('queued', 'running') AND updated_at <= ?1
11 AND NOT EXISTS (SELECT 1 FROM operations pending WHERE pending.instance = operations.instance AND pending.status IN ('queued', 'running'))
12 AND NOT EXISTS (SELECT 1 FROM instances live WHERE live.instance_id = operations.instance_id OR (operations.instance_id IS NULL AND live.name = operations.instance))
13 AND NOT EXISTS (SELECT 1 FROM resources r WHERE r.owner_id = operations.instance_id AND r.phase != 'absent')";
14
15const JOURNALED_VERIFY: &str = "verb = 'verify' AND EXISTS (SELECT 1 FROM operation_events e
16 WHERE e.operation_id = operations.id AND json_extract(e.event_json, '$.event') = 'VerificationJournal'
17 AND json_extract(e.event_json, '$.version') = 1)";
18
19fn request_digest(request: &serde_json::Value) -> String {
20 format!("{:x}", Sha256::digest(request.to_string().as_bytes()))
21}
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "snake_case")]
25pub enum OperationStatus {
26 Queued,
27 Running,
28 Succeeded,
29 Failed,
30 Cancelled,
31 Interrupted,
32}
33
34impl OperationStatus {
35 pub fn terminal(self) -> bool {
36 !matches!(self, Self::Queued | Self::Running)
37 }
38
39 fn as_str(self) -> &'static str {
40 match self {
41 Self::Queued => "queued",
42 Self::Running => "running",
43 Self::Succeeded => "succeeded",
44 Self::Failed => "failed",
45 Self::Cancelled => "cancelled",
46 Self::Interrupted => "interrupted",
47 }
48 }
49}
50
51#[derive(Debug, Clone, Serialize, Deserialize)]
52pub struct Operation {
53 pub instance_id: Option<String>,
54 pub output_version: i64,
55 pub id: String,
56 pub instance: String,
57 pub verb: String,
58 pub status: OperationStatus,
59 pub result: Option<serde_json::Value>,
60 pub error: Option<serde_json::Value>,
61 pub cancel_requested: bool,
62 pub created_at: i64,
63 pub updated_at: i64,
64}
65
66#[derive(Debug, Clone, Serialize, Deserialize)]
67pub struct OperationEvent {
68 pub sequence: i64,
69 pub event: serde_json::Value,
70}
71
72fn json(text: &str) -> Result<serde_json::Value, StateError> {
73 serde_json::from_str(text).map_err(|err| StateError::ResourceInvariant {
74 detail: format!("invalid operation JSON: {err}"),
75 })
76}
77
78impl Operation {
79 fn from_row(row: &Row) -> Result<Self, StateError> {
80 let status = match row.get_string(3)?.as_str() {
81 "queued" => OperationStatus::Queued,
82 "running" => OperationStatus::Running,
83 "succeeded" => OperationStatus::Succeeded,
84 "failed" => OperationStatus::Failed,
85 "cancelled" => OperationStatus::Cancelled,
86 "interrupted" => OperationStatus::Interrupted,
87 other => {
88 return Err(StateError::ResourceInvariant {
89 detail: format!("invalid operation status {other:?}"),
90 });
91 }
92 };
93 let result = json(&row.get_string(4)?)?;
94 let error = json(&row.get_string(5)?)?;
95 Ok(Self {
96 instance_id: row.get_opt_string(9)?,
97 output_version: row.get_i64(10)?,
98 id: row.get_string(0)?,
99 instance: row.get_string(1)?,
100 verb: row.get_string(2)?,
101 status,
102 result: (!result.is_null()).then_some(result),
103 error: (!error.is_null()).then_some(error),
104 cancel_requested: row.get_i64(6)? != 0,
105 created_at: row.get_i64(7)?,
106 updated_at: row.get_i64(8)?,
107 })
108 }
109}
110
111impl Store {
112 pub fn submit_operation(
114 &self,
115 id: &str,
116 instance: &str,
117 verb: &str,
118 request: &serde_json::Value,
119 ) -> Result<Operation, StateError> {
120 let request_json = request.to_string();
121 self.execute("INSERT INTO operations(id, instance, verb, status, request_json, created_at, updated_at, request_digest)
122 VALUES (?1, ?2, ?3, 'queued', ?4, ?5, ?5, ?6) ON CONFLICT(id) DO NOTHING",
123 &[id.into(), instance.into(), verb.into(), request_json.as_str().into(), Self::now().into(), request_digest(request).into()])?;
124 let operation = self
125 .operation(id)?
126 .ok_or_else(|| StateError::ResourceInvariant {
127 detail: "accepted operation missing".into(),
128 })?;
129 if !self.operation_request_matches(id, request)?
130 || operation.verb != verb
131 || operation.instance != instance
132 {
133 return Err(StateError::ResourceInvariant {
134 detail: format!("operation ID {id:?} was already used for a different request"),
135 });
136 }
137 Ok(operation)
138 }
139
140 pub fn operation(&self, id: &str) -> Result<Option<Operation>, StateError> {
141 self.query_row("SELECT id, instance, verb, status, COALESCE(result_json, 'null'),
142 COALESCE(error_json, 'null'), cancel_requested, created_at, updated_at, instance_id, output_version FROM operations WHERE id = ?1",
143 &[id.into()], Operation::from_row)
144 }
145
146 pub fn operation_request(&self, id: &str) -> Result<serde_json::Value, StateError> {
148 self.query_row(
149 "SELECT request_json FROM operations WHERE id = ?1 AND input_retired = 0",
150 &[id.into()],
151 |row| json(&row.get_string(0)?),
152 )?
153 .ok_or_else(|| StateError::ResourceInvariant {
154 detail: format!("operation {id:?} is unknown or its execution input has expired"),
155 })
156 }
157
158 pub fn operation_request_matches(
160 &self,
161 id: &str,
162 request: &serde_json::Value,
163 ) -> Result<bool, StateError> {
164 Ok(self
165 .query_row(
166 "SELECT request_digest, request_json, input_retired FROM operations WHERE id = ?1",
167 &[id.into()],
168 |row| {
169 if let Some(digest) = row.get_opt_string(0)? {
170 Ok(digest == request_digest(request))
171 } else {
172 Ok(row.get_i64(2)? == 0 && json(&row.get_string(1)?)? == *request)
173 }
174 },
175 )?
176 .unwrap_or(false))
177 }
178
179 pub fn expired_operation_inputs(&self) -> Result<Vec<String>, StateError> {
182 self.query_map(
183 &format!(
184 "SELECT id FROM operations WHERE {RETIRABLE} ORDER BY updated_at, id LIMIT 100"
185 ),
186 &[(Self::now() - super::TOMBSTONE_GC_WINDOW.as_secs() as i64).into()],
187 |row| row.get_string(0),
188 )
189 }
190
191 pub fn retire_operation_input(&self, id: &str) -> Result<bool, StateError> {
194 let request = self.operation_request(id)?;
195 Ok(self.execute(&format!("UPDATE operations SET request_digest = ?3, request_json = 'null', input_retired = 1 WHERE id = ?2 AND {RETIRABLE}"),
196 &[(Self::now() - super::TOMBSTONE_GC_WINDOW.as_secs() as i64).into(), id.into(), request_digest(&request).into()])? == 1)
197 }
198
199 pub fn pending_operations(&self) -> Result<Vec<Operation>, StateError> {
200 self.query_map(
201 "SELECT id, instance, verb, status, COALESCE(result_json, 'null'),
202 COALESCE(error_json, 'null'), cancel_requested, created_at, updated_at, instance_id, output_version FROM operations
203 WHERE status IN ('queued', 'running') ORDER BY created_at, rowid",
204 &[],
205 Operation::from_row,
206 )
207 }
208
209 pub fn operations(&self, instance: Option<&str>) -> Result<Vec<Operation>, StateError> {
210 self.query_map(
211 "SELECT id, instance, verb, status, COALESCE(result_json, 'null'),
212 COALESCE(error_json, 'null'), cancel_requested, created_at, updated_at, instance_id, output_version FROM operations
213 WHERE (?1 IS NULL OR instance = ?1) ORDER BY created_at DESC, rowid DESC LIMIT 100",
214 &[instance.map_or(super::value::Value::Null, Into::into)],
215 Operation::from_row,
216 )
217 }
218
219 pub fn running_operation_id(&self, instance: &str) -> Result<Option<String>, StateError> {
220 self.query_row(
221 "SELECT id FROM operations WHERE instance = ?1 AND status = 'running'",
222 &[instance.into()],
223 |row| row.get_string(0),
224 )
225 }
226
227 pub fn start_operation(&self, id: &str) -> Result<bool, StateError> {
229 Ok(self.execute(&format!("UPDATE operations SET status = 'running', updated_at = ?2
230 WHERE id = ?1 AND status = 'queued' AND (cancel_requested = 0 OR ({JOURNALED_VERIFY}))
231 AND NOT EXISTS (SELECT 1 FROM operations active WHERE active.instance = operations.instance AND active.status = 'running')"), &[id.into(), Self::now().into()])? == 1)
232 }
233
234 pub fn mark_verification_journal(&self, id: &str) -> Result<(), StateError> {
236 let operation = self
237 .operation(id)?
238 .ok_or_else(|| StateError::ResourceInvariant {
239 detail: "verification operation disappeared".into(),
240 })?;
241 if operation.verb != "verify" || operation.status != OperationStatus::Running {
242 return Err(StateError::ResourceInvariant {
243 detail: "verification operation is not running".into(),
244 });
245 }
246 self.execute(
247 &format!(
248 "INSERT INTO operation_events(operation_id, event_json, recorded_at)
249 SELECT id, '{{\"event\":\"VerificationJournal\",\"version\":1}}', ?2 FROM operations
250 WHERE id = ?1 AND NOT ({JOURNALED_VERIFY})"
251 ),
252 &[id.into(), Self::now().into()],
253 )?;
254 Ok(())
255 }
256
257 pub fn recover_operations(&self) -> Result<(), StateError> {
259 self.execute(&format!("UPDATE operations SET status = CASE WHEN ({JOURNALED_VERIFY}) THEN 'queued'
260 WHEN cancel_requested = 1 THEN 'cancelled' WHEN verb IN ('up', 'down', 'gc') THEN 'queued' ELSE 'interrupted' END,
261 updated_at = ?1 WHERE status = 'running'"), &[Self::now().into()])?;
262 Ok(())
263 }
264
265 pub fn cancel_operation(&self, id: &str) -> Result<bool, StateError> {
266 Ok(self.execute(
267 &format!("UPDATE operations SET cancel_requested = 1,
268 status = CASE WHEN status = 'queued' AND NOT ({JOURNALED_VERIFY}) THEN 'cancelled' ELSE status END, updated_at = ?2
269 WHERE id = ?1 AND (status = 'queued' OR (status = 'running' AND (verb = 'up' OR ({JOURNALED_VERIFY}))))"),
270 &[id.into(), Self::now().into()],
271 )? == 1)
272 }
273
274 pub fn finish_operation(
275 &self,
276 id: &str,
277 status: OperationStatus,
278 result: Option<&serde_json::Value>,
279 error: Option<&serde_json::Value>,
280 ) -> Result<(), StateError> {
281 if !status.terminal() {
282 return Err(StateError::ResourceInvariant {
283 detail: "finish requires terminal operation status".into(),
284 });
285 }
286 let changed = self.execute(
287 "UPDATE operations SET status = ?2, result_json = ?3, error_json = ?4, updated_at = ?5, output_version = 1
288 WHERE id = ?1 AND status = 'running'",
289 &[
290 id.into(),
291 status.as_str().into(),
292 result.map_or(super::value::Value::Null, |v| v.to_string().into()),
293 error.map_or(super::value::Value::Null, |v| v.to_string().into()),
294 Self::now().into(),
295 ],
296 )?;
297 if changed != 1 {
298 return Err(StateError::ResourceInvariant {
299 detail: format!("operation {id:?} is not running"),
300 });
301 }
302 Ok(())
303 }
304
305 pub fn operation_event(&self, id: &str, event: &serde_json::Value) -> Result<(), StateError> {
306 self.execute("INSERT INTO operation_events(operation_id, event_json, recorded_at) VALUES (?1, ?2, ?3)",
307 &[id.into(), event.to_string().into(), Self::now().into()])?;
308 Ok(())
309 }
310
311 pub fn operation_events(
312 &self,
313 id: &str,
314 after: i64,
315 ) -> Result<Vec<OperationEvent>, StateError> {
316 self.query_map("SELECT sequence, event_json FROM operation_events WHERE operation_id = ?1 AND sequence > ?2 ORDER BY sequence LIMIT 256",
317 &[id.into(), after.into()], |row| Ok(OperationEvent { sequence: row.get_i64(0)?, event: json(&row.get_string(1)?)? }))
318 }
319}
320
321pub fn new_operation_id() -> String {
322 uuid::Uuid::new_v4().to_string()
323}