Previewkernable is not released yet: these docs describe work in progress, and things may change before 1.0.Not released yet.Request early access →
Skip to content

Python SDK ​

sh
pip install kernable-sdk

Python ≥ 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 until stop(); run it in a thread (threading.Thread(target=x.run, daemon=True).start()) to do something else, and wait for the connection with x.ready.wait(seconds).
  • Decorators. apply, command, on, query, middleware and upcast register 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) or def _(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 Outcome with committed=False; a rejected query raises Rejected; a request the kernel refuses raises grpc.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: str
  • domain: str: Always the domain of the command that caused the event.
  • aggregate_type: str
  • aggregate_id: str
  • version: 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 (see Domain.event).
  • redacted: list[str]: Fields kept in the vault whose value is not here (None in data): erased, or not readable with this key (granted vault_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) -> Any
  • handle(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): Use Domain.aggregate, which passes the domain's event and command schemas.
  • apply(event_type: str, fn: Callable | None=None): How an event of event_type changes the state: fn(state, data, evt, ctx) changes state in place and returns nothing, or returns a new state that replaces it. state is a copy, so changing it never touches the state it came from; data is the payload, upcast to the current version; evt (an EventMeta) and ctx (an ApplyContext) are optional. Works as a decorator too: @cart_aggregate.apply("ItemAdded") over def _(state, data): state["items"] += data["qty"]. Returns the decorated function, or the aggregate when fn is given. With an event class (@cart_aggregate.apply(ItemAdded)), data is an instance of it.
  • command(command_type: str, fn: Callable | None=None, *, requires: Callable | None=None): Which events a command_type command produces: fn(state, data, cmd, ctx) returns them as a list of {"type": ..., "data": ...}, or raises Rejected; cmd (a CommandMeta) and ctx (a CommandContext) are optional. state is the state after every earlier event; do not change it. Works as a decorator too: @cart_aggregate.command("AddItem") over def _(state, data): return [{"type": "ItemAdded", "data": data}]. Returns the decorated function, or the aggregate when fn is given. requires(data, state) returns the facts other aggregates of the command's tenant must hold when it commits, as a list of Requirement (state is 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 with requirement_missing if one is not held, so no other command can change them in between. Raises ValueError for a type that starts with _reindex_: aggregates with keys or facts run _reindex_<aggregate_type> themselves (see unique), 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 (a str), several values (a list of str), or None for 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 of name at the same time: a command that would take a value another one holds is rejected with unique_taken (the message names the key, never the value). Normalise the value in fn (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 or None is not held. Example: account_aggregate.unique("email", lambda s: s.get("email"), scope="global"). Works as a decorator too (@account_aggregate.unique("email") over def _(state):) and returns the decorated function, or the aggregate when fn is 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.reindex runs 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 needs run for <domain>._reindex_<aggregate_type> (<domain>.* covers it). An aggregate whose value another one already holds (a duplicate from before) is rejected with unique_taken until its value changes or becomes None. Raises ValueError if the name is declared twice, is empty, holds a dot or is longer than 128 bytes, or scope is 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= of command), checked atomically with their commit (requirement_missing if not held). Example: vehicle_aggregate.fact("open", lambda s: s["status"] == "open"). Works as a decorator too and chains like unique; aggregates that existed before a fact was declared hold it after Kernable.reindex. Raises ValueError if 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 for state, as the worker computes them after a command; for unit tests next to handle: account_aggregate.index(state).keys. Raises the exception of a key's or fact's function, TypeError if a key's value is not a string.
  • schema_of(event_type: str) -> int: The payload version this aggregate writes event_type events at.
  • fold(history: list[tuple], state: Any=_INITIAL) -> Any: State after history, a list of tuples (type, schema, data), optionally followed by an EventMeta and an ApplyContext, starting from state (default: initial). Events are upcast first; events without an apply are 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 the command_type handler on state, e.g. in a unit test, and returns its events. data reaches it as from a client (after a JSON round trip; None as {}), state as a copy. The handler's CommandMeta has the command ID of ctx (see CommandContext.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's Rejected (or other exception), ValueError if there is no handler for command_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]=()): Use Kernable.app.
  • run() -> None: Applies the membership (see Kernable.apply), then runs the worker and the listeners, each in a thread of its own, until stop(); 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 (unless KERNABLE_LOG is below info). Raises grpc.RpcError if 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): Use k.cache of a Kernable.
  • set(domain: str, key: str, value: bytes | str, ttl_ms: int=0, *, tenant: str | None=None, context: RequestContext | None=None) -> None: Stores value under key for ttl_ms milliseconds; 0 keeps it until it is deleted or the kernel restarts. A str is stored as UTF-8.
  • get(domain: str, key: str, *, tenant: str | None=None, context: RequestContext | None=None) -> bytes | None: The live value under key as bytes (decode a str with .decode()), or None if there is none or it expired.
  • delete(domain: str, key: str, *, tenant: str | None=None, context: RequestContext | None=None) -> bool: Deletes the value under key; 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 rejected cancelled.
  • 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 of k.data), "cache" (a cache request of k.cache) or "cancel" (Kernable.cancel of a scheduled command: id, domain, type, the aggregate, target and data are the scheduled command's, request the cancel's sender; decide it as the command).
  • id: str: The command or query ID; empty for a file or cache request.
  • tenant: str
  • domain: str
  • type: str: The type within the domain: the command or query type, or for a file request PutData, GetData or DeleteData, for a cache request SetCache, GetCache or DeleteCache.
  • data: Any: The request's payload; vault fields are None unless the key is granted vault_read. Always None for 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 with Aggregate.handle: id() derives from command_id as in a real command, now() returns received_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 of datetime.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 as id to submit, else a new UUID.
  • type: str: The command type within the domain.
  • domain: str
  • aggregate_type: str
  • aggregate_id: str
  • tenant: 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): Use Domain.command. Raises ValueError if type is qualified.
  • personal(fields: list[str], subject: Callable) -> 'CommandSchema': Keeps these top-level fields in the vault as personal data of subject; see EventSchema.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): Use Domain.query. Raises ValueError if type is qualified.
  • target(aggregate_type: str, field: str) -> 'QuerySchema': The query is about one aggregate of aggregate_type (order, or qualified shop.order), whose ID is in the data's field (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: bytes
  • content_type: str: The media type given when the file was put, e.g. image/png.
  • sha256: str: The SHA-256 of data, 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): Use k.data of a Kernable.
  • put(domain: str, key: str, data: bytes | str, content_type: str | None=None, *, tenant: str | None=None, context: RequestContext | None=None) -> str: Stores data under key, replacing a file stored there. A str is stored as UTF-8; content_type defaults to text/plain; charset=utf-8 for a str and application/octet-stream for bytes. 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 under key, or None if there is none.
  • list(domain: str, prefix: str='', *, after: str='', tenant: str | None=None, context: RequestContext | None=None) -> Listing: The files whose keys start with prefix (granted data_read), in the order of their keys' bytes, up to 1,000 after the key after; next of the result, if set, is the after of 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 under key; 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): Use domain(name). Raises ValueError unless name starts with a letter and holds only letters, digits, - and _.
  • command(type: str) -> CommandSchema: Declares which fields of type commands the vault keeps (personal, secret); see CommandSchema. Clients that submit them need the domain: kernable.use(domain).
  • process(name: str) -> Process: Defines a business process name of this domain (shop.fulfilment for fulfilment): returns the Process builder to chain its steps on (start, command, wait, timer, decide, query, end). Kernable.app registers the domain's processes; see kernable.processes for an example. Raises ValueError if the domain has a process of that name already.
  • query(type: str) -> QuerySchema: Declares what type queries (unqualified) are about: returns the QuerySchema to chain target on. Query classes declare it as target instead. 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 writes type events at version schema (from 1), with an upcast per older version, and which of their fields the vault keeps; see EventSchema. The domain's aggregates and listeners use it; listeners of other domains get it with Listener.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's apply declares them too.
  • aggregate(name: str, initial: Any, snapshot_every: int=100, schema: str='1') -> 'AggregateType': An aggregate of this domain named name (lowercase by convention, like cart), whose state starts as initial (a JSON-like value, usually a dict); see Aggregate for snapshot_every and schema. Run it with kernable.worker(aggregate) or in an app. Example: cart_aggregate = shop_domain.aggregate("cart", {"items": 0}). Raises ValueError if 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 named name: builds a view from events and answers queries from it (on, query; see Listener). Kept in memory and rebuilt from the first event on every start (default). Run it with kernable.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. With store (sqlite:<path> or memory:), its state lives in the running listener's store: data and position are written together per batch, and a restart continues after the stored position. Change schema when the handlers store data differently: the store is cleared and the read model rebuilds from the first event. live and park_after (default 0: never; a read model that parks misses the event's change): see reactor. 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 .; default KERNABLE_INSTANCE, which kernable node sets; 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: see reactor. Raises ValueError if 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 named name: triggers side effects and follow-up commands (on; see Listener). 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 with kernable.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 with ctx.submit and a fixed id, so a redelivered event does not run the command twice. order (default 10), start, reconnect_s, store and schema: see read_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). A Rejected (also from ctx.submit) parks at once; the kernel being unreachable or busy (UNAVAILABLE, DEADLINE_EXCEEDED, RESOURCE_EXHAUSTED), NotSettled or 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 errors handler_error and 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: see read_model. single (default True for 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. Raises ValueError if the domain has a listener of that name already.

Listed ​

A file as k.data.list names it.

  • key: str
  • content_type: str
  • size: 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: str
  • version: int: The aggregate's version after this event: 1 for its first event.
  • tenant: str
  • domain: str
  • aggregate_type: str
  • aggregate_id: str
  • command_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): Use Domain.event. Raises ValueError if type is qualified or schema is below 1.
  • personal(fields: list[str], subject: Callable) -> 'EventSchema': Keeps these top-level fields in the vault, as personal data of the subject subject returns from the payload and, optionally, the aggregate's ID (e.g. lambda d: d["customerId"], or lambda d, id: id for 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 subject subject returns, 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 version from_version into one of the next version: fn(data) returns the new payload. Works as a decorator too: @item_added.upcast(1) over def _(data): return {**data, "qty": data.get("qty", 1)}. Declare one step per older version. Raises ValueError if from_version is 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 with Aggregate.unique.
  • value: str
  • scope: str: "tenant" or "global"; see Aggregate.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 at url, signing with the key in the file key. It connects on first use and again after the connection drops. url: http://host:port (host:port works 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 answers UNAVAILABLE (a standby says not_primary) or cannot be reached. Default KERNABLE_URL, else http://127.0.0.1:7233, where kernable start listens. key: path to this process's .key file; default KERNABLE_KEY, else app.key in the current directory. tenant: default tenant of submits, queries, files and the cache (default default). tls: mutual TLS for host:port; default KERNABLE_TLS_CA, KERNABLE_TLS_CERT and KERNABLE_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; default KERNABLE_GRANT, else the .grant file next to the key file, if there is one. service: the service this process's workers and listeners belong to. The service's membership (see apply) decides what the kernel waits for: what it lists counts, the service's other workers and listeners are dynamic, and only listeners it lists as middlewares may check requests. Default KERNABLE_SERVICE, else none (everything registered counts). 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 raises ValueError unless this is set; default KERNABLE_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 level KERNABLE_LOG names (off, error, warn, info (default), debug). Raises OSError if the key or grant file cannot be read, ValueError if only some of the TLS variables are set.
  • use(*domains: Domain) -> 'Kernable': Seals the vault fields of these domains' commands when submitting them (see Domain.command), and sends the targets of their queries given by name (see Domain.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; see Worker. run() on it blocks until stop(): 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 (see register_process). service defaults to this client's; version and description go into the membership's metadata, followed by metadata. Example: k.app(service="shop", version="1.0.0", domains=[shop_domain]).run(). Every start applies the membership, so the key needs the manage grant for the service. One service is one app: two processes with the same service would replace each other's membership. Raises ValueError if neither service nor 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's service): the workers, listeners and middlewares the kernel waits for, plus free metadata such as {"version": "1.0.0"}. workers are the aggregates the service runs (the kernel waits for a worker of each), listeners the listeners it waits for (the service's others count for nobody), middlewares the service's listeners that may check requests (they count like listeners), processes its 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 the manage grant 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"}). Raises ValueError without a service, grpc.RpcError if the kernel refuses it.
  • process_act(name: str, context: RequestContext) -> bool: Sets as whom the process name (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 grant process for it. Without it, a process acts as process:<name>. Returns whether it changed (False: it acted so already). The kit's identity reactor calls it for every process it gives an identity. Raises grpc.RpcError if the kernel refuses it (NOT_FOUND for a process never registered).
  • register_process(process: 'Process | dict') -> RegisteredProcess: Registers a business process (a Process, or its model as a dict), signed with this client's key: a model equal to the newest version registers nothing (new is False), a different one becomes the next version; running cases stay on theirs. Kernable.app does this for its domains' processes. The key needs the grant process for the process, and submit, query and listen for the commands, queries and events the model names. Raises ValueError if the builder finds the model invalid (see Process.model), grpc.RpcError if the kernel refuses it (INVALID_ARGUMENT names 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 a type command of domain on the aggregate aggregate_type with ID aggregate_id and returns its Outcome. data is the command's payload (JSON-like; None sends {}). wait="settled" (default) responds once every listener that counts has processed the events, so read models already show them, and raises NotSettled on timeout; from a listener's handler, only the listeners with a lower order count. wait="committed" responds once the events are stored; then query with min_position. id is an idempotency key (default: a new UUID): submitting the same id again returns the original outcome. tenant replaces the client's tenant. context replaces the client's default context; inside a listener, pass ctx.follow(). timeout_s replaces the client's deadline for this call. A rejected command returns Outcome(committed=False, code=..., message=...); it does not raise. Raises grpc.RpcError if 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 (no use needed). A scheduled command has no outcome yet: schedule it with enqueue(..., at=...) (at here raises ValueError). Submitting its id again 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 same id to get the outcome. The parameters are those of submit. With at (a datetime, 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 rejected expired. Both are signed with the command. Cancel it with cancel.
  • cancel(command_id: str, *, tenant: str | None=None, context: RequestContext | None=None, timeout_s: float | None=None) -> CancelOutcome: Cancels a scheduled command (enqueue with at) before it is due: it completes as rejected cancelled, and cancelling it again answers the same. Needs submit for the command's type; middlewares check it as a cancel of that type (Check.kind == "cancel"). Returns a CancelOutcome: not cancelled with too_late (due, running or done already), not_found, or a middleware's code. tenant and context replace the client's; timeout_s its 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 answers domain.type with data and 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 a wait="committed" submit). tenant and context replace the client's; timeout_s its 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). Raises Rejected if the read model or a middleware rejects it, grpc.RpcError if the kernel refuses the call (e.g. UNAVAILABLE when 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 the Outcome per ID: committed, or rejected, e.g. with unique_taken for an aggregate whose value another one holds already. An ID without events holds nothing. tenant and context replace the client's. Raises grpc.RpcError if 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 with Domain.read_model or Domain.reactor, in this client's service; see ListenerHandle. run() on it blocks until stop(): 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 raise ClientClosed, 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 .key file.
  • from_file(path: str) -> 'Key': The key in the .key file at path.
  • sign(message: bytes) -> pb.Signature: Signs message (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): Use Domain.read_model or Domain.reactor.
  • use(*domains: Domain) -> 'Listener': Upcasts the events of these other domains with their event schemas (see Domain.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, or orders.OrderPlaced of another domain) or a whole domain (orders.*); works as a decorator too: fn(data, evt, ctx) gets the event's payload, a StoredEventMeta and a ListenerContext (both optional). A raw handler gets payloads as stored, without upcasting, whatever their schema (for archives and exports). Example: @carts_readmodel.on("ItemAdded") over def _(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. Raises ValueError if event_type is none of these.
  • query(query_type: str, fn: Callable | None=None): Answers a query type (GetCart, or orders.GetOrder of another domain) from this listener's state; works as a decorator too: fn(data, qry, ctx) gets the query's data, a QueryMeta and a QueryContext (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; None reaches the caller as None); raise Rejected to refuse (any other exception refuses with handler_error). A handler cannot query its own listener (the answer would wait behind itself): the kernel refuses it. Example: @carts_readmodel.query("GetCart") over def _(data): return rows[data["id"]]. Raises ValueError if query_type is 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 asks fn about every command and query of types (* for all, Type of the own domain, domain.* or domain.Type) before accepting or routing it (or after, see when), in chain order (lower order first, then by listener name), and only once this listener has caught up with the events. fn(check, outcome, ctx) gets a Check, after the request what came of it, and a MiddlewareContext with the listener's store (both optional): an Outcome for a command, a QueryOutcome for a query (check.kind tells which); before, None. types cover file and cache requests too, before they run: domain.PutData, .GetData, .DeleteData, .SetCache, .GetCache and .DeleteCache (and domain.* or * include them); check.kind is then "data" or "cache", check.key the key and check.data None, and a refusal reaches the client as PERMISSION_DENIED. Return False or raise Rejected to 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 remove unregisters it). fn 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. 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 of reserved_order). A live listener cannot be a middleware. Example: @guard_readmodel.middleware(["shop.*"]) over a def _(check): that raises Rejected("not allowed", "forbidden") unless check.request.sender_identity may send check.type. Raises ValueError for an invalid type or when, a second middleware at the same when, 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= of Domain.read_model and Domain.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 fixed id (f"confirm-{evt.aggregate_id}"), so a redelivered event runs it once. domain defaults to the listener's, context to follow(), tenant to the event's; the rest as for Kernable.submit. Raises Rejected (with the kernel's key or requirement, if any) if the command is rejected: a reactor then parks the event at once (see park_after of Domain.reactor); catch it to accept a rejection. Raises like Kernable.submit otherwise. 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, like Kernable.query: type is of the listener's domain (GetOrder) or qualified (crm.GetCustomer). tenant defaults 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 process name acts, with the listener's client; see Kernable.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): Use Kernable.listener. part and store: a partition's stream, sharing the store of the handle that runs it.
  • run() -> None: Processes events, queries and checks until stop(), reconnecting when the stream drops; with a store, opens it first and continues after its position, and closes it when run() 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.app registers 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; False if it was rejected.
  • events: list[StoredEvent]: The committed events, in order; empty if the command was rejected. Vault fields in them are None (see StoredEvent.redacted).
  • code: str: The rejection code (see Rejected), if rejected.
  • message: str: The rejection message, if rejected.
  • key: str: For unique_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': For requirement_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): Use Domain.process. Raises ValueError if name is invalid.
  • qualified() -> str: <domain>.<name>: shop.fulfilment.
  • start(event: type[Event] | str, *, key: str, data: dict | None=None) -> 'Process': Starts a case when event commits. key is where the case's key is in the event (aggregate_id, or data.<field>): one case per key. data maps case fields to references into the event ({"order_id": "aggregate_id", "total": "data.total"}) or value(...).
  • command(name: str, command: type[Command] | str, *, aggregate: str, data: dict | None=None, rejected: dict[str, str] | None=None, next: str | None=None) -> 'Process': Sends command as the process to the aggregate whose ID aggregate names (case.order_id), with data from the case (field → reference or value(...)). rejected maps rejection codes to the steps that handle them; any other rejection raises an incident. Then next, 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 an event of this case: the one whose key (aggregate_id or data.<field>) is the case's key. data merges fields of the event into the case's data. With timeout (3d), the case moves to on_timeout if the event does not come in time. Then next, or the step written after it.
  • timer(name: str, *, after: str | int | None=None, at: str | None=None, next: str | None=None) -> 'Process': Waits after a duration (12h), or until the time (ms) a reference names (at: case.due_at). Then next, 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 to then, or cases=[("case.total > 1000", "approval"), ...] (or dicts with when and then), the first that holds; else otherwise, 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 model query with data from the case; its answer picks the path: paths maps answers ({True: "approved", False: "paid"}, or strings and numbers) to steps, matched against the answer itself or, for an object, its field answer. into keeps the answer in the case's data under that field. An answer no path names goes to otherwise (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 an event of 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. end must be an end step.
  • model() -> dict: The model the kernel registers (design/processes.md "The model format"): types qualified, references with wire names, durations in ms, and an explicit next on every step but end. Raises ValueError naming 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= of Domain.read_model and Domain.reactor).

QueryMeta ​

What a query handler gets about the query besides its data (as an optional second parameter).

  • query_id: str
  • type: str: The query type within the domain.
  • domain: str
  • tenant: 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; False if 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: str
  • sender_session: str
  • on_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: str
  • bypass_authorization: bool: Privileged: only keys granted privileged for 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 by key.
  • fact: str: A fact the aggregate declares with Aggregate.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 key key with value, 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): Opens url (sqlite:<path>, a bare path, or memory:). If the stored data was built at another schema, it is cleared and the read model rebuilds from the first event.
  • get(ns: str, key: str, default: Any=None) -> Any: The value under key in namespace ns, decoded from JSON, or default if there is none.
  • set(ns: str, key: str, value: Any) -> None: Stores value (anything json.dumps takes) under key in namespace ns, replacing a value there.
  • remove(ns: str, key: str) -> None: Removes the value under key in namespace ns, 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 partition part: 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 its run() 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 (see Domain.event), or the stored one for a raw handler.
  • redacted: list[str]: Fields kept in the vault whose value is not in the data (None there): erased, or not readable with this key (granted vault_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: str
  • cert: str
  • key: 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=''): Use Kernable.worker.
  • run() -> None: Processes commands until stop(), 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")}.