Appearance
4. A reactor
A reactor is a listener that acts on events: it sends emails, calls other systems, or sends follow-up commands. Here it confirms every submitted order to the customer's email address.
Confirming an order
The order gets a command and an event for the confirmation, in domain.ts:
ts
orderAggregate.command("Confirm", (s, data: { customerId: string; email: string }) => {
if (s.status !== "submitted") throw new Rejected(`Cannot confirm a ${s.status} order`, "invalid_state");
return [{ type: "OrderConfirmed", data: { customerId: data.customerId, email: data.email } }];
});py
@order_aggregate.command("Confirm")
def _(state, data):
if state["status"] != "submitted":
raise Rejected(f"Cannot confirm a {state['status']} order", "invalid_state")
return [{"type": "OrderConfirmed", "data": {"customerId": data["customerId"], "email": data["email"]}}]rs
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Confirm {
customer_id: String,
email: String,
}
fn confirm(order_aggregate: &Aggregate<Order>) {
order_aggregate.command("Confirm", |s, data: Confirm, _cmd, _ctx| {
if s.status != "submitted" {
let message = format!("Cannot confirm a {} order", s.status);
return Err(Rejected::new(message).code("invalid_state"));
}
Ok(vec![NewEvent::new("OrderConfirmed", data)])
});
}and the orders read model learns about it, in read-models.ts:
ts
ordersReadmodel.on("OrderConfirmed", (data: { email: string }, evt) => {
const row = orders.get(evt.aggregateId)!;
row.status = "confirmed";
row.confirmedTo = data.email;
});py
@orders_readmodel.on("OrderConfirmed")
def _(data, evt):
orders[evt.aggregate_id].update(status="confirmed", confirmedTo=data["email"])rs
let rows = Arc::clone(&orders);
orders_readmodel.on("OrderConfirmed", move |data: Value, evt, _ctx| {
let mut rows = rows.lock().unwrap();
let row = rows.get_mut(&evt.aggregate_id).expect("placed");
row.status = "confirmed".into();
row.confirmed_to = Some(data["email"].as_str().map(str::to_owned));
async { Ok(()) }
});The reactor
ts
// Who this service is (part 6), and the domain's declarations, e.g. which fields are personal (part 7).
const kernable = new Kernable({ context: { senderIdentity: "svc-confirmations" } }).use(shopDomain);
const confirmationsReactor = shopDomain.reactor("confirmations")
.on("OrderSubmitted", async (_data, evt, ctx) => {
// The read models (order 0) have processed this event before the reactor (order 10) gets it.
const order = await ctx.query<{ customerId: string }>("GetOrder", { id: evt.aggregateId });
const customer = await ctx.query<{ email: string }>("GetCustomer", { id: order.customerId });
// Same sender and correlation as the submit that caused the event; a rejection parks the event.
await ctx.submit({
aggregateType: "order",
aggregateId: evt.aggregateId,
type: "Confirm",
data: { customerId: order.customerId, email: customer.email },
id: `confirm-${evt.aggregateId}`, // a redelivered event confirms once
});
});
await kernable.listener(confirmationsReactor).run();py
k = Kernable(context=RequestContext(sender_identity="svc-confirmations")).use(shop_domain) # parts 6 and 7
confirmations_reactor = shop_domain.reactor("confirmations")
@confirmations_reactor.on("OrderSubmitted")
def _(data, evt, ctx):
# The read models (order 0) have processed this event before the reactor (order 10) gets it.
order = ctx.query("GetOrder", {"id": evt.aggregate_id})
customer = ctx.query("GetCustomer", {"id": order["customerId"]})
# Same sender and correlation as the submit that caused the event; a rejection parks the event.
ctx.submit("order", evt.aggregate_id, "Confirm", {"customerId": order["customerId"], "email": customer["email"]},
id=f"confirm-{evt.aggregate_id}") # a redelivered event confirms once
k.listener(confirmations_reactor).run()rs
// Who this service is (part 6), and the domain's declarations, e.g. which fields are personal (part 7).
let me = RequestContext {
sender_identity: "svc-confirmations".into(),
..Default::default()
};
let shop_domain = shop().domain;
let kernable = Kernable::new(Options::default().context(me))?.with_domain(&shop_domain);
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct OrderRow {
customer_id: String,
}
#[derive(Deserialize)]
struct CustomerRow {
email: String,
}
let confirmations_reactor = shop_domain.reactor("confirmations").on(
"OrderSubmitted",
|_: Value, evt, ctx| async move {
// The read models (order 0) have processed this event before the reactor (order 10) gets it.
let get =
|query_type, id: &str| Query::new("shop", query_type).data(json!({ "id": id }));
let order: OrderRow = ctx.query(get("GetOrder", &evt.aggregate_id)).await?;
let customer: CustomerRow = ctx.query(get("GetCustomer", &order.customer_id)).await?;
// Same sender and correlation as the submit that caused the event; a rejection parks the event.
let confirm = Submit::new("shop", "order", &evt.aggregate_id, "Confirm")
.data(json!({ "customerId": order.customer_id, "email": customer.email }))
.id(format!("confirm-{}", evt.aggregate_id)); // a redelivered event confirms once
ctx.submit(confirm).await?;
Ok(())
},
);
kernable.listener(&confirmations_reactor).run().await;Three things make it safe:
- Order. Read models have order 0, reactors order 10. A listener gets an event only after every listener with a lower order has processed it, so the reactor's queries always find the order and the customer.
- A fixed command ID. Delivery is at least once: after a crash the reactor may get the event again. With
confirm-<order>as the ID, the second confirmation returns the first one's outcome.ctx.submitrefuses a follow-up without one. ctx.submitgives the follow-up command the sender and correlation of the command that caused the event (ctx.follow()), so you can trace a confirmation back to the submit. Its queries (ctx.query) stay the reactor's own.
If the confirmation is rejected, ctx.submit throws, and the reactor parks the event: it moves on to the next order, and the kernel keeps the event with the rejection until someone looks at it (kernable listeners parked, the UI) and retries or dismisses it. A handler that fails for another reason (a bug, a mail server that is down) gets the event again a few times first; while the kernel is unreachable it simply waits. See Failures.
Its own submit settles too, but only on the listeners before it: a listener handles one event at a time, so the kernel never makes it wait for itself.
Start it (node confirmations.ts or .venv/bin/python confirmations.py) and submit an order:
ts
await send("customer", "c1", "Register", { email: "ann@example.com", name: "Ann" });
await send("order", "o1", "Place", { customerId: "c1" });
await send("order", "o1", "AddItem", { sku: "apple", qty: 2 });
await send("order", "o1", "Submit");
// The submit settled after the reactor, which confirmed the order before it returned.
console.log(await kernable.query({ domain: "shop", type: "GetOrder", data: { id: "o1" } }));py
send("customer", "c1", "Register", {"email": "ann@example.com", "name": "Ann"})
send("order", "o1", "Place", {"customerId": "c1"})
send("order", "o1", "AddItem", {"sku": "apple", "qty": 2})
send("order", "o1", "Submit")
# The submit settled after the reactor, which confirmed the order before it returned.
print(k.query("shop", "GetOrder", {"id": "o1"}))rs
send(
"customer",
"c1",
"Register",
json!({ "email": "ann@example.com", "name": "Ann" }),
)
.await?;
send("order", "o1", "Place", json!({ "customerId": "c1" })).await?;
send(
"order",
"o1",
"AddItem",
json!({ "sku": "apple", "qty": 2 }),
)
.await?;
send("order", "o1", "Submit", Value::Null).await?;
// The submit settled after the reactor, which confirmed the order before it returned.
let order: Value = kernable
.query(Query::new("shop", "GetOrder").data(json!({ "id": "o1" })))
.await?;
println!("{order}");text
{
id: 'o1',
customerId: 'c1',
status: 'confirmed',
items: { apple: 2 },
confirmedTo: 'ann@example.com'
}text
{'id': 'o1', 'customerId': 'c1', 'status': 'confirmed', 'items': {'apple': 2}, 'confirmedTo': 'ann@example.com'}text
{"id":"o1","customerId":"c1","status":"confirmed","items":{"apple":2},"confirmedTo":"ann@example.com"}The Submit settled after the reactor, which had confirmed the order by then: the query shows it confirmed.
Next: 5. A second language.
