Appearance
10. A business process
A confirmed order is not done: the customer pays, then the shop ships, and an order nobody pays within three days is cancelled. You could build this from a reactor, a scheduled command and a read model that remembers where each order stands. Here you define it once as a business process; the kernel runs it, and its UI shows where every order stands.
This part builds on the shop of parts 2 to 7 (the worker, the read models, the reactor and the guard), without the kit of part 9.
Paying, shipping, cancelling
The order gets three commands and their events, in domain.ts:
ts
// Part 10: a confirmed order is paid, then shipped; or cancelled when it is not paid in time.
orderAggregate
.apply("OrderPaid", (s) => { s.status = "paid"; })
.apply("OrderShipped", (s) => { s.status = "shipped"; })
.apply("OrderCancelled", (s) => { s.status = "cancelled"; })
.command("Pay", (s) => {
if (s.status !== "confirmed") throw new Rejected(`Cannot pay a ${s.status} order`, "invalid_state");
return [{ type: "OrderPaid" }];
})
.command("Ship", (s) => {
if (s.status !== "paid") throw new Rejected(`Cannot ship a ${s.status} order`, "invalid_state");
return [{ type: "OrderShipped" }];
})
.command("Cancel", (s, data: { reason: string }) => {
if (s.status !== "confirmed") throw new Rejected(`Cannot cancel a ${s.status} order`, "invalid_state");
return [{ type: "OrderCancelled", data: { reason: data.reason } }];
});py
# Part 10: a confirmed order is paid, then shipped; or cancelled when it is not paid in time.
@order_aggregate.apply("OrderPaid")
def _(state, data):
state["status"] = "paid"
@order_aggregate.apply("OrderShipped")
def _(state, data):
state["status"] = "shipped"
@order_aggregate.apply("OrderCancelled")
def _(state, data):
state["status"] = "cancelled"
@order_aggregate.command("Pay")
def _(state, data):
if state["status"] != "confirmed":
raise Rejected(f"Cannot pay a {state['status']} order", "invalid_state")
return [{"type": "OrderPaid"}]
@order_aggregate.command("Ship")
def _(state, data):
if state["status"] != "paid":
raise Rejected(f"Cannot ship a {state['status']} order", "invalid_state")
return [{"type": "OrderShipped"}]
@order_aggregate.command("Cancel")
def _(state, data):
if state["status"] != "confirmed":
raise Rejected(f"Cannot cancel a {state['status']} order", "invalid_state")
return [{"type": "OrderCancelled", "data": {"reason": data["reason"]}}]rs
// Part 10: a confirmed order is paid, then shipped; or cancelled when it is not paid in time.
#[derive(Serialize, Deserialize)]
struct Cancel {
reason: String,
}
fn fulfil(order_aggregate: &Aggregate<Order>) {
order_aggregate.apply("OrderPaid", |s, _: Value, _evt, _ctx| {
s.status = "paid".into()
});
order_aggregate.apply("OrderShipped", |s, _: Value, _evt, _ctx| {
s.status = "shipped".into()
});
order_aggregate.apply("OrderCancelled", |s, _: Value, _evt, _ctx| {
s.status = "cancelled".into()
});
order_aggregate.command("Pay", |s, _: Value, _cmd, _ctx| {
if s.status != "confirmed" {
let message = format!("Cannot pay a {} order", s.status);
return Err(Rejected::new(message).code("invalid_state"));
}
Ok(vec![NewEvent::new("OrderPaid", ())])
});
order_aggregate.command("Ship", |s, _: Value, _cmd, _ctx| {
if s.status != "paid" {
let message = format!("Cannot ship a {} order", s.status);
return Err(Rejected::new(message).code("invalid_state"));
}
Ok(vec![NewEvent::new("OrderShipped", ())])
});
order_aggregate.command("Cancel", |s, data: Cancel, _cmd, _ctx| {
if s.status != "confirmed" {
let message = format!("Cannot cancel a {} order", s.status);
return Err(Rejected::new(message).code("invalid_state"));
}
Ok(vec![NewEvent::new("OrderCancelled", data)])
});
}and the orders read model follows them, in read-models.ts:
ts
ordersReadmodel
.on("OrderPaid", (_data, evt) => void (orders.get(evt.aggregateId)!.status = "paid"))
.on("OrderShipped", (_data, evt) => void (orders.get(evt.aggregateId)!.status = "shipped"))
.on("OrderCancelled", (data: { reason: string }, evt) => {
const row = orders.get(evt.aggregateId)!;
row.status = "cancelled";
row.cancelled = data.reason;
});py
@orders_readmodel.on("OrderPaid")
def _(data, evt):
orders[evt.aggregate_id]["status"] = "paid"
@orders_readmodel.on("OrderShipped")
def _(data, evt):
orders[evt.aggregate_id]["status"] = "shipped"
@orders_readmodel.on("OrderCancelled")
def _(data, evt):
orders[evt.aggregate_id].update(status="cancelled", cancelled=data["reason"])rs
for (event_type, status) in [("OrderPaid", "paid"), ("OrderShipped", "shipped")] {
let rows = Arc::clone(&orders);
orders_readmodel.on(event_type, move |_: Value, evt, _ctx| {
rows.lock()
.unwrap()
.get_mut(&evt.aggregate_id)
.expect("placed")
.status = status.into();
async { Ok(()) }
});
}
let rows = Arc::clone(&orders);
orders_readmodel.on("OrderCancelled", move |data: Value, evt, _ctx| {
let mut rows = rows.lock().unwrap();
let row = rows.get_mut(&evt.aggregate_id).expect("placed");
row.status = "cancelled".into();
row.cancelled = data["reason"].as_str().map(str::to_owned);
async { Ok(()) }
});The process
Also in domain.ts, next to the aggregates:
ts
// How long a customer has to pay; PAY_WITHIN=10s to try it.
const payWithin = (process.env.PAY_WITHIN ?? "3d") as Duration;
export const fulfilment = shopDomain.process("fulfilment")
.start("OrderConfirmed", { key: "aggregateId", data: { orderId: "aggregateId" } })
.wait("paid", "OrderPaid", { key: "aggregateId", timeout: payWithin, onTimeout: "cancel" })
.command("ship", "order.Ship", { aggregate: "case.orderId", next: "shipped" })
.command("cancel", "order.Cancel", { aggregate: "case.orderId", data: { reason: value("unpaid") } })
.end("unpaid")
.end("shipped");py
# How long a customer has to pay; PAY_WITHIN=10s to try it.
pay_within = os.environ.get("PAY_WITHIN", "3d")
fulfilment = (
shop_domain.process("fulfilment")
.start("OrderConfirmed", key="aggregate_id", data={"order_id": "aggregate_id"})
.wait("paid", "OrderPaid", key="aggregate_id", timeout=pay_within, on_timeout="cancel")
.command("ship", "order.Ship", aggregate="case.order_id", next="shipped")
.command("cancel", "order.Cancel", aggregate="case.order_id", data={"reason": value("unpaid")})
.end("unpaid")
.end("shipped")
)rs
fn process(shop_domain: &Domain) -> Process {
// How long a customer has to pay; PAY_WITHIN=10s to try it.
let pay_within = std::env::var("PAY_WITHIN").unwrap_or_else(|_| "3d".into());
shop_domain
.process("fulfilment")
.start_named(
"OrderConfirmed",
Start::key("aggregate_id").data([("order_id", "aggregate_id")]),
)
.wait_named(
"paid",
"OrderPaid",
Wait::key("aggregate_id").timeout(&pay_within, "cancel"),
)
.command_named(
"ship",
"order.Ship",
Send::aggregate("case.order_id").next("shipped"),
)
.command_named(
"cancel",
"order.Cancel",
Send::aggregate("case.order_id").data([("reason", value("unpaid"))]),
)
.end("unpaid")
.end("shipped")
}Read it from the top:
start: when an order is confirmed (the reactor of part 4 confirms it), a case starts for it. The order's ID is the case's key: one running case per order. The case keeps it asorderId.wait("paid"): the case waits forOrderPaidof the same order. If none comes withinPAY_WITHIN(three days), it goes tocancelinstead.command("ship"): the kernel sendsShipto the order and, once it committed, goes on toshipped.command("cancel"): sendsCancelwith the reasonunpaid, then goes on to the next step written, the endunpaid.end: the two ways a case ends. The UI counts cases by them.
Each step has a name: the UI, the statistics and a later version of the process know it by its name. Business processes lists every kind of step.
Let the process act
The kernel sends the process's commands as process:shop.fulfilment, and the guard of part 6 refuses anyone who is not the order's customer. Tell it what the process may send, in guard.ts:
ts
const SERVICES = new Set(["svc-confirmations"]);
// What a business process may send (part 10): it acts as `process:<name>`.
const PROCESSES: Record<string, string[]> = { "process:shop.fulfilment": ["Ship", "Cancel"] };
const registered = new Set<string>();
const ownerOf = new Map<string, string>(); // order -> customer
const guardReadmodel = shopDomain.readModel("guard")
.on("CustomerRegistered", (_data, evt) => void registered.add(evt.aggregateId))
.on("CustomerErased", (_data, evt) => void registered.delete(evt.aggregateId))
.on("OrderPlaced", (data: { customerId: string }, evt) => void ownerOf.set(evt.aggregateId, data.customerId))
.middleware({ types: ["shop.*"] }, (check) => {
const who = check.request.senderIdentity ?? "";
if (check.type === "Register") return; // anyone may sign up
if (check.kind === "query" && SERVICES.has(who)) return; // services may read
if (check.kind === "command" && PROCESSES[who]?.includes(check.type)) return;
// Files and cache requests carry no data: they have no owner, so only the rules above pass them.
const data = (check.data ?? {}) as { id?: string; customerId?: string };
const target = check.kind === "command" ? check.aggregateId! : data.id!;
const owner =
check.type === "Place" ? data.customerId
: check.type === "GetCustomer" || check.aggregateType === "customer" ? target
: ownerOf.get(target);
if (!registered.has(who) || owner !== who) throw new Rejected(`${check.type} is not allowed for ${who || "anonymous"}`, "forbidden");
});
await new Kernable().listener(guardReadmodel).run();py
SERVICES = {"svc-confirmations"}
# What a business process may send (part 10): it acts as `process:<name>`.
PROCESSES = {"process:shop.fulfilment": {"Ship", "Cancel"}}
registered: set[str] = set()
owner_of: dict[str, str] = {} # order -> customer
guard_readmodel = shop_domain.read_model("guard")
@guard_readmodel.on("CustomerRegistered")
def _(data, evt):
registered.add(evt.aggregate_id)
@guard_readmodel.on("CustomerErased")
def _(data, evt):
registered.discard(evt.aggregate_id)
@guard_readmodel.on("OrderPlaced")
def _(data, evt):
owner_of[evt.aggregate_id] = data["customerId"]
@guard_readmodel.middleware(["shop.*"])
def _(check: Check):
who = check.request.sender_identity
if check.type == "Register":
return # anyone may sign up
if check.kind == "query" and who in SERVICES:
return # services may read
if check.kind == "command" and check.type in PROCESSES.get(who, ()):
return
data = check.data or {} # files and cache requests carry none: they have no owner
target = check.aggregate_id if check.kind == "command" else data.get("id")
if check.type == "Place":
owner = check.data.get("customerId")
elif check.type == "GetCustomer" or check.aggregate_type == "customer":
owner = target
else:
owner = owner_of.get(target)
if who not in registered or owner != who:
raise Rejected(f"{check.type} is not allowed for {who or 'anonymous'}", "forbidden")
Kernable().listener(guard_readmodel).run()rs
const SERVICES: [&str; 1] = ["svc-confirmations"];
// What a business process may send (part 10): it acts as `process:<name>`.
const PROCESSES: [(&str, &[&str]); 1] = [("process:shop.fulfilment", &["Ship", "Cancel"])];
let registered = Arc::new(Mutex::new(HashSet::<String>::new()));
let owner_of = Arc::new(Mutex::new(HashMap::<String, String>::new())); // order -> customer
let shop_domain = shop().domain;
let guard_readmodel = shop_domain.read_model("guard");
let r = Arc::clone(®istered);
guard_readmodel.on("CustomerRegistered", move |_: Value, evt, _ctx| {
r.lock().unwrap().insert(evt.aggregate_id);
async { Ok(()) }
});
let r = Arc::clone(®istered);
guard_readmodel.on("CustomerErased", move |_: Value, evt, _ctx| {
r.lock().unwrap().remove(&evt.aggregate_id);
async { Ok(()) }
});
let o = Arc::clone(&owner_of);
guard_readmodel.on("OrderPlaced", move |data: Value, evt, _ctx| {
let customer = data["customerId"].as_str().unwrap_or_default().to_owned();
o.lock().unwrap().insert(evt.aggregate_id, customer);
async { Ok(()) }
});
let (r, o) = (Arc::clone(®istered), Arc::clone(&owner_of));
guard_readmodel.middleware(MiddlewareOptions::new(&["shop.*"]), move |check| {
let who = check.request.sender_identity.clone();
let allowed = check.type_name == "Register" // anyone may sign up
|| (check.kind == CheckKind::Query && SERVICES.contains(&who.as_str())) // services may read
|| (check.kind == CheckKind::Command
&& PROCESSES.iter().any(|(process, types)| *process == who && types.contains(&check.type_name.as_str())))
|| {
let field = |name: &str| check.data[name].as_str().map(str::to_owned);
let target = match check.kind {
CheckKind::Command | CheckKind::Cancel => check.aggregate_id.clone(),
CheckKind::Query => field("id"),
// The shop keeps no files: no customer's to protect.
CheckKind::Data | CheckKind::Cache => None,
};
let owner = if check.type_name == "Place" {
field("customerId")
} else if check.type_name == "GetCustomer" || check.aggregate_type.as_deref() == Some("customer") {
target
} else {
target.and_then(|t| o.lock().unwrap().get(&t).cloned())
};
r.lock().unwrap().contains(&who) && owner.as_deref() == Some(who.as_str())
};
let who = if who.is_empty() { "anonymous".to_owned() } else { who };
let refusal = format!("{} is not allowed for {who}", check.type_name);
async move {
if !allowed {
return Err(Rejected::new(refusal).code("forbidden").into());
}
Ok(())
}
});
let kernable = Kernable::new(Options::default())?;
kernable.listener(&guard_readmodel).run().await;Without it, the first Ship would be refused forbidden, and the case would stop there as an incident: nothing lost, the case waits at ship until you fix the cause and run kernable processes retry.
Register it
The kernel runs the process once it is registered, signed with a key that may send what the process sends. An app (kernable.app) registers the processes of its domains itself; the shop runs its parts separately, so it registers the process in a script of its own, once per deploy, after the worker is up:
ts
const kernable = new Kernable();
const { name, version, new: changed } = await kernable.registerProcess(fulfilment);
console.log(`${name} version ${version}${changed ? "" : " (unchanged)"}`);
kernable.close();py
k = Kernable()
registered = k.register_process(fulfilment)
print(f"{registered.name} version {registered.version}{'' if registered.new else ' (unchanged)'}")
k.close()rs
let kernable = Kernable::new(Options::default())?;
let registered = kernable.register_process(&fulfilment).await?;
let unchanged = if registered.new { "" } else { " (unchanged)" };
println!(
"{} version {}{unchanged}",
registered.name, registered.version
);Restart the worker, the read models and the guard, then register the process with a short time to pay, to see an unpaid order cancelled:
sh
PAY_WITHIN=10s node fulfilment.ts # or .venv/bin/python fulfilment.py, or cargo run --bin fulfilmentIt prints shop.fulfilment version 1. Registering the same process again changes nothing; a changed one becomes version 2, and running cases finish on the version they started with.
Try it
Two orders: Ann pays the first, not the second.
ts
await send("customer", "c1", "Register", { email: "ann@example.com", name: "Ann" });
for (const id of ["o1", "o2"]) {
await send("order", id, "Place", { customerId: "c1" });
await send("order", id, "AddItem", { sku: "apple", qty: 1 });
await send("order", id, "Submit"); // confirmed by the reactor: a case starts for the order
}
await send("order", "o1", "Pay");
console.log("o1:", (await until("o1", "shipped")).status);
// o2 is never paid: when its time is up, the process cancels it.
const o2 = await until("o2", "cancelled");
console.log("o2:", o2.status, o2.cancelled);py
send("customer", "c1", "Register", {"email": "ann@example.com", "name": "Ann"})
for id in ("o1", "o2"):
send("order", id, "Place", {"customerId": "c1"})
send("order", id, "AddItem", {"sku": "apple", "qty": 1})
send("order", id, "Submit") # confirmed by the reactor: a case starts for the order
send("order", "o1", "Pay")
print("o1:", until("o1", "shipped")["status"])
# o2 is never paid: when its time is up, the process cancels it.
o2 = until("o2", "cancelled")
print("o2:", o2["status"], o2["cancelled"])rs
let register = json!({ "email": "ann@example.com", "name": "Ann" });
send("customer", "c1", "Register", register).await?;
for id in ["o1", "o2"] {
send("order", id, "Place", json!({ "customerId": "c1" })).await?;
send("order", id, "AddItem", json!({ "sku": "apple", "qty": 1 })).await?;
send("order", id, "Submit", Value::Null).await?; // confirmed by the reactor: a case starts for the order
}
send("order", "o1", "Pay", Value::Null).await?;
println!("o1: {}", until("o1", "shipped").await?.status);
// o2 is never paid: when its time is up, the process cancels it.
let o2 = until("o2", "cancelled").await?;
println!("o2: {} {}", o2.status, o2.cancelled.unwrap_or_default());text
o1: shipped
o2: cancelled unpaidtext
o1: shipped
o2: cancelled unpaidtext
o1: shipped
o2: cancelled unpaidThe script ends after ten seconds: o2 waited for its payment until its time was up.
Watch it
Open the UI (http://127.0.0.1:7234) and Processes: the fulfilment as a diagram, from the confirmed order on the left to its two ends on the right, each path as wide as the orders that took it, with how many are at each step now. Above it: how many ended shipped and unpaid, and how long orders waited for their payment. Click paid to list the orders waiting for it, and a case to read its story: what it waited for, what it sent and how it ended, each linked to the order's history. Searching for o1 in the top bar finds the order and its case.
The case's events are in the log like any other, written and signed by the kernel:
sh
kernable processes cases kernable.db shop.fulfilment
kernable processes case kernable.db shop.fulfilment o1#1Next, see Business processes for decisions, queries and timers, and what happens on a rejection.
