Skip to main content

isothrum_runner/store/db/
resources.rs

1//! The resources each run made, written ahead: `creating` before the call that makes one,
2//! `created` with the provider's id after it, `destroying` before the call that removes it,
3//! `gone` after. A process that dies between the two writes leaves a row that says what may
4//! exist, and the next operation removes it by its id, or by its per-copy name.
5
6use rusqlite::{Row, params};
7
8use super::{CopyName, NewResource, OperationId, ResourceId, ResourceRow, ResourceState, Tx, failed, from_json, from_word, now, to_json, word};
9use crate::Result;
10use crate::error::{Error, ErrorCode};
11use crate::name::RunName;
12
13/// The columns a [`ResourceRow`] is read from, in [`resource_row`]'s order.
14const RESOURCE_COLUMNS: &str = "id, run, key, kind, scope, copy_name, native_id, state, lifetime, created_by, destroyed_by, detail";
15
16/// The text columns of a resource's row, before they are parsed.
17struct RawResource {
18    id: i64,
19    run: String,
20    key: String,
21    kind: String,
22    scope: String,
23    copy_name: Option<String>,
24    native_id: Option<String>,
25    state: String,
26    lifetime: String,
27    created_by: i64,
28    destroyed_by: Option<i64>,
29    detail: Option<String>,
30}
31
32fn raw_resource(r: &Row<'_>) -> rusqlite::Result<RawResource> {
33    Ok(RawResource {
34        id: r.get(0)?,
35        run: r.get(1)?,
36        key: r.get(2)?,
37        kind: r.get(3)?,
38        scope: r.get(4)?,
39        copy_name: r.get(5)?,
40        native_id: r.get(6)?,
41        state: r.get(7)?,
42        lifetime: r.get(8)?,
43        created_by: r.get(9)?,
44        destroyed_by: r.get(10)?,
45        detail: r.get(11)?,
46    })
47}
48
49fn resource_row(raw: RawResource) -> Result<ResourceRow> {
50    Ok(ResourceRow {
51        id: ResourceId(raw.id),
52        run: RunName::new(&raw.run).map_err(|_| super::corrupt("run name", &raw.run))?,
53        key: raw.key,
54        kind: from_word("kind", &raw.kind)?,
55        scope: from_word("scope", &raw.scope)?,
56        copy_name: raw.copy_name.map(CopyName::stored),
57        native_id: raw.native_id,
58        state: from_word("resource state", &raw.state)?,
59        lifetime: from_word("lifetime", &raw.lifetime)?,
60        created_by: OperationId(raw.created_by),
61        destroyed_by: raw.destroyed_by.map(OperationId),
62        detail: raw.detail.as_deref().map(|d| from_json("detail", d)).transpose()?,
63    })
64}
65
66impl Tx<'_> {
67    /// Writes `new` as `creating`, before the call that makes it: commit it before the call.
68    ///
69    /// # Errors
70    ///
71    /// `illegal_transition` when `new` gives a local kind a lifetime other than its own, or a
72    /// provider kind none; the store's.
73    pub fn creating(&mut self, new: &NewResource<'_>) -> Result<ResourceId> {
74        let lifetime = match (new.kind.lifetime(), new.lifetime) {
75            (Some(own), None) => own,
76            (Some(own), Some(asked)) if own == asked => own,
77            (None, Some(asked)) => asked,
78            (own, asked) => {
79                return Err(Error::Store {
80                    action: "written",
81                    code: ErrorCode::IllegalTransition,
82                    reason: format!(
83                        "a {} resource lives {}, not {}",
84                        word(&new.kind),
85                        own.map_or_else(|| "as its manifest says".to_owned(), |l| word(&l)),
86                        asked.map_or_else(|| "unsaid".to_owned(), |l| word(&l)),
87                    ),
88                });
89            }
90        };
91        self.tx
92            .execute(
93                "INSERT INTO resources (run, key, kind, scope, copy_name, state, lifetime, created_by, detail, updated_at)
94                 VALUES (?1, ?2, ?3, ?4, ?5, 'creating', ?6, ?7, ?8, ?9)",
95                params![
96                    new.run.as_str(),
97                    new.key,
98                    word(&new.kind),
99                    word(&new.kind.scope()),
100                    new.copy_name.as_ref().map(CopyName::as_str),
101                    word(&lifetime),
102                    new.by.0,
103                    new.detail.as_ref().map(to_json).transpose()?,
104                    now()
105                ],
106            )
107            .map_err(failed("written"))?;
108        Ok(ResourceId(self.tx.last_insert_rowid()))
109    }
110
111    /// Records that resource `id` was made, as `native_id`.
112    ///
113    /// # Errors
114    ///
115    /// `illegal_transition` when the row isn't `creating` or `created` (a made resource made
116    /// again keeps its row: an idempotent retry); the store's.
117    pub fn created(&mut self, id: ResourceId, native_id: &str) -> Result<()> {
118        self.move_resource(id, &[ResourceState::Creating, ResourceState::Created], ResourceState::Created, |tx| {
119            tx.tx
120                .execute("UPDATE resources SET native_id = ?2 WHERE id = ?1", params![id.0, native_id])
121                .map(drop)
122        })
123    }
124
125    /// Records that operation `by` is removing resource `id`: before the call that removes it.
126    ///
127    /// # Errors
128    ///
129    /// `illegal_transition` when the row is gone already; the store's.
130    pub fn destroying(&mut self, id: ResourceId, by: OperationId) -> Result<()> {
131        let from = [ResourceState::Creating, ResourceState::Created, ResourceState::Destroying];
132        self.move_resource(id, &from, ResourceState::Destroying, |tx| {
133            tx.tx
134                .execute("UPDATE resources SET destroyed_by = ?2 WHERE id = ?1", params![id.0, by.0])
135                .map(drop)
136        })
137    }
138
139    /// Records that resource `id` is gone: removed, or found missing. Gone twice is fine.
140    ///
141    /// # Errors
142    ///
143    /// The store's.
144    pub fn gone(&mut self, id: ResourceId) -> Result<()> {
145        let from = [ResourceState::Creating, ResourceState::Created, ResourceState::Destroying, ResourceState::Gone];
146        self.move_resource(id, &from, ResourceState::Gone, |_| Ok(()))
147    }
148
149    /// Moves resource `id` to `to` when it stands in one of `from`, with `also` in the same
150    /// transaction.
151    fn move_resource(&mut self, id: ResourceId, from: &[ResourceState], to: ResourceState, also: impl FnOnce(&Tx<'_>) -> rusqlite::Result<()>) -> Result<()> {
152        let state: String = self
153            .tx
154            .query_row("SELECT state FROM resources WHERE id = ?1", [id.0], |r| r.get(0))
155            .map_err(failed("read"))?;
156        let state: ResourceState = from_word("resource state", &state)?;
157        if !from.contains(&state) {
158            return Err(Error::Store {
159                action: "written",
160                code: ErrorCode::IllegalTransition,
161                reason: format!("resource {} is {}, so it can't become {}", id.0, word(&state), word(&to)),
162            });
163        }
164        self.tx
165            .execute(
166                "UPDATE resources SET state = ?2, updated_at = ?3 WHERE id = ?1",
167                params![id.0, word(&to), now()],
168            )
169            .map_err(failed("written"))?;
170        also(self).map_err(failed("written"))
171    }
172
173    /// Resource row `id`, in any state.
174    ///
175    /// # Errors
176    ///
177    /// The store can't be read.
178    pub fn resource(&self, id: ResourceId) -> Result<Option<ResourceRow>> {
179        let sql = format!("SELECT {RESOURCE_COLUMNS} FROM resources WHERE id = ?1");
180        Ok(self.resources_where(&sql, params![id.0])?.pop())
181    }
182
183    /// The live provider rows of `run` that operations whose process died made: each made by an
184    /// operation that ended `abandoned`, or never ended and isn't `current` (called with the run
185    /// held, so none of those runs). What a recovery removes by recorded id, newest first. A row
186    /// still `creating` with no id is left out: nothing to remove by, and the next reading of what
187    /// the tool reports gives it its id or lets it go.
188    ///
189    /// # Errors
190    ///
191    /// The store can't be read.
192    pub fn left_by_dead_operations(&self, run: &RunName, current: OperationId) -> Result<Vec<ResourceRow>> {
193        let sql = format!(
194            "SELECT {RESOURCE_COLUMNS} FROM resources r WHERE r.run = ?1 AND r.state <> 'gone' AND r.scope = 'provider'
195               AND r.native_id IS NOT NULL AND r.created_by <> ?2
196               AND EXISTS (SELECT 1 FROM operations o WHERE o.id = r.created_by
197                           AND (o.outcome = 'abandoned' OR o.ended_at IS NULL))
198             ORDER BY r.id DESC"
199        );
200        self.resources_where(&sql, params![run.as_str(), current.0])
201    }
202
203    /// Run `run`'s resources not gone, oldest first (a `down` walks them newest first).
204    ///
205    /// # Errors
206    ///
207    /// The store can't be read.
208    pub fn live_resources(&self, run: &RunName) -> Result<Vec<ResourceRow>> {
209        let sql = format!("SELECT {RESOURCE_COLUMNS} FROM resources WHERE run = ?1 AND state <> 'gone' ORDER BY id");
210        self.resources_where(&sql, params![run.as_str()])
211    }
212
213    /// The resources operation `by` made that aren't gone: what a recovery of it removes.
214    ///
215    /// # Errors
216    ///
217    /// The store can't be read.
218    pub fn resources_of(&self, by: OperationId) -> Result<Vec<ResourceRow>> {
219        let sql = format!("SELECT {RESOURCE_COLUMNS} FROM resources WHERE created_by = ?1 AND state <> 'gone' ORDER BY id");
220        self.resources_where(&sql, params![by.0])
221    }
222
223    /// Run `run`'s live resource keyed `key` of the per-copy name `name`: what an idempotent
224    /// create finds before making it again. Never by a bare name: [`CopyName`] holds the key.
225    ///
226    /// # Errors
227    ///
228    /// The store can't be read.
229    pub fn resource_named(&self, run: &RunName, key: &str, name: &CopyName) -> Result<Option<ResourceRow>> {
230        let sql =
231            format!("SELECT {RESOURCE_COLUMNS} FROM resources WHERE run = ?1 AND key = ?2 AND copy_name = ?3 AND state <> 'gone' ORDER BY id DESC LIMIT 1");
232        Ok(self.resources_where(&sql, params![run.as_str(), key, name.as_str()])?.pop())
233    }
234
235    fn resources_where(&self, sql: &str, params: impl rusqlite::Params) -> Result<Vec<ResourceRow>> {
236        let mut stmt = self.tx.prepare(sql).map_err(failed("read"))?;
237        let found = stmt.query_map(params, raw_resource).map_err(failed("read"))?;
238        let mut rows = Vec::new();
239        for raw in found {
240            rows.push(resource_row(raw.map_err(failed("read"))?)?);
241        }
242        Ok(rows)
243    }
244}