Skip to main content

isothrum_runner/store/db/
mirror.rs

1//! The store's mirror (NTFS's `$MFTMirr`): the rows a later operation can't do without, copied
2//! to `<home>/state.mirror` after each committed transaction that changed them, so a store whose
3//! file is damaged can be rebuilt. It carries every run (but its last observation, which a status
4//! read refreshes), every live resource with its recorded id, the operations those reference and
5//! every open one, what the runs' downloads fetched, the schema version and the event cursor.
6//!
7//! The file is written whole and atomically: a temporary file beside it, `fsync`, `rename` over
8//! the mirror, then `fsync` of the folder. A crash leaves the previous mirror or the new one,
9//! never half of one.
10
11use 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
22/// The mirror's file, in the home.
23pub const MIRROR_FILE: &str = "state.mirror";
24
25/// How far the event cursor jumps at a repair past the mirrored one: events written after the
26/// mirror's last write are lost with the damaged file, and no subscriber's cursor may be ahead of
27/// the new store's.
28const CURSOR_MARGIN: i64 = 1_000_000;
29
30/// The run columns the mirror leaves out: what a status read refreshes.
31const NOT_MIRRORED: [&str; 2] = ["observed", "observed_at"];
32
33/// A table's rows, each column by name.
34type Rows = Vec<BTreeMap<String, serde_json::Value>>;
35
36/// What the mirror holds.
37#[derive(Debug, Serialize, Deserialize)]
38struct Mirror {
39    /// The schema version of the store it copies.
40    schema: i64,
41    /// The store's mirror generation when it was written.
42    generation: i64,
43    /// When.
44    written_at: String,
45    /// The newest event's cursor then.
46    events_cursor: i64,
47    /// The runs.
48    runs: Rows,
49    /// The operations the runs and resources reference, and every open one.
50    operations: Rows,
51    /// The live resources.
52    resources: Rows,
53    /// What the runs' downloads fetched (none in a mirror written before they were recorded).
54    #[serde(default)]
55    downloads: Rows,
56}
57
58/// A repair from the mirror: where the damaged store was kept, when the mirror was written, and
59/// what was wrong with the store.
60#[derive(Debug, Clone, PartialEq, Eq)]
61#[non_exhaustive]
62pub struct Recovered {
63    /// Where the damaged file was moved (its `-wal` and `-shm` beside it, with the same suffix).
64    pub corrupt_kept_at: PathBuf,
65    /// When the mirror it was rebuilt from was written.
66    pub mirror_written_at: String,
67    /// What was wrong with the store.
68    pub reason: String,
69}
70
71/// The mirror generation `conn`'s store is at.
72pub(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
76/// `conn`'s rows of `sql`, each column by name (BLOBs aren't in the mirrored tables).
77fn 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
101/// Writes `conn`'s mirror to `path`, at `generation` (read in the same snapshot by the caller).
102///
103/// # Errors
104///
105/// The store can't be read, or the file can't be written.
106pub(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
134/// Writes `contents` to `path` so that a crash leaves the old file or the new one: a temporary
135/// file beside it, flushed to disk, renamed over it, and the folder flushed.
136fn 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
151/// The mirror at `path`, when there is one this runner reads.
152pub(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/// A mirror read back.
164#[derive(Debug)]
165pub(super) struct MirrorFile(Mirror);
166
167impl MirrorFile {
168    /// When it was written.
169    pub(super) fn written_at(&self) -> &str {
170        &self.0.written_at
171    }
172
173    /// Whether it holds anything: a run, an operation, a resource or a download.
174    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    /// The schema version it copies.
179    pub(super) fn schema(&self) -> i64 {
180        self.0.schema
181    }
182
183    /// Puts its rows into `conn`, a store just made at the same schema, in one transaction.
184    ///
185    /// # Errors
186    ///
187    /// A row can't be written (`store_corrupt`: the mirror doesn't fit the schema).
188    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        // The rows reference each other (a run its last operation, an operation the one it
196        // recovered): checked once all are in.
197        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        // An operation one of them recovered, but that the mirror didn't need.
210        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
224/// Inserts `row` into `table`, column by column.
225fn 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}