Appearance
TypeScript SDK
sh
npm install @kernable/sdkThe SDK needs Node.js ≥ 22.18, which runs TypeScript files directly (node app.ts), and an ES module project ("type": "module" in package.json). A read model with a store uses node:sqlite.
In one file
A cart aggregate run by a worker, a read model that counts its items, a submit and a query. Start a kernel with kernable start --dev first; it creates the app.key the client signs with (Getting started).
ts
import { Kernable, Rejected, domain } from "@kernable/sdk";
const shopDomain = domain("shop");
// Write side: the aggregate decides commands into events.
const cart = shopDomain.aggregate("cart", { items: 0 });
cart.apply("ItemAdded", (state, data: { qty: number }) => { state.items += data.qty; });
cart.command("AddItem", (_state, data: { sku: string; qty: number }) => {
if (data.qty < 1) throw new Rejected("qty must be at least 1", "invalid_qty");
return [{ type: "ItemAdded", data }];
});
// Read side: the read model builds a view from the events and answers queries.
const carts = shopDomain.readModel("carts");
const items = new Map<string, number>();
carts.on("ItemAdded", (data: { qty: number }, evt) => {
items.set(evt.aggregateId, (items.get(evt.aggregateId) ?? 0) + data.qty);
});
carts.query("GetCart", (data: { id: string }) => ({ items: items.get(data.id) ?? 0 }));
const kernable = new Kernable({ key: "app.key" });
const worker = kernable.worker(cart);
const readModel = kernable.listener(carts);
void worker.run();
void readModel.run();
await Promise.all([worker.ready, readModel.ready]);
// submit returns once the command settled: the read model already has the event.
const outcome = await kernable.submit({
domain: "shop", aggregateType: "cart", aggregateId: "c1", type: "AddItem", data: { sku: "apple", qty: 2 },
});
console.log(outcome.committed); // true
console.log(await kernable.query({ domain: "shop", type: "GetCart", data: { id: "c1" } }));
// { items: 2 } on the first run; the events stay, so every run adds 2
worker.stop();
readModel.stop();
kernable.close();In a real service, the worker and the read model run as one app, await kernable.app({ service: "shop", domains: [shopDomain] }).run(), and the submit comes from your API.
How this page is ordered
The items are generated from the TSDoc in sdks/typescript/src, in source order: errors (Rejected, NotSettled), what handlers get (RequestContext, CommandContext, QueryContext, ListenerContext, StoredEvent, Outcome), the definitions (domain(), Domain, Aggregate, EventSchema, CommandSchema), the client (Kernable, App, Data, Cache, Subscription), the processes (Listener, ListenerHandle, Worker), and the read model Store. Each item lists its public members with their signatures; an interface named ...Options holds the options of the method or class it is named after (SubmitOptions for Kernable.submit, ListenerOptions for Domain.readModel and Domain.reactor).
The concepts behind the terms used here: Event sourcing (aggregates, commands, events), Order and consistency (settled and committed, order, which listeners count, dynamic and live listeners), Queries and middleware, Data over time (event versions and upcasts, the vault, stores) and Trust (keys and grants).
Reference
Rejected
A refusal with a business reason: throw it from a command handler, a query handler or a middleware. code is a short machine-readable reason (default "rejected"), message the text for people.
- From a command handler: the command is rejected and stored as rejected, with no events;
submitreturns{ committed: false, code, message }, it does not throw. - From a query handler or a middleware: the request is refused;
Kernable.querythrows aRejectedwith the same code and message.
Any other error a handler throws rejects too, with the code handler_error (a middleware's: middleware_error).
ts
if (state.checkedOut) throw new Rejected("Cart is checked out"); // code: "rejected"
if (!state.open) throw new Rejected("Cart was never opened", reason); // reason: a code of your ownreadonly code: string: The reason as a code, e.g.not_found;"rejected"unless given.key?: string: For a rejected follow-up command (ListenerContext.submit): the key the kernel named (unique_taken).requirement?: Requirement: For a rejected follow-up command: the requirement the kernel named (requirement_missing).
NotSettled
Thrown by a settling submit (wait: "settled", the default) when the command was committed but not every listener that counts processed its events within the kernel's --settle-timeout-ms (default 5 s). The command is not lost, so do not submit it again under a new ID: read models may just not show the change yet. Submitting again with the same id returns the same outcome; a query with minPosition waits for the events.
ts
try {
await kernable.submit({ domain: "shop", aggregateType: "cart", aggregateId: "c1", id: commandId, type: "AddItem", data });
} catch (err) {
if (!(err instanceof NotSettled)) throw err;
const position = err.outcome.events.at(-1)?.position ?? 0; // committed, not yet settled
}readonly outcome: { committed: true; events: StoredEvent[] }: The committed outcome, with the stored events.
NewEvent
An event a command handler returns: { type: "ItemAdded", data: { sku, qty } }. The worker stores it at the payload version declared with Domain.event (1 if not declared) and moves fields declared personal to the vault.
type: string: The event type within the aggregate's domain, unqualified:ItemAdded.data?: unknown: The payload; must survive a JSON round trip. Omitted, it is stored as{}.
RequestContext
Who sends a request and in which context: signed with the command or query and stored with every event a command causes. Middleware decides on it; ListenerContext.follow() passes it on to follow-up commands. All fields are optional; what the sender fields hold is up to your application. attributes are business data only, never security decisions. See The request context.
senderTenant?: string: The sender's tenant, as your application defines it.senderIdentity?: string: The person or system the request is for: who middleware checks.senderAccount?: string: The sender's account, as your application defines it.senderSession?: string: The sender's session, as your application defines it.onBehalfOf?: string: Authorize as this identity of the target tenant; the sender stays the real principal.expectedVersion?: number: Reject the command (version_mismatch) unless the aggregate is at this version.correlationId?: string: Shared by everything one original request causes; defaults to the command ID.causationId?: string: The command that caused this one (follow()sets it).traceId?: string: Your tracing system's ID.bypassAuthorization?: boolean: Privileged: only keys grantedprivilegedforbypass_authorizationmay set it; what it means, middleware decides.attributes?: Record<string, string>: Free key-value pairs for business data, never for security decisions.
CommandMeta
What a command handler gets about the command besides its data (its third argument, cmd).
commandId: string: The command's ID: the idempotency key (SubmitOptions.id) or a generated UUID.type: string: The command type within the domain.domain: stringaggregateType: string: The aggregate type, unqualified:cart.aggregateId: stringtenant: string
CommandContext
What a command handler gets besides state, data and CommandMeta (its fourth argument, ctx). The worker creates it; create one yourself to call a handler directly, e.g. in a unit test with Aggregate.handle: new CommandContext("close-1", {}, new Date(0)).
readonly commandId: string: The command's ID, as inCommandMeta.commandId: whatid()derives its IDs from.request: RequestContext: Who sends the command: check permissions here.readonly now: () => Date: When the kernel received the command: the same every time the command runs. Use it instead ofnew Date().readonly id: () => string: A new ID that is the same every time the command runs (1st call, 2nd call, ...). Use it instead of random IDs.deadline: Date: When the kernel hands the command to another worker if this one has not answered.
QueryMeta
What a query handler gets about the query besides its data (its second argument, qry).
queryId: string: A new UUID per query.type: string: The query type within the domain.domain: stringtenant: string
QueryContext
What a query handler gets besides the query's data and QueryMeta (its third argument, ctx).
request: RequestContext: Who asks: check permissions here.store?: Store: The listener's store, if it has one (ListenerOptions.store).
QueryOptions
A query for Kernable.query: which query type to ask, with which data. The kernel routes it to the read model that answers domain.type.
ts
const cart = await kernable.query<Cart>({ domain: "shop", type: "GetCart", data: { id: "c1" } });domain: string: The domain of the query type:shop.type: string: The query type within the domain:GetCart.data?: unknown: The query's data, sent as JSON; the handler gets it as its first argument.tenant?: string: Default: the client's tenant (Options.tenant).context?: RequestContext: Replaces the client's default context (Options.context).minPosition?: number: Answer only after the read model has processed this global position, e.g. the last event'spositionof acommittedsubmit. Default 0: answer at once.timeoutMs?: number: How long to wait for the connection and the answer; defaultOptions.timeoutMs.allPartitions?: boolean: 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.
Check
A request a middleware checks (the handler's first argument): a command or query, before the kernel accepts or routes it, or after; or a file or cache request (Kernable.data, Kernable.cache), before it runs. Vault fields of a command's data are filled in only for a middleware before the request whose key is granted vault_read; else they are null.
kind: "command" | "query" | "data" | "cache" | "cancel": What is checked: a command, a query, a file request (data) or a cache request (cache); the fields below depend on it.id: string: The command or query ID; empty for a file or cache request.tenant: stringdomain: stringtype: string: The type within the domain: the command or query type, or for a file requestPutData,GetDataorDeleteData, for a cache requestSetCache,GetCacheorDeleteCache.aggregateType?: string: Commands only.aggregateId?: string: Commands only.target?: { type: string; id: string }: The aggregate the request is about, qualified: a command's aggregate (shop.order,o-17), or the one a query declares (Query.target,QuerySchema.target). Absent for queries that declare none, and for file and cache requests.key?: string: File and cache requests only: the file's or value's key.data: unknown: The command's or query's data.undefinedfor a file or cache request: the middleware decides on who asks for which key, never sees the file or value.request: RequestContext: Who sends it: check permissions here.
MiddlewareOptions
What a middleware checks and where it sits in the chain: the first argument of Listener.middleware.
ts
policy.middleware({ types: ["shop.*"] }, (check) => {
if (!check.request.senderIdentity) throw new Rejected("sign in first");
});types: string[]: Request types it checks:*(all), a type of the listener's own domain (Type), another domain's type (domain.Type) or a whole domain (domain.*). Besides command and query types, these cover the file and cache requests of a domain (Kernable.data,Kernable.cache) under the typesPutData,GetData,DeleteData,SetCache,GetCacheandDeleteCache, checked before they run:shop.*includesshop.PutData.when?: "before" | "after":before(default): checks a request before the kernel accepts it; throwing refuses it.after: gets the request's outcome too. Throwing 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). File and cache requests are checked only before.order?: number: 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).
ListenerContext
What a listener handler gets besides the event's data and StoredEventMeta (its third argument, ctx).
replaying: boolean: 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 follow-ups 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.follow(): RequestContext: A request context for commands caused by this event: same sender and correlation, the event's command ascausationId, withoutexpectedVersionandbypassAuthorization. Pass it asSubmitOptions.context.request: RequestContext: The request context of the command that caused the event.store?: Store: The listener's store, if it has one (ListenerOptions.store).processAct(name: string, context: RequestContext): Promise<{ changed: boolean }>: Sets as whom the processnameacts (Kernable.processAct), on the listener's connection: how an authorization kit hands a process its identity.submit(command: FollowUp): Promise<StoredEvent[]>: Submits a command this event causes, on the listener's connection, and returns its events. It needs a fixedid(confirm-<order>), so a redelivered event runs it once. The domain defaults to the listener's, the context tofollow(), the tenant to the event's. ThrowsRejected(with the kernel'skeyorrequirement, if any) if the command is rejected: a reactor then parks the event at once (seeListenerOptions.parkAfter); catch it to accept a rejection. Throws likeKernable.submitotherwise.ts await ctx.submit({ aggregateType: "order", aggregateId: evt.aggregateId, type: "Confirm", id: `confirm-${evt.aggregateId}` });submit(command: Command, target: CommandTarget & { id: string }): Promise<StoredEvent[]>: The same with a command class instance:ctx.submit(new Confirm({ … }), { id, aggregateId }).query<T = unknown>(type: string, data?: unknown, options?: Omit<QueryOptions, "domain" | "type" | "data">): Promise<T>: Asks a query on the listener's connection, likeKernable.query:typeis of the listener's domain (GetOrder) or qualified (crm.GetCustomer). The tenant defaults to the event's. It is the listener's own read: it keeps the client's context, not the event's sender.query<Q extends Query<any>>(query: Q, options?: Omit<QueryOptions, "domain" | "type" | "data">): Promise<AnswerOf<Q>>: The same with a query class instance, typed by its answer:ctx.query(new GetOrder({ id })).
CommandTarget
ts
export type CommandTarget = Omit<SubmitOptions, "domain" | "aggregateType" | "type" | "data">;Where a command class instance goes: SubmitOptions without what the class says.
FollowUp
ts
export type FollowUp = Omit<SubmitOptions, "domain" | "id"> & { domain?: string; id: string };A command a listener's handler submits (ListenerContext.submit): SubmitOptions with a required id, and the domain optional.
EventMeta
What apply gets about an event besides its data. 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()) if the state needs one.
type: string: The event type within its domain:ItemAdded.version: number: 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.aggregateType: string: The aggregate type, unqualified:cart.aggregateId: stringcommandId: string: The command that produced the event.
ApplyContext
What apply gets besides state, data and EventMeta. Nothing that differs between runs (no clock, no IDs), so a replay computes the same state.
request: RequestContext: The request context of the command that caused the event.
StoredEventMeta
What a listener handler gets about an event besides its data and request context (its second argument, evt): the EventMeta fields plus where the event is in the log.
position: number: The event's global position: its place in the one order of all domains and tenants.createdAt: Date: When the kernel committed the event.schema: number: Version of the payload format. Listeners getdataupcast to the version they know (seeDomain.event), unless the handler israw.redacted: string[]: Fields kept in the vault whose value is not here (nullindata): erased, or not readable with this key (grantedvault_read).
StoredEvent
An event as stored by the kernel, with its data and request context: in a submit's Outcome and in a subscription (Kernable.subscribe). Its data is as stored, not upcast; vault fields are null here and listed in redacted.
data: unknown: The payload as stored.request: RequestContext: The request context of the command that caused the event.
Outcome
ts
export type Outcome =
| { committed: true; events: StoredEvent[] }
| { committed: false; code: string; message: string; key?: string; requirement?: Requirement };What came of a command (Kernable.submit): committed with the events it stored, or rejected with a code and message (by its handler, a middleware or the kernel, e.g. version_mismatch). The kernel's codes for unique keys and requirements (see Aggregate.unique): unique_taken (another aggregate holds one of the keys the command would leave its aggregate with: orders.Order key number is taken, never the value), requirement_missing (an aggregate the command requires does not hold the fact: orders.Vehicle v1 does not hold open) and invalid_index (too many keys, facts or requirements, or a malformed name: a bug in the aggregate's definition). A rejection is a result, not an exception; check committed:
ts
const outcome = await kernable.submit({ domain: "shop", aggregateType: "cart", aggregateId: "c1", type: "CheckOut" });
if (!outcome.committed) console.log(outcome.code, outcome.message);For unique_taken, key names the key (number); for requirement_missing, requirement is the first requirement that does not hold. Both are set by the kernel only, and stored with the rejection.
QueryOutcome
ts
export type QueryOutcome =
| { answered: true; data: unknown }
| { answered: false; code: string; message: string };What came of a query: its response data or why it was rejected.
FoldEvent
ts
export type FoldEvent = Partial<EventMeta> & { type: string; schema: number; data: unknown; request?: RequestContext };An event to fold: type, payload version and data, plus as much of EventMeta and its request context as known.
Produced
ts
export type Produced = (NewEvent | Event)[];What a command handler returns: NewEvents or event class instances.
Requirement
A fact another aggregate of the command's tenant must hold (or, absent, must not hold) when the command commits: what CommandOptions.requires returns. The kernel checks it atomically with the commit; if it does not hold, the command is rejected with requirement_missing. The aggregate is named by its ID, or by a unique key of its type (key and value, not a personal key), which the kernel resolves at commit: no aggregate holds the key, none holds the fact. An aggregate without events holds no fact either.
ts
{ aggregateType: "Vehicle", aggregateId: data.vehicleId, fact: "open" }
{ domain: "funds", aggregateType: "Vehicle", key: "isin", value: normalize(data.vehicle), fact: "open" }
{ aggregateType: "Vehicle", aggregateId: data.vehicleId, fact: "woundUp", absent: true }domain?: string: The domain of the aggregate:funds; default: the command's own.aggregateType: string: The aggregate type within the domain, unqualified:Vehicle.aggregateId?: string: The aggregate's ID; omitted when it is named bykey.key?: string: A unique key of the aggregate type that names the aggregate instead of its ID.value?: string: The key's value, normalised as the aggregate type's key function does: the kernel gets only its SHA-256. Absent in a rejection, which never carries the value.fact: string: The fact it must hold, as declared withAggregate.fact:open.absent?: boolean: The aggregate must not hold the fact.
CommandOptions
Options of one command handler: the third argument of Aggregate.command.
requires?: (data: D, state: S) => Requirement[]: The facts other aggregates of the command's tenant must hold for the command to commit, from the command's data and the state before it:(data, state) => Requirement[]. Checked by the kernel at commit, so no command in between can remove a fact unseen; a missing one rejects the command withrequirement_missing. If it throws, the command is rejected as for a handler error.
UniqueOptions
Options of a unique key: the third argument of Aggregate.unique.
scope?: "tenant" | "global":tenant(default): no two aggregates of this type in the same tenant hold the same value;global: none in any tenant. A global key tells a worker of any tenant whether a value is taken.personal?: (state: S) => string | null | undefined: Makes the key personal: the person (subject) its values belong to, from the state, e.g.(state) => state.customerId. The kernel keeps the key in the vault, and erasing the subject frees it. An empty or missing subject: the aggregate holds no value of the key.
HeldKey
A unique key an aggregate holds, as Aggregate.index returns it.
name: string: The key's name, as declared withAggregate.unique.value: string: The value, as the key's function returned it. The kernel gets only its SHA-256 hash.scope: "tenant" | "global"subject?: string: For a personal key: the person the value belongs to.
Index
The unique keys and facts an aggregate holds in a state: what Aggregate.index returns.
keys: HeldKey[]: In the order of declaration, the values of a key in the order its function returned them.facts: string[]: The facts that are true, in the order of declaration.
reindexType()
export function reindexType(aggregateType: string): string
The command an aggregate type with unique keys or facts runs itself, one per aggregate type because command types are unique within a domain: _reindex_Customer. See Kernable.reindex.
AggregateOptions
Snapshot settings of an aggregate: the third argument of Domain.aggregate. Snapshots are a cache of the state; without one, the worker folds all events of the aggregate.
snapshotEvery?: number: Send a snapshot of the state every this many events (default 100; 0 turns them off).schema?: string: 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.
Personal
ts
export type Personal<T> = T | null;A field kept in the vault (EventSchema.personal), as a listener reads it: null after its subject was erased, or for a reader whose key is not granted vault_read. Type such fields with it, so handlers deal with the null: data: { email: Personal<string> }.
EventSchema
The payload format of one event type: its current version, the steps that bring older payloads up to it, and which fields go to the vault. Create it with Domain.event; its methods return it, so they chain. Events are stored as written and never changed; readers upcast them. See Data over time.
ts
shopDomain.event("ItemAdded", 2).upcast(1, (d) => ({ sku: d.sku, count: d.qty }));
identityDomain.event("AccountRegistered", 1).personal(["name", "email"], (_d, id) => id);
identityDomain.event("AccountErased", 1).erases((_d, id) => id);
accounts.on("AccountRegistered", (data: { name: Personal<string>; email: Personal<string> }) => { … });readonly type: string: The event type within its domain, unqualified.readonly schema: number: The current payload version (from 1): what workers write and readers get.readonly steps = new Map<number, Upcast>(): The upcasts by the version they start from.readonly vault = new VaultFields(): The fields kept in the vault; seepersonal.eraser?: Subject: The subject (person) this event erases, if it is an erasing event; seeerases.personal<D = any>(fields: string[], subject: (data: D, aggregateId: string) => string): this: Keeps these top-level fields in the vault, as personal data of the subjectsubjectreturns from the payload and the aggregate's ID (e.g.(d) => d.customerId, or(_d, id) => idfor the aggregate itself). 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.erases<D = any>(subject: (data: D, aggregateId: string) => string): this: 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.upcast<D = any>(from: number, fn: (data: D) => unknown): this: Turns a payload of versionfrominto one of versionfrom + 1;fngets the old payload and returns the new one. Steps chain: version 1 reaches 3 throughupcast(1, …)andupcast(2, …). Throws unlessfromis between 1 andschema - 1. A reader that lacks a step stops at such an event instead of misreading it.
CommandSchema
How a command's payload is kept: which fields go to the vault instead of the signed log. Create it with Domain.command; its methods return it, so they chain. The submitting client seals the fields, so it needs the domain: kernable.use(domain).
ts
identityDomain.command("Register").personal(["name", "email"], (_d, id) => id).secret(["password"]);readonly type: string: The command type within its domain, unqualified.readonly vault = new VaultFields(): The fields kept in the vault; seepersonalandsecret.personal<D = any>(fields: string[], subject: (data: D, aggregateId: string) => string): this: Keeps these top-level fields in the vault as personal data ofsubject; seeEventSchema.personal.secret(fields: string[]): this: 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 domain declares about a query type given by name (domain.query("GetOrder")): the aggregate it is about. Query classes declare it as static target instead.
ts
shopDomain.query("GetOrder").target("order", "id"); // GetOrder { id: "o-17" } is about order o-17readonly type: string: The query type within its domain, unqualified.targetOf?: QueryTarget: The aggregate the query is about; seetarget.target(aggregateType: string, field: string): this: The query is about one aggregate ofaggregateType(order, or qualifiedshop.order), whose ID is in the data'sfield. The SDK sends it with the query, signed, and a middleware decides on it as on a command's aggregate. Clients that ask it need the domain:kernable.use(domain).
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. Create it with domain(name).
Everything is defined on it: aggregates (aggregate), read models (readModel), reactors (reactor), business processes (process), event versions and vault fields (event, command). Kernable.app runs all of it and registers its processes; Kernable.worker and Kernable.listener run parts. See Domains.
ts
const shopDomain = domain("shop");
const cart = shopDomain.aggregate("cart", { items: 0 });
const carts = shopDomain.readModel("carts");
const mailer = shopDomain.reactor("mailer");readonly name: string: The domain's name:shop.readonly events = new Map<string, EventSchema>(): Payload versions and upcasts per event type; types not listed are at version 1.readonly commands = new Map<string, CommandSchema>(): Vault fields per command type; seecommand.readonly queries = new Map<string, QuerySchema>(): What query types given by name are about; seequery.readonly aggregates: Aggregate<any>[] = []: The aggregates defined on it, whichKernable.appruns.readonly listeners: Listener[] = []: The read models and reactors defined on it, whichKernable.appruns.readonly processes: ProcessBuilder[] = []: The business processes defined on it, whichKernable.appregisters.event(type: string, schema: number): EventSchema: Declares the payload format oftypeevents (unqualified): this domain writes them at versionschema(from 1), with anupcastper older version, and may keep fields in the vault (personal) or erase a subject (erases). Returns theEventSchemato chain on. Types not declared are at version 1. The domain's aggregates and listeners use it; listeners of other domains get it withuse(domain). Throws for a qualified type or a version below 1.event(...classes: EventClass<unknown>[]): void: Declares event classes of this domain (their statics:version,upcasts,personal,erases), e.g. in a process that only reads them. An aggregate'sapplydeclares them too.event(type: string | EventClass<unknown>, ...rest: (number | EventClass<unknown>)[]): EventSchema | voidcommand(type: string): CommandSchema: Declares which fields oftypecommands (unqualified) the vault keeps: returns theCommandSchemato chainpersonalandsecreton. Only needed for commands with such fields. Clients that submit them need the domain:kernable.use(domain).query(type: string): QuerySchema: Declares whattypequeries (unqualified) are about: returns theQuerySchemato chaintargeton. Query classes declare it asstatic targetinstead. Clients that ask such queries by name need the domain:kernable.use(domain).aggregate<S>(name: string, initial: S, options?: AggregateOptions): Aggregate<S>: Defines an aggregate typename(cart) of this domain, with the stateinitialevery aggregate of it starts from:shopDomain.aggregate("cart", { items: 0 }). Add its event appliers and command handlers withapplyandcommand; run it withkernable.worker(cart)orkernable.app.options: snapshots, seeAggregateOptions. Throws if the domain has an aggregatenamealready.readModel(name: string, options: ListenerOptions = {}): Listener: Defines a read model namedname: a listener that builds a view from events (on) and answers queries from it (query). Without a store it is kept in memory and rebuilt from the first event on every start (defaults: order 0, start 0); withoptions.storeit continues where it left off.optionsoverride the defaults, seeListenerOptions. Run it withkernable.listener(definition)orkernable.app. Throws if the domain has a listenernamealready.reactor(name: string, options: ListenerOptions = {}): Listener: Defines a reactor namedname: a listener that triggers side effects and follow-up commands. It starts at the newest event when it is new, then resumes after the last acknowledged event (defaults: order 10, no start), so it never reacts to what happened before it existed. Submit follow-ups withctx.submitand a fixed commandid, so a redelivered event is harmless; a rejected one parks the event (seeListenerOptions.parkAfter). 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. Run it withkernable.listener(definition)orkernable.app. Throws if the domain has a listenernamealready.process(name: string): ProcessBuilder: Defines a business processname(fulfilment, qualifiedshop.fulfilment): returns theProcessBuilderto chain its start and steps on. The kernel runs it once registered:Kernable.appregisters the processes of its domains when its workers are connected, and lists them in its membership;Kernable.registerProcessregisters one alone. Throws if the domain has a processnamealready, or for a name other than letters, digits,_and-.
domain()
export function domain(name: string): Domain
Creates a domain named name: const shopDomain = domain("shop"). A name starts with a letter, followed by letters, digits, _ or -; anything else throws. Processes that share a domain (a worker and a read model in another process) each create it with the same name and the same event and command declarations.
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. The state must survive a JSON round trip, because snapshots store it as JSON. An aggregate belongs to a domain and produces events only of that domain; create it with domain(...).aggregate(...). apply and command return the aggregate, so they chain.
A worker runs a command like this: it folds the aggregate's events (from the latest snapshot, if any) into the state, calls the command's handler, and sends the events it returns. The kernel commits them only on the version the state was folded from; if another command came first, the command runs again on the new state.
An aggregate may hold unique keys (unique: no other aggregate holds the same value) and facts (fact), both computed from its state; a command may require facts of other aggregates (CommandOptions.requires). The kernel checks both atomically with the commit, so neither a read model nor a registry of claims is needed to keep a value unique or a condition true.
ts
const cart = shopDomain.aggregate("cart", { items: 0, checkedOut: false });
cart.apply("ItemAdded", (state, data: { qty: number }) => { state.items += data.qty; });
cart.command("AddItem", (state, data: { sku: string; qty: number }) => {
if (state.checkedOut) throw new Rejected("Cart is checked out");
return [{ type: "ItemAdded", data }];
});readonly domain: string: The name of the domain it belongs to.readonly name: string: The aggregate type, unqualified:cart.readonly initial: S: The state every aggregate of this type starts from.readonly snapshotEvery: number: SeeAggregateOptions.snapshotEvery.readonly schema: string: The state format's version; seeAggregateOptions.schema.readonly appliers = new Map<string, Apply<S>>(): Theapplyfunctions per event type.readonly handlers = new Map<string, Handle<S>>(): The command handlers per command type.readonly events: Map<string, EventSchema>: The domain's event schemas.readonly commands: Map<string, CommandSchema>: The domain's command schemas: which fields of a command are personal.readonly keys = new Map<string, KeyDefinition<S>>(): The unique keys by name; seeunique.readonly facts = new Map<string, (state: S) => boolean>(): The facts by name; seefact.readonly requirements = new Map<string, (data: any, state: S) => Requirement[]>(): What the commands require, per command type; seeCommandOptions.requires.apply<D = any>(eventType: string, fn: (state: S, data: D, evt: EventMeta, ctx: ApplyContext) => S | void): this: How an event ofeventType(unqualified, of this domain) changes the state:fn(state, data, evt, ctx)changesstatein place and returns nothing, or returns a new state that replaces it.stateis a copy, so changing it never touches the state it came from.datais upcast to the version declared withDomain.event. Events without anapplyleave the state as it is. Must be deterministic: no clock, no random values, no I/O.apply<E>(event: EventClass<E>, fn: (state: S, data: Fields<E>, evt: EventMeta, ctx: ApplyContext) => S | void): this: The same with an event class:apply(ItemAdded, (state, data) => …),datatyped by its fields.apply(event: string | EventClass<unknown>, fn: Apply<S>): thiscommand<D = any>(commandType: string, fn: (state: S, data: D, cmd: CommandMeta, ctx: CommandContext) => Produced | Promise<Produced>, options?: CommandOptions<S, D>): this: Which events acommandTypecommand (unqualified, of this domain) produces:fn(state, data, cmd, ctx)gets the current state and the command's data and returns the events (NewEvent[], possibly empty), or a promise of them. ThrowRejectedto reject the command. It may run more than once for the same command, so it must decide the same way every time: usectx.now()andctx.id()instead of the clock and random IDs, and leave side effects to reactors.options.requires: facts other aggregates must hold for the command to commit, seeCommandOptions. Throws for a type starting with_reindex_: the built-in commands aggregates with unique keys or facts run themselves (_reindex_Customer, seeKernable.reindex).command<C>(command: CommandClass<C>, fn: (state: S, data: Fields<C>, cmd: CommandMeta, ctx: CommandContext) => Produced | Promise<Produced>, options?: CommandOptions<S, Fields<C>>): this: The same with a command class:command(AddItem, (state, data) => [new ItemAdded({ … })]),datatyped by its fields; its statics declare its vault fields.command(command: string | CommandClass<unknown>, fn: (state: S, data: any, cmd: CommandMeta, ctx: CommandContext) => Produced | Promise<Produced>, options: CommandOptions<S, any> = {}): thisunique(name: string, fn: (state: S) => string | string[] | null | undefined, options: UniqueOptions<S> = {}): this: Declares a unique keyname:fn(state)returns the value (or values) this aggregate holds, ornull/undefinedfor none, and no other aggregate of this type holds the same value within the tenant (options.scope, defaulttenant) or in any tenant (global). After every command the aggregate holds exactly the values its new state yields: a changed value frees the old one in the same commit. A command that would leave the aggregate with a value another one holds is rejected withunique_taken, and nothing is written. Normalise the value yourself (email.trim().toLowerCase()); the kernel gets only its SHA-256 hash.options.personalkeeps the key in the vault, freed by erasing its subject. Aggregates that existed before the key was declared hold it from their next command on; runKernable.reindexto give it to them at once. Two of them with the same value: the second to run a command is rejected withunique_takenuntil its value changes.fnmust be deterministic, asapplymust; if it throws, the command is rejected as for a handler error. Throws for a name declared already, an empty name, or one with a dot or over 128 bytes.ts customer.unique("email", (state) => state.email?.toLowerCase(), { personal: (state) => state.id });fact(name: string, fn: (state: S) => boolean): this: Declares a factnamethis aggregate holds whilefn(state)is true: what other aggregates' commands require (CommandOptions.requires). The kernel keeps the facts each aggregate holds after its last command.fnmust be deterministic, asapplymust. Throws for a name declared already, an empty name, or one with a dot or over 128 bytes.ts vehicle.fact("open", (state) => state.status === "open");index(state: S): Index: The unique keys and facts this aggregate holds instate, as a worker computes them after a command; no kernel needed, so it suits tests next tohandle:cart.index(cart.fold(history)). A key's values come once each; a personal key without a subject holds none. Throws what a key's or fact's function throws, or if a key's function returns something other than a string, a list of strings,nullorundefined.async handle(state: S, commandType: string, data: unknown, ctx: CommandContext, target: { aggregateId?: string; tenant?: string } = {}): Promise<NewEvent[]>: Runs thecommandTypehandler on a copy ofstate, as a worker does, e.g. in a unit test, and returns the events it produces:await cart.handle(state, "AddItem", { sku: "apple", qty: 2 }, new CommandContext("c-1")). The handler'sCommandMetahas the command ID ofctx, this aggregate's domain and name, and the aggregate ID and tenant oftarget(default empty);datagoes through JSON as it would on the wire. Rejects with the handler'sRejected(or other error), or with an error if there is no handler forcommandType.schemaOf(type: string): number: The payload version this aggregate writestypeevents at.fold(history: FoldEvent[], from: S = this.initial): S: State afterhistory, starting fromfrom(default:initial), as a worker computes it; no kernel needed, so it suits tests:cart.fold([{ type: "ItemAdded", schema: 1, data: { qty: 2 } }]). Events are upcast first; events without anapplyare skipped. Fields ofEventMetaan event lacks are empty (0 forversion), as is its request context. Throws if an event's schema is newer than declared or an upcast step is missing.
App
A service made of whole domains, ready to run: one worker for all their aggregates, one ListenerHandle per read model and reactor, and their business processes, registered once the worker and listeners are connected. Create it with Kernable.app, start it with run().
ts
const app = new Kernable({ key: "app.key" }).app({ service: "shop", version: "1.0.0", domains: [shopDomain] });
await app.run(); // until app.stop()readonly ready: Promise<void>: Resolves once every worker and listener of the app is connected and its processes are registered; rejects if a process cannot be registered (run()rejects then too).readonly registered: ProcessVersion[] = []: The app's processes as the kernel registered them (version,new); filled onceready.readonly manifest: Manifest: The membershiprun()applies.readonly worker?: Worker: The worker of all the app's aggregates; none if its domains define no aggregate.readonly listeners: ListenerHandle[]: One handle per read model and reactor of the app's domains, live ones included.async run(options: WorkerOptions = {}): Promise<void>: Applies the membership (seeKernable.apply; the key needsmanagefor the service), then runs the worker and the listeners untilstop(), reconnecting when a connection drops.optionsgo to the worker. Once all are connected, it registers the domains' processes (seeKernable.registerProcess; the key needsprocessfor each, andsubmitfor their commands) and prints an overview of the app on stderr (unlessKERNABLE_LOGis belowinfo). Rejects if the membership cannot be applied, or if a process cannot be registered (an invalid model, a missing grant): it stops the app then, so the deploy fails.stop(): void: Stops the worker and every listener of the app, sorun()resolves.
Manifest
What a service consists of, for Kernable.apply: its membership, which tells the kernel what to wait for. What it lists counts (also before it ever connected); the service's other workers and listeners are dynamic: they run, but nobody waits for them. See Who counts and Membership in kernable.proto.
ts
await kernable.apply({ service: "shop", workers: [cart], listeners: [carts], middlewares: [policy] });service?: string: Default: this process's service (Options.service).workers?: Aggregate<any>[]: The aggregates the service runs; the kernel waits for a worker of each.listeners?: Listener[]: The listeners the kernel waits for, by name; the service's others are dynamic.middlewares?: Listener[]: The service's listeners that may check requests (Listener.middleware); they count like listeners. Only middlewares listed here check requests.metadata?: Record<string, string>: Free metadata, e.g.{ version: "1.0.0" }.processes?: (ProcessBuilder | string)[]: The service's business processes, by builder or qualified name (shop.fulfilment). One the membership no longer lists starts no new cases; its running cases finish.
AppOptions
An app: one service made of whole domains, for Kernable.app. version, description and metadata go into the membership's metadata and the app's overview.
service?: string: The service's name. Default: this process's service (Options.service); one of them is required.version?: string: The app's version, e.g.1.0.0.description?: string: One line about the app.metadata?: Record<string, string>: More metadata.domains: Domain[]: Every aggregate, read model and reactor defined on them runs in this app; their processes are registered.
Options
How a Kernable client connects: kernel address, key, grant and defaults for its requests. Every option has a default, most from an environment variable, so new Kernable() works with the files kernable start --dev creates. The constructor reads the key, grant and TLS files: a missing key file, an explicitly named grant file or a missing TLS file throws.
url?: string: 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.key?: string: Path to this process's.keyfile; it signs every request, worker result and listener handshake. Default:KERNABLE_KEY, elseapp.keyin the current directory.grant?: string: Path to the key's grant (kernable grant), sent with every call. Default:KERNABLE_GRANT, else the key file's path with.grantfor.key(app.grantforapp.key), if it exists.tenant?: string: Default tenant forsubmit,enqueue,query,dataandcache. Default:default.service?: string: The service this process's workers and listeners belong to. Its membership (seeapply) 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).context?: RequestContext: Default request context forsubmit,enqueue,queryand the requests ofdataandcache, e.g. this service's identity; a request's owncontextreplaces it as a whole. Default: empty.tls?: TlsFiles: Mutual TLS forhost:portURLs: paths of the CA certificate and this process's certificate and key. Default:KERNABLE_TLS_CA,KERNABLE_TLS_CERTandKERNABLE_TLS_KEY, if set.insecure?: boolean: Allows plain text to a kernel that is not on this machine. Without TLS, grants, signed requests and vault values cross the network readable, so the client refuses such a URL unless this is set. Default:KERNABLE_INSECURE=1, else false.timeoutMs?: number: 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 000 ms, above the kernel's own submit and settle timeouts.
SubmitOptions
A command for Kernable.submit and Kernable.enqueue: the aggregate it goes to (domain, aggregate type and ID), the command type and its data.
ts
await kernable.submit({ domain: "shop", aggregateType: "cart", aggregateId: "c1", type: "AddItem", data: { sku: "apple", qty: 2 } });domain: string: The domain of the aggregate and the command type:shop.aggregateType: string: The aggregate type within the domain:cart.aggregateId: string: Which aggregate: the stream the command's events go to. A new ID starts a new aggregate.type: string: The command type within the domain:AddItem.data?: unknown: The command's data, sent as JSON; fields declared withDomain.commandgo to the vault.tenant?: string: Default: the client's tenant (Options.tenant).id?: string: The command ID and idempotency key: submitting the same ID again returns the original outcome instead of running the command twice. Default: a new UUID. Give retried commands, and every command a reactor submits, a fixed ID.context?: RequestContext: Replaces the client's default context (Options.context); inside a listener, passctx.follow(). ItscorrelationIddefaults to the command ID.wait?: "settled" | "committed": Whensubmitreturns."settled"(default): once every listener that counts has processed the events, so the next query sees them; throwsNotSettledafter--settle-timeout-ms. From a listener's handler, only the listeners with a lower order count."committed": once the events are stored; read withQueryOptions.minPositionto see them. To return once the command is only queued, useKernable.enqueue. See Settling.timeoutMs?: number: How long to wait for the connection and the outcome; defaultOptions.timeoutMs.at?: Date | number:enqueueonly: a scheduled command, run at this time and not before (aDateor ms since epoch). The kernel stores it at once; the aggregate's other commands pass meanwhile, and middlewares check it now and again when it is due. Cancel it withKernable.cancel.until?: Date | number:enqueueonly, withat: if it cannot run by this time (after an outage), it is rejectedexpired.
ReindexOptions
Which aggregates Kernable.reindex reindexes: domain, aggregate type and IDs.
ts
await kernable.reindex({ domain: "crm", aggregateType: "Customer", aggregateIds: ["k1", "k2"] });domain: string: The domain of the aggregate type:crm.aggregateType: string: The aggregate type within the domain, unqualified:Customer.aggregateIds: string[]: The aggregates to reindex; each ID once.tenant?: string: Default: the client's tenant (Options.tenant).context?: RequestContext: Replaces the client's default context (Options.context).timeoutMs?: number: How long to wait for each outcome; defaultOptions.timeoutMs.
Kernable
A client of one kernel: it submits commands, asks queries, and runs workers and listeners over its connection. Create one per process; the constructor reads the key, grant and TLS files (see Options) and connects on the first call. Every request is signed with the key; the kernel checks it against the key's grant (see Trust).
ts
const kernable = new Kernable({ key: "app.key" }); // or new Kernable() with the defaults
const outcome = await kernable.submit({ domain: "shop", aggregateType: "cart", aggregateId: "c1", type: "AddItem", data: { sku: "apple", qty: 2 } });
const cart = await kernable.query({ domain: "shop", type: "GetCart", data: { id: "c1" } });Calls the kernel refuses itself (not signed, not granted, no read model for a query, the kernel unreachable) reject with the gRPC error, whose details say why. Business rejections come differently: submit returns them in its Outcome, query throws Rejected.
readonly data: Data: Files of a domain kept by the kernel, e.g. invoices; seeData.readonly cache: Cache: The shared cache of a domain; seeCache.use(...domains: Domain[]): this: Seals the vault fields of these domains' commands when submitting them (seeDomain.command); without it, those fields go into the signed log in clear. Returns the client:new Kernable().use(identityDomain).worker(...aggregates: Aggregate<any>[]): Worker: A worker for these aggregates:await kernable.worker(cart).run()executes their commands untilstop(). The kernel registers the aggregates when it connects: commands for an aggregate or command type no worker registered are refused. Start as many workers as you like; the kernel spreads commands over them, one at a time per aggregate. WithoutOptions.serviceor a membership, the aggregates count as soon as they are registered.app(options: AppOptions): App: An app made of whole domains:run()applies the service's membership (its domains' aggregates as workers, their read models and reactors as listeners, those that check requests as middlewares, live ones not listed; and their processes), then runs all of them and, once they are connected, registers the processes:await kernable.app({ service: "shop", domains: [shopDomain] }).run(). Throws if neitheroptions.servicenorOptions.servicenames a service. One service is one app: two processes with the same service would replace each other's membership. To split a service over several processes, runworkerandlistenerandapplythe membership yourself.async apply(manifest: Manifest): Promise<void>: Replaces the membership of a service (default: this process's): the workers, listeners and middlewares the kernel waits for, its processes, and 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 needsmanagefor the service. A middleware the new membership no longer lists stops checking. Throws if neithermanifest.servicenorOptions.servicenames a service. See Remove a listener.async registerProcess(process: ProcessBuilder | ProcessModel): Promise<ProcessVersion>: Registers a business process with the kernel: its builder (Domain.process), whosemodel()it sends, or a model as is. Signed with this client's key, which needs a grantprocessfor the process,submitfor each command,queryfor each query andlistenfor each event the model names. A model equal to the newest version registers nothing (new: false); a different one becomes the next version, while running cases finish on theirs.Kernable.appregisters the processes of its domains itself. Throws whatProcessBuilder.modelthrows, and the kernel'sINVALID_ARGUMENTfor a model it refuses, naming the process, the step and why.ts const { version, new: changed } = await kernable.registerProcess(fulfilment);async processAct(name: string, context: RequestContext): Promise<{ changed: boolean }>: Sets as whom the processname(qualified:shop.fulfilment) acts: the sender tenant, identity and session ofcontextgo with every command and query the kernel's engine sends for it from now on; its correlation and causation stay the engine's. Without it a process acts asprocess:<name>. The identity kit calls it for each process it gives an identity; operator tooling may too. Idempotent:changedis false if the process acted so already. The key needsprocessfor the process. Rejects withNOT_FOUNDfor a process never registered.ts await kernable.processAct("shop.fulfilment", { senderTenant: "platform", senderIdentity, senderSession: keyId });async submit(options: SubmitOptions): Promise<Outcome>: Runs a command and returns its outcome:{ committed: true, events }, or{ committed: false, code, message }if it was rejected (a rejection does not throw). By default it returns once the command settled, so a query right after it sees the events; seeSubmitOptions.wait. ThrowsNotSettledif the command committed but did not settle in time. Idempotent onoptions.id.async submit(command: Command, target: CommandTarget): Promise<Outcome>: The same with a command class instance:submit(new AddItem({ sku, qty }), { aggregateId }). Its class says the domain, aggregate type, type and vault fields (nouseneeded).async submit(command: SubmitOptions | Command, target?: CommandTarget): Promise<Outcome>async enqueue(options: Omit<SubmitOptions, "wait">): Promise<string>: Stores the command in the kernel's queue and returns its ID without waiting for it to run (fire and forget). Submit it again with the sameidto get the outcome. Withat, a scheduled command: it runs at that time, e.g. a reminder in 24 hours,enqueue(Remind.new(), { aggregateId, at: new Date(Date.now() + 86_400_000) }).async enqueue(command: Command, target: Omit<CommandTarget, "wait">): Promise<string>async enqueue(command: Omit<SubmitOptions, "wait"> | Command, target?: Omit<CommandTarget, "wait">): Promise<string>followUpOf(command: Command, target: CommandTarget & { id: string }): FollowUp: A follow-up command (ListenerContext.submit) from a command class instance and its target.async reindex(options: ReindexOptions): Promise<Map<string, Outcome>>: Has these aggregates store the unique keys and facts their current state yields, e.g. after declaring a key on an aggregate type with existing aggregates: each runs the built-in reindex command of its type (_reindex_<aggregateType>, seereindexType), which produces no events. Returns the outcome per ID, once committed: committed (with no events), or rejected, e.g. withunique_takenif another aggregate holds the same value. An ID without events holds nothing. The key needsrunfor<domain>._reindex_<aggregateType>on the worker andsubmithere.ts const outcomes = await kernable.reindex({ domain: "crm", aggregateType: "Customer", aggregateIds: ["k1", "k2"] });async query<T = unknown>(options: QueryOptions): Promise<T>: Asks the read model that answersdomain.typeand returns its answer, typed asT(unchecked):await kernable.query<Cart>({ domain: "shop", type: "GetCart", data: { id: "c1" } }). Queries always go through the kernel, also within one process, so grants and middleware apply. The kernel waits until the read model has caught up (and reachedminPosition). ThrowsRejectedif the read model or a middleware rejects it.async query<Q extends Query<any>>(query: Q, options?: Omit<QueryOptions, "domain" | "type" | "data">): Promise<AnswerOf<Q>>: The same with a query class instance, typed by its answer:query(new GetCart({ id }), { tenant }).async query(query: QueryOptions | Query<any>, more?: Omit<QueryOptions, "domain" | "type" | "data">): Promise<unknown>listener(listener: Listener): ListenerHandle: Runs a listener defined withDomain.readModelorDomain.reactorover this connection:await kernable.listener(carts).run(). Handlers added to the definition later still count untilrun()connects.async cancel(commandId: string, options: { tenant?: string; context?: RequestContext; timeoutMs?: number } = {}): Promise<{ cancelled: true } | { cancelled: false; code: string; message: string }>: Cancels a scheduled command (enqueuewithat) before it is due: it completes as rejectedcancelled. Needssubmitfor the command's type; middlewares check it as a cancel of that type. Returns{ cancelled: false, code }withtoo_late(due, running or done already),not_found, or a middleware's code.subscribe(options: SubscribeOptions, handler: (event: StoredEvent) => void | Promise<void>): Subscription: Streams committed events afteroptions.after(backlog first, then live) tohandler, one at a time, e.g. to export them:kernable.subscribe({ types: ["shop.*"] }, (e) => ...). Reconnects and resumes after the last handled event; if the handler throws, that event is delivered again. Persistpositionyourself to resume across restarts. Unlike a listener, a subscription is not registered: the kernel keeps no position, nobody waits for it, and events arrive as stored (not upcast, vault fieldsnull). The key needssubscribefor the types.close(): void: Closes the connection now; only needed in a long-running process that discards the client.
DataOptions
Options of Data.get, Data.delete, Cache.get and Cache.delete: which tenant's file or value, and who asks.
tenant?: string: Default: the client's tenant (Options.tenant).context?: RequestContext: Who asks; signed, and what middlewares checking the request decide on. Replaces the client's default context (Options.context).
PutDataOptions
Options of Data.put: the tenant, and the content type stored with the file.
contentType?: string: Default:text/plain; charset=utf-8for a string, elseapplication/octet-stream.
Data
Files of a domain kept by the kernel under (tenant, domain, key), at most 16 MiB each (the kernel's --max-data-bytes): PDFs, images, exports. Reading needs a grant of data_read for the domain (shop.*), putting and deleting one of data_write. Files are not part of the signed event log and are not erased with the vault: delete a person's files yourself when erasing them. Use it as kernable.data.
Each request carries a request context (DataOptions.context, default Options.context) and passes the middleware chain first, as <domain>.PutData, .GetData or .DeleteData (see Check). A middleware that refuses it makes the call throw a gRPC error with code PERMISSION_DENIED and the message <code>: <message>.
ts
await kernable.data.put("shop", "invoices/o1.pdf", pdfBytes, { contentType: "application/pdf" });
const file = await kernable.data.get("shop", "invoices/o1.pdf"); // { data, contentType, sha256 } or undefined
const { files, next } = await kernable.data.list("shop", "invoices/"); // up to 1,000; then { after: next }See Store files and cache values.
async put(domain: string, key: string, data: Uint8Array | string, options: PutDataOptions = {}): Promise<string>: Storesdataunderkey, replacing a file there; a string is stored as UTF-8. Resolves to the SHA-256 of the data (hex) as the kernel computed it: for an event to name.async get(domain: string, key: string, options: DataOptions = {}): Promise<{ data: Uint8Array; contentType: string; sha256: string } | undefined>: The file underkeywith its SHA-256 (hex), orundefinedif there is none.async list(domain: string, prefix = "", options: ListDataOptions = {}): Promise<{ files: { key: string; contentType: string; size: number }[]; next?: string }>: The files whose keys start withprefix(needsdata_read), in the order of their keys' bytes, up to 1,000 afteroptions.after;next, if set, is theafterof the next page. To find files no event names, or what a tenant stores.async delete(domain: string, key: string, options: DataOptions = {}): Promise<boolean>: Deletes the file underkey; returns whether there was one.
ListDataOptions
Options of Data.list: the tenant, and where the page starts.
after?: string: Thenextof the page before; default: the first page.
SetCacheOptions
Options of Cache.set: the tenant, and when the value expires.
ttlMs?: number: Milliseconds until the value expires; default: until deleted or the kernel restarts.
Cache
The shared cache of a domain: values of at most 1 MiB under (tenant, domain, key) that may expire, e.g. rates or tokens shared by several processes. Needs a grant of cache for the domain (shop.*). The cache lives in the kernel's memory: a restart empties it. Values are not part of the signed event log and are not erased with the vault. Use it as kernable.cache.
Each request carries a request context (DataOptions.context, default Options.context) and passes the middleware chain first, as <domain>.SetCache, .GetCache or .DeleteCache (see Check). A middleware that refuses it makes the call throw a gRPC error with code PERMISSION_DENIED and the message <code>: <message>.
ts
await kernable.cache.set("shop", "rates/EUR", JSON.stringify(rates), { ttlMs: 60_000 });
const value = await kernable.cache.get("shop", "rates/EUR"); // Uint8Array or undefined
if (value) rates = JSON.parse(new TextDecoder().decode(value));See Store files and cache values.
async set(domain: string, key: string, value: Uint8Array | string, options: SetCacheOptions = {}): Promise<void>: Storesvalueunderkey, replacing a value there; a string is stored as UTF-8.async get(domain: string, key: string, options: DataOptions = {}): Promise<Uint8Array | undefined>: The live value underkey, orundefinedif there is none or it expired.async delete(domain: string, key: string, options: DataOptions = {}): Promise<boolean>: Deletes the value underkey; returns whether there was a live one.
SubscribeOptions
What Kernable.subscribe streams: from which position, and which event types.
after?: number: Global position of the last event already handled; 0 = from the beginning (default).types?: string[]: Qualified event types (orders.OrderPlaced) or domains (orders.*); empty = all the key may read.reconnectMs?: number: Milliseconds to wait before reconnecting after the stream ends (default 1000); twice as long after each further failed attempt, at most 30 s.
Subscription
A running subscription, from Kernable.subscribe. It streams until stop(), reconnecting after position when the stream drops; done resolves after stop().
position: number: Global position of the last handled event.readonly done: Promise<void>: Resolves afterstop().stop(): void: Stops the subscription: ends its stream;donethen resolves.
ListenerOptions
How a listener runs: its place in the order, where it starts, whether it is live, and where it keeps its state. The second argument of Domain.readModel and Domain.reactor, which set the defaults. See Order and consistency.
ts
const carts = shopDomain.readModel("carts", { store: "sqlite:carts.db" });
const push = shopDomain.reactor("push", { live: true });order?: number: 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).start?: number: Position to start after on the first connect: 0 rebuilds from the beginning (default for read models); omitted, the kernel resumes after the last acknowledged event, and a new listener starts at the newest event, so it never reacts to what happened before it existed (default for reactors). Reconnects always resume after the last handled event.live?: boolean: 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. Cannot be a middleware.instance?: string: Runs this process's listener as one instance of 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. The group counts as one listener: it is through an event once one instance has handled it.single?: boolean: 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, and answers queries; such a listener cannot park events. Live listeners are never single.reconnectMs?: number: Milliseconds to wait before reconnecting after the stream ends (default 1000); twice as long after each further failed attempt, at most 30 s.store?: string: 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 (startis then ignored). SeeListenerHandle.store.schema?: string: Version of the stored data's format (default "1"). Change it when the handlers store data differently: the store is cleared and the listener rebuilds from the first event.parkAfter?: number: 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 fromctx.submit) parks at once; the kernel being unreachable or busy (UNAVAILABLE,DEADLINE_EXCEEDED,RESOURCE_EXHAUSTED),NotSettledor 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_errorand the error's type; 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.
HandlerOptions
Options of one event handler: the third argument of Listener.on.
raw?: boolean: Get events as stored, without upcasting, whatever their schema (for archives and exports). By default a listener stops at an event whose schema it does not know.
MiddlewareContext
What a middleware handler gets besides the check: the listener's store, if it has one.
store?: Store
Listener
The definition of a durable, named event listener: which events it handles, which queries it answers and what it checks as a middleware. Define it on a domain with Domain.readModel or Domain.reactor, like an aggregate, and run it with kernable.listener(definition).
Type names without a domain (ItemAdded, GetCart) are of the listener's own domain; types of other domains are qualified (identity.AccountRegistered) or name a whole domain (identity.*).
Handlers get event payloads upcast to the versions of the listener's own domain and of the domains it uses. An event with a newer schema than known stops the listener (it retries and logs) until it is updated, so it never misreads data.
use, on, query and middleware return the listener, so they chain:
ts
const carts = shopDomain.readModel("carts");
const rows = new Map<string, { items: number }>();
carts
.on("ItemAdded", (data: { qty: number }, evt) => {
const row = rows.get(evt.aggregateId) ?? { items: 0 };
row.items += data.qty;
rows.set(evt.aggregateId, row);
})
.query("GetCart", (data: { id: string }) => {
const row = rows.get(data.id);
if (!row) throw new Rejected("no such cart");
return row;
});readonly domain: Domain: The domain the listener is defined on: its unqualified types are of this domain.readonly name: string: The listener's name, unique per tenant; the kernel tracks its position under it.readonly options: ListenerOptions: The options it was defined with, including the defaults ofreadModelorreactor.readonly handlers = new Map<string, { handler: EventHandler; raw: boolean }>(): Event handlers per qualified event type or domain (domain.*).readonly queries = new Map<string, QueryHandler>(): Query handlers per qualified query type.readonly middlewares = new Map<"before" | "after", { options: MiddlewareOptions; handler: MiddlewareHandler }>(): The middleware handlers and their qualified types, before and after requests.readonly domains = new Map<string, Domain>(): The domains whose event schemas upcast events, by name: the own domain and those ituses.use(...domains: Domain[]): this: Upcasts the events of these other domains with their event schemas (seeDomain.event).on<D = any>(eventType: string, handler: (data: D, evt: StoredEventMeta, ctx: ListenerContext) => void | Promise<void>, options?: HandlerOptions): this: Handles events ofeventType: a type of the own domain (ItemAdded), of another domain (identity.AccountRegistered) or a whole domain (identity.*):handler(data, evt, ctx)gets the upcast payload, the event'sStoredEventMetaand aListenerContext. A handler for the exact type wins over one for its domain; one handler per type (a second replaces the first). The listener acknowledges an event only after the handler finished (a returned promise resolved); if it throws, the event is delivered again. Withoptions.raw, it gets the payload as stored. Throws for a malformed type.on<E>(event: EventClass<E>, handler: (data: Fields<E>, evt: StoredEventMeta, ctx: ListenerContext) => void | Promise<void>, options?: HandlerOptions): this: The same with an event class, of this domain or another:on(ItemAdded, (data) => …),datatyped by its fields. The class must be declared (an aggregate'sapplyorDomain.event); its domain's event schemas upcast its events.on(event: string | EventClass<unknown>, handler: (data: any, evt: StoredEventMeta, ctx: ListenerContext) => void | Promise<void>, options: HandlerOptions = {}): thisquery<D = any, R = unknown>(queryType: string, handler: (data: D, qry: QueryMeta, ctx: QueryContext) => R | Promise<R>): this: Answers the query typequeryType, of the own domain (GetCart) or another one (orders.GetOrder), from this listener's state. The kernel delivers queries in order with the events, so an answer reflects every event handled before it.handler(data, qry, ctx)gets the query's data, itsQueryMetaand aQueryContext, and returns the answer (or a promise of it), sent as JSON. ThrowRejectedto refuse; any other error refuses withhandler_error. A handler cannot query its own listener (the answer would wait behind itself): the kernel refuses it. Throws for a malformed type.query<Q>(query: QueryClass<Q>, handler: (data: Fields<Q>, qry: QueryMeta, ctx: QueryContext) => AnswerOf<Q> | Promise<AnswerOf<Q>>): this: The same with a query class:query(GetCart, (data) => …), typed by its fields and its answer.query(query: string | QueryClass<unknown>, handler: (data: any, qry: QueryMeta, ctx: QueryContext) => unknown): thismiddleware(options: MiddlewareOptions, handler: MiddlewareHandler): this: Makes this listener a middleware: the kernel askshandlerabout every command, query, file and cache request ofoptions.types, before accepting or routing it (or after, seeMiddlewareOptions.when), in chain order, and only once this listener has caught up with the events. ThrowRejectedto refuse; any other error refuses too. The registration is stored: while this listener is away, the kernel refuses those requests (kernable listeners removeunregisters it). The handler cannot submit or query what it checks itself (it would wait behind itself): the kernel refuses it. A listener has at most one middleware before and one after.handler(check, outcome, ctx)gets theCheck; after the request, also itsOutcome(a command) orQueryOutcome(a query); and aMiddlewareContextwith the listener's store, if it has one. The key needscheckfor the types; if its service has a membership, the membership must list it as a middleware (Kernable.appdoes that). Throws for a live listener, a malformed type, or a second middleware at the samewhen. See Middleware.
ListenerHandle
A listener running over a connection: kernable.listener(definition). 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 throws, the listener reconnects and the event is delivered again, until a reactor gives up on it and parks it (ListenerOptions.parkAfter). With a store, a batch's data and position are written together, so it takes effect once.
ts
const handle = kernable.listener(carts);
void handle.run(); // until handle.stop()
await handle.ready;position = 0: Global position of the last handled event (or skipped, for other event types).readonly ready: Promise<void>: Resolves once the kernel accepted the listener.startedAt = 0: Position after which the kernel delivered on the first connect.announce = true: Whether the first connect gets its own line; anAppprints it in its overview instead.readonly listener: Listener: The definition it runs.get store(): Store: The listener's store (ListenerOptions.store) whilerun()runs: it opens the store and closes it when it ends. Throws outside of that, or if the listener has no store. Handlers get it asctx.store.async run(): Promise<void>: Opens the store (if any; trying again while it cannot be opened, e.g. on a full disk), connects, and processes events, queries and checks untilstop(), reconnecting after the last handled event when the stream drops or a handler throws (afterListenerOptions.reconnectMs). Resolves afterstop(), having closed the store.stop(): void: Stops the listener: ends its stream, sorun()resolves.
WorkerOptions
How a worker runs: the argument of Worker.run and App.run.
concurrency?: number: Commands executed in parallel, of different aggregates (default 16).reconnectMs?: number: Milliseconds to wait before reconnecting after the session ends (default 1000); twice as long after each further failed attempt, at most 30 s.
Worker
A worker: runs the commands of its aggregates over a connection. Create it with kernable.worker(...aggregates) (or let Kernable.app do it) and start it with run(). The kernel leases it one command at a time per aggregate, with the aggregate's events (and latest snapshot); the worker folds them, calls the command's handler, and sends back the signed events, or the rejection. A command whose handler throws Rejected is rejected with its code; any other error rejects with handler_error. An event whose schema the worker does not know ends the session instead (it logs and reconnects until it is updated).
ts
await kernable.worker(cart).run({ concurrency: 32 });readonly ready: Promise<void>: Resolves once the kernel accepted the worker.announce = true: Whether the first connect gets its own line; anAppprints it in its overview instead.async run(options: WorkerOptions = {}): Promise<void>: Registers the aggregates and processes commands untilstop(), reconnecting when the session drops. Resolves afterstop().stop(): void: Stops the worker: ends its session, sorun()resolves.
Fields
ts
export type Fields<T> = {
[K in keyof T as K extends `__${string}` ? never : T[K] extends (...args: any[]) => any ? never : K]: T[K];
};A message's data: the instance fields of its class, without methods.
SubjectOf
ts
export type SubjectOf<T> = (data: Fields<T>, aggregateId: string) => string;Whose personal data fields hold: from the payload and the aggregate's ID.
PersonalFields
Fields kept in the vault as personal data of subject.
fields: readonly (keyof Fields<T> & string)[]subject: SubjectOf<T>
Event
An event: what happened, in the past tense. Its class name is its type within the domain of the aggregate that writes it; its fields are its payload.
ts
export class TenantCreated extends Event {
slug!: string;
name!: string;
}
tenant.apply(TenantCreated, (state, data) => { state.slug = data.slug; });
return [TenantCreated.new({ slug, name })];Statics declare what Domain.event declares: version (default 1), upcasts (from each older version), personal fields and erases. type overrides the class name, e.g. if a bundler renames classes.
Command
A command: what should happen, imperative. Its class name is its type within the domain of the aggregate that handles it; its fields are its data. Statics: personal and secret fields, type.
ts
export class SignIn extends Command {
static secret: (keyof SignIn)[] = ["password"];
email!: string;
password!: string;
}
account.command(SignIn, (state, data) => …);
await kernable.submit(SignIn.new({ email, password }), { aggregateId });Query
A query: what is asked, with R its answer. Its class name is its type within the domain of the read model that answers it. A query about one aggregate names it in static target: the SDK sends that aggregate with the query, and a middleware decides on it as on a command's aggregate ("only the tenant's members may read it").
ts
export class GetTenant extends Query<TenantRow> {
static target = { aggregateType: "tenancy.tenant", field: "tenantId" };
tenantId!: string;
}
tenants.query(GetTenant, (data) => rows.get(data.tenantId));
const row = await kernable.query(GetTenant.new({ tenantId }), { tenant }); // a TenantRowMessageStatics
The statics a message class may declare.
type?: string: The type, if not the class name.version?: numberupcasts?: Record<number, (data: any) => unknown>personal?: readonly { fields: readonly string[]; subject: (data: any, aggregateId: string) => string }[]erases?: (data: any, aggregateId: string) => stringsecret?: readonly string[]target?: QueryTarget: Queries: the aggregate a query is about, the field of its data that holds the aggregate's ID ({ aggregateType: "order", field: "id" }); an unqualified type is of the query's domain.
QueryTarget
The aggregate a query is about: its type, and the field of the query's data with its ID.
aggregateType: string:order(the query's domain) or qualified:shop.order.field: string: The field of the query's data that holds the aggregate's ID:id.
EventClass
ts
export type EventClass<E> = MessageClass<E>;CommandClass
ts
export type CommandClass<C> = MessageClass<C>;QueryClass
ts
export type QueryClass<Q> = MessageClass<Q>;AnswerOf
ts
export type AnswerOf<Q> = Q extends Query<infer R> ? R : unknown;Binding
Where a class was put to use: its domain, and for a command its aggregate type.
domain: stringaggregateType?: stringschemas?: unknown: The domain's event and command schemas: what upcasts and seals its messages.
isMessageClass()
export function isMessageClass(value: unknown): value is EventClass<unknown>
Whether value is a message class rather than a type name.
typeOf()
export function typeOf(cls: Function & MessageStatics): string
The type a class stands for: static type, else its name. A name that is no type (a bundler renamed the class) throws, so a renamed class never writes events under a wrong type.
bind()
export function bind(cls: Function, binding: Binding): void
Records where cls is used; a class belongs to one domain (and one aggregate type).
bindingOf()
export function bindingOf(cls: Function): Binding | undefined
Where cls is used, if anywhere yet.
boundOrThrow()
export function boundOrThrow(cls: Function, what: string): Binding
cls's binding, or an error that names what to do.
dataOf()
export function dataOf(message: object): Record<string, unknown>
A message instance's data, as plain JSON fields.
Store
A listener's store: JSON values under (namespace, key) in a SQLite file (or in memory), written in one transaction with the listener's position per batch of events. So after a crash every event has taken effect exactly once, and a restart continues after the stored position instead of rebuilding. Give a read model one with ListenerOptions.store; its handlers get it as ctx.store (also query handlers), or use ListenerHandle.store. Reads and writes are synchronous. Uses node:sqlite.
ts
const carts = shopDomain.readModel("carts", { store: "sqlite:carts.db" });
carts.on("ItemAdded", (data: { qty: number }, evt, ctx) => {
const row = ctx.store!.get<{ items: number }>("carts", evt.aggregateId) ?? { items: 0 };
ctx.store!.set("carts", evt.aggregateId, { items: row.items + data.qty });
});
carts.query("GetCart", (data: { id: string }, _qry, ctx) => ctx.store!.get("carts", data.id));committed: number: The global position up to which the stored data is complete: the last committed batch.static async open(url: string, schema: string): Promise<Store>: 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.get<T = unknown>(ns: string, key: string): T | undefined: The value underkeyin namespacens, orundefinedif there is none.set(ns: string, key: string, value: unknown): void: Storesvalue(as JSON) underkeyin namespacens, replacing a value there.remove(ns: string, key: string): void: Removes the value underkeyin namespacens, if there is one.all<T = unknown>(ns: string): [string, T][]: Every key and value of a namespace, ordered by key.reset(ns?: string): void: Clears a namespace, or all data.close(): void: Closes the database, leaving no old pages behind.
Literal
A literal in a mapping or a model: { value: <json> }; build it with value(…).
value: unknown
value()
export function value(x: unknown): Literal
A literal for a mapping, where a plain string would be a reference: data: { reason: value("unpaid") } sends the string unpaid, while "case.reason" sends the case's field. Any JSON value; throws for undefined.
Mapping
ts
export type Mapping = Record<string, string | Literal>;Field → reference or literal: { orderId: "case.orderId", reason: value("unpaid") }. A reference is aggregateId or data.<path> (the event being handled, in start and wait), case.<path> (the case's data), or in a query step answer / answer.<path>. Paths are wire names (camelCase), as the messages' fields.
Duration
ts
export type Duration = `${number}${"s" | "m" | "h" | "d"}`;A duration: a positive whole number of seconds, minutes, hours or days: 30s, 15m, 12h, 3d.
StartOptions
The options of ProcessBuilder.start.
key: string: Where the case's key is in the event:aggregateIdordata.<field>. One case per key.data?: Mapping: The case's data, from the event:{ orderId: "aggregateId", total: "data.total" }.
CancelOnOptions
The options of ProcessBuilder.cancelOn.
key: string: Where the case's key is in the event:aggregateIdordata.<field>.end: string: The end step the case ends at:closed.
CommandStepOptions
The options of ProcessBuilder.command.
aggregate: string: The aggregate the command goes to, a reference:case.orderId.data?: Mapping: The command's data, from the case:{ orderId: "case.orderId", reason: value("unpaid") }.rejected?: Record<string, string>: The step to go to per rejection code:{ out_of_stock: "notify" }. Any other rejection is an incident.next?: string: The step after the command committed. Default: the next step written.
WaitOptions
The options of ProcessBuilder.wait.
key: string: Where the case's key is in the awaited event:aggregateIdordata.<field>.data?: Mapping: Merged into the case's data, from the event:{ paidAt: "data.at" }.timeout?: Duration: How long to wait (3d); withonTimeout, the step to go to then.onTimeout?: string: The step aftertimeout; required with it.next?: string: The step after the event came. Default: the next step written.
TimerWhen
ts
export type TimerWhen = { after: Duration; at?: never } | { at: string; after?: never };When a timer step fires: { after: "1d" }, or { at: "case.dueAt" } (a reference to a time in ms since epoch).
TimerOptions
The options of ProcessBuilder.timer.
next?: string: The step after the timer fired. Default: the next step written.
DecideCase
One case of a decision: if the condition when holds, go to then.
when: string: A condition on the case's data:case.total > 1000.then: string: The step to go to if it holds.
DecideOptions
ts
export type DecideOptions =
| { when: string; then: string; otherwise?: string; cases?: never }
| { cases: DecideCase[]; otherwise?: string; when?: never; then?: never };The options of ProcessBuilder.decide: one condition (when, then) or several in order (cases, the first that holds wins); otherwise if none holds, by default the step written next.
QueryStepOptions
The options of ProcessBuilder.query.
data?: Mapping: The query's data, from the case:{ orderId: "case.orderId" }.answer?: string: For an answer that is an object: the path of the field to matchpathsagainst. Default: the answer itself.paths: Record<string, string> | [unknown, string][]: The step per answer:{ true: "approved", false: "paid" }. Keystrueandfalsestand for the booleans, numeric keys for numbers, others for strings. For a string answer that looks like a boolean or a number, give pairs instead:[["true", "approved"], ["1", "paid"]].into?: string: A case field to keep the answer in:approval(read ascase.approvallater).otherwise?: string: The step for an answer no path matches. Without it, such an answer is an incident.
ProcessModel
A process model, as the kernel registers it; see "The model format" in design/processes.md.
name: string: Qualified:shop.fulfilment.start: { on: string; key: string; data?: Mapping }steps: ProcessStep[]: In the order written.cancelOn?: { event: string; key: string; end: string }[]: Events that end a running case at once, whatever step it is at.
ProcessStep
ts
export type ProcessStep =
| { name: string; kind: "command"; command: string; aggregate: string; data?: Mapping; rejected?: Record<string, string>; next: string }
| { name: string; kind: "wait"; event: string; key: string; data?: Mapping; timeoutMs?: number; onTimeout?: string; next: string }
| { name: string; kind: "timer"; afterMs?: number; at?: string; next: string }
| { name: string; kind: "decide"; when: { if: string; next: string }[]; otherwise: string }
| { name: string; kind: "query"; query: string; data?: Mapping; answer?: string; paths: { value: unknown; next: string }[]; into?: string; otherwise?: string }
| { name: string; kind: "end" };One step of a ProcessModel; every step but end names what comes next.
ProcessVersion
What the kernel answered to a registration: version from 1; new false if the model equals the newest version.
name: string: Qualified:shop.fulfilment.version: numbernew: boolean: False: the model equals the newest version, nothing was registered.
ProcessBuilder
A business process of a domain, built in code and run by the kernel: a case starts when an event commits, and moves through steps (commands, waits for events, timers, decisions by the case's data or by a query) to an end. Create it with Domain.process(name); Kernable.app registers the processes of its domains.
Steps run in the order written, unless a step names next; branching steps (decide, query) and error paths (rejected, onTimeout) name their targets. Step names are required and stable: versions, the UI and the statistics know steps by them. References are strings (aggregateId, data.total, case.orderId, answer.approved), literals value(…), conditions short expressions (case.total > 1000) that the kernel parses when registering.
Messages are classes or names. A command class gives <domain>.<aggregateType>.<Type> from the aggregate that handles it, an event or query class <domain>.<Type>; by name, an unqualified one is of the process's domain (OrderApproved, order.Ship), others qualified (payments.PaymentReceived, shop.order.Ship). Classes are resolved by model(), so they may be bound to their aggregates and read models after the process is defined.
ts
export const fulfilment = shop.process("fulfilment")
.start(OrderSubmitted, { key: "aggregateId", data: { orderId: "aggregateId", total: "data.total" } })
.command("confirm", Confirm, { aggregate: "case.orderId" })
.decide("large", { when: "case.total > 1000", then: "approval", otherwise: "paid" })
.query("approval", NeedsApproval, { data: { orderId: "case.orderId" }, paths: { true: "approved", false: "paid" } })
.wait("approved", OrderApproved, { key: "aggregateId" })
.wait("paid", "payments.PaymentReceived", { key: "data.orderId", timeout: "3d", onTimeout: "cancel" })
.command("ship", Ship, { aggregate: "case.orderId", rejected: { out_of_stock: "notify" }, next: "done" })
.command("notify", NotifyDelay, { aggregate: "case.orderId", next: "done" })
.command("cancel", Cancel, { aggregate: "case.orderId", data: { reason: value("unpaid") } })
.end("done");readonly domain: string: The name of the domain it belongs to:shop.readonly name: string: The process's name within its domain:fulfilment.get qualified(): string: The qualified name, as the kernel knows it:shop.fulfilment.start<E>(event: EventClass<E> | string, options: StartOptions): this: Starts a case when aneventcommits:keysays where the case's key is in the event (aggregateId, ordata.orderId; one case per key),datamaps the event to the case's first data. A process has one start; it goes to the first step written.command<C>(name: string, command: CommandClass<C> | string, options: CommandStepOptions): this: Sends acommandas the process, to the aggregateoptions.aggregatenames, withoptions.databuilt from the case. A rejection goes to the stepoptions.rejectednames for its code; any other rejection is an incident. Thenoptions.next, else the next step written.wait<E>(name: string, event: EventClass<E> | string, options: WaitOptions): this: Waits for aneventof this case (options.keysays where the case's key is in it) and mergesoptions.datafrom it into the case's data. Withtimeout, goes toonTimeoutif it does not come in time. Thenoptions.next, else the next step written.timer(name: string, when: TimerWhen, options: TimerOptions = {}): this: Waits for a time:{ after: "1d" }from when the case reached the step, or{ at: "case.dueAt" }(a reference to a time in ms since epoch). Thenoptions.next, else the next step written.decide(name: string, options: DecideOptions): this: Picks a path by the case's data:{ when: "case.total > 1000", then: "approval", otherwise: "paid" }, or several conditions in order,{ cases: [{ when, then }, …], otherwise }. Conditions are references to the case (case.<field>), literals,== != < <= > >=,and,or,notand parentheses; anything more is a query.query<Q>(name: string, query: QueryClass<Q> | string, options: QueryStepOptions): this: Asks a read model aquerywithoptions.databuilt from the case; the answer (or its fieldoptions.answer) picks the step inoptions.paths, elseoptions.otherwise.options.intokeeps the answer in the case's data.cancelOn<E>(event: EventClass<E> | string, options: CancelOnOptions): this: Ends a running case at once when aneventof its key commits, whatever step it is at:.cancelOn("AccountClosed", { key: "aggregateId", end: "closed" }). Its timer is withdrawn, an outcome it still awaits is ignored, an incident ends with it. Events the case's own commands cause do not count.endmust be anendstep.end(name: string): this: Ends the case. A process may have several ends, e.g.shippedandcancelled.model(): ProcessModel: The model the kernel registers (see "The model format"): types qualified, durations in ms, the order written resolved into explicitnexts. Checks what it can before the kernel does, and throws naming the process and the step: no start, no steps, a malformed or repeated step name, a target that names no step, a step other thanendwithout a successor, a malformed duration,timeoutwithoutonTimeoutor the other way round. Conditions and references are the kernel's to check.
durationMs()
export function durationMs(duration: string, fail: (reason: string) => never = (r) => { throw new Error(r); }): number
30s, 15m, 12h, 3d in ms; fail with the reason otherwise.
