@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 233 lines 8.05 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 * as Redacted from "effect/Redacted";
8 import { MinimumLogLevel } from "effect/References";
9 import * as Schedule from "effect/Schedule";
10 import * as pathe from "pathe";
11
12 // `dev: true` runs local providers behind the RPC sidecar proxy by default,
13 // matching the process topology of the real `alchemy dev` command. The
14 // VpcService/Tunnel providers are mode-agnostic (single implementation), so
15 // they deploy the REAL cloud resources even in dev — only the Worker is
16 // emulated locally, and its `vpc_service` binding proxies to the real
17 // service through the remote-binding bridge.
18 const { test } = Test.make({
19 providers: Cloudflare.providers(),
20 dev: true,
21 });
22
23 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
24
25 const cloudflaredBin = Bun.which("cloudflared");
26
27 class WorkerNotReady extends Data.TaggedError("WorkerNotReady")<{
28 status: number;
29 }> {}
30
31 const getJsonReady = (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.json;
49 }).pipe(Effect.orDie);
50
51 /**
52 * The dev worker binds a real VPC service two ways — the managed resource
53 * and a `lookup` data source — through the remote-binding bridge (there is
54 * nothing to emulate locally; before this the binding was rejected as
55 * unsupported in local mode). Pins that the worker boots with `vpc_service`
56 * bindings and both surface as Fetchers, and that a fetch round-trips
57 * through the bridge to the real service (no connector runs, so the service
58 * answers with an error — reaching it at all is the assertion).
59 */
60 test.provider(
61 "dev worker binds a vpc service through the remote bridge",
62 (stack) =>
63 Effect.gen(function* () {
64 yield* stack.destroy();
65
66 const tunnelAndService = Effect.gen(function* () {
67 const tunnel = yield* Cloudflare.Tunnel.Tunnel("LocalVpcTunnel", {
68 ingress: [{ service: "http://localhost:8080" }],
69 adopt: true,
70 });
71 return yield* Cloudflare.VpcService.VpcService("LocalVpcSvc", {
72 httpPort: 8080,
73 host: {
74 hostname: "localhost",
75 resolverNetwork: { tunnelId: tunnel.tunnelId },
76 },
77 adopt: true,
78 });
79 });
80
81 const svc = yield* stack.deploy(tunnelAndService);
82 // Mode-agnostic provider: a real cloud id even in dev, never `dev:`.
83 expect(svc.serviceId).not.toMatch(/^dev:/);
84
85 const deployed = yield* stack.deploy(
86 Effect.gen(function* () {
87 const managed = yield* tunnelAndService;
88 const worker = yield* Cloudflare.Worker("vpc-local-worker", {
89 main: pathe.resolve(import.meta.dirname, "fixtures/vpc-local-worker.ts"),
90 env: {
91 VPC: managed,
92 VPC_LOOKUP: Cloudflare.VpcService.lookup({
93 serviceId: svc.serviceId,
94 }),
95 },
96 });
97 return { worker };
98 }),
99 );
100
101 expect(deployed.worker.url).toMatch(/^http:\/\/localhost:\d+$/);
102
103 // Both bindings surface as Fetchers inside the local workerd.
104 for (const binding of ["VPC", "VPC_LOOKUP"]) {
105 const body = (yield* getJsonReady(`${deployed.worker.url}/type?binding=${binding}`)) as {
106 type: string;
107 };
108 expect(body.type).toBe("function");
109 }
110
111 // A fetch through the binding round-trips the remote bridge to the
112 // real VPC service. Without a running connector the service cannot
113 // reach an origin, so any JSON answer (an upstream error status or a
114 // fetcher error) proves the bridge path; a broken bridge never
115 // produces one.
116 const proxied = (yield* getJsonReady(`${deployed.worker.url}/proxy?binding=VPC`)) as {
117 status?: number;
118 error?: string;
119 };
120 expect(proxied.status !== undefined || proxied.error !== undefined).toBe(true);
121
122 yield* stack.destroy();
123 }).pipe(logLevel),
124 {
125 tags: [
126 "provider:cloudflare",
127 "provider:cloudflare:tunnel",
128 "provider:cloudflare:vpcservice",
129 "provider:cloudflare:worker",
130 "live",
131 ],
132 timeout: 180_000,
133 },
134 );
135
136 const ORIGIN_PORT = 18787;
137
138 /**
139 * Full end-to-end: a local HTTP origin, a real `cloudflared` connector for
140 * the tunnel, and the dev worker fetching the origin through
141 * `env.VPC.fetch()` — local workerd → remote bridge → real VPC service →
142 * tunnel → connector on this machine → local origin. Gated on the
143 * `cloudflared` binary being installed.
144 */
145 test.provider.skipIf(!cloudflaredBin)(
146 "dev worker fetches a local origin through a cloudflared connector",
147 (stack) =>
148 Effect.gen(function* () {
149 yield* stack.destroy();
150
151 const tunnelAndService = Effect.gen(function* () {
152 const tunnel = yield* Cloudflare.Tunnel.Tunnel("E2eVpcTunnel", {
153 ingress: [{ service: `http://localhost:${ORIGIN_PORT}` }],
154 adopt: true,
155 });
156 const service = yield* Cloudflare.VpcService.VpcService("E2eVpcSvc", {
157 httpPort: ORIGIN_PORT,
158 host: {
159 ipv4: "127.0.0.1",
160 network: { tunnelId: tunnel.tunnelId },
161 },
162 adopt: true,
163 });
164 return { tunnel, service };
165 });
166
167 const { tunnel } = yield* stack.deploy(tunnelAndService);
168
169 const deployed = yield* stack.deploy(
170 Effect.gen(function* () {
171 const { service } = yield* tunnelAndService;
172 const worker = yield* Cloudflare.Worker("vpc-e2e-worker", {
173 main: pathe.resolve(import.meta.dirname, "fixtures/vpc-local-worker.ts"),
174 env: { VPC: service },
175 });
176 return { worker };
177 }),
178 );
179
180 yield* Effect.scoped(
181 Effect.gen(function* () {
182 // Local origin the tunnel connector will proxy to.
183 yield* Effect.acquireRelease(
184 Effect.sync(() =>
185 Bun.serve({
186 port: ORIGIN_PORT,
187 fetch: (req) => new Response(`origin:${new URL(req.url).pathname}`),
188 }),
189 ),
190 (server) => Effect.sync(() => void server.stop(true)),
191 );
192
193 // The connector for the tunnel, running on this machine.
194 yield* Effect.acquireRelease(
195 Effect.sync(() =>
196 Bun.spawn(
197 [cloudflaredBin!, "tunnel", "run", "--token", Redacted.value(tunnel.token)],
198 { stdout: "ignore", stderr: "ignore" },
199 ),
200 ),
201 (proc) => Effect.sync(() => proc.kill()),
202 );
203
204 // Poll the worker until the fetch lands on the origin — the
205 // connector takes a few seconds to register, and the service→edge
206 // wiring can lag behind it.
207 const body = yield* getJsonReady(
208 `${deployed.worker.url}/proxy?binding=VPC&url=http://vpc/hello`,
209 ).pipe(
210 Effect.repeat({
211 schedule: Schedule.spaced("3 seconds"),
212 until: (b) => (b as { status?: number }).status === 200,
213 times: 30,
214 }),
215 );
216
217 expect(body).toEqual({ status: 200, body: "origin:/hello" });
218 }),
219 );
220
221 yield* stack.destroy();
222 }).pipe(logLevel),
223 {
224 tags: [
225 "provider:cloudflare",
226 "provider:cloudflare:tunnel",
227 "provider:cloudflare:vpcservice",
228 "provider:cloudflare:worker",
229 "live",
230 ],
231 timeout: 300_000,
232 },
233 );