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
| 1 | import { resolve4, resolveNs, Resolver } from "node:dns/promises"; |
| 2 | import { fileURLToPath } from "node:url"; |
| 3 | /** |
| 4 | * `AWS.Lambda.Function` custom domains (`domain`): an API Gateway v2 HTTP |
| 5 | * API front door, a regional ACM certificate, an API Gateway domain name + |
| 6 | * API mapping per hostname, and alias records through the DNS host named |
| 7 | * by `domain.dns`. |
| 8 | * |
| 9 | * The HTTPS-serving suites are skipped under --fast (ACM issuance |
| 10 | * plus API Gateway domain activation take minutes — speed doctrine). The |
| 11 | * invalid-domain and no-domain regressions are cheap and ungated. |
| 12 | */ |
| 13 | import * as AWS from "@alchemy.run/aws"; |
| 14 | import { InvalidFunctionDomain } from "@alchemy.run/aws/Lambda/FunctionDomain"; |
| 15 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 16 | import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment"; |
| 17 | import { findZoneByName } from "@alchemy.run/cloudflare/Zone/lookup"; |
| 18 | import { describe, expect } from "@alchemy.run/test"; |
| 19 | import * as Test from "@alchemy.run/test/Alchemy"; |
| 20 | import * as agw2 from "@distilled.cloud/aws/apigatewayv2"; |
| 21 | import * as lambda from "@distilled.cloud/aws/lambda"; |
| 22 | import * as route53 from "@distilled.cloud/aws/route-53"; |
| 23 | import * as dns from "@distilled.cloud/cloudflare/dns"; |
| 24 | import * as Output from "alchemy/Output"; |
| 25 | import * as Cause from "effect/Cause"; |
| 26 | import * as Data from "effect/Data"; |
| 27 | import * as Effect from "effect/Effect"; |
| 28 | import * as Exit from "effect/Exit"; |
| 29 | import * as HttpClient from "effect/http/HttpClient"; |
| 30 | import * as Layer from "effect/Layer"; |
| 31 | import * as Schedule from "effect/Schedule"; |
| 32 | import * as Stream from "effect/Stream"; |
| 33 | |
| 34 | const { test } = Test.make({ |
| 35 | providers: Layer.mergeAll(AWS.providers(), Cloudflare.providers()), |
| 36 | }); |
| 37 | |
| 38 | const handlerPath = fileURLToPath(new URL("./fixtures/domain-handler.ts", import.meta.url)); |
| 39 | const BODY = "hello from a custom domain"; |
| 40 | |
| 41 | const zoneName = process.env.CLOUDFLARE_TEST_DNS_ZONE_NAME ?? "alchemy-test-2.us"; |
| 42 | |
| 43 | /** Cloudflare-hosted hostnames (test 1). */ |
| 44 | const CF_NAME = `fn-dns.${zoneName}`; |
| 45 | const CF_ALIAS = `fn-dns-alias.${zoneName}`; |
| 46 | /** Route 53 sub-zone delegated from the Cloudflare zone (test 2). */ |
| 47 | const R53_ZONE = `fn-dns-r53.${zoneName}`; |
| 48 | const R53_NAME = `api.${R53_ZONE}`; |
| 49 | |
| 50 | class DomainNotServing extends Data.TaggedError("DomainNotServing")<{ |
| 51 | readonly url: string; |
| 52 | readonly status: number; |
| 53 | }> {} |
| 54 | |
| 55 | class RecordNotPublished extends Data.TaggedError("RecordNotPublished")<{ |
| 56 | readonly name: string; |
| 57 | readonly server: string; |
| 58 | }> {} |
| 59 | |
| 60 | const trimDot = (name: string) => name.replace(/\.$/, "").toLowerCase(); |
| 61 | |
| 62 | const resolveCloudflareZoneId = Effect.gen(function* () { |
| 63 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 64 | const zone = yield* findZoneByName({ accountId, name: zoneName }); |
| 65 | if (!zone) { |
| 66 | return yield* Effect.die(new Error(`zone "${zoneName}" not found`)); |
| 67 | } |
| 68 | return zone.id; |
| 69 | }); |
| 70 | |
| 71 | const listCloudflareRecords = (zoneId: string, name: string, type: "CNAME" | "NS") => |
| 72 | dns.listRecords.items({ zoneId, name: { exact: name }, type }).pipe( |
| 73 | Stream.runCollect, |
| 74 | Effect.map((chunk) => Array.from(chunk)), |
| 75 | ); |
| 76 | |
| 77 | /** IPv4 addresses of the given nameserver hostnames. */ |
| 78 | const nameServerIps = (nameServers: readonly string[]) => |
| 79 | Effect.forEach(nameServers, (ns) => |
| 80 | Effect.tryPromise(() => resolve4(trimDot(ns))).pipe(Effect.orDie), |
| 81 | ).pipe(Effect.map((ips) => ips.flat())); |
| 82 | |
| 83 | /** |
| 84 | * Wait until every given authoritative nameserver answers `name` with |
| 85 | * `accept`. Querying a recursive resolver first would negatively cache the |
| 86 | * not-yet-published name, so the HTTPS check only starts once the record |
| 87 | * is authoritative. |
| 88 | */ |
| 89 | const waitForAuthoritative = ( |
| 90 | servers: readonly string[], |
| 91 | name: string, |
| 92 | query: (resolver: Resolver) => Promise<string[]>, |
| 93 | accept: (answers: string[]) => boolean, |
| 94 | ) => |
| 95 | Effect.forEach(servers, (server) => |
| 96 | Effect.gen(function* () { |
| 97 | const resolver = yield* Effect.sync(() => { |
| 98 | const r = new Resolver(); |
| 99 | r.setServers([server]); |
| 100 | return r; |
| 101 | }); |
| 102 | const answers = yield* Effect.tryPromise(() => query(resolver)).pipe( |
| 103 | Effect.orElseSucceed(() => [] as string[]), |
| 104 | ); |
| 105 | if (!accept(answers)) { |
| 106 | return yield* Effect.fail(new RecordNotPublished({ name, server })); |
| 107 | } |
| 108 | }).pipe(Effect.retry({ schedule: Schedule.spaced("3 seconds"), times: 20 })), |
| 109 | ); |
| 110 | |
| 111 | const waitForCloudflareCname = (name: string, target: string) => |
| 112 | Effect.gen(function* () { |
| 113 | const nameServers = yield* Effect.tryPromise(() => resolveNs(zoneName)).pipe(Effect.orDie); |
| 114 | const servers = yield* nameServerIps(nameServers); |
| 115 | yield* waitForAuthoritative( |
| 116 | servers, |
| 117 | name, |
| 118 | (resolver) => resolver.resolveCname(name), |
| 119 | (answers) => answers.some((a) => trimDot(a) === trimDot(target)), |
| 120 | ); |
| 121 | }); |
| 122 | |
| 123 | /** GET `https://{host}/` until it answers 200, returning the body. */ |
| 124 | const fetchBody = (host: string) => |
| 125 | Effect.gen(function* () { |
| 126 | const client = yield* HttpClient.HttpClient; |
| 127 | const url = `https://${host}/`; |
| 128 | return yield* client.get(url).pipe( |
| 129 | Effect.flatMap((res): Effect.Effect<string, unknown> => |
| 130 | res.status === 200 |
| 131 | ? res.text |
| 132 | : Effect.fail(new DomainNotServing({ url, status: res.status })), |
| 133 | ), |
| 134 | Effect.retry({ schedule: Schedule.spaced("5 seconds"), times: 36 }), |
| 135 | ); |
| 136 | }); |
| 137 | |
| 138 | /** Every HTTP API tagged as owned by the given stack + stage. */ |
| 139 | const listStackApis = (stackName: string, stage: string) => |
| 140 | Effect.gen(function* () { |
| 141 | const apis: agw2.Api[] = []; |
| 142 | let nextToken: string | undefined; |
| 143 | do { |
| 144 | const page = yield* agw2.getApis({ |
| 145 | MaxResults: "500", |
| 146 | ...(nextToken === undefined ? {} : { NextToken: nextToken }), |
| 147 | }); |
| 148 | apis.push(...(page.Items ?? [])); |
| 149 | nextToken = page.NextToken; |
| 150 | } while (nextToken !== undefined); |
| 151 | return apis.filter( |
| 152 | (api) => api.Tags?.["alchemy::stack"] === stackName && api.Tags?.["alchemy::stage"] === stage, |
| 153 | ); |
| 154 | }); |
| 155 | |
| 156 | /** The API Gateway regional target of a custom domain name. */ |
| 157 | const apiGatewayTarget = (domainName: string) => |
| 158 | agw2.getDomainName({ DomainName: domainName }).pipe( |
| 159 | Effect.map((domain) => { |
| 160 | const config = domain.DomainNameConfigurations?.[0]; |
| 161 | expect(config?.EndpointType).toBe("REGIONAL"); |
| 162 | expect(config?.ApiGatewayDomainName).toBeDefined(); |
| 163 | return { |
| 164 | hostname: config!.ApiGatewayDomainName!, |
| 165 | hostedZoneId: config!.HostedZoneId!, |
| 166 | }; |
| 167 | }), |
| 168 | ); |
| 169 | |
| 170 | /** Wait (bounded) until the API Gateway domain name is gone. */ |
| 171 | const waitForApiDomainGone = (domainName: string) => |
| 172 | agw2.getDomainName({ DomainName: domainName }).pipe( |
| 173 | Effect.map(() => false), |
| 174 | Effect.catchTag("NotFoundException", () => Effect.succeed(true)), |
| 175 | Effect.repeat({ |
| 176 | schedule: Schedule.spaced("3 seconds"), |
| 177 | until: (gone) => gone, |
| 178 | times: 20, |
| 179 | }), |
| 180 | ); |
| 181 | |
| 182 | const liveTags = [ |
| 183 | "provider:aws", |
| 184 | "provider:aws:acm", |
| 185 | "provider:aws:apigatewayv2", |
| 186 | "provider:aws:lambda", |
| 187 | "provider:aws:route53", |
| 188 | "provider:cloudflare", |
| 189 | "provider:cloudflare:dns", |
| 190 | "live", |
| 191 | ]; |
| 192 | |
| 193 | describe.skipIf(!!process.env.FAST)( |
| 194 | "AWS.Lambda.Function domain (live, slow)", |
| 195 | { tags: liveTags }, |
| 196 | () => { |
| 197 | test.provider( |
| 198 | "serves the Function on a Cloudflare-hosted domain and alias", |
| 199 | (stack) => |
| 200 | Effect.gen(function* () { |
| 201 | yield* stack.destroy(); |
| 202 | const cfZoneId = yield* resolveCloudflareZoneId; |
| 203 | |
| 204 | const deployed = yield* stack.deploy( |
| 205 | Effect.gen(function* () { |
| 206 | const fn = yield* AWS.Lambda.Function("DomainFn", { |
| 207 | main: handlerPath, |
| 208 | handler: "handler", |
| 209 | functionUrl: false, |
| 210 | domain: { |
| 211 | name: CF_NAME, |
| 212 | aliases: [CF_ALIAS], |
| 213 | dns: Cloudflare.DNS.Adapter({ zone: zoneName }), |
| 214 | }, |
| 215 | }); |
| 216 | return { domainUrl: fn.domainUrl.as<string>() }; |
| 217 | }), |
| 218 | ); |
| 219 | expect(deployed.domainUrl).toBe(`https://${CF_NAME}`); |
| 220 | |
| 221 | // Out-of-band: one HTTP API front door owned by this stack, and a |
| 222 | // regional API Gateway domain name mapped to it per hostname. |
| 223 | const apis = yield* listStackApis(stack.name, stack.stage); |
| 224 | expect(apis).toHaveLength(1); |
| 225 | const apiId = apis[0]!.ApiId!; |
| 226 | |
| 227 | for (const name of [CF_NAME, CF_ALIAS]) { |
| 228 | const target = yield* apiGatewayTarget(name); |
| 229 | const mappings = yield* agw2.getApiMappings({ DomainName: name }); |
| 230 | expect((mappings.Items ?? []).map((m) => m.ApiId)).toEqual([apiId]); |
| 231 | |
| 232 | // The Cloudflare CNAME points at the regional target, DNS-only. |
| 233 | const cnames = yield* listCloudflareRecords(cfZoneId, name, "CNAME"); |
| 234 | expect(cnames).toHaveLength(1); |
| 235 | expect(trimDot(cnames[0]!.content ?? "")).toBe(trimDot(target.hostname)); |
| 236 | expect(cnames[0]!.proxied).toBe(false); |
| 237 | |
| 238 | yield* waitForCloudflareCname(name, target.hostname); |
| 239 | expect(yield* fetchBody(name)).toBe(BODY); |
| 240 | } |
| 241 | |
| 242 | yield* stack.destroy(); |
| 243 | |
| 244 | // Both API Gateway domains, their CNAMEs, and the API are gone. |
| 245 | for (const name of [CF_NAME, CF_ALIAS]) { |
| 246 | expect(yield* waitForApiDomainGone(name)).toBe(true); |
| 247 | expect(yield* listCloudflareRecords(cfZoneId, name, "CNAME")).toHaveLength(0); |
| 248 | } |
| 249 | expect(yield* listStackApis(stack.name, stack.stage)).toHaveLength(0); |
| 250 | }), |
| 251 | { timeout: 900_000 }, |
| 252 | ); |
| 253 | |
| 254 | test.provider( |
| 255 | "a hostname string serves through a delegated Route 53 zone", |
| 256 | (stack) => |
| 257 | Effect.gen(function* () { |
| 258 | yield* stack.destroy(); |
| 259 | const cfZoneId = yield* resolveCloudflareZoneId; |
| 260 | |
| 261 | const program = (withFunction: boolean) => |
| 262 | Effect.gen(function* () { |
| 263 | const zone = yield* AWS.Route53.HostedZone("Zone", { |
| 264 | name: R53_ZONE, |
| 265 | forceDestroy: true, |
| 266 | }); |
| 267 | // Delegate the sub-zone from the Cloudflare test zone so ACM |
| 268 | // validation and HTTPS resolve publicly. Public Route 53 |
| 269 | // zones always get exactly four nameservers. |
| 270 | for (const index of [0, 1, 2, 3]) { |
| 271 | yield* Cloudflare.DNS.Record(`Delegation${index}`, { |
| 272 | zoneId: cfZoneId, |
| 273 | name: R53_ZONE, |
| 274 | type: "NS", |
| 275 | content: Output.map(zone.nameServers, (servers: string[]) => servers[index]!), |
| 276 | ttl: 300, |
| 277 | }); |
| 278 | } |
| 279 | const out = { |
| 280 | zoneId: zone.id.as<string>(), |
| 281 | nameServers: zone.nameServers.as<string[]>(), |
| 282 | }; |
| 283 | if (!withFunction) return { ...out, domainUrl: undefined }; |
| 284 | const fn = yield* AWS.Lambda.Function("R53Fn", { |
| 285 | main: handlerPath, |
| 286 | handler: "handler", |
| 287 | functionUrl: false, |
| 288 | domain: R53_NAME, |
| 289 | }); |
| 290 | return { ...out, domainUrl: fn.domainUrl.as<string>() }; |
| 291 | }); |
| 292 | |
| 293 | // The zone exists (and is delegated) BEFORE the Function: the |
| 294 | // certificate and alias record infer the hosted zone at |
| 295 | // reconcile time. |
| 296 | yield* stack.deploy(program(false)); |
| 297 | const deployed = yield* stack.deploy(program(true)); |
| 298 | expect(deployed.domainUrl).toBe(`https://${R53_NAME}`); |
| 299 | |
| 300 | // Out-of-band: an `A` alias to the API Gateway regional target in |
| 301 | // the delegated zone. |
| 302 | const target = yield* apiGatewayTarget(R53_NAME); |
| 303 | const recordSets = yield* route53.listResourceRecordSets({ |
| 304 | HostedZoneId: deployed.zoneId, |
| 305 | }); |
| 306 | const aliases = (recordSets.ResourceRecordSets ?? []).filter( |
| 307 | (record) => trimDot(record.Name) === R53_NAME && record.Type === "A", |
| 308 | ); |
| 309 | expect(aliases).toHaveLength(1); |
| 310 | expect(trimDot(aliases[0]!.AliasTarget?.DNSName ?? "")).toBe(trimDot(target.hostname)); |
| 311 | expect(aliases[0]!.AliasTarget?.HostedZoneId).toBe(target.hostedZoneId); |
| 312 | |
| 313 | // The delegation is live in Cloudflare. |
| 314 | const delegation = yield* listCloudflareRecords(cfZoneId, R53_ZONE, "NS"); |
| 315 | expect(delegation.map((r) => trimDot(r.content ?? "")).sort()).toEqual( |
| 316 | deployed.nameServers.map(trimDot).sort(), |
| 317 | ); |
| 318 | |
| 319 | // Route 53's own nameservers answer the alias before HTTPS. |
| 320 | const servers = yield* nameServerIps(deployed.nameServers); |
| 321 | yield* waitForAuthoritative( |
| 322 | servers, |
| 323 | R53_NAME, |
| 324 | (resolver) => resolver.resolve4(R53_NAME), |
| 325 | (answers) => answers.length > 0, |
| 326 | ); |
| 327 | expect(yield* fetchBody(R53_NAME)).toBe(BODY); |
| 328 | |
| 329 | yield* stack.destroy(); |
| 330 | |
| 331 | expect(yield* waitForApiDomainGone(R53_NAME)).toBe(true); |
| 332 | const zoneGone = yield* route53.getHostedZone({ Id: deployed.zoneId }).pipe( |
| 333 | Effect.map(() => false), |
| 334 | Effect.catchTag("NoSuchHostedZone", () => Effect.succeed(true)), |
| 335 | ); |
| 336 | expect(zoneGone).toBe(true); |
| 337 | expect(yield* listCloudflareRecords(cfZoneId, R53_ZONE, "NS")).toHaveLength(0); |
| 338 | }), |
| 339 | { timeout: 900_000 }, |
| 340 | ); |
| 341 | }, |
| 342 | ); |
| 343 | |
| 344 | /** The `InvalidFunctionDomain` defect a failed deploy died with. */ |
| 345 | const invalidDomainDefect = (exit: Exit.Exit<unknown, unknown>) => { |
| 346 | if (!Exit.isFailure(exit)) return undefined; |
| 347 | const reason = exit.cause.reasons.find( |
| 348 | (r) => Cause.isDieReason(r) && r.defect instanceof InvalidFunctionDomain, |
| 349 | ); |
| 350 | return reason && Cause.isDieReason(reason) ? (reason.defect as InvalidFunctionDomain) : undefined; |
| 351 | }; |
| 352 | |
| 353 | describe( |
| 354 | "AWS.Lambda.Function domain (live)", |
| 355 | { tags: ["provider:aws", "provider:aws:lambda", "live"] }, |
| 356 | () => { |
| 357 | test.provider( |
| 358 | "an empty or duplicate hostname fails the deploy with InvalidFunctionDomain", |
| 359 | (stack) => |
| 360 | Effect.gen(function* () { |
| 361 | yield* stack.destroy(); |
| 362 | |
| 363 | const empty = yield* stack |
| 364 | .deploy( |
| 365 | AWS.Lambda.Function("InvalidFn", { |
| 366 | main: handlerPath, |
| 367 | handler: "handler", |
| 368 | domain: "", |
| 369 | }), |
| 370 | ) |
| 371 | .pipe(Effect.exit); |
| 372 | const emptyDefect = invalidDomainDefect(empty); |
| 373 | expect(emptyDefect?.functionId).toBe("InvalidFn"); |
| 374 | expect(emptyDefect?.message).toContain("non-empty hostnames"); |
| 375 | |
| 376 | const duplicate = yield* stack |
| 377 | .deploy( |
| 378 | AWS.Lambda.Function("InvalidFn", { |
| 379 | main: handlerPath, |
| 380 | handler: "handler", |
| 381 | domain: { name: CF_NAME, aliases: [CF_NAME] }, |
| 382 | }), |
| 383 | ) |
| 384 | .pipe(Effect.exit); |
| 385 | const duplicateDefect = invalidDomainDefect(duplicate); |
| 386 | expect(duplicateDefect?.functionId).toBe("InvalidFn"); |
| 387 | expect(duplicateDefect?.message).toContain("more than once"); |
| 388 | |
| 389 | // Construction died before any plan: nothing was deployed. |
| 390 | expect(yield* listStackApis(stack.name, stack.stage)).toHaveLength(0); |
| 391 | |
| 392 | yield* stack.destroy(); |
| 393 | }), |
| 394 | { timeout: 120_000 }, |
| 395 | ); |
| 396 | |
| 397 | test.provider( |
| 398 | "a Function without `domain` composes no API Gateway front door", |
| 399 | (stack) => |
| 400 | Effect.gen(function* () { |
| 401 | yield* stack.destroy(); |
| 402 | |
| 403 | const deployed = yield* stack.deploy( |
| 404 | Effect.gen(function* () { |
| 405 | const fn = yield* AWS.Lambda.Function("PlainFn", { |
| 406 | main: handlerPath, |
| 407 | handler: "handler", |
| 408 | }); |
| 409 | return { |
| 410 | functionName: fn.functionName.as<string>(), |
| 411 | domainUrl: fn.domainUrl, |
| 412 | }; |
| 413 | }), |
| 414 | ); |
| 415 | expect(deployed.domainUrl).toBeUndefined(); |
| 416 | |
| 417 | // The Function exists; no HTTP API (and so no API Gateway domain |
| 418 | // or mapping) was composed for this stack. |
| 419 | const live = yield* lambda.getFunction({ |
| 420 | FunctionName: deployed.functionName, |
| 421 | }); |
| 422 | expect(live.Configuration?.FunctionName).toBe(deployed.functionName); |
| 423 | expect(yield* listStackApis(stack.name, stack.stage)).toHaveLength(0); |
| 424 | |
| 425 | yield* stack.destroy(); |
| 426 | |
| 427 | const gone = yield* lambda.getFunction({ FunctionName: deployed.functionName }).pipe( |
| 428 | Effect.map(() => false), |
| 429 | Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(true)), |
| 430 | ); |
| 431 | expect(gone).toBe(true); |
| 432 | }), |
| 433 | { timeout: 180_000 }, |
| 434 | ); |
| 435 | }, |
| 436 | ); |