1use rusqlite::{OptionalExtension, Row, params};
4
5use super::{Ended, EventCursor, EventPage, OperationId, OperationRow, Outcome, Owner, Tx, failed, from_json, from_word, now, to_json, word};
6use crate::Result;
7use crate::error::{Error, ErrorCode};
8use crate::events::{Event, StepState};
9use crate::name::RunName;
10use crate::state::Op;
11
12const OPERATION_COLUMNS: &str =
14 "id, run, op, queued_at, started_at, ended_at, outcome, error_code, cancel_requested, owner_pid, owner_boot, owner_token, resumed_from";
15
16struct RawOperation {
18 id: i64,
19 run: String,
20 op: String,
21 queued_at: String,
22 started_at: Option<String>,
23 ended_at: Option<String>,
24 outcome: Option<String>,
25 code: Option<String>,
26 cancel: bool,
27 pid: u32,
28 boot: String,
29 token: String,
30 resumed_from: Option<i64>,
31}
32
33fn raw_operation(r: &Row<'_>) -> rusqlite::Result<RawOperation> {
34 Ok(RawOperation {
35 id: r.get(0)?,
36 run: r.get(1)?,
37 op: r.get(2)?,
38 queued_at: r.get(3)?,
39 started_at: r.get(4)?,
40 ended_at: r.get(5)?,
41 outcome: r.get(6)?,
42 code: r.get(7)?,
43 cancel: r.get(8)?,
44 pid: r.get(9)?,
45 boot: r.get(10)?,
46 token: r.get(11)?,
47 resumed_from: r.get(12)?,
48 })
49}
50
51fn operation_row(raw: RawOperation) -> Result<OperationRow> {
52 let ended = match (raw.ended_at, raw.outcome) {
53 (Some(at), Some(outcome)) => Some(Ended {
54 at,
55 outcome: from_word("outcome", &outcome)?,
56 code: raw.code.as_deref().map(|c| from_word("error_code", c)).transpose()?,
57 }),
58 _ => None,
59 };
60 Ok(OperationRow {
61 id: OperationId(raw.id),
62 run: RunName::new(&raw.run).map_err(|_| super::corrupt("run name", &raw.run))?,
63 op: from_word("op", &raw.op)?,
64 queued_at: raw.queued_at,
65 started_at: raw.started_at,
66 ended,
67 cancel_requested: raw.cancel,
68 owner: Owner {
69 pid: raw.pid,
70 boot: raw.boot,
71 token: raw.token,
72 },
73 resumed_from: raw.resumed_from.map(OperationId),
74 })
75}
76
77impl Tx<'_> {
78 pub fn queue_operation(&mut self, run: &RunName, op: Op, owner: &Owner) -> Result<OperationRow> {
85 self.tx
86 .execute(
87 "INSERT INTO operations (run, op, queued_at, owner_pid, owner_boot, owner_token) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
88 params![run.as_str(), word(&op), now(), owner.pid, owner.boot, owner.token],
89 )
90 .map_err(failed("written"))?;
91 let id = OperationId(self.tx.last_insert_rowid());
92 self.operation(id)?.ok_or_else(|| super::corrupt("operation", "a row just written"))
93 }
94
95 pub fn start_operation(&mut self, id: OperationId, run: &RunName, owner: &Owner, resumed_from: Option<OperationId>) -> Result<OperationRow> {
103 let changed = self
104 .tx
105 .execute(
106 "UPDATE operations SET started_at = ?3, owner_pid = ?4, owner_boot = ?5, owner_token = ?6, resumed_from = ?7
107 WHERE id = ?1 AND run = ?2 AND started_at IS NULL AND ended_at IS NULL",
108 params![id.0, run.as_str(), now(), owner.pid, owner.boot, owner.token, resumed_from.map(|r| r.0)],
109 )
110 .map_err(failed("written"))?;
111 if changed == 0 {
112 return Err(Error::Store {
113 action: "written",
114 code: ErrorCode::IllegalTransition,
115 reason: format!("operation {id} isn't a queued operation of run `{run}`"),
116 });
117 }
118 self.operation(id)?.ok_or_else(|| super::corrupt("operation", "a row just written"))
119 }
120
121 pub fn begin_operation(&mut self, run: &RunName, op: Op, owner: &Owner, resumed_from: Option<OperationId>) -> Result<OperationRow> {
129 let queued = self.queue_operation(run, op, owner)?;
130 self.start_operation(queued.id, run, owner, resumed_from)
131 }
132
133 pub fn step(&mut self, id: OperationId, step: &str, state: StepState) -> Result<()> {
139 self.tx
140 .execute(
141 "INSERT INTO operation_steps (operation, seq, step, state, at)
142 VALUES (?1, (SELECT COALESCE(MAX(seq), 0) + 1 FROM operation_steps WHERE operation = ?1), ?2, ?3, ?4)",
143 params![id.0, step, word(&state), now()],
144 )
145 .map_err(failed("written"))?;
146 Ok(())
147 }
148
149 pub fn steps(&self, id: OperationId) -> Result<Vec<(String, StepState)>> {
155 let mut stmt = self
156 .tx
157 .prepare("SELECT step, state FROM operation_steps WHERE operation = ?1 ORDER BY seq")
158 .map_err(failed("read"))?;
159 let rows = stmt
160 .query_map([id.0], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))
161 .map_err(failed("read"))?;
162 let mut steps = Vec::new();
163 for row in rows {
164 let (step, state) = row.map_err(failed("read"))?;
165 steps.push((step, from_word("step state", &state)?));
166 }
167 Ok(steps)
168 }
169
170 pub fn end_operation(&mut self, id: OperationId, outcome: Outcome, code: Option<ErrorCode>) -> Result<()> {
178 if outcome != Outcome::Cancelled && self.operation(id)?.is_some_and(|o| o.started_at.is_none() && o.ended.is_none()) {
179 return Err(Error::Store {
180 action: "written",
181 code: ErrorCode::IllegalTransition,
182 reason: format!("operation {id} never started: it can only be cancelled"),
183 });
184 }
185 self.tx
186 .execute(
187 "UPDATE operations SET ended_at = ?2, outcome = ?3, error_code = ?4 WHERE id = ?1 AND ended_at IS NULL",
188 params![id.0, now(), word(&outcome), code.map(|c| word(&c))],
189 )
190 .map_err(failed("written"))?;
191 Ok(())
192 }
193
194 pub fn request_cancel(&mut self, id: OperationId) -> Result<bool> {
200 let changed = self
201 .tx
202 .execute("UPDATE operations SET cancel_requested = 1 WHERE id = ?1 AND ended_at IS NULL", [id.0])
203 .map_err(failed("written"))?;
204 Ok(changed > 0)
205 }
206
207 pub fn operation(&self, id: OperationId) -> Result<Option<OperationRow>> {
213 let sql = format!("SELECT {OPERATION_COLUMNS} FROM operations WHERE id = ?1");
214 let raw = self.tx.query_row(&sql, [id.0], raw_operation).optional().map_err(failed("read"))?;
215 raw.map(operation_row).transpose()
216 }
217
218 pub fn operations(&self, run: &RunName, limit: usize) -> Result<Vec<OperationRow>> {
224 let sql = format!("SELECT {OPERATION_COLUMNS} FROM operations WHERE run = ?1 ORDER BY id DESC LIMIT ?2");
225 self.operations_where(&sql, params![run.as_str(), i64::try_from(limit).unwrap_or(i64::MAX)])
226 }
227
228 pub fn in_flight(&self) -> Result<Vec<OperationRow>> {
236 let sql = format!("SELECT {OPERATION_COLUMNS} FROM operations WHERE ended_at IS NULL ORDER BY id");
237 self.operations_where(&sql, params![])
238 }
239
240 pub fn unfinished(&self, run: &RunName) -> Result<Vec<OperationRow>> {
249 let sql = format!("SELECT {OPERATION_COLUMNS} FROM operations WHERE run = ?1 AND ended_at IS NULL ORDER BY id");
250 self.operations_where(&sql, params![run.as_str()])
251 }
252
253 pub fn cancel_orphaned_queued(&mut self) -> Result<Vec<OperationId>> {
261 let sql = format!("SELECT {OPERATION_COLUMNS} FROM operations WHERE started_at IS NULL AND ended_at IS NULL ORDER BY id");
262 let orphans: Vec<OperationId> = self
263 .operations_where(&sql, params![])?
264 .into_iter()
265 .filter(|o| !o.owner.is_alive())
266 .map(|o| o.id)
267 .collect();
268 for id in &orphans {
269 self.end_operation(*id, Outcome::Cancelled, Some(ErrorCode::Cancelled))?;
270 }
271 Ok(orphans)
272 }
273
274 fn operations_where(&self, sql: &str, params: impl rusqlite::Params) -> Result<Vec<OperationRow>> {
275 let mut stmt = self.tx.prepare(sql).map_err(failed("read"))?;
276 let found = stmt.query_map(params, raw_operation).map_err(failed("read"))?;
277 let mut rows = Vec::new();
278 for raw in found {
279 rows.push(operation_row(raw.map_err(failed("read"))?)?);
280 }
281 Ok(rows)
282 }
283
284 pub fn append_event(&mut self, operation: Option<OperationId>, event: &Event) -> Result<EventCursor> {
290 self.append_raw_event(event.run.as_deref(), operation, &to_json(event)?)
291 }
292
293 pub fn append_raw_event(&mut self, run: Option<&str>, operation: Option<OperationId>, body: &str) -> Result<EventCursor> {
300 self.tx
301 .execute(
302 "INSERT INTO events (run, operation, body) VALUES (?1, ?2, ?3)",
303 params![run, operation.map(|id| id.0), body],
304 )
305 .map_err(failed("written"))?;
306 Ok(EventCursor(u64::try_from(self.tx.last_insert_rowid()).unwrap_or(0)))
307 }
308
309 pub fn events_after(&self, after: EventCursor, run: Option<&RunName>, limit: usize) -> Result<(Vec<(EventCursor, Event)>, usize)> {
316 let page = self.events_page(after, run, limit)?;
317 Ok((page.events, page.unreadable))
318 }
319
320 pub fn events_page(&self, after: EventCursor, run: Option<&RunName>, limit: usize) -> Result<EventPage> {
329 let mut stmt = self
330 .tx
331 .prepare("SELECT cursor, body FROM events WHERE cursor > ?1 AND (?2 IS NULL OR run = ?2) ORDER BY cursor LIMIT ?3")
332 .map_err(failed("read"))?;
333 let rows = stmt
334 .query_map(
335 params![
336 i64::try_from(after.0).unwrap_or(i64::MAX),
337 run.map(RunName::as_str),
338 i64::try_from(limit).unwrap_or(i64::MAX)
339 ],
340 |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)),
341 )
342 .map_err(failed("read"))?;
343 let mut page = EventPage {
344 events: Vec::new(),
345 unreadable: 0,
346 last: after,
347 };
348 for row in rows {
349 let (cursor, body) = row.map_err(failed("read"))?;
350 let cursor = EventCursor(u64::try_from(cursor).unwrap_or(0));
351 page.last = cursor;
352 match from_json::<Event>("event", &body) {
353 Ok(event) => page.events.push((cursor, event)),
354 Err(e) => {
355 tracing::debug!(cursor = cursor.0, error = %e, "an event row isn't an event this runner reads");
356 page.unreadable += 1;
357 }
358 }
359 }
360 Ok(page)
361 }
362
363 pub fn last_cursor(&self) -> Result<EventCursor> {
369 let last: i64 = self
370 .tx
371 .query_row("SELECT COALESCE(MAX(cursor), 0) FROM events", [], |r| r.get(0))
372 .map_err(failed("read"))?;
373 Ok(EventCursor(u64::try_from(last).unwrap_or(0)))
374 }
375
376 pub fn trim_events(&mut self, run: &RunName, keep: usize) -> Result<()> {
382 self.tx
383 .execute(
384 "DELETE FROM events WHERE run = ?1 AND cursor NOT IN (SELECT cursor FROM events WHERE run = ?1 ORDER BY cursor DESC LIMIT ?2)",
385 params![run.as_str(), i64::try_from(keep).unwrap_or(i64::MAX)],
386 )
387 .map_err(failed("written"))?;
388 Ok(())
389 }
390}