The official client for GenesisDB. Async (tokio), built on reqwest with rustls, typed events and errors.
cargo add genesisdb tokio --features tokio/full
cargo add serde_jsonQuick start
use genesisdb::{Client, NewEvent};
use serde_json::json;
#[tokio::main]
async fn main() -> genesisdb::Result<()> {
let db = Client::builder().url("http://localhost:8080").token(std::env::var("GENESISDB_AUTH_TOKEN").unwrap()).build()?;
db.commit(
vec![NewEvent::new("io.example.shop", "/customer/42", "io.example.shop.customer-registered", json!({"name": "Bruce Wayne"}))],
vec![],
)
.await?;
let events = db.fetch("/customer/42", None).await?;
println!("{events:?}");
Ok(())
}url and token fall back to GENESISDB_URL and GENESISDB_AUTH_TOKEN, so Client::from_env()? works in an environment that sets both. Client is Clone and shares its connection pool.
Events
use genesisdb::FetchOptions;
// Commit a batch atomically. The server assigns ID, time and hashes and returns the stored events.
let stored = db.commit(vec![
NewEvent::new("io.example.shop", "/order/1", "io.example.shop.order-placed", json!({"total": 99.5})),
NewEvent::new("io.example.shop", "/order/1/item/1", "io.example.shop.item-added", json!({"sku": "A1", "qty": 2})),
], vec![]).await?;
stored[0].id; // "3f2c..."
stored[0].hash; // "a9b1..."
stored[0].time; // chrono::DateTime<Utc>
// A subject with one segment gets a generated ID appended.
db.commit(vec![NewEvent::new("io.example.shop", "/customer", "io.example.shop.customer-registered", json!({"name": "Selina"}))], vec![]).await?;
// Fetch a subject with all descendants, in commit order.
let all = db.fetch("/order/1", None).await?;
// Resume after a known event, or stop at one.
let since = db.fetch("/order", Some(FetchOptions::default().lower_bound(&last_seen_id, false))).await?;
let until = db.fetch("/order", Some(FetchOptions::default().upper_bound(&some_id, true))).await?;
// Only the newest event of a type below the subject.
let latest = db.fetch("/order/1", Some(FetchOptions::default().latest_by_event_type("io.example.shop.order-placed"))).await?;
// Typed payloads
#[derive(serde::Deserialize)]
struct Order { total: f64 }
let order: Order = stored[0].data_as()?;Preconditions
Preconditions are checked atomically with the commit. A failed precondition returns Error::PreconditionFailed and writes nothing.
use genesisdb::{Error, Precondition};
let result = db.commit(
vec![NewEvent::new("io.example.shop", "/customer/42", "io.example.shop.customer-registered", json!({"email": "bruce@example.com"}))],
vec![
Precondition::is_subject_new("/customer/42"),
Precondition::is_query_result_true("STREAM e FROM events WHERE e.data.email == 'bruce@example.com' MAP COUNT() == 0"),
],
).await;
if let Err(Error::PreconditionFailed { precondition_type, reason, .. }) = &result {
println!("{precondition_type}: {reason}"); // "isSubjectNew: subject /customer/42 already has events"
}Variants: IsSubjectNew, IsSubjectExisting, IsQueryResultTrue.
Subscriptions
subscribe returns a Stream over Server-Sent Events. It yields the existing history first, then new events as they are committed, and runs until you drop it.
use futures_util::StreamExt;
use genesisdb::SubscribeOptions;
use std::time::Duration;
let mut stream = Box::pin(db.subscribe("/order", Some(SubscribeOptions::default().interval(Duration::from_millis(500)))).await?);
while let Some(event) = stream.next().await {
let event = event?;
println!("{} {:?}", event.event_type, event.data);
}interval is the poll interval (default 1 s). The bound options of fetch work here as well through SubscribeOptions::fetch, so a consumer that persists the last processed event ID resumes with lower_bound. A stream the server ends with an error yields Error::SubscriptionEnded as its last item.
Queries
GDBQL runs on the server. Results come back as rows, a bare aggregate as a single-element vector.
let rows = db.query("STREAM e FROM events WHERE e.subject UNDER '/customer' MAP { name: e.data.name, total: e.data.total }").await?;
#[derive(serde::Deserialize)]
struct Row { name: String, total: f64 }
let typed: Vec<Row> = db.query_as("STREAM e FROM events WHERE e.subject UNDER '/customer' MAP { name: e.data.name, total: e.data.total }").await?;
let count: Vec<u64> = db.query_as("STREAM e FROM events WHERE e.type == 'io.example.shop.order-placed' MAP COUNT()").await?;
let by_category = db.query(
"STREAM e FROM events WHERE e.type == 'io.example.shop.item-added' GROUP BY e.data.category MAP { category: e.data.category, items: COUNT(), revenue: SUM(e.data.total) }",
).await?;GDPR: reference payloads and erasure
Store a payload as reference data and it can be erased later. The event, its hash and the chain stay intact, the payload becomes {}.
db.commit(vec![
NewEvent::new("io.example.shop", "/customer/42", "io.example.shop.customer-registered", json!({"name": "Bruce", "email": "bruce@example.com"})).as_reference(),
], vec![]).await?;
db.erase("/customer/42").await?; // administrator tokenInline payloads are immutable. erase on a subject without reference payloads returns an error with is_unprocessable() (422).
Schemas
db.register_schema("io.example.shop.order-placed", json!({
"type": "object",
"properties": {"total": {"type": "number"}, "currency": {"type": "string"}},
"required": ["total"]
})).await?;
let schemas = db.schemas().await?;Commits of that type are validated. A violation returns Error::Api with status 400.
Catalog, status, administration
db.subjects().await?; // ["/customer", "/order"]
db.types().await?; // ["io.example.shop.customer-registered", ...]
db.status().await?; // engine version, event counts, storage, readiness
db.ping().await?; // "Pong", no token required
db.audit().await?; // "Audit passed. All 1234 events integrity checks succeeded."Audit, erase and schema registration need the administrator token. Everything else works with a reader token (GENESISDB_READ_TOKEN), commit additionally with a writer token.
Errors
Every non-2xx answer returns Error::Api { status, body, kind, operation }, except 412 which returns Error::PreconditionFailed { precondition_type, reason, .. }. ApiErrorKind classifies Authentication (401, 403), NotFound (404), Conflict (409), Unprocessable (422), NotReady (503) and Other. Convenience predicates: err.status(), err.is_precondition_failed(), err.is_authentication(), err.is_not_found(), err.is_conflict(), err.is_unprocessable(), err.is_not_ready(). Transport errors surface as Error::Http.
Configuration
Client::builder()
.url("http://localhost:8080") // or GENESISDB_URL
.token("...") // or GENESISDB_AUTH_TOKEN
.timeout(Duration::from_secs(30)) // for non-streaming calls, default 30 s
.http(reqwest::Client::builder().build()?) // optional, bring your own reqwest client
.build()?;