The best way to control Claude Code, Codex and more from any computer or phone

main
mdx 166 lines 9.42 KB
Raw
1 ---
2 title: Event
3 description: What an event records, what to put in it, how it's stored, and how the rest of the model consumes it.
4 ---
5
6 import DAG from "../../../components/DAG.astro";
7
8 An event records something that happened: `AccountOpened`, `MoneyDeposited`, `MoneyWithdrawn`. It's named in the past tense because, by the time anyone sees it, it's a fact.
9
10 Events are the only thing an aggregate stores as its history. Its state, every view, and every policy's reaction are all derived from them. This chapter covers how to find a business's events, how to declare one, what to put in it, and what happens to it after it's recorded.
11
12 ## Events are the business's memory
13
14 Businesses ran on events long before software. Take a bank's ledger. It's a list of things that happened, written in order and never erased: opened, deposited 100, withdrew 30. The balance at the bottom of the page is a sum of the lines above it. When the bank finds a mistake, it doesn't rub out a line; it writes a new one that corrects it.
15
16 An event-sourced model keeps its history the same way. Each event is one line in the ledger of one aggregate instance. Everything else, the account's state, its statement, the customer's dashboard, is worked out from those lines. Because nothing is overwritten, you can always answer "how did it get like this?", and a question nobody thought to ask last year can be answered from history you already have.
17
18 <DAG
19 nodes={[
20 { id: "opened", label: "AccountOpened", type: "seq 1", kind: "event", col: 0, row: 0 },
21 { id: "deposited", label: "MoneyDeposited 100", type: "seq 2", kind: "event", col: 1, row: 0 },
22 { id: "withdrew", label: "MoneyWithdrawn 30", type: "seq 3", kind: "event", col: 2, row: 0 },
23 { id: "state", label: "balance: 70", type: "derived", col: 2, row: 1 },
24 ]}
25 edges={[
26 { from: "opened", to: "deposited" },
27 { from: "deposited", to: "withdrew" },
28 { from: "withdrew", to: "state", dashed: true },
29 ]}
30 caption="The events are the record. The balance is what they add up to."
31 />
32
33 ## Find the events
34
35 To find a business's events, ask its people to tell the story of their work as a series of things that happened, in order. At a bank, it might go: "The customer registers. Their main account is opened. They deposit their pay. They withdraw cash. Late at night they withdraw again, and the account is frozen for review." Each sentence in the past tense is an event: `CustomerRegistered`, `AccountOpened`, `MoneyDeposited`, `MoneyWithdrawn`, `AccountFrozen`.
36
37 Telling it as a story surfaces the things people care about, in their own words, and in the order they happen. The commands fall out next: for each event, ask what someone asked for to make it happen. The aggregates come after that: for each command, ask what has to be checked before it's allowed, and what state that check needs.
38
39 ## Name what the business saw
40
41 Name an event after what happened in the business, not after what changed in a database. `AccountFrozen` tells you something. `AccountUpdated` or `StatusChanged` tells you a row was written, and leaves you to dig through its fields to find out why.
42
43 A specific name is what lets the rest of the model react. A fraud policy listens for `MoneyWithdrawn`; a statement prints a line for each `MoneyDeposited`. Neither could subscribe to "the account changed" without re-deciding what kind of change it was.
44
45 One command can record more than one event when more than one thing happened. And a rejection is not an event: when a command is refused, nothing happened, so nothing is recorded.
46
47 ## Declare an event
48
49 An event has a name and, usually, some data.
50
51 ```typescript title="src/WithdrawMoney.command.ts"
52 export class MoneyWithdrawn extends Domain.Event("MoneyWithdrawn", {
53 amount: Schema.Int,
54 balanceAfter: Schema.Int,
55 }) {}
56 ```
57
58 Each field is a schema, so events are encoded the same way wherever they're stored or sent. An event that needs no data has no fields: `Domain.Event("AccountClosed")`.
59
60 ## Only decide creates events
61
62 Events are created in exactly one place: an aggregate's `decide` handler, as its answer to a command.
63
64 ```typescript title="src/Account.aggregate.ts"
65 : [new MoneyWithdrawn({ amount: cmd.amount, balanceAfter: s.balance - cmd.amount })],
66 ```
67
68 The command declares which events it may record, so `decide` can't return anything else. Once they're committed, they're never changed or removed. A mistake is corrected the way an accountant corrects one, with a new event that reverses it, so the history still shows both.
69
70 ## Record what readers will need
71
72 Put in the event what someone reading it later needs to understand it on its own, without asking the aggregate what its state was at the time.
73
74 `MoneyWithdrawn` carries `balanceAfter` for that reason. The aggregate knows the balance when it decides, so it's free to record. A view that shows the balance, a statement that prints it on each line, and a policy that flags low balances can all read it straight from the event. Without it, each would have to keep its own running total and hope it never drifts.
75
76 The same goes for who did something and why. When a support agent freezes an account, the event records the agent and the reason, so the history explains itself.
77
78 ```typescript title="packages/domain/src/Account/FreezeAccount.command.ts"
79 export class AccountFrozen extends Domain.Event("AccountFrozen", {
80 reason: Schema.String,
81 by: Actor,
82 }) {}
83 ```
84
85 ## Keep old events readable
86
87 Events are kept for good, so every event you've ever recorded will be read again: each time an aggregate rebuilds its state, and each time a view is built from history. Treat an event's shape as a promise to your future self.
88
89 Add a new field as optional, so events recorded before it existed still decode. When the meaning of something changes, add a new event rather than changing what an old one means. A history in which `MoneyWithdrawn` meant one thing in March and another in May is a history nobody can read.
90
91 ```typescript
92 export class MoneyWithdrawn extends Domain.Event("MoneyWithdrawn", {
93 amount: Schema.Int,
94 balanceAfter: Schema.Int,
95 channel: Schema.optional(Schema.Literals(["atm", "app"])), // added later
96 }) {}
97 ```
98
99 ## Fold events into state
100
101 The aggregate turns each event into its next state with `evolve`. This is where an event's data takes effect.
102
103 ```typescript title="src/Account.aggregate.ts"
104 evolve: {
105 AccountOpened: (_, e) => ({ _tag: "Open" as const, owner: e.owner, balance: 0 }),
106 MoneyDeposited: (s, e) => (s._tag === "Open" ? { ...s, balance: e.balanceAfter } : s),
107 MoneyWithdrawn: (s, e) => (s._tag === "Open" ? { ...s, balance: e.balanceAfter } : s),
108 },
109 ```
110
111 `evolve` can't refuse an event. It already happened, and only `decide` gets to say no. `decide` returns a typed rejection such as `NotOpen` before it records a deposit to an account that isn't open, so `evolve` only has to cover every state. See [Aggregate](/domain/aggregate#apply-events-with-evolve).
112
113 ## The envelope
114
115 When an event commits, it's stored inside an envelope that says where and when it happened. `id` is the aggregate instance and `stream` names its history, like `Account/a-1`. `seq` is the event's position in that stream, starting at 1. `at` is the commit time, and `commandId` is the id of the command that caused it.
116
117 `evolve` receives the envelope as its third argument, for state that depends on when something happened.
118
119 ```typescript title="src/Account.aggregate.ts"
120 MoneyWithdrawn: (_, e, { at }) => ({
121 balance: e.balanceAfter,
122 lastWithdrawal: DateTime.formatIsoDateUtc(at),
123 }),
124 ```
125
126 The `commandId` lets a client recognize the events its own commands caused, which is how an app confirms an [optimistic update](/domain/optimistic-updates).
127
128 ## Delivered to views and policies
129
130 In the same commit that stores an event, the instance records a delivery for every [view](/domain/view) and [policy](/domain/policy) that consumes it. After the commit, each delivery is sent. Every consumer receives every event it consumes at least once, and in the order the instance recorded them.
131
132 <DAG
133 nodes={[
134 { id: "event", label: "MoneyWithdrawn", type: "Account a-1", kind: "event" },
135 { id: "summary", label: "AccountSummary", type: "view", kind: "view" },
136 { id: "statement", label: "Statement", type: "view", kind: "view" },
137 { id: "outflow", label: "DailyOutflow", type: "view", kind: "view" },
138 ]}
139 edges={[
140 { from: "event", to: "summary", dashed: true },
141 { from: "event", to: "statement", dashed: true },
142 { from: "event", to: "outflow", dashed: true },
143 ]}
144 caption="One event, delivered to every view that reads it."
145 />
146
147 A view can record events of its own as it folds, such as one `StatementLine` per deposit or withdrawal. Those are delivered the same way, so another view or policy can build on them.
148
149 ## Follow an instance's events
150
151 A client can read an instance's history directly, then keep receiving new events as they're recorded.
152
153 ```typescript title="packages/server/test/followAccount.ts"
154 export const followAccount = Effect.fn(function* (bank: CustomerClient, accountId: AccountId) {
155 yield* bank.Account.events(accountId).pipe(
156 Stream.filter(Domain.Read.isEvent),
157 Stream.runForEach(({ event, envelope }) =>
158 Effect.log(`#${envelope.seq} ${event._tag} (command ${envelope.commandId})`),
159 ),
160 );
161 });
162 ```
163
164 `events` replays from the beginning, sends a `CaughtUp` frame, then continues live. `Domain.Read.isEvent` keeps only the events. Pass `after` with a `seq` to resume from a position you've already seen.
165
166 Next, [Aggregate](/domain/aggregate): where commands are decided and events are recorded.