Skip to main content

kernable/
store.rs

1//! A read model's store: a key-value store with namespaces in a SQLite file (or in memory),
2//! with the tables of the other SDKs' stores. The listener writes its data and its position in
3//! one transaction per batch, so after a crash every event has taken effect exactly once, and a
4//! restart continues where it left off instead of replaying everything.
5
6use std::sync::{
7    Arc, Mutex,
8    atomic::{AtomicU64, Ordering},
9};
10
11use rusqlite::{Connection, OptionalExtension, params};
12use serde::{Serialize, de::DeserializeOwned};
13
14use crate::Error;
15
16/// A listener's store: JSON values under keys, grouped in namespaces (`ns`), in a SQLite file or
17/// in memory; see [`crate::Listener::store`]. Cloning gives another handle to it. Handlers get
18/// it as `ctx.store`: `if let Some(store) = &ctx.store { store.set("carts", &evt.aggregate_id,
19/// &row)?; }`. What an event handler writes takes effect together with the listener's
20/// position, once per batch. Errors are [`Error::Store`] (SQLite) or [`Error::Json`].
21#[derive(Clone)]
22pub struct Store {
23    /// `None` once closed.
24    db: Arc<Mutex<Option<Connection>>>,
25    committed: Arc<AtomicU64>,
26    /// Batches take turns: with partitions, several streams share the store.
27    turns: Arc<tokio::sync::Mutex<()>>,
28}
29
30impl std::fmt::Debug for Store {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        f.write_str("Store")
33    }
34}
35
36impl Store {
37    /// Opens `url` (`sqlite:<path>`, a bare path, or `memory:`). If the stored data was built
38    /// at another `schema`, it is cleared and the read model rebuilds from the first event.
39    pub fn open(url: &str, schema: &str) -> Result<Store, Error> {
40        let db = if url == "memory:" {
41            Connection::open_in_memory()?
42        } else {
43            Connection::open(url.strip_prefix("sqlite:").unwrap_or(url))?
44        };
45        db.execute_batch(
46            "PRAGMA journal_mode = WAL;
47             PRAGMA secure_delete = ON;
48             CREATE TABLE IF NOT EXISTS data (ns TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY (ns, key));
49             CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);",
50        )?;
51        // A crash after a batch that erased a subject, before the log was emptied, left the
52        // removed values' old pages in it: empty it before anything else.
53        truncate(&db)?;
54        let meta = |key: &str| -> Result<Option<String>, rusqlite::Error> {
55            db.query_row("SELECT value FROM meta WHERE key = ?", [key], |r| r.get(0))
56                .optional()
57        };
58        if meta("schema")?.as_deref() != Some(schema) {
59            db.execute_batch(
60                "BEGIN; DELETE FROM data; DELETE FROM meta WHERE key LIKE 'position:%';",
61            )?;
62            db.execute(
63                "INSERT OR REPLACE INTO meta (key, value) VALUES ('schema', ?), ('position', '0')",
64                [schema],
65            )?;
66            db.execute_batch("COMMIT")?;
67        }
68        let committed = meta("position")?.and_then(|p| p.parse().ok()).unwrap_or(0);
69        Ok(Store {
70            db: Arc::new(Mutex::new(Some(db))),
71            committed: Arc::new(AtomicU64::new(committed)),
72            turns: Arc::default(),
73        })
74    }
75
76    /// The position up to which the stored data is complete.
77    pub fn committed(&self) -> u64 {
78        self.committed.load(Ordering::SeqCst)
79    }
80
81    /// The position up to which the data is complete for the events of partition `part`: every
82    /// partition has its own positions. `""`: a kernel without partitions.
83    pub fn committed_for(&self, part: &str) -> Result<u64, Error> {
84        if part.is_empty() {
85            return Ok(self.committed());
86        }
87        let value: Option<String> = self.with(|db| {
88            db.query_row(
89                "SELECT value FROM meta WHERE key = ?",
90                [format!("position:{part}")],
91                |r| r.get(0),
92            )
93            .optional()
94        })?;
95        Ok(value.and_then(|v| v.parse().ok()).unwrap_or(0))
96    }
97
98    /// Waits for the store's turn: one batch at a time, of whichever partition.
99    pub(crate) async fn turn(&self) -> tokio::sync::OwnedMutexGuard<()> {
100        Arc::clone(&self.turns).lock_owned().await
101    }
102
103    /// `f` on the connection; [`Error::Store`] if the store is closed.
104    fn with<T>(&self, f: impl FnOnce(&Connection) -> rusqlite::Result<T>) -> Result<T, Error> {
105        let db = self.db.lock().unwrap();
106        let db = db.as_ref().ok_or_else(|| {
107            rusqlite::Error::SqliteFailure(
108                rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_MISUSE),
109                Some("the store is closed".into()),
110            )
111        })?;
112        Ok(f(db)?)
113    }
114
115    /// The value under `key` in namespace `ns` as a `T`; `None` if there is none.
116    pub fn get<T: DeserializeOwned>(&self, ns: &str, key: &str) -> Result<Option<T>, Error> {
117        let value: Option<String> = self.with(|db| {
118            db.query_row(
119                "SELECT value FROM data WHERE ns = ? AND key = ?",
120                [ns, key],
121                |r| r.get(0),
122            )
123            .optional()
124        })?;
125        Ok(value.map(|v| serde_json::from_str(&v)).transpose()?)
126    }
127
128    /// Stores `value` as JSON under `key` in namespace `ns`, replacing a value there.
129    pub fn set<T: Serialize + ?Sized>(&self, ns: &str, key: &str, value: &T) -> Result<(), Error> {
130        let value = serde_json::to_string(value)?;
131        self.with(|db| {
132            db.execute(
133                "INSERT OR REPLACE INTO data (ns, key, value) VALUES (?, ?, ?)",
134                params![ns, key, value],
135            )
136        })?;
137        Ok(())
138    }
139
140    /// Removes the value under `key` in namespace `ns`, if there is one.
141    pub fn remove(&self, ns: &str, key: &str) -> Result<(), Error> {
142        self.with(|db| db.execute("DELETE FROM data WHERE ns = ? AND key = ?", [ns, key]))?;
143        Ok(())
144    }
145
146    /// Every key and value of a namespace, ordered by key.
147    pub fn all<T: DeserializeOwned>(&self, ns: &str) -> Result<Vec<(String, T)>, Error> {
148        let rows = self.with(|db| {
149            db.prepare("SELECT key, value FROM data WHERE ns = ? ORDER BY key")?
150                .query_map([ns], |r| {
151                    Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))
152                })?
153                .collect::<Result<Vec<_>, _>>()
154        })?;
155        rows.into_iter()
156            .map(|(k, v)| Ok((k, serde_json::from_str(&v)?)))
157            .collect()
158    }
159
160    /// Clears a namespace, or all data.
161    pub fn reset(&self, ns: Option<&str>) -> Result<(), Error> {
162        self.with(|db| match ns {
163            Some(ns) => db.execute("DELETE FROM data WHERE ns = ?", [ns]),
164            None => db.execute("DELETE FROM data", []),
165        })?;
166        Ok(())
167    }
168
169    /// Starts a batch, dropping what is left of one that never ended (its future was dropped).
170    pub(crate) fn begin(&self) -> Result<(), Error> {
171        self.with(|db| {
172            if !db.is_autocommit() {
173                db.execute_batch("ROLLBACK")?;
174            }
175            db.execute_batch("BEGIN")
176        })
177    }
178
179    /// Ends a batch: its data and `position` (of partition `part`, see [`Store::committed_for`]) take effect together. After a batch that
180    /// `erased` a subject, the write-ahead log is emptied too: it still holds the pages from
181    /// before the handlers removed the subject's data.
182    pub(crate) fn commit_part(&self, position: u64, erased: bool, part: &str) -> Result<(), Error> {
183        self.with(|db| {
184            if part.is_empty() {
185                db.execute(
186                    "UPDATE meta SET value = ? WHERE key = 'position'",
187                    [position.to_string()],
188                )?;
189            } else {
190                db.execute(
191                    "INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",
192                    [format!("position:{part}"), position.to_string()],
193                )?;
194            }
195            db.execute_batch("COMMIT")?;
196            if erased {
197                truncate(db)?;
198            }
199            Ok(())
200        })?;
201        if part.is_empty() {
202            self.committed.store(position, Ordering::SeqCst);
203        }
204        Ok(())
205    }
206
207    /// Marks where an event's writes begin within a batch, so they can be dropped alone.
208    pub(crate) fn savepoint(&self) -> Result<(), Error> {
209        self.with(|db| db.execute_batch("SAVEPOINT event"))
210    }
211
212    /// Keeps the event's writes (see [`Store::savepoint`]).
213    pub(crate) fn release(&self) -> Result<(), Error> {
214        self.with(|db| db.execute_batch("RELEASE event"))
215    }
216
217    /// Drops the event's writes, keeping the rest of the batch (see [`Store::savepoint`]).
218    pub(crate) fn rollback_event(&self) -> Result<(), Error> {
219        self.with(|db| db.execute_batch("ROLLBACK TO event; RELEASE event"))
220    }
221
222    /// Drops a failed batch.
223    pub(crate) fn rollback(&self) {
224        let _ = self.with(|db| {
225            if !db.is_autocommit() {
226                db.execute_batch("ROLLBACK")?;
227            }
228            Ok(())
229        });
230    }
231
232    /// Closes the store for every handle to it: a batch still open is dropped, the
233    /// write-ahead log emptied into the file (so data removed is gone from disk too), and the
234    /// file released. Using it afterwards is an [`Error::Store`]. A listener closes its store
235    /// when its `run()` ends; a later run opens it again.
236    pub fn close(&self) {
237        if let Some(db) = self.db.lock().unwrap().take() {
238            if !db.is_autocommit() {
239                let _ = db.execute_batch("ROLLBACK");
240            }
241            let _ = truncate(&db);
242            let _ = db.close();
243        }
244    }
245}
246
247/// Moves the write-ahead log into the database file and truncates it to zero bytes.
248fn truncate(db: &Connection) -> rusqlite::Result<()> {
249    db.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
250}