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

main
ts 229 lines 8.59 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 NodeHttpClient from "@effect/platform-node/NodeHttpClient";
5 import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
6 import * as Cause from "effect/Cause";
7 import * as DateTime from "effect/DateTime";
8 import * as Effect from "effect/Effect";
9 import * as Exit from "effect/Exit";
10 import * as HttpClient from "effect/http/HttpClient";
11 import * as HttpClientRequest from "effect/http/HttpClientRequest";
12 import * as HttpServer from "effect/http/HttpServer";
13 import * as Layer from "effect/Layer";
14 import * as Schema from "effect/Schema";
15 import * as Stream from "effect/Stream";
16
17 // A wallet whose deposits a policy books in a ledger: the ledger's events have
18 // their own command id, and the deposit's id as their correlation id.
19 class Deposited extends Domain.Event("Deposited", { amount: Schema.Number }) {}
20 class Deposit extends Domain.Command("Deposit", {
21 target: Schema.String,
22 input: { amount: Schema.Number },
23 events: [Deposited],
24 }) {}
25 class Wallet extends Domain.Aggregate("Wallet", {
26 id: Schema.String,
27 state: Schema.Struct({ balance: Schema.Number }),
28 initial: { balance: 0 },
29 commands: [Deposit],
30 decide: { Deposit: (_, { amount }) => [new Deposited({ amount })] },
31 evolve: { Deposited: (s, e) => ({ balance: s.balance + e.amount }) },
32 read: {},
33 }) {}
34
35 const BookedFields = { wallet: Schema.String, amount: Schema.Number, at: Schema.DateTimeUtc };
36 class Booked extends Domain.Event("Booked", BookedFields) {}
37 class Book extends Domain.Command("Book", {
38 target: Schema.String,
39 input: BookedFields,
40 events: [Booked],
41 }) {}
42 class Ledger extends Domain.Aggregate("Ledger", {
43 id: Schema.String,
44 state: Schema.Struct({ total: Schema.Number }),
45 initial: { total: 0 },
46 commands: [Book],
47 decide: { Book: (_, { wallet, amount, at }) => [new Booked({ wallet, amount, at })] },
48 evolve: { Booked: (s, e) => ({ total: s.total + e.amount }) },
49 read: {},
50 }) {}
51
52 class BookDeposits extends Domain.Policy("BookDeposits", { from: Wallet, on: [Deposited] }) {}
53 const BookDepositsLive = BookDeposits.toLayer(
54 Effect.gen(function* () {
55 const ledger = yield* Ledger;
56 return Effect.fn(function* ({ source, event, envelope }) {
57 yield* ledger.send(
58 "main",
59 new Book({ wallet: source.id, amount: event.amount, at: envelope.at }),
60 );
61 });
62 }),
63 );
64
65 class Bookings extends Domain.View("Bookings", {
66 from: [Ledger],
67 key: Ledger,
68 state: Schema.Struct({ count: Schema.Number }),
69 initial: { count: 0 },
70 evolve: { Booked: (s) => ({ count: s.count + 1 }) },
71 }) {}
72
73 // A parcel's input names the fields a call's target and command id use.
74 class Shipped extends Domain.Event("Shipped", { to: Schema.String, ref: Schema.String }) {}
75 class Ship extends Domain.Command("Ship", {
76 target: Schema.String,
77 input: { target: Schema.String, commandId: Schema.String },
78 events: [Shipped],
79 reply: { to: Schema.String, ref: Schema.String },
80 }) {}
81 class Parcel extends Domain.Aggregate("Parcel", {
82 id: Schema.String,
83 state: Schema.Struct({ to: Schema.String, ref: Schema.String }),
84 initial: { to: "", ref: "" },
85 commands: [Ship],
86 decide: { Ship: (_, { target, commandId }) => [new Shipped({ to: target, ref: commandId })] },
87 evolve: { Shipped: (_, e) => ({ to: e.to, ref: e.ref }) },
88 reply: { Ship: (s) => s },
89 read: {},
90 }) {}
91
92 class Bank extends Domain.Model("Bank", {
93 aggregates: [Wallet, Ledger, Parcel],
94 views: [Bookings],
95 policies: [BookDeposits],
96 }) {}
97
98 class BankApi extends Domain.Api("BankApi", {
99 model: Bank,
100 commands: ["Deposit", "Ship"],
101 views: ["Bookings"],
102 aggregates: ["Wallet", "Ledger", "Parcel"],
103 }) {}
104
105 const Hosted = Bank.layer(BookDepositsLive).pipe(Layer.provide(InMemory));
106
107 // The Api's `fetch` on a real HTTP server; the client speaks the wire protocol to it.
108 const Wire = Domain.protocolHttp("").pipe(
109 Layer.provideMerge(
110 Layer.unwrap(Effect.map(BankApi, (api) => HttpServer.serve()(api.fetch))).pipe(
111 Layer.provideMerge(NodeHttpServer.layerTest),
112 ),
113 ),
114 Layer.provideMerge(Hosted),
115 );
116
117 describe("Domain Api over the wire", { tags: ["unit", "local"] }, () => {
118 it.live("an input may name its fields target and commandId", () =>
119 Effect.gen(function* () {
120 const bank = yield* BankApi.client;
121 const receipt = yield* bank.Ship(
122 "p-1",
123 { target: "Lisbon", commandId: "ref-7" },
124 { commandId: "ship-1" },
125 );
126 expect(receipt).toMatchObject({
127 reply: { to: "Lisbon", ref: "ref-7" },
128 stream: "Parcel/p-1",
129 });
130
131 const [shipped] = yield* bank.Parcel.events("p-1").pipe(
132 Stream.filter(Domain.Read.isEvent),
133 Stream.take(1),
134 Stream.runCollect,
135 );
136 expect(shipped!.envelope.commandId).toBe("ship-1");
137 }).pipe(Effect.scoped, Effect.provide(Wire)),
138 );
139
140 it.live("an envelope keeps its command id and correlation id", () =>
141 Effect.gen(function* () {
142 const bank = yield* BankApi.client;
143 const local = yield* BankApi.clientInProcess;
144 yield* bank.Deposit("w-1", { amount: 5 }, { commandId: "deposit-1" });
145
146 const [wallet] = yield* bank.Wallet.events("w-1").pipe(
147 Stream.filter(Domain.Read.isEvent),
148 Stream.take(1),
149 Stream.runCollect,
150 );
151 expect(wallet!.envelope).toMatchObject({
152 commandId: "deposit-1",
153 correlationId: "deposit-1",
154 });
155
156 // The policy's command has its own id, and carries the deposit's correlation id.
157 const [booked] = yield* bank.Ledger.events("main").pipe(
158 Stream.filter(Domain.Read.isEvent),
159 Stream.take(1),
160 Stream.runCollect,
161 );
162 expect(booked!.envelope.commandId).not.toBe("deposit-1");
163 expect(booked!.envelope.correlationId).toBe("deposit-1");
164
165 const [entry] = yield* bank.Bookings.events("main").pipe(
166 Stream.filter(Domain.Read.isEvent),
167 Stream.take(1),
168 Stream.runCollect,
169 );
170 expect(entry!.envelope.correlationId).toBe("deposit-1");
171 const page = yield* bank.Bookings.list("main");
172 expect(page.entries[0]!.envelope.correlationId).toBe("deposit-1");
173
174 // The wire gives what the in-process client gives.
175 const [direct] = yield* local.Ledger.events("main").pipe(
176 Stream.filter(Domain.Read.isEvent),
177 Stream.take(1),
178 Stream.runCollect,
179 );
180 expect(booked!.envelope).toEqual(direct!.envelope);
181 }).pipe(Effect.scoped, Effect.provide(Wire)),
182 );
183 it.live("a filter on a DateTime field works over the wire", () =>
184 Effect.gen(function* () {
185 const bank = yield* BankApi.client;
186 yield* bank.Deposit("w-1", { amount: 5 }, { commandId: "deposit-1" });
187 yield* bank.Ledger.events("main").pipe(Stream.take(1), Stream.runCollect);
188 const now = yield* DateTime.now;
189
190 const page = yield* bank.Bookings.list("main", { where: { at: { lte: now } } });
191 expect(page.entries.map((entry) => entry.event.amount)).toEqual([5]);
192 const none = yield* bank.Bookings.list("main", { where: { at: { gt: now } } });
193 expect(none.entries).toEqual([]);
194 }).pipe(Effect.scoped, Effect.provide(Wire)),
195 );
196
197 it.live("a malformed filter is refused before it is evaluated", () =>
198 Effect.gen(function* () {
199 const bank = yield* BankApi.client;
200 yield* bank.Deposit("w-1", { amount: 5 }, { commandId: "deposit-1" });
201 yield* bank.Ledger.events("main").pipe(Stream.take(1), Stream.runCollect);
202
203 // `in` takes a list: the filter fails to encode, rather than throwing where it is evaluated.
204 const exit = yield* Effect.exit(
205 bank.Bookings.list("main", { where: { amount: { in: 5 } } as never }),
206 );
207 expect(Exit.isFailure(exit)).toBe(true);
208 const cause = Exit.isFailure(exit) ? Cause.pretty(exit.cause) : "";
209 expect(cause).toContain("Schema validation failed");
210 expect(cause).not.toContain("is not a function");
211 }).pipe(Effect.scoped, Effect.provide(Wire)),
212 );
213
214 it.live("a live read whose request does not decode gets a 400", () =>
215 Effect.gen(function* () {
216 // fetch refuses requests carrying an `upgrade` header; node:http sends
217 // them and hands back a refusal response.
218 const client = yield* HttpServer.makeTestClient.pipe(
219 Effect.provide(NodeHttpClient.layerNodeHttp),
220 );
221 const response = yield* client.execute(
222 HttpClientRequest.get(`/?read=${encodeURIComponent("{not json")}`).pipe(
223 HttpClientRequest.setHeader("upgrade", "websocket"),
224 ),
225 );
226 expect(response.status).toBe(400);
227 }).pipe(Effect.scoped, Effect.provide(Wire)),
228 );
229 });