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)])
});
}go
type Confirm struct {
CustomerID string `json:"customerId"`
Email string `json:"email"`
}
func init() {
kernable.Handle(OrderAggregate, "Confirm", func(_ *kernable.CommandContext, s Order, d Confirm) ([]kernable.NewEvent, error) {
if s.Status != "submitted" {
return nil, kernable.Reject("invalid_state", fmt.Sprintf("Cannot confirm a %s order", s.Status))
}
return kernable.Events(kernable.Event("OrderConfirmed", Confirm{CustomerID: d.CustomerID, Email: d.Email})), nil
})
}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(()) }
});go
func init() {
kernable.On(ordersReadModel, "OrderConfirmed", func(ctx *kernable.ListenerContext, d struct{ Email *string }) error {
row := orders[ctx.Event.AggregateID]
row.Status = "confirmed"
row.ConfirmedTo = d.Email
return nil
})
}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;go
func main() {
// Who this service is (part 6), and the domain's declarations, e.g. which fields are personal (part 7).
client, err := kernable.New(kernable.Options{Context: kernable.RequestContext{SenderIdentity: "svc-confirmations"}})
if err != nil {
log.Fatal(err)
}
client.Use(shop.Domain)
confirmations := shop.Domain.Reactor("confirmations")
kernable.On(confirmations, "OrderSubmitted", func(ctx *kernable.ListenerContext, _ struct{}) error {
// The read models (order 0) have processed this event before the reactor (order 10) gets it.
var order struct {
CustomerID string `json:"customerId"`
}
var customer struct {
Email string `json:"email"`
}
if err := query(ctx, "GetOrder", ctx.Event.AggregateID, &order); err != nil {
return err
}
if err := query(ctx, "GetCustomer", order.CustomerID, &customer); err != nil {
return err
}
// Same sender and correlation as the submit that caused the event; a rejection parks the event.
_, err := ctx.Submit(kernable.Command{
AggregateType: "order",
AggregateID: ctx.Event.AggregateID,
Type: "Confirm",
Data: shop.Confirm{CustomerID: order.CustomerID, Email: customer.Email},
ID: "confirm-" + ctx.Event.AggregateID, // a redelivered event confirms once
})
return err
})
log.Fatal(client.Listener(confirmations).Run(context.Background()))
}
func query(ctx *kernable.ListenerContext, queryType, id string, into any) error {
answer, err := ctx.Query(queryType, map[string]string{"id": id})
if err != nil {
return err
}
return json.Unmarshal(answer, into)
}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, .venv/bin/python confirmations.py, cargo run -q --bin confirmations or go run ./confirmations) 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}");go
send("customer", "c1", "Register", m{"email": "ann@example.com", "name": "Ann"})
send("order", "o1", "Place", m{"customerId": "c1"})
send("order", "o1", "AddItem", m{"sku": "apple", "qty": 2})
send("order", "o1", "Submit", nil)
// The submit settled after the reactor, which confirmed the order before it returned.
order, err := client.Query(ctx, kernable.Query{Domain: "shop", Type: "GetOrder", Data: m{"id": "o1"}})
if err != nil {
log.Fatal(err)
}
fmt.Println(string(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"}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.
