@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 198 lines 7.54 KB
Raw
1 import * as Domain from "@alchemy.run/domain";
2 import { InMemory } from "@alchemy.run/domain/InMemory";
3 import { describe, expect, it } from "@alchemy.run/test";
4 import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
5 import * as Effect from "effect/Effect";
6 import * as Fiber from "effect/Fiber";
7 import * as HttpServer from "effect/http/HttpServer";
8 import * as Layer from "effect/Layer";
9 import * as Schema from "effect/Schema";
10 import * as Stream from "effect/Stream";
11
12 class Incremented extends Domain.Event("Incremented", { by: Schema.Number }) {}
13 class Increment extends Domain.Command("Increment", {
14 target: Schema.String,
15 input: { by: Schema.Number },
16 events: [Incremented],
17 }) {}
18 class Counter extends Domain.Aggregate("Counter", {
19 id: Schema.String,
20 state: Schema.Struct({ total: Schema.Number }),
21 initial: { total: 0 },
22 commands: [Increment],
23 decide: { Increment: (_, { by }) => [new Incremented({ by })] },
24 evolve: { Incremented: (s, e) => ({ total: s.total + e.by }) },
25 read: {},
26 }) {}
27
28 class Totals extends Domain.View("Totals", {
29 from: [Counter],
30 key: Counter,
31 state: Schema.Struct({ total: Schema.Number }),
32 initial: { total: 0 },
33 evolve: { Incremented: (s, e) => ({ total: s.total + e.by }) },
34 }) {}
35
36 class Bumped extends Domain.Event("Bumped", { by: Schema.Number }) {}
37 class Bumps extends Domain.Stream("Bumps", { key: Counter, entries: [Bumped] }) {}
38 class BumpWriter extends Domain.Projection("BumpWriter", {
39 from: [Counter],
40 key: Counter,
41 on: [Incremented],
42 writes: [Bumps],
43 }) {}
44 const BumpWriterLive = BumpWriter.toLayer(
45 Effect.gen(function* () {
46 const bumps = yield* Bumps;
47 return Effect.fn(function* (batch) {
48 for (const input of batch) yield* bumps.append(input, new Bumped({ by: input.event.by }));
49 });
50 }),
51 );
52
53 class Counters extends Domain.Model("Counters", {
54 aggregates: [Counter],
55 views: [Totals],
56 projections: [BumpWriter],
57 streams: [Bumps],
58 }) {}
59 class CounterApi extends Domain.Api("CounterApi", {
60 model: Counters,
61 commands: ["Increment"],
62 views: ["Totals"],
63 streams: ["Bumps"],
64 aggregates: ["Counter"],
65 }) {}
66
67 const Hosted = Counters.layer(BumpWriterLive).pipe(Layer.provideMerge(InMemory));
68 const InProcess = Layer.effect(CounterApi.Client, CounterApi.clientInProcess).pipe(
69 Layer.provideMerge(Hosted),
70 );
71 const Wire = CounterApi.layerClient.pipe(
72 Layer.provide(Domain.protocolHttp("")),
73 Layer.provideMerge(
74 Layer.unwrap(Effect.map(CounterApi, (api) => HttpServer.serve()(api.fetch))).pipe(
75 Layer.provideMerge(NodeHttpServer.layerTest),
76 ),
77 ),
78 Layer.provideMerge(Hosted),
79 );
80
81 type Client = Effect.Success<typeof CounterApi.client>;
82 type Frame = { readonly envelope: { readonly seq: number } } | Domain.Read.CaughtUp;
83
84 /** A key's live reads, the same for an aggregate, a view and a stream. */
85 interface LiveReads {
86 readonly watch: (key: string) => Stream.Stream<{ readonly cursor: number }, unknown>;
87 readonly events: (key: string, after?: number) => Stream.Stream<Frame, unknown>;
88 }
89
90 const readsOf = (api: Client): Record<"aggregate" | "view" | "stream", LiveReads> => ({
91 aggregate: {
92 watch: (key: string) => api.Counter.watch(key),
93 events: (key: string, after?: number) => api.Counter.events(key, { after }),
94 },
95 view: {
96 watch: (key: string) => api.Totals.watch(key),
97 events: (key: string, after?: number) => api.Totals.events(key, { after }),
98 },
99 stream: {
100 watch: (key: string) => api.Bumps.watch(key),
101 events: (key: string, after?: number) => api.Bumps.events(key, { after }),
102 },
103 });
104
105 /** Wait until the view and the stream have caught up to `version` commits of c-1. */
106 const settled = (api: Client, version: number) =>
107 Effect.all([
108 api.Totals.get("c-1", { atLeast: { stream: "Counter/c-1", version } }),
109 api.Bumps.peek("c-1", { atLeast: { stream: "Counter/c-1", version } }),
110 ]);
111
112 /** Three increments of c-1, folded by the view and appended to the stream. */
113 const seed = Effect.gen(function* () {
114 const api = yield* CounterApi.Client;
115 for (const by of [1, 2, 3]) yield* api.Increment("c-1", { by });
116 yield* settled(api, 3);
117 return api;
118 });
119
120 /** What a feed shows: entries by seq, and each CaughtUp by its cursor. */
121 const frames = (items: ReadonlyArray<Frame>) =>
122 items.map((item) =>
123 Domain.Read.isCaughtUp(item) ? `caught up at ${item.cursor}` : item.envelope.seq,
124 );
125
126 for (const [transport, layer] of [
127 ["in process", InProcess],
128 ["over the wire", Wire],
129 ] as const) {
130 describe(`Domain live reads ${transport}`, { tags: ["unit", "local"] }, () => {
131 for (const kind of ["aggregate", "view", "stream"] as const) {
132 it.live(`${kind} events mark the end of their history`, () =>
133 Effect.gen(function* () {
134 const api = yield* seed;
135 const read = readsOf(api)[kind];
136 const feed = yield* read
137 .events("c-1")
138 .pipe(Stream.take(5), Stream.runCollect, Effect.forkChild);
139 yield* Effect.sleep("30 millis");
140 yield* api.Increment("c-1", { by: 4 });
141 yield* settled(api, 4);
142 expect(frames(yield* Fiber.join(feed))).toEqual([1, 2, 3, "caught up at 3", 4]);
143
144 // Resuming after a cursor: the rest of the history, nothing twice, no gap.
145 const resumed = yield* read.events("c-1", 2).pipe(Stream.take(3), Stream.runCollect);
146 expect(frames(resumed)).toEqual([3, 4, "caught up at 4"]);
147
148 const empty = yield* read.events("c-0").pipe(Stream.take(1), Stream.runCollect);
149 expect(frames(empty)).toEqual(["caught up at 0"]);
150 }).pipe(Effect.scoped, Effect.provide(layer)),
151 );
152
153 it.live(`${kind} watch gives a cursor that hands off to events`, () =>
154 Effect.gen(function* () {
155 const api = yield* seed;
156 const read = readsOf(api)[kind];
157 const watched = yield* read
158 .watch("c-1")
159 .pipe(Stream.take(2), Stream.runCollect, Effect.forkChild);
160 yield* Effect.sleep("30 millis");
161 yield* api.Increment("c-1", { by: 4 });
162 const [first, second] = yield* Fiber.join(watched);
163 expect([first!.cursor, second!.cursor]).toEqual([3, 4]);
164
165 // From the first state's cursor, events sends only what came after it.
166 const after = yield* read
167 .events("c-1", first!.cursor)
168 .pipe(Stream.take(2), Stream.runCollect);
169 expect(frames(after)).toEqual([4, "caught up at 4"]);
170 }).pipe(Effect.scoped, Effect.provide(layer)),
171 );
172 }
173
174 it.live("a filter that drops the last entries of the history still ends it", () =>
175 Effect.gen(function* () {
176 const api = yield* seed;
177 const feed = yield* api.Totals.events("c-1", { where: { by: { lt: 3 } } }).pipe(
178 Stream.take(3),
179 Stream.runCollect,
180 );
181 expect(frames(feed)).toEqual([1, 2, "caught up at 3"]);
182 }).pipe(Effect.scoped, Effect.provide(layer)),
183 );
184
185 it.live("watch sends the state with its cursor", () =>
186 Effect.gen(function* () {
187 const api = yield* seed;
188 const [aggregate] = yield* api.Counter.watch("c-1").pipe(Stream.take(1), Stream.runCollect);
189 const [view] = yield* api.Totals.watch("c-1").pipe(Stream.take(1), Stream.runCollect);
190 const [stream] = yield* api.Bumps.watch("c-1").pipe(Stream.take(1), Stream.runCollect);
191 expect(aggregate).toEqual({ state: { total: 6 }, cursor: 3 });
192 expect(view).toEqual({ state: { total: 6 }, cursor: 3 });
193 expect(stream!.state?.event).toEqual(new Bumped({ by: 3 }));
194 expect(stream!.cursor).toBe(3);
195 }).pipe(Effect.scoped, Effect.provide(layer)),
196 );
197 });
198 }