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
| 1 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 2 | import { expect } from "@alchemy.run/test"; |
| 3 | import * as Test from "@alchemy.run/test/Alchemy"; |
| 4 | import * as Data from "effect/Data"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import * as HttpClient from "effect/http/HttpClient"; |
| 7 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 8 | import * as HttpClientResponse from "effect/http/HttpClientResponse"; |
| 9 | import { MinimumLogLevel } from "effect/References"; |
| 10 | import * as Schedule from "effect/Schedule"; |
| 11 | import QueueWorker from "./round-trip-worker.ts"; |
| 12 | |
| 13 | const { test } = Test.make({ providers: Cloudflare.providers() }); |
| 14 | |
| 15 | const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info"); |
| 16 | |
| 17 | class CountMismatch extends Data.TaggedError("CountMismatch")<{ |
| 18 | expected: number; |
| 19 | actual: number; |
| 20 | }> {} |
| 21 | |
| 22 | /** |
| 23 | * End-to-end Cloudflare Queue round-trip via |
| 24 | * `Cloudflare.Queues.consumeQueueMessages(queue, handler)`. |
| 25 | * |
| 26 | * Stack: |
| 27 | * |
| 28 | * - `Counter` Durable Object (per-key count + last-bodies tail). |
| 29 | * - `RoundTripQueue` and `SecondaryRoundTripQueue` |
| 30 | * (Cloudflare.Queues.Queue). |
| 31 | * - `QueueRoundTripWorker` — exposes: |
| 32 | * - `POST /send?name=K` → enqueues a message via the |
| 33 | * `Cloudflare.Queues.WriteQueue` producer. |
| 34 | * - `POST /send-secondary?name=K` → enqueues to a second |
| 35 | * Queue bound to the same Worker. |
| 36 | * - subscribe handlers → increment the named Counter DO |
| 37 | * and stores the body, via |
| 38 | * `Cloudflare.Queues.consumeQueueMessages(RoundTripQueue, handler)`. |
| 39 | * - `GET /count?name=K` → reads the DO snapshot. |
| 40 | * - `Cloudflare.Queues.Consumer` is auto-created by the policy |
| 41 | * side of `consumeQueueMessages(...)` — there is no explicit |
| 42 | * `Consumer(...)` yield in the stack. |
| 43 | * |
| 44 | * The test sends N messages, then polls `/count?name=K` with |
| 45 | * exponential backoff until the DO reports `count >= N`. The |
| 46 | * round-trip proves: producer binding writes, Cloudflare dispatches |
| 47 | * to the registered consumer, the subscribe handler runs, the DO |
| 48 | * RPC stub from inside the queue handler works, and the test |
| 49 | * client can read the resulting DO state. |
| 50 | * |
| 51 | * The second queue catches regressions where Worker dispatch stops |
| 52 | * after the first registered queue listener. The listener generated |
| 53 | * by `consumeQueueMessages(...)` performs its queue-name check inside |
| 54 | * the returned Effect, so dispatch must invoke every listener for |
| 55 | * the event type. |
| 56 | */ |
| 57 | test.provider.skipIf(!!process.env.FAST)( |
| 58 | "send → subscribe handlers → DO state → polled by test client", |
| 59 | (stack) => |
| 60 | Effect.gen(function* () { |
| 61 | yield* stack.destroy(); |
| 62 | |
| 63 | const out = yield* stack.deploy( |
| 64 | Effect.gen(function* () { |
| 65 | // The Worker's init body yields Counter and |
| 66 | // both Queue resources internally — yielding QueueWorker |
| 67 | // is enough to bring the whole stack (Queues + |
| 68 | // QueueConsumers + Counter DO + Worker) into the plan. |
| 69 | const worker = yield* QueueWorker; |
| 70 | return { url: worker.url }; |
| 71 | }), |
| 72 | ); |
| 73 | const url = out.url; |
| 74 | expect(url).toBeTypeOf("string"); |
| 75 | const baseUrl = url as string; |
| 76 | |
| 77 | // Use a unique counter key per test run so we don't |
| 78 | // accumulate state from prior runs (the DO survives across |
| 79 | // deploys when the namespace logical id is stable). |
| 80 | const name = `roundtrip-${Math.random().toString(36).slice(2, 8)}`; |
| 81 | const secondaryName = `roundtrip-secondary-${Math.random().toString(36).slice(2, 8)}`; |
| 82 | const messages = ["alpha", "beta", "gamma", "delta"]; |
| 83 | const secondaryMessages = ["one", "two"]; |
| 84 | |
| 85 | const sendMessage = (pathname: string, counterName: string, text: string) => |
| 86 | HttpClient.execute( |
| 87 | HttpClientRequest.post( |
| 88 | `${baseUrl}${pathname}?name=${encodeURIComponent(counterName)}`, |
| 89 | ).pipe(HttpClientRequest.bodyText(text)), |
| 90 | ).pipe( |
| 91 | Effect.flatMap((res) => |
| 92 | res.status === 202 |
| 93 | ? Effect.succeed(res) |
| 94 | : Effect.fail(new Error(`Worker not ready: ${res.status}`)), |
| 95 | ), |
| 96 | Effect.retry({ |
| 97 | // Bound fresh workers.dev readiness to roughly 25 seconds. |
| 98 | schedule: Schedule.max([ |
| 99 | Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("3 seconds")]), |
| 100 | Schedule.recurs(10), |
| 101 | ]), |
| 102 | }), |
| 103 | ); |
| 104 | |
| 105 | for (const text of messages) { |
| 106 | // Cloudflare's edge takes a few seconds to start serving a fresh |
| 107 | // workers.dev URL — retry until the worker returns 202. |
| 108 | const sendResponse = yield* sendMessage("/send", name, text); |
| 109 | expect(sendResponse.status).toBe(202); |
| 110 | const sent = (yield* sendResponse.json) as { |
| 111 | sent: { name: string; text: string }; |
| 112 | }; |
| 113 | expect(sent.sent.name).toBe(name); |
| 114 | expect(sent.sent.text).toBe(text); |
| 115 | } |
| 116 | |
| 117 | for (const text of secondaryMessages) { |
| 118 | const sendResponse = yield* sendMessage("/send-secondary", secondaryName, text); |
| 119 | expect(sendResponse.status).toBe(202); |
| 120 | const sent = (yield* sendResponse.json) as { |
| 121 | sent: { name: string; text: string }; |
| 122 | }; |
| 123 | expect(sent.sent.name).toBe(secondaryName); |
| 124 | expect(sent.sent.text).toBe(text); |
| 125 | } |
| 126 | |
| 127 | // GET /count is idempotent, so we retry on *any* failure — not |
| 128 | // just CountMismatch. A fresh/hibernating DO can briefly return a |
| 129 | // 500 ("Internal Server Error", which isn't valid JSON and would |
| 130 | // otherwise surface as a decode error), and edge propagation can |
| 131 | // 404 the first calls; both are transient and must be retried. |
| 132 | const readSnapshot = (counterName: string, expected: number) => |
| 133 | HttpClient.get(`${baseUrl}/count?name=${encodeURIComponent(counterName)}`).pipe( |
| 134 | Effect.flatMap(HttpClientResponse.filterStatusOk), |
| 135 | Effect.flatMap((res) => res.json), |
| 136 | Effect.flatMap((body) => { |
| 137 | const snap = body as { count: number; lastBodies: string[] }; |
| 138 | return snap.count >= expected |
| 139 | ? Effect.succeed(snap) |
| 140 | : Effect.fail( |
| 141 | new CountMismatch({ |
| 142 | expected, |
| 143 | actual: snap.count, |
| 144 | }), |
| 145 | ); |
| 146 | }), |
| 147 | Effect.retry({ |
| 148 | // Bound consumer catch-up to roughly 35 seconds. |
| 149 | schedule: Schedule.max([ |
| 150 | Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("4 seconds")]), |
| 151 | Schedule.recurs(10), |
| 152 | ]), |
| 153 | }), |
| 154 | ); |
| 155 | |
| 156 | // Poll the DO snapshot until each consumer has caught up. |
| 157 | const [snapshot, secondarySnapshot] = yield* Effect.all( |
| 158 | [ |
| 159 | readSnapshot(name, messages.length), |
| 160 | readSnapshot(secondaryName, secondaryMessages.length), |
| 161 | ], |
| 162 | { concurrency: "unbounded" }, |
| 163 | ); |
| 164 | |
| 165 | // The DO observed every message. Cloudflare Queues are |
| 166 | // *at-least-once*: a message can be delivered (and thus recorded) |
| 167 | // more than once, so `lastBodies` may legitimately contain |
| 168 | // duplicates and `count` may exceed `messages.length`. Order is |
| 169 | // also best-effort (batches dispatch in parallel). So assert every |
| 170 | // expected message was observed at least once (set containment), |
| 171 | // not exact multiset equality — the latter flakes whenever |
| 172 | // Cloudflare redelivers a message. |
| 173 | expect([...new Set(snapshot.lastBodies)].sort()).toEqual([...messages].sort()); |
| 174 | expect(secondarySnapshot.count).toBeGreaterThanOrEqual(secondaryMessages.length); |
| 175 | expect([...new Set(secondarySnapshot.lastBodies)].sort()).toEqual( |
| 176 | [...secondaryMessages].sort(), |
| 177 | ); |
| 178 | |
| 179 | yield* stack.destroy(); |
| 180 | }).pipe(logLevel), |
| 181 | { |
| 182 | tags: [ |
| 183 | "provider:cloudflare", |
| 184 | "provider:cloudflare:queue", |
| 185 | "provider:cloudflare:worker", |
| 186 | "live", |
| 187 | ], |
| 188 | timeout: 120_000, |
| 189 | }, |
| 190 | ); |