@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, 06:00 UTC

main
ts 496 lines 17.8 KB
Raw
1 import * as Domain from "@alchemy.run/domain";
2 import * as InMemory from "@alchemy.run/domain/InMemory";
3 import { describe, expect, it } from "@alchemy.run/test";
4 import * as Context from "effect/Context";
5 import * as Effect from "effect/Effect";
6 import * as Layer from "effect/Layer";
7 import * as Option from "effect/Option";
8 import * as Ref from "effect/Ref";
9 import * as Schema from "effect/Schema";
10
11 // ---------------------------------------------------------------- two aggregates
12
13 class Deposited extends Domain.Event("Deposited", { amount: Schema.Number }) {}
14 class Deposit extends Domain.Command("Deposit", {
15 target: Schema.String,
16 input: { amount: Schema.Number },
17 events: [Deposited],
18 }) {}
19 class Account extends Domain.Aggregate("Account", {
20 id: Schema.String,
21 state: Schema.Struct({ balance: Schema.Number }),
22 initial: { balance: 0 },
23 commands: [Deposit],
24 decide: { Deposit: (_, cmd) => [new Deposited({ amount: cmd.amount })] },
25 evolve: { Deposited: (s, e) => ({ balance: s.balance + e.amount }) },
26 }) {}
27
28 class Logged extends Domain.Event("Logged", { note: Schema.String }) {}
29 class Log extends Domain.Command("Log", {
30 target: Schema.String,
31 input: { note: Schema.String },
32 events: [Logged],
33 }) {}
34 class Journal extends Domain.Aggregate("Journal", {
35 id: Schema.String,
36 state: Schema.Struct({}),
37 initial: {},
38 commands: [Log],
39 decide: { Log: (_, cmd) => [new Logged({ note: cmd.note })] },
40 evolve: { Logged: (s) => s },
41 }) {}
42
43 // ---------------------------------------------------------------- consumers added later
44
45 /** Every deposit to an account, in the order the view applied them. */
46 class Deposits extends Domain.View("Deposits", {
47 from: [Account],
48 key: Account,
49 state: Schema.Struct({ amounts: Schema.Array(Schema.Number) }),
50 initial: { amounts: [] },
51 evolve: { Deposited: (s, e) => ({ amounts: [...s.amounts, e.amount] }) },
52 }) {}
53
54 /** Counts what reaches it: a policy must never act on replayed history. */
55 class Reactions extends Context.Service<Reactions, Ref.Ref<number>>()("Test/Reactions") {}
56 class OnDeposit extends Domain.Policy("OnDeposit", { from: [Deposits], on: [Deposited] }) {}
57 const OnDepositLive = OnDeposit.toLayer(
58 Effect.gen(function* () {
59 const reactions = yield* Reactions;
60 return Effect.fn(function* () {
61 yield* Ref.update(reactions, (n) => n + 1);
62 });
63 }),
64 );
65
66 /** A store outside the model: what one projection key received, in order. */
67 class Feed extends Context.Service<Feed, Ref.Ref<ReadonlyArray<string>>>()("Test/Feed") {}
68 class Timeline extends Domain.Projection("Timeline", {
69 from: [Account, Journal],
70 key: Schema.String,
71 keyOf: { Deposited: () => "all", Logged: () => "all" },
72 on: [Deposited, Logged],
73 }) {}
74 const timelineLayer = (options?: Domain.Projection.Options) =>
75 Timeline.toLayer(
76 Effect.gen(function* () {
77 const feed = yield* Feed;
78 return Effect.fn(function* (batch) {
79 yield* Ref.update(feed, (all) => [
80 ...all,
81 ...batch.map(({ event }) =>
82 event._tag === "Deposited" ? `deposit ${event.amount}` : `log ${event.note}`,
83 ),
84 ]);
85 });
86 }),
87 options,
88 );
89 const TimelineLive = timelineLayer();
90
91 /** The same view, redefined: it now records each deposit doubled. */
92 class DoubledDeposits extends Domain.View("Deposits", {
93 from: [Account],
94 key: Account,
95 state: Schema.Struct({ amounts: Schema.Array(Schema.Number) }),
96 initial: { amounts: [] },
97 evolve: { Deposited: (s, e) => ({ amounts: [...s.amounts, e.amount * 2] }) },
98 }) {}
99
100 /** Every deposit, in the order the view applied them: one key. */
101 class Activity extends Domain.View("Activity", {
102 from: [Account],
103 key: Schema.String,
104 keyOf: { Deposited: () => "all" },
105 state: Schema.Struct({ entries: Schema.Array(Schema.String) }),
106 initial: { entries: [] },
107 evolve: { Deposited: (s, e) => ({ entries: [...s.entries, `deposit ${e.amount}`] }) },
108 }) {}
109
110 /** The same view, now reading the journal too. */
111 class WideActivity extends Domain.View("Activity", {
112 from: [Account, Journal],
113 key: Schema.String,
114 keyOf: { Deposited: () => "all", Logged: () => "all" },
115 state: Schema.Struct({ entries: Schema.Array(Schema.String) }),
116 initial: { entries: [] },
117 evolve: {
118 Deposited: (s, e) => ({ entries: [...s.entries, `deposit ${e.amount}`] }),
119 Logged: (s, e) => ({ entries: [...s.entries, `log ${e.note}`] }),
120 },
121 }) {}
122
123 /** The views again, each at version 1: what bumping a version deploys. */
124 class DepositsV1 extends Domain.View("Deposits", { ...Deposits.definition, version: 1 }) {}
125 class DoubledDepositsV1 extends Domain.View("Deposits", {
126 ...DoubledDeposits.definition,
127 version: 1,
128 }) {}
129 class WideActivityV1 extends Domain.View("Activity", { ...WideActivity.definition, version: 1 }) {}
130
131 // ---------------------------------------------------------------- one model, three deploys
132
133 class Before extends Domain.Model("Bank", { aggregates: [Account, Journal] }) {}
134 class WithView extends Domain.Model("Bank", {
135 aggregates: [Account, Journal],
136 views: [Deposits],
137 policies: [OnDeposit],
138 }) {}
139 class Redefined extends Domain.Model("Bank", {
140 aggregates: [Account, Journal],
141 views: [DoubledDeposits],
142 }) {}
143 class WithTimeline extends Domain.Model("Bank", {
144 aggregates: [Account, Journal],
145 projections: [Timeline],
146 }) {}
147
148 class WithActivity extends Domain.Model("Bank", {
149 aggregates: [Account, Journal],
150 views: [Activity],
151 }) {}
152 class WithWideActivity extends Domain.Model("Bank", {
153 aggregates: [Account, Journal],
154 views: [WideActivity],
155 }) {}
156 class WithWideActivityV1 extends Domain.Model("Bank", {
157 aggregates: [Account, Journal],
158 views: [WideActivityV1],
159 }) {}
160 class WithViewV1 extends Domain.Model("Bank", {
161 aggregates: [Account, Journal],
162 views: [DepositsV1],
163 }) {}
164 class RedefinedV1 extends Domain.Model("Bank", {
165 aggregates: [Account, Journal],
166 views: [DoubledDepositsV1],
167 }) {}
168
169 const HOUR = 60 * 60 * 1000;
170
171 /**
172 * An in-memory platform that outlives the models built on it, as storage
173 * outlives a deploy. `deploy` builds a model on it and runs `effect` against
174 * that build; the platform delivers only when drained.
175 */
176 const platform = () => {
177 const clock = { now: 0 };
178 const hosted = InMemory.make({ manual: true, now: () => clock.now });
179 const services = Layer.mergeAll(
180 Layer.effect(Reactions, Ref.make(0)),
181 Layer.effect(Feed, Ref.make<ReadonlyArray<string>>([])),
182 );
183 // Deliver everything queued, and wait for the projection runs it forks.
184 const settle: Effect.Effect<void> = Effect.gen(function* () {
185 while (true) {
186 yield* hosted.control.drain;
187 if (yield* hosted.control.idle) return;
188 yield* Effect.sleep("1 millis");
189 }
190 });
191 return {
192 clock,
193 hosted,
194 settle,
195 services,
196 deploy: <A, E, R, P, PE, PR>(
197 model: { readonly layer: (policies: any, options?: any) => Layer.Layer<any, any, any> },
198 policies: Layer.Layer<P, PE, PR>,
199 effect: Effect.Effect<A, E, R>,
200 options?: Domain.Model.LayerOptions,
201 ) =>
202 effect.pipe(
203 Effect.tap(() => settle),
204 Effect.provide(model.layer(policies, options).pipe(Layer.provide(hosted.layer))),
205 ),
206 };
207 };
208
209 const deposit = (id: string, amount: number) =>
210 Effect.gen(function* () {
211 const accounts = yield* Account;
212 yield* accounts.send(Account.ref(id), new Deposit({ amount }));
213 });
214
215 const amounts = (id: string) =>
216 Effect.gen(function* () {
217 const view = yield* Deposits;
218 return Option.getOrUndefined(yield* view.query(Account.ref(id)))?.amounts;
219 });
220
221 describe("Domain catch-up", () => {
222 it.live(
223 "a view that reads more sources without a version bump fails the deploy; with one, it is rebuilt from all of them",
224 () =>
225 Effect.gen(function* () {
226 const bank = platform();
227 yield* bank.deploy(
228 Before,
229 Layer.empty,
230 Effect.gen(function* () {
231 yield* deposit("a-1", 10);
232 const journals = yield* Journal;
233 yield* journals.send(Journal.ref("j-1"), new Log({ note: "opened" }));
234 }),
235 );
236 yield* bank.deploy(WithActivity, Layer.empty, bank.settle);
237 // Its backfill read Account only: waiting on it would miss the journal's history.
238 const refused = yield* bank.deploy(WithWideActivity, Layer.empty, Effect.void).pipe(
239 Effect.as(""),
240 Effect.catchCause((cause) => Effect.succeed(String(cause))),
241 );
242 expect(refused).toContain("BackfillPlanChanged");
243 expect(refused).toContain("Bump its version");
244 const entries = yield* bank.deploy(
245 WithWideActivityV1,
246 Layer.empty,
247 Effect.gen(function* () {
248 yield* bank.settle;
249 const view = yield* WideActivityV1;
250 return Option.getOrUndefined(yield* view.query("all"))?.entries;
251 }),
252 );
253 expect([...(entries ?? [])].sort()).toEqual(["deposit 10", "log opened"]);
254 }).pipe(Effect.provide(platform().services)),
255 );
256
257 it.live("a view added later folds the events recorded before it", () =>
258 Effect.gen(function* () {
259 const bank = platform();
260 yield* bank.deploy(
261 Before,
262 Layer.empty,
263 Effect.all([deposit("a-1", 10), deposit("a-1", 20), deposit("a-2", 5)]),
264 );
265 const [a1, a2] = yield* bank.deploy(
266 WithView,
267 OnDepositLive,
268 Effect.gen(function* () {
269 yield* bank.settle;
270 return [yield* amounts("a-1"), yield* amounts("a-2")] as const;
271 }),
272 );
273 expect(a1).toEqual([10, 20]);
274 expect(a2).toEqual([5]);
275 }).pipe(Effect.provide(platform().services)),
276 );
277
278 it.live("events committed while a view catches up arrive after its history", () =>
279 Effect.gen(function* () {
280 const bank = platform();
281 yield* bank.deploy(Before, Layer.empty, Effect.all([deposit("a-1", 1), deposit("a-1", 2)]));
282 const result = yield* bank.deploy(
283 WithView,
284 OnDepositLive,
285 // The sweep is queued but not run yet: this commit lands first.
286 deposit("a-1", 3).pipe(
287 Effect.andThen(bank.settle),
288 Effect.andThen(deposit("a-1", 4)),
289 Effect.andThen(bank.settle),
290 Effect.andThen(amounts("a-1")),
291 ),
292 );
293 expect(result).toEqual([1, 2, 3, 4]);
294 }).pipe(Effect.provide(platform().services)),
295 );
296
297 it.live("policies never act on replayed history", () =>
298 Effect.gen(function* () {
299 const bank = platform();
300 yield* bank.deploy(Before, Layer.empty, Effect.all([deposit("a-1", 1), deposit("a-2", 2)]));
301 const reactions = yield* bank.deploy(
302 WithView,
303 OnDepositLive,
304 Effect.gen(function* () {
305 yield* bank.settle;
306 const replayed = yield* Ref.get(yield* Reactions);
307 yield* deposit("a-1", 3);
308 yield* bank.settle;
309 return { replayed, live: (yield* Ref.get(yield* Reactions)) - replayed };
310 }),
311 );
312 expect(reactions).toEqual({ replayed: 0, live: 1 });
313 }).pipe(Effect.provide(platform().services)),
314 );
315
316 it.live("a view removed, then added back with a new version, is rebuilt with everything", () =>
317 Effect.gen(function* () {
318 const bank = platform();
319 yield* bank.deploy(WithView, OnDepositLive, deposit("a-1", 1));
320 yield* bank.deploy(Before, Layer.empty, deposit("a-1", 2));
321 const result = yield* bank.deploy(
322 WithViewV1,
323 Layer.empty,
324 bank.settle.pipe(
325 Effect.andThen(
326 Effect.gen(function* () {
327 const view = yield* DepositsV1;
328 return Option.getOrUndefined(yield* view.query(Account.ref("a-1")))?.amounts;
329 }),
330 ),
331 ),
332 );
333 expect(result).toEqual([1, 2]);
334 }).pipe(Effect.provide(platform().services)),
335 );
336
337 it.live("a redeploy does not replay history to a view that has it", () =>
338 Effect.gen(function* () {
339 const bank = platform();
340 yield* bank.deploy(WithView, OnDepositLive, deposit("a-1", 1));
341 const result = yield* bank.deploy(
342 WithView,
343 OnDepositLive,
344 deposit("a-1", 2).pipe(Effect.andThen(bank.settle), Effect.andThen(amounts("a-1"))),
345 );
346 expect(result).toEqual([1, 2]);
347 expect(yield* Ref.get(yield* Reactions)).toBe(2);
348 }).pipe(Effect.provide(platform().services)),
349 );
350
351 it.live("a projection added later receives many instances' history in time order", () =>
352 Effect.gen(function* () {
353 const bank = platform();
354 const at = <R>(hours: number, effect: Effect.Effect<void, never, R>) =>
355 Effect.sync(() => {
356 bank.clock.now = hours * HOUR;
357 }).pipe(Effect.andThen(effect));
358 const log = (id: string, note: string) =>
359 Effect.gen(function* () {
360 yield* (yield* Journal).send(Journal.ref(id), new Log({ note }));
361 });
362 yield* bank.deploy(
363 Before,
364 Layer.empty,
365 Effect.all([
366 at(0, deposit("a-1", 1)),
367 at(1, log("j-1", "one")),
368 at(3, deposit("a-1", 3)),
369 at(4, log("j-1", "four")),
370 at(6, deposit("a-2", 6)),
371 ]),
372 );
373 const feed = yield* bank.deploy(
374 WithTimeline,
375 TimelineLive,
376 bank.settle.pipe(Effect.andThen(Effect.flatMap(Feed, Ref.get))),
377 );
378 // Each instance alone would replay all of its history at once:
379 // deposit 1, deposit 3, log one, log four.
380 expect(feed).toEqual(["deposit 1", "log one", "deposit 3", "log four", "deposit 6"]);
381 }).pipe(Effect.provide(platform().services)),
382 );
383
384 it.live("a new view's history says when it is complete", () =>
385 Effect.gen(function* () {
386 const bank = platform();
387 yield* bank.deploy(Before, Layer.empty, deposit("a-1", 1));
388 const [before, after] = yield* bank.deploy(
389 WithView,
390 OnDepositLive,
391 Effect.gen(function* () {
392 const view = yield* Deposits;
393 const before = yield* view.history;
394 yield* bank.settle;
395 return [before, yield* view.history] as const;
396 }),
397 );
398 expect(before.complete).toBe(false);
399 expect(after.complete).toBe(true);
400 }).pipe(Effect.provide(platform().services)),
401 );
402
403 it.live("instances created and written while a view catches up are folded once", () =>
404 Effect.gen(function* () {
405 const bank = platform();
406 yield* bank.deploy(Before, Layer.empty, Effect.all([deposit("a-1", 1), deposit("a-2", 2)]));
407 const result = yield* bank.deploy(
408 WithView,
409 OnDepositLive,
410 Effect.gen(function* () {
411 // Before the sweep runs: a new instance, and a write to an inactive one.
412 yield* deposit("a-9", 9);
413 yield* deposit("a-2", 3);
414 yield* bank.settle;
415 return [yield* amounts("a-1"), yield* amounts("a-2"), yield* amounts("a-9")];
416 }),
417 );
418 expect(result).toEqual([[1], [2, 3], [9]]);
419 }).pipe(Effect.provide(platform().services)),
420 );
421
422 it.live("a catch-up started again after an interrupted deploy delivers each event once", () =>
423 Effect.gen(function* () {
424 const bank = platform();
425 yield* bank.deploy(Before, Layer.empty, Effect.all([deposit("a-1", 1), deposit("a-1", 2)]));
426 // The first deploy with the view is replaced before its catch-up runs; both sweeps run.
427 const first = WithView.layer(OnDepositLive).pipe(Layer.provide(bank.hosted.layer));
428 yield* Effect.provide(Effect.void, first);
429 const result = yield* bank.deploy(
430 WithView,
431 OnDepositLive,
432 bank.settle.pipe(Effect.andThen(amounts("a-1"))),
433 );
434 expect(result).toEqual([1, 2]);
435 expect(yield* Ref.get(yield* Reactions)).toBe(0);
436 }).pipe(Effect.provide(platform().services)),
437 );
438
439 it.live("bumping a view's version rebuilds it from the history", () =>
440 Effect.gen(function* () {
441 const bank = platform();
442 yield* bank.deploy(
443 WithView,
444 OnDepositLive,
445 Effect.all([deposit("a-1", 1), deposit("a-1", 2)]),
446 );
447 const doubled = (id: string) =>
448 Effect.gen(function* () {
449 const view = yield* DoubledDeposits;
450 return Option.getOrUndefined(yield* view.query(Account.ref(id)))?.amounts;
451 });
452 // Redefined but not rebuilt: only new deposits are doubled, after the old state.
453 const stale = yield* bank.deploy(
454 Redefined,
455 Layer.empty,
456 deposit("a-1", 3).pipe(Effect.andThen(bank.settle), Effect.andThen(doubled("a-1"))),
457 );
458 expect(stale).toEqual([1, 2, 6]);
459 // Keyed by its account: rebuilt in place. Nothing to wait for; each key
460 // reads its account's events again before it answers.
461 const rebuilt = yield* bank.deploy(
462 RedefinedV1,
463 Layer.empty,
464 Effect.gen(function* () {
465 const view = yield* DoubledDepositsV1;
466 expect((yield* view.history).complete).toBe(true);
467 const first = Option.getOrUndefined(yield* view.query(Account.ref("a-1")))?.amounts;
468 expect(first).toEqual([2, 4, 6]);
469 yield* deposit("a-1", 4);
470 yield* bank.settle;
471 return Option.getOrUndefined(yield* view.query(Account.ref("a-1")))?.amounts;
472 }),
473 );
474 expect(rebuilt).toEqual([2, 4, 6, 8]);
475 // A policy on the old view acted on the first two deposits only, never on the rebuild.
476 expect(yield* Ref.get(yield* Reactions)).toBe(2);
477 }).pipe(Effect.provide(platform().services)),
478 );
479
480 it.live("bumping a projection's version runs it again over the history", () =>
481 Effect.gen(function* () {
482 const bank = platform();
483 yield* bank.deploy(
484 WithTimeline,
485 TimelineLive,
486 Effect.all([deposit("a-1", 1), deposit("a-2", 2)]),
487 );
488 const feed = yield* bank.deploy(
489 WithTimeline,
490 timelineLayer({ version: 1 }),
491 bank.settle.pipe(Effect.andThen(Effect.flatMap(Feed, Ref.get))),
492 );
493 expect(feed).toEqual(["deposit 1", "deposit 2", "deposit 1", "deposit 2"]);
494 }).pipe(Effect.provide(platform().services)),
495 );
496 });