Skip to main content

isothrum_runner/store/db/
runs.rs

1//! The runs: what the user wants of each, where each stands, and every move it made.
2
3use rusqlite::{OptionalExtension, Row, params};
4
5use super::{OperationId, RunRow, Tx, failed, from_json, from_word, now, to_json, word};
6use crate::Result;
7use crate::error::Error;
8use crate::name::RunName;
9use crate::state::{Desired, RunState, Transition};
10use crate::store::{LastObserved, RunRecord};
11
12/// The columns a [`RunRow`] is read from, in [`run_row`]'s order.
13const RUN_COLUMNS: &str = "name, project_path, source_digest, desired, state, failed_cause, state_op, state_at, record, observed, observed_at";
14
15/// The text columns of a run's row, before they are parsed.
16struct RawRun {
17    name: String,
18    project: String,
19    digest: String,
20    desired: String,
21    state: String,
22    failed_cause: Option<String>,
23    state_op: Option<i64>,
24    state_at: String,
25    record: String,
26    observed: Option<String>,
27    observed_at: Option<String>,
28}
29
30fn raw_run(r: &Row<'_>) -> rusqlite::Result<RawRun> {
31    Ok(RawRun {
32        name: r.get(0)?,
33        project: r.get(1)?,
34        digest: r.get(2)?,
35        desired: r.get(3)?,
36        state: r.get(4)?,
37        failed_cause: r.get(5)?,
38        state_op: r.get(6)?,
39        state_at: r.get(7)?,
40        record: r.get(8)?,
41        observed: r.get(9)?,
42        observed_at: r.get(10)?,
43    })
44}
45
46/// A run's row, parsed; its record's `state` is the row's.
47fn run_row(raw: RawRun) -> Result<RunRow> {
48    let state: RunState = from_word("state", &raw.state)?;
49    let mut record: RunRecord = from_json("record", &raw.record)?;
50    record.state = state;
51    Ok(RunRow {
52        name: RunName::new(&raw.name).map_err(|_| super::corrupt("run name", &raw.name))?,
53        project: raw.project.into(),
54        source_digest: raw.digest,
55        desired: from_word("desired", &raw.desired)?,
56        state,
57        failed_cause: raw.failed_cause.as_deref().map(|c| from_word("failed_cause", c)).transpose()?,
58        state_op: raw.state_op.map(OperationId),
59        state_at: raw.state_at,
60        record,
61        observed: raw.observed.as_deref().map(|o| from_json::<LastObserved>("observation", o)).transpose()?,
62        observed_at: raw.observed_at,
63    })
64}
65
66impl Tx<'_> {
67    /// Run `name`'s row, when it has one.
68    ///
69    /// # Errors
70    ///
71    /// The store can't be read, or the row holds what this runner doesn't write.
72    pub fn run(&self, name: &RunName) -> Result<Option<RunRow>> {
73        let sql = format!("SELECT {RUN_COLUMNS} FROM runs WHERE name = ?1");
74        let raw = self.tx.query_row(&sql, [name.as_str()], raw_run).optional().map_err(failed("read"))?;
75        raw.map(run_row).transpose()
76    }
77
78    /// Every run's row, by name.
79    ///
80    /// # Errors
81    ///
82    /// As [`Tx::run`].
83    pub fn runs(&self) -> Result<Vec<RunRow>> {
84        let sql = format!("SELECT {RUN_COLUMNS} FROM runs ORDER BY name");
85        let mut stmt = self.tx.prepare(&sql).map_err(failed("read"))?;
86        let found = stmt.query_map([], raw_run).map_err(failed("read"))?;
87        let mut rows = Vec::new();
88        for raw in found {
89            rows.push(run_row(raw.map_err(failed("read"))?)?);
90        }
91        Ok(rows)
92    }
93
94    /// Records `record`: a new run's row is made in the record's state (`absent` for a run
95    /// never started; another for an imported one), wanting `desired`; an existing row gets the
96    /// record's fields and keeps its state, which only [`Tx::apply`] moves.
97    ///
98    /// # Errors
99    ///
100    /// The store can't be written.
101    pub fn save_record(&mut self, record: &RunRecord, desired: Desired) -> Result<()> {
102        let json = to_json(record)?;
103        let project = record.project.to_string_lossy().into_owned();
104        self.tx
105            .execute(
106                "INSERT INTO runs (name, project_path, source_digest, format, desired, state, state_at, record)
107                 VALUES (?1, ?2, '', ?3, ?4, ?5, ?6, ?7)
108                 ON CONFLICT(name) DO UPDATE SET project_path = excluded.project_path, format = excluded.format,
109                   record = excluded.record",
110                params![
111                    record.name.as_str(),
112                    project,
113                    word(&record.format),
114                    word(&desired),
115                    word(&record.state),
116                    now(),
117                    json
118                ],
119            )
120            .map_err(failed("written"))?;
121        Ok(())
122    }
123
124    /// Records the digest of the project files run `name` now runs from
125    /// ([`crate::Project::digest`]).
126    ///
127    /// # Errors
128    ///
129    /// The store can't be written.
130    pub fn set_source_digest(&mut self, name: &RunName, digest: &str) -> Result<()> {
131        self.tx
132            .execute("UPDATE runs SET source_digest = ?2 WHERE name = ?1", params![name.as_str(), digest])
133            .map_err(failed("written"))?;
134        Ok(())
135    }
136
137    /// Sets what the user wants of run `name`.
138    ///
139    /// # Errors
140    ///
141    /// The store can't be written.
142    pub fn set_desired(&mut self, name: &RunName, desired: Desired) -> Result<()> {
143        self.tx
144            .execute("UPDATE runs SET desired = ?2 WHERE name = ?1", params![name.as_str(), word(&desired)])
145            .map_err(failed("written"))?;
146        Ok(())
147    }
148
149    /// Moves run `name` by `transition`, and keeps the move with what made it. A compare-and-set:
150    /// refused (`state_conflict`) when the run no longer stands where the transition starts.
151    ///
152    /// # Errors
153    ///
154    /// `state_conflict` when the run moved meanwhile or has no row; the store's.
155    pub fn apply(&mut self, name: &RunName, transition: Transition) -> Result<()> {
156        let at = now();
157        let op = transition.by().operation().map(|id| id.0);
158        let cause = transition.cause().map(|c| word(&c));
159        let changed = self
160            .tx
161            .execute(
162                "UPDATE runs SET state = ?3, failed_cause = ?4, state_op = ?5, state_at = ?6 WHERE name = ?1 AND state = ?2",
163                params![name.as_str(), word(&transition.from()), word(&transition.to()), cause, op, at],
164            )
165            .map_err(failed("written"))?;
166        if changed == 0 {
167            let found = self.run(name)?.map(|r| r.state);
168            return Err(Error::StateConflict {
169                run: name.to_string(),
170                expected: transition.from(),
171                found,
172            });
173        }
174        self.tx
175            .execute(
176                "INSERT INTO transitions (run, from_state, to_state, cause, operation, by, at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
177                params![
178                    name.as_str(),
179                    word(&transition.from()),
180                    word(&transition.to()),
181                    cause,
182                    op,
183                    super::to_json(&transition.by())?,
184                    at
185                ],
186            )
187            .map_err(failed("written"))?;
188        Ok(())
189    }
190
191    /// Run `name`'s moves, oldest first: from, to, the operation that made each (none for an
192    /// observation).
193    ///
194    /// # Errors
195    ///
196    /// The store can't be read.
197    pub fn transitions(&self, name: &RunName) -> Result<Vec<(RunState, RunState, Option<OperationId>)>> {
198        let mut stmt = self
199            .tx
200            .prepare("SELECT from_state, to_state, operation FROM transitions WHERE run = ?1 ORDER BY id")
201            .map_err(failed("read"))?;
202        let rows = stmt
203            .query_map([name.as_str()], |r| {
204                Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, Option<i64>>(2)?))
205            })
206            .map_err(failed("read"))?;
207        let mut moves = Vec::new();
208        for row in rows {
209            let (from, to, op) = row.map_err(failed("read"))?;
210            moves.push((from_word("state", &from)?, from_word("state", &to)?, op.map(OperationId)));
211        }
212        Ok(moves)
213    }
214
215    /// Keeps `observed` as what the runner last saw of run `name` (no row: nothing kept), its
216    /// state left as it is: an operation's own reads.
217    ///
218    /// # Errors
219    ///
220    /// The store can't be written.
221    pub fn keep_observed(&mut self, name: &RunName, observed: &LastObserved) -> Result<bool> {
222        let changed = self
223            .tx
224            .execute(
225                "UPDATE runs SET observed = ?2, observed_at = ?3 WHERE name = ?1",
226                params![name.as_str(), to_json(observed)?, now()],
227            )
228            .map_err(failed("written"))?;
229        Ok(changed > 0)
230    }
231
232    /// Status = reconcile(desired, observed): keeps `observed`, and when a settled run shows as
233    /// `to` (what its machines say), moves it there by an observation. A moving run (an
234    /// operation owns it) or a move the table doesn't allow keeps its state. The move made, if
235    /// one was.
236    ///
237    /// # Errors
238    ///
239    /// The store can't be written.
240    pub fn observe(&mut self, name: &RunName, observed: &LastObserved, to: RunState) -> Result<Option<Transition>> {
241        if !self.keep_observed(name, observed)? {
242            return Ok(None);
243        }
244        let Some(row) = self.run(name)? else {
245            return Ok(None);
246        };
247        if row.state == to {
248            return Ok(None);
249        }
250        let Ok(transition) = Transition::observed(row.state, to) else {
251            return Ok(None);
252        };
253        self.apply(name, transition)?;
254        Ok(Some(transition))
255    }
256
257    /// Forgets what the runner last saw of run `name`.
258    ///
259    /// # Errors
260    ///
261    /// The store can't be written.
262    pub fn forget_observed(&mut self, name: &RunName) -> Result<()> {
263        self.tx
264            .execute("UPDATE runs SET observed = NULL, observed_at = NULL WHERE name = ?1", [name.as_str()])
265            .map_err(failed("written"))?;
266        Ok(())
267    }
268
269    /// Removes run `name`'s row and its moves.
270    ///
271    /// # Errors
272    ///
273    /// The store can't be written.
274    pub fn forget_run(&mut self, name: &RunName) -> Result<()> {
275        self.tx
276            .execute("DELETE FROM runs WHERE name = ?1", [name.as_str()])
277            .map_err(failed("written"))?;
278        Ok(())
279    }
280}