Skip to main content

isothrum_runner/store/
db.rs

1//! The home's transactional store: one SQLite database, `<home>/state.db`, in WAL mode with
2//! foreign keys on. It holds the runs (what the user wants of each and where each stands), the
3//! journal of operations, the events, the resources each run made (written ahead of the call
4//! that makes them), what the runs' downloads fetched, the host ports reserved, and the leases.
5//! Every change is one transaction.
6//!
7//! The store is synchronous: its transactions are a few rows, and the runner calls it inline
8//! from async code, as it read and wrote its files before.
9
10mod downloads;
11mod journal;
12mod leases;
13mod mirror;
14mod owner;
15mod resources;
16mod rows;
17mod runs;
18mod schema;
19#[cfg(test)]
20mod tests;
21
22/// The pid of a process that ran and exited, on any OS: an owner that is gone.
23#[cfg(test)]
24pub(crate) use owner::tests::dead_pid;
25
26use std::path::{Path, PathBuf};
27use std::sync::atomic::{AtomicI64, Ordering};
28use std::sync::{Mutex, PoisonError};
29use std::time::Duration;
30
31use rusqlite::{Connection, TransactionBehavior};
32use serde::Serialize;
33use serde::de::DeserializeOwned;
34
35pub use leases::Reserver;
36pub use mirror::{MIRROR_FILE, Recovered};
37pub use owner::Owner;
38pub use rows::{
39    CopyName, Ended, EventCursor, EventPage, Lease, LeaseOutcome, Lifetime, NewResource, NotPerCopy, OperationId, OperationRow, Outcome, PortReservation,
40    ResourceId, ResourceKind, ResourceRow, ResourceState, RunRow, Scope,
41};
42
43use crate::Result;
44use crate::error::{Error, ErrorCode};
45
46/// The store's file, in the home.
47pub(crate) const DB_FILE: &str = "state.db";
48
49/// How long a write waits for another process's write before it fails `locked`.
50const BUSY_TIMEOUT: Duration = Duration::from_secs(5);
51
52/// The home's store.
53pub struct Store {
54    conn: Mutex<Connection>,
55    path: PathBuf,
56    /// The mirror's file ([`MIRROR_FILE`]).
57    mirror: PathBuf,
58    /// The mirror generation the mirror was last written at (-1: not since this open).
59    mirrored: AtomicI64,
60    /// The repair `open` made from the mirror, if it made one.
61    recovered: Option<Recovered>,
62}
63
64impl std::fmt::Debug for Store {
65    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66        f.debug_struct("Store").field("path", &self.path).finish_non_exhaustive()
67    }
68}
69
70/// A transaction over the store: every query and change is one of its methods; the changes need
71/// `&mut`, so they are made only in [`Store::write`].
72pub struct Tx<'c> {
73    tx: rusqlite::Transaction<'c>,
74}
75
76impl Store {
77    /// The home's store, `<home>/state.db`: created owner-only when missing, checked
78    /// (`PRAGMA quick_check`) and migrated to this runner's schema. A store whose file is damaged
79    /// is rebuilt from its mirror (`<home>/state.mirror`, [`MIRROR_FILE`]): the damaged file is
80    /// kept aside for diagnostics (`state.db.corrupt-<unix seconds>`), and [`Store::recovered`]
81    /// says so. Nothing else of the home is read: files another release left in it are ignored.
82    ///
83    /// # Errors
84    ///
85    /// `io` when the home or the file can't be made; `store_corrupt` when the file isn't a sound
86    /// database and no mirror can rebuild it; `store_version` when a newer runner wrote it;
87    /// `locked` when another process's write held it past five seconds.
88    pub fn open(home: &Path) -> Result<Store> {
89        let home = &std::path::absolute(home).map_err(Error::io(home, "made absolute"))?;
90        crate::store::create_dir(home)?;
91        let path = home.join(DB_FILE);
92        let mirror = home.join(MIRROR_FILE);
93        match Store::open_checked(&path, &mirror, Fresh::Suspect) {
94            Ok(store) => {
95                // A sound store's mirror is made current at once: one a writer left ahead of its
96                // commit (killed in between) is replaced.
97                store.sync_mirror();
98                Ok(store)
99            }
100            Err(e) if e.code() == ErrorCode::StoreCorrupt => Store::rebuild(&path, &mirror, &e),
101            Err(e) => Err(e),
102        }
103    }
104
105    /// The store at `path`, opened, checked and migrated; a new, empty file beside a mirror that
106    /// holds something is damaged, unless `fresh` says it is the rebuild's own.
107    fn open_checked(path: &Path, mirror: &Path, fresh: Fresh) -> Result<Store> {
108        let conn = connect(path)?;
109        quick_check(&conn)?;
110        let store = Store {
111            conn: Mutex::new(conn),
112            path: path.to_path_buf(),
113            mirror: mirror.to_path_buf(),
114            mirrored: AtomicI64::new(-1),
115            recovered: None,
116        };
117        let was = store.migrate()?;
118        // An empty file where a store was (truncated, replaced) beside a mirror that holds
119        // something: damaged, not new.
120        if was == 0 && fresh == Fresh::Suspect && mirror::read(mirror).is_some_and(|m| m.holds_rows()) {
121            return Err(Error::Store {
122                action: "opened",
123                code: ErrorCode::StoreCorrupt,
124                reason: "its file is empty, but its mirror holds runs, operations or resources".to_owned(),
125            });
126        }
127        Ok(store)
128    }
129
130    /// Runs `f` in a read-only transaction over `home`'s store as it is: opened read-only, never
131    /// created nor migrated, so a process of another release that owns the store is left as it
132    /// was. `None` when the home has no store.
133    ///
134    /// # Errors
135    ///
136    /// `f`'s (a schema `f` doesn't know reads as `io`), or the store's.
137    pub fn read_existing<T>(home: &Path, f: impl FnOnce(&Tx<'_>) -> Result<T>) -> Result<Option<T>> {
138        let path = home.join(DB_FILE);
139        if !path.is_file() {
140            return Ok(None);
141        }
142        let flags = rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX;
143        let conn = Connection::open_with_flags(&path, flags).map_err(failed("opened"))?;
144        conn.busy_timeout(BUSY_TIMEOUT).map_err(failed("opened"))?;
145        let store = Store {
146            conn: Mutex::new(conn),
147            path,
148            mirror: home.join(MIRROR_FILE),
149            mirrored: AtomicI64::new(-1),
150            recovered: None,
151        };
152        store.read(f).map(Some)
153    }
154
155    /// Rebuilds the damaged store at `path` (what was wrong: `cause`) from the mirror at
156    /// `mirror`: the damaged files move aside, a new store is made and filled from the mirror.
157    fn rebuild(path: &Path, mirror: &Path, cause: &Error) -> Result<Store> {
158        let damaged = |reason: String| Error::Store {
159            action: "opened",
160            code: ErrorCode::StoreCorrupt,
161            reason,
162        };
163        let Some(copy) = mirror::read(mirror) else {
164            return Err(damaged(format!("{cause}; and there is no mirror to rebuild it from")));
165        };
166        let known = i64::try_from(schema::MIGRATIONS.len()).unwrap_or(i64::MAX);
167        if copy.schema() != known {
168            return Err(damaged(format!("{cause}; and its mirror is of schema {}, not {known}", copy.schema())));
169        }
170        let kept = set_aside(path)?;
171        tracing::warn!(error = %cause, kept = %kept.display(), "the store was damaged: rebuilt from its mirror");
172        let mut store = Store::open_checked(path, mirror, Fresh::Expected)?;
173        {
174            let mut conn = store.conn.lock().unwrap_or_else(PoisonError::into_inner);
175            copy.restore(&mut conn)?;
176        }
177        store.sync_mirror();
178        store.recovered = Some(Recovered {
179            corrupt_kept_at: kept,
180            mirror_written_at: copy.written_at().to_owned(),
181            reason: cause.to_string(),
182        });
183        Ok(store)
184    }
185
186    /// The repair [`Store::open`] made from the mirror, if it made one: an embedder then reads
187    /// every run's status, which reconciles it with what its tools report.
188    #[must_use]
189    pub fn recovered(&self) -> Option<&Recovered> {
190        self.recovered.as_ref()
191    }
192
193    /// Writes the mirror when the store changed since it was last written (its own snapshot).
194    fn sync_mirror(&self) {
195        let mut conn = self.conn.lock().unwrap_or_else(PoisonError::into_inner);
196        match conn.transaction_with_behavior(TransactionBehavior::Deferred) {
197            Ok(tx) => self.mirror_within(&tx),
198            Err(e) => tracing::warn!(error = %e, "the store's mirror wasn't written"),
199        }
200    }
201
202    /// Writes the mirror from `conn`'s view when the mirror generation moved since it was last
203    /// written. Inside a write transaction, the store's write lock orders the mirrors of every
204    /// process. A mirror that can't be written is said, not failed on: the store holds the rows.
205    fn mirror_within(&self, conn: &Connection) {
206        let written = mirror::generation(conn).map_err(failed("read")).and_then(|n| {
207            if n == self.mirrored.load(Ordering::SeqCst) {
208                Ok(None)
209            } else {
210                mirror::write(conn, n, &self.mirror).map(|()| Some(n))
211            }
212        });
213        match written {
214            Ok(Some(n)) => self.mirrored.store(n, Ordering::SeqCst),
215            Ok(None) => {}
216            Err(e) => {
217                self.mirrored.store(-1, Ordering::SeqCst);
218                tracing::warn!(error = %e, "the store's mirror wasn't written");
219            }
220        }
221    }
222
223    /// The database's file.
224    #[must_use]
225    pub fn path(&self) -> &Path {
226        &self.path
227    }
228
229    /// Runs `f` in a read-only transaction: a snapshot that sees no write half made.
230    ///
231    /// # Errors
232    ///
233    /// `f`'s, or the store's.
234    pub fn read<T>(&self, f: impl FnOnce(&Tx<'_>) -> Result<T>) -> Result<T> {
235        let mut conn = self.conn.lock().unwrap_or_else(PoisonError::into_inner);
236        let tx = conn.transaction_with_behavior(TransactionBehavior::Deferred).map_err(failed("read"))?;
237        let tx = Tx { tx };
238        let value = f(&tx)?;
239        tx.tx.finish().map_err(failed("read"))?;
240        Ok(value)
241    }
242
243    /// Runs `f` in a write transaction: it commits when `f` returns `Ok`, and rolls back when `f`
244    /// fails (or panics), so every change `f` made is kept or none is.
245    ///
246    /// # Errors
247    ///
248    /// `f`'s, or the store's (`locked` when another process's write held it too long).
249    pub fn write<T>(&self, f: impl FnOnce(&mut Tx<'_>) -> Result<T>) -> Result<T> {
250        let mut conn = self.conn.lock().unwrap_or_else(PoisonError::into_inner);
251        let committed = {
252            let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(failed("written"))?;
253            let mut tx = Tx { tx };
254            let value = f(&mut tx)?;
255            // Before the commit, under the write lock: a mirror left ahead by a crash right after
256            // is rewritten at the next open of the sound store.
257            self.mirror_within(&tx.tx);
258            tx.tx.commit().map(|()| value)
259        };
260        committed.map_err(|e| {
261            // The mirror was written ahead of a commit that failed: written again from what is.
262            self.mirrored.store(-1, Ordering::SeqCst);
263            drop(conn);
264            self.sync_mirror();
265            failed("written")(e)
266        })
267    }
268
269    /// Runs the migrations the file hasn't had, each in its own transaction: the version it was
270    /// at (0: a new, empty file).
271    fn migrate(&self) -> Result<i64> {
272        let mut conn = self.conn.lock().unwrap_or_else(PoisonError::into_inner);
273        conn.execute_batch("CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)")
274            .map_err(failed("migrated"))?;
275        let applied: i64 = conn
276            .query_row("SELECT COALESCE(MAX(version), 0) FROM schema_migrations", [], |r| r.get(0))
277            .map_err(failed("migrated"))?;
278        let known = i64::try_from(schema::MIGRATIONS.len()).unwrap_or(i64::MAX);
279        if applied > known {
280            return Err(Error::Store {
281                action: "opened",
282                code: ErrorCode::StoreVersion,
283                reason: format!("its schema is version {applied}, newer than this runner's {known}: a newer runner wrote it"),
284            });
285        }
286        for (version, sql) in (1..).zip(schema::MIGRATIONS).skip(usize::try_from(applied).unwrap_or(0)) {
287            let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(failed("migrated"))?;
288            tx.execute_batch(sql).map_err(failed("migrated"))?;
289            tx.execute(
290                "INSERT INTO schema_migrations (version, applied_at) VALUES (?1, ?2)",
291                rusqlite::params![version, now()],
292            )
293            .map_err(failed("migrated"))?;
294            tx.commit().map_err(failed("migrated"))?;
295        }
296        Ok(applied)
297    }
298}
299
300impl Tx<'_> {}
301
302/// What a new, empty store file means when [`Store::open`] finds one.
303#[derive(Debug, Clone, Copy, PartialEq, Eq)]
304enum Fresh {
305    /// A home's first store, or one emptied: damaged when its mirror holds something.
306    Suspect,
307    /// The file a rebuild made.
308    Expected,
309}
310
311/// A connection to the store's file at `path`: owner-only, WAL, foreign keys on.
312fn connect(path: &Path) -> Result<Connection> {
313    let conn = Connection::open(path).map_err(failed("opened"))?;
314    #[cfg(unix)]
315    restrict(path)?;
316    conn.busy_timeout(BUSY_TIMEOUT).map_err(failed("opened"))?;
317    conn.pragma_update(None, "journal_mode", "WAL").map_err(failed("opened"))?;
318    conn.pragma_update(None, "foreign_keys", "ON").map_err(failed("opened"))?;
319    conn.pragma_update(None, "synchronous", "NORMAL").map_err(failed("opened"))?;
320    Ok(conn)
321}
322
323/// How many of `quick_check`'s findings an error names.
324const FINDINGS_SAID: usize = 3;
325
326/// Checks the store's pages (`PRAGMA quick_check`, as `chkdsk` checks a volume at mount).
327///
328/// # Errors
329///
330/// `store_corrupt`, naming its first findings, when the check finds a problem.
331fn quick_check(conn: &Connection) -> Result<()> {
332    let mut stmt = conn.prepare("PRAGMA quick_check").map_err(failed("checked"))?;
333    let findings: Vec<String> = stmt
334        .query_map([], |r| r.get::<_, String>(0))
335        .map_err(failed("checked"))?
336        .collect::<rusqlite::Result<_>>()
337        .map_err(failed("checked"))?;
338    if findings.iter().all(|f| f == "ok") {
339        return Ok(());
340    }
341    let said: Vec<&str> = findings.iter().take(FINDINGS_SAID).map(String::as_str).collect();
342    Err(Error::Store {
343        action: "checked",
344        code: ErrorCode::StoreCorrupt,
345        reason: format!("its integrity check failed ({} findings): {}", findings.len(), said.join("; ")),
346    })
347}
348
349/// Moves the damaged store at `path` (and its `-wal` and `-shm`) aside, to
350/// `state.db.corrupt-<unix seconds>`: where it is now.
351fn set_aside(path: &Path) -> Result<PathBuf> {
352    let kept = path.with_file_name(format!("{DB_FILE}.corrupt-{}", epoch_now()));
353    for suffix in ["", "-wal", "-shm"] {
354        let with = |p: &Path| {
355            let mut name = p.as_os_str().to_owned();
356            name.push(suffix);
357            PathBuf::from(name)
358        };
359        let (from, to) = (with(path), with(&kept));
360        if from.exists() {
361            std::fs::rename(&from, &to).map_err(Error::io(&from, "moved aside"))?;
362        }
363    }
364    Ok(kept)
365}
366
367/// The store's failure to do `action`, with the code SQLite's error has: a database busy past the
368/// wait is `locked`, a file that isn't one `store_corrupt`, anything else `io`.
369pub(crate) fn failed(action: &'static str) -> impl Fn(rusqlite::Error) -> Error {
370    move |e| {
371        let code = match e.sqlite_error_code() {
372            Some(rusqlite::ErrorCode::DatabaseBusy | rusqlite::ErrorCode::DatabaseLocked) => ErrorCode::Locked,
373            Some(rusqlite::ErrorCode::NotADatabase | rusqlite::ErrorCode::DatabaseCorrupt) => ErrorCode::StoreCorrupt,
374            _ => ErrorCode::Io,
375        };
376        Error::Store {
377            action,
378            code,
379            reason: e.to_string(),
380        }
381    }
382}
383
384/// A column that doesn't hold what this runner writes there.
385pub(crate) fn corrupt(what: &str, value: &str) -> Error {
386    Error::Store {
387        action: "read",
388        code: ErrorCode::StoreCorrupt,
389        reason: format!("a {what} column holds `{value}`, which this runner doesn't write"),
390    }
391}
392
393/// `value`'s wire name, as a column holds it.
394pub(crate) fn word<T: Serialize>(value: &T) -> String {
395    crate::encoding::wire_name(value)
396}
397
398/// The unit enum `T` a column wrote as `word`.
399pub(crate) fn from_word<T: DeserializeOwned>(what: &str, word: &str) -> Result<T> {
400    crate::encoding::from_wire_name(word).ok_or_else(|| corrupt(what, word))
401}
402
403/// `value` as a JSON column.
404pub(crate) fn to_json<T: Serialize>(value: &T) -> Result<String> {
405    serde_json::to_string(value).map_err(|e| Error::Store {
406        action: "written",
407        code: ErrorCode::Io,
408        reason: e.to_string(),
409    })
410}
411
412/// A JSON column read back.
413pub(crate) fn from_json<T: DeserializeOwned>(what: &str, text: &str) -> Result<T> {
414    serde_json::from_str(text).map_err(|e| Error::Store {
415        action: "read",
416        code: ErrorCode::StoreCorrupt,
417        reason: format!("its {what} doesn't parse: {e}"),
418    })
419}
420
421/// Now, as the store writes times.
422pub(crate) fn now() -> String {
423    crate::clock::rfc3339(std::time::SystemTime::now())
424}
425
426/// Now, in seconds since the Unix epoch.
427pub(crate) fn epoch_now() -> u64 {
428    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs())
429}
430
431/// Makes the database's file owner-only (Unix: on Windows the home's DACL already is).
432#[cfg(unix)]
433fn restrict(path: &Path) -> Result<()> {
434    use std::os::unix::fs::PermissionsExt;
435    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).map_err(Error::io(path, "made owner-only"))
436}