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

main
ts 455 lines 15.7 KB
Raw
1 import * as Domain from "@alchemy.run/domain";
2 import { InMemory } from "@alchemy.run/domain/InMemory";
3 import { Story } from "@alchemy.run/domain/Story";
4 import { describe, expect, it } from "@alchemy.run/test";
5 import * as Effect from "effect/Effect";
6 import * as Layer from "effect/Layer";
7 import * as Schema from "effect/Schema";
8 import { Activity, DurableClock, DurableDeferred } from "effect/workflow";
9
10 // Wallets that a transfer saga debits and credits.
11 class Opened extends Domain.Event("Opened", { balance: Schema.Number }) {}
12 class Debited extends Domain.Event("Debited", { transfer: Schema.String, amount: Schema.Number }) {}
13 class Credited extends Domain.Event("Credited", {
14 transfer: Schema.String,
15 amount: Schema.Number,
16 }) {}
17 class Refunded extends Domain.Event("Refunded", {
18 transfer: Schema.String,
19 amount: Schema.Number,
20 }) {}
21 class Closed extends Domain.Event("Closed") {}
22
23 class Insufficient extends Domain.Rejection("Insufficient", { balance: Schema.Number }) {}
24 class NotOpen extends Domain.Rejection("NotOpen") {}
25
26 class Open extends Domain.Command("Open", {
27 target: Schema.String,
28 input: { balance: Schema.Number },
29 events: [Opened],
30 }) {}
31 class Close extends Domain.Command("Close", { target: Schema.String, events: [Closed] }) {}
32 class Debit extends Domain.Command("Debit", {
33 target: Schema.String,
34 input: { transfer: Schema.String, amount: Schema.Number },
35 events: [Debited],
36 rejects: [Insufficient],
37 }) {}
38 class Credit extends Domain.Command("Credit", {
39 target: Schema.String,
40 input: { transfer: Schema.String, amount: Schema.Number },
41 events: [Credited],
42 rejects: [NotOpen],
43 }) {}
44 class Refund extends Domain.Command("Refund", {
45 target: Schema.String,
46 input: { transfer: Schema.String, amount: Schema.Number },
47 events: [Refunded],
48 }) {}
49
50 class Wallet extends Domain.Aggregate("Wallet", {
51 id: Schema.String,
52 state: Schema.Struct({ open: Schema.Boolean, balance: Schema.Number }),
53 initial: { open: false, balance: 0 },
54 commands: [Open, Close, Debit, Credit, Refund],
55 decide: {
56 Open: (_, cmd) => [new Opened({ balance: cmd.balance })],
57 Close: () => [new Closed()],
58 Debit: (s, cmd) =>
59 s.balance < cmd.amount
60 ? new Insufficient({ balance: s.balance })
61 : [new Debited({ transfer: cmd.transfer, amount: cmd.amount })],
62 Credit: (s, cmd) =>
63 s.open ? [new Credited({ transfer: cmd.transfer, amount: cmd.amount })] : new NotOpen(),
64 Refund: (_, cmd) => [new Refunded({ transfer: cmd.transfer, amount: cmd.amount })],
65 },
66 evolve: {
67 Opened: (_, e) => ({ open: true, balance: e.balance }),
68 Debited: (s, e) => ({ ...s, balance: s.balance - e.amount }),
69 Credited: (s, e) => ({ ...s, balance: s.balance + e.amount }),
70 Refunded: (s, e) => ({ ...s, balance: s.balance + e.amount }),
71 Closed: (s) => ({ ...s, open: false }),
72 },
73 }) {}
74
75 // A transfer is requested on its own aggregate; a policy starts the saga.
76 class Requested extends Domain.Event("Requested", {
77 from: Schema.String,
78 to: Schema.String,
79 amount: Schema.Number,
80 approval: Schema.Boolean,
81 }) {}
82 class RequestTransfer extends Domain.Command("RequestTransfer", {
83 target: Schema.String,
84 input: {
85 from: Schema.String,
86 to: Schema.String,
87 amount: Schema.Number,
88 approval: Schema.Boolean,
89 },
90 events: [Requested],
91 }) {}
92 class Transfer extends Domain.Aggregate("Transfer", {
93 id: Schema.String,
94 state: Schema.Struct({ requested: Schema.Boolean }),
95 initial: { requested: false },
96 commands: [RequestTransfer],
97 decide: {
98 RequestTransfer: (s, cmd) =>
99 s.requested
100 ? []
101 : [
102 new Requested({
103 from: cmd.from,
104 to: cmd.to,
105 amount: cmd.amount,
106 approval: cmd.approval,
107 }),
108 ],
109 },
110 evolve: { Requested: () => ({ requested: true }) },
111 }) {}
112
113 class DestinationClosed extends Domain.Rejection("DestinationClosed") {}
114 class NotApproved extends Domain.Rejection("NotApproved") {}
115
116 const Approval = DurableDeferred.make("approval", { success: Schema.String });
117
118 class MoveMoney extends Domain.Saga("MoveMoney", {
119 key: Schema.String,
120 input: {
121 from: Schema.String,
122 to: Schema.String,
123 amount: Schema.Number,
124 approval: Schema.Boolean,
125 },
126 result: { approvedBy: Schema.NullOr(Schema.String) },
127 rejects: [Insufficient, DestinationClosed, NotApproved],
128 }) {}
129
130 const MoveMoneyLive = MoveMoney.toLayer(
131 Effect.gen(function* () {
132 const wallets = yield* Wallet;
133 return Effect.fn(function* ({ key, from, to, amount, approval }) {
134 // Whichever comes first: the approval, or the end of the 24 hour window.
135 const approvedBy = approval
136 ? yield* DurableDeferred.raceAll({
137 name: "approval-window",
138 success: Schema.NullOr(Schema.String),
139 error: Schema.Never,
140 effects: [
141 DurableDeferred.await(Approval),
142 DurableClock.sleep({ name: "window", duration: "24 hours" }).pipe(Effect.as(null)),
143 ],
144 })
145 : null;
146 if (approval && approvedBy === null) return yield* new NotApproved();
147 yield* Activity.make({
148 name: "debit",
149 error: Insufficient,
150 execute: wallets.send(from, new Debit({ transfer: key, amount })),
151 }).pipe(
152 MoveMoney.withCompensation(() =>
153 Activity.make({
154 name: "refund",
155 execute: wallets.send(from, new Refund({ transfer: key, amount })).pipe(Effect.orDie),
156 }),
157 ),
158 );
159 yield* Activity.make({
160 name: "credit",
161 error: DestinationClosed,
162 execute: wallets
163 .send(to, new Credit({ transfer: key, amount }))
164 .pipe(Effect.catchTag("NotOpen", () => Effect.fail(new DestinationClosed()))),
165 });
166 return { approvedBy };
167 });
168 }),
169 );
170
171 class StartTransfers extends Domain.Policy("StartTransfers", {
172 from: Transfer,
173 on: [Requested],
174 }) {}
175 const StartTransfersLive = StartTransfers.toLayer(
176 Effect.gen(function* () {
177 const transfers = yield* MoveMoney;
178 return Effect.fn(function* ({ source, event }) {
179 yield* transfers.start(source, {
180 from: event.from,
181 to: event.to,
182 amount: event.amount,
183 approval: event.approval,
184 });
185 });
186 }),
187 );
188
189 class Bank extends Domain.Model("Bank", {
190 aggregates: [Wallet, Transfer],
191 policies: [StartTransfers],
192 sagas: [MoveMoney],
193 }) {}
194
195 const Handlers = Layer.mergeAll(StartTransfersLive, MoveMoneyLive);
196
197 const story = Story.make(Bank, { layer: Handlers });
198 const alice = Wallet.ref("alice");
199 const bob = Wallet.ref("bob");
200 const transfer = Transfer.ref("t-1");
201 const request = (amount: number, approval = false) =>
202 new RequestTransfer({ from: alice.id, to: bob.id, amount, approval });
203 const requested = (amount: number, approval = false) =>
204 new Requested({ from: alice.id, to: bob.id, amount, approval });
205
206 // A step that sends a debit, then fails its first attempt: the retry sends the
207 // same command again, which the wallet must apply once.
208 class Flaky extends Schema.TaggedError<Flaky>()("Flaky", {}) {}
209
210 class DebitTwice extends Domain.Saga("DebitTwice", {
211 key: Schema.String,
212 input: { from: Schema.String, amount: Schema.Number },
213 }) {}
214
215 const DebitTwiceLive = DebitTwice.toLayer(
216 Effect.gen(function* () {
217 const wallets = yield* Wallet;
218 return Effect.fn(function* ({ key, from, amount }) {
219 yield* Activity.make({
220 name: "debit",
221 error: Flaky,
222 execute: Effect.gen(function* () {
223 yield* wallets.send(from, new Debit({ transfer: key, amount })).pipe(Effect.orDie);
224 if ((yield* Activity.CurrentAttempt) === 1) return yield* new Flaky();
225 }),
226 }).pipe(Activity.retry({ times: 2 }), Effect.orDie);
227 });
228 }),
229 );
230
231 class Retries extends Domain.Model("Retries", {
232 aggregates: [Wallet],
233 sagas: [DebitTwice],
234 }) {}
235
236 // A screening saga that asks an external system, and a saga whose step dies.
237 class SanctionsDown extends Domain.Rejection("SanctionsDown") {}
238
239 class Sanctions extends Domain.ExternalSystem("Sanctions", {
240 check: {
241 args: { wallet: Schema.String },
242 success: { clear: Schema.Boolean },
243 error: SanctionsDown,
244 },
245 }) {}
246
247 class Flagged extends Domain.Rejection("Flagged") {}
248 class ScreeningUnavailable extends Domain.Rejection("ScreeningUnavailable") {}
249
250 class Screen extends Domain.Saga("Screen", {
251 key: Schema.String,
252 input: { wallet: Schema.String },
253 rejects: [Flagged, ScreeningUnavailable],
254 }) {}
255
256 const ScreenLive = Screen.toLayer(
257 Effect.gen(function* () {
258 const sanctions = yield* Sanctions;
259 return Effect.fn(function* ({ wallet }) {
260 const { clear } = yield* Activity.make({
261 name: "check",
262 success: Schema.Struct({ clear: Schema.Boolean }),
263 error: SanctionsDown,
264 execute: sanctions.check({ wallet }),
265 }).pipe(Effect.catchTag("SanctionsDown", () => Effect.fail(new ScreeningUnavailable())));
266 if (!clear) return yield* new Flagged();
267 yield* Activity.make({ name: "approve", execute: Effect.void });
268 });
269 }),
270 );
271
272 class Explode extends Domain.Saga("Explode", {
273 key: Schema.String,
274 input: {},
275 }) {}
276
277 const ExplodeLive = Explode.toLayer(
278 Effect.succeed(() => Activity.make({ name: "boom", execute: Effect.die(new Error("boom")) })),
279 );
280
281 class StartChecks extends Domain.Policy("StartChecks", {
282 from: Transfer,
283 on: [Requested],
284 }) {}
285 const StartChecksLive = StartChecks.toLayer(
286 Effect.gen(function* () {
287 const screens = yield* Screen;
288 const explosions = yield* Explode;
289 return Effect.fn(function* ({ source, event }) {
290 if (event.approval) yield* explosions.start(source, {});
291 else yield* screens.start(source, { wallet: event.from });
292 });
293 }),
294 );
295
296 class Checks extends Domain.Model("Checks", {
297 aggregates: [Wallet, Transfer],
298 policies: [StartChecks],
299 sagas: [Screen, Explode],
300 }) {}
301
302 const checks = Story.make(Checks, {
303 layer: Layer.mergeAll(StartChecksLive, ScreenLive, ExplodeLive),
304 stub: [Sanctions],
305 });
306
307 describe("Domain.Saga", { tags: ["unit", "local"] }, () => {
308 it.effect("a policy starts a saga that debits and credits", () =>
309 story(
310 Story.given(alice, new Opened({ balance: 100 })),
311 Story.given(bob, new Opened({ balance: 0 })),
312 Story.when(transfer, request(40)),
313 Story.then(transfer, requested(40)),
314 Story.then(alice, new Debited({ transfer: "t-1", amount: 40 })),
315 Story.then(bob, new Credited({ transfer: "t-1", amount: 40 })),
316 Story.saga(MoveMoney, "t-1", { _tag: "Completed", result: { approvedBy: null } }),
317 ),
318 );
319
320 it.effect("a failed step undoes the steps before it", () =>
321 story(
322 Story.given(alice, new Opened({ balance: 100 })),
323 Story.given(bob, new Opened({ balance: 0 }), new Closed()),
324 Story.when(transfer, request(40)),
325 Story.then(transfer, requested(40)),
326 Story.then(
327 alice,
328 new Debited({ transfer: "t-1", amount: 40 }),
329 new Refunded({ transfer: "t-1", amount: 40 }),
330 ),
331 Story.then(bob),
332 Story.saga(MoveMoney, "t-1", { _tag: "Rejected", rejection: new DestinationClosed() }),
333 ),
334 );
335
336 it.effect("a refused first step rejects the saga", () =>
337 story(
338 Story.given(alice, new Opened({ balance: 10 })),
339 Story.given(bob, new Opened({ balance: 0 })),
340 Story.when(transfer, request(40)),
341 Story.then(transfer, requested(40)),
342 Story.then(alice),
343 Story.saga(MoveMoney, "t-1", {
344 _tag: "Rejected",
345 rejection: new Insufficient({ balance: 10 }),
346 }),
347 ),
348 );
349
350 it.effect("a step's external system call waits until the story answers it", () =>
351 checks(
352 Story.when(transfer, request(40)),
353 Story.then(transfer, requested(40)),
354 Story.saga(Screen, "t-1", { _tag: "Running" }),
355 Story.call(Sanctions.check, { wallet: "alice" }),
356 Story.succeed(Sanctions.check, { clear: false }),
357 Story.saga(Screen, "t-1", { _tag: "Rejected", rejection: new Flagged() }),
358 ),
359 );
360
361 it.effect("a step's external system call fails with the operation's declared error", () =>
362 checks(
363 Story.when(transfer, request(40)),
364 Story.then(transfer, requested(40)),
365 Story.call(Sanctions.check, { wallet: "alice" }),
366 Story.fail(Sanctions.check, new SanctionsDown()),
367 Story.saga(Screen, "t-1", { _tag: "Rejected", rejection: new ScreeningUnavailable() }),
368 ),
369 );
370
371 it.effect("a step's external system call that dies kills the saga", () =>
372 checks(
373 Story.when(transfer, request(40)),
374 Story.then(transfer, requested(40)),
375 Story.call("t-1", Sanctions.check, { wallet: "alice" }),
376 Story.die("t-1", Sanctions.check, new Error("socket closed")),
377 Story.saga(Screen, "t-1", { _tag: "Died" }),
378 ),
379 );
380
381 it.effect("a saga that dies reads as Died", () =>
382 checks(
383 Story.when(transfer, request(40, true)),
384 Story.then(transfer, requested(40, true)),
385 Story.saga(Explode, "t-1", { _tag: "Died" }),
386 ),
387 );
388
389 it.effect("a saga that dies fails the story unless a step asserts it", () =>
390 checks(Story.when(transfer, request(40, true))).pipe(
391 Effect.flip,
392 Effect.map((failure) =>
393 expect(failure.message).toMatch(/saga Explode run t-1 died with Error: boom/),
394 ),
395 ),
396 );
397
398 it.effect("waits for a signal before it runs", () =>
399 story(
400 Story.given(alice, new Opened({ balance: 100 })),
401 Story.given(bob, new Opened({ balance: 0 })),
402 Story.when(transfer, request(40, true)),
403 Story.then(transfer, requested(40, true)),
404 Story.then(alice),
405 Story.saga(MoveMoney, "t-1", { _tag: "Running" }),
406 Story.signal(MoveMoney, "t-1", Approval, "agent-7"),
407 Story.then(alice, new Debited({ transfer: "t-1", amount: 40 })),
408 Story.then(bob, new Credited({ transfer: "t-1", amount: 40 })),
409 Story.saga(MoveMoney, "t-1", { _tag: "Completed", result: { approvedBy: "agent-7" } }),
410 ),
411 );
412
413 it.effect("rejects when the wait times out on the story's clock", () =>
414 story(
415 Story.clock("2026-01-01T09:00:00Z"),
416 Story.given(alice, new Opened({ balance: 100 })),
417 Story.given(bob, new Opened({ balance: 0 })),
418 Story.when(transfer, request(40, true)),
419 Story.then(transfer, requested(40, true)),
420 Story.clock("2026-01-02T08:59:00Z"),
421 Story.saga(MoveMoney, "t-1", { _tag: "Running" }),
422 Story.clock("2026-01-02T09:00:00Z"),
423 Story.saga(MoveMoney, "t-1", { _tag: "Rejected", rejection: new NotApproved() }),
424 Story.then(alice),
425 ),
426 );
427
428 it.live("a step that runs again sends the same commands", () =>
429 Effect.gen(function* () {
430 const wallets = yield* Wallet;
431 const debits = yield* DebitTwice;
432 yield* wallets.send(alice, new Open({ balance: 100 }));
433 const run = yield* debits.start("t-1", { from: "alice", amount: 40 });
434 yield* run.result;
435 // Debited once: the retry's send had the same command id.
436 expect((yield* wallets.state(alice)).balance).toBe(60);
437 }).pipe(Effect.provide(Retries.layer(DebitTwiceLive).pipe(Layer.provide(InMemory)))),
438 );
439
440 // In real time: the client polls while it waits for the result.
441 it.live("starting a saga twice runs it once, and its client reads the result", () =>
442 Effect.gen(function* () {
443 const transfers = yield* MoveMoney;
444 const wallets = yield* Wallet;
445 yield* wallets.send(alice, new Open({ balance: 100 }));
446 yield* wallets.send(bob, new Open({ balance: 0 }));
447 const input = { from: "alice", to: "bob", amount: 40, approval: false };
448 const first = yield* transfers.start("t-9", input);
449 const second = yield* transfers.start("t-9", input);
450 expect(second.executionId).toBe(first.executionId);
451 expect(yield* first.result).toEqual({ approvedBy: null });
452 expect((yield* wallets.state(alice)).balance).toBe(60);
453 }).pipe(Effect.provide(Bank.layer(Handlers).pipe(Layer.provide(InMemory)))),
454 );
455 });