@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 187 lines 6.58 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 Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as HttpClient from "effect/http/HttpClient";
8 import { MinimumLogLevel } from "effect/References";
9 import * as Schedule from "effect/Schedule";
10 import { AsyncOrders, K2AsyncWorker } from "./fixtures/k2-async-stack.ts";
11 import K2BindingWorker from "./fixtures/k2-binding-worker.ts";
12 import K2HttpWorker from "./fixtures/k2-http-worker.ts";
13 import { BindingOrders, HttpOrders } from "./fixtures/k2-shared.ts";
14 import { drainSubscription, type VerifiedRecord, waitForStreamGone } from "./k2-test-utils.ts";
15
16 const { test } = Test.make({ providers: Cloudflare.providers() });
17
18 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
19
20 class NotProduced extends Data.TaggedError("NotProduced")<{ path: string; status: number }> {}
21
22 /**
23 * `POST {route}`, retrying while a fresh workers.dev URL comes up (bounded
24 * to ~60 s). A 500 carries the typed K2 error tag in its JSON body.
25 */
26 const produce = (url: string, path: string, run: string, count: number) =>
27 HttpClient.post(`${url}${path}?run=${run}&count=${count}`).pipe(
28 Effect.flatMap((res) =>
29 res.status === 202
30 ? Effect.succeed(res)
31 : res.text.pipe(
32 Effect.flatMap((body) => {
33 if (res.status === 500) console.error(`${path} failed: ${body}`);
34 return Effect.fail(new NotProduced({ path, status: res.status }));
35 }),
36 ),
37 ),
38 Effect.retry({
39 schedule: Schedule.max([
40 Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("3 seconds")]),
41 Schedule.recurs(25),
42 ]),
43 }),
44 );
45
46 const byRun = (records: ReadonlyArray<VerifiedRecord>, run: string) =>
47 records.filter(
48 (r) =>
49 r.headers.run === run || r.text.startsWith(`${run}:`) || r.text.includes(`"run":"${run}"`),
50 );
51
52 const verifyRoutes = (url: string, streamId: string, subscriptionId: string) =>
53 Effect.gen(function* () {
54 yield* produce(url, "/typed", "typed", 4);
55 yield* produce(url, "/sink", "sink", 250);
56
57 const records = yield* drainSubscription(streamId, subscriptionId, 4 + 250);
58
59 // Typed records are JSON with a content-type header.
60 const typed = byRun(records, "typed");
61 expect(typed.map((r) => JSON.parse(r.text).index).sort()).toEqual([0, 1, 2, 3]);
62 expect(typed.every((r) => r.headers["content-type"] === "application/json")).toBe(true);
63
64 // The sink appends every element, in order.
65 const sink = byRun(records, "sink").map((r) => JSON.parse(r.text).index as number);
66 expect(new Set(sink).size).toEqual(250);
67 expect(sink).toEqual([...sink].sort((a, b) => a - b));
68 });
69
70 test.provider(
71 "WriteStream and StreamSink produce through the k2 Worker binding",
72 (stack) =>
73 Effect.gen(function* () {
74 const { accountId } = yield* yield* CloudflareEnvironment;
75
76 yield* stack.destroy();
77
78 const deployed = yield* stack.deploy(
79 Effect.gen(function* () {
80 const orders = yield* BindingOrders;
81 const verifier = yield* Cloudflare.K2.Subscription("BindingVerifier", {
82 stream: orders,
83 startAt: "earliest",
84 });
85 const worker = yield* K2BindingWorker;
86 return {
87 url: worker.url.as<string>(),
88 streamId: orders.streamId,
89 subscriptionId: verifier.subscriptionId,
90 };
91 }),
92 );
93
94 yield* verifyRoutes(deployed.url, deployed.streamId, deployed.subscriptionId);
95
96 yield* stack.destroy();
97 yield* waitForStreamGone(accountId, deployed.streamId);
98 }).pipe(logLevel),
99 {
100 tags: ["provider:cloudflare", "provider:cloudflare:k2", "provider:cloudflare:worker", "live"],
101 timeout: 180_000,
102 },
103 );
104
105 test.provider(
106 "an async Worker produces through a K2 stream in env",
107 (stack) =>
108 Effect.gen(function* () {
109 const { accountId } = yield* yield* CloudflareEnvironment;
110
111 yield* stack.destroy();
112
113 const deployed = yield* stack.deploy(
114 Effect.gen(function* () {
115 const orders = yield* AsyncOrders;
116 const verifier = yield* Cloudflare.K2.Subscription("AsyncVerifier", {
117 stream: orders,
118 startAt: "earliest",
119 });
120 const worker = yield* K2AsyncWorker;
121 return {
122 url: worker.url.as<string>(),
123 streamId: orders.streamId,
124 subscriptionId: verifier.subscriptionId,
125 };
126 }),
127 );
128
129 yield* produce(deployed.url, "/send", "async", 5);
130
131 const records = yield* drainSubscription(deployed.streamId, deployed.subscriptionId, 5);
132 expect(records.map((r) => r.text).sort()).toEqual([
133 "async:0",
134 "async:1",
135 "async:2",
136 "async:3",
137 "async:4",
138 ]);
139 expect(records.every((r) => r.headers.run === "async")).toBe(true);
140
141 yield* stack.destroy();
142 yield* waitForStreamGone(accountId, deployed.streamId);
143 }).pipe(logLevel),
144 {
145 tags: ["provider:cloudflare", "provider:cloudflare:k2", "provider:cloudflare:worker", "live"],
146 timeout: 180_000,
147 },
148 );
149
150 // WriteStreamHttp / StreamSinkHttp mint a scoped `K2 Produce` API token, so
151 // the deploying credentials need the K2 permission groups (K2 Config
152 // Read/Write, K2 Consume, K2 Produce). Without them even the stream read fails
153 // with `Unauthorized: Authentication error` (code 10000).
154 test.provider(
155 "WriteStream and StreamSink produce over HTTP with a scoped token",
156 (stack) =>
157 Effect.gen(function* () {
158 const { accountId } = yield* yield* CloudflareEnvironment;
159
160 yield* stack.destroy();
161
162 const deployed = yield* stack.deploy(
163 Effect.gen(function* () {
164 const orders = yield* HttpOrders;
165 const verifier = yield* Cloudflare.K2.Subscription("HttpVerifier", {
166 stream: orders,
167 startAt: "earliest",
168 });
169 const worker = yield* K2HttpWorker;
170 return {
171 url: worker.url.as<string>(),
172 streamId: orders.streamId,
173 subscriptionId: verifier.subscriptionId,
174 };
175 }),
176 );
177
178 yield* verifyRoutes(deployed.url, deployed.streamId, deployed.subscriptionId);
179
180 yield* stack.destroy();
181 yield* waitForStreamGone(accountId, deployed.streamId);
182 }).pipe(logLevel),
183 {
184 tags: ["provider:cloudflare", "provider:cloudflare:k2", "provider:cloudflare:worker", "live"],
185 timeout: 180_000,
186 },
187 );