tinystore 0.11.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
//! A connection in memory: the wire's frames to a store in this process, with
//! no socket between. The FFI hands its bytes here, so Bun, Node, Python and
//! Go reach the core through the same session a server gives a socket, and a
//! server gives each of its clients one.

use std::collections::HashMap;
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
use std::time::Duration;

use crate::wire::Session;
pub use crate::wire::Wake;
use crate::wire::codec::Message;
use crate::wire::protocol::StoreOptions;
use crate::{Durability, Error, ErrorKind, Options, Result, Store, TestClock};

/// The stores this process holds through pipes, by directory: one store a
/// directory, closed with its last pipe.
fn stores() -> MutexGuard<'static, HashMap<PathBuf, Held>> {
    static STORES: OnceLock<Mutex<HashMap<PathBuf, Held>>> = OnceLock::new();
    STORES.get_or_init(Mutex::default).lock().unwrap_or_else(PoisonError::into_inner)
}

/// A store the pipes of this process hold, how many pipes, and the test's
/// clock it was opened on, which `server.clock` moves over every one of them.
struct Held {
    store: Store,
    pipes: usize,
    clock: Option<Arc<TestClock>>,
}

/// An error kind's code as the wire spells it, the same in every SDK's error
/// classes: what a host that opens a pipe raises for a store that did not open.
pub fn code(kind: ErrorKind) -> &'static str {
    crate::wire::code_of(kind)
}

/// Answers a HELLO's challenge: the HMAC-SHA256 of it, keyed with `SERVE`'s
/// secret, which only the user the server runs as can read.
pub type Prove = Arc<dyn Fn(&[u8]) -> Vec<u8> + Send + Sync>;

/// What `server.stop` does, called once its answer has left.
pub type Stop = Arc<dyn Fn() + Send + Sync>;

/// Told the client's name, as its HELLO gives it, once the connection is
/// welcomed: a server logs who came.
pub type Greeted = Arc<dyn Fn(&str) + Send + Sync>;

/// What a remote server lets a connection do by the token its HELLO carries:
/// none for a token it does not know. The host that gives it must compare
/// every token it knows in constant time, so that the time taken says nothing
/// of which matched.
pub type Admit = Arc<dyn Fn(Option<&str>) -> Option<Capability> + Send + Sync>;

/// What a connection may do. A local endpoint's are `Admin`, its permission
/// being the file system's.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Capability {
    /// Everything, stopping the server and changing a schema among it.
    Admin,
    /// Reads and writes.
    Data,
    /// Reads only: a method the schema does not mark `read` is refused, and
    /// its SQL runs on a reader and applies no migration.
    Read,
}

/// What a connection to a store needs of its host beyond the frames.
#[derive(Clone, Default)]
pub struct Connect {
    /// Called when frames become ready after the host took the last ones; a
    /// host that reads with a blocking [`Pipe::recv`] passes none.
    pub wake: Option<Wake>,
    /// A local server's proof; a connection without it, embedded or remote,
    /// gives none.
    pub prove: Option<Prove>,
    /// A connection without it refuses `server.stop`: the program that holds
    /// the store decides when its server stops.
    pub stop: Option<Stop>,
    /// A private server's clock, which `server.clock` reads and moves; a
    /// connection without it refuses the call.
    pub clock: Option<Arc<TestClock>>,
    /// A remote server's tokens; a connection without it admits every client
    /// as `Admin`, as a local endpoint and an embedded store do.
    pub admit: Option<Admit>,
    /// Told who came, once the connection is welcomed.
    pub greeted: Option<Greeted>,
    /// Why a server that takes no more connections turns this one away: its
    /// HELLO, once read and its token admitted, is answered `GOAWAY` `limit`
    /// with these words where the WELCOME belongs.
    pub turned_away: Option<String>,
    /// The folders a server was given, by the name of their directory: what
    /// a connection that names no path opens, and the only folders one that
    /// came with a token reaches (BLOB-15).
    pub directories: Option<Arc<std::collections::BTreeMap<String, std::path::PathBuf>>>,
}

impl fmt::Debug for Connect {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Connect")
            .field("wake", &self.wake.is_some())
            .field("prove", &self.prove.is_some())
            .field("stop", &self.stop.is_some())
            .field("clock", &self.clock)
            .field("admit", &self.admit.is_some())
            .field("greeted", &self.greeted.is_some())
            .field("turned_away", &self.turned_away)
            .field("directories", &self.directories)
            .finish()
    }
}

/// One connection in memory to a store.
pub struct Pipe {
    session: Session,
    /// The directory of a store the process registry holds for its pipes;
    /// none for a store the program holds itself.
    dir: Option<PathBuf>,
}

impl Pipe {
    /// Opens the store in `dir`, or joins it when this process holds it through
    /// another pipe. `options` is the wire's `store.Options`, none of its
    /// bytes for a store as it opens unasked; a store this process holds
    /// already keeps what it was opened with, and one that asks for another
    /// durability is `Invalid`. Its `clock` opens the store on a test's
    /// clock, which `server.clock` moves over every pipe of the store. `wake` is called when frames become ready
    /// after the last were taken; a host that reads with a blocking
    /// [`Pipe::recv`] passes none.
    pub fn open(dir: impl AsRef<Path>, options: &[u8], wake: Option<Wake>) -> Result<Pipe> {
        let dir = std::path::absolute(dir.as_ref()).map_err(|error| crate::Error::io("pipe: its directory", error))?;
        let (store, clock) = join(&dir, asked(options)?)?;
        match Session::new(store, Connect { wake, clock, ..Connect::default() }) {
            Ok(session) => Ok(Pipe { session, dir: Some(dir) }),
            Err(error) => {
                leave(&dir);
                Err(error)
            }
        }
    }

    /// A connection to a store this program holds, as its server gives each
    /// client; the store stays open when the pipe closes.
    pub fn connect(store: &Store, connect: Connect) -> Result<Pipe> {
        Ok(Pipe { session: Session::new(store.clone(), connect)?, dir: None })
    }

    /// Hands frames to the store and returns the frames ready at once.
    pub fn send(&self, frames: &[u8]) -> Vec<u8> {
        self.session.receive(frames);
        self.session.take_ready()
    }

    /// Hands frames to the store and leaves what they answer to
    /// [`Pipe::recv`]: for a host whose one writer takes every frame, so that
    /// frames leave in the order they were made.
    pub fn push(&self, frames: &[u8]) {
        self.session.receive(frames);
    }

    /// The frames ready since, waiting up to `wait` for the first.
    pub fn recv(&self, wait: Duration) -> Vec<u8> {
        self.session.take(wait)
    }

    /// As [`Pipe::send`], the frames ready at once written into the host's
    /// own bytes: it returns how many were written. The bytes are a stream,
    /// so a frame may end in the next read; when they fill `into`, more may
    /// wait, which no wake announces: the host reads on with
    /// [`Pipe::recv_into`]. With no room it is [`Pipe::push`].
    ///
    /// One reader at a time takes the stream: a host that sends from many
    /// threads gives its sends no room and reads in one place.
    pub fn send_into(&self, frames: &[u8], into: &mut [u8]) -> usize {
        self.session.receive(frames);
        self.session.take_ready_into(into)
    }

    /// As [`Pipe::recv`], written into the host's own bytes: it returns how
    /// many were written, and filled bytes may have left more, as
    /// [`Pipe::send_into`] says.
    pub fn recv_into(&self, wait: Duration, into: &mut [u8]) -> usize {
        self.session.take_into(wait, into)
    }

    /// Tells the client the server is closing: a `GOAWAY`, after which a
    /// `REQUEST` is answered `unavailable` unrun, while the streams running
    /// finish.
    pub fn go_away(&self) {
        self.session.go_away();
    }

    /// Tells the session its client closed its side, as a socket's end of
    /// file says: the streams that run until the client cancels them end,
    /// since it can cancel nothing more, and the calls running finish, their
    /// answers left for a client that may read on.
    pub fn client_closed(&self) {
        self.session.client_closed();
    }

    /// Whether the connection owes its client so much that it reads no frame
    /// more until the host takes some: bytes handed to it meanwhile wait
    /// unread, so a host that reads them from a socket stops reading until a
    /// take of its own, since the client may be one that never reads.
    pub fn full(&self) -> bool {
        self.session.full()
    }

    /// The streams whose final frame has not left.
    pub fn streams(&self) -> usize {
        self.session.streams()
    }

    /// Whether the client's HELLO was taken: a server closes a connection
    /// that says nothing for long.
    pub fn welcomed(&self) -> bool {
        self.session.welcomed()
    }

    /// Whether the session reads nothing more and owes nothing more: the
    /// client said `GOAWAY` or broke a rule, and what was owed was taken.
    pub fn finished(&self) -> bool {
        self.session.finished()
    }
}

impl Drop for Pipe {
    fn drop(&mut self) {
        self.session.end();
        if let Some(dir) = &self.dir {
            leave(dir);
        }
    }
}

impl fmt::Debug for Pipe {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.dir {
            Some(dir) => write!(f, "Pipe({})", dir.display()),
            None => f.write_str("Pipe"),
        }
    }
}

/// What a host's options ask of its store: its files' durability, the file
/// of its encryption key, its metrics, the node it is, and where a test's
/// clock starts.
#[derive(Default)]
struct Asked {
    durability: Option<Durability>,
    clock: Option<std::time::SystemTime>,
    #[cfg(feature = "metrics")]
    self_metrics: Option<crate::metrics::SelfMetrics>,
    #[cfg(feature = "metrics")]
    max_series: Option<u64>,
    encryption_key_file: Option<PathBuf>,
    older_encryption_keys: Vec<PathBuf>,
    #[cfg(feature = "replication")]
    node: Option<crate::replication::Node>,
    #[cfg(feature = "local")]
    cli: bool,
}

fn asked(options: &[u8]) -> Result<Asked> {
    if options.is_empty() {
        return Ok(Asked::default());
    }
    let asked = StoreOptions::decode(options)
        .map_err(|refused| Error::invalid(format!("pipe: its options: {}", refused.message)))?;
    let durability = asked.durability.map(|word| word.parse().map_err(|error: Error| error.within("pipe")));
    let node_asked = asked.node
        || !asked.from.is_empty()
        || asked.serve.is_some()
        || asked.synchronous
        || asked.catalog
        || asked.insecure
        || !asked.synchronous_with.is_empty();
    #[cfg(not(feature = "replication"))]
    if node_asked {
        return Err(Error::invalid("pipe: a node's options, and the library was built without replication"));
    }
    #[cfg(feature = "replication")]
    let node = node_asked.then(|| crate::replication::Node {
        from: asked.from,
        serve: asked.serve,
        files: (!asked.files.is_empty()).then_some(asked.files),
        token: asked.token,
        synchronous: asked.synchronous,
        synchronous_with: asked.synchronous_with,
        tls: None,
        catalog: asked.catalog,
        advertise: asked.advertise,
        failover: None,
        witness: false,
        insecure: asked.insecure,
    });
    #[cfg(not(feature = "metrics"))]
    if asked.self_metrics || asked.max_series.is_some() {
        return Err(Error::invalid("pipe: the store's metrics, and the library was built without metrics"));
    }
    #[cfg(not(feature = "local"))]
    if asked.cli {
        return Err(Error::invalid("pipe: an endpoint for the command line, and the library was built without local"));
    }
    Ok(Asked {
        durability: durability.transpose()?,
        clock: asked.clock.map(crate::clock::from_unix_millis),
        #[cfg(feature = "metrics")]
        self_metrics: asked.self_metrics.then_some(crate::metrics::SelfMetrics { system: !asked.without_system }),
        #[cfg(feature = "metrics")]
        max_series: asked.max_series,
        encryption_key_file: asked.encryption_key_file.map(PathBuf::from),
        older_encryption_keys: asked.older_encryption_keys.into_iter().map(PathBuf::from).collect(),
        #[cfg(feature = "replication")]
        node,
        #[cfg(feature = "local")]
        cli: asked.cli,
    })
}

/// The store of `dir`, opened as asked, and its test's clock, or the one
/// this process has open already, which is refused when it was opened
/// another way. A clock asked of a store open on one joins it as it runs now.
fn join(dir: &Path, asked: Asked) -> Result<(Store, Option<Arc<TestClock>>)> {
    let mut stores = stores();
    if let Some(Held { store, pipes, clock }) = stores.get_mut(dir) {
        if asked.clock.is_some() != clock.is_some() {
            let (opened, instead) = if clock.is_some() { ("on", "with") } else { ("without", "without") };
            return Err(Error::invalid(format!(
                "pipe: the store is open {opened} a test's clock: open it {instead} one"
            )));
        }
        if let Some(durability) = asked.durability
            && store.durability() != Some(durability)
        {
            let (opened, instead) = match store.durability() {
                None => ("no durability set, full but os for records and metrics".to_owned(), String::new()),
                Some(opened) => (format!("durability {opened}"), format!("with {opened} or ")),
            };
            return Err(Error::invalid(format!(
                "pipe: the store is open with {opened}, and asked for {durability}: open it {instead}without durability"
            )));
        }
        if let Some(key_file) = &asked.encryption_key_file
            && store.encryption_key_file() != Some(key_file)
        {
            return Err(Error::invalid(format!(
                "pipe: the store is open with another encryption key file than {}",
                key_file.display()
            )));
        }
        if !asked.older_encryption_keys.is_empty() && store.older_encryption_keys() != asked.older_encryption_keys {
            return Err(Error::invalid("pipe: the store is open with other older encryption keys than those asked"));
        }
        #[cfg(feature = "metrics")]
        if asked.self_metrics.is_some() && !store.probe().listening() {
            return Err(Error::invalid("pipe: the store is open without its own metrics, and asked for them"));
        }
        #[cfg(feature = "metrics")]
        if let Some(max_series) = asked.max_series
            && store.max_series() != max_series
        {
            let opened = store.max_series();
            return Err(Error::invalid(format!(
                "pipe: the store is open with max_series {opened}, and asked for {max_series}: open it with \
                 {opened} or without max_series"
            )));
        }
        #[cfg(feature = "replication")]
        if asked.node.is_some() && store.node().is_none() {
            return Err(Error::invalid("pipe: the store is open as no node, and asked to be one"));
        }
        #[cfg(feature = "local")]
        if asked.cli && !store.serves_the_command_line() {
            return Err(Error::invalid("pipe: the store is open without cli, and asked for it"));
        }
        *pipes += 1;
        return Ok((store.clone(), clock.clone()));
    }
    let clock = asked.clock.map(|start| Arc::new(TestClock::new(start)));
    let options = Options {
        clock: clock.clone().map(|clock| clock as Arc<dyn crate::Clock>),
        durability: asked.durability,
        encryption_key_file: asked.encryption_key_file,
        older_encryption_keys: asked.older_encryption_keys,
        #[cfg(feature = "replication")]
        node: asked.node,
        #[cfg(feature = "metrics")]
        self_metrics: asked.self_metrics,
        #[cfg(feature = "metrics")]
        max_series: asked.max_series.unwrap_or(crate::store::MAX_SERIES),
        #[cfg(feature = "local")]
        cli: asked.cli,
        ..Options::default()
    };
    let store = Store::open(dir, options)?;
    stores.insert(dir.to_path_buf(), Held { store: store.clone(), pipes: 1, clock: clock.clone() });
    Ok((store, clock))
}

/// Lets go of a pipe's store, closing it with its last pipe.
fn leave(dir: &Path) {
    let mut stores = stores();
    let Some(Held { store, pipes, .. }) = stores.get_mut(dir) else {
        return;
    };
    *pipes -= 1;
    if *pipes > 0 {
        return;
    }
    let store = store.clone();
    stores.remove(dir);
    drop(stores);
    if let Err(error) = store.close() {
        tracing::warn!(target: "tinystore", %error, "a pipe's store did not close cleanly");
    }
}

#[cfg(test)]
#[path = "pipe_fixture.rs"]
pub(crate) mod fixture;
#[cfg(test)]
#[path = "pipe_tests.rs"]
mod tests;