tinystore 0.5.0

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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//! What every handle of one config in a process shares: the changes kept in
//! kv.db and the config's version, read once and then moved by each change,
//! and the handles that follow them. A change reaches every handle from here,
//! once, however many handles and watchers the process holds.
//!
//! A config loaded without a store has a hub of its own with no kv.db behind
//! it: it keeps no change, and a change it is asked to keep is refused.

use std::collections::BTreeMap;
use std::sync::{Arc, Mutex, Weak};

use rusqlite::{Connection, OptionalExtension, params};
use serde_json::Value;

use super::declaration::Declaration;
use crate::kv::engine::{Kv, next_version};
use crate::limits::CONFIG_BYTES;
#[cfg(feature = "async")]
use crate::polled::Lead;
use crate::sqlite::{Tx, sql_error};
use crate::sync::lock;
use crate::{Error, ErrorKind, Result};

const SELECT_CONFIG: &str = "select version, declaration from _tinystore_kv_configs where name = ?1";
#[cfg(feature = "client")]
const SELECT_NAMES: &str = "select name from _tinystore_kv_configs where declaration is not null order by name";
const SELECT_CHANGES: &str = "select path, value, version, at from _tinystore_kv_config_changes where name = ?1";
const KEEP_VERSION: &str = "insert into _tinystore_kv_configs (name, version) values (?1, ?2)
    on conflict (name) do update set version = excluded.version";
const KEEP_DECLARATION: &str = "insert into _tinystore_kv_configs (name, version, declaration) values (?1, 0, ?2)
    on conflict (name) do update set declaration = excluded.declaration";
const UPSERT_CHANGE: &str = "insert into _tinystore_kv_config_changes (name, path, value, version, at)
    values (?1, ?2, ?3, ?4, ?5)
    on conflict (name, path) do update set value = excluded.value, version = excluded.version, at = excluded.at";
const DELETE_UNDER: &str = "delete from _tinystore_kv_config_changes
    where name = ?1 and (?2 = '' or path = ?2 or substr(path, 1, length(?2) + 1) = ?2 || '.')";
const KEPT_BYTES: &str = "select coalesce(sum(length(cast(path as blob)) + length(cast(value as blob))), 0)
    from _tinystore_kv_config_changes where name = ?1";

/// What a config keeps of its changes, all of them together.
const MOST_KEPT: i64 = CONFIG_BYTES.bound as i64;

/// The changes a config keeps, by the setting's path, and the version that
/// last moved them.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct Kept {
    pub(crate) version: i64,
    pub(crate) changes: BTreeMap<String, Change>,
}

#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Change {
    pub(crate) value: Value,
    /// The config's version that made it.
    pub(crate) version: i64,
    /// When, in unix milliseconds.
    pub(crate) at: i64,
}

impl Kept {
    /// The changes in the order they were made.
    pub(crate) fn in_order(&self) -> Vec<(&String, &Change)> {
        let mut changes: Vec<_> = self.changes.iter().collect();
        changes.sort_by_key(|(_, change)| change.version);
        changes
    }
}

/// A handle of the config, as its hub sees it.
pub(super) trait Follower: Send + Sync {
    fn declaration(&self) -> &Declaration;

    /// Takes the changes as they are once committed; a handle that has seen
    /// a later version ignores them.
    fn follow(&self, kept: &Arc<Kept>);
}

pub(crate) struct Hub {
    /// The kv engine whose file keeps the changes; none for a config loaded
    /// without a store.
    kv: Option<Arc<Kv>>,
    name: String,
    state: Mutex<State>,
}

struct State {
    kept: Arc<Kept>,
    /// The declaration kv.db keeps, the last a program opened the config with.
    remembered: Option<String>,
    followers: Vec<Weak<dyn Follower>>,
    #[cfg(feature = "async")]
    closing: Closing,
}

/// What a change found: it was made, or another came first.
enum Written {
    Made(Kept),
    Moved(Kept),
}

/// What is told when the store closes: an awaited watch, which then ends.
#[cfg(feature = "async")]
pub(crate) type Hook = Weak<dyn Fn() + Send + Sync>;

#[cfg(feature = "async")]
#[derive(Default)]
struct Closing {
    closed: bool,
    hooks: Vec<Hook>,
}

impl Hub {
    /// The hub of `name` in this process: the one open, or one read from kv.db.
    pub(super) fn of(kv: &Arc<Kv>, name: &str) -> Result<Arc<Hub>> {
        let mut hubs = lock(kv.configs());
        if let Some(hub) = hubs.get(name).and_then(Weak::upgrade) {
            return Ok(hub);
        }
        let owned = name.to_owned();
        let (kept, remembered) = kv.file().read(move |connection| read(connection, &owned))?;
        let state = State {
            kept: Arc::new(kept),
            remembered,
            followers: Vec::new(),
            #[cfg(feature = "async")]
            closing: Closing::default(),
        };
        let hub = Arc::new(Hub { kv: Some(Arc::clone(kv)), name: name.to_owned(), state: Mutex::new(state) });
        hubs.retain(|_, hub| hub.strong_count() > 0);
        hubs.insert(name.to_owned(), Arc::downgrade(&hub));
        Ok(hub)
    }

    /// The hub of a config loaded without a store, which keeps no change.
    pub(super) fn detached(name: &str) -> Arc<Hub> {
        let state = State {
            kept: Arc::default(),
            remembered: None,
            followers: Vec::new(),
            #[cfg(feature = "async")]
            closing: Closing::default(),
        };
        Arc::new(Hub { kv: None, name: name.to_owned(), state: Mutex::new(state) })
    }

    /// Whether the config was loaded without a store, and keeps no change.
    #[cfg(feature = "async")]
    pub(super) fn keeps_nothing(&self) -> bool {
        self.kv.is_none()
    }

    /// The kv engine that keeps the changes; refused for a config loaded
    /// without a store.
    fn kv(&self) -> Result<&Arc<Kv>> {
        self.kv.as_ref().ok_or_else(|| {
            Error::invalid("a config loaded without a store keeps no change: open it with store.config to change it")
        })
    }

    /// The store the config was opened in, while it is open.
    #[cfg(feature = "async")]
    pub(super) fn store(&self) -> Result<crate::Store> {
        self.kv()?.store()
    }

    pub(super) fn kept(&self) -> Arc<Kept> {
        Arc::clone(&lock(&self.state).kept)
    }

    /// The declaration kv.db keeps, the last a program opened the config with.
    #[cfg(feature = "wire")]
    pub(super) fn remembered(&self) -> Option<String> {
        lock(&self.state).remembered.clone()
    }

    pub(super) fn join(&self, follower: Weak<dyn Follower>) {
        let mut state = lock(&self.state);
        state.followers.retain(|follower| follower.strong_count() > 0);
        state.followers.push(follower);
    }

    /// The handles of the config open in this process.
    pub(super) fn followers(&self) -> Vec<Arc<dyn Follower>> {
        lock(&self.state).followers.iter().filter_map(Weak::upgrade).collect()
    }

    /// Keeps `leaves` as the config's next version while its version is still
    /// `expected`, and is `conflict` when another change came first; either
    /// way the changes as they are then reach every handle.
    pub(super) fn change(&self, expected: i64, leaves: Vec<(String, Value)>) -> Result<Arc<Kept>> {
        let kv = self.kv()?;
        let (bytes, work) = self.change_work(kv, expected, leaves);
        let written = kv.file().write(bytes, work)?;
        self.published(written)
    }

    /// `change` without waiting, for an awaited call: `done` gets what was
    /// written, on the thread that commits it, and publishes nothing there,
    /// since publishing runs the program's `validate` and its watchers while
    /// the commits behind it wait. A write refused before it is queued is
    /// answered at once.
    #[cfg(feature = "async")]
    pub(super) fn change_then(
        self: &Arc<Self>,
        (expected, leaves): (i64, Vec<(String, Value)>),
        elsewhere: Lead,
        done: impl FnOnce(Result<Unpublished>) + Send + 'static,
    ) {
        let kv = match self.kv() {
            Ok(kv) => Arc::clone(kv),
            Err(error) => return done(Err(error)),
        };
        let (bytes, work) = self.change_work(&kv, expected, leaves);
        let hub = Arc::clone(self);
        let written =
            move |written: Result<Written>| done(written.map(|written| Unpublished::of(hub, written, elsewhere)));
        kv.file().submit(bytes, work, written);
    }

    /// The write that keeps `leaves` while the config's version is still
    /// `expected`, and the bytes it adds to its commit.
    fn change_work(
        &self,
        kv: &Kv,
        expected: i64,
        leaves: Vec<(String, Value)>,
    ) -> (usize, impl FnOnce(&Tx<'_>) -> Result<Written> + Send + 'static) {
        let (name, revision, now) = (self.name.clone(), kv.revision(), kv.now());
        let bytes = leaves.iter().map(|(path, value)| path.len() + value.to_string().len()).sum();
        let work = move |tx: &Tx<'_>| {
            let (kept, _) = read(tx, &name)?;
            if kept.version != expected {
                return Ok(Written::Moved(kept));
            }
            let version = next_version(&revision, tx)?;
            for (path, value) in &leaves {
                let value = value.to_string();
                execute(tx, UPSERT_CHANGE, params![name, path, value, version, now], "a change")?;
            }
            refuse_past_bound(tx, &name)?;
            execute(tx, KEEP_VERSION, params![name, version], "its version")?;
            Ok(Written::Made(read(tx, &name)?.0))
        };
        (bytes, work)
    }

    /// Drops the changes kept at `path` and under it, every change for an
    /// empty path, and says whether there were any: never, for a config
    /// loaded without a store.
    pub(super) fn reset(&self, path: &str) -> Result<bool> {
        let Some(kv) = &self.kv else { return Ok(false) };
        let (bytes, work) = self.reset_work(kv, path);
        let (kept, dropped) = kv.file().write(bytes, work)?;
        self.publish(kept);
        Ok(dropped)
    }

    /// `reset` without waiting, as [`Hub::change_then`] is `change`.
    #[cfg(feature = "async")]
    pub(super) fn reset_then(
        self: &Arc<Self>,
        path: &str,
        elsewhere: Lead,
        done: impl FnOnce(Result<Unpublished>) + Send + 'static,
    ) {
        let kv = match self.kv() {
            Ok(kv) => Arc::clone(kv),
            Err(error) => return done(Err(error)),
        };
        let (bytes, work) = self.reset_work(&kv, path);
        let hub = Arc::clone(self);
        let written = move |written: Result<(Kept, bool)>| {
            done(written.map(|(kept, _)| Unpublished::of(hub, Written::Made(kept), elsewhere)));
        };
        kv.file().submit(bytes, work, written);
    }

    /// The write that drops the changes kept at `path` and under it, and the
    /// bytes it adds to its commit.
    fn reset_work(
        &self,
        kv: &Kv,
        path: &str,
    ) -> (usize, impl FnOnce(&Tx<'_>) -> Result<(Kept, bool)> + Send + 'static) {
        let (name, revision, path) = (self.name.clone(), kv.revision(), path.to_owned());
        let bytes = path.len();
        let work = move |tx: &Tx<'_>| {
            let dropped = tx
                .prepare_cached(DELETE_UNDER)
                .and_then(|mut delete| delete.execute(params![name, path]))
                .map_err(|error| sql_error("its changes", error))?;
            if dropped > 0 {
                let version = next_version(&revision, tx)?;
                execute(tx, KEEP_VERSION, params![name, version], "its version")?;
            }
            Ok((read(tx, &name)?.0, dropped > 0))
        };
        (bytes, work)
    }

    /// Hands what a change wrote to every handle: `conflict` when another
    /// change came first.
    fn published(&self, written: Written) -> Result<Arc<Kept>> {
        match written {
            Written::Made(kept) => Ok(self.publish(kept)),
            Written::Moved(kept) => {
                self.publish(kept);
                Err(Error::new(ErrorKind::Conflict, "changed since the version the change was made on"))
            }
        }
    }

    /// Calls `hook` once, when the store closes, unless it was dropped first;
    /// false, and nothing called, once the store has closed.
    #[cfg(feature = "async")]
    pub(super) fn on_close(&self, hook: Hook) -> bool {
        let mut state = lock(&self.state);
        if state.closing.closed {
            return false;
        }
        state.closing.hooks.retain(|hook| hook.strong_count() > 0);
        state.closing.hooks.push(hook);
        true
    }

    /// Tells every hook that the store closes, once, outside the lock.
    #[cfg(feature = "async")]
    pub(crate) fn close(&self) {
        let hooks = {
            let mut state = lock(&self.state);
            state.closing.closed = true;
            std::mem::take(&mut state.closing.hooks)
        };
        for hook in hooks.iter().filter_map(Weak::upgrade) {
            hook();
        }
    }

    /// Keeps the declaration a program opened the config with, when it is
    /// not the one kv.db keeps already.
    pub(super) fn remember(&self, declaration: &Declaration) -> Result<()> {
        let text = declaration.to_json().to_string();
        if lock(&self.state).remembered.as_deref() == Some(text.as_str()) {
            return Ok(());
        }
        let (name, kept) = (self.name.clone(), text.clone());
        self.kv()?
            .file()
            .write(text.len(), move |tx| execute(tx, KEEP_DECLARATION, params![name, kept], "its declaration"))?;
        lock(&self.state).remembered = Some(text);
        Ok(())
    }

    /// The changes as they are now, for every handle. Commits may answer out
    /// of order, so an older version than the hub has is not taken.
    fn publish(&self, kept: Kept) -> Arc<Kept> {
        let (kept, followers) = {
            let mut state = lock(&self.state);
            if kept.version > state.kept.version {
                state.kept = Arc::new(kept);
            }
            (Arc::clone(&state.kept), state.followers.iter().filter_map(Weak::upgrade).collect::<Vec<_>>())
        };
        for follower in &followers {
            follower.follow(&kept);
        }
        kept
    }
}

/// What an awaited change wrote, until it reaches the config's handles. The
/// future that awaits it publishes it once its commit answered, on the
/// thread that polls it, before the future answers. One dropped first, its
/// answer unread, hands it to `elsewhere`, the store's pool: a handle that
/// missed it would lag behind kv.db until the next change.
#[cfg(feature = "async")]
pub(crate) struct Unpublished {
    hub: Arc<Hub>,
    /// None once published.
    written: Option<Written>,
    elsewhere: Lead,
}

#[cfg(feature = "async")]
impl Unpublished {
    fn of(hub: Arc<Hub>, written: Written, elsewhere: Lead) -> Unpublished {
        Unpublished { hub, written: Some(written), elsewhere }
    }

    /// Hands what was written to every handle and its watchers, then answers
    /// as the blocking change does: `conflict` when another change came first.
    pub(crate) fn publish(mut self) -> Result<()> {
        let Some(written) = self.written.take() else { return Ok(()) };
        self.hub.published(written).map(drop).map_err(|error| error.within(format!("config {}", self.hub.name)))
    }
}

#[cfg(feature = "async")]
impl Drop for Unpublished {
    fn drop(&mut self) {
        if let Some(written) = self.written.take() {
            let hub = Arc::clone(&self.hub);
            (self.elsewhere)(Box::new(move || drop(hub.published(written))));
        }
    }
}

/// The changes `name` keeps, and the declaration kept with them.
fn read(connection: &Connection, name: &str) -> Result<(Kept, Option<String>)> {
    let config: Option<(i64, Option<String>)> = connection
        .prepare_cached(SELECT_CONFIG)
        .and_then(|mut select| select.query_row([name], |row| Ok((row.get(0)?, row.get(1)?))).optional())
        .map_err(|error| sql_error("its version", error))?;
    let (version, remembered) = config.unwrap_or((0, None));
    let mut select = connection.prepare_cached(SELECT_CHANGES).map_err(|error| sql_error("its changes", error))?;
    let rows = select
        .query_map([name], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?, row.get(2)?, row.get(3)?)))
        .map_err(|error| sql_error("its changes", error))?;
    let mut changes = BTreeMap::new();
    for row in rows {
        let (path, text, changed_at_version, at) = row.map_err(|error| sql_error("its changes", error))?;
        let value = serde_json::from_str(&text)
            .map_err(|error| Error::corrupt(format!("the change of {path} is not JSON: {error}")))?;
        changes.insert(path, Change { value, version: changed_at_version, at });
    }
    Ok((Kept { version, changes }, remembered))
}

fn refuse_past_bound(connection: &Connection, name: &str) -> Result<()> {
    let bytes: i64 = connection
        .prepare_cached(KEPT_BYTES)
        .and_then(|mut select| select.query_row([name], |row| row.get(0)))
        .map_err(|error| sql_error("its changes' size", error))?;
    if bytes > MOST_KEPT {
        let refused = format!("its changes would hold {bytes} bytes, past the {MOST_KEPT} a config keeps");
        return Err(CONFIG_BYTES.refuse(bytes as u64, refused));
    }
    Ok(())
}

use crate::sqlite::execute_cached as execute;

/// The configs kv.db keeps a declaration of, by name, for the command line's
/// completion and `status --json`: none while the store has no kv.db.
#[cfg(feature = "client")]
pub(crate) fn names(store: &crate::Store) -> Result<Vec<String>> {
    if !store.dir().join("kv.db").exists() {
        return Ok(Vec::new());
    }
    Kv::of(store)?.file().read(|connection| {
        let mut select = connection.prepare_cached(SELECT_NAMES).map_err(|error| sql_error("its configs", error))?;
        let rows = select.query_map([], |row| row.get(0));
        rows.and_then(Iterator::collect).map_err(|error| sql_error("its configs", error))
    })
}