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

main
mdx 264 lines 14.5 KB
Raw
1 ---
2 title: Policy
3 description: How a policy reacts to events with commands and calls to outside systems, and how to make it safe to run more than once.
4 ---
5
6 import DAG from "../../../components/DAG.astro";
7
8 A policy is one of the business's standing rules about what to do when something happens. In the example bank, whenever a customer registers, their main account is opened, and whenever an account's withdrawals for the day cross a threshold, it's scored for fraud and frozen if the risk is high.
9
10 The name comes from business policy, and that's the point: a policy doesn't just react, it decides. It's triggered by an event, works out whether and how to act, and acts by sending commands to aggregates or calling systems outside the model.
11
12 That's a different kind of rule from an aggregate's. An aggregate enforces invariants, which must hold the instant a command commits and can refuse it. A policy applies a procedure, which runs after the event and decides what happens next. This chapter covers how to find the policies in a business, how to declare and implement one, and the one property every policy must have, which is that running it twice does no harm.
13
14 ## Find the policies in your business
15
16 Policies hide in sentences that start with "whenever" or "when … then". Whenever a customer registers, open their main account. When money settles on a closed account, refund it. When a large transfer is requested, wait for an agent to approve it. People in the business say these all the time, often as "we always …" or "the rule is that …".
17
18 Each sentence has two halves. The "whenever" names an event, which is what the policy listens for. The "then" names what the business does next, which becomes a command to an aggregate or a call to a system outside the model. Between them sits whatever judgment the business applies: the fraud rule only freezes an account when the score is high.
19
20 <DAG
21 nodes={[
22 { id: "event", label: "Whenever …", type: "CustomerRegistered", kind: "event", layer: 0 },
23 { id: "policy", label: "the rule", type: "open a main account", kind: "policy", layer: 1 },
24 { id: "command", label: "… then", type: "OpenAccount", kind: "command", layer: 2 },
25 ]}
26 edges={[
27 { from: "event", to: "policy", dashed: true },
28 { from: "policy", to: "command" },
29 ]}
30 caption="A policy is a sentence the business already says, written as code."
31 />
32
33 Writing these down as policies, instead of burying them in the code that handles a request, keeps them visible. The registration command only registers. The rule about main accounts has its own name, its own file and its own tests, and changing it touches nothing else.
34
35 ## Policy or invariant?
36
37 Before you write a policy, check that the rule can tolerate a delay. A policy runs shortly after the event, so there's always a moment when the event has happened and the policy hasn't acted yet.
38
39 "Open a main account for every new customer" is fine with that: for a moment, a customer has no account. "A frozen account can't be withdrawn from" isn't. If a policy enforced it, a withdrawal could slip through between the freeze and the policy noticing. Rules that must hold at every instant are invariants, and they belong in an aggregate's `decide`. Rules about what happens next are policies.
40
41 ## Declare what triggers it
42
43 A policy names its source, an aggregate or a view, and the events from it that it reacts to.
44
45 ```typescript title="src/MainAccountProvisioning.policy.ts"
46 export class MainAccountProvisioning extends Domain.Policy("MainAccountProvisioning", {
47 from: Customer,
48 on: [CustomerRegistered],
49 }) {}
50 ```
51
52 The declaration is all the model needs to deliver the right events. Add it to the model's `policies`.
53
54 `from` can also list several sources. Each source's events still arrive in that source's order, but there is no order between them: see [Partition it by key](#partition-it-by-key).
55
56 ## Implement it as a Layer
57
58 The implementation is separate from the declaration, because it usually depends on things outside the model's definition: a client for another aggregate, a payment provider, a fraud service. `toLayer` takes an Effect that resolves those once, and returns the handler that runs for each event.
59
60 ```typescript title="src/MainAccountProvisioning.policy.ts"
61 export const MainAccountProvisioningLive = MainAccountProvisioning.toLayer(
62 Effect.gen(function* () {
63 const accounts = yield* Account;
64 return Effect.fn(function* ({ source }) {
65 yield* accounts
66 .send(AccountId.make(`${source.id}-main`), new OpenAccount({ owner: source.id }))
67 .pipe(Effect.catchTag("AlreadyOpen", () => Effect.void));
68 });
69 }),
70 );
71 ```
72
73 The handler receives the event and its `source`, the instance that recorded it. Here the source is the customer who registered, and the policy opens an account whose id is derived from theirs.
74
75 You pass the implementation to the model when you run it: `Bank.layer(BankHandlers)`. See [Domain Model](/domain/model#declare-the-model).
76
77 <DAG
78 nodes={[
79 { id: "customer", label: "Customer c-1", type: "aggregate", kind: "aggregate" },
80 { id: "policy", label: "policy", type: "on CustomerRegistered", kind: "policy" },
81 { id: "account", label: "Account c-1-main", type: "OpenAccount", kind: "aggregate" },
82 ]}
83 edges={[
84 { from: "customer", to: "policy", dashed: true },
85 { from: "policy", to: "account" },
86 ]}
87 caption="The registration commits first. The policy runs shortly after and opens the account."
88 />
89
90 ## It runs after the commit
91
92 A policy never runs in the same step as the event it reacts to. The customer's registration commits on its own; then the event is delivered to the policy, which sends a separate command to a separate aggregate.
93
94 So there's a moment when the customer exists and their account doesn't yet. That's fine for opening an account, and it's the only way to coordinate two aggregates, since each is its own consistency boundary. It's not fine for a rule that must hold the instant a command commits, like "a frozen account can't be withdrawn from". That rule belongs in the aggregate's `decide`, even when it's about the aggregate's own events. See [Aggregate](/domain/aggregate#one-command-at-a-time).
95
96 <DAG
97 nodes={[
98 { id: "c1", label: "commit 1", type: "Customer c-1", layer: 0, kind: "aggregate" },
99 { id: "policy", label: "policy", type: "MainAccountProvisioning", layer: 1, kind: "policy" },
100 { id: "c2", label: "commit 2", type: "Account c-1-main", layer: 2, kind: "aggregate" },
101 ]}
102 edges={[
103 { from: "c1", to: "policy", dashed: true },
104 { from: "policy", to: "c2" },
105 ]}
106 caption="Two commits, in two aggregates. Between them, the customer exists and the account doesn't yet."
107 />
108
109 ## Make it safe to run twice
110
111 Every event reaches every policy that reacts to it, in order for each source instance, even across restarts. To guarantee that, the model may deliver an event more than once: if a handler fails or the host restarts midway, it's run again.
112
113 Two things make a second run harmless. First, every command a policy sends gets an id derived from the event that caused it. A second run sends the same command with the same id, and the aggregate returns the receipt it stored the first time instead of deciding again. See [Command](/domain/command#send-it-exactly-once).
114
115 Second, a policy handles the rejections it expects from a repeat. Opening an account that's already open is refused with `AlreadyOpen`, so the policy treats that as done:
116
117 ```typescript title="src/MainAccountProvisioning.policy.ts"
118 .pipe(Effect.catchTag("AlreadyOpen", () => Effect.void));
119 ```
120
121 Calls to outside systems need the same care. Pass them an idempotency key derived from the event, so the payment provider charges once however many times it's asked.
122
123 ## Partition it by key
124
125 By default, a policy is partitioned by source instance: everything one customer records is handled in order, one event at a time, and different customers run in parallel.
126
127 When a rule spans several sources, choose the partition yourself with `key`, and route each event to it with `keyOf`, exactly as a view does. Here one welcome flow per customer hears both the registration and every account the customer opens, in one ordered queue.
128
129 ```typescript title="src/Welcome.policy.ts"
130 export class Welcome extends Domain.Policy("Welcome", {
131 from: [Customer, Account],
132 key: Customer,
133 keyOf: {
134 AccountOpened: ({ event }) => Customer.ref(CustomerId.make(event.owner)),
135 },
136 on: [CustomerRegistered, AccountOpened],
137 }) {}
138 ```
139
140 `CustomerRegistered` comes from a customer, so it needs no route. `AccountOpened` comes from an account, so `keyOf` names the customer it belongs to. The handler receives that customer as `key`.
141
142 <DAG
143 nodes={[
144 { id: "customer", label: "Customer c-1", type: "CustomerRegistered", kind: "aggregate", layer: 0 },
145 { id: "account", label: "Account c-1-main", type: "AccountOpened", kind: "aggregate", layer: 0 },
146 { id: "policy", label: "Welcome c-1", type: "one ordered queue", kind: "policy", layer: 1 },
147 ]}
148 edges={[
149 { from: "customer", to: "policy", dashed: true },
150 { from: "account", to: "policy", dashed: true },
151 ]}
152 caption="Two sources, one partition per customer. Within it, events from different sources have no order between them."
153 />
154
155 `key` can also be a string Schema, such as an org id. `keyOf` then returns the value, and the handler gets it as `key`.
156
157 ```typescript
158 export class OrgLimits extends Domain.Policy("OrgLimits", {
159 from: Account,
160 key: OrgId,
161 keyOf: { MoneyWithdrawn: ({ event }) => event.orgId },
162 on: [MoneyWithdrawn],
163 }) {}
164 ```
165
166 The key is also the policy's unit of concurrency. Pick the narrowest thing whose events must be handled in sequence: everything for one key runs one at a time, and more keys mean more parallelism.
167
168 ## Tune it on its Layer
169
170 What a policy means lives on its declaration. How it runs lives on its Layer. `toLayer` takes options, such as a retry schedule for a run that fails before the platform's own redelivery takes over.
171
172 ```typescript title="src/Welcome.policy.ts"
173 export const WelcomeLive = Welcome.toLayer(
174 Effect.succeed(
175 Effect.fn(function* ({ key, event }) {
176 yield* Effect.log(`welcome ${key.id}: ${event._tag}`);
177 }),
178 ),
179 { retry: Schedule.exponential("1 second").pipe(Schedule.upTo({ duration: "1 minute" })) },
180 );
181 ```
182
183 ## React to a view
184
185 A policy can listen to a view as well as an aggregate. That lets it react to patterns no single event shows.
186
187 The example bank wants to review an account when its withdrawals for one day add up past a threshold, even if each one is small. No withdrawal event says that. So a view, `DailyOutflow`, keeps a running total per account per day, and emits `DailyOutflowExceeded` when the total crosses the line. The policy listens for that.
188
189 ```typescript title="packages/domain/src/Fraud/FraudReview.policy.ts"
190 export class FraudReview extends Domain.Policy("FraudReview", {
191 from: DailyOutflow,
192 on: [DailyOutflowExceeded],
193 }) {}
194 ```
195
196 <DAG
197 nodes={[
198 { id: "account", label: "Account a-1", type: "aggregate", kind: "aggregate" },
199 { id: "outflow", label: "DailyOutflow a-1", type: "view", kind: "view" },
200 { id: "review", label: "FraudReview", type: "policy", kind: "policy" },
201 { id: "check", label: "FraudCheck", type: "external system", kind: "external" },
202 { id: "freeze", label: "FreezeAccount", type: "command", kind: "command" },
203 ]}
204 edges={[
205 { from: "account", to: "outflow", dashed: true },
206 { from: "outflow", to: "review", dashed: true },
207 { from: "review", to: "check" },
208 { from: "review", to: "freeze" },
209 ]}
210 caption="DailyOutflow emits DailyOutflowExceeded; FraudReview scores the account and freezes it if it's risky."
211 />
212
213 ## Call an external system
214
215 To decide whether the account is risky, the policy asks a fraud-scoring service. It doesn't call a vendor's SDK directly. It depends on a `Domain.ExternalSystem`, which names the outside system and the calls the model makes to it.
216
217 ```typescript title="packages/domain/src/Fraud/FraudCheck.external.ts"
218 export class FraudCheck extends Domain.ExternalSystem("FraudCheck", {
219 score: { args: { accountId: AccountId, amount: Cents }, success: { risk: Schema.Number } },
220 }) {}
221 ```
222
223 The policy resolves it like any other service, then calls it per event.
224
225 ```typescript title="packages/domain/src/Fraud/FraudReview.policy.ts"
226 const fraud = yield* FraudCheck;
227 const accounts = yield* Account;
228 return Effect.fn(function* ({ source, event }) {
229 const { risk } = yield* fraud.score({ accountId: source.id, amount: event.total });
230 ```
231
232 An external system is implemented by a Layer, so production can use the vendor's HTTP API while a test uses something else. In a [story](/domain/story), each call waits until the test answers it, so you can check what the policy does with every possible answer. See [External System](/domain/external-system).
233
234 ## Act as the system
235
236 Commands sent by people pass through middleware that says who they are. A policy has no caller, so when a command's `decide` needs to know who's acting, the policy says so itself.
237
238 ```typescript title="packages/domain/src/Fraud/FraudReview.policy.ts"
239 yield* accounts.send(source, new FreezeAccount({ reason: `fraud risk ${risk}` })).pipe(
240 Effect.provideService(CurrentActor, system("FraudReview")),
241 ```
242
243 The freeze is then recorded as done by `FraudReview`, so the account's history says why it was frozen and by what.
244
245 ## Chain policies into a process
246
247 One policy covers one reaction, and it should stay small: hear one kind of event, decide one thing, send one command or make one call. When you find a policy waiting for a second event, tracking how far along something is, or undoing what it did earlier, it has grown into a process. A process with several steps, like a transfer that debits one account, credits another, and refunds the first if the second fails, is a [saga](/domain/saga). The policy stays small: it hears that a transfer was requested and starts the saga.
248
249 <DAG
250 nodes={[
251 { id: "requested", label: "Transfer t-1", type: "TransferRequested", layer: 0, kind: "aggregate" },
252 { id: "debit", label: "Account a-1", type: "DebitTransfer", layer: 1, kind: "aggregate" },
253 { id: "credit", label: "Account a-2", type: "CreditTransfer", layer: 2, kind: "aggregate" },
254 { id: "refund", label: "Account a-1", type: "RefundTransfer", layer: 3, kind: "aggregate" },
255 ]}
256 edges={[
257 { from: "requested", to: "debit", dashed: true },
258 { from: "debit", to: "credit", dashed: true },
259 { from: "credit", to: "refund", dashed: true },
260 ]}
261 caption="One process, three steps across two accounts. If the credit is refused, a refund undoes the debit."
262 />
263
264 Next, [Saga](/domain/saga): a process that takes several steps, and undoes them when one fails.