Skip to main content

Crate kernable

Crate kernable 

Source
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 with domain(...).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 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().
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.
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()).
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::middleware gets.
CommandContext
What a command handler gets besides state, data and the command’s meta: the request context, and the command’s time and IDs.
CommandMeta
What a command handler gets about the command besides its payload.
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).
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 named domain.Type. Cloning gives another handle to the same domain.
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.
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.
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, DeleteData or ListData 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 { .. }).
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.
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.
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::list names 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::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).
ListenerContext
What a listener handler gets besides the event’s payload and meta (the ctx of Listener::on).
ListenerHandle
A Listener running on a connection; see crate::Kernable::listener. Cloning gives another handle to the same running listener.
Listing
One page of Files::list: up to 1,000 files, and next (to pass as after) if there may be more.
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").
MiddlewareOptions
What a middleware checks: MiddlewareOptions::new(&["shop.*"]), with MiddlewareOptions { order: 5, ..MiddlewareOptions::new(&["*"]) } for another order and .after() to run after requests.
NewEvent
An event returned by a command handler; data is stored as JSON. Make it with NewEvent::new: NewEvent::new("ItemAdded", &item).
Of
Stands for the message type M where the SDK takes a type: the attributes declare one named like the struct, so apply(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" })). Without data, the query’s data is an empty object ({}).
QueryContext
What a query handler gets besides the query’s data and meta (the ctx of Listener::query).
QueryMeta
What a query handler gets about the query besides its data (the qry of Listener::query).
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).
QueryTarget
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 (default rejected) is what callers act on, message what they show.
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.
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).
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.
StoredEvent
An event as stored by the kernel: in an Outcome and in a Kernable::subscribe handler.
StoredEventMeta
What a listener handler gets about an event besides its payload (the evt of Listener::on).
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 ({}).
SubscribeOptions
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::stop also 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’s toISOString(): format it with to_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, also Unique::default()) or across tenants (Unique::global), and optionally personal: Unique::global().personal(|s: &Customer| Some(s.id.clone())).
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.
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§

CancelOutcome
What became of a cancel, returned by Kernable::cancel.
CheckKind
Whether a middleware checks a command, a query, a file request or a cache request (Check::kind).
CheckOutcome
What came of the request a middleware after it checks: an Outcome for a command, a QueryOutcome for a query.
Error
Why a call to the kernel failed. It implements std::error::Error, so ? turns it into a BoxError in handlers and main.
Outcome
What became of a command, returned by Kernable::submit.
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.
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 submit waits 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§

CommandType
A command of an aggregate: #[command("domain", aggregate = "name")].
EventType
An event: #[event("domain")].
Message
A message of a domain: implemented by the attributes, not by hand.
QueryType
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 + 'static is one, typically a struct with #[derive(Clone, Default, Serialize, Deserialize)].
TypeKey
A type as apply, command, requires, on and query take it: a name ("ItemAdded", "orders.OrderPlaced") with the data as any D, 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::reindex submits 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, 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).

Attribute Macros§

command
A command of a domain’s aggregate: #[command("tenancy", aggregate = "tenant")], optionally with personal(fields = [...], subject = path) (repeatable), secret = [password] and type = "OtherName".
event
An event of a domain: #[event("tenancy")], optionally with version = 2, upcasts = path (a fn(EventSchema) -> EventSchema adding the steps), personal(fields = [email, name], subject = path) (repeatable), erases = path and type = "OtherName".
query
A query of a domain: #[query("tenancy", answer = TenantRow)] (default answer: any JSON), optionally with target(aggregate = "tenant", field = tenant_id) (the aggregate it is about: of the query’s domain, or qualified tenancy.tenant; its ID in that field) and type = "OtherName".