isothrum_runner/store/db/
mirror.rs1use std::collections::BTreeMap;
12use std::io::Write as _;
13use std::path::{Path, PathBuf};
14
15use rusqlite::Connection;
16use rusqlite::types::{Value, ValueRef};
17use serde::{Deserialize, Serialize};
18
19use crate::Result;
20use crate::error::{Error, ErrorCode};
21
22pub const MIRROR_FILE: &str = "state.mirror";
24
25const CURSOR_MARGIN: i64 = 1_000_000;
29
30const NOT_MIRRORED: [&str; 2] = ["observed", "observed_at"];
32
33type Rows = Vec<BTreeMap<String, serde_json::Value>>;
35
36#[derive(Debug, Serialize, Deserialize)]
38struct Mirror {
39 schema: i64,
41 generation: i64,
43 written_at: String,
45 events_cursor: i64,
47 runs: Rows,
49 operations: Rows,
51 resources: Rows,
53 #[serde(default)]
55 downloads: Rows,
56}
57
58#[derive(Debug, Clone, PartialEq, Eq)]
61#[non_exhaustive]
62pub struct Recovered {
63 pub corrupt_kept_at: PathBuf,
65 pub mirror_written_at: String,
67 pub reason: String,
69}
70
71pub(super) fn generation(conn: &Connection) -> rusqlite::Result<i64> {
73 conn.query_row("SELECT n FROM mirror_generation WHERE id = 1", [], |r| r.get(0))
74}
75
76fn rows(conn: &Connection, sql: &str) -> rusqlite::Result<Rows> {
78 let mut stmt = conn.prepare(sql)?;
79 let names: Vec<String> = stmt.column_names().map(str::to_owned).collect();
80 let mut out = Vec::new();
81 let mut found = stmt.query([])?;
82 while let Some(row) = found.next()? {
83 let mut columns = BTreeMap::new();
84 for (i, name) in names.iter().enumerate() {
85 if NOT_MIRRORED.contains(&name.as_str()) {
86 continue;
87 }
88 let value = match row.get_ref(i)? {
89 ValueRef::Null | ValueRef::Blob(_) => serde_json::Value::Null,
90 ValueRef::Integer(n) => n.into(),
91 ValueRef::Real(f) => f.into(),
92 ValueRef::Text(t) => String::from_utf8_lossy(t).into_owned().into(),
93 };
94 columns.insert(name.clone(), value);
95 }
96 out.push(columns);
97 }
98 Ok(out)
99}
100
101pub(super) fn write(conn: &Connection, generation: i64, path: &Path) -> Result<()> {
107 let read = |e: rusqlite::Error| super::failed("read")(e);
108 let schema: i64 = conn
109 .query_row("SELECT COALESCE(MAX(version), 0) FROM schema_migrations", [], |r| r.get(0))
110 .map_err(read)?;
111 let events_cursor: i64 = conn.query_row("SELECT COALESCE(MAX(cursor), 0) FROM events", [], |r| r.get(0)).map_err(read)?;
112 let mirror = Mirror {
113 schema,
114 generation,
115 written_at: super::now(),
116 events_cursor,
117 runs: rows(conn, "SELECT * FROM runs ORDER BY name").map_err(read)?,
118 operations: rows(
119 conn,
120 "SELECT * FROM operations WHERE ended_at IS NULL
121 OR id IN (SELECT state_op FROM runs)
122 OR id IN (SELECT created_by FROM resources WHERE state <> 'gone')
123 OR id IN (SELECT destroyed_by FROM resources WHERE state <> 'gone')
124 ORDER BY id",
125 )
126 .map_err(read)?,
127 resources: rows(conn, "SELECT * FROM resources WHERE state <> 'gone' ORDER BY id").map_err(read)?,
128 downloads: rows(conn, "SELECT * FROM downloads ORDER BY id").map_err(read)?,
129 };
130 let text = serde_json::to_vec(&mirror).map_err(|e| Error::io(path, "written")(e.into()))?;
131 write_durably(path, &text).map_err(Error::io(path, "written"))
132}
133
134fn write_durably(path: &Path, contents: &[u8]) -> std::io::Result<()> {
137 let tmp = path.with_extension("mirror.tmp");
138 {
139 let mut f = crate::store::create_private(&tmp)?;
140 f.write_all(contents)?;
141 f.sync_all()?;
142 }
143 std::fs::rename(&tmp, path)?;
144 #[cfg(unix)]
145 if let Some(dir) = path.parent() {
146 std::fs::File::open(dir)?.sync_all()?;
147 }
148 Ok(())
149}
150
151pub(super) fn read(path: &Path) -> Option<MirrorFile> {
153 let bytes = std::fs::read(path).ok()?;
154 match serde_json::from_slice::<Mirror>(&bytes) {
155 Ok(mirror) => Some(MirrorFile(mirror)),
156 Err(e) => {
157 tracing::warn!(path = %path.display(), error = %e, "the store's mirror can't be read");
158 None
159 }
160 }
161}
162
163#[derive(Debug)]
165pub(super) struct MirrorFile(Mirror);
166
167impl MirrorFile {
168 pub(super) fn written_at(&self) -> &str {
170 &self.0.written_at
171 }
172
173 pub(super) fn holds_rows(&self) -> bool {
175 !(self.0.runs.is_empty() && self.0.operations.is_empty() && self.0.resources.is_empty() && self.0.downloads.is_empty())
176 }
177
178 pub(super) fn schema(&self) -> i64 {
180 self.0.schema
181 }
182
183 pub(super) fn restore(&self, conn: &mut Connection) -> Result<()> {
189 let corrupt = |e: rusqlite::Error| Error::Store {
190 action: "rebuilt from its mirror",
191 code: ErrorCode::StoreCorrupt,
192 reason: e.to_string(),
193 };
194 let tx = conn.transaction().map_err(corrupt)?;
195 tx.pragma_update(None, "defer_foreign_keys", "ON").map_err(corrupt)?;
198 let tables = [
199 ("operations", &self.0.operations),
200 ("runs", &self.0.runs),
201 ("resources", &self.0.resources),
202 ("downloads", &self.0.downloads),
203 ];
204 for (table, rows) in tables {
205 for row in rows {
206 insert(&tx, table, row).map_err(corrupt)?;
207 }
208 }
209 tx.execute(
211 "UPDATE operations SET resumed_from = NULL WHERE resumed_from IS NOT NULL AND resumed_from NOT IN (SELECT id FROM operations)",
212 [],
213 )
214 .map_err(corrupt)?;
215 tx.execute(
216 "INSERT OR REPLACE INTO sqlite_sequence (name, seq) VALUES ('events', ?1)",
217 [self.0.events_cursor.saturating_add(CURSOR_MARGIN)],
218 )
219 .map_err(corrupt)?;
220 tx.commit().map_err(corrupt)
221 }
222}
223
224fn insert(tx: &rusqlite::Transaction<'_>, table: &str, row: &BTreeMap<String, serde_json::Value>) -> rusqlite::Result<()> {
226 let names: Vec<&str> = row.keys().map(String::as_str).collect();
227 let marks: Vec<String> = (1..=names.len()).map(|i| format!("?{i}")).collect();
228 let sql = format!("INSERT INTO {table} ({}) VALUES ({})", names.join(", "), marks.join(", "));
229 let values: Vec<Value> = row
230 .values()
231 .map(|v| match v {
232 serde_json::Value::Null => Value::Null,
233 serde_json::Value::Number(n) => n.as_i64().map_or_else(|| Value::Real(n.as_f64().unwrap_or_default()), Value::Integer),
234 serde_json::Value::Bool(b) => Value::Integer(i64::from(*b)),
235 serde_json::Value::String(s) => Value::Text(s.clone()),
236 other => Value::Text(other.to_string()),
237 })
238 .collect();
239 tx.execute(&sql, rusqlite::params_from_iter(values))?;
240 Ok(())
241}