@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 195 lines 8.47 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { readPythonWorkerBundle } from "@alchemy.run/cloudflare/Workers/Sources/Python";
4 import { describe, expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as Effect from "effect/Effect";
7 import * as HttpClient from "effect/http/HttpClient";
8 import * as HttpClientRequest from "effect/http/HttpClientRequest";
9 import { MinimumLogLevel } from "effect/References";
10 import * as Schedule from "effect/Schedule";
11 import * as pathe from "pathe";
12 import { expectUrlContains, HttpAssertionFailed } 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 const main = pathe.resolve(import.meta.dirname, "fixtures/python/worker.py");
20 const depsMain = pathe.resolve(import.meta.dirname, "fixtures/python-deps/worker.py");
21 const fastapiMain = pathe.resolve(import.meta.dirname, "fixtures/python-fastapi/worker.py");
22
23 describe.concurrent(
24 "Cloudflare.Worker with a Python entrypoint",
25 { tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"] },
26 () => {
27 test.provider(
28 "uploads python modules and serves from the runtime",
29 (stack) =>
30 Effect.gen(function* () {
31 const { accountId } = yield* yield* CloudflareEnvironment;
32
33 yield* stack.destroy();
34
35 // The bundle the provider must upload: the entry first (it becomes
36 // `main_module`), sibling `.py` sources named by their path
37 // relative to the entry's directory. No bundler runs — Python
38 // sources are interpreted directly by Pyodide.
39 const expected = yield* readPythonWorkerBundle({
40 id: "PythonWorker",
41 fqn: "PythonWorker",
42 main,
43 compatibility: { date: "2026-03-17", flags: ["python_workers"] },
44 });
45 const paths = expected.files.map((file) => file.path);
46 expect(paths.slice(0, 2)).toEqual(["worker.py", "util.py"]);
47 // Current workerd releases externalize the Python Workers SDK, so
48 // Alchemy vendors the managed runtime even without a pyproject.toml.
49 expect(paths).toContain("python_modules/workers/__init__.py");
50
51 const worker = yield* stack.deploy(
52 Effect.gen(function* () {
53 return yield* Cloudflare.Worker("PythonWorker", {
54 main,
55 workersDev: true,
56 env: { PY_SUFFIX: "42" },
57 });
58 }),
59 );
60
61 // The stored bundle hash covers the source and managed SDK bytes;
62 // Python modules are uploaded directly without JS bundling.
63 expect(worker.hash?.bundle).toEqual(expected.hash);
64
65 // End-to-end: the response interpolates a constant from the
66 // sibling `util.py` module and an env binding, so it only renders
67 // if the module graph and bindings survived the upload.
68 expect(worker.url).toBeDefined();
69 yield* expectUrlContains(worker.url!, "alchemy-python-worker-7c1f suffix=42");
70
71 yield* stack.destroy();
72 yield* waitForWorkerToBeDeleted(worker.workerName, accountId);
73 }).pipe(logLevel),
74 { timeout: 360_000 },
75 );
76
77 // Vendors `humanize` (plus the managed `workers-runtime-sdk`) with uv
78 // against the Pyodide wheel index and uploads it under
79 // `python_modules/`. Requires uv (>= 0.8.10) on PATH.
80 test.provider.skipIf(!!process.env.FAST)(
81 "vendors pyproject.toml dependencies with uv",
82 (stack) =>
83 Effect.gen(function* () {
84 const { accountId } = yield* yield* CloudflareEnvironment;
85
86 yield* stack.destroy();
87
88 const bundle = yield* readPythonWorkerBundle({
89 id: "PythonDepsWorker",
90 fqn: "PythonDepsWorker",
91 main: depsMain,
92 compatibility: { date: "2026-03-17", flags: ["python_workers"] },
93 });
94 const paths = bundle.files.map((file) => file.path);
95 expect(paths[0]).toEqual("worker.py");
96 // The vendored wheel contents ride along under python_modules/.
97 expect(paths.some((p) => p.startsWith("python_modules/humanize/"))).toBe(true);
98 // pywrangler parity: the managed SDK package is always vendored.
99 expect(paths.some((p) => p.startsWith("python_modules/workers/"))).toBe(true);
100
101 const worker = yield* stack.deploy(
102 Effect.gen(function* () {
103 return yield* Cloudflare.Worker("PythonDepsWorker", {
104 main: depsMain,
105 workersDev: true,
106 });
107 }),
108 );
109
110 // `humanize.intcomma` only resolves if the vendored package was
111 // uploaded and is importable at runtime.
112 expect(worker.url).toBeDefined();
113 yield* expectUrlContains(worker.url!, "vendored=1,234,567");
114
115 yield* stack.destroy();
116 yield* waitForWorkerToBeDeleted(worker.workerName, accountId);
117 }).pipe(logLevel),
118 { timeout: 360_000 },
119 );
120
121 // The supported-package surface of Python Workers, exercised end-to-end
122 // through one FastAPI app:
123 // - fastapi + pydantic (Pyodide-built-in packages) served via the
124 // runtime-provided `asgi` module
125 // - numpy — a compiled-extension wheel, proving vendored binary wheels
126 // match the deployed Pyodide runtime's emscripten-wasm32 ABI
127 // - httpx — async outbound HTTP (the only kind Workers support)
128 // - env bindings threaded into ASGI routes via `request.scope["env"]`
129 test.provider.skipIf(!!process.env.FAST)(
130 "serves a FastAPI app with pydantic, numpy, and httpx",
131 (stack) =>
132 Effect.gen(function* () {
133 const { accountId } = yield* yield* CloudflareEnvironment;
134
135 yield* stack.destroy();
136
137 const worker = yield* stack.deploy(
138 Effect.gen(function* () {
139 return yield* Cloudflare.Worker("PythonFastapiWorker", {
140 main: fastapiMain,
141 workersDev: true,
142 env: { DEPLOYMENT: "alchemy-fastapi-e2e" },
143 });
144 }),
145 );
146 expect(worker.url).toBeDefined();
147 const url = worker.url!.replace(/\/$/, "");
148
149 // ASGI routing (absorbs first-deploy propagation via retries).
150 yield* expectUrlContains(`${url}/`, '"framework":"fastapi"');
151 // Env bindings reach ASGI routes through request.scope["env"].
152 yield* expectUrlContains(`${url}/env`, "alchemy-fastapi-e2e");
153 // numpy: compiled wheel imports and computes (sum(0..9) = 45).
154 yield* expectUrlContains(`${url}/numpy`, '"sum":45');
155 // httpx: async outbound subrequest succeeds.
156 yield* expectUrlContains(`${url}/outbound`, '"status":200');
157
158 // pydantic: POST body is validated and parsed into the Item model.
159 // The POST rides the same first-deploy propagation as the GETs above
160 // (a cold POP can still 404 briefly), so retry it the same way
161 // instead of asserting a single shot.
162 const client = yield* HttpClient.HttpClient;
163 const body = (yield* HttpClientRequest.post(`${url}/items`).pipe(
164 HttpClientRequest.bodyJsonUnsafe({ name: "widget", quantity: 21 }),
165 client.execute,
166 Effect.flatMap((response) =>
167 response.status === 200
168 ? response.json
169 : response.text.pipe(
170 Effect.flatMap((text) =>
171 Effect.fail(
172 new HttpAssertionFailed({
173 url: `${url}/items`,
174 marker: "200",
175 status: response.status,
176 bodyExcerpt: text.slice(0, 240),
177 }),
178 ),
179 ),
180 ),
181 ),
182 Effect.retry({
183 while: (e) => e._tag === "HttpAssertionFailed",
184 schedule: Schedule.max([Schedule.exponential("1 second"), Schedule.recurs(8)]),
185 }),
186 )) as { name: string; total: number };
187 expect(body).toEqual({ name: "widget", total: 42 });
188
189 yield* stack.destroy();
190 yield* waitForWorkerToBeDeleted(worker.workerName, accountId);
191 }).pipe(logLevel),
192 { timeout: 360_000 },
193 );
194 },
195 );