tinystore 0.10.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 every kind of kv handle shares: the engine, the row of its name in
//! the engine's file, what the name holds, and the branch the handle sees.

use std::sync::Arc;

use rusqlite::Connection;

use super::engine::{Kv, Revision};
use super::path::{Branch, Key};
use crate::engine::Home;
use crate::sqlite::Tx;
use crate::{Error, Result};

/// What a name in kv's file holds. A name keeps its kind: a name that holds
/// counters never opens as a bucket of values.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Kind {
    Values,
    /// Values sealed with the store's encryption key.
    Encrypted,
    Counters,
    RateLimit,
    Quota,
    Once,
}

impl Kind {
    /// The kind as the name's row keeps it.
    pub(crate) fn role(self) -> &'static str {
        match self {
            Kind::Values => "values",
            Kind::Encrypted => "encrypted values",
            Kind::Counters => "counters",
            Kind::RateLimit => "rate limit",
            Kind::Quota => "quota",
            Kind::Once => "once",
        }
    }

    /// The kind a name's row keeps as `role`.
    #[cfg(feature = "replication")]
    pub(crate) fn of_role(role: &str) -> Option<Kind> {
        [Kind::Values, Kind::Encrypted, Kind::Counters, Kind::RateLimit, Kind::Quota, Kind::Once]
            .into_iter()
            .find(|kind| kind.role() == role)
    }

    /// What an error calls a handle of this kind: `kv counters hits`.
    fn shown(self) -> &'static str {
        match self {
            Kind::Values | Kind::Encrypted => "bucket",
            Kind::Counters => "counters",
            Kind::RateLimit => "rate limit",
            Kind::Quota => "quota",
            Kind::Once => "once",
        }
    }
}

/// A handle's place in its engine's file, cheap to clone.
#[derive(Clone)]
pub(crate) struct Scope {
    pub(crate) kv: Arc<Kv>,
    pub(crate) id: i64,
    name: Arc<str>,
    kind: Kind,
    /// An invalid owner given to `under` fails the branch's calls, not `under`.
    branch: std::result::Result<Branch, String>,
}

impl Scope {
    /// Opens `name` as `kind` where `home` says, making its row the first time.
    pub(crate) fn open(home: &Home, name: &str, kind: Kind) -> Result<Scope> {
        let lent_by = match home {
            Home::Store(_) => None,
            Home::Shared(shared) => Some(shared.owner()),
        };
        let shown = || described(lent_by, kind, name);
        check_name(name).map_err(|error| error.within(shown()))?;
        let kv = Kv::at(home).map_err(|error| error.within(shown()))?;
        let id = kv.name(name, kind).map_err(|error| error.within(shown()))?;
        Ok(Scope { kv, id, name: name.into(), kind, branch: Ok(Branch::default()) })
    }

    /// Opens `name` as `kind` where `home` says, as the store holds it, for a
    /// connection that may only read: neither kv.db, nor kv's tables in a
    /// database's file, nor the name's row is made.
    #[cfg(feature = "wire")]
    pub(crate) fn open_as_it_is(home: &Home, name: &str, kind: Kind) -> Result<Scope> {
        let lent_by = match home {
            Home::Store(_) => None,
            Home::Shared(shared) => Some(shared.owner()),
        };
        let shown = || described(lent_by, kind, name);
        check_name(name).map_err(|error| error.within(shown()))?;
        let kv = Kv::at_as_it_is(home).map_err(|error| error.within(shown()))?;
        let id = kv.name_as_it_is(name, kind).map_err(|error| error.within(shown()))?;
        Ok(Scope { kv, id, name: name.into(), kind, branch: Ok(Branch::default()) })
    }

    /// The same name seen from the branch `owner` names under this one.
    pub(crate) fn under(&self, owner: impl Key) -> Scope {
        let branch = match &self.branch {
            Ok(branch) => branch.under(&owner.text()).map_err(|error| error.to_string()),
            Err(invalid) => Err(invalid.clone()),
        };
        Scope { branch, ..self.clone() }
    }

    pub(crate) fn branch(&self) -> Result<&Branch> {
        self.branch.as_ref().map_err(|invalid| Error::invalid(invalid.clone()).within(self.shown()))
    }

    /// Passes a call on `key` of `handle`, under this branch, to the home of
    /// the copy the scope's file is, and gives its answer's bytes once the
    /// copy holds the commit that made it.
    #[cfg(feature = "replication")]
    pub(crate) fn pass_on(
        &self,
        handle: &super::forward::Handle,
        key: &str,
        call: &super::forward::Call,
    ) -> Result<Vec<u8>> {
        let store = self.kv.store().map_err(|error| error.within(self.shown_key(key)))?;
        super::forward::pass_on(&store, handle, self.branch()?.owners(), key, call)
    }

    pub(crate) fn path(&self, key: &str) -> Result<Vec<u8>> {
        self.branch()?.path(key).map_err(|error| error.within(self.shown()))
    }

    /// The store's time, in unix milliseconds.
    pub(crate) fn now(&self) -> i64 {
        self.kv.now()
    }

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

    /// The handle as an error names it: `kv counters hits`.
    pub(crate) fn shown(&self) -> String {
        described(self.kv.lent_by(), self.kind, &self.name)
    }

    pub(crate) fn shown_key(&self, key: &str) -> String {
        match &self.branch {
            Ok(branch) => format!("{}: {}", self.shown(), branch.shown_key(key)),
            Err(_) => self.shown(),
        }
    }

    pub(crate) fn shown_branch(&self) -> String {
        match &self.branch {
            Ok(branch) => format!("{}: {}", self.shown(), branch.shown()),
            Err(_) => self.shown(),
        }
    }

    /// Runs a write on the file's writer in a commit it may share, naming the
    /// key in its errors.
    pub(crate) fn write<T: Send + 'static>(
        &self,
        key: &str,
        bytes: usize,
        work: impl FnOnce(&Tx<'_>, &Revision) -> Result<T> + Send + 'static,
    ) -> Result<T> {
        let revision = self.kv.revision();
        self.kv.file().write(bytes, move |tx| work(tx, &revision)).map_err(|error| error.within(self.shown_key(key)))
    }

    /// Queues a write on the file's writer and returns; `done` gets its answer
    /// on the thread that commits it.
    #[cfg(any(feature = "wire", feature = "async"))]
    pub(crate) fn submit<T: Send + 'static>(
        &self,
        key: &str,
        bytes: usize,
        work: impl FnOnce(&Tx<'_>, &Revision) -> Result<T> + Send + 'static,
        done: impl FnOnce(Result<T>) + Send + 'static,
    ) {
        let revision = self.kv.revision();
        let shown = self.shown_key(key);
        let answered = move |answer: Result<T>| done(answer.map_err(|error| error.within(shown)));
        self.kv.file().submit(bytes, move |tx| work(tx, &revision), answered);
    }

    /// Submits the work a call made, or gives `done` why it made none.
    #[cfg(any(feature = "wire", feature = "async"))]
    pub(crate) fn submit_made<T: Send + 'static>(
        &self,
        key: &str,
        bytes: usize,
        work: Result<impl FnOnce(&Tx<'_>, &Revision) -> Result<T> + Send + 'static>,
        done: impl FnOnce(Result<T>) + Send + 'static,
    ) {
        match work {
            Ok(work) => self.submit(key, bytes, work, done),
            Err(error) => done(Err(error)),
        }
    }

    /// The pool of the store the handle's engine opened in, where its awaited
    /// calls run what must not run on an executor's thread; a stopped one once
    /// that store is gone, whose calls answer `Closed`.
    #[cfg(feature = "async")]
    pub(crate) fn pool(&self) -> Arc<crate::pool::Pool> {
        match self.kv.store() {
            Ok(store) => crate::pool::Pool::of_or_stopped(&store),
            Err(_) => crate::pool::Pool::stopped(),
        }
    }

    /// Runs a read on a reader, in one snapshot, naming the key in its errors.
    pub(crate) fn read<T>(&self, key: &str, read: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
        self.kv.file().read(read).map_err(|error| error.within(self.shown_key(key)))
    }
}

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

/// A handle as an error names it: `kv counters hits`, or `sql app: kv bucket
/// sessions` for one kept in a database's file.
fn described(lent_by: Option<&str>, kind: Kind, name: &str) -> String {
    match lent_by {
        Some(owner) => format!("{owner}: kv {} {name}", kind.shown()),
        None => format!("kv {} {name}", kind.shown()),
    }
}

pub(super) fn check_name(name: &str) -> Result<()> {
    crate::text::check_name("the", name)
}