The best way to control Claude Code, Codex and more from any computer or phone
| 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 Context from "effect/Context"; |
| 6 | import * as Effect from "effect/Effect"; |
| 7 | import * as Headers from "effect/http/Headers"; |
| 8 | import * as Layer from "effect/Layer"; |
| 9 | import * as Option from "effect/Option"; |
| 10 | import * as Ref from "effect/Ref"; |
| 11 | import * as RpcMiddleware from "effect/rpc/RpcMiddleware"; |
| 12 | import * as Schedule from "effect/Schedule"; |
| 13 | import * as Schema from "effect/Schema"; |
| 14 | import * as Stream from "effect/Stream"; |
| 15 | |
| 16 | // ---------------------------------------------------------------- a wallet domain |
| 17 | |
| 18 | class Deposited extends Domain.Event("Deposited", { |
| 19 | amount: Schema.Number, |
| 20 | balance: Schema.Number, |
| 21 | }) {} |
| 22 | class Deposit extends Domain.Command("Deposit", { |
| 23 | target: Schema.String, |
| 24 | input: { amount: Schema.Number }, |
| 25 | events: [Deposited], |
| 26 | reply: { balance: Schema.Number }, |
| 27 | }) {} |
| 28 | class Wallet extends Domain.Aggregate("Wallet", { |
| 29 | id: Schema.String, |
| 30 | state: Schema.Struct({ balance: Schema.Number }), |
| 31 | initial: { balance: 0 }, |
| 32 | commands: [Deposit], |
| 33 | decide: { |
| 34 | Deposit: (s, cmd) => [new Deposited({ amount: cmd.amount, balance: s.balance + cmd.amount })], |
| 35 | }, |
| 36 | evolve: { Deposited: (_, e) => ({ balance: e.balance }) }, |
| 37 | reply: { Deposit: (s) => ({ balance: s.balance }) }, |
| 38 | }) {} |
| 39 | |
| 40 | class Sent extends Domain.Event("Sent", { |
| 41 | from: Schema.String, |
| 42 | to: Schema.String, |
| 43 | amount: Schema.Number, |
| 44 | }) {} |
| 45 | class Send extends Domain.Command("Send", { |
| 46 | target: Schema.String, |
| 47 | input: { from: Schema.String, to: Schema.String, amount: Schema.Number }, |
| 48 | events: [Sent], |
| 49 | }) {} |
| 50 | class Payment extends Domain.Aggregate("Payment", { |
| 51 | id: Schema.String, |
| 52 | state: Schema.Struct({}), |
| 53 | initial: {}, |
| 54 | commands: [Send], |
| 55 | decide: { Send: (_, { from, to, amount }) => [new Sent({ from, to, amount })] }, |
| 56 | evolve: { Sent: (s) => s }, |
| 57 | }) {} |
| 58 | |
| 59 | // ---------------------------------------------------------------- a store you own |
| 60 | |
| 61 | interface Row { |
| 62 | readonly id: string; |
| 63 | readonly wallet: string; |
| 64 | readonly kind: "deposit" | "out" | "in"; |
| 65 | readonly amount: number; |
| 66 | } |
| 67 | |
| 68 | /** A table outside the model, standing in for a database. */ |
| 69 | class Ledger extends Context.Service< |
| 70 | Ledger, |
| 71 | { |
| 72 | readonly upsert: (rows: ReadonlyArray<Row>) => Effect.Effect<void>; |
| 73 | readonly rows: Effect.Effect<ReadonlyArray<Row>>; |
| 74 | readonly runs: Effect.Effect<ReadonlyArray<number>>; |
| 75 | } |
| 76 | >()("Test/Ledger") { |
| 77 | static readonly memory = Layer.effect( |
| 78 | Ledger, |
| 79 | Effect.gen(function* () { |
| 80 | const table = yield* Ref.make(new Map<string, Row>()); |
| 81 | const runs = yield* Ref.make<ReadonlyArray<number>>([]); |
| 82 | return { |
| 83 | upsert: (rows) => |
| 84 | Ref.update(table, (map) => { |
| 85 | const next = new Map(map); |
| 86 | for (const row of rows) next.set(row.id, row); |
| 87 | return next; |
| 88 | }).pipe(Effect.andThen(Ref.update(runs, (all) => [...all, rows.length]))), |
| 89 | rows: Ref.get(table).pipe(Effect.map((map) => [...map.values()])), |
| 90 | runs: Ref.get(runs), |
| 91 | }; |
| 92 | }), |
| 93 | ); |
| 94 | } |
| 95 | |
| 96 | // A projection with two sources and named routes: a payment lands on both wallets. |
| 97 | class WalletLedger extends Domain.Projection("WalletLedger", { |
| 98 | from: [Wallet, Payment], |
| 99 | key: Wallet, |
| 100 | keyOf: { |
| 101 | Sent: { |
| 102 | out: ({ event }) => Wallet.ref(event.from), |
| 103 | in: ({ event }) => Wallet.ref(event.to), |
| 104 | }, |
| 105 | }, |
| 106 | on: [Deposited, Sent], |
| 107 | }) {} |
| 108 | |
| 109 | const walletLedgerLayer = (options?: Domain.Projection.Options) => |
| 110 | WalletLedger.toLayer( |
| 111 | Effect.gen(function* () { |
| 112 | const ledger = yield* Ledger; |
| 113 | return Effect.fn(function* (batch) { |
| 114 | yield* ledger.upsert( |
| 115 | batch.map(({ key, route, event, envelope }) => ({ |
| 116 | id: `${envelope.stream}:${envelope.seq}:${route ?? ""}`, |
| 117 | wallet: key.id, |
| 118 | kind: event._tag === "Deposited" ? "deposit" : (route as "out" | "in"), |
| 119 | amount: event.amount, |
| 120 | })), |
| 121 | ); |
| 122 | }); |
| 123 | }), |
| 124 | options, |
| 125 | ); |
| 126 | |
| 127 | // ---------------------------------------------------------------- a stream the frontend reads |
| 128 | |
| 129 | class Viewer extends Domain.RequestContext<Viewer>()("Test/Viewer", Schema.String) {} |
| 130 | class Unauthenticated extends Domain.Rejection("Unauthenticated") {} |
| 131 | class NotYours extends Domain.Rejection("NotYours") {} |
| 132 | class ViewerSession extends RpcMiddleware.Service<ViewerSession, { provides: Viewer }>()( |
| 133 | "Test/ViewerSession", |
| 134 | { error: Unauthenticated }, |
| 135 | ) {} |
| 136 | const ViewerSessionLive = Layer.succeed(ViewerSession, (effect, { headers }) => |
| 137 | Option.match(Headers.get(headers, "x-viewer"), { |
| 138 | onNone: () => Effect.fail(new Unauthenticated()), |
| 139 | onSome: (name) => Effect.provideService(effect, Viewer, name), |
| 140 | }), |
| 141 | ); |
| 142 | |
| 143 | class BalanceChanged extends Domain.Event("BalanceChanged", { |
| 144 | owner: Schema.String, |
| 145 | balance: Schema.Number, |
| 146 | }) {} |
| 147 | |
| 148 | class WalletCard extends Domain.Stream("WalletCard", { |
| 149 | key: Wallet, |
| 150 | entries: [BalanceChanged], |
| 151 | middleware: [ViewerSession], |
| 152 | rejects: [NotYours], |
| 153 | validate: Effect.fn(function* (_request, latest) { |
| 154 | if (latest && latest.event.owner !== (yield* Viewer)) return yield* new NotYours(); |
| 155 | }), |
| 156 | }) {} |
| 157 | |
| 158 | class WalletCards extends Domain.Projection("WalletCards", { |
| 159 | from: [Wallet], |
| 160 | key: Wallet, |
| 161 | on: [Deposited], |
| 162 | writes: [WalletCard], |
| 163 | }) {} |
| 164 | const WalletCardsLive = WalletCards.toLayer( |
| 165 | Effect.gen(function* () { |
| 166 | const cards = yield* WalletCard; |
| 167 | return Effect.fn(function* (batch) { |
| 168 | for (const input of batch) { |
| 169 | yield* cards.append( |
| 170 | input, |
| 171 | new BalanceChanged({ owner: input.key.id.split("-")[0]!, balance: input.event.balance }), |
| 172 | ); |
| 173 | } |
| 174 | }); |
| 175 | }), |
| 176 | ); |
| 177 | |
| 178 | // ---------------------------------------------------------------- a keyed policy over two sources |
| 179 | |
| 180 | class Flagged extends Domain.Event("Flagged", { reason: Schema.String }) {} |
| 181 | class Flag extends Domain.Command("Flag", { |
| 182 | target: Schema.String, |
| 183 | input: { reason: Schema.String }, |
| 184 | events: [Flagged], |
| 185 | }) {} |
| 186 | class Review extends Domain.Aggregate("Review", { |
| 187 | id: Schema.String, |
| 188 | state: Schema.Struct({ flags: Schema.Number }), |
| 189 | initial: { flags: 0 }, |
| 190 | commands: [Flag], |
| 191 | decide: { Flag: (_, cmd) => [new Flagged({ reason: cmd.reason })] }, |
| 192 | evolve: { Flagged: (s) => ({ flags: s.flags + 1 }) }, |
| 193 | }) {} |
| 194 | |
| 195 | // Keyed by wallet: a deposit and both sides of a payment each run in their wallet's order. |
| 196 | class LargeMovements extends Domain.Policy("LargeMovements", { |
| 197 | from: [Wallet, Payment], |
| 198 | key: Wallet, |
| 199 | keyOf: { |
| 200 | Sent: { |
| 201 | out: ({ event }) => Wallet.ref(event.from), |
| 202 | in: ({ event }) => Wallet.ref(event.to), |
| 203 | }, |
| 204 | }, |
| 205 | on: [Deposited, Sent], |
| 206 | }) {} |
| 207 | const LargeMovementsLive = LargeMovements.toLayer( |
| 208 | Effect.gen(function* () { |
| 209 | const reviews = yield* Review; |
| 210 | return Effect.fn(function* ({ key, route, event }) { |
| 211 | if (event.amount < 100) return; |
| 212 | yield* reviews.send(key.id, new Flag({ reason: `${event._tag}${route ? `:${route}` : ""}` })); |
| 213 | }); |
| 214 | }), |
| 215 | { retry: Schedule.recurs(2) }, |
| 216 | ); |
| 217 | |
| 218 | class Wallets extends Domain.Model("Wallets", { |
| 219 | aggregates: [Wallet, Payment, Review], |
| 220 | policies: [LargeMovements], |
| 221 | projections: [WalletLedger, WalletCards], |
| 222 | streams: [WalletCard], |
| 223 | }) {} |
| 224 | |
| 225 | class WalletApi extends Domain.Api("WalletApi", { |
| 226 | model: Wallets, |
| 227 | commands: ["Deposit"], |
| 228 | streams: ["WalletCard"], |
| 229 | }) {} |
| 230 | |
| 231 | const handlers = (options?: Domain.Projection.Options) => |
| 232 | Layer.mergeAll(walletLedgerLayer(options), WalletCardsLive, LargeMovementsLive); |
| 233 | |
| 234 | const story = Story.make(Wallets, { layer: handlers() }); |
| 235 | const sam = Wallet.ref("sam-1"); |
| 236 | const kim = Wallet.ref("kim-1"); |
| 237 | const p1 = Payment.ref("p-1"); |
| 238 | |
| 239 | describe("Domain Projection", { tags: ["unit", "local"] }, () => { |
| 240 | it.effect("routes inputs to keys and writes a store you own", () => |
| 241 | Effect.gen(function* () { |
| 242 | yield* story( |
| 243 | Story.when(sam, new Deposit({ amount: 50 })), |
| 244 | Story.then(sam, new Deposited({ amount: 50, balance: 50 })), |
| 245 | Story.when(p1, new Send({ from: "sam-1", to: "kim-1", amount: 20 })), |
| 246 | Story.then(p1, new Sent({ from: "sam-1", to: "kim-1", amount: 20 })), |
| 247 | ); |
| 248 | const ledger = yield* Ledger; |
| 249 | const rows = yield* ledger.rows; |
| 250 | expect(rows.map((r) => [r.wallet, r.kind, r.amount]).sort()).toEqual([ |
| 251 | ["kim-1", "in", 20], |
| 252 | ["sam-1", "deposit", 50], |
| 253 | ["sam-1", "out", 20], |
| 254 | ]); |
| 255 | }).pipe(Effect.provide(Ledger.memory)), |
| 256 | ); |
| 257 | |
| 258 | it.effect("history reaches projections", () => |
| 259 | Effect.gen(function* () { |
| 260 | yield* story(Story.given(sam, new Deposited({ amount: 5, balance: 5 }))); |
| 261 | const rows = yield* (yield* Ledger).rows; |
| 262 | expect(rows.map((r) => r.amount)).toEqual([5]); |
| 263 | }).pipe(Effect.provide(Ledger.memory)), |
| 264 | ); |
| 265 | |
| 266 | it.effect("appends to a stream, once per input", () => |
| 267 | story( |
| 268 | Story.when(sam, new Deposit({ amount: 50 })), |
| 269 | Story.then(sam, new Deposited({ amount: 50, balance: 50 })), |
| 270 | Story.streamed(WalletCard, sam, new BalanceChanged({ owner: "sam", balance: 50 })), |
| 271 | Story.when(sam, new Deposit({ amount: 25 })), |
| 272 | Story.then(sam, new Deposited({ amount: 25, balance: 75 })), |
| 273 | Story.streamed(WalletCard, sam, new BalanceChanged({ owner: "sam", balance: 75 })), |
| 274 | Story.when(kim, new Deposit({ amount: 1 })), |
| 275 | Story.then(kim, new Deposited({ amount: 1, balance: 1 })), |
| 276 | Story.streamed(WalletCard, sam), |
| 277 | ).pipe(Effect.provide(Ledger.memory)), |
| 278 | ); |
| 279 | |
| 280 | it.effect("a keyed policy runs per route, over two sources", () => |
| 281 | story( |
| 282 | Story.when(sam, new Deposit({ amount: 150 })), |
| 283 | Story.then(sam, new Deposited({ amount: 150, balance: 150 })), |
| 284 | Story.then(Review.ref("sam-1"), new Flagged({ reason: "Deposited" })), |
| 285 | Story.when(p1, new Send({ from: "sam-1", to: "kim-1", amount: 120 })), |
| 286 | Story.then(p1, new Sent({ from: "sam-1", to: "kim-1", amount: 120 })), |
| 287 | Story.then(Review.ref("sam-1"), new Flagged({ reason: "Sent:out" })), |
| 288 | Story.then(Review.ref("kim-1"), new Flagged({ reason: "Sent:in" })), |
| 289 | ).pipe(Effect.provide(Ledger.memory)), |
| 290 | ); |
| 291 | |
| 292 | it.live("batches a key's inputs and reads your own write with caughtUp", () => |
| 293 | Effect.gen(function* () { |
| 294 | const wallets = yield* Wallet; |
| 295 | for (const amount of [1, 2, 3]) yield* wallets.send(sam, new Deposit({ amount })); |
| 296 | const receipt = yield* wallets.send(sam, new Deposit({ amount: 4 })); |
| 297 | yield* WalletLedger.caughtUp(receipt); |
| 298 | const ledger = yield* Ledger; |
| 299 | expect((yield* ledger.rows).map((r) => r.amount).sort()).toEqual([1, 2, 3, 4]); |
| 300 | // Four inputs, batches of up to three: fewer runs than inputs. |
| 301 | expect((yield* ledger.runs).reduce((a, b) => a + b, 0)).toBe(4); |
| 302 | expect((yield* ledger.runs).length).toBeLessThan(4); |
| 303 | }).pipe( |
| 304 | Effect.provide( |
| 305 | Wallets.layer(handlers({ batch: { size: 3, wait: "50 millis" } })).pipe( |
| 306 | Layer.provideMerge(Layer.mergeAll(InMemory, Ledger.memory)), |
| 307 | ), |
| 308 | ), |
| 309 | ), |
| 310 | ); |
| 311 | |
| 312 | it.live("serves a stream through an Api, judged by validate", () => |
| 313 | Effect.gen(function* () { |
| 314 | const wallets = yield* Wallet; |
| 315 | const receipt = yield* wallets.send(sam, new Deposit({ amount: 40 })); |
| 316 | const api = yield* WalletApi.clientInProcess; |
| 317 | const asSam = { headers: { "x-viewer": "sam" } }; |
| 318 | const latest = yield* api.WalletCard.peek("sam-1", { |
| 319 | ...asSam, |
| 320 | atLeast: { stream: receipt.stream, version: receipt.version }, |
| 321 | }); |
| 322 | expect(latest?.event).toEqual(new BalanceChanged({ owner: "sam", balance: 40 })); |
| 323 | const refused = yield* api.WalletCard.peek("sam-1", { headers: { "x-viewer": "kim" } }).pipe( |
| 324 | Effect.flip, |
| 325 | ); |
| 326 | expect(refused._tag).toBe("NotYours"); |
| 327 | // A read without a session fails with the middleware's error, and the client's type has it. |
| 328 | const anonymous = yield* api.WalletCard.peek("sam-1").pipe( |
| 329 | Effect.catchTag("Unauthenticated", (e) => Effect.succeed(e._tag)), |
| 330 | ); |
| 331 | expect(anonymous).toBe("Unauthenticated"); |
| 332 | yield* wallets.send(sam, new Deposit({ amount: 2 })); |
| 333 | const all = yield* api.WalletCard.events("sam-1", asSam).pipe( |
| 334 | Stream.filter(Domain.Read.isEvent), |
| 335 | Stream.take(2), |
| 336 | Stream.runCollect, |
| 337 | ); |
| 338 | expect([...all].map((entry) => entry.event.balance)).toEqual([40, 42]); |
| 339 | const page = yield* api.WalletCard.list("sam-1", { ...asSam, order: "desc", take: 1 }); |
| 340 | expect(page.entries.map((entry) => entry.event.balance)).toEqual([42]); |
| 341 | }).pipe( |
| 342 | Effect.scoped, |
| 343 | Effect.provide( |
| 344 | Wallets.layer(handlers()).pipe( |
| 345 | Layer.provideMerge(Layer.mergeAll(InMemory, Ledger.memory, ViewerSessionLive)), |
| 346 | ), |
| 347 | ), |
| 348 | ), |
| 349 | ); |
| 350 | |
| 351 | it("refuses a second writer for one stream", () => { |
| 352 | class AlsoCards extends Domain.Projection("AlsoCards", { |
| 353 | from: [Wallet], |
| 354 | key: Wallet, |
| 355 | on: [Deposited], |
| 356 | writes: [WalletCard], |
| 357 | }) {} |
| 358 | class Broken extends Domain.Model("Broken", { |
| 359 | aggregates: [Wallet], |
| 360 | projections: [WalletCards, AlsoCards], |
| 361 | streams: [WalletCard], |
| 362 | }) {} |
| 363 | const exit = Effect.runSyncExit( |
| 364 | Layer.build( |
| 365 | Broken.layer( |
| 366 | Layer.mergeAll(WalletCardsLive, AlsoCards.toLayer(Effect.succeed(() => Effect.void))), |
| 367 | ), |
| 368 | ).pipe(Effect.scoped, Effect.provide(InMemory)) as Effect.Effect<unknown>, |
| 369 | ); |
| 370 | expect(String(exit)).toContain("two writers"); |
| 371 | }); |
| 372 | }); |