@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 130 lines 5.1 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as kv from "@distilled.cloud/cloudflare/kv";
6 import * as workers from "@distilled.cloud/cloudflare/workers";
7 import * as Effect from "effect/Effect";
8 import { MinimumLogLevel } from "effect/References";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import * as pathe from "pathe";
12 import { expectUrlContains } from "../Utils/Http.ts";
13 import { waitForWorkerToBeDeleted } from "../Utils/Worker.ts";
14
15 const { test } = Test.make({ providers: Cloudflare.providers() });
16
17 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
18
19 /**
20 * Producer: logs on every request so each invocation produces trace events
21 * for its tail consumers.
22 */
23 const producerScript = `export default {
24 fetch() {
25 console.log("alchemy-tail-marker");
26 return new Response("producer-ok");
27 },
28 };`;
29
30 test.provider(
31 "worker with tailConsumers attaches the consumer and delivers traces",
32 (stack) =>
33 Effect.gen(function* () {
34 const { accountId } = yield* yield* CloudflareEnvironment;
35
36 yield* stack.destroy();
37
38 // The consumer is a file-based async Worker exporting a `tail()`
39 // handler that persists each trace batch into a KV namespace keyed by
40 // the producing script's name — KV makes delivery observable
41 // out-of-band, independent of which isolate received the tail event.
42 const deployStack = (tails: "attached" | "detached") =>
43 Effect.gen(function* () {
44 const events = yield* Cloudflare.KV.Namespace("TailEvents");
45 const consumer = yield* Cloudflare.Worker("TailConsumer", {
46 main: pathe.resolve(import.meta.dirname, "fixtures/tail/tail-consumer.ts"),
47 env: { EVENTS: events },
48 });
49 const producer = yield* Cloudflare.Worker("TailProducer", {
50 script: producerScript,
51 tailConsumers: tails === "attached" ? [consumer] : [],
52 });
53 return { events, consumer, producer };
54 });
55
56 const v1 = yield* stack.deploy(deployStack("attached"));
57
58 // The attribute records the consumer by deployed script name.
59 expect(v1.producer.tailConsumers).toEqual([{ service: v1.consumer.workerName }]);
60
61 // Out-of-band: the producer's script settings carry the tail consumer.
62 const settings = yield* workers.getScriptScriptAndVersionSetting({
63 accountId,
64 scriptName: v1.producer.workerName,
65 });
66 expect(settings.tailConsumers?.map((c) => c.service)).toEqual([v1.consumer.workerName]);
67
68 // Invoke the producer (retrying through workers.dev propagation),
69 // then poll KV until a tail batch keyed by the producer's script name
70 // arrives. Each poll re-invokes the producer so delivery that begins
71 // slightly after the first request still surfaces.
72 yield* expectUrlContains(v1.producer.url!, "producer-ok", {
73 label: "tail producer",
74 });
75 const eventKeys = yield* Effect.gen(function* () {
76 yield* expectUrlContains(v1.producer.url!, "producer-ok", {
77 timeout: "15 seconds",
78 label: "tail producer (poll)",
79 });
80 const keys = yield* kv.listNamespaceKeys({
81 accountId,
82 namespaceId: v1.events.namespaceId,
83 prefix: `evt:${v1.producer.workerName}:`,
84 });
85 return keys.result.map((k) => k.name);
86 }).pipe(
87 Effect.repeat({
88 schedule: Schedule.spaced("5 seconds"),
89 until: (keys): boolean => keys.length > 0,
90 times: 18,
91 }),
92 );
93 expect(eventKeys.length).toBeGreaterThan(0);
94
95 // The recorded batch references the producer script.
96 const batch = yield* kv
97 .getNamespaceValue({
98 accountId,
99 namespaceId: v1.events.namespaceId,
100 keyName: eventKeys[0],
101 })
102 .pipe(
103 Effect.flatMap((res) =>
104 Effect.tryPromise(() =>
105 new Response(Stream.toReadableStream(res.body) as BodyInit).text(),
106 ),
107 ),
108 );
109 expect(batch).toContain(v1.producer.workerName);
110
111 // Detaching every consumer is an in-place update, never a replace.
112 const v2 = yield* stack.deploy(deployStack("detached"));
113 expect(v2.producer.workerId).toEqual(v1.producer.workerId);
114 expect(v2.producer.workerName).toEqual(v1.producer.workerName);
115 expect(v2.producer.tailConsumers ?? []).toEqual([]);
116 const detached = yield* workers.getScriptScriptAndVersionSetting({
117 accountId,
118 scriptName: v2.producer.workerName,
119 });
120 expect(detached.tailConsumers ?? []).toEqual([]);
121
122 yield* stack.destroy();
123 yield* waitForWorkerToBeDeleted(v1.producer.workerName, accountId);
124 yield* waitForWorkerToBeDeleted(v1.consumer.workerName, accountId);
125 }).pipe(logLevel),
126 {
127 tags: ["provider:cloudflare", "provider:cloudflare:kv", "provider:cloudflare:worker", "live"],
128 timeout: 240_000,
129 },
130 );