1use 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
13const RESOURCE_COLUMNS: &str = "id, run, key, kind, scope, copy_name, native_id, state, lifetime, created_by, destroyed_by, detail";
15
16struct 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 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 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 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 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 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 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 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 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 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 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}