Skip to main content

isothrum_runner/store/db/
journal.rs

1//! The journal (each operation: started, its steps, ended) and the event table.
2
3use 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
12/// The columns an [`OperationRow`] is read from, in [`operation_row`]'s order.
13const 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
16/// The text columns of an operation's row, before they are parsed.
17struct 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    /// Journals operation `op` on `run` as queued by `owner` (a service answering a command): its
79    /// id is the one every later event and the client see; [`Tx::start_operation`] starts it.
80    ///
81    /// # Errors
82    ///
83    /// The store can't be written.
84    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    /// Starts queued operation `id` of `run`, owned now by `owner`, recovering `resumed_from` when
96    /// it found that one unfinished.
97    ///
98    /// # Errors
99    ///
100    /// `illegal_transition` when `id` isn't a queued operation of `run` (started or ended
101    /// already, another run's, or none); the store's.
102    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    /// Journals operation `op` on `run` as queued and started at once by `owner` (the command
122    /// line, an embedder with no service), recovering `resumed_from` when it found that one
123    /// unfinished.
124    ///
125    /// # Errors
126    ///
127    /// The store can't be written.
128    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    /// Journals that step `step` of operation `id` reached `state`.
134    ///
135    /// # Errors
136    ///
137    /// The store can't be written.
138    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    /// Operation `id`'s journaled steps, in order: each step and where it reached.
150    ///
151    /// # Errors
152    ///
153    /// The store can't be read.
154    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    /// Journals how operation `id` ended. An operation already ended keeps its first end. A
171    /// queued one that never started can only be `cancelled`: it never ran.
172    ///
173    /// # Errors
174    ///
175    /// `illegal_transition` when a queued operation is ended otherwise than cancelled; the
176    /// store's.
177    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    /// Asks operation `id` to stop: false when it already ended.
195    ///
196    /// # Errors
197    ///
198    /// The store can't be written.
199    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    /// Operation `id`.
208    ///
209    /// # Errors
210    ///
211    /// The store can't be read, or the row holds what this runner doesn't write.
212    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    /// Run `run`'s last `limit` operations, newest first.
219    ///
220    /// # Errors
221    ///
222    /// As [`Tx::operation`].
223    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    /// The home's operations that never ended, every run's, queued or started, oldest first:
229    /// those still in their owner's queue or running while it lives, else left by a process that
230    /// died.
231    ///
232    /// # Errors
233    ///
234    /// As [`Tx::operation`].
235    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    /// Run `run`'s operations that never ended, queued or started, oldest first. Called with the
241    /// run held (its lock, or its lease), so none of the started ones runs: each is one whose
242    /// process died, or whose future was dropped before it could say how it ended. A queued one
243    /// still waits in its owner's queue while that owner lives.
244    ///
245    /// # Errors
246    ///
247    /// As [`Tx::operation`].
248    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    /// Ends `cancelled` every queued operation of the home (any run) that never started and whose
254    /// owner is gone (another boot, a dead process): a service that died with operations in its
255    /// queue. Returns their ids. A live owner's queued rows stay: they wait in its queue.
256    ///
257    /// # Errors
258    ///
259    /// The store can't be read or written.
260    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    /// Appends `event` (of operation `operation`, if any) to the event table: its cursor.
285    ///
286    /// # Errors
287    ///
288    /// The store can't be written.
289    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    /// Appends an event already written as JSON, as written (another version's kind): it is read
294    /// back as an event when this runner reads it, else counted unreadable.
295    ///
296    /// # Errors
297    ///
298    /// The store can't be written.
299    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    /// Up to `limit` events after cursor `after`, of run `run` or of every run, oldest first,
310    /// with how many rows it couldn't read as an event (another version's kind).
311    ///
312    /// # Errors
313    ///
314    /// The store can't be read.
315    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    /// Up to `limit` event rows after cursor `after`, of run `run` or of every run, oldest first:
321    /// the events it reads, how many rows it couldn't read as one, and the cursor of the last row
322    /// it scanned, read or not (`after` when there was none). A reader resumes from `last`: a
323    /// page of rows another version wrote, none of them readable, still moves it on.
324    ///
325    /// # Errors
326    ///
327    /// The store can't be read.
328    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    /// The newest event's cursor (0 when there is none).
364    ///
365    /// # Errors
366    ///
367    /// The store can't be read.
368    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    /// Keeps run `run`'s newest `keep` events.
377    ///
378    /// # Errors
379    ///
380    /// The store can't be written.
381    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}