Reference / Records API for Rust
Records API for Rust
Every public type, trait and function of the Records engine in tinystore::records and tinystore::console and tinystore::aio::records, generated from its source. The Records guide explains how to use them, and the Bun and Node, Python and Go pages list the same API.
Store
impl StoreStore.logger
pub fn logger(&self, stream: &str) -> LoggerBuilder<'_>A logger of the stream stream: a tracing layer that prints each
line as it is logged, and keeps it within a second without ever
making its caller wait.
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
let store = tinystore::Store::open("data", Default::default())?;
tracing_subscriber::registry().with(store.logger("api").layer()?).init();
tracing::info!(user = 42, "signed in");Store.events
pub fn events(&self, stream: &str) -> EventsBuilder<'_>The stream of events stream, made the first time it opens: events
appended whole, and read back by time and by what they hold.
Store.all_events
pub fn all_events(&self) -> Result<AllEvents>Every stream's events, to read.
aio::Store
impl aio::Storeaio::Store.logger
pub fn logger(&self, stream: &str) -> LoggerBuilder<'_>A logger of the stream stream, as crate::Store::logger gives
one: a tracing layer whose lines go to a buffer and never wait.
aio::Store.events
pub fn events(&self, stream: &str) -> EventsBuilder<'_>The stream of events stream, made the first time it opens, as
crate::Store::events opens it: its appends and reads awaited.
aio::Store.all_events
pub fn all_events(&self) -> Result<AllEvents>Every stream's events, to read. The first opens the records engine, a plain call made once at start, since it may migrate records.db.
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-").
FieldInfo
pub struct FieldInfo {
pub name: String,
pub kinds: Vec<Kind>,
pub count: u64,
}A key of a stream's events' fields or contexts.
Kind
pub enum Kind {
Float,
Integer,
Text,
Bool,
Object,
List,
Null,
}What a value is, as its JSON is spelled.
Kind.name
pub fn name(self) -> &'static strHow the wire and every SDK spell it.
NameCount
pub struct NameCount {
pub name: String,
pub count: u64,
}A name a stream's events have, and how many have it.
StreamFields
pub struct StreamFields {
pub event_names: Vec<NameCount>,
pub fields: Vec<FieldInfo>,
pub context: Vec<FieldInfo>,
}What a stream's events carry, by name.
Condition
pub struct Condition(_)What a key's value must be for a read to find an event: one of some JSON
values, none of them, or a text that starts with a prefix. A value, a
Not, a Prefix or a statement of a database converts into one.
Aggregate
pub struct Aggregate { /* private fields */ }What aggregate makes rows of: spans of every or of a calendar, the
values of the keys in by, and of the fields in stats and distinct.
Aggregate.new
pub fn new() -> AggregateAggregate.every
pub fn every(self, span: Duration) -> SelfA row a span this long, each beginning at a whole number of them since 1970; the whole range is one span without it.
Aggregate.calendar
pub fn calendar(self, unit: Calendar, zone: &str) -> SelfA row a span of the calendar of a time zone, its IANA name:
calendar(Calendar::Day, "Europe/Moscow") begins each at a local
midnight, a day 23 or 25 hours long when the clock moves; a row's at
is the instant its span begins.
Aggregate.by
pub fn by<S: Into<String>>(self, keys: impl IntoIterator<Item = S>) -> SelfA row a value of each key: a field's, or stream, name, level or
message, which are the event's own before a field of that name.
Aggregate.stats
pub fn stats<S: Into<String>>(self, keys: impl IntoIterator<Item = S>) -> SelfThe count, sum, least, most and mean of each field's numbers.
Aggregate.distinct
pub fn distinct<S: Into<String>>(self, keys: impl IntoIterator<Item = S>) -> SelfHow many different values each field has.
Aggregate.fill
pub fn fill(self) -> SelfA row for every span of the range the stream keeps, of each value of
by the answer has, an empty one counting 0: the read needs a start,
since or from, and the rows, filled ones too, are 10,000 at most.
Number
pub enum Number {
Integer(i128),
Float(f64),
}A number a field holds: an integer exactly, however large a sum of them grows, or a float.
Number.as_f64
pub fn as_f64(self) -> f64Row
pub struct Row {
pub at: SystemTime,
pub count: u64,
pub by: BTreeMap<String, Value>,
pub stats: BTreeMap<String, Stats>,
pub distinct: BTreeMap<String, u64>,
pub date: Option<LocalDate>,
}A row of aggregate: a span of time and a value of each key by named.
Stats
pub struct Stats {
pub samples: u64,
pub sum: Number,
pub min: Number,
pub max: Number,
pub avg: f64,
}What a row says of the numbers a field holds; a field with no number in a row has none there.
StreamInfo
pub struct StreamInfo {
pub name: String,
pub keep: Duration,
pub retained_from: SystemTime,
pub newest: SystemTime,
}What a store holds of a stream.
Top
pub struct Top {
pub value: Value,
pub count: u64,
}A value of a key and how many events hold it.
Event
pub struct Event {
pub at: SystemTime,
pub stream: String,
pub id: Option<String>,
pub name: String,
pub level: Option<Level>,
pub message: Option<String>,
pub fields: Fields,
pub context: Fields,
pub trace_id: Option<TraceId>,
pub span_id: Option<SpanId>,
}An event as a read gives it.
Fields
pub struct Fields(_)An event's fields, or its context: keys in the order they were written,
each value the JSON it was written as, so that 1.2300, an integer past
2⁵³ and a key written twice come back as they went in.
Fields.of
pub fn of(value: &impl Serialize) -> Result<Fields>The fields of a struct or a map, in the order it writes them; ()
is none.
Fields.read
pub fn read(object: &str) -> Result<Fields>The fields of a JSON object's text; null is none.
Fields.len
pub fn len(&self) -> usizeFields.is_empty
pub fn is_empty(&self) -> boolFields.iter
pub fn iter(&self) -> impl Iterator<Item = (&str, &str)>Each key with the JSON of its value, in the order they were written.
Fields.json
pub fn json(&self, key: &str) -> Option<&str>The JSON a key's value was written as; the last, of a key written twice.
Fields.get
pub fn get<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>>A key's value, read as T; None without the key.
Fields.to
pub fn to<T: DeserializeOwned>(&self) -> Result<T>The fields read as a struct or a map.
Level
pub struct Level(_)How grave an event is: one of six names, or a number between two of them
as Go's slog counts, which reads as the name under it.
Level.TRACE
pub const TRACE: LevelLevel.DEBUG
pub const DEBUG: LevelLevel.INFO
pub const INFO: LevelLevel.WARN
pub const WARN: LevelLevel.ERROR
pub const ERROR: LevelLevel.FATAL
pub const FATAL: LevelLevel.of
pub fn of(number: i32) -> LevelThe level of slog's number: -4 debug, 0 info, 4 warn, 8 error.
Level.number
pub fn number(self) -> i32Level.name
pub fn name(self) -> &'static strNewEvent
pub struct NewEvent { /* private fields */ }An event to write: its name, and what it carries beside its fields.
NewEvent.new
pub fn new(name: &str) -> NewEventNewEvent.id
pub fn id(self, id: impl AsRef<str>) -> SelfWhat names it in its stream, a webhook's delivery or a job's key: an append of an id the stream holds writes nothing, so that an append sent again is harmless. The stream holds an id while it keeps its event; the first event of an id stands, whatever a later one carries.
NewEvent.at
pub fn at(self, at: SystemTime) -> SelfIts time: when it is appended, unless given.
NewEvent.level
pub fn level(self, level: Level) -> SelfNewEvent.message
pub fn message(self, message: &str) -> SelfNewEvent.fields
pub fn fields(self, fields: &impl Serialize) -> SelfWhat happened: a struct or a map, kept as the JSON it writes.
NewEvent.context
pub fn context(self, context: &impl Serialize) -> SelfWhat it happened in: who asked, which request.
NewEvent.trace
pub fn trace(self, trace_id: TraceId, span_id: SpanId) -> SelfSpanId
pub struct SpanId(pub [u8; 8])A span's id: eight bytes, written as 16 hex digits.
TraceId
pub struct TraceId(pub [u8; 16])A trace's id: sixteen bytes, written as 32 hex digits.
AllEvents
pub struct AllEvents { /* private fields */ }Every stream's events, to read.
AllEvents.fields
pub fn fields(&self, stream: &str) -> Result<StreamFields>What the events of stream carry, none of it read from a packed
event: each name with how many events have it, and each key of their
fields and of their contexts with the kinds of value it holds and how
many events carry it, each by name. It counts every event the stream
holds, as streams finds them: one older than the stream's keep
among them while it shares a segment with newer ones, since expiry
removes a segment whole. A stream with no events carries nothing, and
a name no stream could have is invalid.
let store = tinystore::Store::open("data", Default::default())?;
let orders = store.all_events()?.fields("orders")?;
for field in &orders.fields {
println!("{} {:?} in {} events", field.name, field.kinds, field.count);
}AllEvents.streams
pub fn streams(&self) -> Result<Vec<StreamInfo>>Every stream with events, by name: what it keeps, where what it keeps begins, and its newest event's time.
AllEvents.list
pub fn list(&self) -> ListThe events of every stream, or of those streams names, found by
the conditions the answer adds.
AllEvents.poll
pub fn poll(&self, cursor: Option<&str>) -> Result<PollBatch>Every packed event once, a batch a call, 1000 at most: from cursor,
a batch's, or from the oldest event kept without one. With no event
past the cursor, the batch is empty and its cursor the one given;
with no event at all, the cursor where the next packed ones begin.
AllEvents.poll_limit
pub fn poll_limit(&self, cursor: Option<&str>, limit: usize) -> Result<PollBatch>As poll, limit events at most, 10,000 at the most.
AllEvents.damaged
pub fn damaged(&self) -> Result<Vec<Damage>>What reads, packing, merges and polls met that no longer reads,
which drop removes: each head row and segment with its stream and
its events' times. What this run of the store has not met yet is not
listed.
AllEvents.drop
pub fn drop(&self, damage: &Damage) -> Result<()>Removes a head row or a segment that no longer reads, so that the reads over it work again: a segment with its blocks and places, its events counted as expired for a poll behind it. What still reads is refused.
EventCall
pub struct EventCall<'e> { /* private fields */ }One event on its way into a stream.
EventCall.appending
pub fn appending(self, fields: &impl Serialize) -> WriteThe event's append for a batch of the database its stream was opened
from, with what the call carries beside its fields, its id, its time;
see Events::appending. One made
through a transaction runs in it, and fails the batch.
EventCall.id
pub fn id(self, id: impl AsRef<str>) -> SelfWhat names it in its stream, a webhook's delivery or a job's key: an
append of an id the stream holds writes nothing and gives false,
so that an append sent again is harmless. The stream holds an id
while it keeps its event, and the first event of an id stands.
EventCall.at
pub fn at(self, at: SystemTime) -> SelfIts time, from as long ago as the stream keeps to ten minutes ahead of the store's clock.
EventCall.level
pub fn level(self, level: Level) -> SelfEventCall.message
pub fn message(self, message: &str) -> SelfEventCall.context
pub fn context(self, context: &impl Serialize) -> SelfWhat it happened in: who asked, which request.
EventCall.trace
pub fn trace(self, trace_id: TraceId, span_id: SpanId) -> SelfEventCall.append
pub fn append(self, fields: &impl Serialize) -> Result<bool>Writes the event, and says whether it did: false when its stream
holds its id. Made through a database's transaction, it is written
once the transaction commits, and says whether it will be.
Events
pub struct Events { /* private fields */ }A stream of events: written with append, which waits for the file, and
read back by time and by what they hold.
Events.appending
pub fn appending(&self, name: &str, fields: &impl Serialize) -> WriteAn event's append for a batch of the database the stream was opened
from: in Database::batch it is kept with the batch's rows and
written to the stream once the batch commits, before the batch
returns. A stream opened from the store, or from another database,
fails the batch, Invalid.
let db = store.database("app").open()?;
let audit = db.events("audit").open()?;
db.batch([
tinystore::sql!("update roles set role = ? where user_id = ?", "admin", 42).into(),
audit.appending("role.changed", &serde_json::json!({ "user_id": 42, "role": "admin" })),
])?;Events.append
pub fn append(&self, name: &str, fields: &impl Serialize) -> Result<bool>Writes an event of name with fields, a struct or a map, at the
store's time. It returns once the event is written, and a read finds
it at once: always true, since only an event with an id can be one
its stream holds.
Events.event
pub fn event(&self, name: &str) -> EventCall<'_>An append of one event, what it carries beside its fields before its verb:
let (actor, change) = (serde_json::json!({ "actor": 7 }), serde_json::json!({ "user": 42 }));
audit.event("role.changed").at(at).context(&actor).append(&change)?;Events.append_all
pub fn append_all(&self, events: impl IntoIterator<Item = NewEvent>) -> Result<usize>Writes a list of events, all of them or none, and says how many it wrote: an event whose id the stream holds, or an earlier event of the list holds, is nothing. A refused one names its place in the list and its name.
Events.list
pub fn list(&self) -> ListThe stream's events, found by the conditions the answer adds.
Events.lines
pub fn lines(&self) -> Result<Lines>A writer of another program's output, a child's standard output or a file followed: each line it is given becomes an event of this stream, and a write never waits. What its buffer has no room for, and a line longer than an event holds, are dropped and counted. Dropped, it hands over what it holds, a last line without its newline too.
let mut worker = std::process::Command::new("worker").stdout(std::process::Stdio::piped()).spawn()?;
let mut out = store.events("worker").open()?.lines()?;
std::io::copy(worker.stdout.as_mut().unwrap(), &mut out)?;An event named log keeps its text as its message, a line that is no
UTF-8 with U+FFFD for each sequence that spells nothing. A JSON object's
fields and a logfmt line's pairs become the event's fields, named
json or logfmt, when they spell the line again. Its level is found
where pino, logfmt, glog, Redis, log4j, zerolog and Postgres write it.
EventsBuilder
pub struct EventsBuilder<'s> { /* private fields */ }What opens a stream of events: its name, and how long it keeps them.
EventsBuilder.keep
pub fn keep(self, keep: Duration) -> SelfHow long the stream keeps its events. It is the stream's own, kept in
the file: an open that says none leaves it, fourteen days until one
says, and another than an earlier open of this store said is
invalid.
EventsBuilder.open
pub fn open(self) -> Result<Events>Lines
pub struct Lines { /* private fields */ }A writer of another program's lines into a stream, which never waits.
Lines.dropped
pub fn dropped(&self) -> u64The lines dropped since the writer began: a full buffer, a line longer than an event holds, one the file refused.
Levels
pub struct Levels {
pub store: Option<Level>,
pub console: Option<Level>,
}The least levels a store's logger keeps and prints, each part left out as
the option is: no store keeps every level, and no console prints what
is kept, following the config log's changes of it. One tracing::Level
is the store part alone, so it sets both.
Level::INFO info+ kept and printed
Levels { store: Some(Level::INFO), console: Some(Level::WARN) } info+ kept, warn+ printed
Levels { console: Some(Level::WARN), ..Levels::default() } all kept, warn+ printedLoggerBuilder
pub struct LoggerBuilder<'s> { /* private fields */ }What opens a logger: its stream, how it prints, the lines it holds.
LoggerBuilder.level
pub fn level(self, level: impl Into<Levels>) -> SelfThe least level kept and printed, every level without it, or each
apart as Levels says. LOG_LEVEL wins over the level kept, and
LOG_CONSOLE_LEVEL over the level printed.
use tinystore::records::Levels;
use tracing::Level;
let both = store.logger("api").level(Level::INFO).layer()?;
// every line from info kept, warnings and errors printed
let levels = Levels { store: Some(Level::INFO), console: Some(Level::WARN) };
let quiet = store.logger("jobs").level(levels).layer()?;LoggerBuilder.console
pub fn console(self, format: Format) -> SelfHow lines print: pretty on a terminal and JSON otherwise without
it, and LOG_FORMAT wins over it unless it is Off.
LoggerBuilder.time
pub fn time(self, time: Time) -> SelfA pretty line's time; LOG_TIME wins over it.
LoggerBuilder.hide_stream
pub fn hide_stream(self) -> SelfLeaves the stream out of a pretty line.
LoggerBuilder.to
pub fn to(self, out: impl Write + Send + 'static) -> SelfPrints to out instead of standard error.
LoggerBuilder.redact
pub fn redact<S: AsRef<str>>(self, names: impl IntoIterator<Item = S>) -> SelfHides the values of fields whose keys name a secret, at any depth,
where they print and where they are kept: SECRETS is the usual
names. A message's text is left as it is.
LoggerBuilder.keep_url_passwords
pub fn keep_url_passwords(self) -> SelfLeaves the password of a URL inside a value as it is.
LoggerBuilder.replace
pub fn replace(self, replace: impl Fn(&str, &str) -> Option<String> + Send + Sync + 'static) -> SelfChanges each field before it is hidden: given its key and its JSON, the JSON to keep, text that is no JSON kept as a string, or none to drop the field.
LoggerBuilder.source
pub fn source(self) -> SelfAdds where each line was logged: source={"function":…,"file":…,"line":42}.
LoggerBuilder.env
pub fn env(self, prefix: &str) -> SelfReads PREFIX_LOG_LEVEL, PREFIX_LOG_CONSOLE_LEVEL,
PREFIX_LOG_FORMAT and PREFIX_LOG_TIME in place of LOG_LEVEL
and the rest.
LoggerBuilder.no_env
pub fn no_env(self) -> SelfReads no variable: what the code says is what the logger does.
LoggerBuilder.buffer
pub fn buffer(self, lines: usize) -> SelfThe lines held between writes, 1024 unless given: a line that finds them all held is dropped and counted.
LoggerBuilder.keep
pub fn keep(self, keep: Duration) -> SelfHow long the stream keeps its events, as store.events takes it.
LoggerBuilder.layer
pub fn layer(self) -> Result<Layer>The layer that prints each line tracing hands it and keeps it in
the stream within a second.
Maintenance
pub struct Maintenance {
pub expired: u64,
pub packed: u64,
pub segments: u64,
pub merged: u64,
}What one pass of maintenance did.
maintain
pub fn maintain(store: &Store) -> Result<Maintenance>Runs the store's records maintenance now, as a store opened without background work has to.
PollBatch
pub struct PollBatch {
pub events: Vec<Event>,
pub cursor: String,
pub expired: u64,
}A batch of poll: its events, the cursor after them, and how many events
their streams' keep removed before the cursor reached them.
All
pub struct All { /* private fields */ }Every event of an answer, read a page at a time as it is walked, and several windows at once while they hold fewer events than a page.
List
pub struct List { /* private fields */ }A read being asked: every condition narrows it, and page or all runs
it.
List.count
pub fn count(&self) -> Result<u64>How many events the read finds.
List.top
pub fn top(&self, key: &str) -> Result<Vec<Top>>The most frequent values of key and how many events hold each, the
most first and those as frequent in the order of their JSON: ten
unless the read's limit says, 1000 at most. The key is a field's or a
context's, or stream, name, level or message.
List.largest
pub fn largest(&self, key: &str) -> Result<Vec<Event>>The events whose value at key is a JSON number, the largest first:
what sorting every event the read finds by that number would give
first, ten unless the read's limit says, 1000 at most. The key is a
field's, else a context's; an event without a number there is passed
over, and events of one number come in the read's order. It walks
the read as count does and holds the events it gives, of the
store's memory: past it the answer is limit, never a shorter list.
List.aggregate
pub fn aggregate(&self, aggregate: &Aggregate) -> Result<Vec<Row>>A row for each span and each value of the keys by names, in the
order of their spans: an answer whole, or an error of kind limit
past 10,000 rows.
List.since
pub fn since(self, span: Duration) -> SelfThe span before now the range covers; or from and to.
List.from
pub fn from(self, at: SystemTime) -> SelfThe range's start, which is in it.
List.to
pub fn to(self, at: SystemTime) -> SelfThe range's end, which is not in it.
List.streams
pub fn streams<S: Into<String>>(self, streams: impl IntoIterator<Item = S>) -> SelfAny of these streams, for a read of every stream.
List.names
pub fn names<S: Into<String>>(self, names: impl IntoIterator<Item = S>) -> SelfAny of these names: ["log"] is the lines.
List.min_level
pub fn min_level(self, level: Level) -> SelfThis level and worse. An event without a level is not found.
List.trace_id
pub fn trace_id(self, trace_id: TraceId) -> SelfList.filter
pub fn filter(self, key: &str, condition: impl Into<Condition>) -> Selfkey at the top of an event's fields or of its context with a value
the condition takes: a value by the JSON it is written as, so that
&42 finds 42, and neither "42" nor 42.0; a list, one of its
items, &[7, 12, 31], and a list or an object as the value itself
inside one, &[["a", "b"]]; Not, none of them or no
such key; Prefix, a text that starts with it. A key
written twice is found by its last value, the one Fields::get
reads. An empty list or another object is refused, invalid.
A statement of a database, db.statement(…), is a list of the
values its one column gives, read once when the query starts, on a
reader of its database, 100,000 rows of 4 KiB at most and held of
the store's memory: an integer 7 finds 7, a text '7' finds "7" and not 7, a real 7.0 finds 7.0
and not 7, a null finds nothing, and a blob is invalid. It is not
read in one moment with the events, since they are two files; a page
asked later, by after, reads it again. A tail refuses one.
let db = store.database("app").open()?;
let teachers = db.statement(tinystore::sql!("select id from teachers"));
let day = std::time::Duration::from_secs(24 * 60 * 60);
let used = store.events("activity").open()?.list().since(day).filter("userId", &teachers).count()?;List.search
pub fn search(self, text: &str) -> SelfThis text as a phrase, its case ignored: in an event's message, in its name, or in a value of its fields or its context at any depth.
List.newest
pub fn newest(self) -> SelfNewest first; oldest first without it.
List.delete
pub fn delete(&self) -> Result<u64>Deletes every event the read finds, of those appended before the
call, and what the store keeps only for them: a context of their
own, their keys and counts, their values in a filter, the bytes they
lay in. Says how many it deleted. It takes a where, and no search,
newest, limit or after.
A delete is a commit a segment it changes, and cannot be undone: a read meanwhile may still find what it has not reached, and a delete cut short by a crash or a cancel leaves what it reached deleted, so that running it again finishes it. No poll's cursor moves (REC-21), and an event's id stays held till the stream's keep passes its time. A backup taken before it, and another node's records.db, keep the events.
let store = tinystore::Store::open("data", Default::default())?;
let events = store.all_events()?;
let deleted = events.list().streams(["activity", "client-errors"]).filter("userId", &97516).delete()?;A statement in its where is read once, as the delete starts, and its
values hold for every segment it changes.
List.limit
pub fn limit(self, events: usize) -> SelfThe events of a page: 1000, and 10,000 at most.
List.after
pub fn after(self, next: &str) -> SelfA page's next, with the rest of the read as it was: the page after
it, in the range the first page had.
List.page
pub fn page(&self) -> Result<Page>One page: its limit of events that match, less those of a time the
limit would split, or fewer on the last page, which has no next.
It reads on past the events that match nothing, several windows at
once as all does, each from a moment of the file of its own.
List.field_names
pub fn field_names(&self) -> Result<Vec<String>>The keys the events of the read's range hold, in their fields and their contexts, sorted: as many as its limit, 1000 unless it says. A packed segment that reaches into the range gives every key it holds, which the file keeps beside its events.
List.field_names_prefix
pub fn field_names_prefix(&self, prefix: &str) -> Result<Vec<String>>The keys field_names gives that begin with prefix.
List.tail
pub fn tail(&self) -> Result<Tail>The events appended from now on that meet the read's conditions, a batch as they come: a tail takes no range, order, limit or after.
List.all
pub fn all(self) -> AllEvery event of the answer, a page at a time; a statement in its
where is read once, as the first page is.
List.sessions
pub fn sessions(&self, sessions: &Sessions) -> Result<Vec<Session>>The events the read finds cut into sessions by a pause, as
Sessions says, in the order of their first events and those of
one time by their values of by: an answer whole, not paged, or an
error of kind limit past 10,000 sessions held, open ones among
them, or past 64 MiB of what they keep.
A session cut by the range is answered with partial. A count is of
every event of its session, however few it keeps.
use std::time::Duration;
use tinystore::records::Sessions;
let events = store.events("activity").open()?;
let (month, minute) = (Duration::from_hours(30 * 24), Duration::from_secs(60));
let visits = Sessions::by(["userId"]).gap(minute * 30).max(minute * 240).first_sessions(1).max_events(50);
let first_visits = events.list().since(month).sessions(&visits)?;PAGE_EVENTS
pub const PAGE_EVENTS: usizeThe events of a page unless its limit says.
Page
pub struct Page {
pub events: Vec<Event>,
pub next: Option<String>,
}One page of an answer. next is the page after it, for after; the last
page has none.
Damage
pub struct Damage {
pub part: Part,
pub id: i64,
pub stream: String,
pub first: SystemTime,
pub last: SystemTime,
pub error: String,
}A head row or a segment that no longer reads, as damaged lists it and
drop takes it.
Part
pub enum Part {
HeadRow,
Segment,
}What holds a damage's events: a head row those not packed yet, a segment packed ones.
Session
pub struct Session {
pub by: BTreeMap<String, Value>,
pub from: SystemTime,
pub to: SystemTime,
pub count: u64,
pub events: Vec<Event>,
pub partial: bool,
}A session: the events of one value of each key of by, each within
gap of the one before.
Sessions
pub struct Sessions { /* private fields */ }What sessions cuts a read into: the keys whose values a session shares,
the pause that ends one, and what it keeps of each.
Sessions.by
pub fn by<S: Into<String>>(keys: impl IntoIterator<Item = S>) -> SessionsSessions of each value of these keys together: a field's, else a
context's, or stream, name, level or message, the event's
own before a field of that name.
Sessions.gap
pub fn gap(self, gap: Duration) -> SelfThe pause that ends a session: an event later than this after the one before begins the next.
Sessions.max
pub fn max(self, max: Duration) -> SelfThe longest a session lasts: an event later than this after its first begins the next, pause or none.
Sessions.first_sessions
pub fn first_sessions(self, sessions: usize) -> SelfOnly each value's first sessions of the range; its later events are
passed over.
Sessions.max_events
pub fn max_events(self, events: usize) -> SelfThe first events each session keeps, 1000 at most; none unless asked.
Tail
pub struct Tail { /* private fields */ }The events appended after a tail opened that meet its read, a batch as they come; walked as an iterator, it ends when the store closes.
Tail.next_within
pub fn next_within(&mut self, wait: Duration) -> Result<Option<TailBatch>>The next batch, waiting up to wait for it: none when none came in
that time, and Closed once the store has closed.
TailBatch
pub struct TailBatch {
pub events: Vec<Event>,
pub missed: u64,
}A batch of a tail: its events, and how many events left the store's hold before the tail read them.
TxEvents
pub struct TxEvents<'t> { /* private fields */ }A stream's appends inside a transaction of the database it was opened
from, tx.with(&audit): each is kept with the transaction's rows and
written to the stream once it commits, before db.tx returns. A read goes
through the stream's own handle, and finds what committed.
TxEvents.append
pub fn append(&self, name: &str, fields: &impl Serialize) -> Result<bool>Appends an event of name with fields, as Events::append does,
once the transaction commits: always true, since only an event with
an id can be one its stream holds.
TxEvents.event
pub fn event(&self, name: &str) -> EventCall<'t>An append of one event, what it carries beside its fields before its
verb, as Events::event has: its id, its time, its level.
Layer
pub struct Layer { /* private fields */ }A logger's layer: what tracing hands it is printed, and kept by a
store's logger. A clone is the same logger, for flush and dropped once
the subscriber holds the layer.
Layer.flush
pub fn flush(&self)Writes what the logger holds and returns once it is written, as the store does every second and when it closes; then flushes the console.
Layer.dropped
pub fn dropped(&self) -> u64The lines dropped since the logger began: a full buffer, a line the file refused, an event without a name or whose fields are no object.
Layer.event
pub fn event(&self, name: &str, fields: &impl Serialize)Writes an event named name with fields, a struct or a map, and
neither a level nor a message, as a line is written: at once, and
dropped under load. Its context is the current span's.
Replace
pub type Replace = Arc<dyn Fn(&str, &str) -> Option<String> + Send + Sync>What changes each field before it is hidden and kept: given its key and its JSON, the value to keep, or none to drop the field.
Time
pub enum Time {
Clock,
Full,
Off,
}How a pretty line's time shows; a JSON line always has its own.
SECRETS
pub const SECRETS: &[&str]The usual names of secrets, which redact takes to hide them. It hides a
counter named like one too, token_count among them.
colors
pub fn colors(stream: &impl IsTerminal) -> boolWhether stream shows colours, by the rule every logger keeps, in Rust,
Bun, Python and Go, and the command line too, so that a program's own
words and the log lines printed beside them are coloured alike: off under
NO_COLOR or a TERM of dumb, on where FORCE_COLOR is other than 0,
a pipe or a file too, and otherwise on a terminal alone. On Windows it
asks the console to read the escape sequences colours are written with,
and says no where a console refuses.
let painted = tinystore::console::colors(&std::io::stdout());logger
pub fn logger(stream: &str) -> LoggerBuilderA logger of the console alone, its lines printed and kept nowhere: the same calls, the same options but a store's, and the same lines as a store's logger.
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
let console = tinystore::console::logger("app").redact(tinystore::console::SECRETS).layer();
tracing_subscriber::registry().with(console).init();
tracing::info!(user = 42, "signed in");LoggerBuilder
pub struct LoggerBuilder { /* private fields */ }What a logger of the console alone is told before its layer is made.
LoggerBuilder.level
pub fn level(self, level: Level) -> SelfThe least level printed, every level without it. LOG_LEVEL wins
over it, and LOG_CONSOLE_LEVEL over both, since this logger only
prints.
LoggerBuilder.console
pub fn console(self, format: Format) -> SelfHow lines print: pretty on a terminal and JSON otherwise without
it, and LOG_FORMAT wins over it unless it is Off.
LoggerBuilder.time
pub fn time(self, time: Time) -> SelfA pretty line's time; LOG_TIME wins over it.
LoggerBuilder.hide_stream
pub fn hide_stream(self) -> SelfLeaves the stream out of a pretty line.
LoggerBuilder.to
pub fn to(self, out: impl Write + Send + 'static) -> SelfPrints to out instead of standard error.
LoggerBuilder.redact
pub fn redact<S: AsRef<str>>(self, names: impl IntoIterator<Item = S>) -> SelfHides the values of fields whose keys name a secret, at any depth,
where they print and where they are kept: SECRETS is the usual
names. A message's text is left as it is.
LoggerBuilder.keep_url_passwords
pub fn keep_url_passwords(self) -> SelfLeaves the password of a URL inside a value as it is.
LoggerBuilder.replace
pub fn replace(self, replace: impl Fn(&str, &str) -> Option<String> + Send + Sync + 'static) -> SelfChanges each field before it is hidden: given its key and its JSON, the JSON to keep, text that is no JSON kept as a string, or none to drop the field.
LoggerBuilder.source
pub fn source(self) -> SelfAdds where each line was logged: source={"function":…,"file":…,"line":42}.
LoggerBuilder.env
pub fn env(self, prefix: &str) -> SelfReads PREFIX_LOG_LEVEL, PREFIX_LOG_CONSOLE_LEVEL,
PREFIX_LOG_FORMAT and PREFIX_LOG_TIME in place of LOG_LEVEL
and the rest.
LoggerBuilder.no_env
pub fn no_env(self) -> SelfReads no variable: what the code says is what the logger does.
LoggerBuilder.layer
pub fn layer(self) -> LayerThe layer that prints what tracing hands it.
Format
pub enum Format {
Pretty,
Json,
Off,
}How a console prints a line. Without one, lines are pretty on a terminal and JSON otherwise.
aio::records::EventsBuilder
pub struct EventsBuilder<'s> { /* private fields */ }What opens a stream of events: its name, and how long it keeps them.
aio::records::EventsBuilder.keep
pub fn keep(self, keep: Duration) -> SelfHow long the stream keeps its events, as
crate::records::EventsBuilder::keep says.
aio::records::EventsBuilder.open
pub fn open(self) -> Result<Events>Opens the stream: a plain call, made once at start, which may migrate records.db and write the stream's row the first time.
aio::records::Events
pub struct Events { /* private fields */ }A stream of events: its appends wait for its file without a thread, and its reads run on the store's pool.
aio::records::Events.blocking
pub fn blocking(&self) -> &EventsThe same stream, for its blocking calls.
aio::records::Events.append
pub fn append(
&self,
name: &str,
fields: &impl Serialize,
) -> impl Future<Output = Result<bool>> + Send + 'staticWrites an event of name with fields, a struct or a map, at the
store's time, its fields serialized when the call is made. It answers
once the event is written, and a read finds it at once: always
true, since only an event with an id can be one its stream holds.
aio::records::Events.event
pub fn event(&self, name: &str) -> EventCall<'_>An append of one event, what it carries beside its fields before its
verb, as crate::records::Events::event has.
aio::records::Events.append_all
pub fn append_all(
&self,
events: impl IntoIterator<Item = NewEvent>,
) -> impl Future<Output = Result<usize>> + Send + 'staticWrites a list of events, all of them or none, in one commit, and answers how many it wrote: an event whose id the stream holds, or an earlier event of the list holds, is nothing.
The events are checked in the future's first poll, at most 4 MiB an append, and queued at records.db's writer, whose commit runs on the store's pool. Up to 256 KiB, a head row's worth, they are cut into rows and compressed in that poll too; a heavier append, or one that comes while another compresses, is compressed on the pool. When the store's memory has no room for them yet, the append waits for it on no thread, and is compressed on the pool once the room comes. Once polled, the events commit and reach every tail open, whether or not anyone still awaits them.
aio::records::Events.list
pub fn list(&self) -> ListThe stream's events, found by the conditions the answer adds.
aio::records::Events.lines
pub fn lines(&self) -> Result<Lines>A writer of another program's output, as
crate::records::Events::lines opens one: a write never waits, and
a flush is awaited.
aio::records::Events.appending
pub fn appending(&self, name: &str, fields: &impl Serialize) -> WriteAn event's append for a batch of the database the stream was opened
from, as Events::appending
makes one: it checks the event, with no I/O, and the batch is awaited.
aio::records::EventCall
pub struct EventCall<'e> { /* private fields */ }One event on its way into a stream.
aio::records::EventCall.id
pub fn id(self, id: impl AsRef<str>) -> SelfWhat names it in its stream, as crate::records::EventCall::id
has: an append of an id the stream holds writes nothing.
aio::records::EventCall.at
pub fn at(self, at: SystemTime) -> SelfIts time, from as long ago as the stream keeps to ten minutes ahead of the store's clock.
aio::records::EventCall.level
pub fn level(self, level: Level) -> Selfaio::records::EventCall.message
pub fn message(self, message: &str) -> Selfaio::records::EventCall.context
pub fn context(self, context: &impl Serialize) -> SelfWhat it happened in: who asked, which request.
aio::records::EventCall.trace
pub fn trace(self, trace_id: TraceId, span_id: SpanId) -> Selfaio::records::EventCall.append
pub fn append(self, fields: &impl Serialize) -> impl Future<Output = Result<bool>> + Send + 'staticWrites the event with fields, as Events::append_all writes one,
and answers whether it did: false when its stream holds its id.
aio::records::EventCall.appending
pub fn appending(self, fields: &impl Serialize) -> WriteThe event's append for a batch of the database its stream was opened
from, with what the call carries beside its fields; see
Events::appending.
aio::records::AllEvents
pub struct AllEvents { /* private fields */ }Every stream's events, to read.
aio::records::AllEvents.blocking
pub fn blocking(&self) -> &AllEventsThe same events, for their blocking calls.
aio::records::AllEvents.list
pub fn list(&self) -> ListThe events of every stream, or of those streams names, found by
the conditions the answer adds.
aio::records::AllEvents.streams
pub fn streams(&self) -> impl Future<Output = Result<Vec<StreamInfo>>> + Send + 'staticEvery stream with events, by name, as
crate::records::AllEvents::streams lists them.
aio::records::AllEvents.fields
pub fn fields(&self, stream: &str) -> impl Future<Output = Result<StreamFields>> + Send + 'staticWhat the events of stream carry, as
crate::records::AllEvents::fields counts it.
aio::records::AllEvents.poll
pub fn poll(&self, cursor: Option<&str>) -> impl Future<Output = Result<PollBatch>> + Send + 'staticEvery packed event once, a batch a call, 1000 at most, from cursor,
as crate::records::AllEvents::poll gives them: an empty batch at
once when nothing past the cursor is packed. A dropped poll leaves the
cursor the program keeps as it was.
aio::records::AllEvents.poll_limit
pub fn poll_limit(
&self,
cursor: Option<&str>,
limit: usize,
) -> impl Future<Output = Result<PollBatch>> + Send + 'staticAs poll, limit events at most, 10,000 at the most.
aio::records::AllEvents.damaged
pub fn damaged(&self) -> impl Future<Output = Result<Vec<Damage>>> + Send + 'staticWhat reads, packing, merges and polls met that no longer reads, as
crate::records::AllEvents::damaged lists it.
aio::records::AllEvents.drop
pub fn drop(&self, damage: &Damage) -> impl Future<Output = Result<()>> + Send + 'staticRemoves a head row or a segment that no longer reads, as
crate::records::AllEvents::drop does, on the store's pool: it
reads the part again under maintenance's lock, then writes its
removal. Once polled it runs to its end, as a write does.
aio::records::List
pub struct List { /* private fields */ }A read being asked: every condition narrows it, and an awaited call runs it on the store's pool.
aio::records::List.since
pub fn since(self, span: Duration) -> SelfThe span before now the range covers; or from and to.
aio::records::List.from
pub fn from(self, at: SystemTime) -> SelfThe range's start, which is in it.
aio::records::List.to
pub fn to(self, at: SystemTime) -> SelfThe range's end, which is not in it.
aio::records::List.streams
pub fn streams<S: Into<String>>(self, streams: impl IntoIterator<Item = S>) -> SelfAny of these streams, for a read of every stream.
aio::records::List.names
pub fn names<S: Into<String>>(self, names: impl IntoIterator<Item = S>) -> SelfAny of these names: ["log"] is the lines.
aio::records::List.min_level
pub fn min_level(self, level: Level) -> SelfThis level and worse. An event without a level is not found.
aio::records::List.trace_id
pub fn trace_id(self, trace_id: TraceId) -> Selfaio::records::List.filter
pub fn filter(self, key: &str, condition: impl Into<Condition>) -> Selfkey at the top of an event's fields or of its context with a value
the condition takes, as crate::records::List::filter reads it: a
value, a list of them, a Not or a Prefix.
aio::records::List.search
pub fn search(self, text: &str) -> SelfThis text as a phrase, its case ignored.
aio::records::List.newest
pub fn newest(self) -> SelfNewest first; oldest first without it.
aio::records::List.limit
pub fn limit(self, events: usize) -> SelfThe events of a page: 1000, and 10,000 at most.
aio::records::List.after
pub fn after(self, next: &str) -> SelfA page's next, with the rest of the read as it was.
aio::records::List.page
pub fn page(&self) -> impl Future<Output = Result<Page>> + Send + 'staticOne page of events that match, full but for the last, as
crate::records::List::page reads it.
aio::records::List.field_names
pub fn field_names(&self) -> impl Future<Output = Result<Vec<String>>> + Send + 'staticThe keys the events of the read's range hold, sorted, as
crate::records::List::field_names gives them.
aio::records::List.field_names_prefix
pub fn field_names_prefix(
&self,
prefix: &str,
) -> impl Future<Output = Result<Vec<String>>> + Send + 'staticThe keys field_names gives that begin with prefix.
aio::records::List.delete
pub fn delete(&self) -> impl Future<Output = Result<u64>> + Send + 'staticDeletes every event the read finds, as
crate::records::List::delete does, and says how many. Once polled
it runs to its end on the store's pool, whether or not anyone still
awaits it, as a write does.
aio::records::List.count
pub fn count(&self) -> impl Future<Output = Result<u64>> + Send + 'staticHow many events the read finds. It walks every page of the read on one thread of the store's pool, several at once while they hold few events; a drop stops the walk at the page it reads.
aio::records::List.top
pub fn top(&self, key: &str) -> impl Future<Output = Result<Vec<Top>>> + Send + 'staticThe most frequent values of key and how many events hold each, as
crate::records::List::top counts them, walking the read as
count does.
aio::records::List.largest
pub fn largest(&self, key: &str) -> impl Future<Output = Result<Vec<Event>>> + Send + 'staticThe events of the largest numbers at key, as
crate::records::List::largest keeps them, walking the read as
count does.
aio::records::List.aggregate
pub fn aggregate(
&self,
aggregate: &Aggregate,
) -> impl Future<Output = Result<Vec<Row>>> + Send + 'staticA row for each span and each value of the keys by names, as
crate::records::List::aggregate makes them, walking the read as
count does.
aio::records::List.sessions
pub fn sessions(
&self,
sessions: &Sessions,
) -> impl Future<Output = Result<Vec<Session>>> + Send + 'staticThe events the read finds cut into sessions by a pause, as
crate::records::List::sessions cuts them, walking the read once as
count does.
aio::records::List.tail
pub fn tail(&self) -> Result<Tail>The events appended from now on that meet the read's conditions, a
batch as they come, as crate::records::List::tail opens a tail:
a plain call, which checks the read and opens the tail.
aio::records::List.all
pub fn all(self) -> AllEvery event of the answer, as a stream: a page's worth at a time, read on the store's pool once the stream has given the last, never sooner. A cancellation token around this call stops its reads as one around a blocking read does.
aio::records::All
pub struct All { /* private fields */ }Every event of an answer, a Stream that reads a page's worth on the
store's pool each time it has given the last. Dropped while a page is
read, that read stops as a dropped read does.
aio::records::Tail
pub struct Tail { /* private fields */ }The events appended after a tail opened that meet its read, a Stream
of batches that waits on no thread: each append that brings events wakes
it from the thread that committed them, and the batch is taken in the
poll, from the store's hold of its last megabyte of events. It ends when
the store closes, and dropped, the tail closes.
A wait with a bound is the runtime's: tokio::time::timeout(d, tail.next()) ends the wait and keeps the tail open.
aio::records::Lines
pub struct Lines { /* private fields */ }A writer of another program's lines into a stream: a write goes to its buffer and never waits, and a flush is awaited. Dropped, it hands over what it holds, a last line without its newline too, which the store writes within a second.
It is no std::io::Write, whose flush would block the executor's thread.
aio::records::Lines.write
pub fn write(&mut self, bytes: &[u8]) -> Result<()>Takes a piece of output: each line it ends becomes an event. It never waits, and fails only once the writer or its store closed.
aio::records::Lines.flush
pub fn flush(&mut self) -> impl Future<Output = Result<()>> + Send + 'staticWrites the events of every line ended so far, and answers once they are written; a line without its newline yet stays. It runs on the store's pool, and once polled runs to its end, as a write does.
aio::records::Lines.dropped
pub fn dropped(&self) -> u64The lines dropped since the writer began: a full buffer, a line longer than an event holds, one the file refused.