@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 447 lines 16.1 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { generateLocalId, isLiveId } from "@alchemy.run/cloudflare/LocalRuntime";
4 import { expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as queues from "@distilled.cloud/cloudflare/queues";
7 import * as Provider from "alchemy/Provider";
8 import { State } from "alchemy/State";
9 import type { CreatedResourceState } from "alchemy/State/ResourceState";
10 import { poll } from "alchemy/Util/poll";
11 import * as Effect from "effect/Effect";
12 import * as Exit from "effect/Exit";
13 import * as HttpClient from "effect/http/HttpClient";
14 import { MinimumLogLevel } from "effect/References";
15 import * as Schedule from "effect/Schedule";
16 import ConsumerWorker from "./fixtures/dedicated-consumer-worker.ts";
17 import ProducerWorker from "./fixtures/dedicated-producer-worker.ts";
18
19 const { test } = Test.make({ providers: Cloudflare.providers() });
20
21 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
22
23 /**
24 * Seed a `created` Queue state row whose `queueId` is a `dev:` mock id —
25 * i.e. the shape `alchemy dev` persists when a queue is "created" locally
26 * against the in-memory local runtime instead of Cloudflare. Dev runs stamp
27 * `providerMode: "local"` on every commit, so the seeded row carries it.
28 */
29 const seedDevQueue = (input: {
30 stackName: string;
31 stage: string;
32 fqn: string;
33 queueId: string;
34 queueName: string;
35 accountId: string;
36 }) =>
37 Effect.gen(function* () {
38 const state = yield* yield* State;
39 yield* state.set({
40 stack: input.stackName,
41 stage: input.stage,
42 fqn: input.fqn,
43 value: {
44 kind: "resource",
45 status: "created",
46 resourceType: "Cloudflare.Queues.Queue",
47 namespace: undefined,
48 fqn: input.fqn,
49 logicalId: input.fqn,
50 instanceId: "00000000000000000000000000000001",
51 providerVersion: 0,
52 providerMode: "local",
53 bindings: [],
54 downstream: [],
55 props: {},
56 attr: { queueId: input.queueId, queueName: input.queueName, accountId: input.accountId },
57 } satisfies CreatedResourceState,
58 });
59 });
60
61 /**
62 * Promotion: a queue that was "created" in dev (its persisted `queueId`
63 * is a `dev:` mock id) must be promoted to a real Cloudflare queue on the
64 * first live deploy.
65 *
66 * The row is stamped `providerMode: "local"`, which differs from the
67 * deploy's resolved mode (`live`), so the engine plans a REPLACEMENT: the
68 * live provider creates a real queue and the old local-mode generation is
69 * deleted via the local provider (no cloud call for the `dev:` id). The
70 * resulting `queueId` must be a live id and resolvable on Cloudflare.
71 */
72 test.provider(
73 "promotes a dev queue to a live queue on deploy",
74 (stack) =>
75 Effect.gen(function* () {
76 const { accountId } = yield* yield* CloudflareEnvironment;
77
78 yield* stack.destroy();
79
80 const devQueueId = generateLocalId();
81 yield* seedDevQueue({
82 stackName: stack.name,
83 stage: stack.stage,
84 fqn: "Q",
85 queueId: devQueueId,
86 queueName: "dev-placeholder-name",
87 accountId,
88 });
89
90 const deployed = yield* stack.deploy(
91 Effect.gen(function* () {
92 const queue = yield* Cloudflare.Queues.Queue("Q");
93 return { queue };
94 }),
95 );
96
97 // The dev id has been replaced with a real Cloudflare queue id.
98 expect(isLiveId(deployed.queue.queueId)).toBe(true);
99 expect(deployed.queue.queueId).not.toEqual(devQueueId);
100
101 // The promoted queue is a real, resolvable Cloudflare resource. A
102 // brand-new queue can briefly 404 from this out-of-band read under load,
103 // so ride out the read-after-create lag before asserting.
104 const live = yield* queues.getQueue({ accountId, queueId: deployed.queue.queueId }).pipe(
105 Effect.retry({
106 while: (e) => e._tag === "QueueNotFound",
107 schedule: Schedule.exponential("500 millis"),
108 times: 8,
109 }),
110 );
111 expect(live.queueId).toEqual(deployed.queue.queueId);
112
113 // And the persisted state now carries the live id, not the dev one.
114 const persisted = yield* Effect.gen(function* () {
115 const state = yield* yield* State;
116 return yield* state.get({ stack: stack.name, stage: stack.stage, fqn: "Q" });
117 });
118 expect((persisted as any)?.attr?.queueId).toEqual(deployed.queue.queueId);
119
120 yield* stack.destroy();
121
122 // After destroy the promoted (live) queue is gone on Cloudflare.
123 const exit = yield* Effect.exit(
124 queues.getQueue({ accountId, queueId: deployed.queue.queueId }),
125 );
126 expect(Exit.isFailure(exit)).toBe(true);
127 }).pipe(logLevel),
128 { tags: ["provider:cloudflare", "provider:cloudflare:queue", "live"] },
129 );
130
131 // Canonical `list()` test (account-scoped collection): deploy a real
132 // queue, resolve the provider from context via `findProvider`, call
133 // `list()`, and assert the deployed queue appears in the exhaustively-
134 // paginated result.
135 test.provider(
136 "list enumerates the deployed queue",
137 (stack) =>
138 Effect.gen(function* () {
139 yield* stack.destroy();
140
141 const deployed = yield* stack.deploy(
142 Effect.gen(function* () {
143 return yield* Cloudflare.Queues.Queue("ListQueue");
144 }),
145 );
146
147 const provider = yield* Provider.findProvider(Cloudflare.Queues.Queue);
148
149 // A just-created queue can lag the account-wide list under load — poll
150 // until it shows up (bounded) instead of asserting on the first read.
151 const all = yield* poll({
152 description: "list() includes the deployed queue",
153 effect: provider.list(),
154 predicate: (all) => all.some((q) => q.queueId === deployed.queueId),
155 schedule: Schedule.max([Schedule.spaced("2 seconds"), Schedule.recurs(20)]),
156 });
157
158 expect(all.some((q) => q.queueId === deployed.queueId)).toBe(true);
159
160 yield* stack.destroy();
161 }).pipe(logLevel),
162 { tags: ["provider:cloudflare", "provider:cloudflare:queue", "live"] },
163 );
164
165 /**
166 * Suppressed delete: a queue that only ever existed in dev (its
167 * persisted `queueId` is a `dev:` mock id) has no Cloudflare counterpart.
168 * Destroying it must NOT issue a `deleteQueue` against Cloudflare — the
169 * `dev:` id is not a valid queue id and the request URL would be
170 * malformed. The row is stamped `providerMode: "local"`, so the engine
171 * resolves the LOCAL provider's `delete` for it (an in-memory registry
172 * removal), and destroy succeeds with the state row removed cleanly.
173 */
174 test.provider(
175 "suppresses deletion of a dev-only queue",
176 (stack) =>
177 Effect.gen(function* () {
178 const { accountId } = yield* yield* CloudflareEnvironment;
179
180 yield* stack.destroy();
181
182 const devQueueId = generateLocalId();
183 yield* seedDevQueue({
184 stackName: stack.name,
185 stage: stack.stage,
186 fqn: "Q",
187 queueId: devQueueId,
188 queueName: "dev-placeholder-name",
189 accountId,
190 });
191
192 // Destroy must not attempt a (malformed) live delete against the dev id.
193 const exit = yield* Effect.exit(stack.destroy());
194 expect(Exit.isSuccess(exit)).toBe(true);
195
196 // The dev-only resource is removed from state.
197 const persisted = yield* Effect.gen(function* () {
198 const state = yield* yield* State;
199 return yield* state.get({ stack: stack.name, stage: stack.stage, fqn: "Q" });
200 });
201 expect(persisted).toBeUndefined();
202 }).pipe(logLevel),
203 { tags: ["provider:cloudflare", "provider:cloudflare:queue", "live"] },
204 );
205
206 const getLiveQueue = (accountId: string, queueId: string) =>
207 queues.getQueue({ accountId, queueId }).pipe(
208 // A brand-new or just-patched queue can briefly read stale under load.
209 Effect.retry({
210 while: (e) => e._tag === "QueueNotFound",
211 schedule: Schedule.exponential("500 millis"),
212 times: 8,
213 }),
214 );
215
216 const expectQueueGone = (accountId: string, queueId: string) =>
217 queues.getQueue({ accountId, queueId }).pipe(
218 Effect.flatMap(() => Effect.fail({ _tag: "QueueNotDeleted" } as const)),
219 Effect.catchTag(["QueueNotFound", "InvalidRoute"], () => Effect.void),
220 Effect.retry({
221 while: (e) => e._tag === "QueueNotDeleted",
222 schedule: Schedule.max([Schedule.fixed("500 millis"), Schedule.recurs(20)]),
223 }),
224 );
225
226 const queueNameFor = (stage: string, suffix: string) =>
227 `alchemy-test-${stage.toLowerCase().replace(/[^a-z0-9-]/g, "-")}-${suffix}`;
228
229 // #2226 — settings are sent on create and update, and a removed setting
230 // goes back to the Cloudflare default.
231 test.provider(
232 "creates, updates and resets queue settings",
233 (stack) =>
234 Effect.gen(function* () {
235 const { accountId } = yield* yield* CloudflareEnvironment;
236
237 yield* stack.destroy();
238
239 const created = yield* stack.deploy(
240 Effect.gen(function* () {
241 return yield* Cloudflare.Queues.Queue("SettingsQueue", {
242 messageRetentionPeriod: 1209600,
243 deliveryDelay: 5,
244 });
245 }),
246 );
247 expect(created).toMatchObject({
248 messageRetentionPeriod: 1209600,
249 deliveryDelay: 5,
250 deliveryPaused: false,
251 });
252 const live = yield* getLiveQueue(accountId, created.queueId);
253 expect(live.settings?.messageRetentionPeriod).toEqual(1209600);
254 expect(live.settings?.deliveryDelay).toEqual(5);
255
256 const updated = yield* stack.deploy(
257 Effect.gen(function* () {
258 return yield* Cloudflare.Queues.Queue("SettingsQueue", {
259 deliveryDelay: 10,
260 deliveryPaused: true,
261 });
262 }),
263 );
264 // Settings update in place.
265 expect(updated.queueId).toEqual(created.queueId);
266 expect(updated).toMatchObject({
267 messageRetentionPeriod: 345600,
268 deliveryDelay: 10,
269 deliveryPaused: true,
270 });
271 const after = yield* getLiveQueue(accountId, updated.queueId);
272 expect(after.settings?.messageRetentionPeriod).toEqual(345600);
273 expect(after.settings?.deliveryDelay).toEqual(10);
274 expect(after.settings?.deliveryPaused).toEqual(true);
275
276 yield* stack.destroy();
277 yield* expectQueueGone(accountId, created.queueId);
278 }).pipe(logLevel),
279 { tags: ["provider:cloudflare", "provider:cloudflare:queue", "live"] },
280 );
281
282 // #2226 — jurisdiction is create-only. Changing it replaces the queue, and
283 // an explicit name (unique per account across jurisdictions) forces the old
284 // generation to be deleted first.
285 test.provider(
286 "creates a queue in a jurisdiction and replaces it when the jurisdiction changes",
287 (stack) =>
288 Effect.gen(function* () {
289 const { accountId } = yield* yield* CloudflareEnvironment;
290 const name = queueNameFor(stack.stage, "jurisdiction");
291
292 yield* stack.destroy();
293
294 const eu = yield* stack.deploy(
295 Effect.gen(function* () {
296 return yield* Cloudflare.Queues.Queue("JurisdictionQueue", {
297 name,
298 jurisdiction: "eu",
299 deliveryDelay: 3,
300 });
301 }),
302 );
303 expect(eu.jurisdiction).toEqual("eu");
304 const live = yield* getLiveQueue(accountId, eu.queueId);
305 expect(live.jurisdiction).toEqual("eu");
306 expect(live.settings?.deliveryDelay).toEqual(3);
307
308 const global = yield* stack.deploy(
309 Effect.gen(function* () {
310 return yield* Cloudflare.Queues.Queue("JurisdictionQueue", {
311 name,
312 deliveryDelay: 3,
313 });
314 }),
315 );
316 expect(global.queueId).not.toEqual(eu.queueId);
317 expect(global.queueName).toEqual(name);
318 expect(global.jurisdiction).toBeUndefined();
319 const replaced = yield* getLiveQueue(accountId, global.queueId);
320 expect(replaced.jurisdiction ?? undefined).toBeUndefined();
321 yield* expectQueueGone(accountId, eu.queueId);
322
323 yield* stack.destroy();
324 yield* expectQueueGone(accountId, global.queueId);
325 }).pipe(logLevel),
326 { tags: ["provider:cloudflare", "provider:cloudflare:queue", "live"] },
327 );
328
329 // #2226 — a queue found by name in another jurisdiction is refused as
330 // foreign instead of adopted (and replaced, deleting its owner's queue).
331 test.provider(
332 "refuses a queue whose name is taken in another jurisdiction",
333 (stack) =>
334 Effect.gen(function* () {
335 const { accountId } = yield* yield* CloudflareEnvironment;
336 const name = queueNameFor(stack.stage, "jurisdiction-taken");
337
338 yield* stack.destroy();
339
340 const global = yield* stack.deploy(
341 Effect.gen(function* () {
342 return yield* Cloudflare.Queues.Queue("GlobalQueue", { name });
343 }),
344 );
345
346 const error = yield* Effect.flip(
347 stack.deploy(
348 Effect.gen(function* () {
349 const globalQueue = yield* Cloudflare.Queues.Queue("GlobalQueue", { name });
350 const euQueue = yield* Cloudflare.Queues.Queue("EuQueue", {
351 name,
352 jurisdiction: "eu",
353 });
354 return { globalQueue, euQueue };
355 }),
356 ),
357 );
358 expect(error._tag).toEqual("OwnedBySomeoneElse");
359
360 // The global queue was left alone.
361 const live = yield* getLiveQueue(accountId, global.queueId);
362 expect(live.jurisdiction ?? undefined).toBeUndefined();
363
364 yield* stack.destroy();
365 yield* expectQueueGone(accountId, global.queueId);
366 }).pipe(logLevel),
367 { tags: ["provider:cloudflare", "provider:cloudflare:queue", "live"] },
368 );
369
370 /**
371 * Regression test for #1243 — producer and consumer split across two
372 * Workers, so the consuming Worker has no producer binding and learns its
373 * queue's name only from the `DedicatedQueue_queueName` env binding.
374 *
375 * Before the `packEnvValue` fix, that binding deployed as the JSON-packed
376 * `"the-name"` (quote characters on the wire): the raw-binding assertion
377 * below failed, and any consumer of the raw value — including the
378 * reporter's — could never match Cloudflare's bare `MessageBatch.queue`.
379 * The test pins both halves: the binding is the bare name, and the
380 * handler receives the message end-to-end.
381 */
382 test.provider.skipIf(!!process.env.FAST)(
383 "dedicated consumer worker deploys a bare queue-name binding and receives messages",
384 (stack) =>
385 Effect.gen(function* () {
386 yield* stack.destroy();
387
388 const out = yield* stack.deploy(
389 Effect.gen(function* () {
390 const producer = yield* ProducerWorker;
391 const consumer = yield* ConsumerWorker;
392 return { producer: producer.url.as<string>(), consumer: consumer.url.as<string>() };
393 }),
394 );
395
396 const client = yield* HttpClient.HttpClient;
397 // Fresh workers.dev URLs 404 for a few seconds; retry through it.
398 const get = (url: string) =>
399 client.get(url).pipe(
400 Effect.flatMap((res) =>
401 res.status < 300
402 ? Effect.succeed(res)
403 : Effect.fail(new Error(`Worker not ready: ${res.status}`)),
404 ),
405 Effect.retry({
406 schedule: Schedule.max([
407 Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("3 seconds")]),
408 Schedule.recurs(10),
409 ]),
410 }),
411 Effect.orDie,
412 );
413
414 // The raw env binding is the bare queue name — no quote characters
415 // on the wire (#1243: it deployed as `"the-name"`).
416 const binding = (yield* (yield* get(`${out.consumer}/binding`)).json) as {
417 queueName: string;
418 };
419 expect(binding.queueName).not.toMatch(/^"/);
420 expect(binding.queueName).toMatch(/queue/);
421
422 yield* get(`${out.producer}/send?text=dedicated`);
423
424 const received = yield* get(`${out.consumer}/received`).pipe(
425 Effect.flatMap((res) => res.json),
426 Effect.map((body) => (body as { bodies?: string[] })?.bodies ?? []),
427 Effect.repeat({
428 schedule: Schedule.spaced("4 seconds"),
429 until: (bodies) => bodies.includes("dedicated"),
430 times: 10,
431 }),
432 Effect.orDie,
433 );
434 expect(received).toContain("dedicated");
435
436 yield* stack.destroy();
437 }).pipe(logLevel),
438 {
439 tags: [
440 "provider:cloudflare",
441 "provider:cloudflare:queue",
442 "provider:cloudflare:worker",
443 "live",
444 ],
445 timeout: 120_000,
446 },
447 );