Reference / Store API for Rust
Store API for Rust
Every public type, trait and function of the store in tinystore and tinystore::aio and tinystore::limits, generated from its source. The Store guide explains how to use them, and the Bun and Node, Python and Go pages list the same API.
Calendar
pub enum Calendar {
Day,
Week,
Month,
}The span of the calendar a bucket covers, in the time zone an aggregate gives with it.
Calendar.as_str
pub fn as_str(self) -> &'static strThe unit as the wire and every SDK spell it: day, week, month.
LocalDate
pub struct LocalDate(_)The local date a calendar's span begins on, as ISO 8601 writes it:
2026-11-19 for a day, its Monday for a week, its first for a month.
Text held in place, so that a bucket that carries one stays Copy.
LocalDate.as_str
pub fn as_str(&self) -> &strThe date as text: 2026-11-19.
CancellationToken
pub struct CancellationToken { /* private fields */ }Stops the reads of a call from another thread, at once or after a
timeout: a read under way stops, gives its reader back and fails
Cancelled, and one that has not started fails before it takes one.
The token stops what run runs, on its thread:
use tinystore::CancellationToken;
let token = CancellationToken::new();
let counting = std::thread::spawn({
let (db, token) = (db.clone(), token.clone());
move || token.run(|| db.scalar::<i64>("select count(*) from events"))
});
token.cancel(); // the visitor left: the count stops with `Cancelled`, its reader back
let timed = CancellationToken::timeout(Duration::from_secs(2));
let total: i64 = timed.run(|| db.scalar("select count(*) from events"))?;Only reads stop: a write runs to its end, and so does a read inside a transaction, which its own bound stops. Clones share the token.
A program built with mcp and no store has no reads to stop: there the
token is what an MCP tool's handler asks
is_cancelled.
CancellationToken.new
pub fn new() -> SelfCancellationToken.timeout
pub fn timeout(after: Duration) -> SelfA token that stops its reads once after has passed since it was
made, or earlier when it is cancelled.
A timeout is read as a statement runs and as a read waits; a statement
SQLite runs as one step, as a count(*) of a whole table, finishes that
step first, where cancel stops it at once.
CancellationToken.cancel
pub fn cancel(&self)Stops the reads under the token now and from now on.
CancellationToken.is_cancelled
pub fn is_cancelled(&self) -> boolWhether the token was cancelled or its timeout passed.
CancellationToken.run
pub fn run<T>(&self, call: impl FnOnce() -> T) -> TRuns call on this thread with the token over every read it makes:
once the token is cancelled, each read under way fails Cancelled and
each one after it fails before it starts. Tokens nest: a read stops
when any token around it does.
Clock
pub trait ClockWhere a store reads the time. Every engine reads it through the store, so a test that moves one clock moves them all.
Clock.now
fn now(&self) -> SystemTimeSystemClock
pub struct SystemClockThe system's clock.
TestClock
pub struct TestClock { /* private fields */ }A clock a test moves by hand. It never moves backwards: engines keep watermarks and leases by it, and a step back would make them lie.
TestClock.new
pub fn new(start: SystemTime) -> SelfTestClock.advance
pub fn advance(&self, by: Duration)TestClock.set
pub fn set(&self, to: SystemTime) -> Result<()>unix_millis
pub fn unix_millis(time: SystemTime) -> i64Milliseconds since the Unix epoch; negative before it.
unix_nanos
pub fn unix_nanos(time: SystemTime) -> i64Nanoseconds since the Unix epoch; negative before it.
Not
pub struct Not<T>(pub T)A value equal to none of these, or absent: Not("dev"), Not(["dev", "test"]).
Prefix
pub struct Prefix<T>(pub T)A text that starts with this one: Prefix("api-").
Constraint
pub struct Constraint {
pub kind: ConstraintKind,
pub table: Option<String>,
pub columns: Vec<String>,
pub name: Option<String>,
}A constraint a write broke, as SQLite names it: its kind always, and the table and the columns, or the constraint's own name, when SQLite says them.
ConstraintKind
pub enum ConstraintKind {
Unique,
PrimaryKey,
ForeignKey,
Check,
NotNull,
}A unique or a primary key already held is conflict; any other is
invalid.
ConstraintKind.as_str
pub fn as_str(self) -> &'static strThe kind as the wire and every SDK say it: primaryKey.
Error
pub struct Error { /* private fields */ }An error that names what failed: kv bucket sessions: key "a": not found.
Error.new
pub fn new(kind: ErrorKind, what: impl Into<String>) -> SelfError.invalid
pub fn invalid(what: impl Into<String>) -> SelfError.not_found
pub fn not_found(what: impl Into<String>) -> SelfError.closed
pub fn closed(what: impl Into<String>) -> SelfError.limit
pub fn limit(what: impl Into<String>) -> SelfError.corrupt
pub fn corrupt(what: impl Into<String>) -> SelfError.internal
pub fn internal(what: impl Into<String>) -> SelfError.io
pub fn io(what: impl Into<String>, source: Error) -> SelfError.with_source
pub fn with_source(self, source: impl Into<Box<dyn StdError + Send + Sync>>) -> SelfError.within
pub fn within(self, outer: impl Display) -> SelfThe same error, said of what contains it: kv bucket sessions around
key "a" reads kv bucket sessions: key "a".
Error.duplicate
pub fn duplicate(&self) -> SelfA copy for each of several callers one failure answers, its cause kept as text.
Error.fact
pub fn fact(&self, name: &str) -> Option<&str>A fact the error carries by name: a limit's limit, wanted and
bound; a broken constraint's constraint, table, columns and
name, which Error::constraint reads as one; a metrics sample's
at and the time its series is packed before, when it is too old.
Error.constraint
pub fn constraint(&self) -> Option<Constraint>The constraint a write broke, as SQLite names it:
match db.exec(sql!("insert into users (email) values (?)", "ann@example.com")) {
Err(error) if error.constraint().is_some_and(|broken| broken.columns == ["email"]) => {
println!("that email is taken")
}
done => drop(done?),
}Error.kind
pub fn kind(&self) -> ErrorKindError.what
pub fn what(&self) -> &strErrorKind
pub enum ErrorKind {
Invalid,
NotFound,
Conflict,
TooOld,
TooNew,
Limit,
Closed,
Corrupt,
InUse,
Suspended,
Unavailable,
Cancelled,
OutcomeUnknown,
CommittedLocally,
Lost,
Io,
Internal,
}What went wrong, with the same meaning in every engine, on the wire and in every SDK.
ErrorKind.as_str
pub fn as_str(self) -> &'static strResult
pub type Result<T, E> = Result<T, E>Key
pub trait KeyWhat names a key, an owner or a folder: text, or an integer spelled in
decimal, so that 42 and "42" are one key.
Key.text
fn text(&self) -> Cow<'_, str>Memory
pub struct Memory { /* private fields */ }Memory.new
pub fn new(limit: u64) -> Arc<Self>Memory.limit
pub fn limit(&self) -> u64Memory.used
pub fn used(&self) -> u64Memory.bounded
pub fn bounded(&self) -> boolWhether the store was given a budget; without one, work reserves nothing and pays nothing for it.
Memory.try_reserve
pub fn try_reserve(self: &Arc<Self>, bytes: u64, what: &str) -> Result<Reservation>Takes bytes now, or fails with Limit: so does a call that would
take the room a waiting reservation waits for.
Memory.nothing
pub fn nothing(self: &Arc<Self>) -> ReservationA reservation of nothing yet, which grows as its work holds more.
Memory.reserve
pub fn reserve(self: &Arc<Self>, bytes: u64, what: &str, patience: Duration) -> Result<Reservation>Takes bytes, waiting up to patience for other work to give them
back; waiters are served in the order they came, and a call that
takes nothing waits for none of them. A crate::CancellationToken
around the call does not stop the wait: only reads stop.
Reservation
pub struct Reservation { /* private fields */ }Bytes taken from a store's memory, given back when dropped.
Reservation.bytes
pub fn bytes(&self) -> u64Reservation.grow
pub fn grow(&mut self, bytes: u64, what: &str) -> Result<()>Takes bytes more now, or fails with Limit and keeps what it held.
Reservation.shrink
pub fn shrink(&mut self, to: u64)Gives back what the work turned out not to need.
Durability
pub enum Durability {
Full,
Os,
}How far a commit goes before it returns: a setting of a store's files,
kv.db, jobs.db and each database's, which Options
gives for them all and a database may say for itself.
Options
pub struct Options {
pub memory: Option<u64>,
pub clock: Option<Arc<dyn Clock>>,
pub background: bool,
pub durability: Option<Durability>,
pub keep_free: u64,
pub encryption_key_file: Option<PathBuf>,
pub older_encryption_keys: Vec<PathBuf>,
pub node: Option<Node>,
pub self_metrics: Option<SelfMetrics>,
pub max_series: u64,
pub cli: bool,
}How a store opens.
Store
pub struct Store { /* private fields */ }One directory of engine files, held by one store at a time through its
LOCK. Engines open against a store and close with it, the last opened
first: at close, or when the last clone of the store is dropped.
Store.open
pub fn open(dir: impl AsRef<Path>, options: Options) -> Result<Store>Opens the store in dir, creating the directory when it is missing.
Another store holding the directory, in this process or another, makes
it an InUse error.
Store.open_beside
pub fn open_beside(dir: impl AsRef<Path>) -> Result<Store>Opens the store in dir to read beside the process that holds it, a
server or a program: no lock taken, no background work, each file read
through readers alone, none written and none checkpointed. A write is
refused, Invalid, and a file the store does not hold is NotFound
rather than made. What the holder commits meanwhile, a read sees.
Store.dir
pub fn dir(&self) -> &PathStore.is_beside
pub fn is_beside(&self) -> boolWhether the store was opened beside its holder, to read only.
Store.keep_free
pub fn keep_free(&self) -> u64The bytes of the disk the store keeps free, as its options said.
Store.max_series
pub fn max_series(&self) -> u64The metrics series the store holds at most, as its options said.
Store.now
pub fn now(&self) -> SystemTimeStore.clock_moved
pub fn clock_moved(&self)Tells every engine that a test moved the store's clock by hand, so that what sleeps until a time reads it again: a worker waiting for a job due in an hour runs it once the clock is an hour on.
Store.memory
pub fn memory(&self) -> &Arc<Memory>Store.close
pub fn close(&self) -> Result<()>Stops background work, waiting for the task under way, then every
handler the engines run, a queue's or a channel's, waiting for those
running; then closes every engine, the last opened first, and lets go
of the directory. The first engine that fails to close is the error;
the others still close. A second call does nothing, and neither does
the last clone's drop after. From inside a transaction it is
Invalid: it would wait for the writer the transaction holds. So it is
from inside one of the handlers it waits for, a worker's, a schedule's
or a subscription's, blocking or awaited: it would wait for the handler
that calls it. Such a handler returns first, or stops its worker or its
subscription, whose stop returns at once there.
Store.tx
pub fn tx<T, E: From<Error>>(&self, work: impl FnOnce(&Tx<'_>) -> Result<T, E>) -> Result<T, E>Runs work in one transaction of one of the store's own files, kv.db
or jobs.db: the file of the first handle tx.with takes in, whose
writer it then holds alone, so that what it reads cannot change before
it writes. Two orders cannot both take the last item, and a hundred
jobs are added together or not at all. It commits when work returns
Ok and rolls back when it returns an error or panics.
Inside, every call on the store's buckets and queues goes through the
transaction, tx.with(&bucket): one made around it would not see what
it wrote, or would wait for the writer it holds, and fails Invalid
instead. A bucket and a queue of the store are two files, and no write
is atomic across two: a handle kept in another file than the first is
Invalid, and to commit keys and jobs together a program opens both
from a database. Writes that need no reads need no transaction, since
separate calls already share commits.
Tx
pub struct Tx<'a> { /* private fields */ }A transaction of the store, given to the function Store::tx runs.
Tx.with
pub fn with<'h, H: TxHandle>(&self, handle: &'h H) -> H::InTxThe calls of handle inside this transaction: what they read sees what
the transaction wrote, and what they write commits with it or not at
all. A handle kept in another file is refused at its first call.
Transaction
pub struct Transaction<'t> { /* private fields */ }A transaction as the handles it takes in see it: the writer it holds, the file a handle must be kept in, the bound it ends within, and what runs once it ends.
TxHandle
pub trait TxHandleA handle a transaction of its file takes in with tx.with(&handle): a
bucket or counters, and a queue, from the store or from a database.
sql
macro_rules! sqlA statement and the values of its ?s, in order:
sql!("select * from notes where author_id = ? and done = ?", user_id, false).
aio::Store
pub struct Store { /* private fields */ }A store whose calls are awaited: the same directory, engines and files as
crate::Store, and the same store when one is made from the other.
use tinystore::Options;
use tinystore::aio::Store;
let store = Store::open("data", Options::default())?;
let stock = store.blocking().bucket::<i64>("stock").open()?;
let placed = store
.tx(move |tx| -> tinystore::Result<bool> {
let left = tx.with(&stock).get("sku-1")?.unwrap_or(0);
if left < 1 {
return Ok(false); // sold out: nothing written
}
tx.with(&stock).set("sku-1", &(left - 1))?;
Ok(true)
})
.await?;
store.close().await?;aio::Store.open
pub fn open(dir: impl AsRef<Path>, options: Options) -> Result<Store>Opens the store in dir as crate::Store::open does: a plain call,
made once at start.
aio::Store.open_beside
pub fn open_beside(dir: impl AsRef<Path>) -> Result<Store>Opens the store in dir to read beside the process that holds it, as
crate::Store::open_beside does.
aio::Store.blocking
pub fn blocking(&self) -> &StoreThe same store, for its blocking calls: a command-line tool and a server beside it share one store, its engines and its files.
aio::Store.dir
pub fn dir(&self) -> &Pathaio::Store.now
pub fn now(&self) -> SystemTimeaio::Store.close
pub fn close(&self) -> impl Future<Output = Result<()>> + Send + 'staticCloses the store as crate::Store::close does, on a thread the call
starts, so that the executor's thread waits for nothing: the close
waits for background work, for the handlers running and for each
engine's last writes. A store whose last handle is dropped closes on
the dropping thread instead, which may be the executor's. Awaited
inside a transaction or a handler it waits for, it is Invalid at its
first poll, as the blocking close is.
aio::Store.tx
pub fn tx<T, E, F>(&self, work: F) -> impl Future<Output = Result<T, E>> + Send + 'static
where
F: FnOnce(&Tx<'_>) -> Result<T, E> + Send + 'static,
T: Send + 'static,
E: From<Error> + Send + 'static,Runs work in one transaction of one of the store's own files, as
crate::Store::tx does, on a thread of the store's pool: work is
blocking and holds the file's writer, so it must not wait for the
program's awaits, and it runs on no executor's thread. Inside, the
calls of a handle go through tx.with(&handle) and are blocking.
Once polled it runs to its end, as a write does, whether or not anyone
still awaits it. A panic in work rolls the transaction back and is
resumed at the .await.
Limit
pub struct Limit {
pub name: &'static str,
pub bound: u64,
}A bound by its name, which a limit error's limit fact gives, and the
most it takes, its bound fact.
VALUE_BYTES
pub const VALUE_BYTES: LimitA bucket's value, as it is stored.
SETTING_BYTES
pub const SETTING_BYTES: LimitA live setting's change, as JSON.
CONFIG_BYTES
pub const CONFIG_BYTES: LimitEvery change a config keeps, together.
LOCK_WAITERS
pub const LOCK_WAITERS: LimitThe callers that wait for one lock or semaphore at once.
SUBSCRIPTIONS
pub const SUBSCRIPTIONS: LimitThe subscriptions to the store's channels at once.
JOB_BYTES
pub const JOB_BYTES: LimitA job's payload, its result or a step's answer, as JSON.
PROGRESS_BYTES
pub const PROGRESS_BYTES: LimitA run's progress, as JSON.
ROWS_BYTES
pub const ROWS_BYTES: LimitThe values one call reads from a database: past them, read a page at a time or a row at a time.
MIRROR_ROWS
pub const MIRROR_ROWS: LimitThe rows of a mirror's list, and those its scope holds.
EVENT_BYTES
pub const EVENT_BYTES: LimitOne event, its name, fields and text together.
APPEND_BYTES
pub const APPEND_BYTES: LimitThe events of one append together.
AGGREGATE_ROWS
pub const AGGREGATE_ROWS: LimitThe rows one aggregate answers.
COUNT_BYTES
pub const COUNT_BYTES: LimitThe different values one top or distinct holds, as JSON.
SESSIONS
pub const SESSIONS: LimitThe sessions one sessions holds while it cuts them, those still open
among them, and answers.
SESSION_BYTES
pub const SESSION_BYTES: LimitWhat one sessions holds: the events each session keeps, and its values
of by.
WHERE_VALUE_BYTES
pub const WHERE_VALUE_BYTES: LimitA value a where's statement gives, as JSON.
SUM_RANGE
pub const SUM_RANGE: LimitThe bits an aggregate row's sum of integers is held in, its sign among
them: a sum is exact, and past them limit rather than a float.
INGEST_SAMPLES
pub const INGEST_SAMPLES: LimitThe samples of one ingest, written in one write: what one exporter's
text takes.
INGEST_BYTES
pub const INGEST_BYTES: LimitThe bytes of one ingest's samples, each with its labels.
REPLACE_SAMPLES
pub const REPLACE_SAMPLES: LimitThe samples of one gauge's replace, which decodes and cuts the blocks
its range reaches.
REPLACE_BYTES
pub const REPLACE_BYTES: LimitThe bytes of one replace's samples, with the series' labels.
TEXT_SAMPLES
pub const TEXT_SAMPLES: LimitThe samples of one exporter's text.
TEXT_BYTES
pub const TEXT_BYTES: LimitOne exporter's text, and the bytes of its samples.
QUERY_SERIES
pub const QUERY_SERIES: LimitThe series one query finds.
QUERY_BYTES
pub const QUERY_BYTES: LimitWhat one query reads from the file: labels, directories, payloads, heads.
QUERY_SAMPLES
pub const QUERY_SAMPLES: LimitThe samples one query decodes.
QUERY_ANSWER
pub const QUERY_ANSWER: LimitThe samples or buckets one query answers.
SET_MANY_DOCUMENTS
pub const SET_MANY_DOCUMENTS: LimitThe documents of one set_many.
SET_MANY_BYTES
pub const SET_MANY_BYTES: LimitThe documents of one set_many as JSON.
DOCUMENT_BYTES
pub const DOCUMENT_BYTES: LimitOne document as JSON, or a table's row as its index reads it.
SEARCH_HITS
pub const SEARCH_HITS: LimitThe hits a search reaches, its offset and its limit together.
SEARCH_TEXT
pub const SEARCH_TEXT: LimitA search's text, in bytes.
FILTER_CONDITIONS
pub const FILTER_CONDITIONS: LimitThe conditions of one search's filter.
FILTER_VALUES
pub const FILTER_VALUES: LimitThe values the lists of one search's conditions hold together.
FILTER_ROWS
pub const FILTER_ROWS: LimitThe rows a statement of a where gives: a table's index's, or a stream's.
FILTER_TEXT
pub const FILTER_TEXT: LimitA text a filter keeps or asks for, in bytes.
VECTOR_DIMENSIONS
pub const VECTOR_DIMENSIONS: LimitA vector's dimensions.
REQUEST_BYTES
pub const REQUEST_BYTES: LimitOne request over the wire, its message sent in several frames past one, as every SDK and the command line agree it at their HELLO: a call whose message is larger fails before it is sent. Against a server that agrees no max message, one released before multi-frame messages, it is one frame's body, 2 MiB.
ANSWER_BYTES
pub const ANSWER_BYTES: LimitOne answer over the wire, agreed as a request is.