The best way to control Claude Code, Codex and more from any computer or phone

main
ts 222 lines 7.88 KB
Raw
1 import { resolve4, resolveNs, Resolver } from "node:dns/promises";
2 /**
3 * `domain.dns` on Neon websites, deployed for real: a StaticSite whose
4 * custom hostname is published through `Cloudflare.DNS.Adapter()`. Asserts
5 * Cloudflare holds exactly one DNS-only CNAME to the CustomDomain's
6 * `cnameTarget`, Neon activates the domain and serves HTTPS on it, and
7 * destroy removes both the record and the Neon domain.
8 */
9 import * as Cloudflare from "@alchemy.run/cloudflare";
10 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
11 import { findZoneByName } from "@alchemy.run/cloudflare/Zone/lookup";
12 import * as Neon from "@alchemy.run/neon";
13 import { expect } from "@alchemy.run/test";
14 import * as Test from "@alchemy.run/test/Alchemy";
15 import * as dns from "@distilled.cloud/cloudflare/dns";
16 import * as Api from "@distilled.cloud/neon";
17 import * as Data from "effect/Data";
18 import * as Effect from "effect/Effect";
19 import * as HttpClient from "effect/http/HttpClient";
20 import * as HttpClientError from "effect/http/HttpClientError";
21 import * as Layer from "effect/Layer";
22 import * as Schedule from "effect/Schedule";
23 import * as Stream from "effect/Stream";
24 import * as pathe from "pathe";
25 import { cloneFixture } from "../../Cloudflare/Utils/Fixture.ts";
26
27 const { test } = Test.make({
28 providers: Layer.mergeAll(Neon.providers(), Cloudflare.providers()),
29 });
30
31 const ZONE = "alchemy-test-2.us";
32 const HOSTNAME = `neon-dns.${ZONE}`;
33 const MARKER = "StaticSite fixture v1";
34
35 const fixtureDir = pathe.resolve(
36 import.meta.dirname,
37 "../../Cloudflare/Website/staticsite-fixture",
38 );
39 const tempRoot = pathe.resolve(import.meta.dirname, "../../../.tmp");
40
41 class CnameNotPublished extends Data.TaggedError("CnameNotPublished")<{
42 readonly server: string;
43 }> {}
44
45 class DomainNotActive extends Data.TaggedError("DomainNotActive")<{
46 readonly status: string | undefined;
47 readonly dnsStatus: string | undefined;
48 readonly bindingStatus: string | undefined;
49 }> {}
50
51 class SiteNotServing extends Data.TaggedError("SiteNotServing")<{
52 readonly status: number;
53 }> {}
54
55 const trimDot = (value: string) => value.replace(/\.$/, "").toLowerCase();
56
57 const resolveZoneId = Effect.gen(function* () {
58 const { accountId } = yield* yield* CloudflareEnvironment;
59 const zone = yield* findZoneByName({ accountId, name: ZONE });
60 if (!zone) {
61 return yield* Effect.die(new Error(`zone "${ZONE}" not found`));
62 }
63 return zone.id;
64 });
65
66 /** Every Cloudflare record at or below the hostname. */
67 const recordsUnder = (zoneId: string) =>
68 dns.listRecords.items({ zoneId, name: { endswith: HOSTNAME } }).pipe(
69 Stream.runCollect,
70 Effect.map((chunk) =>
71 Array.from(chunk).filter(
72 (record) =>
73 trimDot(record.name) === HOSTNAME || trimDot(record.name).endsWith(`.${HOSTNAME}`),
74 ),
75 ),
76 );
77
78 /** Wait until every authoritative nameserver of the zone answers the CNAME. */
79 const waitForAuthoritativeCname = (target: string) =>
80 Effect.gen(function* () {
81 const nameServers = yield* Effect.tryPromise(() => resolveNs(ZONE)).pipe(Effect.orDie);
82 const servers = (yield* Effect.forEach(nameServers, (ns) =>
83 Effect.tryPromise(() => resolve4(ns)).pipe(Effect.orDie),
84 )).flat();
85 yield* Effect.forEach(servers, (server) =>
86 Effect.gen(function* () {
87 const resolver = yield* Effect.sync(() => {
88 const r = new Resolver();
89 r.setServers([server]);
90 return r;
91 });
92 const answers = yield* Effect.tryPromise(() => resolver.resolveCname(HOSTNAME)).pipe(
93 Effect.orElseSucceed(() => [] as string[]),
94 );
95 if (!answers.some((answer) => trimDot(answer) === trimDot(target))) {
96 return yield* Effect.fail(new CnameNotPublished({ server }));
97 }
98 }).pipe(Effect.retry({ schedule: Schedule.spaced("3 seconds"), times: 20 })),
99 );
100 });
101
102 const observeDomain = (fn: { projectId: string; branchId: string }) =>
103 Api.listProjectBranchCustomDomains({
104 project_id: fn.projectId,
105 branch_id: fn.branchId,
106 }).pipe(
107 Effect.map(({ custom_domains }) => custom_domains.find((domain) => domain.domain === HOSTNAME)),
108 );
109
110 test.provider(
111 "Cloudflare DNS publishes a DNS-only CNAME to the Neon target; the hostname activates and serves HTTPS",
112 (stack) =>
113 Effect.gen(function* () {
114 yield* stack.destroy();
115 const zoneId = yield* resolveZoneId;
116 const cwd = yield* cloneFixture(fixtureDir, {
117 prefix: "alchemy-neon-dns-",
118 tempRoot,
119 entries: ["src", "build.sh"],
120 });
121
122 const site = yield* stack.deploy(
123 Neon.Website.StaticSite("Site", {
124 cwd,
125 command: "bash build.sh",
126 shell: true,
127 outdir: "dist",
128 domain: { name: HOSTNAME, dns: Cloudflare.DNS.Adapter() },
129 }),
130 );
131 expect(site.url).toBe(`https://${HOSTNAME}`);
132 const fn = site.function!;
133 const domain = site.domain!;
134 expect(domain.hostname).toBe(HOSTNAME);
135 expect(domain.cnameTarget.length).toBeGreaterThan(0);
136
137 // Exactly one record: a DNS-only CNAME to the CustomDomain's target.
138 const records = yield* recordsUnder(zoneId);
139 expect(
140 records.map((record) => ({
141 name: trimDot(record.name),
142 type: record.type,
143 content: trimDot(record.content ?? ""),
144 proxied: record.proxied,
145 })),
146 ).toEqual([
147 {
148 name: HOSTNAME,
149 type: "CNAME",
150 content: trimDot(domain.cnameTarget),
151 proxied: false,
152 },
153 ]);
154
155 // Neon registered the hostname against the site's Function.
156 const registered = yield* observeDomain(fn);
157 expect(registered?.entity_type).toBe("function");
158 expect(registered?.entity_id).toBe(fn.slug);
159 expect(registered?.cname_target).toBe(domain.cnameTarget);
160
161 yield* waitForAuthoritativeCname(domain.cnameTarget);
162
163 const active = yield* observeDomain(fn).pipe(
164 Effect.flatMap((live) =>
165 live?.status === "active" && live.dns_status === "ok" && live.binding_status === "present"
166 ? Effect.succeed(live)
167 : Effect.fail(
168 new DomainNotActive({
169 status: live?.status,
170 dnsStatus: live?.dns_status,
171 bindingStatus: live?.binding_status,
172 }),
173 ),
174 ),
175 Effect.tapError((error) => Effect.logInfo("Neon domain pending", error)),
176 Effect.retry({
177 while: (error) => error._tag === "DomainNotActive",
178 schedule: Schedule.spaced("5 seconds"),
179 times: 36,
180 }),
181 );
182 expect(active.status).toBe("active");
183
184 const client = yield* HttpClient.HttpClient;
185 const body = yield* client.get(`https://${HOSTNAME}/`).pipe(
186 Effect.flatMap(
187 (res): Effect.Effect<string, HttpClientError.HttpClientError | SiteNotServing> =>
188 res.status === 200 ? res.text : Effect.fail(new SiteNotServing({ status: res.status })),
189 ),
190 Effect.timeout("10 seconds"),
191 Effect.tapError((error) =>
192 Effect.logInfo(
193 `https://${HOSTNAME} not serving yet: ${error._tag === "SiteNotServing" ? `HTTP ${error.status}` : error.message}`,
194 ),
195 ),
196 Effect.retry({ schedule: Schedule.spaced("5 seconds"), times: 36 }),
197 );
198 expect(body).toContain(MARKER);
199
200 yield* stack.destroy();
201
202 expect(yield* recordsUnder(zoneId)).toEqual([]);
203 // The site's implicit project (and with it the branch's domain) is gone.
204 expect(
205 yield* Api.getProject({ project_id: fn.projectId }).pipe(
206 Effect.as("found" as const),
207 Effect.catchTag("NotFound", () => Effect.succeed("gone" as const)),
208 ),
209 ).toBe("gone");
210 }),
211 {
212 tags: [
213 "provider:neon",
214 "provider:neon:customdomain",
215 "provider:neon:website",
216 "provider:cloudflare",
217 "provider:cloudflare:dns",
218 "live",
219 ],
220 timeout: 600_000,
221 },
222 );