@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, 07:15 UTC

main
ts 403 lines 13.7 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import type {
3 CommitMetadata,
4 TreeEntry,
5 } from "@alchemy.run/cloudflare/Artifacts/ReadWriteNamespace";
6 import { expect } from "@alchemy.run/test";
7 import * as Test from "@alchemy.run/test/Alchemy";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as FileSystem from "effect/FileSystem";
11 import * as HttpClient from "effect/http/HttpClient";
12 import * as HttpClientRequest from "effect/http/HttpClientRequest";
13 import type * as HttpClientResponse from "effect/http/HttpClientResponse";
14 import * as Path from "effect/Path";
15 import * as ChildProcess from "effect/process/ChildProcess";
16 import * as Redacted from "effect/Redacted";
17 import { MinimumLogLevel } from "effect/References";
18 import * as Schedule from "effect/Schedule";
19 import * as Stream from "effect/Stream";
20 import Stack from "./fixtures/stack.ts";
21
22 /**
23 * Artifacts ("Git for agents") is a beta product whose native Worker binding +
24 * implicit-namespace REST surface require the account to be onboarded to the
25 * beta. The standing test account IS entitled, so this suite runs live by
26 * default (verified green: deploy → create/list/get/delete round-trip → destroy
27 * for both the effect-native and async invocation styles).
28 *
29 * If an account is NOT onboarded, repo creation is rejected at runtime; set
30 * `CLOUDFLARE_TEST_ARTIFACTS=0` to skip the entire suite skip-clean on such an
31 * account.
32 */
33 const ARTIFACTS_ENABLED = process.env.CLOUDFLARE_TEST_ARTIFACTS !== "0";
34
35 const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
36 providers: Cloudflare.providers(),
37 state: Cloudflare.state(),
38 });
39
40 const HOOK_TIMEOUT = 300_000;
41 // Must cover the ~150s `ready` readiness budget plus the round-trip itself.
42 const TEST_TIMEOUT = 240_000;
43
44 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
45
46 class WorkerNotReady extends Data.TaggedError("WorkerNotReady")<{
47 status: number;
48 body: string;
49 }> {
50 override get message() {
51 return `status=${this.status} body=${this.body.slice(0, 500)}`;
52 }
53 }
54
55 // Bounded spaced schedule — caps total cold-start wait so a real failure
56 // surfaces fast instead of riding to the test timeout. ~150s: fresh
57 // workers.dev URLs 404 well past a minute under full-suite deploy load.
58 const ready = Schedule.max([Schedule.spaced("2 seconds"), Schedule.recurs(75)]);
59
60 /** Retry an HTTP call until it returns 200 (rides out cold-start 404s). */
61 const untilOk = <E, R>(eff: Effect.Effect<HttpClientResponse.HttpClientResponse, E, R>) =>
62 eff.pipe(
63 Effect.flatMap((res) =>
64 res.status === 200
65 ? Effect.succeed(res)
66 : res.text.pipe(
67 Effect.flatMap((body) => Effect.fail(new WorkerNotReady({ status: res.status, body }))),
68 ),
69 ),
70 Effect.retry({
71 while: (e): e is WorkerNotReady => e instanceof WorkerNotReady,
72 schedule: ready,
73 }),
74 );
75
76 const body = <T>(res: HttpClientResponse.HttpClientResponse) =>
77 res.json.pipe(Effect.map((b) => b as T));
78
79 const createRepo = (base: string, name: string) =>
80 untilOk(
81 HttpClient.execute(HttpClientRequest.post(`${base}/create?name=${encodeURIComponent(name)}`)),
82 ).pipe(
83 Effect.flatMap(
84 body<{
85 name: string;
86 remote: string;
87 defaultBranch: string;
88 hasToken: boolean;
89 }>,
90 ),
91 );
92
93 const listRepos = (base: string) =>
94 untilOk(HttpClient.get(`${base}/list`)).pipe(
95 Effect.flatMap(body<{ names: string[]; total: number }>),
96 );
97
98 const getRepo = (base: string, name: string) =>
99 untilOk(HttpClient.get(`${base}/get?name=${encodeURIComponent(name)}`)).pipe(
100 Effect.flatMap(body<{ found: boolean }>),
101 );
102
103 const deleteRepo = (base: string, name: string) =>
104 untilOk(
105 HttpClient.execute(
106 HttpClientRequest.make("DELETE")(`${base}/delete?name=${encodeURIComponent(name)}`),
107 ),
108 ).pipe(Effect.flatMap(body<{ deleted: boolean }>));
109
110 /**
111 * Drive the full client surface over one worker base URL: create a repo,
112 * confirm it shows up in `list` and `get`, then `delete` it and confirm it is
113 * gone. `label` namespaces the repo so the two style-runs stay independent
114 * against the one shared namespace.
115 */
116 const exercise = (label: string, base: string) =>
117 Effect.gen(function* () {
118 const repo = `${label}-repo`;
119
120 // Pre-clean: an interrupted earlier run can leave the deterministic
121 // repo behind (Artifacts repos live outside the account nuke's view),
122 // and a leaked repo makes create fail "already exists" forever after.
123 // getRepo also rides out worker cold-start via its readiness retry.
124 if ((yield* getRepo(base, repo)).found) {
125 yield* deleteRepo(base, repo);
126 }
127
128 const created = yield* createRepo(base, repo);
129 expect(created.name).toBe(repo);
130 expect(created.defaultBranch).toBe("main");
131 expect(created.remote).toContain("https://");
132 expect(created.hasToken).toBe(true);
133
134 const listed = yield* listRepos(base);
135 expect(listed.names).toContain(repo);
136
137 expect((yield* getRepo(base, repo)).found).toBe(true);
138
139 expect((yield* deleteRepo(base, repo)).deleted).toBe(true);
140 expect((yield* getRepo(base, repo)).found).toBe(false);
141 });
142
143 const query = (params: Record<string, string>) => new URLSearchParams(params).toString();
144
145 /** GET a read-worker route, riding out cold starts and in-progress imports. */
146 const read = <T>(base: string, path: string, params: Record<string, string>) =>
147 untilOk(HttpClient.get(`${base}${path}?${query(params)}`)).pipe(Effect.flatMap(body<T>));
148
149 /** POST a write route on the Effect-native worker. */
150 const write = <T>(base: string, path: string, params: Record<string, string>) =>
151 untilOk(HttpClient.execute(HttpClientRequest.post(`${base}${path}?${query(params)}`))).pipe(
152 Effect.flatMap(body<T>),
153 );
154
155 /** Delete `repo` if an interrupted earlier run left it behind. */
156 const preClean = (base: string, repo: string) =>
157 Effect.gen(function* () {
158 if ((yield* getRepo(base, repo)).found) {
159 yield* deleteRepo(base, repo);
160 }
161 });
162
163 class GitFailed extends Data.TaggedError("GitFailed")<{
164 command: string;
165 stderr: string;
166 }> {
167 override get message() {
168 return `git ${this.command} failed: ${this.stderr}`;
169 }
170 }
171
172 /**
173 * Run `git` in `cwd`. The auth header travels through `GIT_CONFIG_*` env vars
174 * rather than argv, so a failure message never carries the token.
175 */
176 const git = (cwd: string, args: string[], token?: Redacted.Redacted<string>) =>
177 Effect.gen(function* () {
178 const proc = yield* ChildProcess.make("git", args, {
179 cwd,
180 stdout: "pipe",
181 stderr: "pipe",
182 extendEnv: true,
183 env: {
184 GIT_TERMINAL_PROMPT: "0",
185 GIT_AUTHOR_NAME: "Alchemy Test",
186 GIT_AUTHOR_EMAIL: "test@alchemy.run",
187 GIT_COMMITTER_NAME: "Alchemy Test",
188 GIT_COMMITTER_EMAIL: "test@alchemy.run",
189 ...(token
190 ? {
191 GIT_CONFIG_COUNT: "1",
192 GIT_CONFIG_KEY_0: "http.extraHeader",
193 GIT_CONFIG_VALUE_0: Redacted.make(`Authorization: Bearer ${Redacted.value(token)}`),
194 }
195 : {}),
196 },
197 });
198 const [stderr, code] = yield* Effect.all(
199 [proc.stderr.pipe(Stream.decodeText(), Stream.mkString), proc.exitCode],
200 { concurrency: "unbounded" },
201 );
202 if (code !== 0) {
203 return yield* new GitFailed({ command: args[0]!, stderr });
204 }
205 }).pipe(Effect.scoped);
206
207 // `beforeAll` has no `.skipIf`, so the deploy is gated inside the effect: when
208 // the Artifacts beta flag is unset, skip the (entitlement-blocked) deploy and
209 // return empty URLs. The tests below are `skipIf`-gated on the same flag, so
210 // they never read these placeholder URLs.
211 const stack = beforeAll(
212 ARTIFACTS_ENABLED
213 ? deploy(Stack)
214 : Effect.succeed({ effectWorkerUrl: "", asyncWorkerUrl: "", readWorkerUrl: "" }),
215 { timeout: HOOK_TIMEOUT },
216 );
217 afterAll.skipIf(!ARTIFACTS_ENABLED || !!process.env.NO_DESTROY)(destroy(Stack), {
218 timeout: HOOK_TIMEOUT,
219 });
220
221 // Effect-native worker: `Cloudflare.Artifacts.ReadWriteNamespace(Repos)` + `ReadWriteNamespaceBinding`.
222 test.skipIf(!ARTIFACTS_ENABLED)(
223 "effect binding: create / list / get / delete round-trip",
224 Effect.gen(function* () {
225 const out = yield* stack;
226 yield* exercise("effect", out.effectWorkerUrl);
227 }).pipe(logLevel),
228 {
229 tags: [
230 "provider:cloudflare",
231 "provider:cloudflare:artifacts",
232 "provider:cloudflare:worker",
233 "live",
234 ],
235 timeout: TEST_TIMEOUT,
236 },
237 );
238
239 // Async worker: namespace declared on `env: { REPOS }`, used from plain async fetch.
240 test.skipIf(!ARTIFACTS_ENABLED)(
241 "async binding: create / list / get / delete round-trip",
242 Effect.gen(function* () {
243 const out = yield* stack;
244 yield* exercise("async", out.asyncWorkerUrl);
245 }).pipe(logLevel),
246 {
247 tags: [
248 "provider:cloudflare",
249 "provider:cloudflare:artifacts",
250 "provider:cloudflare:worker",
251 "live",
252 ],
253 timeout: TEST_TIMEOUT,
254 },
255 );
256
257 // Read-only worker: `Cloudflare.Artifacts.ReadNamespace(Repos)` over a repo
258 // imported from a public GitHub remote.
259 test.skipIf(!ARTIFACTS_ENABLED)(
260 "read binding: reads an imported repo's history and files",
261 Effect.gen(function* () {
262 const out = yield* stack;
263 const repo = "hello-world-import";
264 yield* preClean(out.effectWorkerUrl, repo);
265
266 yield* write(out.effectWorkerUrl, "/import", {
267 name: repo,
268 url: "https://github.com/octocat/Hello-World",
269 branch: "master",
270 });
271
272 // `get` fails with IMPORT_IN_PROGRESS until the import lands; `read`
273 // retries the 500 that route returns.
274 const info = yield* read<{ name: string; defaultBranch: string }>(out.readWorkerUrl, "/info", {
275 name: repo,
276 });
277 expect(info.name).toBe(repo);
278
279 // An imported repo keeps reporting `defaultBranch: "main"` even when the
280 // imported branch is `master`, so walk the branch that was imported.
281 const commits = yield* read<CommitMetadata[]>(out.readWorkerUrl, "/log", {
282 name: repo,
283 ref: "master",
284 limit: "1",
285 });
286 expect(commits).toHaveLength(1);
287 expect(commits[0]!.hash).toMatch(/^[0-9a-f]{40}$/);
288
289 const readme = yield* read<{ text: string } | null>(out.readWorkerUrl, "/read-file", {
290 name: repo,
291 ref: commits[0]!.hash,
292 path: "README",
293 });
294 expect(readme?.text).toContain("Hello World");
295
296 expect((yield* deleteRepo(out.effectWorkerUrl, repo)).deleted).toBe(true);
297 }).pipe(logLevel),
298 {
299 tags: [
300 "provider:cloudflare",
301 "provider:cloudflare:artifacts",
302 "provider:cloudflare:worker",
303 "live",
304 ],
305 timeout: TEST_TIMEOUT,
306 },
307 );
308
309 // Read-only worker over commits pushed with `git` and a write token minted
310 // through the read-write binding.
311 test.skipIf(!ARTIFACTS_ENABLED)(
312 "read binding: walks commits, trees and blobs pushed over git",
313 Effect.gen(function* () {
314 const out = yield* stack;
315 const fs = yield* FileSystem.FileSystem;
316 const path = yield* Path.Path;
317 const repo = "pushed-repo";
318 yield* preClean(out.effectWorkerUrl, repo);
319 yield* createRepo(out.effectWorkerUrl, repo);
320
321 const token = yield* write<{ id: string; plaintext: string; remote: string }>(
322 out.effectWorkerUrl,
323 "/token",
324 { name: repo, scope: "write" },
325 );
326
327 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "alchemy-artifacts-" });
328 const dataPath = path.join(dir, "data.json");
329 yield* git(dir, ["init", "-b", "main"]);
330 yield* fs.writeFileString(path.join(dir, "README.md"), "# pushed\n");
331 yield* fs.writeFileString(dataPath, `{"v":1}`);
332 yield* git(dir, ["add", "-A"]);
333 yield* git(dir, ["commit", "-m", "first"]);
334 yield* fs.writeFileString(dataPath, `{"v":2}`);
335 yield* git(dir, ["commit", "-am", "second"]);
336 yield* git(dir, ["push", token.remote, "HEAD:main"], Redacted.make(token.plaintext));
337
338 const commits = yield* read<CommitMetadata[]>(out.readWorkerUrl, "/log", {
339 name: repo,
340 ref: "main",
341 limit: "10",
342 });
343 expect(commits.map((c) => c.message)).toEqual(["second", "first"]);
344 const [head, previous] = commits as [CommitMetadata, CommitMetadata];
345 expect(head.parents).toEqual([previous.hash]);
346 expect(head.author.email).toBe("test@alchemy.run");
347
348 const commit = yield* read<CommitMetadata | null>(out.readWorkerUrl, "/read-commit", {
349 name: repo,
350 hash: head.hash,
351 });
352 expect(commit?.treeHash).toBe(head.treeHash);
353
354 const tree = yield* read<TreeEntry[] | null>(out.readWorkerUrl, "/read-tree", {
355 name: repo,
356 hash: head.treeHash,
357 });
358 expect(tree?.map((e) => e.name).sort()).toEqual(["README.md", "data.json"]);
359 const data = tree!.find((e) => e.name === "data.json")!;
360 expect(data.type).toBe("blob");
361
362 const blob = yield* read<{ text: string } | null>(out.readWorkerUrl, "/read-blob", {
363 name: repo,
364 hash: data.hash,
365 });
366 expect(blob?.text).toBe(`{"v":2}`);
367
368 const older = yield* read<{ text: string } | null>(out.readWorkerUrl, "/read-file", {
369 name: repo,
370 ref: previous.hash,
371 path: "data.json",
372 });
373 expect(older?.text).toBe(`{"v":1}`);
374
375 const missing = yield* read<{ text: string } | null>(out.readWorkerUrl, "/read-file", {
376 name: repo,
377 ref: "main",
378 path: "missing.txt",
379 });
380 expect(missing).toBeNull();
381
382 const revoked = yield* write<{ revoked: boolean }>(out.effectWorkerUrl, "/revoke", {
383 name: repo,
384 id: token.id,
385 });
386 expect(revoked.revoked).toBe(true);
387
388 expect((yield* deleteRepo(out.effectWorkerUrl, repo)).deleted).toBe(true);
389 const gone = yield* read<{ found: boolean; code?: string }>(out.readWorkerUrl, "/get", {
390 name: repo,
391 });
392 expect(gone).toEqual({ found: false, code: "NOT_FOUND" });
393 }).pipe(Effect.scoped, logLevel),
394 {
395 tags: [
396 "provider:cloudflare",
397 "provider:cloudflare:artifacts",
398 "provider:cloudflare:worker",
399 "live",
400 ],
401 timeout: TEST_TIMEOUT,
402 },
403 );