@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 158 lines 6.79 KB
Raw
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 { MinimumLogLevel } from "effect/References";
8 import * as Schedule from "effect/Schedule";
9 import * as pathe from "pathe";
10
11 // Mirrors the marker logged by `fixtures/tail/streaming-tail-producer.ts` on
12 // every request. Duplicated (not imported) because the fixture's default
13 // export must be its only export — extra named exports become workerd
14 // top-level exports and fail startup validation.
15 const STREAM_TAIL_MARKER = "alchemy-local-streaming-tail-marker";
16
17 // `dev: true` runs local providers behind the RPC sidecar proxy by default,
18 // matching the process topology of the real `alchemy dev` command.
19 const { test } = Test.make({
20 providers: Cloudflare.providers(),
21 dev: true,
22 });
23
24 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
25
26 class WorkerNotReady extends Data.TaggedError("WorkerNotReady")<{
27 status: number;
28 }> {}
29
30 /** GET a route, retrying until the freshly started workerd serves a 200. */
31 const getTextReady = (url: string) =>
32 Effect.gen(function* () {
33 const client = yield* HttpClient.HttpClient;
34 const res = yield* client.get(url).pipe(
35 Effect.flatMap((res) =>
36 res.status === 200
37 ? Effect.succeed(res)
38 : Effect.fail(new WorkerNotReady({ status: res.status })),
39 ),
40 Effect.retry({
41 while: (e): e is WorkerNotReady => e instanceof WorkerNotReady,
42 schedule: Schedule.max([
43 Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("2 seconds")]),
44 Schedule.recurs(10),
45 ]),
46 }),
47 );
48 return yield* res.text;
49 }).pipe(Effect.orDie);
50
51 /** The recorded shape of one streamed `TailEvent` in a consumer session. */
52 interface RecordedTailEvent {
53 invocationId?: string;
54 event?: { type?: string; outcome?: string; message?: unknown };
55 }
56
57 /**
58 * Under `alchemy dev` a Worker's `streamingTailConsumers` lower into
59 * workerd's `streamingTails` service designators: each consumer script name
60 * resolves through the dev registry proxy — the same path plain tails and
61 * cross-worker service bindings take — and the consumer's `tailStream()`
62 * handler receives the invocation's `onset` while the producer is still
63 * executing, then every subsequent event ending with the terminal `outcome`,
64 * exactly like the deployed `streaming_tail_consumers` setting. The consumer
65 * records each completed session into a locally-emulated KV namespace and
66 * serves it back on `/events`, so this exercises the full local roundtrip
67 * with zero cloud calls.
68 */
69 test.provider(
70 "local producer streams events to its local streaming tail consumer",
71 (stack) =>
72 Effect.gen(function* () {
73 yield* stack.destroy();
74
75 const deployed = yield* stack.deploy(
76 Effect.gen(function* () {
77 const events = yield* Cloudflare.KV.Namespace("StreamTailEvents");
78 const consumer = yield* Cloudflare.Worker("StreamingTailConsumer", {
79 main: pathe.resolve(import.meta.dirname, "fixtures/tail/streaming-tail-consumer.ts"),
80 env: { EVENTS: events },
81 });
82 const producer = yield* Cloudflare.Worker("StreamingTailProducer", {
83 main: pathe.resolve(import.meta.dirname, "fixtures/tail/streaming-tail-producer.ts"),
84 streamingTailConsumers: [consumer],
85 });
86 return { events, consumer, producer };
87 }),
88 );
89
90 // Dev markers: the KV namespace is locally emulated (no cloud call
91 // ran), and both workers serve from the local dev proxy.
92 expect(deployed.events.namespaceId).toMatch(/^dev:/);
93 expect(deployed.consumer.url).toMatch(/^http:\/\/localhost:\d+$/);
94 expect(deployed.producer.url).toMatch(/^http:\/\/localhost:\d+$/);
95
96 // Attribute parity with the live provider: the consumer is recorded
97 // by script name.
98 expect(deployed.producer.streamingTailConsumers).toEqual([
99 { service: deployed.consumer.workerName },
100 ]);
101 expect(deployed.producer.tailConsumers).toBeUndefined();
102
103 // Readiness probes for both freshly started workerds.
104 expect(yield* getTextReady(deployed.consumer.url!)).toBe("streaming-tail-consumer-ok");
105 expect(yield* getTextReady(deployed.producer.url!)).toBe("streaming-producer-ok");
106
107 // Drive the producer and poll the consumer's read route until a full
108 // session carrying the producer's log marker arrives. The producer's
109 // registry proxy may pick the consumer up asynchronously — each poll
110 // re-invokes the producer so early dropped sessions don't strand the
111 // test.
112 const client = yield* HttpClient.HttpClient;
113 const sessions = yield* Effect.gen(function* () {
114 yield* client.get(deployed.producer.url!).pipe(
115 Effect.flatMap((res) => res.text),
116 Effect.orDie,
117 );
118 const res = yield* client.get(`${deployed.consumer.url}/events`).pipe(Effect.orDie);
119 const body = (yield* res.json.pipe(Effect.orDie)) as {
120 sessions?: unknown;
121 };
122 return Array.isArray(body.sessions) ? (body.sessions as string[]) : [];
123 }).pipe(
124 Effect.repeat({
125 schedule: Schedule.spaced("1 second"),
126 until: (sessions): boolean =>
127 sessions.some((session) => session.includes(STREAM_TAIL_MARKER)),
128 times: 20,
129 }),
130 );
131
132 const session = sessions.find((s) => s.includes(STREAM_TAIL_MARKER));
133 expect(session).toBeDefined();
134 // The recorded session is the JSON-serialized event stream: the onset
135 // handed to `tailStream()`, the console.log marker, and the terminal
136 // outcome — all from one producer invocation.
137 const events = JSON.parse(session!) as RecordedTailEvent[];
138 const types = events.map((tailEvent) => tailEvent.event?.type);
139 expect(types).toContain("onset");
140 expect(types).toContain("outcome");
141 const log = events.find((tailEvent) => tailEvent.event?.type === "log");
142 expect(log).toBeDefined();
143 expect(log?.event?.message).toEqual([STREAM_TAIL_MARKER]);
144 const onset = events.find((tailEvent) => tailEvent.event?.type === "onset");
145 // Every streamed event belongs to the onset's invocation.
146 for (const tailEvent of events) {
147 expect(tailEvent.invocationId).toBe(onset?.invocationId);
148 }
149 const outcome = events.find((tailEvent) => tailEvent.event?.type === "outcome");
150 expect(outcome?.event?.outcome).toBe("ok");
151
152 yield* stack.destroy();
153 }).pipe(logLevel),
154 {
155 tags: ["provider:cloudflare", "provider:cloudflare:kv", "provider:cloudflare:worker", "local"],
156 timeout: 180_000,
157 },
158 );