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

main
mdx 263 lines 14 KB
Raw
1 ---
2 title: View
3 description: How a view folds events into a read model per key, emits events of its own, combines other views, and serves reads.
4 ---
5
6 import DAG from "../../../components/DAG.astro";
7
8 A view answers a question: what's the balance of this account, what's on its statement, what does this customer hold across all their accounts. It reads events, folds them into state, and keeps that state current as new events arrive.
9
10 Aggregates hold only what their rules need. Views hold everything people want to see, each shaped for one question. This chapter starts with why the two are kept apart and how to design a view from a screen, then builds views up from the simplest case.
11
12 ## Deciding and answering need different shapes
13
14 An account needs exactly three things to decide a withdrawal: whether it's open, who owns it, and its balance. A customer's app needs much more. It shows a statement, line by line. It shows a dashboard with every account the customer holds. A support agent sees an account's freezes, closures and owner changes, and a fraud check needs today's total withdrawals.
15
16 Putting all of that in the `Account` aggregate would make every rule harder to read, and every new screen a change to the code that guards the money. So the model keeps them apart. Aggregates are the **write side**, holding just what their rules need. Views are the **read side**: as many as there are questions, each built from the same events and shaped for the question it answers.
17
18 <DAG
19 nodes={[
20 { id: "account", label: "Account", type: "open, owner, balance", kind: "aggregate", layer: 0 },
21 { id: "events", label: "Events", type: "the shared record", kind: "event", layer: 1 },
22 { id: "summary", label: "AccountSummary", type: "the balance now", kind: "view", layer: 2 },
23 { id: "statement", label: "Statement", type: "one line per movement", kind: "view", layer: 2 },
24 { id: "outflow", label: "DailyOutflow", type: "today's withdrawals", kind: "view", layer: 2 },
25 ]}
26 edges={[
27 { from: "account", to: "events" },
28 { from: "events", to: "summary", dashed: true },
29 { from: "events", to: "statement", dashed: true },
30 { from: "events", to: "outflow", dashed: true },
31 ]}
32 caption="One aggregate, many views. Adding a view never touches a rule."
33 />
34
35 ## Design a view from its question
36
37 Start from the screen, not from the events. Write down the question it answers and the data it shows: "what's on this account's statement?" needs a list of lines, each with a kind, an amount and the balance after. Then decide what one instance of the view is about. A statement is about one account, so it's keyed by account. A dashboard is about one customer, so it's keyed by customer.
38
39 Last, work backwards to the events that change that data. A statement line comes from each deposit and each withdrawal. If the data a screen needs isn't in any event, that's worth noticing: either the event is missing a fact the business cares about, or the screen is asking for something the business never recorded.
40
41 ## Fold one aggregate's events
42
43 The simplest view follows one aggregate. `AccountSummary` reads the account's events and keeps its owner and balance.
44
45 ```typescript title="src/AccountSummary.view.ts"
46 export class AccountSummary extends Domain.View("AccountSummary", {
47 from: [Account],
48 key: Account,
49 state: Schema.Struct({ owner: Schema.NullOr(Schema.String), balance: Schema.Int }),
50 initial: { owner: null, balance: 0 },
51 evolve: {
52 AccountOpened: (v, e) => ({ ...v, owner: e.owner }),
53 MoneyDeposited: (v, e) => ({ ...v, balance: e.balanceAfter }),
54 MoneyWithdrawn: (v, e) => ({ ...v, balance: e.balanceAfter }),
55 },
56 }) {}
57 ```
58
59 `from` lists where its events come from. `key` says what one instance of the view is about: here, one account. So every account gets its own summary, and an event from account `a-1` updates only the summary for `a-1`.
60
61 <DAG
62 nodes={[
63 { id: "a1", label: "Account a-1", type: "aggregate", kind: "aggregate" },
64 { id: "a2", label: "Account a-2", type: "aggregate", kind: "aggregate" },
65 { id: "s1", label: "Summary a-1", type: "AccountSummary", kind: "view" },
66 { id: "s2", label: "Summary a-2", type: "AccountSummary", kind: "view" },
67 ]}
68 edges={[
69 { from: "a1", to: "s1", dashed: true },
70 { from: "a2", to: "s2", dashed: true },
71 ]}
72 caption="One summary per account, each fed by that account's events."
73 />
74
75 `evolve` works like an aggregate's: one handler per event, returning the next state. A view only handles the events it names. The rest pass it by, so adding an event to the account never breaks a view that doesn't care about it.
76
77 ## Views catch up after the commit
78
79 A view is never updated in the same step as the aggregate. The account commits its events first, then they're delivered to the view. Each view receives every event it reads at least once, in the order each source recorded them, and drops any it has already applied.
80
81 So a view is always correct, but it can be a moment behind. Most screens never notice. One that has just sent a command and wants to show its result waits for the view to catch up, using the command's receipt.
82
83 ```typescript title="packages/server/test/depositThenRead.ts"
84 export const depositThenRead = Effect.fn(function* (bank: CustomerClient, accountId: AccountId) {
85 const receipt = yield* bank.DepositMoney(accountId, { amount: 500 });
86 const summary = yield* bank.AccountSummary.get(accountId, {
87 atLeast: { stream: receipt.stream, version: receipt.version },
88 });
89 return summary?.balance;
90 });
91 ```
92
93 `atLeast` makes `get` wait until the summary has applied that version of the account's stream. If it hasn't within 10 seconds, the read fails with `ConsistencyTimeout`.
94
95 A view added to a model that already has events receives them first, so a new screen starts from the whole history (see [Consumers added later receive the history](/domain/model#consumers-added-later-receive-the-history)).
96
97 ## Emit events of your own
98
99 A view can record events as it folds, which is how you build lists like a statement. Instead of `evolve`, `Statement` has `emit`: for each deposit or withdrawal, it records one `StatementLine`.
100
101 ```typescript title="src/Statement.view.ts"
102 export class Statement extends Domain.View("Statement", {
103 from: [Account],
104 key: Account,
105 events: [StatementLine],
106 emit: {
107 MoneyDeposited: (e) =>
108 new StatementLine({ kind: "deposit", amount: e.amount, balance: e.balanceAfter }),
109 MoneyWithdrawn: (e) =>
110 new StatementLine({ kind: "withdrawal", amount: e.amount, balance: e.balanceAfter }),
111 },
112 }) {}
113 ```
114
115 `StatementLine` is shaped for the reader, not the account. A client lists the lines a page at a time, or follows them live.
116
117 A view that declares no `events` emits every event it applies, each paired with its state after that event. That makes any view a source for another.
118
119 ## Build on other views
120
121 A customer's dashboard shows every account they own, with each balance. No single account knows that, and the customer aggregate doesn't track balances. But `AccountSummary` already knows each account's balance and owner, so the dashboard reads from it.
122
123 <DAG
124 nodes={[
125 { id: "a1", label: "Summary a-1", type: "AccountSummary", kind: "view" },
126 { id: "a2", label: "Summary a-2", type: "AccountSummary", kind: "view" },
127 { id: "c", label: "Customer c-1", type: "aggregate", kind: "aggregate" },
128 { id: "d", label: "Dashboard c-1", type: "CustomerDashboard", kind: "view" },
129 ]}
130 edges={[
131 { from: "a1", to: "d", dashed: true },
132 { from: "a2", to: "d", dashed: true },
133 { from: "c", to: "d", dashed: true },
134 ]}
135 caption="The dashboard is keyed by customer and fed by every summary that customer owns."
136 />
137
138 The dashboard is keyed by customer, but a summary's events come from accounts. `keyOf` tells the view which customer each one belongs to, using the summary's state after the event.
139
140 ```typescript title="packages/domain/src/Customer/CustomerDashboard.view.ts"
141 keyOf: {
142 AccountSummary: ({ state }) => (state?.customerId ? Customer.ref(state.customerId) : undefined),
143 ```
144
145 Returning `undefined` means the event belongs to no dashboard, like a summary for an account that hasn't been opened yet. The handler for those events receives the same state, and records that account's balance.
146
147 ```typescript title="packages/domain/src/Customer/CustomerDashboard.view.ts"
148 AccountSummary: (d, _, { source, state }) => ({
149 ...d,
150 balances:
151 state && !state.closed
152 ? { ...d.balances, [source.id]: state.balance }
153 : without(d.balances, source.id),
154 }),
155 ```
156
157 ## Key a view by a value
158
159 Some read models are about something the model has no aggregate for, like an organization that owns many accounts. Key the view by a string Schema instead of an aggregate. Each value gets its own instance, and `keyOf` returns the value itself, not a ref.
160
161 ```typescript
162 export const OrgId = Schema.String.pipe(Schema.brand("OrgId"));
163
164 export class OrgSchedule extends Domain.View("OrgSchedule", {
165 from: [Tour],
166 key: OrgId,
167 keyOf: { Tour: ({ event }) => event.orgId },
168 state: Schema.Struct({ tours: Schema.Record(Schema.String, Schema.String) }),
169 initial: { tours: {} },
170 evolve: {
171 TourBooked: (s, e, { source }) => ({ tours: { ...s.tours, [source.id]: e.unit } }),
172 },
173 }) {}
174 ```
175
176 Reads take the value too: `schedules.watch(orgId)`, `client.OrgSchedule.get(orgId)`, and `Story.view(OrgSchedule, orgId, ...)`. In handlers, `key` is the value, and a view, policy or projection that consumes this view gets it as `source`. Policies, projections and streams take a Schema `key` the same way. A view keyed by the same Schema follows this one without `keyOf`, so use a branded Schema to keep different kinds of ids apart.
177
178 ## Route one event to several keys
179
180 Some events matter to more than one key. A transfer request names two accounts, and both of their transfer histories should show it, one as money out and one as money in.
181
182 `keyOf` can return named routes. Each route picks a key, and each has its own handler.
183
184 ```typescript title="packages/domain/src/Transfer/AccountTransfers.view.ts"
185 keyOf: {
186 TransferRequested: {
187 out: ({ event }) => Account.ref(event.from),
188 in: ({ event }) => Account.ref(event.to),
189 },
190 },
191 events: [TransferMoved],
192 emit: {
193 TransferRequested: { out: moved("out"), in: moved("in") },
194 },
195 ```
196
197 One `TransferRequested` updates both accounts: the sender's as `out` and the recipient's as `in`.
198
199 ## Read it
200
201 Through an [Api](/domain/api), a view offers these reads for one key. `get` returns its current state, or `null` if nothing has happened to that key yet. `list` returns a page of its emitted events. `watch` streams the state now and after every change, each with its cursor. `events` streams its emitted events: history first, then a `CaughtUp` frame, then new ones as they're recorded. `snapshot` returns the state with the cursor it is valid at.
202
203 ```typescript title="packages/server/test/statementPage.ts"
204 export const statementPage = Effect.fn(function* (bank: CustomerClient, accountId: AccountId) {
205 const page = yield* bank.Statement.list(accountId, { order: "desc", take: 10 });
206 return page.entries.map(({ event }) => `${event.kind} ${event.amount}`);
207 });
208 ```
209
210 A `where` filter narrows any read, like only deposits over a threshold. A filter can only narrow what you're already allowed to read; it never grants access.
211
212 ## Know when a live read is current
213
214 `events` sends the key's history, then a `CaughtUp` frame, then new entries as they're recorded. Once `CaughtUp` arrives, the screen shows the key's current state and can stop showing "loading".
215
216 ```typescript
217 yield* bank.Statement.events(accountId).pipe(
218 Stream.runForEach((frame) =>
219 Domain.Read.isCaughtUp(frame) ? markLive(frame.cursor) : addLine(frame),
220 ),
221 );
222 ```
223
224 `Stream.filter(Domain.Read.isEvent)` drops the frame when you don't need it.
225
226 `watch` sends each state with its cursor, `{ state, cursor }`. Pass a cursor as `after` to `events` and the feed starts right after it: nothing arrives twice, and nothing is missed. That's how a screen that rendered a watched state follows the events from there, and how a dropped feed resumes from its last `CaughtUp`. Over `protocolWebSocket`, a read that reconnects sends `CaughtUp` again after the entries it missed.
227
228 ### Render a snapshot, then follow it
229
230 `snapshot` returns a key's state together with its `cursor`: the `seq` of the last event the key had emitted when that state was read. Render the state, then follow `events` from the cursor. Every change after the snapshot arrives once, and none is missed, even when it was written between the two reads:
231
232 ```typescript title="packages/server/test/followSummary.ts"
233 export const followSummary = Effect.fn(function* (
234 bank: CustomerClient,
235 accountId: AccountId,
236 render: (balance: number | undefined) => Effect.Effect<void>,
237 ) {
238 const { state, cursor } = yield* bank.AccountSummary.snapshot(accountId);
239 yield* render(state?.balance);
240 yield* bank.AccountSummary.events(accountId, { after: cursor }).pipe(
241 Stream.filter(Domain.Read.isEvent),
242 Stream.runForEach((entry) => render(entry.state?.balance)),
243 );
244 });
245 ```
246
247 A server can read the snapshot while it renders a page and send it with the page, so the browser shows data at once and starts its feed from the cursor. `snapshot` and `list` take `atLeast`, like `get`: pass a command's `stream` and `version` to wait until the view has applied it.
248
249 ## Decide who may read it
250
251 A view that's exposed through an Api declares `middleware` to identify the caller, and `validate` to judge each read against the view's state.
252
253 ```typescript title="packages/domain/src/Account/AccountSummary.view.ts"
254 validate: Effect.fn(function* (_request, summary) {
255 yield* mustOwn(summary?.customerId ?? null);
256 }),
257 ```
258
259 `validate` runs on every read, and again on every change while a client watches. If an account changes owner, the previous owner's watch ends with `NotOwner`. See [Views as security boundaries](/domain/view-security).
260
261 Every key keeps an input log: each delivery it applied, in order, kept for good. A view's state is a fold of that log.
262
263 Next, [Projection](/domain/projection): a read model in a store you own, when a view's built-in store isn't the right one.