tinystore 0.12.0

A small storage runtime for applications on SQLite: SQL, key-value state, durable jobs, files, search, logs and metrics in one directory
Documentation
//! What engines use of their store. An application never imports this module:
//! it opens engines, and engines call these.

use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;

use crate::Result;
pub use crate::schedule::Wake;

// a database's file lent to kv's and jobs' handles, and where a handle opens
#[cfg(any(feature = "kv", feature = "jobs", feature = "sql"))]
mod shared;
#[cfg(any(feature = "kv", feature = "jobs"))]
pub(crate) use shared::Home;
#[cfg(any(feature = "sql", feature = "wire"))]
pub(crate) use shared::SharedFile;
#[cfg(all(feature = "sql", any(feature = "jobs", feature = "records")))]
pub(crate) use shared::{LentWrite, Wrote};

/// An engine as its store sees it: something to close at the store's close.
pub trait Engine: Send + Sync + 'static {
    /// Stops the threads that run the program's code, a queue's handlers or a
    /// channel's, and waits for those running. The store stops every engine
    /// before it closes any, so that a handler finishes while every file it
    /// writes is open. A second call does nothing.
    fn stop(&self) {}

    /// Closes the engine. A second call, or a call after the engine closed by
    /// itself, does nothing.
    fn close(&self) -> Result<()>;

    /// The store's clock was moved by hand, as a test moves it: what sleeps
    /// until a time reads the clock again.
    fn clock_moved(&self) {}

    /// A commit of its home was applied to the store's file `file`, a copy:
    /// what the engine keeps in memory of the file may be its no longer.
    fn applied(&self, file: &str) {
        let _ = file;
    }

    /// Readies the engine for a snapshot of the store, which copies the files
    /// every engine names at one moment of them all, while they keep working:
    /// it writes what it holds in memory first, and names its SQLite files.
    /// An engine whose file another lends names none: the lender does.
    fn snapshot(&self) -> Result<Copying<'_>> {
        Ok(Copying::default())
    }
}

/// What marks a thread while it runs a program's handler that one store's
/// close waits for: a queue's worker's, a schedule's, a channel
/// subscription's. That store's close, called there, would wait for the
/// handler that calls it, so it refuses instead, as it does inside a
/// transaction. A close of another store waits for no such handler: each
/// store has a mark of its own.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Handling(u64);

thread_local! {
    /// The marks of the handlers this thread runs, the innermost last.
    static HANDLING: std::cell::RefCell<Vec<u64>> = const { std::cell::RefCell::new(Vec::new()) };
}

impl Handling {
    /// A mark no other store has: a number, never an address, which another
    /// store could take once this one is gone.
    pub(crate) fn new() -> Handling {
        static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        Handling(LAST.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1)
    }

    /// Runs `handler` with this thread marked, a panic's unwinding included.
    #[cfg(any(feature = "jobs", feature = "channels"))]
    pub(crate) fn run<T>(self, handler: impl FnOnce() -> T) -> T {
        HANDLING.with(|marks| marks.borrow_mut().push(self.0));
        let _unmarked = Unmark(self.0);
        handler()
    }

    /// Whether this thread runs a handler under this mark now.
    pub(crate) fn on_this_thread(self) -> bool {
        HANDLING.with(|marks| marks.borrow().contains(&self.0))
    }
}

/// Takes a handler's mark off its thread as the handler ends.
#[cfg(any(feature = "jobs", feature = "channels"))]
struct Unmark(u64);

#[cfg(any(feature = "jobs", feature = "channels"))]
impl Drop for Unmark {
    fn drop(&mut self) {
        HANDLING.with(|marks| {
            let mut marks = marks.borrow_mut();
            if let Some(at) = marks.iter().rposition(|&mark| mark == self.0) {
                marks.remove(at);
            }
        });
    }
}

/// A file of a snapshot: its path inside the store, `/` between its parts,
/// as `kv.db`, `sql/app.db` or `blobs/objects/1a3/1a3f07`, and the engine
/// whose it is.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Copied {
    pub name: String,
    pub engine: &'static str,
}

/// What a snapshot copies of an engine: its SQLite files, at the moment, and
/// what the engine copies beside them once they are.
#[derive(Default)]
pub struct Copying<'a> {
    pub(crate) files: Vec<(Copied, crate::sqlite::Source)>,
    pub(crate) at_the_moment: Option<AtTheMoment<'a>>,
}

impl fmt::Debug for Copying<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let files: Vec<&str> = self.files.iter().map(|(copied, _)| copied.name.as_str()).collect();
        let at_the_moment = self.at_the_moment.is_some();
        f.debug_struct("Copying").field("files", &files).field("at_the_moment", &at_the_moment).finish()
    }
}

/// What an engine does at the moment, every writer held: it gives back what
/// it does once the files are copied, into the snapshot's directory, as blobs
/// links the objects its copy names, none of which goes meanwhile.
pub(crate) type AtTheMoment<'a> = Box<dyn FnOnce() -> Then<'a> + 'a>;
pub(crate) type Then<'a> = Box<dyn FnOnce(&Path) -> Result<Vec<Copied>> + 'a>;

/// An SQLite file of an engine's, `name` inside the store, as a snapshot
/// copies it.
#[cfg_attr(
    not(any(
        feature = "kv",
        feature = "jobs",
        feature = "sql",
        feature = "blobs",
        feature = "records",
        feature = "metrics",
        feature = "search"
    )),
    expect(dead_code, reason = "every engine copies its files with it, and a store of none has none")
)]
pub(crate) fn to_copy<'a>(file: &crate::sqlite::File, name: &str, engine: &'static str) -> Result<Copying<'a>> {
    let copied = Copied { name: name.to_owned(), engine };
    Ok(Copying { files: vec![(copied, file.source()?)], at_the_moment: None })
}

/// What a store holds under one name, a bucket, a queue, a set of files, a
/// stream or an index, as the command line's `status --names` shows it.
#[cfg(feature = "client")]
#[doc(hidden)]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Held {
    pub name: String,
    /// Its keys, jobs, files, events or documents, as a program counts them.
    pub count: u64,
    /// What its keys, values and bodies weigh as SQLite keeps them, without
    /// its pages' and indexes' own bytes: near what the file gives the name.
    pub bytes: u64,
}

/// Rows one maintenance transaction removes, so that no pass holds the
/// writer long, and transactions of each kind one pass runs at most.
#[cfg(any(feature = "jobs", feature = "blobs"))]
pub(crate) const BATCH: usize = 10_000;
#[cfg(any(feature = "jobs", feature = "blobs"))]
pub(crate) const BATCHES: usize = 10;

/// Runs `batch`, a transaction that removes at most `BATCH` rows and says how
/// many it removed, until one removes fewer, `BATCHES` times at most; the
/// rows removed in all.
#[cfg(any(feature = "jobs", feature = "blobs"))]
pub(crate) fn in_batches(mut batch: impl FnMut() -> Result<usize>) -> Result<usize> {
    let mut total = 0;
    for _ in 0..BATCHES {
        let removed = batch()?;
        total += removed;
        if removed < BATCH {
            break;
        }
    }
    Ok(total)
}

/// What a connection that only reads is told of a name its store does not
/// hold, as search's open of an index tells it: `what` would have been made.
#[cfg(feature = "wire")]
pub(crate) fn not_held(what: &str) -> crate::Error {
    crate::Error::invalid(format!("no such {what}, and a connection that only reads makes none"))
}

/// The folder of the store's directory that holds the databases' files,
/// and with them the buckets and queues opened from a database.
#[cfg(any(feature = "kv", feature = "sql", feature = "replication"))]
pub(crate) const DATABASES: &str = "sql";

/// The file a database's name keeps, by its path in the store's directory.
#[cfg(any(feature = "sql", feature = "replication"))]
pub(crate) fn database_file(name: &str) -> String {
    format!("{DATABASES}/{name}.db")
}

/// The folder of the store's directory that holds the databases opened with
/// `backup(false)`, and the bytes of their files. Where they lie is the whole
/// policy: a backup walks `sql/` and the engines' own files, this release's
/// and every one released before it, so none takes what is here; and a node
/// copies none of it, as it copies no node's own records and metrics.
#[cfg(any(feature = "kv", feature = "sql", feature = "replication", feature = "backup", feature = "metrics"))]
pub(crate) const LOCAL: &str = "local";

/// Whether `file`, by its path in the store's directory, lies in `local/`:
/// no backup holds it and no node copies it.
#[cfg(any(all(feature = "sql", feature = "blobs"), feature = "replication", feature = "metrics"))]
pub(crate) fn is_local(file: &str) -> bool {
    file.strip_prefix(LOCAL).is_some_and(|rest| rest.starts_with('/'))
}

/// The store's calls for the engines opened against it.
pub trait Host {
    /// The engine of type `E` this store has open, or the one `open` makes and
    /// the store then closes at its own close; every handle shares it.
    fn engine<E: Engine>(&self, open: impl FnOnce(&crate::Store) -> Result<Arc<E>>) -> Result<Arc<E>>;

    /// Closes `engine` when the store closes, the last attached first.
    fn attach(&self, engine: Arc<dyn Engine>) -> Result<()>;

    /// Runs `work` every `period` on the store's background thread, one task at
    /// a time, and sooner when what it gives back wakes it. A failure is logged
    /// once and a recovery once. Nothing runs when the store was opened without
    /// background work.
    fn every(&self, name: &str, period: Duration, work: impl FnMut() -> Result<()> + Send + 'static) -> Result<Wake>;

    /// Claims a file name in the store's directory, so that no other engine
    /// opens the same file; the name is free again once the claim is dropped.
    fn claim(&self, name: &str) -> Result<Claim>;
}

/// What gives a claimed name back to its store.
type Release = Box<dyn FnOnce(&str) + Send + Sync>;

/// A file name in the store's directory that one engine holds.
pub struct Claim {
    name: String,
    path: PathBuf,
    release: Option<Release>,
}

impl Claim {
    pub(crate) fn new(name: &str, path: PathBuf, release: Release) -> Self {
        Self { name: name.to_owned(), path, release: Some(release) }
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn path(&self) -> &Path {
        &self.path
    }
}

impl Drop for Claim {
    fn drop(&mut self) {
        if let Some(release) = self.release.take() {
            release(&self.name);
        }
    }
}

impl fmt::Debug for Claim {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Claim({})", self.path.display())
    }
}

/// Migrates an engine's tables in `file`. On a copy kept in a database's
/// file whose home has not made those tables yet, it asks the home to make
/// them, then checks again: a copy's migrations are its home's.
#[cfg(any(feature = "kv", feature = "jobs"))]
pub(crate) fn migrate_in(
    store: &crate::Store,
    file: &crate::sqlite::File,
    history: &str,
    migrations: &[crate::sqlite::Migration],
    lent_by: Option<&str>,
) -> Result<()> {
    let migrated = file.migrate(history, migrations);
    #[cfg(feature = "replication")]
    if let Err(error) = &migrated
        && error.kind() == crate::ErrorKind::Unavailable
        && file.is_copy()
        && let Some(database) = lent_by.and_then(crate::replication::database_of)
        && let Some(tag) = crate::replication::tag_of(history)
    {
        crate::replication::make_in(store, &crate::replication::database_file(database), tag)?;
        return file.migrate(history, migrations);
    }
    let _ = (store, lent_by);
    migrated
}