The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { expect } from "bun:test"; |
| 2 | import * as Axiom from "@alchemy.run/axiom"; |
| 3 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 4 | import * as Domain from "@alchemy.run/domain"; |
| 5 | import * as Stripe from "@alchemy.run/stripe"; |
| 6 | import * as Test from "@alchemy.run/test/Bun"; |
| 7 | // Runs under `bun test`: deploying a Worker from Vitest does not yet produce a |
| 8 | // correct bundle (the Effect entrypoint is not detected under Vite's transform). |
| 9 | import { CreatePaymentIntent } from "@distilled.cloud/stripe/stripe"; |
| 10 | import * as Alchemy from "alchemy"; |
| 11 | import * as Effect from "effect/Effect"; |
| 12 | import * as FetchHttpClient from "effect/http/FetchHttpClient"; |
| 13 | import * as HttpClient from "effect/http/HttpClient"; |
| 14 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 15 | import * as Layer from "effect/Layer"; |
| 16 | import * as Option from "effect/Option"; |
| 17 | import * as Schedule from "effect/Schedule"; |
| 18 | import * as Socket from "effect/socket/Socket"; |
| 19 | import * as Stream from "effect/Stream"; |
| 20 | import Stack from "../alchemy.run.ts"; |
| 21 | import { CustomerId } from "../packages/domain/src/Customer/Customer.id.ts"; |
| 22 | import { CustomerDashboard } from "../packages/domain/src/Customer/CustomerDashboard.view.ts"; |
| 23 | import { CustomerApi } from "../packages/domain/src/CustomerApi.api.ts"; |
| 24 | import { sessionClient } from "../packages/domain/src/Session.middleware.ts"; |
| 25 | import { mfa, register, transfer } from "../packages/server/test/flows.ts"; |
| 26 | |
| 27 | const { test, beforeAll, afterAll, deploy, destroy } = Test.make({ |
| 28 | providers: Layer.mergeAll(Cloudflare.providers(), Stripe.providers(), Axiom.providers()), |
| 29 | state: Alchemy.localState(), |
| 30 | }); |
| 31 | |
| 32 | const stack = beforeAll(destroy(Stack).pipe(Effect.andThen(deploy(Stack)))); |
| 33 | afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack)); |
| 34 | |
| 35 | /** Sign a customer in through the bank's `/api/session` route; returns the signed session token. */ |
| 36 | const signIn = Effect.fn(function* (url: string, customerId: string) { |
| 37 | const response = yield* HttpClient.execute( |
| 38 | HttpClientRequest.post(`${url}/api/session`).pipe( |
| 39 | HttpClientRequest.bodyJsonUnsafe({ customerId }), |
| 40 | ), |
| 41 | ).pipe(Effect.provide(FetchHttpClient.layer)); |
| 42 | return ((yield* response.json) as { readonly token: string }).token; |
| 43 | }); |
| 44 | |
| 45 | /** |
| 46 | * A typed CustomerApi client signed in as `customerId`: commands over HTTP, |
| 47 | * every watch a WebSocket to the Durable Object that owns what it reads. |
| 48 | * Not a browser, so it sends `Authorization` rather than the session cookie: |
| 49 | * with its calls through `sessionClient`, and on each WebSocket upgrade |
| 50 | * through Bun's `WebSocket`, which accepts headers. |
| 51 | */ |
| 52 | const customerClient = Effect.fn(function* (url: string, customerId: string) { |
| 53 | const token = yield* signIn(url, customerId); |
| 54 | const webSockets = Layer.succeed( |
| 55 | Socket.WebSocketConstructor, |
| 56 | (socketUrl, protocols) => |
| 57 | new WebSocket(socketUrl, { |
| 58 | protocols, |
| 59 | headers: { authorization: `Bearer ${token}` }, |
| 60 | } as unknown as string[]), |
| 61 | ); |
| 62 | return yield* CustomerApi.client.pipe( |
| 63 | Effect.provide( |
| 64 | Layer.mergeAll(Domain.protocolWebSocket(`${url}/api`), sessionClient(token)).pipe( |
| 65 | Layer.provide(Layer.mergeAll(FetchHttpClient.layer, webSockets)), |
| 66 | ), |
| 67 | ), |
| 68 | ); |
| 69 | }); |
| 70 | |
| 71 | test( |
| 72 | "the deployed bank decides, projects, runs policies and streams views", |
| 73 | Effect.gen(function* () { |
| 74 | const { url } = yield* stack; |
| 75 | const base = url.replace(/\/+$/, ""); |
| 76 | |
| 77 | // wait for the workers.dev URL to serve this Worker (Cloudflare's own 404 page comes first) |
| 78 | yield* HttpClient.get(`${base}/health`).pipe( |
| 79 | Effect.flatMap((res) => res.text), |
| 80 | Effect.flatMap((body) => (body === "Not Found" ? Effect.void : Effect.fail("not ready"))), |
| 81 | Effect.retry({ schedule: Schedule.spaced("1 second"), times: 30 }), |
| 82 | ); |
| 83 | |
| 84 | const sam = yield* customerClient(base, "c-1"); |
| 85 | const alex = yield* customerClient(base, "c-2"); |
| 86 | |
| 87 | // right after a deploy, Durable Objects can still answer with the placeholder |
| 88 | // script: wait until a read reaches one (any domain answer means it did) |
| 89 | yield* sam.CustomerDashboard.get(CustomerId.make("c-1")).pipe( |
| 90 | Effect.retry({ |
| 91 | while: (e) => e._tag === "RpcClientError", |
| 92 | schedule: Schedule.spaced("1 second"), |
| 93 | times: 30, |
| 94 | }), |
| 95 | Effect.ignore, |
| 96 | ); |
| 97 | |
| 98 | // a command, then a policy (MainAccountProvisioning) opens the account; the dashboard shows it |
| 99 | const samMain = yield* register(sam, "c-1", "sam"); |
| 100 | const alexMain = yield* register(alex, "c-2", "alex"); |
| 101 | |
| 102 | // a command's reply, computed from the committed state in the account's Durable Object |
| 103 | expect((yield* sam.DepositMoney(samMain, { amount: 100 })).reply).toEqual({ |
| 104 | balance: 100, |
| 105 | }); |
| 106 | |
| 107 | // MFA middleware, and ownership enforced by the aggregate against the session's actor |
| 108 | expect((yield* sam.WithdrawMoney(samMain, { amount: 10 }).pipe(Effect.flip))._tag).toBe( |
| 109 | "MfaRequired", |
| 110 | ); |
| 111 | expect((yield* sam.WithdrawMoney(samMain, { amount: 10 }, mfa)).reply).toEqual({ |
| 112 | balance: 90, |
| 113 | }); |
| 114 | expect((yield* alex.WithdrawMoney(samMain, { amount: 10 }, mfa).pipe(Effect.flip))._tag).toBe( |
| 115 | "NotOwner", |
| 116 | ); |
| 117 | |
| 118 | // a process manager across three aggregates, followed by the requester through a multi-source view |
| 119 | const outcome = yield* transfer(sam, { |
| 120 | transferId: "t-1", |
| 121 | from: samMain, |
| 122 | to: alexMain, |
| 123 | amount: 40, |
| 124 | }); |
| 125 | expect(outcome.status).toBe("completed"); |
| 126 | // the recipient sees it arrive on their own account |
| 127 | const incoming = yield* alex.AccountTransfers.list(alexMain).pipe( |
| 128 | Effect.filterOrFail( |
| 129 | (p) => p.entries.length === 1, |
| 130 | () => "not projected yet", |
| 131 | ), |
| 132 | Effect.retry({ schedule: Schedule.spaced("500 millis"), times: 20 }), |
| 133 | ); |
| 134 | expect(incoming.entries[0]!.event.direction).toBe("in"); |
| 135 | |
| 136 | // Stripe deliveries are signature-checked by consumeEvents before they reach the Bank |
| 137 | const forged = yield* HttpClient.execute( |
| 138 | HttpClientRequest.post(`${base}/webhooks/stripe`).pipe( |
| 139 | HttpClientRequest.setHeader("stripe-signature", "t=1,v1=00"), |
| 140 | HttpClientRequest.bodyText("{}"), |
| 141 | ), |
| 142 | ); |
| 143 | expect(forged.status).toBe(401); |
| 144 | |
| 145 | // views are eventually consistent: wait until the transfer has been projected |
| 146 | const page = yield* sam.Statement.list(samMain, { order: "desc" }).pipe( |
| 147 | Effect.filterOrFail( |
| 148 | (p) => p.entries.length === 3, |
| 149 | () => "not projected yet", |
| 150 | ), |
| 151 | Effect.retry({ schedule: Schedule.spaced("500 millis"), times: 20 }), |
| 152 | ); |
| 153 | expect(page.entries.map((e) => e.event.kind)).toEqual([ |
| 154 | "transfer-out", |
| 155 | "withdrawal", |
| 156 | "deposit", |
| 157 | ]); |
| 158 | |
| 159 | // a feed pushed by the view's Durable Object marks the end of its history |
| 160 | const feed = yield* sam.Statement.events(samMain).pipe( |
| 161 | Stream.take(4), |
| 162 | Stream.runCollect, |
| 163 | Effect.timeout("20 seconds"), |
| 164 | ); |
| 165 | expect( |
| 166 | feed.map((frame) => (Domain.Read.isCaughtUp(frame) ? frame.cursor : frame.event.kind)), |
| 167 | ).toEqual(["deposit", "withdrawal", "transfer-out", page.entries[0]!.envelope.seq]); |
| 168 | // a watched state's cursor resumes the feed with nothing twice: straight to CaughtUp |
| 169 | const [watched] = yield* sam.Statement.watch(samMain).pipe( |
| 170 | Stream.take(1), |
| 171 | Stream.runCollect, |
| 172 | Effect.timeout("20 seconds"), |
| 173 | ); |
| 174 | expect(watched!.cursor).toBe(page.entries[0]!.envelope.seq); |
| 175 | const [resumed] = yield* sam.Statement.events(samMain, { after: watched!.cursor }).pipe( |
| 176 | Stream.take(1), |
| 177 | Stream.runCollect, |
| 178 | Effect.timeout("20 seconds"), |
| 179 | ); |
| 180 | expect(resumed).toEqual({ _tag: "CaughtUp", cursor: watched!.cursor }); |
| 181 | |
| 182 | // an aggregate's Durable Object reads the same way: its watched cursor ends its history |
| 183 | const [account] = yield* sam.Account.watch(samMain).pipe( |
| 184 | Stream.take(1), |
| 185 | Stream.runCollect, |
| 186 | Effect.timeout("20 seconds"), |
| 187 | ); |
| 188 | const history = yield* sam.Account.events(samMain).pipe( |
| 189 | Stream.takeUntil((frame) => Domain.Read.isCaughtUp(frame)), |
| 190 | Stream.runCollect, |
| 191 | Effect.timeout("20 seconds"), |
| 192 | ); |
| 193 | expect(history.at(-1)).toEqual({ _tag: "CaughtUp", cursor: account!.cursor }); |
| 194 | expect(history.length - 1).toBe(account!.cursor); |
| 195 | |
| 196 | // a projection (AccountCards) appends to a stream; its Durable Object pushes each new card |
| 197 | const card = yield* sam.AccountCard.watch(samMain).pipe( |
| 198 | Stream.map(({ state }) => state), |
| 199 | Stream.filter((latest) => latest?.event.balance === 50), |
| 200 | Stream.runHead, |
| 201 | Effect.timeout("20 seconds"), |
| 202 | ); |
| 203 | expect(Option.getOrThrow(card)?.event).toMatchObject({ owner: "sam", balance: 50 }); |
| 204 | // the stream's validate: only the owner reads the card |
| 205 | expect((yield* alex.AccountCard.peek(samMain).pipe(Effect.flip))._tag).toBe("NotOwner"); |
| 206 | |
| 207 | // a projection (Ledger) writes D1 in batches; the ledger is served by a plain route |
| 208 | const ledger = yield* HttpClient.execute( |
| 209 | HttpClientRequest.get(`${base}/api/ledger/${samMain}`).pipe( |
| 210 | HttpClientRequest.bearerToken(yield* signIn(base, "c-1")), |
| 211 | ), |
| 212 | ).pipe( |
| 213 | Effect.flatMap((res) => res.json), |
| 214 | Effect.map( |
| 215 | (rows) => rows as ReadonlyArray<{ readonly kind: string; readonly amount: number }>, |
| 216 | ), |
| 217 | Effect.filterOrFail( |
| 218 | (rows) => rows.length === 3, |
| 219 | () => "not projected yet", |
| 220 | ), |
| 221 | Effect.retry({ schedule: Schedule.spaced("1 second"), times: 30 }), |
| 222 | ); |
| 223 | expect(ledger.map((row) => [row.kind, row.amount])).toEqual([ |
| 224 | ["MoneyDeposited", 100], |
| 225 | ["MoneyWithdrawn", 10], |
| 226 | ["TransferDebited", 40], |
| 227 | ]); |
| 228 | |
| 229 | // a live view (AccountSummary → CustomerDashboard, view to view), pushed by its Durable Object |
| 230 | const dashboard = yield* sam.CustomerDashboard.watch(CustomerId.make("c-1")).pipe( |
| 231 | Stream.map(({ state }) => state), |
| 232 | Stream.filter((d) => d !== null && CustomerDashboard.computed.totalBalance(d) === 50), |
| 233 | Stream.runHead, |
| 234 | Effect.timeout("20 seconds"), |
| 235 | ); |
| 236 | expect(Option.getOrThrow(dashboard)).toMatchObject({ name: "sam" }); |
| 237 | }).pipe(Effect.scoped), |
| 238 | { timeout: 180_000 }, |
| 239 | ); |
| 240 | |
| 241 | // Real delivery to a fresh workers.dev URL waits on edge propagation and |
| 242 | // Stripe's retry backoff (minutes), so it is opt-in. |
| 243 | test.skipIf(process.env.STRIPE_TEST_REAL_DELIVERY !== "1")( |
| 244 | "a Stripe payment settles onto an account through consumeEvents", |
| 245 | Effect.gen(function* () { |
| 246 | const { url } = yield* stack; |
| 247 | const base = url.replace(/\/+$/, ""); |
| 248 | const sam = yield* customerClient(base, "c-3"); |
| 249 | const accountId = yield* register(sam, "c-3", "sam"); |
| 250 | |
| 251 | // a test-mode card payment whose metadata names the account |
| 252 | yield* CreatePaymentIntent({ |
| 253 | amount: 500, |
| 254 | currency: "usd", |
| 255 | confirm: true, |
| 256 | payment_method: "pm_card_visa", |
| 257 | automatic_payment_methods: { enabled: true, allow_redirects: "never" }, |
| 258 | metadata: { accountId }, |
| 259 | }).pipe( |
| 260 | Effect.provide( |
| 261 | Stripe.fromAuthProvider().pipe( |
| 262 | Layer.provideMerge(Stripe.StripeAuth), |
| 263 | Layer.provideMerge(FetchHttpClient.layer), |
| 264 | ), |
| 265 | ), |
| 266 | ); |
| 267 | |
| 268 | const page = yield* sam.Statement.list(accountId, { order: "desc" }).pipe( |
| 269 | Effect.filterOrFail( |
| 270 | (p) => p.entries.some((e) => e.event.kind === "settlement"), |
| 271 | () => "not delivered yet", |
| 272 | ), |
| 273 | Effect.retry({ schedule: Schedule.spaced("5 seconds"), times: 36 }), |
| 274 | ); |
| 275 | expect(page.entries[0]!.event).toMatchObject({ |
| 276 | kind: "settlement", |
| 277 | amount: 500, |
| 278 | balance: 500, |
| 279 | }); |
| 280 | }).pipe(Effect.scoped), |
| 281 | { timeout: 240_000 }, |
| 282 | ); |