summaryrefslogtreecommitdiffstats
path: root/src/db/mod.rs
blob: c271fe7c9010200c40c08c240eafc1903e80d653 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
pub mod approvals;
pub mod builds;
pub mod candidates;
pub mod migrations;
pub mod model;
pub mod queries;

pub use migrations::MIGRATIONS;
pub use model::*;

/// Parse a state column into one of the state enums. A value the code does not
/// recognise fails the row instead of becoming a default.
pub(crate) fn state_col<T: StateEnum>(col: usize, text: &str) -> rusqlite::Result<T> {
    T::parse(text).ok_or_else(|| {
        rusqlite::Error::FromSqlConversionFailure(
            col,
            rusqlite::types::Type::Text,
            Box::new(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("{} has a state outside the state machine: {text:?}", T::KIND),
            )),
        )
    })
}

pub use queries::*;

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

use crossbeam_channel::{bounded, unbounded, Sender};
use rusqlite::Connection;

use crate::config::Config;
use crate::error::{Error, Result};

/// Open a connection with the pragmas every connection needs.
fn open(path: &Path, read_only: bool) -> Result<Connection> {
    let conn = if read_only {
        Connection::open_with_flags(
            path,
            rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
        )
    } else {
        Connection::open(path)
    }
    .map_err(|e| Error::db(format!("open {}: {e}", path.display())))?;
    configure(&conn, read_only)?;
    Ok(conn)
}

fn configure(conn: &Connection, read_only: bool) -> Result<()> {
    conn.pragma_update(None, "journal_mode", "WAL")
        .and_then(|_| conn.pragma_update(None, "busy_timeout", 5000))
        .and_then(|_| conn.pragma_update(None, "foreign_keys", "ON"))
        .map_err(|e| Error::db(e.to_string()))?;
    if !read_only {
        // Durability of the approval trail is worth the fsync (§11a).
        conn.pragma_update(None, "synchronous", "FULL")
            .map_err(|e| Error::db(e.to_string()))?;
    }
    Ok(())
}

/// Apply pending migrations. Must run before the writer actor starts.
pub fn migrate(path: &Path) -> Result<u32> {
    let mut conn = open(path, false)?;
    let mut applied = 0u32;
    let current: u32 = conn
        .pragma_query_value(None, "user_version", |r| r.get(0))
        .map_err(|e| Error::db(e.to_string()))?;
    for m in migrations::MIGRATIONS {
        if m.version > current {
            let tx = conn
                .transaction()
                .map_err(|e| Error::db(e.to_string()))?;
            tx.execute_batch(m.sql)
                .map_err(|e| Error::db(format!("migration {} ({}): {e}", m.version, m.name)))?;
            tx.pragma_update(None, "user_version", m.version)
                .map_err(|e| Error::db(e.to_string()))?;
            tx.commit().map_err(|e| Error::db(e.to_string()))?;
            applied += 1;
        }
    }
    if applied > 0 {
        let mut stmt = conn
            .prepare("INSERT OR IGNORE INTO settings (key, value) VALUES (?1, ?2)")
            .map_err(|e| Error::db(e.to_string()))?;
        for (k, v) in migrations::DEFAULT_SETTINGS {
            let _ = stmt.execute(rusqlite::params![k, *v]);
        }
    }
    Ok(applied)
}

type BoxedCall = Box<dyn FnOnce(&mut Connection) + Send>;

enum Msg {
    Call(BoxedCall),
    Shutdown,
}

/// Handle on the single writer thread.
///
/// Cheap to clone; every clone talks to the same actor.
pub struct Writer {
    tx: Sender<Msg>,
    path: PathBuf,
    alive: Arc<AtomicBool>,
}

impl Writer {
    /// Spawn the writer actor thread.
    pub fn start(path: &Path) -> Result<Self> {
        let conn = open(path, false)?;
        let (tx, rx) = unbounded::<Msg>();
        let alive = Arc::new(AtomicBool::new(true));
        let alive_thread = alive.clone();
        let thread_path = path.to_path_buf();
        std::thread::Builder::new()
            .name("db-writer".into())
            .spawn(move || {
                let mut conn = conn;
                alive_thread.store(true, Ordering::SeqCst);
                for msg in rx.iter() {
                    match msg {
                        Msg::Call(f) => f(&mut conn),
                        Msg::Shutdown => break,
                    }
                }
                // Best-effort WAL checkpoint on the way out.
                let _ = conn.pragma_update(None, "wal_checkpoint", "TRUNCATE");
                alive_thread.store(false, Ordering::SeqCst);
            })
            .map_err(|e| Error::db(format!("spawn writer: {e}")))?;
        Ok(Self { tx, path: thread_path, alive })
    }

    pub fn path(&self) -> &Path {
        &self.path
    }

    pub fn is_alive(&self) -> bool {
        self.alive.load(Ordering::SeqCst)
    }

    /// Run `f` on the write connection and wait for its result. No transaction
    /// may span a build step: `f` should be short.
    ///
    /// `pub(crate)`, not `pub`: the schema has one owner, this module (§6 M-1).
    /// Inside the crate the convention is enforced by
    /// `tests/schema_ownership.rs`, which fails the build if a SQL statement
    /// appears outside `src/db/`.
    pub(crate) fn call<T>(&self, f: impl FnOnce(&mut Connection) -> Result<T> + Send + 'static) -> Result<T>
    where
        T: Send + 'static,
    {
        let (reply_tx, reply_rx) = bounded::<Result<T>>(1);
        self.send(Box::new(move |conn| {
            let _ = reply_tx.send(f(conn));
        }))?;
        reply_rx
            .recv()
            .map_err(|_| Error::db("writer actor gone"))?
    }

    /// Run `f` inside a single `BEGIN IMMEDIATE` transaction.
    pub(crate) fn tx<T>(
        &self,
        f: impl FnOnce(&mut rusqlite::Transaction<'_>) -> Result<T> + Send + 'static,
    ) -> Result<T>
    where
        T: Send + 'static,
    {
        self.call(move |conn| {
            let mut tx = conn
                .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
                .map_err(|e| Error::db(e.to_string()))?;
            let out = f(&mut tx)?;
            tx.commit().map_err(|e| Error::db(e.to_string()))?;
            Ok(out)
        })
    }

    /// Fire-and-forget write (audit rows, bookkeeping where the result is unused).
    pub(crate) fn send(&self, f: BoxedCall) -> Result<()> {
        if !self.is_alive() {
            return Err(Error::db("writer actor gone"));
        }
        self.tx
            .send(Msg::Call(f))
            .map_err(|_| Error::db("writer actor gone"))
    }

    pub fn shutdown(&self) {
        let _ = self.tx.send(Msg::Shutdown);
    }
}

/// The raw-SQL door, open only for the test harness (§6 M-9). A fixture
/// sometimes has to reach a state the typed API only reaches through several
/// steps, but that is not a reason to leave the door unlocked in the binary an
/// operator runs.
#[cfg(feature = "test-support")]
impl Writer {
    pub fn tx_for_tests<T>(
        &self,
        f: impl FnOnce(&mut rusqlite::Transaction<'_>) -> Result<T> + Send + 'static,
    ) -> Result<T>
    where
        T: Send + 'static,
    {
        self.tx(f)
    }

    pub fn call_for_tests<T>(&self, f: impl FnOnce(&mut Connection) -> Result<T> + Send + 'static) -> Result<T>
    where
        T: Send + 'static,
    {
        self.call(f)
    }
}

/// Thread-local read-only connection pool: one connection per thread per
/// database file. HTTP handlers and watchers use this; they never touch the
/// write connection.
pub struct Readers {
    path: PathBuf,
}

thread_local! {
    static POOL: std::cell::RefCell<Vec<(PathBuf, Connection)>> = const { std::cell::RefCell::new(Vec::new()) };
}

impl Readers {
    pub fn new(path: &Path) -> Self {
        Self { path: path.to_path_buf() }
    }

    /// Run `f` against this thread's read-only connection.
    pub fn with<T>(&self, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
        let path = self.path.clone();
        POOL.with(|pool| {
            let mut pool = pool.borrow_mut();
            if pool.iter().position(|(p, _)| p == &path).is_none() {
                pool.push((path.clone(), open(&path, true)?));
            }
            let idx = pool
                .iter()
                .position(|(p, _)| p == &path)
                .ok_or_else(|| Error::db("reader pool lost entry"))?;
            // We only ever use one connection at a time per thread, and `f`
            // receives &Connection rather than &Readers, so it cannot re-enter.
            let conn = &pool[idx].1;
            f(conn)
        })
    }
}

/// A handle bundling the writer with a reader factory; passed around as `App`.
#[derive(Clone)]
pub struct Db {
    pub writer: Arc<Writer>,
    pub readers: Arc<Readers>,
}

impl Db {
    pub fn open(cfg: &Config) -> Result<Self> {
        let path = cfg.db_path();
        migrate(&path)?;
        Self::open_migrated(&path)
    }

    pub fn open_migrated(path: &Path) -> Result<Self> {
        Ok(Self {
            writer: Arc::new(Writer::start(path)?),
            readers: Arc::new(Readers::new(path)),
        })
    }

    /// Convenience: read-only query against the shared reader pool.
    pub fn read<T>(&self, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
        self.readers.with(f)
    }
}

/// Consistent snapshot for backups: `VACUUM INTO`, never `cp` of a live WAL db.
pub fn backup_to(writer: &Writer, dest: &Path) -> Result<()> {
    let dest_s = dest.display().to_string();
    writer.call(move |conn| {
        conn.execute("VACUUM INTO ?1", rusqlite::params![dest_s])
            .map_err(|e| Error::db(e.to_string()))?;
        Ok(())
    })
}

/// The schema version a database file reports. A backup that does not answer
/// with a migrated schema is a file, not a backup.
///
/// Opened read-write and untouched by the connection pragmas: a WAL database
/// cannot even be opened read-only.
pub fn schema_version(path: &Path) -> Result<i64> {
    let conn = rusqlite::Connection::open(path)
        .map_err(|e| Error::db(format!("{} does not open: {e}", path.display())))?;
    conn.query_row("PRAGMA user_version", [], |r| r.get(0))
        .map_err(|e| Error::db(format!("{} has no schema version: {e}", path.display())))
}

pub fn wal_stats(db: &Db) -> (u64, u64) {
    let db_file = std::fs::metadata(db.writer.path()).map(|m| m.len()).unwrap_or(0);
    let mut wal = db.writer.path().as_os_str().to_os_string();
    wal.push("-wal");
    let wal_file = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0);
    (db_file, wal_file)
}