Skip to main content

griz_store/
lib.rs

1//! Durable journal, locks, and recovery for griz edits.
2//!
3//! The store is the only part of griz that writes source files. Every write is
4//! journaled as `applying` before the first rename, so an interrupted apply is
5//! finished by the next process that opens the store.
6
7mod absorb;
8mod apply;
9mod batch_sync;
10mod blob_batch;
11mod blobs;
12mod committing;
13mod db;
14mod error;
15mod execute;
16mod journal;
17mod listing;
18mod locks;
19mod merge;
20mod parallel;
21mod paths;
22mod plans;
23mod receipts;
24mod recovery;
25mod restore;
26mod restore_selection;
27mod staging;
28mod write;
29
30pub use absorb::Absorbed;
31pub use apply::{ApplyRequest, OnStale, UndoRequest};
32pub use blobs::{blob_id, parse_blob_id};
33pub use error::StoreError;
34pub use journal::{
35    ConflictRegion, FileWrite, MergeConflict, Operation, OperationKind, OperationState, Restores,
36};
37pub use listing::Page;
38pub use paths::{PathResolver, destination_path, directory_path};
39pub use plans::{PlanRecord, Selection};
40pub use receipts::Claim;
41pub use restore::RestoreScope;
42
43use rusqlite::Connection;
44use std::{
45    path::{Path, PathBuf},
46    sync::Mutex,
47};
48
49/// Environment variable naming the state directory.
50pub const HOME_ENV: &str = "GRIZ_HOME";
51
52/// Durable griz state for one home directory.
53pub struct Store {
54    home: PathBuf,
55    conn: Mutex<Connection>,
56}
57
58impl Store {
59    /// Opens the store at `$GRIZ_HOME`, or the user data directory.
60    ///
61    /// # Errors
62    /// Returns an error when the directory or database cannot be opened.
63    pub fn open_default() -> Result<Self, StoreError> {
64        let home = std::env::var_os(HOME_ENV)
65            .map(PathBuf::from)
66            .or_else(|| dirs::data_dir().map(|dir| dir.join("griz")))
67            .ok_or_else(|| StoreError::Invalid("no data directory for griz state".into()))?;
68        Self::open(&home)
69    }
70
71    /// Opens the store at `home` and finishes any interrupted apply.
72    ///
73    /// # Errors
74    /// Returns an error when the directory or database cannot be opened, or
75    /// recovery cannot finish.
76    pub fn open(home: &Path) -> Result<Self, StoreError> {
77        std::fs::create_dir_all(home)?;
78        let conn = db::open(&home.join("griz.sqlite3"))?;
79        let store = Self {
80            home: home.to_path_buf(),
81            conn: Mutex::new(conn),
82        };
83        recovery::recover(&store)?;
84        Ok(store)
85    }
86
87    /// The state directory.
88    #[must_use]
89    pub fn home(&self) -> &Path {
90        &self.home
91    }
92
93    fn with<T>(
94        &self,
95        run: impl FnOnce(&mut Connection) -> Result<T, StoreError>,
96    ) -> Result<T, StoreError> {
97        let mut conn = self
98            .conn
99            .lock()
100            .map_err(|_| StoreError::Invalid("store connection poisoned".into()))?;
101        run(&mut conn)
102    }
103}
104
105/// Reads one JSON body column by identifier.
106fn body_by_id(conn: &Connection, sql: &str, id: &str) -> Result<Option<String>, StoreError> {
107    use rusqlite::OptionalExtension;
108    Ok(conn.query_row(sql, [id], |row| row.get(0)).optional()?)
109}
110
111/// Reads every JSON body column a query returns.
112fn bodies(
113    conn: &Connection,
114    sql: &str,
115    params: impl rusqlite::Params,
116) -> Result<Vec<String>, StoreError> {
117    let mut statement = conn.prepare(sql)?;
118    let rows = statement.query_map(params, |row| row.get(0))?;
119    Ok(rows.collect::<Result<_, _>>()?)
120}
121
122/// Milliseconds since the Unix epoch.
123fn now_ms() -> i64 {
124    std::time::SystemTime::now()
125        .duration_since(std::time::UNIX_EPOCH)
126        .map_or(0, |elapsed| {
127            i64::try_from(elapsed.as_millis()).unwrap_or(i64::MAX)
128        })
129}
130
131/// A new time-ordered identifier with `prefix`.
132fn new_id(prefix: &str) -> String {
133    format!("{prefix}_{}", uuid::Uuid::now_v7().simple())
134}