Expand description
kernable: write event-sourced business logic in Rust; the kernel does the rest.
use kernable::{Kernable, NewEvent, Options, Rejected, domain};
use serde::{Deserialize, Serialize};
#[derive(Clone, Default, Serialize, Deserialize)]
struct Cart { items: u32, checked_out: bool }
#[derive(Serialize, Deserialize)]
struct AddItem { sku: String, qty: u32 }
let shop_domain = domain("shop");
let cart_aggregate = shop_domain.aggregate("cart", Cart::default());
cart_aggregate.apply("ItemAdded", |state, data: AddItem, _evt, _ctx| state.items += data.qty);
cart_aggregate.command("AddItem", |state, data: AddItem, _cmd, _ctx| {
if state.checked_out {
return Err(Rejected::new("Cart is checked out"));
}
Ok(vec![NewEvent::new("ItemAdded", data)])
});
Kernable::new("app.key")?.worker(&cart_aggregate).run().await;Re-exports§
pub use process::Process;
Modules§
- process
- Business processes (design/processes.md): a flow across commands, events and queries, defined in code next to the domain, built into a model the kernel runs.
Structs§
- 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 withdomain(...).aggregate(...); cloning gives another handle to the same aggregate. The registering methods return the aggregate, so they chain. - 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: - AppHandle
- An
Appon a connection; seeKernable::app. Cloning gives another handle to the same app, e.g. to callstop()orready()while another task awaitsrun(). - Apply
Context - What
applygets besides state, data and the event’s meta. No clock and no IDs:applymust compute the same state every time. - 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); seecrate::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 isError::Status; a middleware that refuses it (checkingSetCache,GetCacheorDeleteCacheof the domain) makes itPERMISSION_DENIEDwith"<code>: <message>". Example:kernable.cache().set("shop", "rate:c1", "3", Some(Duration::from_secs(60))).await?, thenkernable.cache().get("shop", "rate:c1").await?returnsSome(b"3".to_vec()). - Cancel
- A cancel of a scheduled command for
Kernable::cancel, built with methods that each return the changed cancel:Cancel::new(&id).tenant("t1"). - 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::middlewaregets. - Command
Context - What a command handler gets besides state, data and the command’s meta: the request context, and the command’s time and IDs.
- Command
Meta - What a command handler gets about the command besides its payload.
- Command
Schema - 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). - Data
- A file as stored by the kernel, returned by
Files::get. - 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 nameddomain.Type. Cloning gives another handle to the same domain. - Event
Meta - What
applygets 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
Schema - 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.
- Files
- Files of up to 16 MiB (the kernel’s
--max-data-bytes) under keys of 1 to 512 bytes, per tenant and domain; seecrate::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 isError::Status; a middleware that refuses it (checkingPutData,GetData,DeleteDataorListDataof the domain) makes itPERMISSION_DENIEDwith"<code>: <message>". Example:kernable.data().put("shop", "invoices/c1.pdf", pdf, "application/pdf").await?, thenkernable.data().get("shop", "invoices/c1.pdf").await?returnsSome(Data { .. }). - Fold
Event - An event to fold with
Aggregate::fold: type, payload version and data, and whatapplylearns about it (empty fields if unknown).FoldEvent::new("ItemAdded", json!({ "qty": 2 }))is enough for most tests. - Index
- The unique keys and facts an aggregate holds in some state, as
crate::Aggregate::indexcomputes them for a test, in the order they are declared. - Kernable
- A connection to the kernel: submits commands, asks queries, and runs workers and listeners. Cloning gives another handle to the same connection.
- Listed
- A file as
Files::listnames it. - 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::listenerruns 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). - Listener
Context - What a listener handler gets besides the event’s payload and meta (the
ctxofListener::on). - Listener
Handle - A
Listenerrunning on a connection; seecrate::Kernable::listener. Cloning gives another handle to the same running listener. - Listing
- One page of
Files::list: up to 1,000 files, andnext(to pass asafter) if there may be more. - Manifest
- What a service consists of, for
Kernable::apply; seeMembershipin 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"). - Middleware
Options - What a middleware checks:
MiddlewareOptions::new(&["shop.*"]), withMiddlewareOptions { order: 5, ..MiddlewareOptions::new(&["*"]) }for another order and.after()to run after requests. - NewEvent
- An event returned by a command handler;
datais stored as JSON. Make it withNewEvent::new:NewEvent::new("ItemAdded", &item). - Of
- Stands for the message type
Mwhere the SDK takes a type: the attributes declare one named like the struct, soapply(TenantCreated, ...)reads like the type itself. - Options
- How to reach the kernel and as whom: the options of
Kernable::new, set with builder methods that each return the changed options. - 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" })). Withoutdata, the query’s data is an empty object ({}). - Query
Context - What a query handler gets besides the query’s data and meta (the
ctxofListener::query). - Query
Meta - What a query handler gets about the query besides its data (the
qryofListener::query). - Query
Schema - What a query type is about. Made with
Domain::query:shop_domain.query("GetOrder").target("order", "id");(aGetOrderwith{"id": "o-17"}is about ordero-17). Clients that ask these queries by name need the domain:kernable.with_domain(&shop_domain). - Query
Target - The aggregate a query is about, as its type declares it:
QuerySchema::target. - Reindex
- Aggregates to reindex with
Kernable::reindex, built with methods that each return the changed request:Reindex::new("shop", "customer", ["k1", "k2"]).tenant("t1"). - Rejected
- A business reason to refuse a command or query: return it from a handler.
code(defaultrejected) is what callers act on,messagewhat they show. - Request
Context - 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.
attributesare business data only, never security decisions. - 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 tocrate::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). - Store
- A listener’s store: JSON values under keys, grouped in namespaces (
ns), in a SQLite file or in memory; seecrate::Listener::store. Cloning gives another handle to it. Handlers get it asctx.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 areError::Store(SQLite) orError::Json. - Stored
Event - An event as stored by the kernel: in an
Outcomeand in aKernable::subscribehandler. - Stored
Event Meta - What a listener handler gets about an event besides its payload (the
evtofListener::on). - Submit
- A command to submit with
Kernable::submitorKernable::enqueue, built with methods that each return the changed command:Submit::new("shop", "cart", "c1", "AddItem").data(json!({ "qty": 2 })).wait(Wait::Committed). Withoutdata, the payload is an empty object ({}). - Subscribe
Options - Where a subscription starts and what it reads, for
crate::Kernable::subscribe:SubscribeOptions { after: last_seen, types: vec!["shop.*".into()], ..Default::default() }. - Subscription
- A running subscription; see
crate::Kernable::subscribe. Dropping it ends the subscription too;Subscription::stopalso waits until it has ended. - Target
- The aggregate a request is about (
Check::target). - 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’stoISOString(): format it withto_string().Timestamp(ms)makes one from milliseconds; the default is the epoch. - Tls
- PEM files for mutual TLS: the CA that signed the kernel’s certificate, and this process’s own certificate and key.
- Unique
- How a unique key is unique, for
crate::Aggregate::unique: within the command’s tenant (Unique::tenant, alsoUnique::default()) or across tenants (Unique::global), and optionally personal:Unique::global().personal(|s: &Customer| Some(s.id.clone())). - Unique
Key - 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.
- 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.
Enums§
- Cancel
Outcome - What became of a cancel, returned by
Kernable::cancel. - Check
Kind - Whether a middleware checks a command, a query, a file request or a cache request
(
Check::kind). - Check
Outcome - What came of the request a middleware after it checks: an
Outcomefor a command, aQueryOutcomefor a query. - Error
- Why a call to the kernel failed. It implements
std::error::Error, so?turns it into aBoxErrorin handlers andmain. - Outcome
- What became of a command, returned by
Kernable::submit. - Query
Outcome - What became of a query, as a middleware that runs after requests gets it
(
CheckOutcome::Query): its response data or why it was rejected. - Switch
- When a membership that names another deployment than the one serving its service switches
to it (
Manifest::switch,App::switch). See the how-to “Deployments and rollbacks”. - Wait
- How long
submitwaits before it responds. - When
- When a middleware runs.
Constants§
- DEFAULT_
TIMEOUT - How long a request waits, for the connection and the answer, unless told otherwise: above the kernel’s own submit and settle timeouts.
Traits§
- Command
Type - A command of an aggregate:
#[command("domain", aggregate = "name")]. - Event
Type - An event:
#[event("domain")]. - Message
- A message of a domain: implemented by the attributes, not by hand.
- Query
Type - A query and its answer:
#[query("domain", answer = Row)]. A query about one aggregate names it, and the field with its ID:#[query("shop", answer = OrderRow, target(aggregate = "order", field = order_id))]. The SDK sends that aggregate with the query, and a middleware decides on it as on a command’s aggregate (crate::Check::target): “only the order’s owner may read it”. The aggregate type is of the query’s domain, or qualified:shop.order. - State
- What an aggregate’s state must be: copied, and stored as JSON in snapshots. Every type that
is
Clone + Serialize + DeserializeOwned + Send + Sync + 'staticis one, typically a struct with#[derive(Clone, Default, Serialize, Deserialize)]. - TypeKey
- A type as
apply,command,requires,onandquerytake it: a name ("ItemAdded","orders.OrderPlaced") with the data as anyD, or a message type’s constant (OrderPlaced), whose data is then that type.
Functions§
- domain
- A domain named
name, on which you define its aggregates, read models, reactors and event and command schemas:let shop_domain = domain("shop");. - reindex_
type - 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::reindexsubmits it. Command types starting with_reindex_are reserved for it.
Type Aliases§
- BoxError
- Any error a listener, query or middleware handler may return;
?converts most errors into it, aRejectedtoo:return Err(Rejected::new("no such cart").code("not_found").into()). A query or middleware handler that returns aRejected(also one wrapped inError::Rejected, e.g. by a query it asked) refuses with its code; any other error refuses withhandler_error(middleware_errorfrom 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 aRejected, else after a few attempts (seecrate::Listener::park_after).
Attribute Macros§
- command
- A command of a domain’s aggregate:
#[command("tenancy", aggregate = "tenant")], optionally withpersonal(fields = [...], subject = path)(repeatable),secret = [password]andtype = "OtherName". - event
- An event of a domain:
#[event("tenancy")], optionally withversion = 2,upcasts = path(afn(EventSchema) -> EventSchemaadding the steps),personal(fields = [email, name], subject = path)(repeatable),erases = pathandtype = "OtherName". - query
- A query of a domain:
#[query("tenancy", answer = TenantRow)](default answer: any JSON), optionally withtarget(aggregate = "tenant", field = tenant_id)(the aggregate it is about: of the query’s domain, or qualifiedtenancy.tenant; its ID in that field) andtype = "OtherName".