tinystore 0.2.0-rc.1

A small storage runtime for applications on SQLite: SQL, key-value state, durable jobs, files, search, logs and metrics in one directory
Documentation
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! Transactions as the handles they take in see them. The store's `store.tx`
//! and a database's `db.tx` each run one, and `tx.with(&handle)` runs a
//! bucket's or a queue's calls in it, so that what they write commits with the
//! rest or not at all.
//!
//! ```no_run
//! # fn main() -> tinystore::Result<()> {
//! # let store = tinystore::Store::open("data", Default::default())?;
//! let stock = store.bucket::<i64>("stock").open()?;
//! let orders = store.bucket::<String>("orders").open()?;
//! let placed = store.tx(|tx| -> tinystore::Result<bool> {
//!     let left = tx.with(&stock).get("sku-1")?.unwrap_or(0);
//!     if left < 1 {
//!         return Ok(false); // sold out: nothing written
//!     }
//!     tx.with(&stock).set("sku-1", &(left - 1))?;
//!     tx.with(&orders).set("order-7", &"sku-1".to_owned())?;
//!     Ok(true)
//! })?;
//! # Ok(())
//! # }
//! ```

use std::cell::RefCell;
use std::fmt;
#[cfg(any(feature = "kv", feature = "jobs"))]
use std::sync::Arc;

#[cfg(any(feature = "kv", feature = "jobs"))]
use crate::Store;
#[cfg(any(feature = "kv", feature = "jobs"))]
use crate::sqlite::{Begun, Committed, Mark};
use crate::sqlite::{File, Left, Tx as SqlTx, refuse_when_rolled_back, sql_error};
use crate::{Error, Result};

const SAVEPOINT: &str = "savepoint call";
const RELEASE: &str = "release call";
const ROLLBACK_TO: &str = "rollback to call";

#[cfg(any(feature = "kv", feature = "jobs"))]
impl Store {
    /// Runs `work` in one transaction of one of the store's own files, kv.db
    /// or jobs.db: the file of the first handle `tx.with` takes in, whose
    /// writer it then holds alone, so that what it reads cannot change before
    /// it writes. Two orders cannot both take the last item, and a hundred
    /// jobs are added together or not at all. It commits when `work` returns
    /// `Ok` and rolls back when it returns an error or panics.
    ///
    /// Inside, every call on the store's buckets and queues goes through the
    /// transaction, `tx.with(&bucket)`: one made around it would not see what
    /// it wrote, or would wait for the writer it holds, and fails `Invalid`
    /// instead. A bucket and a queue of the store are two files, and no write
    /// is atomic across two: a handle kept in another file than the first is
    /// `Invalid`, and to commit keys and jobs together a program opens both
    /// from a database. Writes that need no reads need no transaction, since
    /// separate calls already share commits.
    pub fn tx<T, E: From<Error>>(&self, work: impl FnOnce(&Tx<'_>) -> Result<T, E>) -> Result<T, E> {
        self.refuse_when_closed("a transaction")?;
        let files = self.engine_files();
        Transaction::of_store(&files, |transaction| work(&Tx { transaction }))
    }
}

/// A transaction of the store, given to the function [`Store::tx`] runs.
#[cfg(any(feature = "kv", feature = "jobs"))]
pub struct Tx<'a> {
    transaction: &'a Transaction<'a>,
}

#[cfg(any(feature = "kv", feature = "jobs"))]
impl Tx<'_> {
    /// The calls of `handle` inside this transaction: what they read sees what
    /// the transaction wrote, and what they write commits with it or not at
    /// all. A handle kept in another file is refused at its first call.
    pub fn with<'h, H: TxHandle>(&'h self, handle: &'h H) -> H::InTx<'h> {
        handle.in_tx(self.transaction)
    }

    /// The transaction itself, for the wire's calls in it: a queue's batch.
    #[cfg(all(feature = "wire", feature = "jobs"))]
    pub(crate) fn transaction(&self) -> &Transaction<'_> {
        self.transaction
    }
}

#[cfg(any(feature = "kv", feature = "jobs"))]
impl fmt::Debug for Tx<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Tx")
    }
}

/// A transaction as the handles it takes in see it: the writer it holds, the
/// file a handle must be kept in, the bound it ends within, and what runs
/// once it ends.
pub struct Transaction<'t> {
    writer: &'t dyn Writer,
    bound: Option<&'t dyn Fn() -> Result<()>>,
    #[cfg_attr(not(feature = "jobs"), expect(dead_code, reason = "only a queue asks for what runs once it ends"))]
    ended: &'t Ended,
}

impl Transaction<'_> {
    /// Runs `work` in a transaction of `file` that holds its writer alone,
    /// then what the calls inside asked to run once it ended. A bound, when
    /// there is one, fails every call past it and the commit.
    #[cfg(feature = "sql")]
    pub(crate) fn run<T, E: From<Error>>(
        file: &File,
        owner: &str,
        bound: Option<&dyn Fn() -> Result<()>>,
        work: impl FnOnce(&Transaction<'_>) -> Result<T, E>,
    ) -> Result<T, E> {
        if file.is_copy() {
            return Err(crate::sqlite::a_copy_takes_no_transaction(owner).into());
        }
        let ended = Ended::default();
        let outcome = file.transaction(|raw| {
            let writer = OneFile { raw, file, owner };
            let transaction = Transaction { writer: &writer, bound, ended: &ended };
            let value = work(&transaction)?;
            transaction.within_bound()?;
            Ok(value)
        });
        ended.finish(outcome.is_ok());
        outcome
    }

    /// Runs `work` in a transaction of whichever of the store's `files` its
    /// first handle is kept in, begun when that handle makes its first call.
    /// The thread is marked for all of them from the start, so that a call
    /// around the transaction is refused whichever it turns out to be of.
    #[cfg(any(feature = "kv", feature = "jobs"))]
    fn of_store<T, E: From<Error>>(
        files: &[Arc<File>],
        work: impl FnOnce(&Transaction<'_>) -> Result<T, E>,
    ) -> Result<T, E> {
        let ended = Ended::default();
        let outcome = (|| {
            let marks = files.iter().map(|file| file.mark()).collect::<Result<Vec<_>>>()?;
            let writer = OfStore { files, begun: RefCell::new(None), marks, early: Committed::default() };
            let value = work(&Transaction { writer: &writer, bound: None, ended: &ended })?;
            writer.commit()?;
            Ok(value)
        })();
        ended.finish(outcome.is_ok());
        outcome
    }

    /// Runs one call in a savepoint of the transaction, rolled back when the
    /// call fails, once the transaction is still within its bound: a call that
    /// fails leaves the transaction as it was before the call.
    pub(crate) fn call<T>(&self, work: impl FnOnce(&SqlTx<'_>) -> Result<T>) -> Result<T> {
        self.within_bound()?;
        let (mut work, mut value) = (Some(work), None);
        self.writer.on(&mut |raw| {
            let work = work.take().ok_or_else(|| Error::internal("a transaction's call ran twice"))?;
            refuse_when_rolled_back(raw)?;
            value = Some(in_savepoint(raw, || {
                let value = work(raw)?;
                raw.settle(Left::Here)?;
                Ok(value)
            })?);
            Ok(())
        })?;
        value.ok_or_else(|| Error::internal("a transaction's call did not run"))
    }

    /// Runs `hook` once the transaction commits, while its writer is still
    /// held, so that what commits of one file hand over comes in their order;
    /// a rollback runs nothing. A transaction of the store that took no
    /// handle in yet runs it at its commit, or when its function returns, if
    /// it never began on a file.
    #[cfg(feature = "channels")]
    pub(crate) fn after_commit(&self, hook: Box<dyn FnOnce()>) {
        self.writer.after_commit(hook);
    }

    /// Refuses a handle kept in another file than the transaction's, `place`:
    /// what it wrote would not commit with the rest.
    #[cfg(any(feature = "kv", feature = "jobs", feature = "search"))]
    pub(crate) fn takes(&self, file: &File, place: &str) -> Result<()> {
        self.writer.takes(file, place)
    }

    /// Runs `hook` once the transaction ends, told whether it committed: a
    /// queue wakes its workers only for jobs that are there to find.
    #[cfg(feature = "jobs")]
    pub(crate) fn after(&self, hook: impl FnOnce(bool) + 'static) {
        self.ended.0.borrow_mut().push(Box::new(hook));
    }

    pub(crate) fn within_bound(&self) -> Result<()> {
        self.bound.map_or(Ok(()), |bound| bound())
    }
}

impl fmt::Debug for Transaction<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Transaction")
    }
}

/// What holds a transaction's writer and says which file it is of.
trait Writer {
    /// Refuses a handle kept in another file than the transaction's.
    #[cfg(any(feature = "kv", feature = "jobs", feature = "search"))]
    fn takes(&self, file: &File, place: &str) -> Result<()>;

    /// Runs `work` on the writer the transaction holds.
    fn on(&self, work: &mut dyn FnMut(&SqlTx<'_>) -> Result<()>) -> Result<()>;

    /// Keeps `hook` for after the commit.
    #[cfg(feature = "channels")]
    fn after_commit(&self, hook: Box<dyn FnOnce()>);
}

/// The writer of a transaction that began on its file before its function
/// ran: a database's.
#[cfg(feature = "sql")]
struct OneFile<'t> {
    raw: &'t SqlTx<'t>,
    #[cfg_attr(
        not(any(feature = "kv", feature = "jobs", feature = "search")),
        expect(dead_code, reason = "only kv's, jobs' and search's handles ask whether they are kept in a file")
    )]
    file: &'t File,
    /// What an error calls the file: `sql app`.
    #[cfg_attr(
        not(any(feature = "kv", feature = "jobs", feature = "search")),
        expect(dead_code, reason = "only kv's, jobs' and search's handles ask whether they are kept in a file")
    )]
    owner: &'t str,
}

#[cfg(feature = "sql")]
impl Writer for OneFile<'_> {
    #[cfg(any(feature = "kv", feature = "jobs", feature = "search"))]
    fn takes(&self, file: &File, place: &str) -> Result<()> {
        if std::ptr::eq(self.file, file) {
            return Ok(());
        }
        Err(Error::invalid(format!("kept in {place}, outside this transaction of {}", self.owner)))
    }

    fn on(&self, work: &mut dyn FnMut(&SqlTx<'_>) -> Result<()>) -> Result<()> {
        work(self.raw)
    }

    #[cfg(feature = "channels")]
    fn after_commit(&self, hook: Box<dyn FnOnce()>) {
        self.raw.after_commit(hook);
    }
}

/// The writer of the store's transaction, which begins on the file of the
/// first handle it takes in, one of the store's own.
#[cfg(any(feature = "kv", feature = "jobs"))]
struct OfStore<'f> {
    files: &'f [Arc<File>],
    /// The transaction once it began, and what an error calls it: the place of
    /// the first handle it took in, such as `kv bucket sessions`.
    begun: RefCell<Option<(Begun<'f>, String)>>,
    /// This thread marked inside a transaction of each file, in their order.
    marks: Vec<Mark>,
    /// What asked to run after the commit before the transaction began.
    early: Committed,
}

#[cfg(any(feature = "kv", feature = "jobs"))]
impl OfStore<'_> {
    fn commit(&self) -> Result<()> {
        match self.begun.borrow_mut().take() {
            Some((begun, _)) => begun.commit(),
            None => {
                self.early.run();
                Ok(())
            }
        }
    }
}

#[cfg(any(feature = "kv", feature = "jobs"))]
impl Writer for OfStore<'_> {
    fn takes(&self, file: &File, place: &str) -> Result<()> {
        let mut begun = self.begun.borrow_mut();
        if let Some((held, owner)) = begun.as_ref() {
            if std::ptr::eq(held.file(), file) {
                return Ok(());
            }
            return Err(Error::invalid(format!("kept in {place}, outside this transaction of {owner}")));
        }
        let Some(at) = self.files.iter().position(|own| std::ptr::eq(&**own, file)) else {
            return Err(Error::invalid(format!(
                "kept in {place}, which this store's transaction does not hold: a database's handle joins its db.tx"
            )));
        };
        let began = self.files[at].begin(&self.marks[at])?;
        #[cfg(feature = "channels")]
        began.tx().committed().append(self.early.take());
        *begun = Some((began, place.to_owned()));
        Ok(())
    }

    fn on(&self, work: &mut dyn FnMut(&SqlTx<'_>) -> Result<()>) -> Result<()> {
        let begun = self.begun.borrow();
        let Some((begun, _)) = begun.as_ref() else {
            return Err(Error::internal("a call in a transaction that took no handle in"));
        };
        work(&begun.tx())
    }

    #[cfg(feature = "channels")]
    fn after_commit(&self, hook: Box<dyn FnOnce()>) {
        match self.begun.borrow().as_ref() {
            Some((begun, _)) => begun.tx().after_commit(hook),
            None => self.early.push(hook),
        }
    }
}

/// Runs `work` in a savepoint, kept when it succeeds and rolled back when it
/// fails. A call that ended the transaction, which SQLite then rolled back
/// whole, fails with its own failure.
fn in_savepoint<T>(raw: &SqlTx<'_>, work: impl FnOnce() -> Result<T>) -> Result<T> {
    let failed = |error| sql_error("a call's savepoint", error);
    raw.execute_batch(SAVEPOINT).map_err(failed)?;
    let mark = raw.committed().mark();
    let outcome = work();
    if raw.is_autocommit() {
        raw.committed().take_back(mark);
        return outcome.and_then(|value| refuse_when_rolled_back(raw).map(|()| value));
    }
    match outcome {
        Ok(value) => raw.execute_batch(RELEASE).map_err(failed).map(|()| value),
        Err(error) => {
            raw.committed().take_back(mark);
            // The work's own failure is the answer; one of the rollback
            // after it only says why the transaction cannot go on.
            match raw.execute_batch(ROLLBACK_TO).and_then(|()| raw.execute_batch(RELEASE)) {
                Ok(()) => Err(error),
                Err(rollback) => Err(error.within(format!("a savepoint not rolled back ({rollback})"))),
            }
        }
    }
}

/// What runs once a transaction ends, told whether it committed.
type Hook = Box<dyn FnOnce(bool)>;

/// What runs once a transaction ends. A transaction that panicked tells it
/// that it did not commit, as it rolls back.
#[derive(Default)]
struct Ended(RefCell<Vec<Hook>>);

impl Ended {
    fn finish(&self, committed: bool) {
        let hooks = std::mem::take(&mut *self.0.borrow_mut());
        for hook in hooks {
            hook(committed);
        }
    }
}

impl Drop for Ended {
    fn drop(&mut self) {
        self.finish(false);
    }
}

/// A handle a transaction of its file takes in with `tx.with(&handle)`: a
/// bucket or counters, and a queue, from the store or from a database.
pub trait TxHandle: sealed::Sealed {
    /// The handle's calls inside a transaction.
    type InTx<'t>
    where
        Self: 't;

    #[doc(hidden)]
    fn in_tx<'t>(&'t self, tx: &'t Transaction<'t>) -> Self::InTx<'t>;
}

/// A handle held by reference joins as the handle does.
impl<H: TxHandle + ?Sized> TxHandle for &H {
    type InTx<'t>
        = H::InTx<'t>
    where
        Self: 't;

    fn in_tx<'t>(&'t self, tx: &'t Transaction<'t>) -> H::InTx<'t> {
        (**self).in_tx(tx)
    }
}

/// Sealed: a public bound that no other crate can implement. Each engine
/// seals its own handles.
pub(crate) mod sealed {
    pub trait Sealed {}

    impl<H: Sealed + ?Sized> Sealed for &H {}
}

#[cfg(test)]
#[path = "transaction_tests.rs"]
mod tests;