Appearance
Python SDK
sh
pip install kernable-sdkPython ≥ 3.10; it brings grpcio, protobuf and cryptography. A kernel to connect to: kernable start --dev (see Getting started).
A cart aggregate, a read model that answers a query, and a client that submits and reads back, in one process:
python
import threading
from kernable import Kernable, Rejected, domain
shop_domain = domain("shop")
cart_aggregate = shop_domain.aggregate("cart", {"items": 0})
carts_readmodel = shop_domain.read_model("carts")
rows = {}
@cart_aggregate.apply("ItemAdded")
def _(state, data):
state["items"] += data["qty"]
@cart_aggregate.command("AddItem")
def _(state, data):
if data["qty"] < 1:
raise Rejected("qty must be at least 1")
return [{"type": "ItemAdded", "data": data}]
@carts_readmodel.on("ItemAdded")
def _(data, evt):
rows[evt.aggregate_id] = rows.get(evt.aggregate_id, 0) + data["qty"]
@carts_readmodel.query("GetCart")
def _(data):
return {"items": rows.get(data["id"], 0)}
k = Kernable(key="app.key")
app = k.app(service="shop", domains=[shop_domain])
threading.Thread(target=app.run, daemon=True).start()
app.ready.wait(10)
k.submit("shop", "cart", "c1", "AddItem", {"sku": "apple", "qty": 2})
print(k.query("shop", "GetCart", {"id": "c1"})) # {'items': 2}How the SDK works:
- Blocking calls. Every call blocks the calling thread; there is no
asyncio.run()of a worker, a listener or an app blocks untilstop(); run it in a thread (threading.Thread(target=x.run, daemon=True).start()) to do something else, and wait for the connection withx.ready.wait(seconds). - Decorators.
apply,command,on,query,middlewareandupcastregister a handler as a decorator (@cart_aggregate.command("AddItem")) or directly (cart_aggregate.command("AddItem", fn)). - Optional parameters. A handler takes only the parameters it needs, in order:
def _(state, data)ordef _(state, data, cmd, ctx). - Keyword arguments. Options after the required arguments are keyword-only where the signature has a
*:k.submit(..., wait="committed"),domain.read_model("carts", store="sqlite:carts.db"). - Errors. A rejected command returns an
Outcomewithcommitted=False; a rejected query raisesRejected; a request the kernel refuses raisesgrpc.RpcError(Errors).
The rest of this page is generated from the docstrings in sdks/python/kernable.
PROTOCOL
PROTOCOL = 1: The protocol version this SDK speaks; see "Protocol versions" in kernable.proto.
Event
What happened, in the past tense; see the module's docstring.
Command
What should happen, imperative; see the module's docstring.
Query
What is asked, with R its answer: class GetTenant(Query[TenantRow]). A query about one aggregate names it in target: the aggregate type (tenant, of the query's domain, or qualified: tenancy.tenant) and the field that holds the aggregate's ID. 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"): class GetTenant(Query[TenantRow]): target = {"aggregate_type": "tenancy.tenant", "field": "tenant_id"} tenant_id: str
target: ClassVar[dict | None]: The aggregate the query is about:{"aggregate_type": ..., "field": ...}; None if none.
StoredEvent
An event as stored by the kernel, as Outcome.events holds it.
position: int: Global position of the event in the kernel's log.tenant: strdomain: str: Always the domain of the command that caused the event.aggregate_type: straggregate_id: strversion: int: The aggregate's version after this event: 1 for its first event.type: str: The event type within the domain, e.g.ItemAdded.data: Any: The payload.command_id: str: The command that caused the event.request: RequestContext: The request context of the command that caused the event.schema: int: Version of the payload format, as stored (seeDomain.event).redacted: list[str]: Fields kept in the vault whose value is not here (None indata): erased, or not readable with this key (grantedvault_read).created_at: datetime: When the kernel committed the event (UTC).
Aggregate
An aggregate defined as a class: its fields are the state, and the class is registered as an aggregate of domain (its name: the class name in lowercase, or name). The state is a dataclass (no @dataclass); mutable defaults ([], {}) are copied for every aggregate, and snapshots hold its fields as JSON. Handlers get and change an instance: s.status = "active". class Cart(Aggregate, domain=shop_domain): items: int = 0 @Cart.apply(ItemAdded) def _(s: Cart, d: ItemAdded): s.items += d.count Cart.command, Cart.unique, Cart.fact, Cart.fold, Cart.handle and Cart.index work as on AggregateType (what domain.aggregate returns, which keeps working with a dict).
update(**values: Any) -> None: Sets several fields at once:s.update(status="active", slug=d.slug).apply(cls, event_type, fn: Callable | None=None)command(cls, command_type, fn: Callable | None=None, *, requires: Callable | None=None)unique(cls, name: str, fn: Callable | None=None, *, scope: str='tenant', personal: Callable | None=None)fact(cls, name: str, fn: Callable | None=None)fold(cls, history: list[tuple], state: Any=_INITIAL) -> Anyhandle(cls, state: Any, command_type: str, data: Any, ctx: 'CommandContext', *, aggregate_id: str='', tenant: str='') -> list[dict]index(cls, state: Any) -> 'Index'
AggregateType
How events change an aggregate's state (apply) and which events a command produces (command). Handlers must be deterministic and free of side effects; they may run again. Make it with Domain.aggregate. Both work as decorators (@agg.apply("Type")) or directly (agg.apply("Type", fn)). A command handler returns a list of {"type": ..., "data": ...} and refuses with raise Rejected(...). Handlers take only the parameters they need: def _(state, data) is enough, def _(state, data, cmd, ctx) gets the rest. Every snapshot_every events (0 turns it off) the worker sends a snapshot of the state, so later commands fold only the events after it. The state must survive a JSON round trip. Change schema when apply produces differently shaped state: older snapshots are then ignored and the state is rebuilt from the events. Uniqueness and conditions across aggregates: unique declares keys no other aggregate may hold at the same time (an email, an order number), fact what other aggregates' commands may require of this one (requires= of command). The kernel checks both atomically with the commit.
AggregateType(domain: str, name: str, initial: Any, snapshot_every: int=100, schema: str='1', events: dict[str, EventSchema] | None=None, commands: dict[str, CommandSchema] | None=None): UseDomain.aggregate, which passes the domain's event and command schemas.apply(event_type: str, fn: Callable | None=None): How an event ofevent_typechanges 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 the payload, upcast to the current version;evt(anEventMeta) andctx(anApplyContext) are optional. Works as a decorator too:@cart_aggregate.apply("ItemAdded")overdef _(state, data): state["items"] += data["qty"]. Returns the decorated function, or the aggregate whenfnis given. With an event class (@cart_aggregate.apply(ItemAdded)),datais an instance of it.command(command_type: str, fn: Callable | None=None, *, requires: Callable | None=None): Which events acommand_typecommand produces:fn(state, data, cmd, ctx)returns them as a list of{"type": ..., "data": ...}, or raisesRejected;cmd(aCommandMeta) andctx(aCommandContext) are optional.stateis the state after every earlier event; do not change it. Works as a decorator too:@cart_aggregate.command("AddItem")overdef _(state, data): return [{"type": "ItemAdded", "data": data}]. Returns the decorated function, or the aggregate whenfnis given.requires(data, state)returns the facts other aggregates of the command's tenant must hold when it commits, as a list ofRequirement(stateis the state before the command):requires=lambda data, state: [Requirement("funds", "vehicle", data["vehicleId"], "open")]. The kernel checks them atomically with the commit and rejects the command withrequirement_missingif one is not held, so no other command can change them in between. RaisesValueErrorfor a type that starts with_reindex_: aggregates with keys or facts run_reindex_<aggregate_type>themselves (seeunique), and one of another aggregate of the domain could clash.unique(name: str, fn: Callable | None=None, *, scope: str='tenant', personal: Callable | None=None): A unique key:fn(state)returns its value (astr), several values (a list ofstr), orNonefor none. After every command the aggregate holds exactly the values of its new state, and no two aggregates of this type hold the same value ofnameat the same time: a command that would take a value another one holds is rejected withunique_taken(the message names the key, never the value). Normalise the value infn(e.g..lower()for an email); the kernel compares its SHA-256 hash.scope:"tenant"(default) for unique within the command's tenant,"global"for across tenants.personal(state): the person the value belongs to, for personal data such as an email; the kernel keeps the key in the vault, and erasing that subject frees it. A personal key whose subject is empty orNoneis not held. Example:account_aggregate.unique("email", lambda s: s.get("email"), scope="global"). Works as a decorator too (@account_aggregate.unique("email")overdef _(state):) and returns the decorated function, or the aggregate whenfnis given, so it chains. Keys come from the state, so aggregates that existed before a key was declared hold it only after their next command:Kernable.reindexruns the built-in command_reindex_<aggregate_type>(reindex_type, e.g._reindex_account; no events) on them. Workers of an aggregate with keys or facts run it too, so their key needsrunfor<domain>._reindex_<aggregate_type>(<domain>.*covers it). An aggregate whose value another one already holds (a duplicate from before) is rejected withunique_takenuntil its value changes or becomesNone. RaisesValueErrorif the name is declared twice, is empty, holds a dot or is longer than 128 bytes, orscopeis neither of the two.fact(name: str, fn: Callable | None=None): A fact:fn(state)returns whether the aggregate holds it. After every command the aggregate holds the facts that are true for its new state, and commands of other aggregates may require them (requires=ofcommand), checked atomically with their commit (requirement_missingif not held). Example:vehicle_aggregate.fact("open", lambda s: s["status"] == "open"). Works as a decorator too and chains likeunique; aggregates that existed before a fact was declared hold it afterKernable.reindex. RaisesValueErrorif the name is declared twice, is empty, holds a dot or is longer than 128 bytes.index(state: Any) -> Index: The unique keys and facts this aggregate holds forstate, as the worker computes them after a command; for unit tests next tohandle:account_aggregate.index(state).keys. Raises the exception of a key's or fact's function,TypeErrorif a key's value is not a string.schema_of(event_type: str) -> int: The payload version this aggregate writesevent_typeevents at.fold(history: list[tuple], state: Any=_INITIAL) -> Any: State afterhistory, a list of tuples(type, schema, data), optionally followed by anEventMetaand anApplyContext, starting fromstate(default:initial). Events are upcast first; events without anapplyare skipped. For unit tests without a kernel:cart_aggregate.fold([("ItemAdded", 1, {"qty": 2})]). Raises the handler's exception, or an error if an event's schema is newer than this process knows.handle(state: Any, command_type: str, data: Any, ctx: CommandContext, *, aggregate_id: str='', tenant: str='') -> list[dict]: Runs thecommand_typehandler onstate, e.g. in a unit test, and returns its events.datareaches it as from a client (after a JSON round trip;Noneas{}),stateas a copy. The handler'sCommandMetahas the command ID ofctx(seeCommandContext.new), this aggregate's domain and name, and an empty aggregate ID and tenant:cart_aggregate.handle( state, "AddItem", {"qty": 2}, CommandContext.new("add-1")). Raises the handler'sRejected(or other exception),ValueErrorif there is no handler forcommand_type.
MiddlewareContext
What a middleware handler gets besides the check (an optional third parameter).
store: 'Store | None': The listener's store, if it has one.
App
An app made of whole domains, returned by kernable.app(...): run() applies its membership (manifest), then runs its worker and listeners until stop(); ready is set once all of them are connected. run() blocks the calling thread. To do something once the app is up (e.g. in a test), run it in a thread and wait: threading.Thread(target=app.run, daemon=True).start(), then app.ready.wait(5), which returns whether everything connected within 5 seconds. Call app.stop() from another thread or a handler to end run(). Attributes: manifest (a Manifest), worker (a Worker, or None without aggregates), listeners (a ListenerHandle per read model and reactor, live ones too), ready and processes (a RegisteredProcess per process of its domains, once registered). One service is one app: two processes with the same service would replace each other's membership.
App(k: Kernable, manifest: Manifest, worker: 'Worker | None', listeners: list['ListenerHandle'], domains: Iterable[str]=()): UseKernable.app.run() -> None: Applies the membership (seeKernable.apply), then runs the worker and the listeners, each in a thread of its own, untilstop(); blocks until then. A failing handler does not end it: a command handler's error rejects the command (handler_error), a listener handler's error makes the listener reconnect and get the event again. If a worker or listener itself fails, it stops the others and raises that error (a store that cannot be opened is tried again instead); Ctrl-C stops all of them too. Once all are connected, it prints an overview of the app (unlessKERNABLE_LOGis belowinfo). Raisesgrpc.RpcErrorif the kernel refuses the membership.stop() -> None: Stops the worker and all listeners;run()returns once they are done.
ApplyContext
What apply gets besides state, data and the event (as an optional fourth parameter). No clock and no IDs: apply must compute the same state on every replay.
request: RequestContext: The request context of the command that caused the event.
CacheClient
A domain's shared cache, kept in the kernel's memory under (tenant, domain, key): rate limits, short-lived tokens, computed values. Not durable: a kernel restart empties it. Values are not part of the signed event log and not erased with the vault. Needs a grant of cache for the domain; a refused or invalid request raises grpc.RpcError. Each request runs the middleware chain first, as <domain>.SetCache, .GetCache or .DeleteCache (the middleware sees the key and the request context, never the value); a middleware's refusal raises grpc.RpcError with code PERMISSION_DENIED and details "<code>: <message>". Keys are 1 to 512 bytes, values at most 1 MiB. Use it as k.cache: k.cache.set("shop", "rate:c1", "3", ttl_ms=60_000), then k.cache.get("shop", "rate:c1") returns b"3". tenant= replaces the client's tenant, context= the client's default request context.
CacheClient(k: Kernable): Usek.cacheof aKernable.set(domain: str, key: str, value: bytes | str, ttl_ms: int=0, *, tenant: str | None=None, context: RequestContext | None=None) -> None: Storesvalueunderkeyforttl_msmilliseconds;0keeps it until it is deleted or the kernel restarts. Astris stored as UTF-8.get(domain: str, key: str, *, tenant: str | None=None, context: RequestContext | None=None) -> bytes | None: The live value underkeyasbytes(decode astrwith.decode()), orNoneif there is none or it expired.delete(domain: str, key: str, *, tenant: str | None=None, context: RequestContext | None=None) -> bool: Deletes the value underkey; returns whether it had a live one.
CancelOutcome
What became of Kernable.cancel: cancelled, or rejected with a code and a message (too_late, not_found, or a middleware's code).
cancelled: bool: Whether the scheduled command was cancelled (or had been already): it completes as rejectedcancelled.code: str: The rejection code, if not cancelled.message: str: The rejection message, if not cancelled.
Check
A command, query, file or cache request a middleware checks, before the kernel accepts, routes or runs it (or, for commands and queries, after): the first parameter of a Listener.middleware handler.
kind: str:"command","query","data"(a file request ofk.data),"cache"(a cache request ofk.cache) or"cancel"(Kernable.cancelof a scheduled command:id,domain,type, the aggregate,targetanddataare the scheduled command's,requestthe cancel's sender; decide it as the command).id: str: The command or query ID; empty for a file or cache request.tenant: strdomain: strtype: str: The type within the domain: the command or query type, or for a file requestPutData,GetDataorDeleteData, for a cache requestSetCache,GetCacheorDeleteCache.data: Any: The request's payload; vault fields areNoneunless the key is grantedvault_read. AlwaysNonefor 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.aggregate_type: str: Commands only; empty otherwise.aggregate_id: str: Commands only; empty otherwise.key: str: File and cache requests only: the file or cache key; empty otherwise.target: 'Target | None': The aggregate the request is about: a command's aggregate (Target("shop.order", "o-17")), or the one a query declares (Query.target,QuerySchema.target). None for queries that declare none, and for file and cache requests.
ClientClosed
Raised by a request on a client after Kernable.close(). Workers and listeners of a closed client end their run().
ClientClosed()
CommandContext
What a command handler gets besides state, data and the command (as an optional fourth parameter).
request: RequestContext: Who sends the command: check permissions here.deadline: datetime: When the kernel hands the command to another worker if this one has not answered.received_at: datetime: When the kernel received the command (UTC);now()returns it.new(cls, command_id: str, request: RequestContext | None=None, received_at: datetime=_EPOCH) -> 'CommandContext': A context for calling a command handler directly, e.g. in a unit test withAggregate.handle:id()derives fromcommand_idas in a real command,now()returnsreceived_at(default: the epoch), and its deadline is 30 s after that.now() -> datetime: When the kernel received the command: the same every time the command runs. Use it instead ofdatetime.now().id() -> str: A new ID that is the same every time the command runs (1st call, 2nd call, ...). Use it instead of random IDs.
CommandMeta
What a command handler gets about the command besides state and data (as an optional third parameter).
command_id: str: The command's ID: given asidtosubmit, else a new UUID.type: str: The command type within the domain.domain: straggregate_type: straggregate_id: strtenant: str
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"], lambda d, id: id).secret(["password"]). Clients that submit these commands need the domain: k.use(shop_domain).
CommandSchema(type: str): UseDomain.command. RaisesValueErroriftypeis qualified.personal(fields: list[str], subject: Callable) -> 'CommandSchema': Keeps these top-level fields in the vault as personal data ofsubject; seeEventSchema.personal. Declare them on the events that carry them too: a worker rejects the command (personal_in_clear) if one of its events holds such a field, under the same name, without declaring it.secret(fields: list[str]) -> 'CommandSchema': 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: the aggregate it is about. Made with Domain.query; query classes declare it as target instead (see Query): shop_domain.query("GetOrder").target("order", "id") (GetOrder {"id": "o-17"} is about order o-17).
QuerySchema(type: str): UseDomain.query. RaisesValueErroriftypeis qualified.target(aggregate_type: str, field: str) -> 'QuerySchema': The query is about one aggregate ofaggregate_type(order, or qualifiedshop.order), whose ID is in the data'sfield(as sent:orderId). 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).
Target
The aggregate a request is about, as Check.target holds it.
type: str: Qualified:shop.order.id: str
Data
A file as stored by the kernel, returned by k.data.get.
data: bytescontent_type: str: The media type given when the file was put, e.g.image/png.sha256: str: The SHA-256 ofdata, hex, as the kernel computed it.
DataClient
Files of a domain, kept by the kernel under (tenant, domain, key): invoices, uploads, exports. They are not part of the signed event log and not erased with the vault; keep personal data in vault fields instead. Needs a grant of data_read (get) or data_write (put, delete) for the domain; a refused or invalid request raises grpc.RpcError. Each request runs the middleware chain first, as <domain>.PutData, .GetData or .DeleteData (the middleware sees the key and the request context, never the file); a middleware's refusal raises grpc.RpcError with code PERMISSION_DENIED and details "<code>: <message>". Keys are 1 to 512 bytes, files at most 16 MiB (the kernel's --max-data-bytes). Use it as k.data: k.data.put("shop", "invoices/c1.pdf", pdf_bytes, "application/pdf"). tenant= replaces the client's tenant, context= the client's default request context.
DataClient(k: Kernable): Usek.dataof aKernable.put(domain: str, key: str, data: bytes | str, content_type: str | None=None, *, tenant: str | None=None, context: RequestContext | None=None) -> str: Storesdataunderkey, replacing a file stored there. Astris stored as UTF-8;content_typedefaults totext/plain; charset=utf-8for astrandapplication/octet-streamforbytes. Returns the SHA-256 of the data (hex) as the kernel computed it: for an event to name.get(domain: str, key: str, *, tenant: str | None=None, context: RequestContext | None=None) -> Data | None: The file stored underkey, orNoneif there is none.list(domain: str, prefix: str='', *, after: str='', tenant: str | None=None, context: RequestContext | None=None) -> Listing: The files whose keys start withprefix(granteddata_read), in the order of their keys' bytes, up to 1,000 after the keyafter;nextof the result, if set, is theafterof the next page. To find files no event names, or what a tenant stores.delete(domain: str, key: str, *, tenant: str | None=None, context: RequestContext | None=None) -> bool: Deletes the file stored underkey; returns whether there was one.
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. Make it with domain("shop"). It remembers the aggregates, read models and reactors defined on it, so Kernable.app runs all of them.
Domain(name: str): Usedomain(name). RaisesValueErrorunlessnamestarts with a letter and holds only letters, digits,-and_.command(type: str) -> CommandSchema: Declares which fields oftypecommands the vault keeps (personal,secret); seeCommandSchema. Clients that submit them need the domain:kernable.use(domain).process(name: str) -> Process: Defines a business processnameof this domain (shop.fulfilmentforfulfilment): returns theProcessbuilder to chain its steps on (start,command,wait,timer,decide,query,end).Kernable.appregisters the domain's processes; seekernable.processesfor an example. RaisesValueErrorif the domain has a process of that name already.query(type: str) -> QuerySchema: Declares whattypequeries (unqualified) are about: returns theQuerySchemato chaintargeton. Query classes declare it astargetinstead. Clients that ask such queries by name need the domain:kernable.use(domain).event(type, schema: int | None=None, *more) -> EventSchema | None: Declares that this domain writestypeevents at versionschema(from 1), with anupcastper older version, and which of their fields the vault keeps; seeEventSchema. The domain's aggregates and listeners use it; listeners of other domains get it withListener.use(domain). Types not declared are at version 1. Example:shop_domain.event("ItemAdded", 2).upcast(1, lambda d: {**d, "qty": 1}). With event classes instead (shop_domain.event(ItemAdded, CartCleared)), declares them from their class attributes, e.g. in a process that only reads them; an aggregate'sapplydeclares them too.aggregate(name: str, initial: Any, snapshot_every: int=100, schema: str='1') -> 'AggregateType': An aggregate of this domain namedname(lowercase by convention, likecart), whose state starts asinitial(a JSON-like value, usually a dict); seeAggregateforsnapshot_everyandschema. Run it withkernable.worker(aggregate)or in an app. Example:cart_aggregate = shop_domain.aggregate("cart", {"items": 0}). RaisesValueErrorif the domain has an aggregate of that name already.read_model(name: str, *, order: int=0, start: int | None=0, reconnect_s: float=1.0, store: str | None=None, schema: str='1', live: bool=False, park_after: int=0, instance: str | None=None, single: bool=False) -> 'Listener': A read model of this domain namedname: builds a view from events and answers queries from it (on,query; seeListener). Kept in memory and rebuilt from the first event on every start (default). Run it withkernable.listener(read_model)or in an app. Example:carts_readmodel = shop_domain.read_model("carts").order(default 0): listeners with a lower order process each event first.start: the position to start after on the first connect (default 0, from the beginning;None: the kernel's stored position, or the newest event for a new listener).reconnect_s: seconds to wait before reconnecting after the stream drops (default 1), twice as long after each further failed attempt, at most 30. Withstore(sqlite:<path>ormemory:), its state lives in the running listener'sstore: data and position are written together per batch, and a restart continues after the stored position. Changeschemawhen the handlers store data differently: the store is cleared and the read model rebuilds from the first event.liveandpark_after(default 0: never; a read model that parks misses the event's change): seereactor.instance: runs this process's read model as one instance of a group under its name, e.g. one per node of a pair (1 to 128 letters, digits,-,_and.; defaultKERNABLE_INSTANCE, whichkernable nodesets; without either, the name has one connection). Every instance gets every event, from its own position, and answers queries; the group is through an event once one instance has handled it.single: seereactor. RaisesValueErrorif the domain has a listener (read model or reactor) of that name already.reactor(name: str, *, order: int=10, start: int | None=None, reconnect_s: float=1.0, store: str | None=None, schema: str='1', live: bool=False, park_after: int=_PARK_AFTER, instance: str | None=None, single: bool=True) -> 'Listener': A reactor of this domain namedname: triggers side effects and follow-up commands (on; seeListener). It starts at the newest event when it is new, then resumes after the last acknowledged event (start=None, default), so it never reacts to what happened before it existed. Run it withkernable.listener(reactor)or in an app. A settling submit from its handler waits for the listeners before it (the read models), not for the reactor itself, which handles one event at a time. Submit follow-ups withctx.submitand a fixedid, so a redelivered event does not run the command twice.order(default 10),start,reconnect_s,storeandschema: seeread_model.park_after(default 5): how often a handler may fail on one event before the reactor parks it and moves on (0: never, it 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 reactor waits and tries again. The kernel keeps parked events with the rejection's code and message (for other errorshandler_errorand the exception's type; the log has the whole error) until an operator retries or dismisses them (kernable listeners retry). 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.live: 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: seeread_model.single(defaultTruefor reactors): the instances take turns: one gets events, the others wait and the first of them takes over when it leaves, so a side effect happens once.False: every instance gets every event; such a listener cannot park events. Live listeners are never single. RaisesValueErrorif the domain has a listener of that name already.
Listed
A file as k.data.list names it.
key: strcontent_type: strsize: int: The file's length in bytes.
Listing
One page of k.data.list: up to 1,000 files, and next (to pass as after=) if there may be more.
files: list[Listed]next: str | None
EventMeta
What apply gets besides state and data (as an optional third parameter): the event without 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()) if the state needs one.
type: strversion: int: The aggregate's version after this event: 1 for its first event.tenant: strdomain: straggregate_type: straggregate_id: strcommand_id: str
EventSchema
The payload format of one event type: its current version and the steps that bring older payloads up to it. Events are stored as written and never changed; readers upcast them. Made with Domain.event; its methods return it, so they chain: shop_domain.event("CustomerRegistered", 1).personal(["email"], lambda d, id: id).
EventSchema(type: str, schema: int): UseDomain.event. RaisesValueErroriftypeis qualified orschemais below 1.personal(fields: list[str], subject: Callable) -> 'EventSchema': Keeps these top-level fields in the vault, as personal data of the subjectsubjectreturns from the payload and, optionally, the aggregate's ID (e.g.lambda d: d["customerId"], orlambda 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(subject: Callable) -> 'EventSchema': 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 read None.upcast(from_version: int, fn: Callable | None=None): Turns a payload of versionfrom_versioninto one of the next version:fn(data)returns the new payload. Works as a decorator too:@item_added.upcast(1)overdef _(data): return {**data, "qty": data.get("qty", 1)}. Declare one step per older version. RaisesValueErroriffrom_versionis not between 1 and the current version minus 1.
HeldKey
A unique key an aggregate holds for a state, as Aggregate.index returns it: the value in clear (the worker sends only its SHA-256 hash).
name: str: The name declared withAggregate.unique.value: strscope: str:"tenant"or"global"; seeAggregate.unique.subject: str: The person the value belongs to, for a personal key; empty otherwise.
Index
The unique keys and facts an aggregate holds for a state, returned by Aggregate.index.
keys: list[HeldKey]facts: list[str]: The names of the facts that are true, in the order they were declared.
Kernable
A connection to the kernel: submits commands (submit, enqueue), asks queries (query), runs workers, listeners and apps, and applies memberships. All calls block the calling thread; one client may be shared by threads. k.data (a DataClient) holds files of a domain, k.cache (a CacheClient) its shared cache. Kernable() without arguments takes everything from the environment or the defaults, which fit a kernel started with kernable start --dev in the current directory.
Kernable(url: str | None=None, key: str | None=None, tenant: str='default', tls: Tls | None=None, context: RequestContext | None=None, grant: str | None=None, service: str | None=None, insecure: bool | None=None, timeout_s: float=DEFAULT_TIMEOUT_S): A client for the kernel aturl, signing with the key in the filekey. It connects on first use and again after the connection drops.url: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. DefaultKERNABLE_URL, elsehttp://127.0.0.1:7233, wherekernable startlistens.key: path to this process's.keyfile; defaultKERNABLE_KEY, elseapp.keyin the current directory.tenant: default tenant of submits, queries, files and the cache (defaultdefault).tls: mutual TLS forhost:port; defaultKERNABLE_TLS_CA,KERNABLE_TLS_CERTandKERNABLE_TLS_KEY, if set (all three or none).context: default request context for submits, queries, files and the cache, e.g. this service's identity, replaced by a request's own.grant: path to the key's grant (kernable grant), sent with every call; defaultKERNABLE_GRANT, else the.grantfile next to the key file, if there is one.service: the service this process's workers and listeners belong to. The service's 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. DefaultKERNABLE_SERVICE, else none (everything registered counts).insecure: allows plain text to a kernel that is not on this machine; without TLS, grants, signed requests and vault values would cross the network readable, so such a URL raisesValueErrorunless this is set; defaultKERNABLE_INSECURE=1, else False.timeout_s: how long a request (submit, query, files, cache, apply) waits in all, for the connection (e.g. while the kernel restarts) and its answer; default 60 s. A connection the network dropped silently is noticed within 40 s by keepalive pings. Workers and listeners print connection lines to stderr up to the levelKERNABLE_LOGnames (off,error,warn,info(default),debug). RaisesOSErrorif the key or grant file cannot be read,ValueErrorif only some of the TLS variables are set.use(*domains: Domain) -> 'Kernable': Seals the vault fields of these domains' commands when submitting them (seeDomain.command), and sends the targets of their queries given by name (seeDomain.query). Returns this client, so it chains:k = Kernable().use(shop_domain).worker(*aggregates: 'AggregateType | type[Aggregate]') -> 'Worker': A worker that runs these aggregates' commands, in this client's service; seeWorker.run()on it blocks untilstop():k.worker(cart_aggregate).run().app(*, domains: Iterable[Domain], service: str | None=None, version: str | None=None, description: str | None=None, metadata: dict[str, str] | None=None) -> 'App': An app made of whole domains: every aggregate, read model and reactor defined on them.run()on it applies the service's membership (the domains' aggregates as workers, their read models and reactors as listeners, those with a middleware as middlewares, their processes; live listeners are not listed), then runs all of them, and registers the domains' processes once its worker is connected (seeregister_process).servicedefaults to this client's;versionanddescriptiongo into the membership's metadata, followed bymetadata. Example:k.app(service="shop", version="1.0.0", domains=[shop_domain]).run(). Every start applies the membership, so the key needs themanagegrant for the service. One service is one app: two processes with the same service would replace each other's membership. RaisesValueErrorif neitherservicenor the client names a service.apply(*, service: str | None=None, workers: Iterable[AggregateType]=(), listeners: Iterable['Listener']=(), middlewares: Iterable['Listener']=(), metadata: dict[str, str] | None=None, processes: Iterable['Process | str']=()) -> None: Replaces the membership of a service (default: this client'sservice): the workers, listeners and middlewares the kernel waits for, plus free metadata such as{"version": "1.0.0"}.workersare the aggregates the service runs (the kernel waits for a worker of each),listenersthe listeners it waits for (the service's others count for nobody),middlewaresthe service's listeners that may check requests (they count like listeners),processesits business processes (Processes or qualified names): one it no longer lists starts no new cases, its running cases finish. Apply it once per deploy, e.g. from a deploy script, not from every process: the newest apply wins, and an older one that arrives late is refused. The key needs themanagegrant for the service. A middleware the new membership no longer lists stops checking. Example:k.apply(service="shop", workers=[cart_aggregate], listeners=[carts_readmodel], metadata={"version": "1.0.0"}). RaisesValueErrorwithout a service,grpc.RpcErrorif the kernel refuses it.process_act(name: str, context: RequestContext) -> bool: Sets as whom the processname(qualified:shop.fulfilment) acts: the request context its commands and queries carry (sender tenant, identity, session), signed with this client's key, which needs the grantprocessfor it. Without it, a process acts asprocess:<name>. Returns whether it changed (False: it acted so already). The kit's identity reactor calls it for every process it gives an identity. Raisesgrpc.RpcErrorif the kernel refuses it (NOT_FOUNDfor a process never registered).register_process(process: 'Process | dict') -> RegisteredProcess: Registers a business process (aProcess, or its model as a dict), signed with this client's key: a model equal to the newest version registers nothing (newis False), a different one becomes the next version; running cases stay on theirs.Kernable.appdoes this for its domains' processes. The key needs the grantprocessfor the process, andsubmit,queryandlistenfor the commands, queries and events the model names. RaisesValueErrorif the builder finds the model invalid (seeProcess.model),grpc.RpcErrorif the kernel refuses it (INVALID_ARGUMENTnames the step and why).submit(domain, aggregate_type: str | None=None, aggregate_id: str | None=None, type: str | None=None, data: Any=None, *, tenant: str | None=None, id: str | None=None, wait: str='settled', context: RequestContext | None=None, timeout_s: float | None=None, at: Any=None) -> Outcome: Runs atypecommand ofdomainon the aggregateaggregate_typewith IDaggregate_idand returns itsOutcome.datais the command's payload (JSON-like;Nonesends{}).wait="settled"(default) responds once every listener that counts has processed the events, so read models already show them, and raisesNotSettledon timeout; from a listener's handler, only the listeners with a lower order count.wait="committed"responds once the events are stored; then query withmin_position.idis an idempotency key (default: a new UUID): submitting the sameidagain returns the original outcome.tenantreplaces the client's tenant.contextreplaces the client's default context; inside a listener, passctx.follow().timeout_sreplaces the client's deadline for this call. A rejected command returnsOutcome(committed=False, code=..., message=...); it does not raise. Raisesgrpc.RpcErrorif the kernel refuses the call (no grant, unknown aggregate type, timeout). Example:k.submit("shop", "cart", "c1", "AddItem", {"sku": "apple", "qty": 2}). With a command class instance:k.submit(AddItem(sku="apple", qty=2), aggregate_id="c1"); its class says the domain, aggregate type, type and vault fields (nouseneeded). A scheduled command has no outcome yet: schedule it withenqueue(..., at=...)(athere raisesValueError). Submitting itsidagain waits for its outcome, so ask once it is due; until then the kernel holds the call.enqueue(domain, aggregate_type: str | None=None, aggregate_id: str | None=None, type: str | None=None, data: Any=None, *, tenant: str | None=None, id: str | None=None, context: RequestContext | None=None, timeout_s: float | None=None, at: 'datetime | int | None'=None, until: 'datetime | int | None'=None) -> str: Stores the command in the kernel's queue and returns its ID without waiting for it to run (wait="accepted"). Submit it again with the sameidto get the outcome. The parameters are those ofsubmit. Withat(adatetime, or ms since epoch), a scheduled command: it runs at that time and not before, e.g. a reminder in 24 hours,k.enqueue(Remind(), aggregate_id="o1", at=datetime.now(timezone.utc) + timedelta(days=1)). The kernel stores it at once; the aggregate's other commands pass meanwhile, and middlewares check it now and again when it is due.until: if it cannot run by then (after an outage), it is rejectedexpired. Both are signed with the command. Cancel it withcancel.cancel(command_id: str, *, tenant: str | None=None, context: RequestContext | None=None, timeout_s: float | None=None) -> CancelOutcome: Cancels a scheduled command (enqueuewithat) before it is due: it completes as rejectedcancelled, and cancelling it again answers the same. Needssubmitfor the command's type; middlewares check it as a cancel of that type (Check.kind == "cancel"). Returns aCancelOutcome: not cancelled withtoo_late(due, running or done already),not_found, or a middleware's code.tenantandcontextreplace the client's;timeout_sits deadline for this call. Example:k.cancel(reminder_id).query(domain, type: str | None=None, data: Any=None, *, tenant: str | None=None, context: RequestContext | None=None, min_position: int=0, timeout_s: float | None=None, all_partitions: bool=False) -> Any: Asks the read model that answersdomain.typewithdataand returns its answer, decoded from JSON. Queries always go through the kernel, also within one process.min_position: answer only after the read model has processed this global position (e.g. of an event from await="committed"submit).tenantandcontextreplace the client's;timeout_sits deadline for this call.all_partitions, 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 (a wait-only query to each partition first). RaisesRejectedif the read model or a middleware rejects it,grpc.RpcErrorif the kernel refuses the call (e.g.UNAVAILABLEwhen no read model answers it). Example:cart = k.query("shop", "GetCart", {"id": "c1"}).reindex(domain: str, aggregate_type: str, aggregate_ids: Iterable[str], *, tenant: str | None=None, context: RequestContext | None=None) -> dict[str, Outcome]: Runs the built-in command_reindex_<aggregate_type>on these aggregates, one after the other, so they hold the unique keys and facts of their current state, e.g. after declaring a key (Aggregate.unique) for aggregates that existed before. It produces no events. Returns theOutcomeper ID: committed, or rejected, e.g. withunique_takenfor an aggregate whose value another one holds already. An ID without events holds nothing.tenantandcontextreplace the client's. Raisesgrpc.RpcErrorif the kernel refuses a call (e.g. the aggregate's worker declares no keys or facts). Example:k.reindex("identity", "account", ["a1", "a2"]).listener(listener: 'Listener') -> 'ListenerHandle': A handle that runs a listener defined withDomain.read_modelorDomain.reactor, in this client's service; seeListenerHandle.run()on it blocks untilstop():k.listener(carts_readmodel).run(). Each call gives a new handle.close() -> None: Closes the connection now; only needed in a long-running process that discards the client. Requests afterwards raiseClientClosed, and its workers and listeners end.
Key
An Ed25519 key; its ID (id) is the hex-encoded public key. Kernable reads its own from the .key file (kernable keys new); you rarely need this class directly.
Key(seed_hex: str): The key with this hex-encoded 32-byte seed, the content of a.keyfile.from_file(path: str) -> 'Key': The key in the.keyfile atpath.sign(message: bytes) -> pb.Signature: Signsmessage(the signed bytes of a request, see Signatures) with this key.
Listener
A listener definition: a durable, named event listener of a domain, made with Domain.read_model or Domain.reactor and run with kernable.listener(listener), which returns a ListenerHandle. 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 raises, the listener reconnects and the event is delivered again, until a reactor gives up on it and parks it (park_after of Domain.reactor). Type names without a domain (ItemAdded, GetCart) are the listener's own domain's; types of other domains are qualified (identity.AccountRegistered, identity.*). Handlers get event payloads upcast to the versions of the listener's 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. on, query and middleware work as decorators (@carts_readmodel.on("ItemAdded")) or directly (carts_readmodel.on("ItemAdded", fn)); handlers take only the parameters they need. They run in the thread of the listener's run(), one at a time, so plain dicts are safe to use as state there; guard state that other threads also touch.
Listener(domain: Domain, name: str, order: int, start: int | None, reconnect_s: float, store: str | None=None, schema: str='1', *, live: bool=False, park_after: int=0, instance: str | None=None, single: bool=False): UseDomain.read_modelorDomain.reactor.use(*domains: Domain) -> 'Listener': Upcasts the events of these other domains with their event schemas (seeDomain.event); the listener's own domain's apply already. Returns the listener, so it chains:shop_domain.read_model("orders").use(billing_domain).on(event_type: str, fn: Callable | None=None, *, raw: bool=False): Registers a handler for an event type (ItemAdded, ororders.OrderPlacedof another domain) or a whole domain (orders.*); works as a decorator too:fn(data, evt, ctx)gets the event's payload, aStoredEventMetaand aListenerContext(both optional). Arawhandler gets payloads as stored, without upcasting, whatever their schema (for archives and exports). Example:@carts_readmodel.on("ItemAdded")overdef _(data, evt): rows[evt.aggregate_id] = data["qty"]. If the handler raises, the listener reconnects and the event is delivered again, so handlers must be idempotent. RaisesValueErrorifevent_typeis none of these.query(query_type: str, fn: Callable | None=None): Answers a query type (GetCart, ororders.GetOrderof another domain) from this listener's state; works as a decorator too:fn(data, qry, ctx)gets the query's data, aQueryMetaand aQueryContext(both optional). The kernel delivers queries in order with the events, so an answer reflects every event handled before it. Return the answer (JSON-like;Nonereaches the caller asNone); raiseRejectedto refuse (any other exception refuses withhandler_error). A handler cannot query its own listener (the answer would wait behind itself): the kernel refuses it. Example:@carts_readmodel.query("GetCart")overdef _(data): return rows[data["id"]]. RaisesValueErrorifquery_typeis invalid.middleware(types: list[str], order: int=0, fn: Callable | None=None, *, when: str='before'): Makes this listener a middleware; works as a decorator too. The kernel asksfnabout every command and query oftypes(*for all,Typeof the own domain,domain.*ordomain.Type) before accepting or routing it (or after, seewhen), in chain order (lowerorderfirst, then by listener name), and only once this listener has caught up with the events.fn(check, outcome, ctx)gets aCheck, after the request what came of it, and aMiddlewareContextwith the listener's store (both optional): anOutcomefor a command, aQueryOutcomefor a query (check.kindtells which); before, None.typescover file and cache requests too, before they run:domain.PutData,.GetData,.DeleteData,.SetCache,.GetCacheand.DeleteCache(anddomain.*or*include them);check.kindis then"data"or"cache",check.keythe key andcheck.dataNone, and a refusal reaches the client asPERMISSION_DENIED. Return False or raiseRejectedto refuse; any other error refuses too, and so does a return value other than None, True or False. The registration is stored: while this listener is away, the kernel refuses those requests (kernable listeners removeunregisters it).fncannot 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.when: "before" (default) checks a request before the kernel accepts it; raising refuses it. "after" gets the request's outcome too: raising 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). Negative orders are reserved for kernable's kits (a grant ofreserved_order). A live listener cannot be a middleware. Example:@guard_readmodel.middleware(["shop.*"])over adef _(check):that raisesRejected("not allowed", "forbidden")unlesscheck.request.sender_identitymay sendcheck.type. RaisesValueErrorfor an invalid type orwhen, a second middleware at the samewhen, or a live listener.
ListenerContext
What a listener handler gets besides the event's data and meta (as an optional third parameter).
replaying: bool: The event was committed before this connection began: a read model rebuilding from the start, and equally the backlog a reactor catches up on after a restart or a lost connection. A reactor must not skip side effects because of it (those events are new to it); submitting with fixed command IDs makes them safe to repeat instead. Use it to skip work that only matters live, e.g. a notification about something long past, in a listener that starts at 0.request: RequestContext: The request context of the command that caused the event.store: 'Store | None': The listener's store, if it has one (store=ofDomain.read_modelandDomain.reactor).submit(aggregate_type, aggregate_id: str | None=None, type: str | None=None, data: Any=None, *, id: str, domain: str | None=None, tenant: str | None=None, context: 'RequestContext | None'=None, wait: str='settled', timeout_s: float | None=None) -> 'list': Submits a command this event causes, on the listener's client, and returns its events. It needs a fixedid(f"confirm-{evt.aggregate_id}"), so a redelivered event runs it once.domaindefaults to the listener's,contexttofollow(),tenantto the event's; the rest as forKernable.submit. RaisesRejected(with the kernel'skeyorrequirement, if any) if the command is rejected: a reactor then parks the event at once (seepark_afterofDomain.reactor); catch it to accept a rejection. Raises likeKernable.submitotherwise. Example:ctx.submit("order", evt.aggregate_id, "Confirm", id=f"confirm-{evt.aggregate_id}").query(type, data: Any=None, *, tenant: str | None=None, context: 'RequestContext | None'=None, min_position: int=0, timeout_s: float | None=None, all_partitions: bool=False) -> Any: Asks a query on the listener's client, likeKernable.query:typeis of the listener's domain (GetOrder) or qualified (crm.GetCustomer).tenantdefaults to the event's. It is the listener's own read: it keeps the client's context, not the event's sender.process_act(name: str, context: RequestContext) -> bool: Sets as whom the processnameacts, with the listener's client; seeKernable.process_act. Returns whether it changed.follow() -> RequestContext: A request context for commands caused by this event: same sender and correlation.
ListenerHandle
A running Listener, returned by kernable.listener(listener): run() processes events, queries and checks until stop(); ready is set once the kernel accepted it. run() blocks the calling thread. To run several listeners in one process, run all but one in threads (threading.Thread(target=handle.run, daemon=True).start()), or use Kernable.app. ready is a threading.Event: handle.ready.wait(5) returns whether the kernel accepted the listener within 5 seconds. stop() ends run(), also from another thread. Attributes: listener (the definition), position (global position of the last handled event, or skipped, for other event types) and store (the listener's Store, while run() has it open).
ListenerHandle(channel: 'grpc.Channel | _Partitioned', key: Key, listener: Listener, log: _Log, service: str='', kernable: 'Kernable | None'=None, part: str='', store: 'Store | None'=None, parent: 'ListenerHandle | None'=None): UseKernable.listener.partandstore: a partition's stream, sharing the store of the handle that runs it.run() -> None: Processes events, queries and checks untilstop(), reconnecting when the stream drops; with a store, opens it first and continues after its position, and closes it whenrun()ends. A store that cannot be opened (a full disk) is tried again, backing off like a reconnect. With partitions, a stream per partition, each from its own position in the shared store.
Manifest
What a service consists of, as Kernable.apply takes it: the membership an app applies (app.manifest, see Kernable.app).
service: str: The service the membership is for.workers: list[AggregateType]: The aggregates the service runs; the kernel waits for a worker of each.listeners: list['Listener']: The listeners the kernel waits for.middlewares: list['Listener']: The service's listeners that may check requests; they count like listeners.metadata: dict[str, str]: Free metadata, e.g.{"version": "1.0.0"}.processes: list[Process]: The service's business processes;Kernable.appregisters them.
NotSettled
Raised by a settling Kernable.submit (the default wait="settled"): the command was committed, but not every listener that counts processed its events within the kernel's --settle-timeout-ms. Read models may not show the change yet; outcome (an Outcome) has the committed events, e.g. except NotSettled as err: events = err.outcome.events. Submitting again with the same id returns the same outcome, without running the command again.
NotSettled(outcome: Outcome)
Outcome
What became of a command, returned by Kernable.submit: committed with its events, or rejected with a code and a message. Example: Outcome(committed=False, events=[], code='rejected', message='Cart is checked out').
committed: bool: Whether the command's events were stored;Falseif it was rejected.events: list[StoredEvent]: The committed events, in order; empty if the command was rejected. Vault fields in them areNone(seeStoredEvent.redacted).code: str: The rejection code (seeRejected), if rejected.message: str: The rejection message, if rejected.key: str: Forunique_taken: the name of the key another aggregate holds (never its value). Set by the kernel only, and stored with the rejection.requirement: 'Requirement | None': Forrequirement_missing: the first requirement that does not hold. Set by the kernel only.
Process
A business process of a domain, built step by step: made with Domain.process(name); each method adds a step and returns the process, so they chain. See the module's docstring for an example. model() builds the model the kernel registers, checking what it can.
Process(domain: str, name: str): UseDomain.process. RaisesValueErrorifnameis invalid.qualified() -> str:<domain>.<name>:shop.fulfilment.start(event: type[Event] | str, *, key: str, data: dict | None=None) -> 'Process': Starts a case wheneventcommits.keyis where the case's key is in the event (aggregate_id, ordata.<field>): one case per key.datamaps case fields to references into the event ({"order_id": "aggregate_id", "total": "data.total"}) orvalue(...).command(name: str, command: type[Command] | str, *, aggregate: str, data: dict | None=None, rejected: dict[str, str] | None=None, next: str | None=None) -> 'Process': Sendscommandas the process to the aggregate whose IDaggregatenames (case.order_id), withdatafrom the case (field → reference orvalue(...)).rejectedmaps rejection codes to the steps that handle them; any other rejection raises an incident. Thennext, or the step written after it.wait(name: str, event: type[Event] | str, *, key: str, data: dict | None=None, timeout: str | int | None=None, on_timeout: str | None=None, next: str | None=None) -> 'Process': Waits for aneventof this case: the one whosekey(aggregate_idordata.<field>) is the case's key.datamerges fields of the event into the case's data. Withtimeout(3d), the case moves toon_timeoutif the event does not come in time. Thennext, or the step written after it.timer(name: str, *, after: str | int | None=None, at: str | None=None, next: str | None=None) -> 'Process': Waitsaftera duration (12h), or until the time (ms) a reference names (at:case.due_at). Thennext, or the step written after it.decide(name: str, *, when: str | None=None, then: str | None=None, cases: list | None=None, otherwise: str | None=None) -> 'Process': Picks a path by the case's data:when("case.total > 1000") goes tothen, orcases=[("case.total > 1000", "approval"), ...](or dicts withwhenandthen), the first that holds; elseotherwise, or the step written after it.query(name: str, query: type[Query] | str, *, data: dict | None=None, answer: str | None=None, paths: dict, into: str | None=None, otherwise: str | None=None) -> 'Process': Asks a read modelquerywithdatafrom the case; its answer picks the path:pathsmaps answers ({True: "approved", False: "paid"}, or strings and numbers) to steps, matched against the answer itself or, for an object, its fieldanswer.intokeeps the answer in the case's data under that field. An answer no path names goes tootherwise(without it: an incident).end(name: str) -> 'Process': Ends the case.cancel_on(event: type[Event] | str, *, key: str, end: str) -> 'Process': Ends a running case at once when aneventof its key commits, whatever step it is at:.cancel_on(AccountClosed, key="aggregate_id", 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.model() -> dict: The model the kernel registers (design/processes.md "The model format"): types qualified, references with wire names, durations in ms, and an explicitnexton every step butend. RaisesValueErrornaming the process and step for what can be checked here: no start, duplicate or invalid step names, a step without successor, a target that names no step, malformed references and durations. The kernel checks the rest.
QueryContext
What a query handler gets besides the query's data and meta (as an optional third parameter).
request: RequestContext: Who asks: check permissions here.store: 'Store | None': The listener's store, if it has one (store=ofDomain.read_modelandDomain.reactor).
QueryMeta
What a query handler gets about the query besides its data (as an optional second parameter).
query_id: strtype: str: The query type within the domain.domain: strtenant: str
QueryOutcome
What came of a query, as a middleware that runs after requests (when="after") gets it: its response data or why it was rejected.
answered: bool: Whether the read model answered;Falseif the query was rejected.data: Any: The answer, if answered.code: str: The rejection code, if rejected.message: str: The rejection message, if rejected.
RegisteredProcess
What became of Kernable.register_process: the process's version.
name: str: Qualified:shop.fulfilment.version: int: From 1; the newest version, whether registered now or before.new: bool: False if the model equals the newest version: nothing was registered.
Rejected
A business reason to refuse a command or query: raise it from a command handler, a query handler or a middleware, e.g. raise Rejected("Cart is checked out", "checked_out"). code (default rejected) is what callers act on, the message (str(err)) what they show. Kernable.query raises it when the read model or a middleware refuses the query; a rejected command does not raise: Kernable.submit returns an Outcome with committed=False. Any other exception from a command or query handler rejects too, with the code handler_error (middleware_error from a middleware).
Rejected(message: str, code: str='rejected')
RequestContext
Who sends a request and in which context: signed with the command and stored with every event it causes. attributes are business data only, never security decisions. Set a default for a client with Kernable(context=...), or one per request with context= of submit, enqueue and query. Inside a listener's handler, submit follow-up commands with ctx.follow(). Example: RequestContext(sender_identity="customer-7", expected_version=3).
sender_tenant: str: The tenant the sender belongs to.sender_identity: str: Who sends the request, e.g. a user or service ID; middlewares check permissions on it.sender_account: strsender_session: stron_behalf_of: str: Authorize as this identity of the target tenant; the sender stays the real principal.expected_version: int | None: Reject the command (version_mismatch) unless the aggregate is at this version.correlation_id: str: Shared by everything one original request causes; defaults to the command ID.causation_id: str: The command that caused this one.trace_id: strbypass_authorization: bool: Privileged: only keys grantedprivilegedfor it may set it.attributes: dict[str, str]
Requirement
A fact another aggregate of the command's tenant must hold (or, absent, must not hold) when the command commits, as requires= of Aggregate.command returns them: Requirement("funds", "vehicle", data["vehicleId"], "open"). 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 (Requirement.by_key, not a personal key), which the kernel resolves at commit: no aggregate holds the key, none holds the fact; an aggregate without events holds none either. An empty domain is the command's own (Requirement.of).
domain: str: Empty: the domain of the command's aggregate.aggregate_type: str: Unqualified, e.g.vehicle.aggregate_id: str: Empty when the aggregate is named bykey.fact: str: A fact the aggregate declares withAggregate.fact.key: str: A unique key of the aggregate type that names the aggregate instead of its ID.value: str: The key's value, normalised as the aggregate type's key function does: the kernel gets only its SHA-256. Empty in a rejection, which never carries the value.absent: bool: The aggregate must not hold the fact.of(cls, aggregate_type: str, aggregate_id: str, fact: str, *, absent: bool=False) -> 'Requirement': A requirement of an aggregate type of the command's own domain:Requirement.of("vehicle", data["vehicleId"], "woundUp", absent=True).by_key(cls, aggregate_type: str, key: str, value: str, fact: str, *, domain: str='', absent: bool=False) -> 'Requirement': The fact of the aggregate that holds the unique keykeywithvalue, normalised as its key function does:Requirement.by_key("vehicle", "isin", data["vehicle"], "open").
Store
A listener's store: JSON values under keys, grouped in namespaces (ns), in a SQLite file or in memory. Give a read model or reactor one with store="sqlite:carts.db"; its handlers then get it as ctx.store (ListenerContext, QueryContext), e.g. ctx.store.set("carts", evt.aggregate_id, row) and ctx.store.get("carts", data["id"]). What an event handler writes takes effect together with the listener's position, once per batch. Thread-safe.
Store(url: str, schema: str): 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(ns: str, key: str, default: Any=None) -> Any: The value underkeyin namespacens, decoded from JSON, ordefaultif there is none.set(ns: str, key: str, value: Any) -> None: Storesvalue(anythingjson.dumpstakes) underkeyin namespacens, replacing a value there.remove(ns: str, key: str) -> None: Removes the value underkeyin namespacens, if there is one.all(ns: str) -> list[tuple[str, Any]]: Every key and value of a namespace, ordered by key.reset(ns: str | None=None) -> None: Clears a namespace, or all data.committed_for(part: str) -> int: The position up to which the data is complete for the events of partitionpart: every partition has its own positions."": a kernel without partitions.close() -> None: Closes the database, truncating its WAL first; the store cannot be used afterwards. A listener closes its store when itsrun()ends; closing it again does nothing.
StoredEventMeta
What a listener handler gets about the event besides its data (as an optional second parameter): the stored event without its payload and request context. It has every field of EventMeta (type, version, tenant, domain, aggregate_type, aggregate_id, command_id), and these. Unlike EventMeta, it says when the event was committed: a read model may show that time, apply may not depend on it.
position: int: Global position of the event in the kernel's log.schema: int: Version of the payload format: the version the listener knows (seeDomain.event), or the stored one for arawhandler.redacted: list[str]: Fields kept in the vault whose value is not in the data (None there): erased, or not readable with this key (grantedvault_read).created_at: datetime: When the kernel committed the event (UTC).
Tls
Paths of PEM files for mutual TLS with a kernel at host:port: the CA that signed the kernel's certificate, and this process's own certificate and key. Pass it as Kernable(tls=Tls(ca="ca.pem", cert="app.pem", key="app-key.pem")), or set KERNABLE_TLS_CA, KERNABLE_TLS_CERT and KERNABLE_TLS_KEY.
ca: strcert: strkey: str
Worker
Runs the commands of its aggregates, one at a time: the kernel sends each command with the aggregate's events (or a snapshot and the events after it), the worker folds the state, calls the command handler and sends the new events back, signed. Made with Kernable.worker. run() processes commands until stop(), reconnecting when the session drops (after 1 s); it blocks the calling thread. ready (a threading.Event) is set once the kernel registered the worker: run it in a thread and wait with worker.ready.wait(5), e.g. threading.Thread(target=worker.run, daemon=True).start(). stop() ends run(), also from another thread.
Worker(channel: 'grpc.Channel | _Partitioned', key: Key, aggregates, log: _Log, service: str=''): UseKernable.worker.run() -> None: Processes commands untilstop(), reconnecting when the session drops; with partitions, a session per partition.
Value
A literal in a mapping, made with value(...): {"value": ...} in the model.
value: Any
domain()
domain(name: str) -> Domain
A domain named name, on which you define its aggregates, read models, reactors and event and command schemas: shop_domain = domain("shop"). Raises ValueError unless name starts with a letter and holds only letters, digits, - and _.
reindex_type()
reindex_type(aggregate_type: str) -> str
The type of the built-in command an aggregate with unique keys or facts runs without events, _reindex_<aggregate_type> (see Aggregate.unique and Kernable.reindex): one per aggregate, as command types are unique within a domain. reindex_type("fund") is "_reindex_fund".
value()
value(x: Any) -> Value
A literal (JSON-like) where a mapping takes a reference: data={"reason": value("unpaid")}.
