Appearance
Rust SDK
sh
cargo add kernable-sdk serde_json
cargo add serde --features derive
cargo add tokio --features macros,rt-multi-threadRust 1.88 or newer (edition 2024), on Tokio. A kernel to connect to: kernable start --dev (see Getting started).
A cart aggregate, a read model that answers a query, and a client that submits and reads back, in one process:
rust
use std::{
collections::HashMap,
sync::{Arc, Mutex},
};
use kernable::{App, BoxError, Kernable, NewEvent, Query, Rejected, Submit, domain};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
#[derive(Clone, Default, Serialize, Deserialize)]
struct Cart {
items: u32,
}
#[derive(Serialize, Deserialize)]
struct Item {
qty: u32,
}
#[derive(Deserialize)]
struct GetCart {
id: String,
}
#[tokio::main]
async fn main() -> Result<(), BoxError> {
let shop_domain = domain("shop");
let cart_aggregate = shop_domain.aggregate("cart", Cart::default());
cart_aggregate.apply("ItemAdded", |state, data: Item, _evt, _ctx| state.items += data.qty);
cart_aggregate.command("AddItem", |_state, data: Item, _cmd, _ctx| {
if data.qty == 0 {
return Err(Rejected::new("qty must be at least 1"));
}
Ok(vec![NewEvent::new("ItemAdded", data)])
});
// Handlers are called again for every event: share their state as Arc<Mutex<…>>.
let rows = Arc::new(Mutex::new(HashMap::<String, u32>::new()));
let carts_readmodel = shop_domain.read_model("carts");
let r = Arc::clone(&rows);
carts_readmodel.on("ItemAdded", move |data: Item, evt, _ctx| {
*r.lock().unwrap().entry(evt.aggregate_id).or_default() += data.qty;
async { Ok(()) }
});
let r = Arc::clone(&rows);
carts_readmodel.query("GetCart", move |q: GetCart, _qry, _ctx| {
let items = r.lock().unwrap().get(&q.id).copied().unwrap_or(0);
async move { Ok(json!({ "items": items })) }
});
let kernable = Kernable::new("app.key")?;
let app = kernable.app(App::new().service("shop").domain(&shop_domain))?;
tokio::spawn({
let app = app.clone();
async move { app.run().await }
});
app.ready().await;
let add_apples = Submit::new("shop", "cart", "c1", "AddItem").data(json!({ "qty": 2 }));
kernable.submit(add_apples).await?;
let get_cart = Query::new("shop", "GetCart").data(json!({ "id": "c1" }));
let cart: Value = kernable.query(get_cart).await?;
println!("{cart}"); // {"items":2}
Ok(())
}How the SDK works:
- Async, on Tokio. Calls to the kernel are
async fns; run them in a Tokio runtime (#[tokio::main]).run()of a worker, a listener or an app returns only afterstop():.awaitit last, ortokio::spawnit and.awaititsready(). - Builders.
Options,Submit,Query,ManifestandAppare built with methods that each return the changed value:Submit::new(…).data(…).wait(Wait::Committed). Domains, aggregates, listeners and workers are handles: their methods register on the shared definition and return another handle, so they chain too. - Typed payloads. A handler's
dataparameter has the type you annotate (data: Item, anyDeserializetype, orserde_json::Value); state, events and answers areSerialize. - Handler state. Listener handlers are
Fnclosures that return a future and run again for every event: keep their state in anArc<Mutex<…>>(or a store), clone theArcinto eachmoveclosure, and lock before theasyncblock. - Errors. Command handlers return
Result<Vec<NewEvent>, Rejected>; listener, query and middleware handlers returnResult<_, BoxError>, where?and.into()turn aRejectedor any other error into aBoxError. Client calls returnResult<_, Error>; a rejected command isOk(Outcome::Rejected(_)), a rejected queryErr(Error::Rejected(_))(Errors).
The rest of this page is generated from the doc comments in sdks/rust/src.
Options
How to reach the kernel and as whom: the options of Kernable::new, set with builder methods that each return the changed options.
Options::default() takes everything from the environment, else the defaults: the key from KERNABLE_KEY, else app.key in the current directory; the kernel from KERNABLE_URL, else http://127.0.0.1:7233; the grant from KERNABLE_GRANT, else the .grant file next to the key; the service from KERNABLE_SERVICE; TLS from KERNABLE_TLS_CA, KERNABLE_TLS_CERT and KERNABLE_TLS_KEY; the tenant default. A key file's path (&str, String, &Path, PathBuf) converts into options with only the key set, so Kernable::new("app.key") works too. Example: Kernable::new(Options::new("shop.key").url("http://kernel:7233").service("shop"))?.
fn new(key: impl AsRef<Path>) -> Options: Options that sign with the key in the.keyfile atkey(made withkernable keys new), every other option at its default.fn url(self, url: impl Into<String>) -> Options: Kernel address:http://host:port(host:portworks too) or, on Unix,unix:/path/to.sock. For a pair of kernels with a standby, both, comma-separated (http://a:7233,http://b:7233): the client turns to the other one when a kernel answersUNAVAILABLE(a standby saysnot_primary) or cannot be reached. Default:KERNABLE_URL, elsehttp://127.0.0.1:7233, wherekernable startlistens.fn grant(self, path: impl AsRef<Path>) -> Options: The key's grant (kernable grant), sent with every call. Default:KERNABLE_GRANT, else the.grantfile next to the key file, if there is one.fn tenant(self, tenant: impl Into<String>) -> Options: Default tenant forsubmit,query, files and the cache (defaultdefault).fn service(self, service: impl Into<String>) -> Options: The service this process's workers and listeners belong to. The service's membership (seeKernable::apply) decides what the kernel waits for: what it lists counts, the service's other workers and listeners are dynamic, and only listeners it lists as middlewares may check requests. Default:KERNABLE_SERVICE, else none (everything registered counts).fn context(self, context: RequestContext) -> Options: Default request context, e.g. this service's identity; a request's own context replaces it.fn tls(self, tls: Tls) -> Options: Mutual TLS forhost:portURLs: the CA certificate and this process's certificate and key, as paths of PEM files (Tls { ca, cert, key }, re-exported from the kernel's crate). Default:KERNABLE_TLS_CA,KERNABLE_TLS_CERTandKERNABLE_TLS_KEY, if set (all three or none).fn insecure(self) -> Options: Allows plain text to a kernel that is not on this machine. Without TLS, grants, signed requests and vault values cross the network readable, soKernable::newrefuses such a URL unless this is set. Default:KERNABLE_INSECURE=1, else not allowed.fn timeout(self, timeout: Duration) -> Options: How long a request (submit,query, files, cache,apply) waits in all: for the connection, e.g. while the kernel restarts, and for its answer. Default 60 s. A connection the network dropped silently is noticed within 40 s by keepalive pings.
Kernable
A connection to the kernel: submits commands, asks queries, and runs workers and listeners. Cloning gives another handle to the same connection.
The calls to the kernel are async and need a Tokio runtime (#[tokio::main]). Workers, listeners and apps run until stopped: run().await them, or tokio::spawn them and wait for ready(). Workers and listeners print connection lines to stderr up to the level KERNABLE_LOG names (off, error, warn, info (default), debug). Example: let kernable = Kernable::new("app.key")?; let outcome = kernable.submit(Submit::new("shop", "cart", "c1", "AddItem").data(json!({ "qty": 2 }))).await?;
fn new(options: impl Into<Options>) -> Result<Kernable, Error>: A client for the kerneloptionsnames, or with only a key file's path, for the default kernel;Options::default()takes everything from the environment (seeOptions). It connects on first use and again after the connection drops. Needs a Tokio runtime.Error::Configif the key, grant or TLS files cannot be read, only some of the TLS variables are set, or the URL is invalid. Example:Kernable::new("app.key")?.fn with_domain(&self, domain: &Domain) -> Kernable: Seals the vault fields of this domain's commands when submitting them (seeDomain::command) and sends the target of its queries asked by name (seeDomain::query). Returns another handle to this connection, so it chains:Kernable::new("app.key")?.with_domain(&shop_domain).fn worker<S: State>(&self, aggregate: &Aggregate<S>) -> Worker: A worker that runs the commands ofaggregate; add more withWorker::aggregate. It belongs to this connection's service (seeOptions::service). Nothing runs untilWorker::runis awaited:kernable.worker(&cart_aggregate).run().await.fn listener(&self, listener: &Listener) -> ListenerHandle: Runslistener(a read model or reactor of a domain) on this connection: the handle processes its events withrun(). Each call gives a new handle. The listener belongs to this connection's service (seeOptions::service). Example:kernable.listener(&carts_readmodel).run().await.fn data(&self) -> Files: Files of the default tenant: bytes up to 16 MiB per key, kept by the kernel outside the signed event log; seeFiles. Example:kernable.data().put("shop", "invoices/c1.pdf", bytes, "application/pdf").await?.fn cache(&self) -> Cache: The kernel's cache for the default tenant: values up to 1 MiB per key, optionally with a TTL, lost when the kernel restarts; seeCache. Example:kernable.cache().set("shop", "rate:c1", "3", Some(Duration::from_secs(60))).await?.async fn apply(&self, manifest: Manifest) -> Result<(), Error>: Replaces the membership of a service (default: this connection's, seeOptions::service): the workers, listeners and middlewares the kernel waits for, plus free metadata. Apply it once per deploy (e.g. from a deploy script), not from every process: the newest apply wins, and an older one that arrives late is refused. The key needs themanagegrant for the service. A middleware the new membership no longer lists stops checking. Example:kernable.apply(Manifest::new().service("shop").worker(&cart_aggregate).listener(&carts_readmodel)).await?.Error::Configif neither the manifest nor the connection names a service,Error::Statusif the kernel refuses it.async fn register_process(&self, process: &Process) -> Result<process::Registered, Error>: Registers a business process with the kernel (seeprocess): its model, signed. The kernel numbers the versions: a model equal to the newest version registers nothing (process::Registered::newisfalse), a different one becomes the next version; running cases finish on the version they started with. An app registers its domains' processes itself (Kernable::app). The key needs theprocessgrant for the process, andsubmit,queryandlistenfor the commands, queries and events it names.Error::Configif the model is invalid (Process::model),Error::Statusif the kernel refuses it (INVALID_ARGUMENTnames the step and why).async fn process_act(&self, name: &str, context: RequestContext) -> Result<bool, Error>: Sets as whom the processname(qualified:shop.fulfilment) acts: the request context its commands and queries carry (sender tenant, identity, session), instead ofprocess:<name>. The kernel keeps it with the process, replicated to every partition. The kernable kit calls it for every process it gives an identity and an API key. Returns whether it changed (false: it acted so already). The key needs theprocessgrant for the process;Error::Statusif the kernel refuses (NOT_FOUND: no such process).fn app(&self, app: App) -> Result<AppHandle, Error>: An app made of whole domains:AppHandle::runapplies the service's membership (the domains' aggregates as workers, their read models and reactors as listeners, those that check requests as middlewares; live ones are not listed, and the metadata isversionanddescription, when given, then the app's other metadata; the domains' business processes), then runs one worker for all the aggregates and every listener, live ones too, all in the app's service, and registers the processes once the worker is ready (Kernable::register_process; the key then needs theprocessgrant for them). Example:kernable.app(App::new().service("shop").version("1.0.0").domain(&shop_domain))?.run().await?. Every start applies the membership, so the key needs themanagegrant for the service. One service is one app: two processes with the same service would replace each other's membership.Error::Configif neither the app nor the connection names a service.async fn submit(&self, submit: Submit) -> Result<Outcome, Error>: Runs a command and returns its outcome:Outcome::Committedwith the new events, orOutcome::Rejectedif a handler or middleware rejected it (a rejection isOk, not an error). By default it waits until every listener that counts has processed the events; seeSubmit::wait.Error::NotSettledif they did not in time (the command is committed),Error::Statusif the kernel refuses the call (no grant, unknown aggregate type, timeout). Example:kernable.submit(Submit::new("shop", "cart", "c1", "AddItem").data(json!({ "sku": "apple", "qty": 2 }))).await?. A scheduled command (Submit::at) has no outcome yet: enqueue it (Kernable::enqueue); submitting it isError::Config. Submitted again by its ID withoutat, it waits for the scheduled command's outcome;Error::NotDueif the kernel answers that it is not due yet.async fn enqueue(&self, submit: Submit) -> Result<String, Error>: Stores the command in the kernel's queue and returns its ID without waiting for it to run. Submit it again with the sameid(Submit::id) to get the outcome; itswaitis ignored. WithSubmit::at, a scheduled command: it runs at that time, e.g. a reminder in 24 hours,kernable.enqueue(Submit::command(Remind {}, "o1") .at(SystemTime::now() + Duration::from_secs(86_400))).await?; cancel it withKernable::cancel.async fn cancel(&self, cancel: Cancel) -> Result<CancelOutcome, Error>: Cancels a scheduled command (Submit::at) before it is due: it completes as rejectedcancelled, which a submit of its ID answers from then on. Needs thesubmitgrant for the command's type; middlewares check it as a cancel of that type (CheckKind::Cancel). ReturnsCancelOutcome::Cancelled(also when it was cancelled before), orCancelOutcome::Rejectedwithtoo_late(due, running or done already),not_found, or a middleware's code. Example:kernable.cancel(Cancel::new(&id)).await?.async fn query<T: DeserializeOwned>(&self, query: Query) -> Result<T, Error>: Asks the read model that answersdomain.typeand returns its answer, deserialized asT(serde_json::Valuefor any). Queries always go through the kernel, also within one process. A refusal by the read model or a middleware isError::Rejected; the kernel's own (no grant, no read model connected) isError::Status; an answer that is not aTisError::Json. Example:let cart: Value = kernable.query(Query::new("shop", "GetCart").data(json!({ "id": "c1" }))).await?;async fn ask<Q: QueryType>(&self, query: Q, options: impl FnOnce(Query) -> Query) -> Result<Q::Answer, Error>: Asks a query of a message type and returns its typed answer:kernable.ask(GetOrder { id }, |q| q.tenant(t)).await?;optionssets whatQuery's methods set.fn subscribe<F, Fut>(&self, options: SubscribeOptions, handler: F) -> Subscription where F: Fn(StoredEvent) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), BoxError>> + Send + 'static: Streams committed events afteroptions.after(backlog first, then live) tohandler, one at a time. Reconnects and resumes after the last handled event; if the handler fails, that event is delivered again. Persist the position yourself to resume across restarts. Needs thesubscribegrant for the types. Unlike a listener, a subscription is not registered with the kernel: nobody waits for it, and its events carry no vault values (vault fields arenulland listed inredacted). It runs in a Tokio task from the call on;Subscription::stopends it.async fn reindex(&self, reindex: Reindex) -> Result<Vec<(String, Outcome)>, Error>: Stores the unique keys and facts of aggregates as their current state yields them: submits the built-in_reindex_<aggregate_type>command (reindex_type; no events) to each ID in turn and returns each ID with its outcome. Run it after declaring a key or fact on an aggregate that has events already: until an aggregate runs a command, it holds what its last command left. An ID without events holds nothing and commits. A rejection is an outcome, e.g.unique_takenif another aggregate holds one of its keys (a duplicate from before the key was declared).Erroras forKernable::submit, for the first ID that fails; the ones before it are done. Needs thesubmitgrant for<domain>._reindex_<aggregate_type>. Example:kernable.reindex(Reindex::new("shop", "customer", ["k1", "k2"])).await?.
Wait
How long submit waits before it responds.
Settled: Until every listener has processed the events, so read models already show them (default);Error::NotSettledon timeout. From a listener's handler, only the listeners with a lower order count.Committed: Until the events are stored. To read them back, ask withQuery::min_positionset to the last event's position.
Manifest
What a service consists of, for Kernable::apply; see Membership in kernable.proto. Built with methods that each return the changed manifest: Manifest::new().service("shop").worker(&cart_aggregate).listener(&carts_readmodel).metadata("version", "1.0.0").
fn new() -> Manifest: An empty manifest for the connection's service.fn service(self, service: impl Into<String>) -> Manifest: The service it is for. Default: the connection's (Options::service).fn worker<S: State>(self, aggregate: &Aggregate<S>) -> Manifest: An aggregate the service runs: the kernel waits for a worker of it and accepts its commands even before a worker registered it.fn listener(self, listener: &Listener) -> Manifest: A listener the kernel waits for; the service's other listeners count for nobody.fn middleware(self, listener: &Listener) -> Manifest: A listener of the service that may check requests; it counts like a listener.fn process(self, process: &Process) -> Manifest: A business process of the service (Domain::process): the kernel starts new cases of it while a membership lists it; one no longer listed starts none, its running cases finish. Register it too (Kernable::register_process); an app does both.fn metadata(self, key: impl Into<String>, value: impl Into<String>) -> Manifest: Free metadata, e.g.("version", "1.0.0"); kept in the order given.
Submit
A command to submit with Kernable::submit or Kernable::enqueue, built with methods that each return the changed command: Submit::new("shop", "cart", "c1", "AddItem").data(json!({ "qty": 2 })).wait(Wait::Committed). Without data, the payload is an empty object ({}).
fn new(domain: &str, aggregate_type: &str, aggregate_id: &str, command_type: &str) -> Submit: Acommand_typecommand ofdomainfor the aggregateaggregate_typewith IDaggregate_id.fn command<C: CommandType>(command: C, aggregate_id: &str) -> Submit: A command of a message type (seecommand) for the aggregate with IDaggregate_id: its type says the domain, the aggregate type and the vault fields.Submit::command(PlaceOrder { customer_id }, "o1").tenant(t). Panics ifcommandcannot be represented as JSON.fn data(self, data: impl Serialize) -> Submit: The command's data. Panics ifdatacannot be represented as JSON.fn tenant(self, tenant: impl Into<String>) -> Submit: The tenant to submit to. Default: the connection's (Options::tenant).fn id(self, id: impl Into<String>) -> Submit: Idempotency key (default: a new UUID); resubmitting the same ID returns the original outcome without running the command again.fn context(self, context: RequestContext) -> Submit: Replaces the client's default context; inside a listener, passctx.follow().fn at(self, time: SystemTime) -> Submit:Kernable::enqueueonly: a scheduled command, run attimeand not before. The kernel stores it at once; the aggregate's other commands pass meanwhile, and middlewares check it now and again when it is due. At most the kernel's--schedule-max-days(default 366) ahead. Cancel it withKernable::cancel.fn until(self, time: SystemTime) -> Submit: WithSubmit::at: if the command cannot run bytime(after an outage, say), it is rejectedexpiredinstead of running late.fn wait(self, wait: Wait) -> Submit: How longKernable::submitwaits:Wait::Settled(default) orWait::Committed.fn timeout(self, timeout: Duration) -> Submit: How long to wait for the connection and the outcome; defaultOptions::timeout.
Cancel
A cancel of a scheduled command for Kernable::cancel, built with methods that each return the changed cancel: Cancel::new(&id).tenant("t1").
fn new(command_id: &str) -> Cancel: A cancel of the scheduled commandcommand_id(the IDKernable::enqueuereturned).fn tenant(self, tenant: impl Into<String>) -> Cancel: The command's tenant. Default: the connection's (Options::tenant).fn context(self, context: RequestContext) -> Cancel: Replaces the client's default context: who cancels, for the middlewares.fn timeout(self, timeout: Duration) -> Cancel: How long to wait for the connection and the answer; defaultOptions::timeout.
CancelOutcome
What became of a cancel, returned by Kernable::cancel.
Cancelled: The scheduled command will not run: it completed as rejectedcancelled.Rejected(Rejected): Not cancelled:too_late(due, running or done already),not_found, or a middleware's rejection.fn is_cancelled(&self) -> bool: Whether the command was cancelled.
Query
A query to ask with Kernable::query, built with methods that each return the changed query: Query::new("shop", "GetCart").data(json!({ "id": "c1" })). Without data, the query's data is an empty object ({}).
fn new(domain: &str, query_type: &str) -> Query: Aquery_typequery ofdomain.fn of<Q: QueryType>(query: Q) -> Query: A query of a message type (seequery); its type says the domain and the aggregate it is about. Ask it withKernable::askfor its typed answer. Panics ifquerycannot be represented as JSON.fn data(self, data: impl Serialize) -> Query: The query's data. Panics ifdatacannot be represented as JSON.fn tenant(self, tenant: impl Into<String>) -> Query: The tenant to ask in. Default: the connection's (Options::tenant).fn context(self, context: RequestContext) -> Query: Replaces the client's default context.fn min_position(self, position: u64) -> Query: Answer only after the read model has processed this global position (e.g. of a committed submit).fn timeout(self, timeout: Duration) -> Query: How long to wait for the connection and the answer; defaultOptions::timeout.fn all_partitions(self) -> Query: For a read model across tenants with partitions: answer only once the read model has processed every partition's events up to the query, not only those of the tenant's partition. Costs a wait-only query to each partition first.
Outcome
What became of a command, returned by Kernable::submit.
Committed(Vec<StoredEvent>): The command's events are stored, in order. Vault fields in them arenull(seeStoredEvent::redacted).Rejected(Rejected): A handler, a middleware or the kernel rejected the command; nothing was stored but the rejection.fn is_committed(&self) -> bool: Whether the command was committed.fn events(&self) -> &[StoredEvent]: The committed events; none if the command was rejected.
QueryOutcome
What became of a query, as a middleware that runs after requests gets it (CheckOutcome::Query): its response data or why it was rejected.
Answered(Value): The read model's answer.Rejected(Rejected): The read model or a middleware rejected the query.fn is_answered(&self) -> bool: Whether the read model answered.
StoredEvent
An event as stored by the kernel: in an Outcome and in a Kernable::subscribe handler.
position: u64: Global position of the event in the kernel's log.tenant: Stringdomain: String: Always the domain of the command that caused the event.aggregate_type: Stringaggregate_id: Stringversion: u64: The aggregate's version after this event: 1 for its first event.event_type: String: The event type within the domain, e.g.ItemAdded.schema: u32: Version of the payload format. Listeners getdataupcast to the version they know (seeDomain::event), unless the handler is raw.data: Value: The payload;StoredEvent::parsedeserializes it.redacted: Vec<String>: Fields kept in the vault whose value is not here (nullindata): erased, or not readable with this key (grantedvault_read).command_id: String: The command that caused the event.created_at: Timestamp: When the kernel committed the event.request: RequestContext: The request context of the command that caused the event.fn parse<D: DeserializeOwned>(&self) -> Result<D, serde_json::Error>:dataas aD, e.g.let item: ItemAdded = event.parse()?;.
App
An app: one service made of whole domains, for Kernable::app. Every aggregate, read model and reactor created through its domains runs in it. Built with methods that each return the changed app:
let app = kernable.app(App::new().service("shop").version("1.0.0").domain(&shop_domain))?; then app.run().await?. To do something once everything is connected (e.g. in a test), spawn it and wait: let running = tokio::spawn({ let app = app.clone(); async move { app.run().await } }); app.ready().await;.
fn new() -> App: An app without domains for the connection's service; add them withApp::domain.fn service(self, service: impl Into<String>) -> App: The service it is. Default: the connection's (crate::Options::service).fn version(self, version: impl Into<String>) -> App: Goes into the membership's metadata asversion.fn description(self, description: impl Into<String>) -> App: Goes into the membership's metadata asdescription.fn metadata(self, key: impl Into<String>, value: impl Into<String>) -> App: More metadata, afterversionanddescription; kept in the order given.fn domain(self, domain: &Domain) -> App: A domain of the app: its aggregates, read models and reactors run in it. Call it once per domain.
AppHandle
An App on a connection; see Kernable::app. Cloning gives another handle to the same app, e.g. to call stop() or ready() while another task awaits run().
fn manifest(&self) -> &Manifest: The membershiprun()applies.fn worker(&self) -> Option<&Worker>: The worker of all the app's aggregates; none if it has none.fn listeners(&self) -> &[ListenerHandle]: Every read model and reactor of the app, live ones too.async fn ready(&self): Returns once the worker and every listener of the app are connected, and the domains' processes are registered; waits forever if one never connects, so wrap it intokio::time::timeoutwhere that matters.fn stop(&self): Endsrun: stops the worker and every listener.async fn run(&self) -> Result<(), Error>: Applies the membership (seeKernable::apply; it lists the domains' processes), then runs the worker and every listener untilstop(). Once the worker is ready, it registers the domains' processes (Kernable::register_process): a process whose commands no worker runs yet would be refused. Once all are connected, it prints an overview of the app (unlessKERNABLE_LOGis belowinfo) instead of their connection lines. Fails only if the kernel refuses the membership (Error::Status); a failing handler does not end it (a command handler's error rejects the command, a listener handler's error makes the listener reconnect and get the event again), or the kernel refuses a process (then it stops). A panic in a worker or listener task is passed on.
Domain
A domain: a name that scopes its aggregates, commands and events, lowercase by convention (orders) like aggregates, while message types are capitalized (orders.PlaceOrder). Both cases are valid; names are case-sensitive. Types are unique within a domain; elsewhere they are named domain.Type. Cloning gives another handle to the same domain.
Make it with domain: let shop_domain = domain("shop");. A domain remembers the aggregates, read models and reactors created through it, so that an app runs all of them (see crate::Kernable::app); they live as long as the domain does.
fn name(&self) -> &str: The domain's name, e.g.shop.fn event(&self, event_type: &str, schema: u32) -> EventSchema: Declares that this domain writesevent_typeevents at versionschema, with anupcastper older version, and which of their fields the vault keeps; seeEventSchema. The domain's aggregates and listeners use it; other domains' listeners get it withListener::with_domain. Types not declared are at version 1. Panics ifevent_typeis qualified orschemais 0.fn command(&self, command_type: &str) -> CommandSchema: Declares which fields ofcommand_typecommands the vault keeps (personal,secret); seeCommandSchema. Clients that submit them need the domain:kernable.with_domain(&domain). Panics ifcommand_typeis qualified.fn query(&self, query_type: &str) -> QuerySchema: Declares whatquery_typequeries are about (seeQuerySchema::target): returns theQuerySchemato chaintargeton. A query type (seecrate::query) declares it withtarget(...)instead. Clients that ask such queries by name need the domain:kernable.with_domain(&domain). Panics ifquery_typeis qualified.fn process(&self, name: &str) -> crate::process::Process: A business process of this domain namedname(fulfilment; qualifiedshop.fulfilment): add its start and steps to thecrate::process::Processit returns. An app of the domain registers it with the kernel (crate::Kernable::app). Example:shop_domain.process("fulfilment").start::<OrderSubmitted>(Start::key("aggregate_id")).... Panics ifnameis not letters, digits,-and_, or the domain has a process namednamealready.fn aggregate<S: State>(&self, name: &str, initial: S) -> Aggregate<S>: An aggregate of this domain namedname(lowercase by convention, likecart), whose state starts asinitial; seeAggregate. Example:let cart_aggregate = shop_domain.aggregate("cart", Cart::default());. Panics if the domain has an aggregate namednamealready.fn read_model(&self, name: &str) -> Listener: A read model of this domain namedname: builds a view from events and answers queries from it; seeListener. Kept in memory and rebuilt from the first event on every start (order 0;Listener::storekeeps it in a file instead). Run it withcrate::Kernable::listeneror in an app. Example:let carts_readmodel = shop_domain.read_model("carts");. Panics if the domain has a read model or reactor namednamealready.fn reactor(&self, name: &str) -> Listener: A reactor of this domain namedname: triggers side effects and follow-up commands; seeListener. It starts at the newest event when it is new, then resumes after the last acknowledged event (order 10). A settling submit from its handler waits for the listeners before it (the read models), not for the reactor itself, which handles one event at a time. Submit follow-ups withctx.submitand a fixed ID, so a redelivered event does not run the command twice; a rejected one parks the event (seeListener::park_after). Run it withcrate::Kernable::listeneror in an app. Panics if the domain has a read model or reactor namednamealready.fn schema_of(&self, event_type: &str) -> u32: The payload version this domain writesevent_typeevents at.
domain()
fn domain(name: &str) -> Domain
A domain named name, on which you define its aggregates, read models, reactors and event and command schemas: let shop_domain = domain("shop");.
Panics if name does not start with a letter or holds characters other than letters, digits, - and _.
EventSchema
The payload format of one event type: its current version and the steps that bring older payloads up to it. Events are stored as written and never changed; readers upcast them.
Made with Domain::event; its methods return it, so they chain: shop_domain.event("ItemAdded", 2).upcast(1, |mut d| { d["qty"] = json!(1); d }); or shop_domain.event("CustomerRegistered", 1).personal(&["email"], |_, id| id.to_owned());. A subject function gets the payload and the aggregate's ID, e.g. |d, _| d["customerId"].as_str().unwrap_or_default().to_owned().
fn personal(self, fields: &[&str], subject: impl Fn(&Value, &str) -> String + Send + Sync + 'static) -> Self: Keeps these top-level fields in the vault, as personal data of the subjectsubjectreturns from the payload and the aggregate's ID (seeEventSchemafor examples). Events then hold only references; the kernel hands the values to workers and to listeners allowed to read them, until an event erases the subject.fn erases(self, subject: impl Fn(&Value, &str) -> String + Send + Sync + 'static) -> Self: Makes this an erasing event: it deletes every vault value of the subjectsubjectreturns, in every stream, and the snapshots that may hold them. Read models should drop the subject's data when they see it; rebuilt, they readnull.fn upcast(self, from: u32, step: impl Fn(Value) -> Value + Send + Sync + 'static) -> Self: Turns a payload of versionfrominto one of versionfrom + 1:stepgets the old payload and returns the new one. Declare one step per older version. Panics iffromis not a version below the current one.
CommandSchema
How a command's payload is kept: which fields go to the vault. Made with Domain::command; its methods return it, so they chain: shop_domain.command("Register").personal(&["email"], |_, id| id.to_owned()).secret(&["password"]);. Clients that submit these commands need the domain: kernable.with_domain(&shop_domain).
fn personal(self, fields: &[&str], subject: impl Fn(&Value, &str) -> String + Send + Sync + 'static) -> Self: Keeps these top-level fields in the vault as personal data ofsubject; seeEventSchema::personal.fn secret(self, fields: &[&str]) -> Self: Keeps these top-level fields (passwords, one-time tokens) in the vault only until the command completed. The handler gets them in clear; the stored command keeps a reference.
QuerySchema
What a query type is about. Made with Domain::query: shop_domain.query("GetOrder").target("order", "id"); (a GetOrder with {"id": "o-17"} is about order o-17). Clients that ask these queries by name need the domain: kernable.with_domain(&shop_domain).
fn target(self, aggregate_type: &str, field: &str) -> Self: The query is about one aggregate ofaggregate_type(order, of the query's domain, or qualified:shop.order), whose ID is in the data's fieldfield(as on the wire:orderId). The SDK sends it with the query, signed, and a middleware decides on it as on a command's aggregate (crate::Check::target). Data without a non-empty string infieldsends no target.
QueryTarget
The aggregate a query is about, as its type declares it: QuerySchema::target.
aggregate_type: String:order(of the query's domain) or qualified:shop.order.field: String: The field of the query's data that holds the aggregate's ID, as on the wire:orderId.
NewEvent
An event returned by a command handler; data is stored as JSON. Make it with NewEvent::new: NewEvent::new("ItemAdded", &item).
event_type: String: The event type within the aggregate's domain, e.g.ItemAdded.data: Value: The payload.fn new(event_type: &str, data: impl Serialize) -> NewEvent: Anevent_typeevent withdata;()stands for no data. Panics ifdatacannot be represented as JSON (a map with non-string keys).
EventMeta
What apply gets about an event besides its payload. Only fields known before the kernel stores the event, so a snapshot and a replay compute the same state; put a time into the data (ctx.now() in the command handler) if the state needs one.
event_type: Stringversion: u64: The aggregate's version after this event: 1 for its first event.tenant: Stringdomain: Stringaggregate_type: Stringaggregate_id: Stringcommand_id: String: The command that caused the event.
ApplyContext
What apply gets besides state, data and the event's meta. No clock and no IDs: apply must compute the same state every time.
request: RequestContext: The request context of the command that caused the event.
CommandMeta
What a command handler gets about the command besides its payload.
command_id: String: The command's ID: given withcrate::Submit::id, else a new UUID.command_type: String: The command type within the domain.domain: Stringaggregate_type: Stringaggregate_id: Stringtenant: String
CommandContext
What a command handler gets besides state, data and the command's meta: the request context, and the command's time and IDs.
request: RequestContext: Who sends the command: check permissions here.fn new(command_id: &str, request: RequestContext, received_at: Timestamp) -> CommandContext: A context for calling a command handler directly, e.g. in a unit test withAggregate::handle; its deadline is 30 s afterreceived_at.fn on(self, aggregate_id: &str, tenant: &str) -> CommandContext: ForAggregate::handle: the aggregate ID and tenant the handler'sCommandMetanames (default: empty), e.g. for a handler that checks them.fn now(&self) -> Timestamp: When the kernel received the command: the same every time the command runs. Use it instead of the clock.fn id(&self) -> String: A new ID that is the same every time the command runs (1st call, 2nd call, ...). Use it instead of random IDs.fn deadline(&self) -> Timestamp: When the kernel hands the command to another worker if this one has not answered.
FoldEvent
An event to fold with Aggregate::fold: type, payload version and data, and what apply learns about it (empty fields if unknown). FoldEvent::new("ItemAdded", json!({ "qty": 2 })) is enough for most tests.
event_type: Stringschema: u32data: Valuemeta: EventMetarequest: RequestContext: The request context of the command that caused the event:applygets it in itsApplyContext.fn new(event_type: &str, data: impl Serialize) -> FoldEvent: Anevent_typeevent at version 1 of its payload.
State
What an aggregate's state must be: copied, and stored as JSON in snapshots. Every type that is Clone + Serialize + DeserializeOwned + Send + Sync + 'static is one, typically a struct with #[derive(Clone, Default, Serialize, Deserialize)].
Aggregate
An aggregate: how events change its state (apply) and which events a command produces (command). Handlers must be deterministic and free of side effects; they may run again. Create it with domain(...).aggregate(...); cloning gives another handle to the same aggregate. The registering methods return the aggregate, so they chain.
apply handlers change the state in place: cart_aggregate.apply("ItemAdded", |state, data: Item, _evt, _ctx| state.items += data.qty);. command handlers return the new events or a Rejected: cart_aggregate.command("AddItem", |state, data: Item, _cmd, _ctx| { if state.checked_out { return Err(Rejected::new("Cart is checked out")); } Ok(vec![NewEvent::new("ItemAdded", data)]) });. The type of data (here Item, any Deserialize type, or serde_json::Value) says how the payload is read; a payload that does not fit fails the command with handler_error. Handlers are synchronous and must not block.
Unique keys, facts and requirements reach across aggregates; the kernel checks them atomically when a command commits. unique declares a key computed from the state, which no two aggregates hold with the same value: customer_aggregate.unique("email", |s| s.email.clone(), Unique::tenant());. fact declares a condition of the state that other aggregates' commands may require: vehicle_aggregate.fact("open", |s| !s.wound_up);. requires names the facts a command needs: account_aggregate.requires("OpenAccount", |_state, data: Open| [Requirement::new("funds", "vehicle", &data.vehicle_id, "open")]);. After every command, the worker sends the keys and facts of the new state, so an aggregate always holds exactly what its state yields.
Test without a kernel: cart_aggregate.fold([FoldEvent::new("ItemAdded", json!({ "qty": 2 }))], None)? returns the state, cart_aggregate.handle(&state, "AddItem", json!({ "qty": 1 }), &mut ctx) runs a command handler with a CommandContext::new, and cart_aggregate.index(&state)? and cart_aggregate.requirements(&state, "AddItem", json!({ "qty": 1 }))? compute the keys, facts and requirements.
fn domain(&self) -> &Domain: The domain the aggregate belongs to.fn name(&self) -> &str: The aggregate's name within its domain, e.g.cart.fn initial(&self) -> &S: The state before the first event.fn snapshot_every(&self, events: u64) -> Self: Sends a snapshot of the state everyeventsevents (default 100; 0 turns them off).fn schema(&self, schema: &str) -> Self: Version of the state format (default "1"). Change it whenapplyproduces differently shaped state; older snapshots are then ignored and the state is rebuilt from the events.fn apply<D: DeserializeOwned>(&self, event_type: impl TypeKey<D>, f: impl Fn(&mut S, D, &EventMeta, &ApplyContext) + Send + Sync + 'static) -> Self: How an event ofevent_typechanges the state:f(state, data, evt, ctx)changesstatein place, or replaces it with*state = ….datais the event's payload asD, upcast to the current version;evtis anEventMeta,ctxanApplyContext.event_typeis a name, or an event type's constant (seecrate::event), whose dataDthen is:order_aggregate.apply(OrderPlaced, |s, d, _evt, _ctx| ...). The same holds forcommandandrequires. SeeAggregatefor an example.fn command<D: DeserializeOwned>(&self, command_type: impl TypeKey<D>, f: impl Fn(&S, D, &CommandMeta, &mut CommandContext) -> Result<Vec<NewEvent>, Rejected> + Send + Sync + 'static) -> Self: Which events acommand_typecommand produces:f(state, data, cmd, ctx)returns them asOk(vec![NewEvent::new(…)]), orErr(Rejected::new(…)).datais the command's payload asD;cmdis aCommandMeta,ctxaCommandContextwith the request context and deterministicnow()andid(). SeeAggregatefor an example. Panics ifcommand_typestarts with_reindex_: those are reserved for the built-in command of aggregates with unique keys or facts (seecrate::reindex_type), and an aggregate cannot see the other aggregate types of its domain.fn unique<I: IntoIterator<Item = String>>(&self, name: &str, values: impl Fn(&S) -> I + Send + Sync + 'static, options: Unique<S>) -> Self: Declares a unique key namedname:values(state)returns the values the aggregate holds in that state, as anything that iterates overStrings (values are strings by type; format numbers yourself):None(holds nothing),Some(value)(one value) or aVec(several; repeated ones count once). No two aggregates of this type hold the same value of the key at the same time; a command that would make its aggregate hold a value another one holds is rejected withunique_taken. The value is compared as is: normalize it invalues(e.g. lowercase an email); an empty string is a value like any other.optionssays where it is unique (within the tenant, orUnique::global) and whether the value is personal (Unique::personal). Example:customer_aggregate.unique("email", |s| s.email.as_ref().map(|e| e.to_lowercase()), Unique::tenant());. The worker computes the keys from the state after every command, also one without events;valuesmust be deterministic likeapply, and one that panics fails the command withhandler_error. An aggregate that had events before the key was declared holds none of its values until it runs a command:crate::Kernable::reindexruns one. Panics ifnameis empty, longer than 128 bytes or holds.or*, or the aggregate declares a key namednamealready (a fact may have the same name).fn fact(&self, name: &str, holds: impl Fn(&S) -> bool + Send + Sync + 'static) -> Self: Declares a fact namedname, which the aggregate holds whileholds(state)is true. Commands of other aggregates of the tenant may require it (seeAggregate::requires). Computed like the keys (seeAggregate::unique). Example:vehicle_aggregate.fact("open", |s| !s.wound_up);. Panics ifnameis empty, longer than 128 bytes or holds.or*, or the aggregate declares a fact namednamealready (a key may have the same name).fn requires<D: DeserializeOwned, I: IntoIterator<Item = Requirement>>(&self, command_type: impl TypeKey<D>, f: impl Fn(&S, D) -> I + Send + Sync + 'static) -> Self: Which facts of other aggregates of the tenant acommand_typecommand requires:f(state, data)returnsRequirements (anything that iterates over them), from the state before the command and its payload asD. The command commits only if each named aggregate holds its fact at that moment, otherwise it is rejected withrequirement_missing; nothing is locked in between. Example:account_aggregate.requires("OpenAccount", |_state, data: Open| [Requirement::new("funds", "vehicle", &data.vehicle_id, "open")]);. A payload that is not aD, or anfthat panics, fails the command withhandler_error. Panics if the aggregate has nocommand_typehandler (declare it withAggregate::commandfirst).fn index(&self, state: &S) -> Result<Index, Error>: The unique keys and facts the aggregate holds instate, as the worker sends them after a command that leaves it instate; for tests without a kernel.Error::Configif a key or fact function panics.fn requirements(&self, state: &S, command_type: &str, data: impl Serialize) -> Result<Vec<Requirement>, Error>: The requirements of acommand_typecommand withdataonstate(none if it declares none, seeAggregate::requires); for tests without a kernel.Error::Configifdatais not the function'sDor it panics.fn fold(&self, history: impl IntoIterator<Item = FoldEvent>, from: Option<S>) -> Result<S, Error>: State afterhistory, starting fromfrom(default: the initial state). Events are upcast first; events without anapplyare skipped. For tests without a kernel.Error::Configif anapplyfails (also a payload that is not itsD, or a panic) or an event's schema is newer than known.fn handle(&self, state: &S, command_type: &str, data: impl Serialize, ctx: &mut CommandContext) -> Result<Vec<NewEvent>, Error>: Runs thecommand_typehandler onstate, e.g. in a unit test. The handler'sCommandMetahas the command ID ofctx, this aggregate's domain and name, and an empty aggregate ID and tenant.Error::Rejectedif the handler rejects the command,Error::Configif there is no handler forcommand_typeor it fails otherwise.
Worker
Runs the commands of its aggregates: the kernel sends each command with the aggregate's events, the worker decides and sends the new events back, signed. Cloning gives another handle to the same worker. Made with crate::Kernable::worker; the configuring methods return it, so they chain.
run().await processes commands until stop(). To do something once it is connected, spawn it and wait: let worker = kernable.worker(&cart_aggregate); tokio::spawn({ let worker = worker.clone(); async move { worker.run().await } }); worker.ready().await;.
fn aggregate<S: State>(&self, aggregate: &Aggregate<S>) -> Worker: Runs the commands ofaggregate, too.fn concurrency(&self, commands: u32) -> Worker: Commands executed in parallel (default 16).fn reconnect(&self, delay: Duration) -> Worker: Delay before reconnecting after the session ends (default 1 s); twice as long after each further failed attempt, at most 30 s.async fn ready(&self): Returns once the kernel accepted the worker; waits forever if it never connects.fn stop(&self): Endsrun, also from another task.async fn run(&self): Processes commands untilstop(), reconnecting when the session drops. A handler's error or panic rejects that command (handler_error); it does not endrun.
StoredEventMeta
What a listener handler gets about an event besides its payload (the evt of Listener::on).
event_type: Stringversion: u64: The aggregate's version after this event: 1 for its first event.tenant: Stringdomain: String: Always the domain of the command that caused the event.aggregate_type: Stringaggregate_id: Stringcommand_id: String: The command that caused the event.position: u64: Global position of the event.created_at: Timestamp: When the kernel committed the event.schema: u32: Version of the payload format as stored; the handler gets the payload upcast to the version it knows, unless it is raw.redacted: Vec<String>: Fields kept in the vault whose value is not in the payload (null): erased, or not readable with this key (grantedvault_read).
ListenerContext
What a listener handler gets besides the event's payload and meta (the ctx of Listener::on).
replaying: bool: The event was committed before this connection began: a read model rebuilding from the start, and equally the backlog a reactor catches up on after a restart or a lost connection. A reactor must not skip side effects because of it (those events are new to it); submit with fixed command IDs instead, so they are safe to repeat. Use it to skip work that only matters live, e.g. a notification about something long past in a listener that starts at 0.store: Option<Store>: The listener's store, if it has one (Listener::store).request: RequestContext: The request context of the command that caused the event.fn follow(&self) -> RequestContext: A request context for commands caused by this event: same sender and correlation, this event's command as the cause, without an expected version or privileges. Pass it withcrate::Submit::context;ListenerContext::submitdoes.async fn submit(&self, submit: Submit) -> Result<Vec<StoredEvent>, Error>: Submits a command this event causes, on the listener's connection, and returns its events. It needs a fixed ID (Submit::id, e.g.confirm-<order>), so a redelivered event runs it once; without one it isError::Config. Unless the submit sets them, the context isListenerContext::followand the tenant the event's. A rejection isError::Rejected: returned from the handler (?), it parks the event at once in a reactor (seeListener::park_after). Match it to accept one:match ctx.submit(s).await { Err(Error::Rejected(r)) if r.code == "unique_taken" => {} r => { r?; } }. Other errors as forKernable::submit.async fn query<T: DeserializeOwned>(&self, query: Query) -> Result<T, Error>: Asks a query on the listener's connection, likeKernable::query; unless the query sets it, for the event's tenant. It is the listener's own read: it keeps the connection's context, not the event's sender.async fn process_act(&self, name: &str, context: RequestContext) -> Result<bool, Error>: Sets as whom a business process acts, on the listener's connection, likeKernable::process_act: e.g. a reactor that gives each registered process an identity.
QueryMeta
What a query handler gets about the query besides its data (the qry of Listener::query).
query_id: String: The query's ID, a new UUID per query.query_type: String: The query type within the domain.domain: Stringtenant: String
QueryContext
What a query handler gets besides the query's data and meta (the ctx of Listener::query).
request: RequestContext: Who asks: check permissions here.store: Option<Store>: The listener's store, if it has one (Listener::store).
CheckKind
Whether a middleware checks a command, a query, a file request or a cache request (Check::kind).
Command: A command:Check::aggregate_typeandCheck::aggregate_idare set.Query: A query.Data: A file request (crate::Files):Check::type_nameisPutData,GetDataorDeleteData,Check::keyis set.Cache: A cache request (crate::Cache):Check::type_nameisSetCache,GetCacheorDeleteCache,Check::keyis set.Cancel: A cancel of a scheduled command (crate::Kernable::cancel):Check::id,Check::type_name,Check::aggregate_type,Check::aggregate_id,Check::targetandCheck::dataare the scheduled command's (vault fieldsnull),Check::requestis who cancels it. Decide it as the command itself, typically.
CheckOutcome
What came of the request a middleware after it checks: an Outcome for a command, a QueryOutcome for a query.
Command(Outcome): What became of a command.Query(QueryOutcome): What became of a query.
Check
A command, query, cancel, file or cache request a middleware checks, before the kernel accepts or routes it or after (cancels, file and cache requests: before only): what the handler of Listener::middleware gets.
kind: CheckKindid: String: The command or query ID (a cancel: the scheduled command's); for a file or cache request, the kernel's call ID.tenant: Stringdomain: Stringtype_name: String: The command or query type within the domain (a cancel: the scheduled command's); for a file or cache requestPutData,GetData,DeleteData,SetCache,GetCacheorDeleteCache.aggregate_type: Option<String>: Commands and cancels.aggregate_id: Option<String>: Commands and cancels.target: Option<Target>: The aggregate the request is about, its type qualified: a command's aggregate (shop.order,o-17; a cancel: the scheduled command's), or the one a query declares (crate::query'starget,crate::QuerySchema::target).Nonefor queries that declare none, and for file and cache requests.key: Option<String>: File and cache requests only: the file's or value's key.data: Value: The request's payload; vault fields arenullunless the key is grantedvault_read.Value::Nullfor a file or cache request: the middleware never sees the file or value.request: RequestContext: Who sends it: check permissions here.outcome: Option<CheckOutcome>: After it, what came of the request; before it,None.store: Option<Store>: The listener's store, if it has one (Listener::store): what the middleware learned from events, to decide with.
Target
The aggregate a request is about (Check::target).
aggregate_type: String: Qualified:shop.order.aggregate_id: String
When
When a middleware runs.
Before: Checks a request before the kernel accepts or routes it; a rejection refuses it (default).After: Gets the request's outcome too. A rejection refuses a query's response; a command's outcome, and a rejected query, it only observes, best effort (it misses what happens while it is away, and nobody waits for it).
MiddlewareOptions
What a middleware checks: MiddlewareOptions::new(&["shop.*"]), with MiddlewareOptions { order: 5, ..MiddlewareOptions::new(&["*"]) } for another order and .after() to run after requests.
types: Vec<String>: Command and query types:*(all), a type of the listener's domain (Place), of another domain (orders.Place) or a whole domain (orders.*). File and cache requests are types too:PutData,GetData,DeleteData,SetCache,GetCache,DeleteCache(e.g.shop.PutData);*andorders.*cover them.order: i32: Position in the chain: lower runs first, equal orders by listener name (default 0). Negative orders are reserved for kernable's kits (a grant ofreserved_order).when: When: Before (default) or after requests; seeWhen.fn new(types: &[&str]) -> MiddlewareOptions: Checkstypes(seeMiddlewareOptions::types) before requests, at order 0.fn after(self) -> MiddlewareOptions: Runs after requests instead of before: the handler gets their outcome too.
Listener
A durable, named event listener of a domain: a read model (Domain::read_model) or a reactor (Domain::reactor). It defines what to handle; crate::Kernable::listener runs it. Events arrive in order, one at a time, after every listener with a lower order has processed them. Delivery is at least once: if a handler fails, the listener reconnects and the event is delivered again, until a reactor gives up on it and parks it (Listener::park_after).
Types without a domain (ItemAdded) are the listener's own domain's; other domains' are qualified (identity.AccountRegistered). Handlers get event payloads upcast to the versions of the listener's domain and of the domains it is given with with_domain. An event with a newer schema than known stops the listener (it retries and logs) until it is updated, so it never misreads data. Cloning gives another handle to the same definition, and every configuring method returns one, so they chain.
Handlers are closures that return a future: Fn(data, meta, ctx) -> impl Future<Output = Result<_, BoxError>>. They are called again for every event, so they cannot own mutable state: share it as Arc<Mutex<…>>, clone the Arc into each closure with move, and lock it before the async block (do not hold a std::sync::MutexGuard across .await): let rows = Arc::new(Mutex::new(HashMap::<String, u32>::new())); let r = Arc::clone(&rows); carts_readmodel.on("ItemAdded", move |data: ItemAdded, evt, _ctx| { *r.lock().unwrap().entry(evt.aggregate_id).or_default() += data.qty; async { Ok(()) } });
A query handler returns its answer (any Serialize) or a Rejected as a BoxError: carts_readmodel.query("GetCart", move |q: GetCart, _qry, _ctx| { let row = r.lock().unwrap().get(&q.id).copied(); async move { Ok(row.ok_or_else(|| Rejected::new("no such cart").code("not_found"))?) } });
fn name(&self) -> &str: The listener's name: the kernel keeps its position under it.fn domain(&self) -> &Domain: The domain the listener belongs to: types without a domain are its.fn order(&self, order: i32) -> Listener: Listeners with a lower order process each event first; equal orders run in parallel. Defaults: 0 for read models, 10 for reactors. Negative orders are reserved for kernable's kits (a grant ofreserved_order).fn start(&self, position: u64) -> Listener: Position to start after on the first connect: 0 rebuilds from the beginning (default for read models). Reactors resume after the last acknowledged event unless given one, and a new one starts at the newest event, so it never reacts to what happened before it existed. Reconnects always resume after the last handled event.fn live(&self) -> Listener: Not registered with the kernel: no stored position, always starts at the newest event, nobody waits for it, and it is forgotten when it disconnects. For reactions that only matter while the process runs, e.g. pushing to connected browsers. Make it live before running it. Panics if the listener is a middleware: a live listener cannot be one.fn instance(&self, id: &str) -> Listener: Runs this process's listener as the instanceidof a group under the listener's name, e.g. one per node of a pair: 1 to 128 letters, digits,-,_and.. Default:KERNABLE_INSTANCE, whichkernable nodesets; without either, the name has one connection. Read models are replicated: every instance gets every event and answers queries. Reactors are single (seeListener::single).fn single(&self, single: bool) -> Listener: Whether the instances take turns (default for reactors): one gets events, the others wait and the first of them takes over when it leaves, so a side effect happens once.false(default for read models): every instance gets every event, from its own position; such a listener cannot park events. Live listeners are never single.fn reconnect(&self, delay: Duration) -> Listener: Delay before reconnecting after the stream drops or a handler fails (default 1 s); twice as long after each further failed attempt, at most 30 s.fn park_after(&self, attempts: u32) -> Listener: How often a handler may fail on one event before the listener parks it and moves on (default 5 for reactors, 0 for read models; 0: never, the listener keeps getting the event and everything behind it waits). ARejected(also a rejectedListenerContext::submit) parks at once; the kernel being unreachable or busy (UNAVAILABLE,DEADLINE_EXCEEDED,RESOURCE_EXHAUSTED,Error::NotSettled) or the store failing never does: the listener waits and tries again. The kernel keeps parked events with the rejection's code and message (for other errorshandler_errorandhandler failed; the log has the whole error) until an operator retries or dismisses them (kernable listeners retry). A read model should not park: it would miss the event's change. With a store, a parked event's writes are dropped, the rest of its batch kept. Live listeners never park, and no listener parks an event that erases a subject: its handler must get past it, so no personal data stays behind.fn store(&self, url: &str, schema: &str) -> Listener: Keeps the listener's state in a store (sqlite:<path>ormemory:) instead of memory: its data and position are written together per batch, and a restart continues after the stored position.schemais the version of the stored data's format: change it when the handlers store data differently, and the store is cleared and rebuilt. Handlers get the store asctx.store(ListenerContext::store,QueryContext::store). Example:shop_domain.read_model("carts").store("sqlite:carts.db", "1").fn with_domain(&self, domain: &Domain) -> Listener: Upcasts the events of anotherdomainwith its event schemas (seeDomain::event); the listener's own domain's apply without it.fn on<D, F, Fut>(&self, event_type: impl TypeKey<D>, handler: F) -> Listener where D: DeserializeOwned + Send + 'static, F: Fn(D, StoredEventMeta, ListenerContext) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), BoxError>> + Send + 'static: Handlesevent_typeevents: a type of the listener's domain (ItemAdded), of another domain (orders.OrderPlaced), a whole domain (orders.*), or an event type's constant (seecrate::event;querytakes a query type's likewise).handler(data, evt, ctx)gets the payload asD(serde_json::Valuefor any), aStoredEventMetaand aListenerContext, and returns a future ofResult<(), BoxError>. A payload that is not aDor anErrfails the batch: the listener reconnects and the event is delivered again, so handlers must be idempotent. SeeListenerfor an example. Panics ifevent_typeis none of these.fn on_raw<D, F, Fut>(&self, event_type: impl TypeKey<D>, handler: F) -> Listener where D: DeserializeOwned + Send + 'static, F: Fn(D, StoredEventMeta, ListenerContext) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), BoxError>> + Send + 'static: Likeon, but gets events as stored, without upcasting, whatever their schema (for archives and exports).fn also_on<D, F, Fut>(&self, event_type: impl TypeKey<D>, handler: F) -> Listener where D: DeserializeOwned + Send + 'static, F: Fn(D, StoredEventMeta, ListenerContext) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), BoxError>> + Send + 'static: Likeon, but keeps a handler registered for the type already: this one runs after it, in the same delivery (a failing first one skips it). For code that adds to a listener it does not own, e.g. the kit'svisibility; register it after your own handlers.fn query<D, R, F, Fut>(&self, query_type: impl TypeKey<D>, handler: F) -> Listener where D: DeserializeOwned + Send + 'static, R: Serialize, F: Fn(D, QueryMeta, QueryContext) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<R, BoxError>> + Send + 'static: Answersquery_typequeries: a type of the listener's domain (GetOrder) or of another one (orders.GetOrder), from this listener's state:handler(data, qry, ctx)gets the query's data asD, aQueryMetaand aQueryContext, and returns a future of the answerR(anySerialize). The kernel delivers queries in order with the events, so an answer reflects every event handled before it. Return aRejected(as aBoxError) to refuse; any other error refuses withhandler_error. A handler cannot query its own listener (the answer would wait behind itself): the kernel refuses it. SeeListenerfor an example. Panics ifquery_typeis neither.fn middleware<F, Fut>(&self, options: MiddlewareOptions, handler: F) -> Listener where F: Fn(Check) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), BoxError>> + Send + 'static: Makes this listener a middleware: the kernel askshandlerabout every command, query, file and cache request ofoptions.types(seeMiddlewareOptions::types), before accepting or routing it (or after, seeWhen), in chain order, and only once this listener has caught up with the events. Return aRejectedto refuse; any other error refuses too. After a request, the check carries its outcome (Check::outcome). The registration is stored: while this listener is away, the kernel refuses those requests (kernable listeners removeunregisters it). A listener has at most one middleware before and one after. The handler gets aCheckand returns a future ofResult<(), BoxError>:Ok(())lets the request pass. Example:MiddlewareOptions::new(&["shop.*"])with a handler that returnsErr(Rejected::new("not allowed").code("forbidden").into())unlesscheck.request.sender_identitymay sendcheck.type_name. Panics if a type is not*, a type, a qualified type or a domain, the listener has a middleware atoptions.whenalready, or it is live.
ListenerHandle
A Listener running on a connection; see crate::Kernable::listener. Cloning gives another handle to the same running listener.
run().await processes events until stop(). To run several listeners in one process, spawn each (tokio::spawn(async move { handle.run().await })) and await ready() where the next step needs them connected, or use an app (crate::Kernable::app).
fn listener(&self) -> &Listener: The listener's definition.fn position(&self) -> u64: Global position of the last handled event (or skipped, for other event types).fn opened_store(&self) -> Option<Store>: The listener's store, whilerun()has it open.async fn ready(&self): Returns once the kernel accepted the listener.fn stop(&self): Endsrun.async fn run(&self): Processes events, queries and checks untilstop(), reconnecting when the stream drops or a handler fails. With a store, opens it first and continues after its position; if it cannot be opened (a full disk), logs the error and tries again, backing off like a reconnect. When it ends, it closes the store (Store::close); a later run opens it again.
SubscribeOptions
Where a subscription starts and what it reads, for crate::Kernable::subscribe: SubscribeOptions { after: last_seen, types: vec!["shop.*".into()], ..Default::default() }.
after: u64: Global position of the last event already handled; 0: from the beginning.types: Vec<String>: Qualified event types (orders.OrderPlaced) or domains (orders.*); empty: all the key may read.reconnect: Duration: Delay before reconnecting after the stream drops or the handler fails (default 1 s); twice as long after each further failed attempt, at most 30 s.
Subscription
A running subscription; see crate::Kernable::subscribe. Dropping it ends the subscription too; Subscription::stop also waits until it has ended.
fn position(&self) -> u64: Global position of the last handled event.async fn stop(self): Ends the subscription and waits until it has.
Store
A listener's store: JSON values under keys, grouped in namespaces (ns), in a SQLite file or in memory; see crate::Listener::store. Cloning gives another handle to it. Handlers get it as ctx.store: if let Some(store) = &ctx.store { store.set("carts", &evt.aggregate_id, &row)?; }. What an event handler writes takes effect together with the listener's position, once per batch. Errors are Error::Store (SQLite) or Error::Json.
fn open(url: &str, schema: &str) -> Result<Store, Error>: Opensurl(sqlite:<path>, a bare path, ormemory:). If the stored data was built at anotherschema, it is cleared and the read model rebuilds from the first event.fn committed(&self) -> u64: The position up to which the stored data is complete.fn committed_for(&self, part: &str) -> Result<u64, Error>: The position up to which the data is complete for the events of partitionpart: every partition has its own positions."": a kernel without partitions.fn get<T: DeserializeOwned>(&self, ns: &str, key: &str) -> Result<Option<T>, Error>: The value underkeyin namespacensas aT;Noneif there is none.fn set<T: Serialize + ?Sized>(&self, ns: &str, key: &str, value: &T) -> Result<(), Error>: Storesvalueas JSON underkeyin namespacens, replacing a value there.fn remove(&self, ns: &str, key: &str) -> Result<(), Error>: Removes the value underkeyin namespacens, if there is one.fn all<T: DeserializeOwned>(&self, ns: &str) -> Result<Vec<(String, T)>, Error>: Every key and value of a namespace, ordered by key.fn reset(&self, ns: Option<&str>) -> Result<(), Error>: Clears a namespace, or all data.fn close(&self): Closes the store for every handle to it: a batch still open is dropped, the write-ahead log emptied into the file (so data removed is gone from disk too), and the file released. Using it afterwards is anError::Store. A listener closes its store when itsrun()ends; a later run opens it again.
Data
A file as stored by the kernel, returned by Files::get.
data: Vec<u8>: The file's bytes.content_type: String: The media type given when the file was put, e.g.image/png.sha256: String: The SHA-256 ofdata, hex, as the kernel computed it.
Listed
A file as Files::list names it.
key: Stringcontent_type: Stringsize: u64: The file's length in bytes.
Listing
One page of Files::list: up to 1,000 files, and next (to pass as after) if there may be more.
files: Vec<Listed>next: Option<String>
Files
Files of up to 16 MiB (the kernel's --max-data-bytes) under keys of 1 to 512 bytes, per tenant and domain; see crate::Kernable::data. Files are not part of the signed event log, and erasing a vault subject does not delete them, so keep personal data in vault fields instead. A refused or invalid request is Error::Status; a middleware that refuses it (checking PutData, GetData or DeleteData of the domain) makes it PERMISSION_DENIED with "<code>: <message>". Example: kernable.data().put("shop", "invoices/c1.pdf", pdf, "application/pdf").await?, then kernable.data().get("shop", "invoices/c1.pdf").await? returns Some(Data { .. }).
fn context(self, context: RequestContext) -> Files: Replaces the client's default context for the requests of this handle (signed with each; middlewares decide on it); inside a listener, passctx.follow(). Example:kernable.data().context(alice).get("shop", "k").await?.async fn put(&self, domain: &str, key: &str, data: impl Into<Vec<u8>>, content_type: &str) -> Result<String, Error>: Storesdataaskeyofdomain(granteddata_write), replacing any file there. Returns the SHA-256 ofdata(hex) as the kernel computed it: for an event to name.async fn get(&self, domain: &str, key: &str) -> Result<Option<Data>, Error>: The filekeyofdomain(granteddata_read);Noneif there is none.async fn list(&self, domain: &str, prefix: &str, after: &str) -> Result<Listing, Error>: The files ofdomainwhose keys start withprefix(granteddata_read), in the order of their keys' bytes, up to 1,000 after the keyafter(""for the first page). To find files no event names, or what a tenant stores. Example:let mut after = String::new(); loop { let page = files.list("shop", "invoices/", &after).await?; …; match page.next { Some(n) => after = n, None => break } }.async fn delete(&self, domain: &str, key: &str) -> Result<bool, Error>: Deletes the filekeyofdomain(granteddata_write); whether there was one.
Cache
Values of up to 1 MiB under keys of 1 to 512 bytes, per tenant and domain, held in the kernel's memory (granted cache); see crate::Kernable::cache. A restart of the kernel empties the cache; values are not part of the signed event log, and erasing a vault subject does not delete them. For rate limits, short-lived tokens and computed values. A refused or invalid request is Error::Status; a middleware that refuses it (checking SetCache, GetCache or DeleteCache of the domain) makes it PERMISSION_DENIED with "<code>: <message>". Example: kernable.cache().set("shop", "rate:c1", "3", Some(Duration::from_secs(60))).await?, then kernable.cache().get("shop", "rate:c1").await? returns Some(b"3".to_vec()).
fn tenant(self, tenant: impl Into<String>) -> Cache: The tenant to keep values under. Default: the connection's (crate::Options::tenant).fn context(self, context: RequestContext) -> Cache: Replaces the client's default context for the requests of this handle (signed with each; middlewares decide on it); inside a listener, passctx.follow(). Example:kernable.cache().context(alice).get("shop", "k").await?.async fn set(&self, domain: &str, key: &str, value: impl Into<Vec<u8>>, ttl: Option<Duration>) -> Result<(), Error>: Storesvalueaskeyofdomain(grantedcache), replacing any value there. With attl, the value expires after it; without, it stays until deleted or the kernel restarts. A&strorStringis stored as UTF-8.async fn get(&self, domain: &str, key: &str) -> Result<Option<Vec<u8>>, Error>: The valuekeyofdomain;Noneif there is none or it expired.async fn delete(&self, domain: &str, key: &str) -> Result<bool, Error>: Deletes the valuekeyofdomain; whether there was one.
RequestContext
Who sends a request and in which context: signed with the command and stored with every event it causes; signed with file and cache requests too, for middlewares to check. attributes are business data only, never security decisions.
Set a default for a connection with crate::Options::context, or one per request with crate::Submit::context, crate::Query::context, crate::Files::context and crate::Cache::context. Inside a listener's handler, submit follow-up commands with ctx.follow() (crate::ListenerContext::follow). All fields default to empty; set the ones you need: RequestContext { sender_identity: "customer-7".into(), expected_version: Some(3), ..Default::default() }.
sender_tenant: String: The tenant the sender belongs to.sender_identity: String: Who sends the request, e.g. a user or service ID; middlewares check permissions on it.sender_account: Stringsender_session: Stringon_behalf_of: String: Authorize as this identity of the target tenant; the sender stays the real principal.expected_version: Option<u64>: Reject the command (version_mismatch) unless the aggregate is at this version.correlation_id: String: Shared by everything one original request causes; defaults to the command ID.causation_id: String: The command that caused this one.trace_id: Stringbypass_authorization: bool: Privileged: only keys grantedprivilegedfor it may set it.attributes: BTreeMap<String, String>
Timestamp
A point in time in milliseconds since the epoch, shown as RFC 3339 in UTC with milliseconds (2026-10-27T09:00:00.000Z), like JavaScript's toISOString(): format it with to_string(). Timestamp(ms) makes one from milliseconds; the default is the epoch.
fn now() -> Timestamp: The current time. In a command handler, usectx.now()instead (crate::CommandContext::now), which is the same every time the command runs.fn millis(self) -> i64: Milliseconds since the Unix epoch.
BoxError
type BoxError = Box<dyn std::error::Error + Send + Sync>
Any error a listener, query or middleware handler may return; ? converts most errors into it, a Rejected too: return Err(Rejected::new("no such cart").code("not_found").into()). A query or middleware handler that returns a Rejected (also one wrapped in Error::Rejected, e.g. by a query it asked) refuses with its code; any other error refuses with handler_error (middleware_error from a middleware). An event handler's error makes the listener reconnect and get the event again; a reactor parks it at once if it is a Rejected, else after a few attempts (see crate::Listener::park_after).
Rejected
A business reason to refuse a command or query: return it from a handler. code (default rejected) is what callers act on, message what they show.
A command handler returns Err(Rejected::new("Cart is checked out")); a listener's query or middleware handler returns it as a BoxError (.into() or ?). Callers see it as crate::Outcome::Rejected from submit and as Error::Rejected from query.
code: Stringmessage: Stringkey: Option<String>: Set by the kernel forunique_taken: the name of the key another aggregate holds.requirement: Option<Box<crate::Requirement>>: Set by the kernel forrequirement_missing: the first requirement that does not hold. Boxed: it keeps everyResultwith anErrorsmall.fn new(message: impl Into<String>) -> Rejected: A rejection withmessageand the coderejected.fn code(self, code: impl Into<String>) -> Rejected: This rejection with another code, e.g.Rejected::new("no such cart").code("not_found").
Error
Why a call to the kernel failed. It implements std::error::Error, so ? turns it into a BoxError in handlers and main.
Rejected(Rejected): A rejection: the read model or a middleware refused the query (crate::Kernable::query), or a command handler refused the command incrate::Aggregate::handle. A rejected submit is not an error butcrate::Outcome::Rejected.NotSettled(Vec<StoredEvent>): The command was committed, but not every listener that counts processed its events within the kernel's--settle-timeout-ms. Read models may not show the change yet; the committed events are attached. Submitting again with the same ID returns the same outcome.NotDue(String): The command with this ID is scheduled (crate::Submit::at) and not due yet: it has no outcome to wait for. Submit it again by its ID after its time.Status(tonic::Status): The kernel refused the call or could not be reached: the gRPC status, e.g.PERMISSION_DENIEDwithout a grant (see Errors in the reference).Config(String): A key, grant or certificate could not be read, or an option is invalid; also a failing handler incrate::Aggregate::foldandcrate::Aggregate::handle.Json(serde_json::Error): Data could not be encoded or decoded as JSON.Store(rusqlite::Error): A read model's store failed.
reindex_type()
fn reindex_type(aggregate_type: &str) -> String
The type of the command every aggregate that declares unique keys or facts runs without a handler of its own: _reindex_<aggregate_type>, e.g. reindex_type("customer") is _reindex_customer (command types are unique within a domain). It produces no events, so the worker sends the keys and facts of the current state; Kernable::reindex submits it. Command types starting with _reindex_ are reserved for it.
Unique
How a unique key is unique, for crate::Aggregate::unique: within the command's tenant (Unique::tenant, also Unique::default()) or across tenants (Unique::global), and optionally personal: Unique::global().personal(|s: &Customer| Some(s.id.clone())).
fn tenant() -> Self: Unique within the command's tenant: another tenant may hold the same value.fn global() -> Self: Unique across tenants. The key's identity has no tenant, so a command that is rejected withunique_takenlearns that some tenant holds the value.fn personal(self, subject: impl Fn(&S) -> Option<String> + Send + Sync + 'static) -> Self: Makes the value personal data of the subjectsubjectreturns from the state: the kernel keeps the key in its vault, and erasing the subject frees it.Noneor an empty subject: the aggregate holds no value of this key.
Index
The unique keys and facts an aggregate holds in some state, as crate::Aggregate::index computes them for a test, in the order they are declared.
keys: Vec<UniqueKey>facts: Vec<String>: The names of the facts that are true.
UniqueKey
A value of a unique key: no other aggregate holds the same value of the same key (of the same domain and aggregate type, in the same tenant unless global) at the same time.
name: String: The key's name, as declared.value: String: The value. The kernel gets only its SHA-256, never the value.global: bool: Unique across tenants.subject: Option<String>: The person the value belongs to, for a personal key.
Requirement
A fact that another aggregate of the command's tenant must hold (or, Requirement::absent, must not hold) when a command commits, returned by the function given to crate::Aggregate::requires: Requirement::new("shop", "vehicle", &data.vehicle_id, "open"). The aggregate is named by its ID, or by a unique key of its type and the key's value (Requirement::by_key), which the kernel resolves at commit: no aggregate holds the key, none holds the fact. An empty domain is the command's own (Requirement::of).
domain: String: Empty: the domain of the command's aggregate.aggregate_type: String: Unqualified, e.g.vehicle.aggregate_id: String: Empty when the aggregate is named by a key.key: Option<String>: The unique key that names the aggregate instead of its ID, as the aggregate type declares it.value: Option<String>: The key's value, normalised as the aggregate type's key function does: the kernel gets only its SHA-256.Nonein a rejection, which never carries the value.fact: String: The name of a fact that aggregate declares.absent: bool: The aggregate must not hold the fact.fn new(domain: &str, aggregate_type: &str, aggregate_id: &str, fact: &str) -> Requirement: The factfactof thedomain.aggregate_typeaggregate with IDaggregate_id.fn of(aggregate_type: &str, aggregate_id: &str, fact: &str) -> Requirement: AsRequirement::new, of an aggregate type of the command's own domain:Requirement::of("vehicle", &data.vehicle_id, "open").fn by_key(domain: &str, aggregate_type: &str, key: &str, value: &str, fact: &str) -> Requirement: The factfactof thedomain.aggregate_typeaggregate that holds the unique keykeywithvalue(not a personal key):Requirement::by_key("funds", "vehicle", "isin", &data.vehicle, "open"). Normalisevalueas the aggregate type's key does.fn absent(self) -> Requirement: This requirement turned around: the aggregate must not hold the fact. One without events, or no holder of the key, holds none:Requirement::of("vehicle", id, "woundUp").absent().
Reindex
Aggregates to reindex with Kernable::reindex, built with methods that each return the changed request: Reindex::new("shop", "customer", ["k1", "k2"]).tenant("t1").
fn new(domain: &str, aggregate_type: &str, aggregate_ids: impl IntoIterator<Item = impl Into<String>>) -> Reindex: Thedomain.aggregate_typeaggregates with these IDs.fn tenant(self, tenant: impl Into<String>) -> Reindex: The tenant they belong to. Default: the connection's (crate::Options::tenant).
