@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 211 lines 10.8 KB
Raw
1 ---
2 title: External System
3 description: Declare the outside systems your model calls in the model's own language, implement them with Layers, and turn their events into commands.
4 ---
5
6 import DAG from "../../../components/DAG.astro";
7
8 An external system is a service outside the model that its policies call, such as a payment processor or a fraud scorer. The model declares the calls it makes, in its own words, with their arguments and results, and nothing about the vendor behind them. A Layer supplies the vendor, so production, tests and stories can each use a different one.
9
10 This chapter starts with why the model keeps outside systems at arm's length, then declares one, implements it, calls it, and turns events from outside into commands.
11
12 ## Keep the outside world at the edge
13
14 Every vendor has its own language. A payment processor talks about payment intents, charges, balance transactions and webhooks. A fraud vendor talks about risk signals and decision codes. None of those words belong to your model. If they leak into the model, the model starts speaking two languages, and changing vendor means rewriting rules.
15
16 DDD's answer is a translation layer at the edge, sometimes called an **anti-corruption layer**. The model says what it needs in its own terms: "refund this settlement", "score this withdrawal". A small adapter outside the model turns that into whatever the vendor's API wants, and turns the vendor's answer back into the model's terms.
17
18 <DAG
19 nodes={[
20 { id: "policy", label: "SettlementRefund", type: "calls refund", kind: "policy", col: 0, row: 0 },
21 { id: "payments", label: "Payments", type: "in the bank's words", kind: "external", col: 1, row: 0 },
22 { id: "stripe", label: "StripePayments", type: "Layer · production", col: 2, row: 0 },
23 { id: "story", label: "Story", type: "you answer each call", col: 2, row: 1 },
24 ]}
25 edges={[
26 { from: "policy", to: "payments" },
27 { from: "payments", to: "stripe" },
28 { from: "payments", to: "story", dashed: true },
29 ]}
30 caption="The model depends on the declaration. Production and tests plug in different implementations."
31 />
32
33 A `Domain.ExternalSystem` is that edge, written down. It names the calls the model makes and nothing else. The example bank declares two: `FraudCheck` and `Payments`.
34
35 It works in the other direction too. News from outside, like a webhook saying a payment settled, crosses the same edge and becomes a command in the model's language.
36
37 ## Declare an external system
38
39 A `Domain.ExternalSystem` lists the calls you make to one outside system, with their arguments and results. It's an Effect service, like a `Context.Service`: policies `yield*` it, and a Layer implements it.
40
41 ```typescript title="packages/domain/src/Settlement/Payments.external.ts"
42 export class Payments extends Domain.ExternalSystem("Payments", {
43 refund: {
44 args: { settlementId: Schema.String, amount: Cents },
45 success: { refundId: Schema.String },
46 },
47 }) {}
48 ```
49
50 Name each call after what the model wants done, not after the vendor endpoint that does it. `refund` is a request in the model's own language. `createRefundForPaymentIntent` would be Stripe's language leaking in.
51
52 Keep the arguments and results to what the model uses. The fraud check returns a risk score, because that's all the fraud policy decides on; the dozens of other fields the vendor sends stay in the adapter.
53
54 ```typescript title="packages/domain/src/Fraud/FraudCheck.external.ts"
55 export class FraudCheck extends Domain.ExternalSystem("FraudCheck", {
56 score: { args: { accountId: AccountId, amount: Cents }, success: { risk: Schema.Number } },
57 }) {}
58 ```
59
60 ## Declare its errors
61
62 When the vendor can refuse, declare the error with `error:`. The call's Effect then fails with that type, so a policy handles it like any typed error.
63
64 ```typescript
65 class RefundDeclined extends Domain.Rejection("RefundDeclined", { reason: Schema.String }) {}
66
67 export class Payments extends Domain.ExternalSystem("Payments", {
68 refund: {
69 args: { settlementId: Schema.String, amount: Cents },
70 success: { refundId: Schema.String },
71 error: RefundDeclined,
72 },
73 }) {}
74 ```
75
76 When the vendor can refuse in several ways, list each error. The call fails with any of them, and a policy handles each one by its tag:
77
78 ```typescript
79 class CardFrozen extends Domain.Rejection("CardFrozen") {}
80
81 export class Payments extends Domain.ExternalSystem("Payments", {
82 refund: {
83 args: { settlementId: Schema.String, amount: Cents },
84 success: { refundId: Schema.String },
85 error: [RefundDeclined, CardFrozen],
86 },
87 }) {}
88 ```
89
90 A `Schema.Union([RefundDeclined, CardFrozen])` declares the same errors.
91
92 Declare the refusals the model has an answer for, in its own words. A declined refund is a business outcome a policy can act on. A timeout or a 500 from the vendor isn't; it's a failure, and the policy that made the call runs again.
93
94 ## Implement it with a Layer
95
96 An adapter is a Layer that implements every call. It's the only code that knows the vendor, so swapping vendor, or using a fake, never touches the model. To prove a fake answers like the vendor, [run the same tests against both](/domain/testing-models#run-the-same-tests-against-every-adapter).
97
98 ```typescript title="packages/server/src/Settlement/StripePayments.ts"
99 export const StripePayments = Payments.toLayer(
100 Effect.succeed({
101 refund: ({ settlementId }) => Effect.succeed({ refundId: `re_${settlementId}` }),
102 }),
103 );
104 ```
105
106 This one is a stand-in. A production adapter calls the vendor's HTTP API, maps its response onto `{ refundId }`, and maps its refusals onto the declared errors.
107
108 Adapters live in the server package, next to the platform, because they reach the network. The domain package only holds the declaration. See [Project layout](/domain/project-layout).
109
110 ## Calls are checked against the schemas
111
112 Every call through a `toLayer` adapter is checked against the operation's schemas: the arguments before the adapter runs, then its success value or error. A value a schema rejects is a defect, an `ExternalSystemSchemaError` that names the system, the operation and the side that broke:
113
114 ```text
115 Payments.refund returned a value its success schema rejects
116 Expected string
117 at ["refundId"]
118 ```
119
120 A policy that sends bad arguments, or an adapter that maps a vendor response wrong, fails at the seam instead of deep inside the model. Fields the success schema doesn't declare are dropped, so the model sees only what it declared. An error the operation doesn't declare is a defect too. An operation without `success` returns the adapter's value as it is.
121
122 Turn the check off for one adapter with `validate: false`, for example when the payload is large and the adapter already validates it:
123
124 ```typescript
125 export const StripePayments = Payments.toLayer(build, { validate: false });
126 ```
127
128 ## Call it from a policy
129
130 A policy uses it like any other service. This one refunds money that settled on an account that had already closed.
131
132 ```typescript title="packages/domain/src/Settlement/SettlementRefund.policy.ts"
133 export const SettlementRefundLive = SettlementRefund.toLayer(
134 Effect.gen(function* () {
135 const payments = yield* Payments;
136 return Effect.fn(function* ({ event }) {
137 yield* payments.refund({ settlementId: event.settlementId, amount: event.amount });
138 });
139 }),
140 );
141 ```
142
143 A policy can run more than once for the same event, so the call it makes can arrive twice. Pass the vendor something that identifies the request, here the `settlementId`, and have the adapter use it as the vendor's idempotency key. However many times it's asked, the money is refunded once. See [Make it safe to run twice](/domain/policy#make-it-safe-to-run-twice).
144
145 Provide the adapters where you host the model, next to the platform: see [Domain Model](/domain/model#run-it).
146
147 ## Turn outside events into commands
148
149 Money arrives from Stripe as webhook events. Each successful payment becomes a `RecordSettlement`, in the model's words. It reports a fact that already happened outside the model, so it declares no rejections.
150
151 ```typescript title="packages/domain/src/Account/RecordSettlement.command.ts"
152 export class RecordSettlement extends Domain.Command("RecordSettlement", {
153 target: AccountId,
154 input: { settlementId: Schema.String, amount: Cents },
155 events: [SettlementReceived, SettlementOnClosedAccount],
156 }) {}
157 ```
158
159 The account can't refuse money that has already settled, so it records what the settlement means for it. An open account records `SettlementReceived` with its new balance. A closed one records `SettlementOnClosedAccount`, and `SettlementRefund` sends the money back.
160
161 The webhook handler is the adapter for this direction. It receives each event, checks its signature, picks out what the model cares about, and sends the command:
162
163 ```typescript title="packages/server/src/Settlement/StripeSettlements.ts"
164 Effect.fn(function* (event) {
165 const intent = event.object;
166 const accountId = intent.metadata?.accountId;
167 if (!accountId) return;
168 yield* accounts.send(
169 AccountId.make(accountId),
170 new RecordSettlement({ settlementId: intent.id, amount: intent.amount_received }),
171 { commandId: `settlement:${intent.id}` },
172 );
173 }),
174 ```
175
176 `Stripe.consumeEvents` receives the webhooks and checks their signatures before this handler runs. The payment's id becomes the command id, so a webhook Stripe delivers twice settles once.
177
178 ## Test external system calls
179
180 In a story, an external system call waits until you answer it. That puts every outcome of the outside world under your control: the refund that succeeds, the one that's declined, and the one whose connection breaks.
181
182 ```typescript title="packages/domain/test/settlements.test.ts"
183 it.effect("money that settles on a closed account is refunded", () =>
184 story(
185 Story.given(
186 account,
187 new AccountOpened({ customerId: CustomerId.make("c-1"), owner: "sam" }),
188 new AccountClosed(),
189 ),
190 Story.when(account, new RecordSettlement({ settlementId: "st_1", amount: 500 })),
191 Story.then(account, new SettlementOnClosedAccount({ settlementId: "st_1", amount: 500 })),
192 Story.call(Payments.refund, { settlementId: "st_1", amount: 500 }),
193 Story.succeed(Payments.refund, { refundId: "re_1" }),
194 ),
195 );
196 ```
197
198 `Story.call` checks what was asked, and must come first; `succeed` answers it. `fail` answers with the operation's declared error instead; see [Fail a call](/domain/testing-models#fail-a-call).
199
200 The story runner lists the systems it fakes in `stub`:
201
202 ```typescript title="packages/domain/test/settlements.test.ts"
203 const story = Story.make(Bank, {
204 layer: BankHandlers.pipe(Layer.provide(MemoryLedgerStore)),
205 stub: [FraudCheck, Payments],
206 });
207 ```
208
209 A system you leave out of `stub` is called for real through the Layer you provide, and the story checks what each call was sent and returned; see [Assert real calls](/domain/testing-models#assert-real-calls). A story fails if any call is left unanswered or unasserted, so every outside call is accounted for.
210
211 Next, [Api](/domain/api): what the model publishes to its own clients.