tinystore 0.4.1

A small storage runtime for applications on SQLite: SQL, key-value state, durable jobs, files, search, logs and metrics in one directory
Documentation
use std::fmt;
use std::sync::Arc;
use std::time::Duration;

use rusqlite::Connection;

use super::bucket::{Work, clear_work};
use super::buffer::{Buffer, Change, Live};
use super::cells;
use super::engine::{Revision, next_version};
#[cfg(feature = "replication")]
use super::forward;
use super::path::Key;
use super::scope::{Kind, Scope};
use super::value::Raw;
use crate::clock::millis;
use crate::engine::Home;
use crate::sqlite::Tx;
use crate::{Error, Result, Store};

/// Counters being opened: their name, how long a counter lasts, and whether
/// they are kept in memory between flushes.
#[must_use = "counters open with open()"]
pub struct CountersBuilder {
    store: Store,
    name: String,
    ttl: Option<Duration>,
    flush_every: Option<Duration>,
}

impl Store {
    /// Numbers by key that add up, in the store's kv.db: attempts, hits, uses.
    pub fn counters(&self, name: &str) -> CountersBuilder {
        CountersBuilder { store: self.clone(), name: name.to_owned(), ttl: None, flush_every: None }
    }
}

impl CountersBuilder {
    /// A counter lasts this long from its first add, then starts again from 0:
    /// the adds after the first do not move it.
    pub fn ttl(mut self, ttl: Duration) -> Self {
        self.ttl = Some(ttl);
        self
    }

    /// Keeps the counters in memory and writes what changed once a span, so
    /// that an add costs no commit and a crash loses at most the last span.
    /// Without it each add is written before it returns.
    pub fn flush_every(mut self, span: Duration) -> Self {
        self.flush_every = Some(span);
        self
    }

    pub fn open(self) -> Result<Counters> {
        let shown = || format!("kv counters {}", self.name);
        if self.ttl.is_some_and(|ttl| ttl.is_zero()) {
            return Err(Error::invalid("a ttl of zero").within(shown()));
        }
        if self.flush_every.is_some_and(|span| span.is_zero()) {
            return Err(Error::invalid("a flush every zero").within(shown()));
        }
        let scope = Scope::open(&Home::Store(self.store.clone()), &self.name, Kind::Counters)?;
        let buffer =
            scope.kv.buffer(scope.id, self.flush_every, &scope.shown()).map_err(|error| error.within(scope.shown()))?;
        Ok(Counters { scope, ttl: self.ttl, buffer })
    }
}

/// Numbers by key that only add up; a counter that is not there holds 0.
/// Every handle on a name counts the same way, in the file or in memory.
pub struct Counters {
    pub(crate) scope: Scope,
    ttl: Option<Duration>,
    pub(crate) buffer: Option<Arc<Buffer>>,
}

impl Counters {
    /// Refuses counters kept in memory, which join no transaction or batch.
    pub(crate) fn refuse_in_memory(&self) -> Result<()> {
        if self.buffer.is_none() {
            return Ok(());
        }
        Err(Error::invalid(
            "counters kept in memory join no transaction; open them without flush_every to write them in one",
        )
        .within(self.scope.shown()))
    }

    /// The same counters seen from the branch `owner` names under these.
    pub fn under(&self, owner: impl Key) -> Counters {
        Counters { scope: self.scope.under(owner), ttl: self.ttl, buffer: self.buffer.clone() }
    }

    /// Adds `n` to the counter under `key` and returns what it holds now. A
    /// counter that is not there starts from 0, its ttl from now; a sum past
    /// the range of an `i64` is `Limit` and changes nothing.
    pub fn add(&self, key: impl Key, n: i64) -> Result<i64> {
        let key = key.text();
        #[cfg(feature = "replication")]
        if self.scope.kv.file().is_copy() {
            if self.queued_on_a_copy() {
                return self.add_queued_here(&key, n);
            }
            return forward::sum(&self.pass_on(&key, &forward::Call::Add(n))?);
        }
        let Some(buffer) = &self.buffer else {
            return self.scope.write(&key, 0, self.add_work(&key, n)?);
        };
        let (path, now) = (self.scope.path(&key)?, self.scope.now());
        let created = self.created(now);
        let step = |live: Option<Live>| {
            let (held, expires) = live.map_or((0, created), |live| (live.value, live.expires));
            let sum = held.checked_add(n).ok_or_else(|| overflow(n))?;
            Ok((Change::Set(Live { value: sum, expires }), sum))
        };
        buffer.step(&self.scope.kv, &path, now, step).map_err(|error| error.within(self.scope.shown_key(&key)))
    }

    /// `add` without waiting for its commit: `done` gets the sum on the
    /// thread that commits it. Counters kept in memory answer before this
    /// returns.
    #[cfg(any(feature = "wire", feature = "async"))]
    pub(crate) fn add_then(&self, key: &str, n: i64, done: impl FnOnce(Result<i64>) + Send + 'static) {
        if self.buffer.is_some() || self.on_a_copy() {
            return done(self.add(key, n));
        }
        self.scope.submit_made(key, 0, self.add_work(key, n), done);
    }

    /// `delete` without waiting for its commit.
    #[cfg(any(feature = "wire", feature = "async"))]
    pub(crate) fn delete_then(&self, key: &str, done: impl FnOnce(Result<bool>) + Send + 'static) {
        if self.buffer.is_some() || self.on_a_copy() {
            return done(self.delete(key));
        }
        self.scope.submit_made(key, 0, self.delete_work(key), done);
    }

    /// What the counter under `key` holds; 0 when it is not there.
    pub fn get(&self, key: impl Key) -> Result<i64> {
        let key = key.text();
        #[cfg(feature = "replication")]
        if self.buffer.is_none() && self.scope.kv.file().is_copy() {
            return self.get_with_queued(&key).map_err(|error| error.within(self.scope.shown_key(&key)));
        }
        let (id, path, now) = (self.scope.id, self.scope.path(&key)?, self.scope.now());
        let live = match &self.buffer {
            Some(buffer) => buffer.get(&self.scope.kv, &path, now),
            None => self.scope.kv.file().read(|connection| live(connection, id, &path, now)),
        };
        let live = live.map_err(|error| error.within(self.scope.shown_key(&key)))?;
        Ok(live.map_or(0, |live| live.value))
    }

    /// Removes the counter under `key` and says whether it was there.
    pub fn delete(&self, key: impl Key) -> Result<bool> {
        let key = key.text();
        #[cfg(feature = "replication")]
        if self.scope.kv.file().is_copy() {
            return forward::found(&self.pass_on(&key, &forward::Call::DeleteCounter)?);
        }
        let Some(buffer) = &self.buffer else {
            return self.scope.write(&key, 0, self.delete_work(&key)?);
        };
        let (path, now) = (self.scope.path(&key)?, self.scope.now());
        let step =
            |live: Option<Live>| Ok((if live.is_some() { Change::Remove } else { Change::Leave }, live.is_some()));
        buffer.step(&self.scope.kv, &path, now, step).map_err(|error| error.within(self.scope.shown_key(&key)))
    }

    /// Removes every counter of this branch and of the branches under it, at
    /// once for every reader, however many there are.
    pub fn clear(&self) -> Result<()> {
        #[cfg(feature = "replication")]
        if self.scope.kv.file().is_copy() {
            return self.pass_on("", &forward::Call::ClearCounters).map(drop);
        }
        let work = clear_work(&self.scope)?;
        let prefix = self.scope.branch()?.prefix().to_vec();
        let revision = self.scope.kv.revision();
        let file = self.scope.kv.file();
        let write = move || file.write(0, move |tx| work(tx, &revision));
        let cleared = match &self.buffer {
            Some(buffer) => buffer.clear(&prefix, write),
            None => write(),
        };
        cleared.map_err(|error| error.within(self.scope.shown_branch()))
    }

    /// `clear` without waiting for its commit, for counters written each add
    /// on the file's home. Counters kept in memory hold that memory across
    /// their clear's commit, and a copy's clear blocks on its home: both are
    /// answered before this returns.
    #[cfg(feature = "async")]
    pub(crate) fn clear_then(&self, done: impl FnOnce(Result<()>) + Send + 'static) {
        if self.buffer.is_some() || self.on_a_copy() {
            return done(self.clear());
        }
        let work = match clear_work(&self.scope) {
            Ok(work) => work,
            Err(error) => return done(Err(error)),
        };
        let (revision, shown) = (self.scope.kv.revision(), self.scope.shown_branch());
        let answered = move |cleared: Result<()>| done(cleared.map_err(|error| error.within(shown)));
        self.scope.kv.file().submit(0, move |tx| work(tx, &revision), answered);
    }

    /// Whether the counters are kept in memory between flushes.
    #[cfg(feature = "async")]
    pub(crate) fn in_memory(&self) -> bool {
        self.buffer.is_some()
    }

    /// Whether the counters' file is a copy, whose writes block on their home
    /// rather than queue for a commit here.
    #[cfg(any(feature = "wire", feature = "async"))]
    pub(crate) fn on_a_copy(&self) -> bool {
        #[cfg(feature = "replication")]
        return self.scope.kv.file().is_copy();
        #[cfg(not(feature = "replication"))]
        false
    }

    /// Whether an add on a copy is queued on this node and answered at once,
    /// rather than passed on to the home and waited for: an add of counters
    /// written each add, in the store's own kv.db.
    #[cfg(any(feature = "replication", feature = "async"))]
    pub(crate) fn queued_on_a_copy(&self) -> bool {
        self.buffer.is_none() && self.scope.kv.lent_by().is_none()
    }

    /// An add on a copy, queued on this node and answered at once: the copy's
    /// count with what the queue still holds of the key. Adds commute, so the
    /// home counts them whenever they arrive, each once.
    #[cfg(feature = "replication")]
    fn add_queued_here(&self, key: &str, n: i64) -> Result<i64> {
        let shown = || self.scope.shown_key(key);
        let store = self.scope.kv.store().map_err(|error| error.within(shown()))?;
        let owners = self.scope.branch()?.owners().to_vec();
        let handle = forward::Handle::Counters { name: self.scope.name().to_owned(), ttl: self.ttl };
        let request = forward::encode(&handle, &owners, key, &forward::Call::AddQueued { n, from: None });
        let subject = forward::subject(self.scope.name(), &owners, key);
        crate::replication::enqueue(&store, forward::FILE, subject, request).map_err(|error| error.within(shown()))?;
        self.get(key)
    }

    /// A copy's count with what this node's queue holds of `key`'s adds that
    /// the copy does not hold yet. The queue is read first: an op it no longer
    /// holds left it once the copy held it, so the copy's snapshot after has it.
    #[cfg(feature = "replication")]
    fn get_with_queued(&self, key: &str) -> Result<i64> {
        let store = self.scope.kv.store()?;
        let subject = forward::subject(self.scope.name(), self.scope.branch()?.owners(), key);
        let pending = crate::replication::queued(&store, forward::FILE, &subject)?;
        let (id, path, now) = (self.scope.id, self.scope.path(key)?, self.scope.now());
        let (held, applied) = self.scope.kv.file().read(|connection| {
            let held = live(connection, id, &path, now)?.map_or(0, |live| live.value);
            Ok((held, cells::queued_applied(connection, &pending.node)?.unwrap_or(0)))
        })?;
        let not_held = pending.ops.iter().filter(|queued| queued.op as i64 > applied);
        Ok(not_held.filter_map(|queued| forward::added(&queued.request)).fold(held, i64::saturating_add))
    }

    /// An add a node queued, applied at the home only past the last op of
    /// that node it applied, in the commit that keeps the op's number: an op
    /// sent twice counts once.
    #[cfg(feature = "replication")]
    pub(crate) fn add_queued(&self, key: &str, n: i64, node: &str, op: u64) -> Result<i64> {
        if self.scope.kv.file().is_copy() {
            // a node between the one that queued it and its home passes it on as it came
            let call = forward::Call::AddQueued { n, from: Some((node.to_owned(), op)) };
            return forward::sum(&self.pass_on(key, &call)?);
        }
        let now = self.scope.now();
        let (id, path, created) = (self.scope.id, self.scope.path(key)?, self.created(now));
        let (node, op) = (node.to_owned(), i64::try_from(op).map_err(|_| Error::invalid("an op past 2^63"))?);
        self.scope.write(key, 0, move |tx: &Tx<'_>, revision: &Revision| {
            if cells::queued_applied(tx, &node)?.is_some_and(|applied| applied >= op) {
                return Ok(live(tx, id, &path, now)?.map_or(0, |live| live.value));
            }
            let version = next_version(revision, tx)?;
            let added = cells::add(tx, id, &path, (version, created), n, now)?;
            cells::keep_queued_applied(tx, &node, op)?;
            // its caller had its answer when the node queued it, so an add past
            // an i64 is let go rather than refused, which would hold the queue
            let Some(sum) = added else {
                tracing::warn!(
                    target: "tinystore",
                    node,
                    op,
                    n,
                    "a queued add passes the range of an i64 and is not counted",
                );
                return Ok(live(tx, id, &path, now)?.map_or(0, |live| live.value));
            };
            Ok(sum)
        })
    }

    /// Passes a call on `key` to the home of the copy the counters' file is.
    #[cfg(feature = "replication")]
    fn pass_on(&self, key: &str, call: &forward::Call) -> Result<Vec<u8>> {
        let handle = forward::Handle::Counters { name: self.scope.name().to_owned(), ttl: self.ttl };
        self.scope.pass_on(&handle, key, call)
    }

    pub(crate) fn add_work(&self, key: &str, n: i64) -> Result<impl Work<i64> + use<>> {
        let now = self.scope.now();
        let (id, path, created) = (self.scope.id, self.scope.path(key)?, self.created(now));
        Ok(move |tx: &Tx<'_>, revision: &Revision| {
            let version = next_version(revision, tx)?;
            cells::add(tx, id, &path, (version, created), n, now)?.ok_or_else(|| overflow(n))
        })
    }

    pub(crate) fn delete_work(&self, key: &str) -> Result<impl Work<bool> + use<>> {
        let now = self.scope.now();
        let (id, path) = (self.scope.id, self.scope.path(key)?);
        Ok(move |tx: &Tx<'_>, _: &Revision| {
            let was_live = cells::current(tx, id, &path, now)?.is_some_and(|current| current.live);
            cells::remove(tx, id, &path, None)?;
            Ok(was_live)
        })
    }

    /// The counter under `key` as `connection` sees it.
    pub(crate) fn get_on(&self, connection: &Connection, key: &str) -> Result<i64> {
        let (id, path, now) = (self.scope.id, self.scope.path(key)?, self.scope.now());
        Ok(live(connection, id, &path, now)?.map_or(0, |live| live.value))
    }

    fn created(&self, now: i64) -> Option<i64> {
        self.ttl.map(|ttl| now.saturating_add(millis(ttl)))
    }
}

impl Clone for Counters {
    fn clone(&self) -> Self {
        Counters { scope: self.scope.clone(), ttl: self.ttl, buffer: self.buffer.clone() }
    }
}

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

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

/// A counter's row as a live counter, read on `connection`.
pub(crate) fn live(connection: &Connection, id: i64, path: &[u8], now: i64) -> Result<Option<Live>> {
    let Some(cell) = cells::live(connection, id, path, now)? else {
        return Ok(None);
    };
    match cell.raw {
        Raw::Int(value) => Ok(Some(Live { value, expires: cell.expires })),
        _ => Err(Error::corrupt("a counter's row holds no integer")),
    }
}

fn overflow(n: i64) -> Error {
    Error::limit(format!("adding {n} passes the range of an i64"))
}

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