scriva — Rust client
Async Rust gRPC client for ScrivaDB.
Built on tonic + prost, using Tokio for async I/O.
Prerequisites
- Rust 1.75+ (2021 edition)
protoc(Protocol Buffers compiler) — required at build time for code generation
Install: https://grpc.io/docs/protoc-installation/
Install
Add to Cargo.toml:
[]
= "0.1"
= { = "1", = ["full"] }
= "1"
Connect
use ScrivaDB;
async
The API key is sent as x-api-key gRPC metadata on every call.
Collection management
db.create_collection.await?;
let names: = db.list_collections.await?;
db.drop_collection.await?;
// Give the collection a default per-record TTL (seconds). Records inserted
// without an explicit TTL then expire this long after being written.
db.create_collection_with_ttl.await?;
CRUD
use json;
// Insert one record — returns the assigned u64 ID.
let id = db.insert.await?;
// Insert many — returns Vec<u64> of IDs.
let ids = db.insert_many.await?;
// Fetch by ID.
let record = db.find_by_id.await?;
println!;
// Update.
db.update.await?;
// Delete.
let existed: bool = db.delete.await?;
Every record also carries a caller-supplied key (empty for records inserted
without one) and a monotonic rev (starts at 1, bumped on every write):
let r = db.find_by_id.await?;
println!;
Keyed CRUD, upsert & compare-and-swap
Records may carry a caller-supplied string primary key, giving natural upsert
and optimistic-concurrency (compare-and-swap on rev) semantics.
use ScrivaDbError;
// Insert under a key. A key already held by a live record is AlreadyExists.
let id = db.insert_with_key.await?;
// Upsert: insert under the key, or replace the existing keyed record — atomic.
// Returns the resulting Record (rev is incremented on replace).
let rec = db.upsert.await?;
println!;
// Fetch / overwrite / delete by key. A missing key is a typed NotFound error.
let rec = db.find_by_key.await?;
let upd = db.update_by_key.await?;
println!;
let existed = db.delete_by_key.await?;
// Compare-and-swap: applies only if the current rev matches expected_rev.
// A stale rev (or missing key) is a clean no-op — swapped = false, never an error.
let cas = db.update_if_rev.await?;
if cas.swapped
// NotFound / AlreadyExists are dedicated error variants you can match on.
match db.find_by_key.await
Per-record TTL
insert, insert_many, and update each have a *_with_ttl variant taking a
ttl_seconds: i64:
// Expire this record 60 seconds from now, regardless of the collection default.
db.insert_with_ttl.await?;
// Same TTL applied to every record in the batch.
db.insert_many_with_ttl.await?;
// On update, ttl_seconds > 0 resets the deadline; the plain `update` (ttl 0) is
// sticky and leaves the existing deadline untouched.
db.update_with_ttl.await?;
A ttl_seconds of 0 (what the plain insert/insert_many/update methods
use) inherits the collection's default TTL on insert; a value greater than 0
overrides it. Negative values are rejected by the server.
Find (querying)
use ;
// Collect all results into a Vec<Record>.
let admins = db.find.await?;
// AND composite filter.
let records = db.find.await?;
// OR composite filter.
let records = db.find.await?;
// Streaming variant — more memory-efficient for large result sets.
use StreamExt;
let mut stream = db.find_stream.await?;
while let Some = stream.next.await
Field projection
Set fields to project each record's data down to those top-level fields
(id, key and rev are always returned; unknown fields are silently omitted):
let slim = db.find.await?;
// Also on single-record fetches:
let r = db.find_by_id_with_fields.await?;
let r = db.find_by_key_with_fields.await?;
Multi-field sort & keyset pagination
order_by_fields gives a multi-field, per-field-directional sort (the record id
is always the final tiebreaker, so the order is total). Use find_page to walk
results page by page with a keyset cursor — O(page), not O(offset):
use OrderBy;
let mut page_token = Stringnew;
loop
Keep the same filter, ordering and limit on every page. The deprecated scalar
order_by / descending fields are still honoured when order_by_fields is empty.
Filter operators
FilterOp |
Description |
|---|---|
Eq |
Equal |
Neq |
Not equal |
Gt |
Greater than |
Gte |
Greater than or equal |
Lt |
Less than |
Lte |
Less than or equal |
Contains |
String contains (substring) |
Regex |
Regular expression match |
FindOptions
| Field | Type | Default | Description |
|---|---|---|---|
filter |
Option<FilterInput> |
None |
Query filter |
limit |
u32 |
0 |
Max results (0 = no limit) |
offset |
u32 |
0 |
Skip first N results |
order_by |
String |
"" |
Deprecated single-field sort — use order_by_fields |
descending |
bool |
false |
Deprecated direction for order_by |
order_by_fields |
Vec<OrderBy> |
[] |
Multi-field sort (supersedes order_by) |
fields |
Vec<String> |
[] |
Project data to these top-level fields |
page_token |
String |
"" |
Keyset cursor from a previous find_page |
Secondary indexes
// Create an index on a field (no-op if already exists).
db.ensure_index.await?;
// List indexes.
let fields: = db.list_indexes.await?;
// Drop an index.
db.drop_index.await?;
Once an index exists, find with a single Eq filter on that field uses
the index automatically (O(1) lookup instead of full scan).
Transactions
let tx_id = db.begin_tx.await?;
// Stage writes... (the server records them under tx_id)
db.insert.await?;
// Commit or roll back.
db.commit_tx.await?;
// db.rollback_tx(&tx_id).await?;
Watch (change feed)
watch returns an async Stream of WatchEvents. Drop the stream to cancel.
use StreamExt;
use WatchOp;
let mut events = db.watch.await?;
while let Some = events.next.await
// With a filter — only receive events matching the filter.
let filter = field;
let mut events = db.watch.await?;
Aggregations
Compute count and numeric aggregations (sum/avg/min/max) entirely in the
engine — optionally grouped by a field, honouring the same filter as find.
use ;
// Count matching records.
let n = db.count.await?;
// Whole-collection numeric aggregation over a field.
let groups = db.aggregate.await?;
let g = &groups; // ungrouped => exactly one group, with `group == Null`
println!;
// Group by a field — one AggregateGroup per distinct value.
let by_role = db.group_by.await?;
for g in &by_role
count is always returned; sum/avg/min/max require field to be set.
Aggregate is server-streaming (one message per group); these helpers collect it
into a Vec<AggregateGroup>.
Stats
let s = db.stats.await?;
println!;
Maintenance
// Force a synchronous compaction of a collection — merges dirty segments and
// reclaims space from deleted/overwritten records. Returns true on success.
db.compact.await?;
// Stream a consistent gzip-compressed tar snapshot of the whole database
// straight to a file. Returns the number of bytes written; restore with
// `tar xzf backup.tar.gz`.
let bytes = db.snapshot_to_file.await?;
// Or consume the raw archive chunks yourself (Snapshot is server-streaming):
use StreamExt;
let mut chunks = db.snapshot.await?;
while let Some = chunks.next.await
TLS
let ca_pem = read.expect;
let mut db = connect_tls.await?;
Generate a self-signed CA for local testing:
Then start the server with --tls-cert cert.pem --tls-key key.pem and connect
with ScrivaDB::connect_tls("localhost", 5433, "api-key", &std::fs::read("cert.pem")?).await?.
Examples
Run the end-to-end examples against a live server (make run from repo root):
# Basic CRUD, filters, indexes, transactions, stats
# Watch change feed with concurrent inserts
Building from source
tonic-build calls protoc during cargo build. If protoc is not on your
PATH, set PROTOC=/path/to/protoc before building.
Crates.io