@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 740 lines 26 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare";
3 import { findZoneByName } from "@alchemy.run/cloudflare/Zone";
4 import * as Neon from "@alchemy.run/neon";
5 import { assert, expect } from "@alchemy.run/test";
6 import * as Test from "@alchemy.run/test/Alchemy";
7 import * as hyperdrive from "@distilled.cloud/cloudflare/hyperdrive";
8 import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust";
9 import * as Provider from "alchemy/Provider";
10 import * as Data from "effect/Data";
11 import * as Effect from "effect/Effect";
12 import * as HttpClient from "effect/http/HttpClient";
13 import * as Layer from "effect/Layer";
14 import * as Redacted from "effect/Redacted";
15 import { MinimumLogLevel } from "effect/References";
16 import * as Schedule from "effect/Schedule";
17 import * as pathe from "pathe";
18 import { testName } from "../../names.ts";
19 import { waitForWorkerToBeDeleted } from "../Utils/Worker.ts";
20 import HyperdriveAccessEffectWorker from "./fixtures/access-effect-worker.ts";
21 import {
22 ACCESS_ORIGIN_HOST,
23 ACCESS_ORIGIN_PASSWORD,
24 ACCESS_ORIGIN_PORT,
25 ACCESS_ORIGIN_ZONE,
26 AccessOriginConnection,
27 AccessOriginRoute,
28 } from "./fixtures/access-origin.ts";
29 import { ISRG_ROOT_X1 } from "./fixtures/ca.ts";
30 import { outOfBandConfig } from "./fixtures/lookup-config.ts";
31 import HyperdriveLookupEffectWorker from "./fixtures/lookup-effect-worker.ts";
32 import { lookupConfigName } from "./fixtures/lookup.ts";
33 import HyperdriveVpcEffectWorker from "./fixtures/vpc-effect-worker.ts";
34 import {
35 VPC_ORIGIN_PASSWORD,
36 VPC_ORIGIN_PORT,
37 VpcOriginConnection,
38 VpcOriginService,
39 VpcOriginTunnel,
40 } from "./fixtures/vpc-origin.ts";
41
42 const { test } = Test.make({ providers: Layer.merge(Cloudflare.providers(), Neon.providers()) });
43
44 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
45 test.provider(
46 "create and delete hyperdrive with default props",
47 (stack) =>
48 Effect.gen(function* () {
49 const { accountId } = yield* yield* CloudflareEnvironment;
50
51 yield* stack.destroy();
52
53 const { db, hd } = yield* stack.deploy(
54 Effect.gen(function* () {
55 const db = yield* Neon.Project("DefaultProject");
56 const hd = yield* Cloudflare.Hyperdrive.Connection("DefaultHyperdrive", {
57 origin: db.origin,
58 });
59 return { db, hd };
60 }),
61 );
62
63 expect(hd.hyperdriveId).toBeDefined();
64 expect(hd.name).toBeDefined();
65
66 const actual = yield* hyperdrive.getConfig({ accountId, hyperdriveId: hd.hyperdriveId });
67 expect(actual.id).toEqual(hd.hyperdriveId);
68 assert("host" in actual.origin, "db.origin must have a host");
69 expect(actual.origin.host).toEqual(db.origin.host);
70
71 yield* stack.destroy();
72
73 yield* waitForConfigToBeDeleted(hd.hyperdriveId, accountId);
74 }).pipe(logLevel),
75 {
76 tags: [
77 "provider:cloudflare",
78 "provider:cloudflare:hyperdrive",
79 "provider:neon",
80 "provider:neon:project",
81 "live",
82 ],
83 },
84 );
85
86 test.provider(
87 "create, update, delete hyperdrive",
88 (stack) =>
89 Effect.gen(function* () {
90 const { accountId } = yield* yield* CloudflareEnvironment;
91
92 yield* stack.destroy();
93
94 const hd = yield* stack.deploy(
95 Effect.gen(function* () {
96 const project = yield* Neon.Project("CRUDProject");
97 return yield* Cloudflare.Hyperdrive.Connection("CRUDHyperdrive", {
98 origin: project.origin,
99 caching: { disabled: false, maxAge: 60 },
100 });
101 }),
102 );
103
104 const updated = yield* stack.deploy(
105 Effect.gen(function* () {
106 const project = yield* Neon.Project("CRUDProject");
107 return yield* Cloudflare.Hyperdrive.Connection("CRUDHyperdrive", {
108 origin: project.origin,
109 caching: { disabled: true },
110 });
111 }),
112 );
113
114 expect(updated.hyperdriveId).toEqual(hd.hyperdriveId);
115
116 const actual = yield* hyperdrive.getConfig({ accountId, hyperdriveId: updated.hyperdriveId });
117 // After PUT with `disabled: true`, caching should reflect the change.
118 expect(actual.caching).toBeDefined();
119
120 yield* stack.destroy();
121
122 yield* waitForConfigToBeDeleted(hd.hyperdriveId, accountId);
123 }).pipe(logLevel),
124 {
125 tags: [
126 "provider:cloudflare",
127 "provider:cloudflare:hyperdrive",
128 "provider:neon",
129 "provider:neon:project",
130 "live",
131 ],
132 },
133 );
134
135 // #1807: every `updateConfig` opens a new origin pool, so a redeploy that
136 // plans an update without changing the config must not call it.
137 test.provider(
138 "an update with an unchanged config leaves the live config untouched",
139 (stack) =>
140 Effect.gen(function* () {
141 const { accountId } = yield* yield* CloudflareEnvironment;
142
143 yield* stack.destroy();
144
145 // Updating the project leaves its `origin` unresolved at plan time,
146 // so Hyperdrive is planned as an update without any change of its own.
147 const program = (historyRetentionSeconds: number, originConnectionLimit: number) =>
148 Effect.gen(function* () {
149 const project = yield* Neon.Project("NoopProject", { historyRetentionSeconds });
150 return yield* Cloudflare.Hyperdrive.Connection("NoopHyperdrive", {
151 origin: project.origin,
152 originConnectionLimit,
153 });
154 });
155
156 const hd = yield* stack.deploy(program(21600, 5));
157 const before = yield* hyperdrive.getConfig({ accountId, hyperdriveId: hd.hyperdriveId });
158
159 const plan = yield* stack.plan(program(3600, 5));
160 expect(plan.resources.NoopHyperdrive!.action).toEqual("update");
161 yield* stack.deploy(program(3600, 5));
162
163 const unchanged = yield* hyperdrive.getConfig({ accountId, hyperdriveId: hd.hyperdriveId });
164 expect(unchanged.modifiedOn).toEqual(before.modifiedOn);
165
166 // Drift on a readable field is still corrected.
167 yield* hyperdrive.patchConfig({
168 accountId,
169 hyperdriveId: hd.hyperdriveId,
170 originConnectionLimit: 7,
171 });
172 yield* stack.deploy(program(21600, 5));
173 const corrected = yield* hyperdrive.getConfig({ accountId, hyperdriveId: hd.hyperdriveId });
174 expect(corrected.originConnectionLimit).toEqual(5);
175
176 // A real change is applied.
177 yield* stack.deploy(program(21600, 6));
178 const changed = yield* hyperdrive.getConfig({ accountId, hyperdriveId: hd.hyperdriveId });
179 expect(changed.originConnectionLimit).toEqual(6);
180
181 yield* stack.destroy();
182
183 yield* waitForConfigToBeDeleted(hd.hyperdriveId, accountId);
184 }).pipe(logLevel),
185 {
186 tags: [
187 "provider:cloudflare",
188 "provider:cloudflare:hyperdrive",
189 "provider:neon",
190 "provider:neon:project",
191 "live",
192 ],
193 timeout: 240_000,
194 },
195 );
196
197 test.provider(
198 "renaming replaces the config while the origin is unresolved",
199 (stack) =>
200 Effect.gen(function* () {
201 const { accountId } = yield* yield* CloudflareEnvironment;
202 const stage = stack.stage.toLowerCase().replace(/[^a-z0-9-]/g, "-");
203 const nameV1 = `alchemy-test-hd-rename-a-${stage}`;
204 const nameV2 = `alchemy-test-hd-rename-b-${stage}`;
205
206 yield* stack.destroy();
207
208 const v1 = yield* stack.deploy(
209 Effect.gen(function* () {
210 const project = yield* Neon.Project("RenameProjectA");
211 return yield* Cloudflare.Hyperdrive.Connection("RenamedHyperdrive", {
212 name: nameV1,
213 origin: project.origin,
214 });
215 }),
216 );
217 expect(v1.name).toEqual(nameV1);
218
219 // The new project is created in the same deploy, so the origin is an
220 // unresolved output at plan time. The rename must still replace.
221 const program = Effect.gen(function* () {
222 yield* Neon.Project("RenameProjectA");
223 const project = yield* Neon.Project("RenameProjectB");
224 return yield* Cloudflare.Hyperdrive.Connection("RenamedHyperdrive", {
225 name: nameV2,
226 origin: project.origin,
227 });
228 });
229 const plan = yield* stack.plan(program);
230 expect(plan.resources.RenamedHyperdrive!.action).toEqual("replace");
231
232 const v2 = yield* stack.deploy(program);
233 expect(v2.name).toEqual(nameV2);
234 expect(v2.hyperdriveId).not.toEqual(v1.hyperdriveId);
235
236 const actual = yield* hyperdrive.getConfig({ accountId, hyperdriveId: v2.hyperdriveId });
237 expect(actual.name).toEqual(nameV2);
238 yield* waitForConfigToBeDeleted(v1.hyperdriveId, accountId);
239
240 yield* stack.destroy();
241
242 yield* waitForConfigToBeDeleted(v2.hyperdriveId, accountId);
243 }).pipe(logLevel),
244 {
245 tags: [
246 "provider:cloudflare",
247 "provider:cloudflare:hyperdrive",
248 "provider:neon",
249 "provider:neon:project",
250 "live",
251 ],
252 timeout: 240_000,
253 },
254 );
255
256 test.provider(
257 "dropping a CA pin replaces the config",
258 (stack) =>
259 Effect.gen(function* () {
260 const { accountId } = yield* yield* CloudflareEnvironment;
261
262 yield* stack.destroy();
263
264 const pinnedProgram = Effect.gen(function* () {
265 const project = yield* Neon.Project("PinnedProject");
266 const ca = yield* Cloudflare.MtlsCertificate.MtlsCertificate("PinnedCa", {
267 ca: true,
268 certificates: ISRG_ROOT_X1,
269 });
270 const hd = yield* Cloudflare.Hyperdrive.Connection("PinnedHyperdrive", {
271 origin: project.origin,
272 mtls: { caCertificateId: ca.mtlsCertificateId, sslmode: "verify-ca" },
273 });
274 return { ca, hd };
275 });
276 const pinned = yield* stack.deploy(pinnedProgram);
277
278 const before = yield* hyperdrive.getConfig({
279 accountId,
280 hyperdriveId: pinned.hd.hyperdriveId,
281 });
282 expect(before.mtls?.caCertificateId).toEqual(pinned.ca.mtlsCertificateId);
283
284 // Keep the CA deployed so the replacement doesn't also remove a
285 // dependency in the same step.
286 const unpinnedProgram = Effect.gen(function* () {
287 const project = yield* Neon.Project("PinnedProject");
288 yield* Cloudflare.MtlsCertificate.MtlsCertificate("PinnedCa", {
289 ca: true,
290 certificates: ISRG_ROOT_X1,
291 });
292 return yield* Cloudflare.Hyperdrive.Connection("PinnedHyperdrive", {
293 origin: project.origin,
294 mtls: { sslmode: "require" },
295 });
296 });
297 const plan = yield* stack.plan(unpinnedProgram);
298 expect(plan.resources.PinnedHyperdrive!.action).toEqual("replace");
299
300 const unpinned = yield* stack.deploy(unpinnedProgram);
301 expect(unpinned.hyperdriveId).not.toEqual(pinned.hd.hyperdriveId);
302
303 const after = yield* hyperdrive.getConfig({ accountId, hyperdriveId: unpinned.hyperdriveId });
304 expect(after.mtls?.caCertificateId ?? undefined).toBeUndefined();
305 expect(after.mtls?.sslmode).toEqual("require");
306 yield* waitForConfigToBeDeleted(pinned.hd.hyperdriveId, accountId);
307
308 yield* stack.destroy();
309
310 yield* waitForConfigToBeDeleted(unpinned.hyperdriveId, accountId);
311 }).pipe(logLevel),
312 {
313 tags: [
314 "provider:cloudflare",
315 "provider:cloudflare:hyperdrive",
316 "provider:cloudflare:mtlscertificate",
317 "provider:neon",
318 "provider:neon:project",
319 "live",
320 ],
321 timeout: 240_000,
322 },
323 );
324
325 test.provider(
326 "list enumerates the deployed hyperdrive",
327 (stack) =>
328 Effect.gen(function* () {
329 yield* stack.destroy();
330
331 const hd = yield* stack.deploy(
332 Effect.gen(function* () {
333 const project = yield* Neon.Project("ListProject");
334 return yield* Cloudflare.Hyperdrive.Connection("ListHyperdrive", {
335 origin: project.origin,
336 });
337 }),
338 );
339
340 const provider = yield* Provider.findProvider(Cloudflare.Hyperdrive.Connection);
341 const all = yield* provider.list();
342
343 expect(all.some((x) => x.hyperdriveId === hd.hyperdriveId)).toBe(true);
344
345 yield* stack.destroy();
346 }).pipe(logLevel),
347 {
348 tags: [
349 "provider:cloudflare",
350 "provider:cloudflare:hyperdrive",
351 "provider:neon",
352 "provider:neon:project",
353 "live",
354 ],
355 },
356 );
357
358 // ── Existing configuration (#1343) ─────────────────────────────────────────
359 // `Hyperdrive.lookup` binds a configuration the stack does not own: deploys
360 // only read it and destroy leaves it untouched.
361
362 class WorkerNotReady extends Data.TaggedError("WorkerNotReady")<{
363 status: number;
364 body: string;
365 }> {}
366
367 /** GET `${base}/meta`, riding out fresh workers.dev cold-start 404s. */
368 const getMeta = (base: string) =>
369 HttpClient.get(`${base}/meta`).pipe(
370 Effect.flatMap((res) =>
371 res.text.pipe(
372 Effect.flatMap((body) =>
373 res.status === 200
374 ? Effect.succeed(JSON.parse(body) as { database: string; hasConnectionString: boolean })
375 : Effect.fail(new WorkerNotReady({ status: res.status, body })),
376 ),
377 ),
378 ),
379 Effect.retry({
380 while: (e) => e._tag === "WorkerNotReady",
381 schedule: Schedule.spaced("2 seconds"),
382 times: 30,
383 }),
384 );
385
386 test.provider(
387 "lookup binds an existing configuration without managing it",
388 (stack) =>
389 Effect.gen(function* () {
390 const { accountId } = yield* yield* CloudflareEnvironment;
391
392 yield* stack.destroy();
393
394 const { origin } = yield* stack.deploy(
395 Effect.gen(function* () {
396 const project = yield* Neon.Project("LookupProject");
397 return { origin: project.origin };
398 }),
399 );
400
401 const deployed = yield* Effect.scoped(
402 Effect.gen(function* () {
403 const created = yield* outOfBandConfig(accountId, lookupConfigName("live"), origin);
404
405 const deployed = yield* stack.deploy(
406 Effect.gen(function* () {
407 yield* Neon.Project("LookupProject");
408 // By name, through `Cloudflare.Hyperdrive.Connect`.
409 const effectWorker = yield* HyperdriveLookupEffectWorker;
410 // By id, through `env`.
411 const asyncWorker = yield* Cloudflare.Worker("HyperdriveLookupAsyncWorker", {
412 main: pathe.resolve(import.meta.dirname, "fixtures/async-worker.ts"),
413 env: {
414 HD: Cloudflare.Hyperdrive.lookup("HyperdriveLookupById", {
415 hyperdriveId: created.id,
416 }),
417 },
418 });
419 return { effectWorker, asyncWorker };
420 }),
421 );
422
423 // Both binding flavors are bound to the looked-up configuration —
424 // the runtime binding reports the configuration id as its database.
425 for (const url of [deployed.effectWorker.url!, deployed.asyncWorker.url!]) {
426 const meta = yield* getMeta(url);
427 expect(meta.database).toEqual(created.id);
428 expect(meta.hasConnectionString).toBe(true);
429 }
430
431 yield* stack.destroy();
432
433 // Neither the deploy nor the destroy touched the configuration.
434 const survived = yield* hyperdrive.getConfig({ accountId, hyperdriveId: created.id });
435 expect(survived.id).toEqual(created.id);
436 expect(survived.modifiedOn).toEqual(created.modifiedOn);
437 return deployed;
438 }),
439 );
440
441 yield* waitForWorkerToBeDeleted(deployed.effectWorker.workerName, accountId);
442 yield* waitForWorkerToBeDeleted(deployed.asyncWorker.workerName, accountId);
443 }).pipe(logLevel),
444 {
445 tags: [
446 "provider:cloudflare",
447 "provider:cloudflare:hyperdrive",
448 "provider:cloudflare:worker",
449 "provider:neon",
450 "provider:neon:project",
451 "live",
452 ],
453 timeout: 240_000,
454 },
455 );
456
457 // ── Access-protected origin (#1836) ────────────────────────────────────────
458 // A real origin behind Cloudflare Access: Postgres in Docker, published
459 // through a Cloudflare Tunnel whose connector (`cloudflared`) runs here,
460 // guarded by a self-hosted Access app that admits one service token. Both
461 // binding flavors bind the Connection with no `dev` override and must
462 // deploy and query through it.
463
464 const cloudflaredBin = Bun.which("cloudflared");
465 const dockerBin = Bun.which("docker");
466 const ACCESS_ORIGIN_CONTAINER = testName("alchemy-test-hyperdrive-access-origin");
467
468 const run = (cmd: string[]) =>
469 Effect.sync(() => Bun.spawnSync(cmd, { stdout: "pipe", stderr: "pipe" }));
470
471 /** Postgres with TLS (the image's snakeoil cert) on `127.0.0.1:${port}`, removed when the scope closes. */
472 const localPostgres = (container: string, port: number, password: string) =>
473 Effect.acquireRelease(
474 Effect.gen(function* () {
475 yield* run([dockerBin!, "rm", "-f", container]);
476 const started = yield* run([
477 dockerBin!,
478 "run",
479 "-d",
480 "--rm",
481 "--name",
482 container,
483 "-e",
484 `POSTGRES_PASSWORD=${password}`,
485 "-p",
486 `127.0.0.1:${port}:5432`,
487 "postgres:17",
488 "-c",
489 "ssl=on",
490 "-c",
491 "ssl_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem",
492 "-c",
493 "ssl_key_file=/etc/ssl/private/ssl-cert-snakeoil.key",
494 ]);
495 if (started.exitCode !== 0) {
496 return yield* Effect.die(new Error(`docker run failed: ${started.stderr.toString()}`));
497 }
498 yield* run([
499 dockerBin!,
500 "exec",
501 container,
502 "pg_isready",
503 "-h",
504 "127.0.0.1",
505 "-U",
506 "postgres",
507 ]).pipe(
508 Effect.repeat({
509 schedule: Schedule.spaced("1 second"),
510 until: (result) => result.exitCode === 0,
511 times: 30,
512 }),
513 );
514 }),
515 () => run([dockerBin!, "rm", "-f", container]),
516 );
517
518 const accessOriginPostgres = localPostgres(
519 ACCESS_ORIGIN_CONTAINER,
520 ACCESS_ORIGIN_PORT,
521 ACCESS_ORIGIN_PASSWORD,
522 );
523
524 class TunnelNotHealthy extends Data.TaggedError("TunnelNotHealthy")<{ status: string }> {}
525 class OriginQueryFailed extends Data.TaggedError("OriginQueryFailed")<{
526 status: number;
527 body: string;
528 }> {}
529
530 /** Run the tunnel's connector here until the scope closes, then wait for it to register. */
531 const tunnelConnector = (accountId: string, tunnelId: string, token: string) =>
532 Effect.gen(function* () {
533 yield* Effect.acquireRelease(
534 Effect.sync(() =>
535 Bun.spawn([cloudflaredBin!, "tunnel", "run", "--token", token], {
536 stdout: "ignore",
537 stderr: "ignore",
538 }),
539 ),
540 (proc) =>
541 Effect.promise(async () => {
542 proc.kill();
543 await proc.exited;
544 }),
545 );
546 yield* zeroTrust.getTunnelCloudflared({ accountId, tunnelId }).pipe(
547 Effect.flatMap((tunnel) =>
548 tunnel.status === "healthy"
549 ? Effect.void
550 : Effect.fail(new TunnelNotHealthy({ status: String(tunnel.status) })),
551 ),
552 Effect.retry({
553 while: (e) => e._tag === "TunnelNotHealthy",
554 schedule: Schedule.spaced("2 seconds"),
555 times: 30,
556 }),
557 );
558 });
559
560 const queryThroughOrigin = (url: string) =>
561 HttpClient.get(url).pipe(
562 Effect.flatMap((res) =>
563 res.text.pipe(
564 Effect.flatMap((body) =>
565 res.status === 200
566 ? Effect.succeed(JSON.parse(body) as { via: string })
567 : Effect.fail(new OriginQueryFailed({ status: res.status, body })),
568 ),
569 ),
570 ),
571 Effect.retry({ schedule: Schedule.spaced("3 seconds"), times: 20 }),
572 );
573
574 test.provider.skipIf(!cloudflaredBin || !dockerBin)(
575 "deploys and queries an Access-protected origin without a dev override",
576 (stack) =>
577 Effect.gen(function* () {
578 const { accountId } = yield* yield* CloudflareEnvironment;
579 const zone = yield* findZoneByName({ accountId, name: ACCESS_ORIGIN_ZONE });
580 if (!zone) return yield* Effect.die(new Error(`zone ${ACCESS_ORIGIN_ZONE} not found`));
581
582 yield* stack.destroy();
583
584 const deployed = yield* Effect.scoped(
585 Effect.gen(function* () {
586 yield* accessOriginPostgres;
587
588 // The tunnel must have a live connector before Hyperdrive is
589 // created: Cloudflare connects to the origin when it creates it.
590 const route = yield* stack.deploy(AccessOriginRoute(zone.id));
591 yield* tunnelConnector(
592 accountId,
593 route.tunnel.tunnelId,
594 Redacted.value(route.tunnel.token),
595 );
596
597 const deployed = yield* stack
598 .deploy(
599 Effect.gen(function* () {
600 yield* AccessOriginRoute(zone.id);
601 const connection = yield* AccessOriginConnection;
602 const effectWorker = yield* HyperdriveAccessEffectWorker;
603 const asyncWorker = yield* Cloudflare.Worker("HyperdriveAccessAsyncWorker", {
604 main: pathe.resolve(import.meta.dirname, "fixtures/access-async-worker.ts"),
605 env: { HD: AccessOriginConnection },
606 });
607 return { connection, effectWorker, asyncWorker };
608 }),
609 )
610 .pipe(
611 // Hyperdrive resolves the origin host when it creates the config,
612 // and a just-created CNAME can take a little while to answer.
613 Effect.retry({ schedule: Schedule.spaced("10 seconds"), times: 12 }),
614 );
615
616 const actual = yield* hyperdrive.getConfig({
617 accountId,
618 hyperdriveId: deployed.connection.hyperdriveId,
619 });
620 assert("accessClientId" in actual.origin, "origin must be Access-protected");
621 expect(actual.origin.host).toEqual(ACCESS_ORIGIN_HOST);
622
623 // Both binding flavors reach Postgres through Access + the tunnel.
624 expect(yield* queryThroughOrigin(deployed.effectWorker.url!)).toEqual({
625 via: "through-access",
626 });
627 expect(yield* queryThroughOrigin(deployed.asyncWorker.url!)).toEqual({
628 via: "through-access",
629 });
630 return deployed;
631 }),
632 );
633
634 yield* stack.destroy();
635 yield* waitForConfigToBeDeleted(deployed.connection.hyperdriveId, accountId);
636 yield* waitForWorkerToBeDeleted(deployed.effectWorker.workerName, accountId);
637 yield* waitForWorkerToBeDeleted(deployed.asyncWorker.workerName, accountId);
638 }).pipe(logLevel),
639 {
640 tags: [
641 "provider:cloudflare",
642 "provider:cloudflare:hyperdrive",
643 "provider:cloudflare:tunnel",
644 "provider:cloudflare:access",
645 "live",
646 ],
647 timeout: 300_000,
648 },
649 );
650
651 // ── Workers VPC origin ──────────────────────────────────────────────────────
652 // A private origin reached through Workers VPC: Postgres in Docker, exposed
653 // as a TCP VPC Service over a Cloudflare Tunnel whose connector
654 // (`cloudflared`) runs here — the same topology as an Aurora/RDS instance
655 // inside an AWS VPC with `cloudflared` running in the VPC. Both binding
656 // flavors must query through it.
657
658 const VPC_ORIGIN_CONTAINER = testName("alchemy-test-hyperdrive-vpc-origin");
659
660 test.provider.skipIf(!cloudflaredBin || !dockerBin)(
661 "deploys and queries a private origin through a Workers VPC Service",
662 (stack) =>
663 Effect.gen(function* () {
664 const { accountId } = yield* yield* CloudflareEnvironment;
665
666 yield* stack.destroy();
667
668 const deployed = yield* Effect.scoped(
669 Effect.gen(function* () {
670 yield* localPostgres(VPC_ORIGIN_CONTAINER, VPC_ORIGIN_PORT, VPC_ORIGIN_PASSWORD);
671
672 // The tunnel must have a live connector before Hyperdrive is
673 // created: Cloudflare connects to the origin when it creates it.
674 const tunnel = yield* stack.deploy(VpcOriginTunnel);
675 yield* tunnelConnector(accountId, tunnel.tunnelId, Redacted.value(tunnel.token));
676
677 // The VPC Service is created in the same deploy as Hyperdrive, so
678 // Hyperdrive's create must ride out the service's propagation.
679 const deployed = yield* stack.deploy(
680 Effect.gen(function* () {
681 yield* VpcOriginTunnel;
682 const service = yield* VpcOriginService;
683 const connection = yield* VpcOriginConnection;
684 const effectWorker = yield* HyperdriveVpcEffectWorker;
685 const asyncWorker = yield* Cloudflare.Worker("HyperdriveVpcAsyncWorker", {
686 main: pathe.resolve(import.meta.dirname, "fixtures/vpc-async-worker.ts"),
687 env: { HD: VpcOriginConnection },
688 });
689 return { service, connection, effectWorker, asyncWorker };
690 }),
691 );
692
693 const actual = yield* hyperdrive.getConfig({
694 accountId,
695 hyperdriveId: deployed.connection.hyperdriveId,
696 });
697 assert("serviceId" in actual.origin, "origin must be a VPC Service origin");
698 expect(actual.origin.serviceId).toEqual(deployed.service.serviceId);
699 expect(actual.origin.database).toEqual("postgres");
700
701 // Both binding flavors reach Postgres through the VPC Service.
702 expect(yield* queryThroughOrigin(deployed.effectWorker.url!)).toEqual({
703 via: "through-vpc",
704 });
705 expect(yield* queryThroughOrigin(deployed.asyncWorker.url!)).toEqual({
706 via: "through-vpc",
707 });
708 return deployed;
709 }),
710 );
711
712 yield* stack.destroy();
713 yield* waitForConfigToBeDeleted(deployed.connection.hyperdriveId, accountId);
714 yield* waitForWorkerToBeDeleted(deployed.effectWorker.workerName, accountId);
715 yield* waitForWorkerToBeDeleted(deployed.asyncWorker.workerName, accountId);
716 }).pipe(logLevel),
717 {
718 tags: [
719 "provider:cloudflare",
720 "provider:cloudflare:hyperdrive",
721 "provider:cloudflare:tunnel",
722 "provider:cloudflare:connectivity",
723 "live",
724 ],
725 timeout: 300_000,
726 },
727 );
728
729 const waitForConfigToBeDeleted = Effect.fn(function* (hyperdriveId: string, accountId: string) {
730 yield* hyperdrive.getConfig({ accountId, hyperdriveId }).pipe(
731 Effect.flatMap(() => Effect.fail(new ConfigStillExists())),
732 Effect.retry({
733 while: (e): e is ConfigStillExists => e instanceof ConfigStillExists,
734 schedule: Schedule.exponential(100),
735 }),
736 Effect.catchTag("HyperdriveConfigNotFound", () => Effect.void),
737 );
738 });
739
740 class ConfigStillExists extends Data.TaggedError("ConfigStillExists") {}