@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
mdx 306 lines 16.2 KB
Raw
1 ---
2 title: Aggregate
3 description: How an aggregate holds state, decides commands, applies events, and keeps its rules consistent.
4 ---
5
6 import DAG from "../../../components/DAG.astro";
7
8 An aggregate is the part of a model that makes decisions. Each instance, one bank account for example, holds the state its rules need, takes one command at a time, and answers with events or a refusal.
9
10 This chapter starts with what an aggregate is for and how to find one, then builds the account from the [tutorial](/domain/tutorial/part-1) piece by piece: its state, how it decides, how it applies what it decided, and what makes it safe under concurrent use. It ends with how to draw an aggregate's boundary.
11
12 ## What an aggregate protects
13
14 Every business has rules that must never be broken, not even for a moment. An account's balance never goes below zero. A username belongs to at most one customer. A transfer is either approved or expired, never both. DDD calls these **invariants**, and an aggregate is the thing that keeps one true.
15
16 To find the invariants, ask the business what must never happen. Then ask which commands could make it happen. A withdrawal could overdraw an account, so `WithdrawMoney` has to be decided by something that knows the balance. That something is the `Account` aggregate: it holds the balance, and every command that could break the rule about it goes through it.
17
18 <DAG
19 nodes={[
20 { id: "deposit", label: "DepositMoney", type: "changes the balance", kind: "command", layer: 0 },
21 { id: "withdraw", label: "WithdrawMoney", type: "could overdraw", kind: "command", layer: 0 },
22 { id: "account", label: "Account", type: "balance ≥ 0", kind: "aggregate", layer: 1 },
23 ]}
24 edges={[
25 { from: "deposit", to: "account" },
26 { from: "withdraw", to: "account" },
27 ]}
28 caption="Every command that touches the balance goes through the one thing that guards it."
29 />
30
31 So an aggregate isn't a table or an entity with getters and setters. It's a rule, together with exactly the state the rule needs, and the commands that have to respect it. Find the rule first; the state and the commands follow.
32
33 ## Give it an identity
34
35 An aggregate type has many instances, and each is addressed by an id. The account's id is an `AccountId`, the same schema its commands use as their `target`.
36
37 ```typescript title="src/Account.aggregate.ts"
38 export class Account extends Domain.Aggregate("Account", {
39 id: AccountId,
40 ```
41
42 Instances aren't created explicitly. Every id exists from the start, in the aggregate's initial state, and a command sent to a new id is decided against that state. Opening an account is just the first command an account accepts.
43
44 ## Model the state its rules need
45
46 The state holds what `decide` needs to check its rules, and nothing more. An account must know whether it's open, who owns it, and its balance.
47
48 ```typescript title="src/Account.aggregate.ts"
49 const State = Schema.Union([
50 Schema.TaggedStruct("Unopened", {}),
51 Schema.TaggedStruct("Open", { owner: Schema.String, balance: Schema.Int }),
52 ]);
53 ```
54
55 A union of tagged states makes the lifecycle explicit. An `Unopened` account has no owner and no balance, so there's no field to forget to check. Code that wants the balance has to establish that the account is `Open` first, and the types enforce it.
56
57 ```typescript title="src/Account.aggregate.ts"
58 state: State,
59 initial: { _tag: "Unopened" },
60 ```
61
62 `initial` is the state of every instance before its first event.
63
64 Keep the statement, the transaction count and the monthly totals out of here. The account doesn't need them to decide anything, so they belong in [views](/domain/view).
65
66 ## Decide each command
67
68 `decide` has one handler per command in `commands`. A handler receives the current state and the command, and returns the events to record or a rejection.
69
70 ```typescript title="src/Account.aggregate.ts"
71 WithdrawMoney: (s, cmd) =>
72 s._tag !== "Open"
73 ? new NotOpen()
74 : cmd.amount > s.balance
75 ? new InsufficientFunds({ balance: s.balance, requested: cmd.amount })
76 : [new MoneyWithdrawn({ amount: cmd.amount, balanceAfter: s.balance - cmd.amount })],
77 ```
78
79 Read it as the business rule it is: an account that isn't open can't be withdrawn from; a withdrawal can't exceed the balance; otherwise, the money is withdrawn and here's the new balance.
80
81 `decide` doesn't change the state. It only describes what should happen. That keeps every rule in a function you can test with a state and a command, and nothing else.
82
83 A handler can also return an empty array. The command is accepted, but there's nothing to record, like freezing an account that's already frozen. The caller still gets a receipt.
84
85 So every handler picks one of three answers. Record events when the command changes something. Return `[]` when the state already is what the command asks for. Return a rejection when the command can't be done, so the caller sees why in its type.
86
87 ## Name the rules decide shares
88
89 Most commands check the same thing first: the account must be open. Write that check once, as a pure function that returns the narrowed state or the rejection.
90
91 ```typescript title="src/Account.aggregate.ts"
92 type Open = Extract<State, { _tag: "Open" }>;
93
94 const openFor = (s: State): Open | NotOpen => (s._tag === "Open" ? s : new NotOpen());
95 ```
96
97 Each handler starts from it. After the check, `o` is an `Open` account, so the rest of the rule reads its balance without another test.
98
99 ```typescript title="src/Account.aggregate.ts"
100 DepositMoney: (s, cmd) => {
101 const o = openFor(s);
102 if (o._tag !== "Open") return o;
103 return [new MoneyDeposited({ amount: cmd.amount, balanceAfter: o.balance + cmd.amount })];
104 },
105 ```
106
107 A handler written with `Effect.fn` fails with the rejection instead: `if (o._tag !== "Open") return yield* o;`.
108
109 ## Record the facts evolve needs
110
111 An event carries the outcome `decide` worked out, not just the request. `MoneyDeposited` records `balanceAfter`, so `evolve` copies it and never repeats the arithmetic.
112
113 ```typescript title="src/DepositMoney.command.ts"
114 export class MoneyDeposited extends Domain.Event("MoneyDeposited", {
115 amount: Schema.Int,
116 balanceAfter: Schema.Int,
117 }) {}
118 ```
119
120 The rules then live in one place. A view or a policy reading the event sees the same balance the account does.
121
122 ## Apply events with evolve
123
124 `evolve` has one handler per event. It receives the current state and the event, and returns the next state.
125
126 ```typescript title="src/Account.aggregate.ts"
127 evolve: {
128 AccountOpened: (_, e) => ({ _tag: "Open" as const, owner: e.owner, balance: 0 }),
129 MoneyDeposited: (s, e) => (s._tag === "Open" ? { ...s, balance: e.balanceAfter } : s),
130 MoneyWithdrawn: (s, e) => (s._tag === "Open" ? { ...s, balance: e.balanceAfter } : s),
131 },
132 ```
133
134 Keeping `evolve` separate from `decide` is what lets the state be derived from events. `decide` runs once, when the command arrives, and may refuse. `evolve` must always accept, because it applies events that have already been recorded, and applying the same events must always give the same state.
135
136 `evolve` never fails either, and never throws. Refusing is `decide`'s job: every command that records `MoneyDeposited` has already returned `NotOpen` for an account that isn't open. So each handler covers every state, and keeps a state its event can't follow. An event that moves the account to another stage, like `AccountOpened`, returns the new state whole.
137
138 ## Reply from the new state
139
140 A command that declares a `reply` gets one from a `reply` handler. It runs after `evolve`, on the state the events produced.
141
142 ```typescript title="src/Account.aggregate.ts"
143 reply: {
144 DepositMoney: (s) => ({ balance: s._tag === "Open" ? s.balance : 0 }),
145 WithdrawMoney: (s) => ({ balance: s._tag === "Open" ? s.balance : 0 }),
146 },
147 ```
148
149 Like `evolve`, `reply` covers every state and never fails. The reply is stored with the events, so a retried command returns the same reply as the first time.
150
151 ## Focus on a state with optics
152
153 Once many handlers repeat the same `s._tag === "Open" ? ... : s`, an optic from `effect/Optic` can say it once. It focuses on the `Open` state, and leaves any other state unchanged.
154
155 ```typescript title="src/Account.aggregate.ts"
156 import * as Optic from "effect/Optic";
157
158 const open = Optic.id<State>().tag("Open");
159 const balance = open.key("balance");
160 ```
161
162 A handler that sets one field replaces it through the optic.
163
164 ```typescript title="src/Account.aggregate.ts"
165 MoneyDeposited: (s, e) => Optic.replace(s, balance, e.balanceAfter),
166 ```
167
168 A handler that changes several fields modifies the focused state.
169
170 ```typescript title="src/Account.aggregate.ts"
171 OwnerChanged: (s, e) => open.modify((o) => ({ ...o, owner: e.owner }))(s),
172 ```
173
174 Optics are optional. They give the same states as the plain checks, with less repetition. The [example bank](https://github.com/alchemy-run/alchemy/tree/main/examples/cloudflare-domain) uses them for its account.
175
176 ## Never refuse a compensation
177
178 Some commands undo a step another process already took, like refunding a transfer whose credit failed. Refusing one would strand the money, so its handler records a fact for every state instead of rejecting.
179
180 ```typescript title="packages/domain/src/Account/Account.aggregate.ts"
181 RefundTransfer: (s, cmd) =>
182 s._tag === "Open"
183 ? [
184 new TransferRefunded({
185 transferId: cmd.transferId,
186 amount: cmd.amount,
187 balanceAfter: s.balance + cmd.amount,
188 }),
189 ]
190 : [new RefundStranded({ transferId: cmd.transferId, amount: cmd.amount })],
191 ```
192
193 `RefundStranded` tells a policy or a person that the account closed before the money came back. The [saga](/domain/saga) that sent the refund never has to handle a refusal it can do nothing about.
194
195 ## Use context in decisions
196
197 Some rules need more than the state and the command. Only the account's owner may withdraw from it, so `decide` needs to know who's asking.
198
199 A command's [middleware](/domain/sessions) can provide that. When it does, the handler can be an `Effect.fn` and read it. In the example bank, the withdrawal handler first checks that the current actor may act on the account.
200
201 ```typescript title="packages/domain/src/Account/Account.aggregate.ts"
202 const authorized = Effect.fn(function* (s: AccountState) {
203 const o = openFor(s, yield* CurrentActor);
204 if (o._tag !== "Open") return yield* o;
205 return o;
206 });
207 ```
208
209 Rules can depend on time, too. The handler's third argument carries `now`, the time the command is decided. The example bank uses it for a daily withdrawal limit:
210
211 ```typescript title="packages/domain/src/Account/Account.aggregate.ts"
212 const used = o.today.day === dayOf(now) ? o.today.withdrawn : 0;
213 if (used + cmd.amount > DAILY_LIMIT)
214 return yield* new DailyLimitExceeded({ remaining: DAILY_LIMIT - used });
215 ```
216
217 `now` is the time the command is stamped with, and its events record the same time as `at` in their envelopes, which is what `evolve` uses to track the day's total. A [story](/domain/story) can move the clock, so rules like this are testable.
218
219 ## One command at a time
220
221 Each instance processes one command at a time. When two withdrawals for the same account arrive together, the second is decided against the state the first one left. Both can't pass the balance check on the same money.
222
223 <DAG
224 nodes={[
225 { id: "first", label: "WithdrawMoney 80", type: "arrives first", layer: 0, kind: "command" },
226 { id: "second", label: "WithdrawMoney 80", type: "arrives second", layer: 0, kind: "command" },
227 { id: "account", label: "Account a-1", type: "balance: 100", layer: 1, kind: "aggregate" },
228 { id: "ok", label: "MoneyWithdrawn", type: "balance: 20", layer: 2, kind: "event" },
229 { id: "no", label: "InsufficientFunds", type: "balance: 20", layer: 2, kind: "rejection" },
230 ]}
231 edges={[
232 { from: "first", to: "account" },
233 { from: "second", to: "account" },
234 { from: "account", to: "ok" },
235 { from: "account", to: "no" },
236 ]}
237 caption="The second withdrawal is decided against the balance the first one left."
238 />
239
240 Everything a command produces, its events, the new state, the reply and the deliveries to views and policies, commits together or not at all. This is what makes an instance a consistency boundary: its rules hold at every moment, for every observer.
241
242 Nothing spans two instances. A transfer between accounts can't debit one and credit the other in a single step, because they're separate boundaries. Instead, each account handles its own side, and a [saga](/domain/saga) drives the steps in order.
243
244 That shapes how big an aggregate should be. Draw it around the rules that must hold together, and no wider. A customer and their accounts are separate aggregates: no rule needs a customer's name and an account's balance to change in the same step, and keeping them apart means one busy account never slows down the others.
245
246 ## Give a rule across instances its own aggregate
247
248 Some rules span many instances. Usernames must be unique across every customer, but each customer is its own aggregate, and no customer can see the others. Making `Customer` check every other customer would need a transaction across all of them, which doesn't exist.
249
250 The answer is to ask what the rule is about. Uniqueness is about one username, so make the username the aggregate. `UsernameClaim` is keyed by the username itself, and holds who has it:
251
252 ```typescript title="packages/domain/src/Customer/UsernameClaim.aggregate.ts"
253 export class UsernameClaim extends Domain.Aggregate("UsernameClaim", {
254 id: Username,
255 state: Schema.Union([
256 Schema.TaggedStruct("Free", {}),
257 Schema.TaggedStruct("Claimed", { customerId: CustomerId }),
258 ]),
259 initial: { _tag: "Free" },
260 commands: [ClaimUsername],
261 decide: {
262 ClaimUsername: (s, cmd) =>
263 s._tag === "Free"
264 ? [new UsernameClaimed({ customerId: cmd.customerId })]
265 : s.customerId === cmd.customerId
266 ? []
267 : new UsernameTaken(),
268 },
269 evolve: {
270 UsernameClaimed: (_, e) => ({ _tag: "Claimed" as const, customerId: e.customerId }),
271 },
272 }) {}
273 ```
274
275 Two customers who ask for `sam` at the same moment both send `ClaimUsername` to the same instance, `UsernameClaim/sam`. It decides one at a time, so one wins and the other is told `UsernameTaken`. The rule holds without anything spanning two aggregates. See [Unique values](/domain/unique-values).
276
277 ## Keep a process's state in an aggregate
278
279 A process that takes time, like a transfer that may wait a day for approval, has state of its own: requested, awaiting approval, completed, failed. Rules apply to that state too. An approval that arrives after the deadline must be refused, and an expiry that arrives after an approval must do nothing.
280
281 Those rules make the process an aggregate. In the example bank, `Transfer` holds where each transfer stands, and both `ApproveTransfer` and `ExpireTransfer` go through it, so whichever arrives first wins:
282
283 ```typescript title="packages/domain/src/Transfer/Transfer.aggregate.ts"
284 ExpireTransfer: (s, _, { id }) =>
285 s._tag === "AwaitingApproval"
286 ? [new TransferFailed({ transferId: id, reason: "not approved in time" })]
287 : [],
288 ```
289
290 The money itself still moves through the two accounts, each guarding its own balance. A [saga](/domain/saga) carries out the steps, and reports each outcome back to the `Transfer`, so there's one place that knows how every transfer ended.
291
292 ## Send it commands
293
294 Inside a hosted model, the aggregate is a service. `yield* Account` gives you its client, and `send` takes an instance id and a command.
295
296 ```typescript title="src/MainAccountProvisioning.policy.ts"
297 yield* accounts
298 .send(AccountId.make(`${source.id}-main`), new OpenAccount({ owner: source.id }))
299 .pipe(Effect.catchTag("AlreadyOpen", () => Effect.void));
300 ```
301
302 The same client reads an instance's current state with `accounts.state(id)`, schedules a command for later with `accounts.schedule(id, command, { after })`, which returns the command id and when it's due, and cancels a pending one with `accounts.unschedule(id, commandId)`. Both fail with `AlreadyExecuted` when that command already ran, and `unschedule` fails with `AlreadyCancelled` or `NotScheduled` when there's nothing pending to cancel. See [Deadlines](/domain/deadlines).
303
304 Clients outside the model send commands through an [Api](/domain/api). An aggregate with a `read` contract can also be read through one, so a client can fetch an account, watch it change, and follow its events.
305
306 Next, [View](/domain/view): the query side, built from the events aggregates record.