1import * as Cloudflare from "@/Cloudflare/index.ts";
2import { CloudflareEnvironment } from "@/Cloudflare/CloudflareEnvironment.ts";
3import * as Neon from "@/Neon/index.ts";
4import * as Test from "@/Test/Alchemy";
5import * as hyperdrive from "@distilled.cloud/cloudflare/hyperdrive";
6import { expect } from "alchemy-test";
7import * as Data from "effect/Data";
8import * as Effect from "effect/Effect";
9import * as Layer from "effect/Layer";
10import { MinimumLogLevel } from "effect/References";
11import * as Schedule from "effect/Schedule";
12import * as HttpClient from "effect/http/HttpClient";
13import HyperdriveLocalWorker, {
14 LocalHyperdrive,
15} from "./fixtures/local-worker.ts";
16import HyperdriveRemoteWorker, {
17 RemoteHyperdrive,
18} from "./fixtures/remote-worker.ts";
19
20// `dev: true` runs local providers behind the RPC sidecar proxy by default,
21// matching the process topology of the real `alchemy dev` command. Neon has
22// a single (mode-agnostic) provider, so the Postgres origin is always real.
23const { test } = Test.make({
24 providers: Layer.merge(Cloudflare.providers(), Neon.providers()),
25 dev: true,
26});
27
28const logLevel = Effect.provideService(
29 MinimumLogLevel,
30 process.env.DEBUG ? "Debug" : "Info",
31);
32
33class WorkerNotReady extends Data.TaggedError("WorkerNotReady")<{
34 status: number;
35 body: string;
36}> {
37 override get message() {
38 return `worker answered ${this.status}: ${this.body.slice(0, 500)}`;
39 }
40}
41
42const getJsonReady = (url: string) =>
43 Effect.gen(function* () {
44 const client = yield* HttpClient.HttpClient;
45 const res = yield* client.get(url).pipe(
46 Effect.flatMap((res) =>
47 res.status === 200
48 ? Effect.succeed(res)
49 : res.text.pipe(
50 Effect.flatMap((body) =>
51 Effect.fail(new WorkerNotReady({ status: res.status, body })),
52 ),
53 ),
54 ),
55 Effect.retry({
56 while: (e): e is WorkerNotReady => e instanceof WorkerNotReady,
57 // Cap the backoff: an uncapped exponential over 10 recurs sums to
58 // ~8.5 minutes and turns a persistent non-200 into an apparent hang.
59 schedule: Schedule.max([
60 Schedule.min([
61 Schedule.exponential("500 millis"),
62 Schedule.spaced("2 seconds"),
63 ]),
64 Schedule.recurs(10),
65 ]),
66 }),
67 );
68 return yield* res.json;
69 }).pipe(Effect.orDie);
70
71type QueryBody = {
72 row: { sum: number; db: string };
73 host: string;
74};
75
76/**
77 * Under `alchemy dev` the Hyperdrive Connection is emulated by the local
78 * provider: reconcile mints a `dev:` id with no cloud API call, and the
79 * worker's `hyperdrive` binding is lowered onto the local runtime's origin
80 * passthrough pointed at the `dev` origin (a real Neon Postgres). Running
81 * SQL through the binding proves the whole local loop.
82 */
83test.provider(
84 "Hyperdrive binding round-trips SQL through the local passthrough",
85 (stack) =>
86 Effect.gen(function* () {
87 yield* stack.destroy();
88
89 const deployed = yield* stack.deploy(
90 Effect.gen(function* () {
91 const project = yield* Neon.Project("HyperdriveLocalProject");
92 const connection = yield* LocalHyperdrive;
93 const worker = yield* HyperdriveLocalWorker;
94 return { project, connection, worker };
95 }),
96 );
97
98 // The local provider fabricates a `dev:` id — proof no cloud call
99 // ran — and the worker serves from the local dev proxy.
100 expect(deployed.connection.hyperdriveId).toMatch(/^dev:/);
101 expect(deployed.worker.url).toMatch(/^http:\/\/localhost:\d+$/);
102
103 const body = (yield* getJsonReady(
104 `${deployed.worker.url}/query`,
105 )) as QueryBody;
106 expect(body.row.sum).toBe(2);
107 // The query really ran against the dev origin's database.
108 expect(body.row.db).toBe(deployed.project.databaseName);
109 // The runtime binding passes through to the dev origin host.
110 expect(body.host).toBe(deployed.project.origin.host);
111
112 yield* stack.destroy();
113 }).pipe(logLevel),
114 {
115 tags: [
116 "provider:cloudflare",
117 "provider:cloudflare:hyperdrive",
118 "provider:cloudflare:worker",
119 "provider:neon",
120 "provider:neon:project",
121 "live",
122 ],
123 timeout: 180_000,
124 },
125);
126
127/**
128 * `Alchemy.remote()` opts the Connection OUT of local emulation: even under
129 * `alchemy dev` the live provider creates a real Hyperdrive config on
130 * Cloudflare (a real UUID id), the locally-served worker still round-trips
131 * SQL, and destroy deletes the real config (its state row is stamped live,
132 * so the live provider handles the delete even in a dev run).
133 */
134test.provider(
135 "Alchemy.remote() connection runs live in dev",
136 (stack) =>
137 Effect.gen(function* () {
138 yield* stack.destroy();
139
140 const deployed = yield* stack.deploy(
141 Effect.gen(function* () {
142 const project = yield* Neon.Project("HyperdriveRemoteProject");
143 const connection = yield* RemoteHyperdrive;
144 const worker = yield* HyperdriveRemoteWorker;
145 return { project, connection, worker };
146 }),
147 );
148
149 // A real Cloudflare id — the live provider created it.
150 expect(deployed.connection.hyperdriveId).not.toMatch(/^dev:/);
151
152 // Out-of-band: the config exists on real Cloudflare and fronts the
153 // Neon origin.
154 const { accountId } = yield* yield* CloudflareEnvironment;
155 const config = yield* hyperdrive.getConfig({
156 accountId,
157 hyperdriveId: deployed.connection.hyperdriveId,
158 });
159 expect(config.id).toBe(deployed.connection.hyperdriveId);
160 expect("host" in config.origin ? config.origin.host : undefined).toBe(
161 deployed.project.origin.host,
162 );
163
164 // The locally-served worker's binding still round-trips SQL.
165 const body = (yield* getJsonReady(
166 `${deployed.worker.url}/query`,
167 )) as QueryBody;
168 expect(body.row.sum).toBe(2);
169 expect(body.row.db).toBe(deployed.project.databaseName);
170
171 yield* stack.destroy();
172
173 // Destroy deleted the real config (stamped live mode).
174 const gone = yield* hyperdrive
175 .getConfig({
176 accountId,
177 hyperdriveId: deployed.connection.hyperdriveId,
178 })
179 .pipe(
180 Effect.as(false),
181 Effect.catchTag("HyperdriveConfigNotFound", () =>
182 Effect.succeed(true),
183 ),
184 );
185 expect(gone).toBe(true);
186 }).pipe(logLevel),
187 {
188 tags: [
189 "provider:cloudflare",
190 "provider:cloudflare:hyperdrive",
191 "provider:cloudflare:worker",
192 "provider:neon",
193 "provider:neon:project",
194 "live",
195 ],
196 timeout: 180_000,
197 },
198);