The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { fileURLToPath } from "node:url"; |
| 2 | import * as AWS from "@alchemy.run/aws"; |
| 3 | import { expect } from "@alchemy.run/test"; |
| 4 | import * as Test from "@alchemy.run/test/Alchemy"; |
| 5 | import * as Logs from "@distilled.cloud/aws/cloudwatch-logs"; |
| 6 | import * as iam from "@distilled.cloud/aws/iam"; |
| 7 | import * as lambdacore from "@distilled.cloud/aws/lambda-core"; |
| 8 | import * as LambdaWeb from "@distilled.cloud/aws/lambda-web"; |
| 9 | import * as RDSData from "@distilled.cloud/aws/rds-data"; |
| 10 | import * as Cause from "effect/Cause"; |
| 11 | import * as Clock from "effect/Clock"; |
| 12 | import * as Duration from "effect/Duration"; |
| 13 | import * as Effect from "effect/Effect"; |
| 14 | import * as HttpClient from "effect/http/HttpClient"; |
| 15 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 16 | import type * as HttpClientResponse from "effect/http/HttpClientResponse"; |
| 17 | import * as Schedule from "effect/Schedule"; |
| 18 | import * as Stream from "effect/Stream"; |
| 19 | import EffectWebFunctionLive, { EffectWebFunction } from "./fixtures/web/effect-web.ts"; |
| 20 | import { |
| 21 | BackgroundLoopWeb, |
| 22 | BackgroundLoopWebLive, |
| 23 | EventSourceWeb, |
| 24 | EventSourceWebLive, |
| 25 | } from "./fixtures/web/not-http.ts"; |
| 26 | import RdsWebFunctionLive, { RdsWebFunction, RdsWebInfra } from "./fixtures/web/rds-web.ts"; |
| 27 | |
| 28 | const asyncServerMain = fileURLToPath(new URL("./fixtures/web/async-server.ts", import.meta.url)); |
| 29 | const prebuiltMain = fileURLToPath(new URL("./fixtures/web/prebuilt/server.mjs", import.meta.url)); |
| 30 | |
| 31 | const { test } = Test.make({ providers: AWS.providers() }); |
| 32 | |
| 33 | const tags = ["provider:aws", "provider:aws:iam", "provider:aws:lambda", "live"]; |
| 34 | |
| 35 | class UnexpectedStatus extends Error {} |
| 36 | |
| 37 | /** |
| 38 | * Send a request until the endpoint answers 200. A new endpoint's domain |
| 39 | * and a freshly shifted revision take a few seconds to serve. |
| 40 | */ |
| 41 | const send = (request: HttpClientRequest.HttpClientRequest) => |
| 42 | HttpClient.execute(request).pipe( |
| 43 | Effect.flatMap((response) => |
| 44 | response.status === 200 |
| 45 | ? Effect.succeed(response) |
| 46 | : Effect.fail(new UnexpectedStatus(`${request.url} returned ${response.status}`)), |
| 47 | ), |
| 48 | Effect.retry({ |
| 49 | schedule: Schedule.max([Schedule.spaced("2 seconds"), Schedule.recurs(30)]), |
| 50 | }), |
| 51 | ); |
| 52 | |
| 53 | const getText = (url: string) => |
| 54 | send(HttpClientRequest.get(url)).pipe(Effect.flatMap((response) => response.text)); |
| 55 | |
| 56 | /** Poll `url` until its body satisfies `until`. */ |
| 57 | const getTextUntil = (url: string, until: (body: string) => boolean) => |
| 58 | getText(url).pipe(Effect.repeat({ schedule: Schedule.spaced("2 seconds"), until, times: 30 })); |
| 59 | |
| 60 | /** |
| 61 | * Read a streamed body, recording when each chunk arrived. A buffered |
| 62 | * bridge delivers every chunk at once; a streaming one spreads them over |
| 63 | * the time the handler took to produce them. |
| 64 | */ |
| 65 | const readChunks = (response: HttpClientResponse.HttpClientResponse) => |
| 66 | response.stream.pipe( |
| 67 | Stream.decodeText, |
| 68 | Stream.mapEffect((text) => Effect.map(Clock.currentTimeMillis, (at) => ({ at, text }))), |
| 69 | Stream.runCollect, |
| 70 | Effect.map((chunks) => Array.from(chunks)), |
| 71 | ); |
| 72 | |
| 73 | const expectStreamed = (url: string) => |
| 74 | Effect.gen(function* () { |
| 75 | const chunks = yield* send(HttpClientRequest.get(`${url}/stream`)).pipe( |
| 76 | Effect.flatMap(readChunks), |
| 77 | ); |
| 78 | expect(chunks.map((c) => c.text).join("")).toBe("one\ntwo\nthree\n"); |
| 79 | // The handler sleeps 600 ms between chunks; buffered delivery would |
| 80 | // land them together. |
| 81 | expect(chunks.length).toBeGreaterThan(1); |
| 82 | expect(chunks.at(-1)!.at - chunks[0]!.at).toBeGreaterThan(800); |
| 83 | }); |
| 84 | |
| 85 | const getEndpoint = (functionName: string, endpointName = "default") => |
| 86 | LambdaWeb.getWebFunctionEndpoint({ functionName, endpointName }); |
| 87 | |
| 88 | const expectFunctionDeleted = (functionName: string, roleName: string) => |
| 89 | Effect.gen(function* () { |
| 90 | const fn = yield* LambdaWeb.getWebFunction({ functionName }).pipe( |
| 91 | Effect.map(() => true), |
| 92 | Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(false)), |
| 93 | ); |
| 94 | expect(fn).toBe(false); |
| 95 | const role = yield* iam.getRole({ RoleName: roleName }).pipe( |
| 96 | Effect.map(() => true), |
| 97 | Effect.catchTag("NoSuchEntityException", () => Effect.succeed(false)), |
| 98 | ); |
| 99 | expect(role).toBe(false); |
| 100 | const logGroups = yield* Logs.describeLogGroups({ |
| 101 | logGroupNamePrefix: `/aws/lambda/web/${functionName}`, |
| 102 | }); |
| 103 | expect(logGroups.logGroups ?? []).toEqual([]); |
| 104 | }); |
| 105 | |
| 106 | test.provider( |
| 107 | "async server deployed as-is: create, update, delete", |
| 108 | (stack) => |
| 109 | Effect.gen(function* () { |
| 110 | yield* stack.destroy(); |
| 111 | |
| 112 | const declare = (props: Partial<AWS.Lambda.WebFunctionProps>) => |
| 113 | AWS.Lambda.WebFunction("AsyncServer", { |
| 114 | main: asyncServerMain, |
| 115 | authType: "ApplicationManaged", |
| 116 | ...props, |
| 117 | }); |
| 118 | |
| 119 | const created = yield* stack.deploy(declare({ env: { GREETING: "hello" } })); |
| 120 | expect(created.url).toBe(`https://${created.domainName}`); |
| 121 | expect(created.domainName).toContain(".lambda-web."); |
| 122 | |
| 123 | const root = yield* send(HttpClientRequest.get(created.url)); |
| 124 | expect(yield* root.text).toBe("greeting=hello"); |
| 125 | expect(root.headers["x-fixture"]).toBe("async-server"); |
| 126 | // The server runs unwrapped: nothing set listen variables for it. |
| 127 | expect(root.headers["x-port-env"]).toBe("unset"); |
| 128 | expect(root.headers["lambda-web-request-id"]).toBeTruthy(); |
| 129 | |
| 130 | const echo = yield* send( |
| 131 | HttpClientRequest.post(`${created.url}/echo`).pipe( |
| 132 | HttpClientRequest.bodyText("ping", "text/plain"), |
| 133 | ), |
| 134 | ).pipe(Effect.flatMap((response) => response.json)); |
| 135 | expect(echo).toEqual({ method: "POST", body: "ping" }); |
| 136 | |
| 137 | yield* expectStreamed(created.url); |
| 138 | |
| 139 | // Out-of-band: one endpoint, all traffic on the deployed revision. |
| 140 | const endpoint = yield* getEndpoint(created.functionName); |
| 141 | expect(endpoint.endpointType).toBe("HomeRegion"); |
| 142 | expect(endpoint.authType).toBe("ApplicationManaged"); |
| 143 | expect(endpoint.revisionWeights).toEqual([{ revisionId: created.revisionId, weight: 100 }]); |
| 144 | const revision = yield* LambdaWeb.getWebFunctionRevision({ |
| 145 | functionName: created.functionName, |
| 146 | revisionId: created.revisionId, |
| 147 | }); |
| 148 | expect(revision.buildConfig.runtimeConfig.runtime).toBe("nodejs24.x"); |
| 149 | expect(revision.serviceConfig.maxConcurrencyPerEnvironment).toBe(64); |
| 150 | expect(revision.serviceConfig.timeoutSeconds).toBe(30); |
| 151 | expect(revision.serviceConfig.environmentVariables?.GREETING).toBe("hello"); |
| 152 | |
| 153 | // Re-planning unchanged props is a noop. |
| 154 | const plan = yield* stack.plan(declare({ env: { GREETING: "hello" } })); |
| 155 | expect(plan.resources.AsyncServer).toMatchObject({ action: "noop" }); |
| 156 | |
| 157 | // Update: new env + concurrency create a revision; the endpoint |
| 158 | // shifts to it and picks up the rate limit. |
| 159 | const updated = yield* stack.deploy( |
| 160 | declare({ env: { GREETING: "updated" }, maxConcurrencyPerEnvironment: 32, rateLimit: 100 }), |
| 161 | ); |
| 162 | expect(updated.functionName).toBe(created.functionName); |
| 163 | expect(updated.url).toBe(created.url); |
| 164 | expect(updated.revisionId).not.toBe(created.revisionId); |
| 165 | const updatedEndpoint = yield* getEndpoint(updated.functionName); |
| 166 | expect(updatedEndpoint.revisionWeights).toEqual([ |
| 167 | { revisionId: updated.revisionId, weight: 100 }, |
| 168 | ]); |
| 169 | expect(updatedEndpoint.throttleConfig?.rateLimit).toBe(100); |
| 170 | const updatedRevision = yield* LambdaWeb.getWebFunctionRevision({ |
| 171 | functionName: updated.functionName, |
| 172 | revisionId: updated.revisionId, |
| 173 | }); |
| 174 | expect(updatedRevision.serviceConfig.maxConcurrencyPerEnvironment).toBe(32); |
| 175 | expect(yield* getTextUntil(updated.url, (body) => body === "greeting=updated")).toBe( |
| 176 | "greeting=updated", |
| 177 | ); |
| 178 | |
| 179 | // Endpoint-only change: no new revision; unsigned callers are refused. |
| 180 | const iamAuth = yield* stack.deploy( |
| 181 | declare({ |
| 182 | env: { GREETING: "updated" }, |
| 183 | maxConcurrencyPerEnvironment: 32, |
| 184 | rateLimit: 100, |
| 185 | authType: "IamAuth", |
| 186 | }), |
| 187 | ); |
| 188 | expect(iamAuth.revisionId).toBe(updated.revisionId); |
| 189 | expect((yield* getEndpoint(iamAuth.functionName)).authType).toBe("IamAuth"); |
| 190 | const unsigned = yield* HttpClient.get(iamAuth.url).pipe( |
| 191 | Effect.map((response) => response.status), |
| 192 | Effect.repeat({ |
| 193 | schedule: Schedule.spaced("2 seconds"), |
| 194 | until: (status) => status === 403, |
| 195 | times: 30, |
| 196 | }), |
| 197 | ); |
| 198 | expect(unsigned).toBe(403); |
| 199 | |
| 200 | // Renaming the built-in endpoint creates a new one (new URL) and |
| 201 | // removes the old one; the function and its revision are untouched. |
| 202 | const renamed = yield* stack.deploy( |
| 203 | declare({ |
| 204 | env: { GREETING: "updated" }, |
| 205 | maxConcurrencyPerEnvironment: 32, |
| 206 | endpointName: "primary", |
| 207 | }), |
| 208 | ); |
| 209 | expect(renamed.functionName).toBe(created.functionName); |
| 210 | expect(renamed.endpointName).toBe("primary"); |
| 211 | expect(renamed.url).not.toBe(created.url); |
| 212 | expect(renamed.revisionId).toBe(updated.revisionId); |
| 213 | const endpoints = yield* LambdaWeb.listWebFunctionEndpoints({ |
| 214 | functionName: renamed.functionName, |
| 215 | }); |
| 216 | expect(endpoints.endpoints.map((e) => e.endpointName)).toEqual(["primary"]); |
| 217 | expect(yield* getText(renamed.url)).toBe("greeting=updated"); |
| 218 | |
| 219 | yield* stack.destroy(); |
| 220 | yield* expectFunctionDeleted(created.functionName, created.roleName); |
| 221 | }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))), |
| 222 | { tags, timeout: 300_000 }, |
| 223 | ); |
| 224 | |
| 225 | /** Sorted so a two-revision split compares regardless of order. */ |
| 226 | const sortedWeights = (weights: readonly { revisionId: string; weight: number }[]) => |
| 227 | [...weights].sort((a, b) => a.revisionId.localeCompare(b.revisionId)); |
| 228 | |
| 229 | /** The distinct bodies `count` requests got back. */ |
| 230 | const sampleBodies = (url: string, count: number) => |
| 231 | Effect.forEach(Array.from({ length: count }), () => getText(url)).pipe( |
| 232 | Effect.map((bodies) => [...new Set(bodies)].sort()), |
| 233 | ); |
| 234 | |
| 235 | test.provider( |
| 236 | "canary: split, replace the canary, roll back, promote", |
| 237 | (stack) => |
| 238 | Effect.gen(function* () { |
| 239 | yield* stack.destroy(); |
| 240 | |
| 241 | // Each greeting is a new revision. "Webhooks" has no canary: it |
| 242 | // follows every deploy at 100%. |
| 243 | const deploy = (greeting: string, canary?: { weight: number }) => |
| 244 | stack.deploy( |
| 245 | Effect.gen(function* () { |
| 246 | const fn = yield* AWS.Lambda.WebFunction("Canary", { |
| 247 | main: asyncServerMain, |
| 248 | authType: "ApplicationManaged", |
| 249 | env: { GREETING: greeting }, |
| 250 | ...(canary ? { canary } : {}), |
| 251 | }); |
| 252 | const webhooks = yield* AWS.Lambda.WebFunctionEndpoint("Webhooks", { |
| 253 | function: fn, |
| 254 | authType: "ApplicationManaged", |
| 255 | }); |
| 256 | return { fn, webhooks }; |
| 257 | }), |
| 258 | ); |
| 259 | const weightsOf = (functionName: string) => |
| 260 | getEndpoint(functionName).pipe(Effect.map((e) => sortedWeights(e.revisionWeights))); |
| 261 | |
| 262 | // First deploy: nothing to compare against, so all traffic. |
| 263 | const v1 = yield* deploy("v1", { weight: 50 }); |
| 264 | expect(v1.fn.revisionWeights).toEqual([{ revisionId: v1.fn.revisionId, weight: 100 }]); |
| 265 | |
| 266 | // A new revision takes the canary share; the previous one keeps the rest. |
| 267 | const v2 = yield* deploy("v2", { weight: 50 }); |
| 268 | expect(v2.fn.revisionId).not.toBe(v1.fn.revisionId); |
| 269 | const split = sortedWeights([ |
| 270 | { revisionId: v1.fn.revisionId, weight: 50 }, |
| 271 | { revisionId: v2.fn.revisionId, weight: 50 }, |
| 272 | ]); |
| 273 | expect(sortedWeights(v2.fn.revisionWeights)).toEqual(split); |
| 274 | expect(yield* weightsOf(v2.fn.functionName)).toEqual(split); |
| 275 | expect(yield* sampleBodies(v2.fn.url, 30)).toEqual(["greeting=v1", "greeting=v2"]); |
| 276 | // The other endpoint has no canary and moved over entirely. |
| 277 | expect(v2.webhooks.revisionWeights).toEqual([{ revisionId: v2.fn.revisionId, weight: 100 }]); |
| 278 | expect(yield* getTextUntil(v2.webhooks.url, (b) => b === "greeting=v2")).toBe("greeting=v2"); |
| 279 | |
| 280 | // Unchanged props plan a noop. |
| 281 | const plan = yield* stack.plan( |
| 282 | AWS.Lambda.WebFunction("Canary", { |
| 283 | main: asyncServerMain, |
| 284 | authType: "ApplicationManaged", |
| 285 | env: { GREETING: "v2" }, |
| 286 | canary: { weight: 50 }, |
| 287 | }), |
| 288 | ); |
| 289 | expect(plan.resources.Canary).toMatchObject({ action: "noop" }); |
| 290 | |
| 291 | // Another change during the canary replaces the canary; the stable |
| 292 | // revision stays. |
| 293 | const v3 = yield* deploy("v3", { weight: 50 }); |
| 294 | expect(sortedWeights(v3.fn.revisionWeights)).toEqual( |
| 295 | sortedWeights([ |
| 296 | { revisionId: v1.fn.revisionId, weight: 50 }, |
| 297 | { revisionId: v3.fn.revisionId, weight: 50 }, |
| 298 | ]), |
| 299 | ); |
| 300 | |
| 301 | // Shift more traffic in place: no new revision. |
| 302 | const shifted = yield* deploy("v3", { weight: 90 }); |
| 303 | expect(shifted.fn.revisionId).toBe(v3.fn.revisionId); |
| 304 | expect(yield* weightsOf(shifted.fn.functionName)).toEqual( |
| 305 | sortedWeights([ |
| 306 | { revisionId: v1.fn.revisionId, weight: 10 }, |
| 307 | { revisionId: v3.fn.revisionId, weight: 90 }, |
| 308 | ]), |
| 309 | ); |
| 310 | |
| 311 | // Roll back: all traffic to the stable revision. |
| 312 | const rolledBack = yield* deploy("v3", { weight: 0 }); |
| 313 | expect(rolledBack.fn.revisionId).toBe(v3.fn.revisionId); |
| 314 | expect(rolledBack.fn.revisionWeights).toEqual([ |
| 315 | { revisionId: v1.fn.revisionId, weight: 100 }, |
| 316 | ]); |
| 317 | expect(yield* getTextUntil(rolledBack.fn.url, (b) => b === "greeting=v1")).toBe( |
| 318 | "greeting=v1", |
| 319 | ); |
| 320 | // A rollback on one endpoint leaves the others on the new revision. |
| 321 | expect(yield* getText(rolledBack.webhooks.url)).toBe("greeting=v3"); |
| 322 | |
| 323 | // Promote: remove `canary`. |
| 324 | const promoted = yield* deploy("v3"); |
| 325 | expect(yield* weightsOf(promoted.fn.functionName)).toEqual([ |
| 326 | { revisionId: v3.fn.revisionId, weight: 100 }, |
| 327 | ]); |
| 328 | expect(yield* getTextUntil(promoted.fn.url, (b) => b === "greeting=v3")).toBe("greeting=v3"); |
| 329 | |
| 330 | yield* stack.destroy(); |
| 331 | yield* expectFunctionDeleted(promoted.fn.functionName, promoted.fn.roleName); |
| 332 | }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))), |
| 333 | { tags, timeout: 600_000 }, |
| 334 | ); |
| 335 | |
| 336 | test.provider( |
| 337 | "Effect fetch handler with bindings and streaming", |
| 338 | (stack) => |
| 339 | Effect.gen(function* () { |
| 340 | yield* stack.destroy(); |
| 341 | |
| 342 | const fn = yield* stack.deploy(EffectWebFunction.pipe(Effect.provide(EffectWebFunctionLive))); |
| 343 | |
| 344 | expect(yield* getText(fn.url)).toBe("hello from effect"); |
| 345 | |
| 346 | const runtime = (yield* send(HttpClientRequest.get(`${fn.url}/runtime`)).pipe( |
| 347 | Effect.flatMap((response) => response.json), |
| 348 | )) as { endpoint?: string; requestId?: string; hasCredentials: boolean; region?: string }; |
| 349 | expect(runtime.endpoint).toMatch(/:\d+$/); |
| 350 | expect(runtime.requestId).toBeTruthy(); |
| 351 | expect(runtime.hasCredentials).toBe(true); |
| 352 | |
| 353 | // The S3 bindings granted the execution role access and the runtime |
| 354 | // signs with the role's credentials. |
| 355 | const s3 = yield* send(HttpClientRequest.get(`${fn.url}/s3?key=effect.txt`)).pipe( |
| 356 | Effect.flatMap((response) => response.json), |
| 357 | ); |
| 358 | expect(s3).toEqual({ key: "effect.txt", body: `written by ${stack.stage}` }); |
| 359 | |
| 360 | yield* expectStreamed(fn.url); |
| 361 | |
| 362 | yield* stack.destroy(); |
| 363 | yield* expectFunctionDeleted(fn.functionName, fn.roleName); |
| 364 | }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))), |
| 365 | { tags, timeout: 300_000 }, |
| 366 | ); |
| 367 | |
| 368 | test.provider( |
| 369 | "prebuilt directory deployed as-is", |
| 370 | (stack) => |
| 371 | Effect.gen(function* () { |
| 372 | yield* stack.destroy(); |
| 373 | |
| 374 | const fn = yield* stack.deploy( |
| 375 | AWS.Lambda.WebFunction("Prebuilt", { |
| 376 | main: prebuiltMain, |
| 377 | bundle: false, |
| 378 | authType: "ApplicationManaged", |
| 379 | }), |
| 380 | ); |
| 381 | const body = yield* getText(fn.url); |
| 382 | expect(body).toMatch(/^prebuilt on .+:\d+$/); |
| 383 | |
| 384 | yield* stack.destroy(); |
| 385 | yield* expectFunctionDeleted(fn.functionName, fn.roleName); |
| 386 | }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))), |
| 387 | { tags, timeout: 240_000 }, |
| 388 | ); |
| 389 | |
| 390 | test.provider( |
| 391 | "a rejected create does not strand the execution role", |
| 392 | (stack) => |
| 393 | Effect.gen(function* () { |
| 394 | yield* stack.destroy(); |
| 395 | |
| 396 | const declaration = AWS.Lambda.WebFunction("Rejected", { |
| 397 | main: asyncServerMain, |
| 398 | authType: "ApplicationManaged", |
| 399 | // Reserved for Lambda: CreateWebFunction rejects the revision after |
| 400 | // the execution role already exists. |
| 401 | env: { AWS_LAMBDA_HTTP_ENDPOINT: "127.0.0.1:1" }, |
| 402 | }); |
| 403 | const failure = yield* stack.deploy(declaration).pipe(Effect.flip); |
| 404 | expect(String(failure)).toContain("ValidationException"); |
| 405 | |
| 406 | // Physical names start with the (truncated) stack name. |
| 407 | const prefix = stack.name |
| 408 | .replaceAll(/[^a-zA-Z0-9-]/g, "-") |
| 409 | .replace(/-+/g, "-") |
| 410 | .slice(0, 32); |
| 411 | const roles = iam.listRoles.items({}).pipe( |
| 412 | Stream.filter((role) => role.RoleName.startsWith(prefix)), |
| 413 | Stream.map((role) => role.RoleName), |
| 414 | Stream.runCollect, |
| 415 | Effect.map((names) => Array.from(names)), |
| 416 | ); |
| 417 | expect((yield* roles).length).toBeGreaterThan(0); |
| 418 | |
| 419 | yield* stack.destroy(); |
| 420 | expect(yield* roles).toEqual([]); |
| 421 | }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))), |
| 422 | { tags, timeout: 180_000 }, |
| 423 | ); |
| 424 | |
| 425 | test.provider( |
| 426 | "event sources and background loops fail at plan", |
| 427 | (stack) => |
| 428 | Effect.gen(function* () { |
| 429 | const failure = <A, E, R>(plan: Effect.Effect<A, E, R>) => |
| 430 | plan.pipe( |
| 431 | Effect.exit, |
| 432 | Effect.map((exit) => (exit._tag === "Failure" ? String(Cause.squash(exit.cause)) : "")), |
| 433 | ); |
| 434 | |
| 435 | expect( |
| 436 | yield* failure(stack.plan(EventSourceWeb.pipe(Effect.provide(EventSourceWebLive)))), |
| 437 | ).toContain( |
| 438 | 'AWS.Lambda.QueueEventSource needs an AWS.Lambda.Function, but "EventSourceWeb" is an AWS.Lambda.WebFunction', |
| 439 | ); |
| 440 | expect( |
| 441 | yield* failure(stack.plan(BackgroundLoopWeb.pipe(Effect.provide(BackgroundLoopWebLive)))), |
| 442 | ).toContain("ServerHost"); |
| 443 | }), |
| 444 | { tags, timeout: 60_000 }, |
| 445 | ); |
| 446 | |
| 447 | // Slow: the network connector takes ~3 minutes to become ACTIVE. |
| 448 | test.provider.skipIf(!!process.env.FAST)( |
| 449 | "vpc routes outbound traffic through the VPC", |
| 450 | (stack) => |
| 451 | Effect.gen(function* () { |
| 452 | yield* stack.destroy(); |
| 453 | |
| 454 | // The VPC's Amazon-provided resolver (base + 2) only answers from |
| 455 | // inside the VPC: a function without VPC egress can't reach it. |
| 456 | const resolverUrl = (url: string) => `${url}/dns?server=10.61.0.2&name=aws.amazon.com`; |
| 457 | const deploy = (withVpc: boolean) => |
| 458 | stack.deploy( |
| 459 | Effect.gen(function* () { |
| 460 | const network = yield* AWS.EC2.Network("WebVpc", { |
| 461 | cidrBlock: "10.61.0.0/16", |
| 462 | availabilityZones: 2, |
| 463 | }); |
| 464 | const sg = yield* AWS.EC2.SecurityGroup("WebVpcSg", { vpcId: network.vpcId }); |
| 465 | const fn = yield* AWS.Lambda.WebFunction("VpcFunction", { |
| 466 | main: asyncServerMain, |
| 467 | authType: "ApplicationManaged", |
| 468 | ...(withVpc |
| 469 | ? { vpc: { subnetIds: network.privateSubnetIds, securityGroupIds: [sg.groupId] } } |
| 470 | : {}), |
| 471 | }); |
| 472 | // A second endpoint: when `vpc` is removed it moves after the |
| 473 | // built-in one, so it is the one that releases the connector. |
| 474 | const extra = yield* AWS.Lambda.WebFunctionEndpoint("VpcExtra", { |
| 475 | function: fn, |
| 476 | authType: "ApplicationManaged", |
| 477 | }); |
| 478 | return { fn, extraUrl: extra.url }; |
| 479 | }), |
| 480 | ); |
| 481 | |
| 482 | const dns = (url: string) => |
| 483 | send(HttpClientRequest.get(resolverUrl(url))).pipe( |
| 484 | Effect.flatMap((response) => response.json), |
| 485 | Effect.map((body) => body as { ok: boolean; addresses?: string[]; error?: string }), |
| 486 | ); |
| 487 | |
| 488 | const { fn: before } = yield* deploy(false); |
| 489 | expect((yield* dns(before.url)).ok).toBe(false); |
| 490 | |
| 491 | const { fn: after, extraUrl } = yield* deploy(true); |
| 492 | expect(after.revisionId).not.toBe(before.revisionId); |
| 493 | const resolved = yield* dns(after.url).pipe( |
| 494 | Effect.repeat({ schedule: Schedule.spaced("3 seconds"), until: (r) => r.ok, times: 20 }), |
| 495 | ); |
| 496 | expect(resolved.ok).toBe(true); |
| 497 | expect(resolved.addresses?.length).toBeGreaterThan(0); |
| 498 | |
| 499 | // Out-of-band: the revision pins a version of a WebFunction connector. |
| 500 | const revision = yield* LambdaWeb.getWebFunctionRevision({ |
| 501 | functionName: after.functionName, |
| 502 | revisionId: after.revisionId, |
| 503 | }); |
| 504 | const connectorArn = revision.serviceConfig.egressNetworkConnectorArn!; |
| 505 | expect(connectorArn).toMatch(/:network-connector:.+:\d+$/); |
| 506 | const connectorId = connectorArn.split(":").at(-2)!; |
| 507 | const connector = yield* lambdacore.getNetworkConnector({ Identifier: connectorId }); |
| 508 | expect(connector.State).toBe("ACTIVE"); |
| 509 | expect( |
| 510 | connector.Configuration?.VpcEgressConfiguration?.AssociatedComputeResourceTypes, |
| 511 | ).toEqual(["WebFunction"]); |
| 512 | |
| 513 | // VPC egress needs a single-Region endpoint. |
| 514 | const multiRegion = yield* stack |
| 515 | .plan( |
| 516 | AWS.Lambda.WebFunction("VpcFunction", { |
| 517 | main: asyncServerMain, |
| 518 | authType: "ApplicationManaged", |
| 519 | vpc: { subnetIds: ["subnet-0"], securityGroupIds: ["sg-0"] }, |
| 520 | regions: ["us-east-1"], |
| 521 | }), |
| 522 | ) |
| 523 | .pipe(Effect.flip); |
| 524 | expect(String(multiRegion)).toContain("WebFunctionVpcRequiresHomeRegion"); |
| 525 | |
| 526 | const connectorGone = lambdacore.getNetworkConnector({ Identifier: connectorId }).pipe( |
| 527 | Effect.map(() => false), |
| 528 | Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(true)), |
| 529 | ); |
| 530 | const operatorRole = connector.OperatorRole!.split("/").pop()!; |
| 531 | const operatorRoleGone = iam.getRole({ RoleName: operatorRole }).pipe( |
| 532 | Effect.map(() => false), |
| 533 | Effect.catchTag("NoSuchEntityException", () => Effect.succeed(true)), |
| 534 | ); |
| 535 | expect((yield* dns(extraUrl)).ok).toBe(true); |
| 536 | |
| 537 | // Removing `vpc` releases the connector and its operator role in the |
| 538 | // same deploy, once no endpoint serves a revision that uses it. |
| 539 | const { fn: removed, extraUrl: removedExtraUrl } = yield* deploy(false); |
| 540 | expect(yield* connectorGone).toBe(true); |
| 541 | expect(yield* operatorRoleGone).toBe(true); |
| 542 | expect((yield* dns(removed.url)).ok).toBe(false); |
| 543 | expect((yield* dns(removedExtraUrl)).ok).toBe(false); |
| 544 | |
| 545 | yield* stack.destroy(); |
| 546 | yield* expectFunctionDeleted(after.functionName, after.roleName); |
| 547 | }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))), |
| 548 | { tags: [...tags, "provider:aws:ec2"], timeout: 1_500_000 }, |
| 549 | ); |
| 550 | |
| 551 | // Slow: the endpoint replicates the revision to every Region. |
| 552 | test.provider.skipIf(!!process.env.FAST)( |
| 553 | "regions serves from several Regions behind one global domain", |
| 554 | (stack) => |
| 555 | Effect.gen(function* () { |
| 556 | yield* stack.destroy(); |
| 557 | |
| 558 | const deploy = (regions: string[] | undefined) => |
| 559 | stack.deploy( |
| 560 | AWS.Lambda.WebFunction("Global", { |
| 561 | main: asyncServerMain, |
| 562 | authType: "ApplicationManaged", |
| 563 | env: { GREETING: "global" }, |
| 564 | ...(regions ? { regions } : {}), |
| 565 | }), |
| 566 | ); |
| 567 | |
| 568 | const global = yield* deploy(["us-east-1"]); |
| 569 | expect(global.domainName).toContain(".lambda-web.global.on.aws"); |
| 570 | expect(global.endpointType).toBe("MultiRegion"); |
| 571 | const endpoint = yield* getEndpoint(global.functionName); |
| 572 | expect(endpoint.endpointType).toBe("MultiRegion"); |
| 573 | expect([...endpoint.regions].sort()).toEqual(["us-east-1", "us-west-2"]); |
| 574 | expect(yield* getTextUntil(global.url, (body) => body === "greeting=global")).toBe( |
| 575 | "greeting=global", |
| 576 | ); |
| 577 | |
| 578 | // Regions are immutable on an endpoint: changing them recreates it |
| 579 | // with a new domain; the function and its revision stay. |
| 580 | const home = yield* deploy(undefined); |
| 581 | expect(home.functionName).toBe(global.functionName); |
| 582 | expect(home.url).not.toBe(global.url); |
| 583 | expect((yield* getEndpoint(home.functionName)).endpointType).toBe("HomeRegion"); |
| 584 | expect(home.endpointType).toBe("HomeRegion"); |
| 585 | expect(yield* getText(home.url)).toBe("greeting=global"); |
| 586 | |
| 587 | yield* stack.destroy(); |
| 588 | yield* expectFunctionDeleted(global.functionName, global.roleName); |
| 589 | }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))), |
| 590 | { tags, timeout: 900_000 }, |
| 591 | ); |
| 592 | |
| 593 | // Slow: an Aurora cluster takes ~10 minutes to create and to delete. |
| 594 | test.provider.skipIf(!!process.env.FAST)( |
| 595 | "RDS.Connect requests VPC access through the binding channel", |
| 596 | (stack) => |
| 597 | Effect.gen(function* () { |
| 598 | yield* stack.destroy(); |
| 599 | |
| 600 | const { api, cluster, secret } = yield* stack.deploy( |
| 601 | Effect.gen(function* () { |
| 602 | const { cluster, secret } = yield* RdsWebInfra; |
| 603 | const api = yield* RdsWebFunction; |
| 604 | return { api, cluster, secret }; |
| 605 | }).pipe(Effect.provide(RdsWebFunctionLive)), |
| 606 | ); |
| 607 | |
| 608 | // The binding's subnets and security group became the function's |
| 609 | // egress connector, though the function sets no `vpc` prop. |
| 610 | const revision = yield* LambdaWeb.getWebFunctionRevision({ |
| 611 | functionName: api.functionName, |
| 612 | revisionId: api.revisionId, |
| 613 | }); |
| 614 | const connectorArn = revision.serviceConfig.egressNetworkConnectorArn!; |
| 615 | expect(connectorArn).toMatch(/:network-connector:.+:\d+$/); |
| 616 | const connector = yield* lambdacore.getNetworkConnector({ |
| 617 | Identifier: connectorArn.split(":").at(-2)!, |
| 618 | }); |
| 619 | expect(connector.Configuration?.VpcEgressConfiguration?.SubnetIds).toHaveLength(2); |
| 620 | |
| 621 | // Bootstrap the IAM-auth database user through the Data API. |
| 622 | for (const sqlText of [ |
| 623 | "DO $$ BEGIN CREATE USER app_iam WITH LOGIN; EXCEPTION WHEN duplicate_object THEN NULL; END $$", |
| 624 | "GRANT rds_iam TO app_iam", |
| 625 | ]) { |
| 626 | yield* RDSData.executeStatement({ |
| 627 | resourceArn: cluster.dbClusterArn, |
| 628 | secretArn: secret.secretArn, |
| 629 | database: "app", |
| 630 | sql: sqlText, |
| 631 | }).pipe( |
| 632 | Effect.retry({ |
| 633 | while: (e) => e._tag === "DatabaseResumingException", |
| 634 | schedule: Schedule.spaced("5 seconds"), |
| 635 | times: 24, |
| 636 | }), |
| 637 | ); |
| 638 | } |
| 639 | |
| 640 | // A real query: IAM token, TLS, and a socket into the private subnets. |
| 641 | const health = yield* send(HttpClientRequest.get(`${api.url}/drizzle-health`)).pipe( |
| 642 | Effect.flatMap((response) => response.json), |
| 643 | ); |
| 644 | expect(health).toEqual({ rows: [{ one: 1 }] }); |
| 645 | |
| 646 | yield* stack.destroy(); |
| 647 | yield* expectFunctionDeleted(api.functionName, api.roleName); |
| 648 | }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))), |
| 649 | { tags: [...tags, "provider:aws:rds", "provider:aws:ec2"], timeout: 2_700_000 }, |
| 650 | ); |
| 651 | |
| 652 | test.provider( |
| 653 | "out-of-range settings fail at plan", |
| 654 | (stack) => |
| 655 | Effect.gen(function* () { |
| 656 | const planError = <A, E, R>(declaration: Effect.Effect<A, E, R>) => |
| 657 | stack.plan(declaration).pipe( |
| 658 | Effect.exit, |
| 659 | Effect.map((exit) => (exit._tag === "Failure" ? String(Cause.squash(exit.cause)) : "")), |
| 660 | ); |
| 661 | const fn = (props: Partial<AWS.Lambda.WebFunctionProps>) => |
| 662 | AWS.Lambda.WebFunction("Invalid", { |
| 663 | main: asyncServerMain, |
| 664 | authType: "ApplicationManaged", |
| 665 | ...props, |
| 666 | }); |
| 667 | |
| 668 | expect(yield* planError(fn({ rateLimit: 1500 }))).toContain("rateLimit 1500 is not allowed"); |
| 669 | expect(yield* planError(fn({ rateLimit: 150 }))).toContain("e.g. 100 or 200"); |
| 670 | expect(yield* planError(fn({ maxEnvironments: 1 }))).toContain( |
| 671 | "maxEnvironments 1 is not allowed", |
| 672 | ); |
| 673 | expect(yield* planError(fn({ canary: { weight: 150 } }))).toContain( |
| 674 | "canary weight 150 is not allowed: use a whole number from 0 to 100.", |
| 675 | ); |
| 676 | expect(yield* planError(fn({ canary: { weight: 12.5 } }))).toContain( |
| 677 | "canary weight 12.5 is not allowed", |
| 678 | ); |
| 679 | expect(yield* planError(fn({ maxConcurrencyPerEnvironment: 129 }))).toContain( |
| 680 | "maxConcurrencyPerEnvironment 129 is not allowed", |
| 681 | ); |
| 682 | expect(yield* planError(fn({ timeout: Duration.minutes(20) }))).toContain( |
| 683 | "timeout of 1200 seconds is not allowed", |
| 684 | ); |
| 685 | expect( |
| 686 | yield* planError( |
| 687 | Effect.gen(function* () { |
| 688 | const api = yield* fn({}); |
| 689 | return yield* AWS.Lambda.WebFunctionEndpoint("InvalidEndpoint", { |
| 690 | function: api, |
| 691 | authType: "ApplicationManaged", |
| 692 | rateLimit: 2500, |
| 693 | }); |
| 694 | }), |
| 695 | ), |
| 696 | ).toContain("rateLimit 2500 is not allowed"); |
| 697 | |
| 698 | expect( |
| 699 | yield* planError( |
| 700 | fn({ |
| 701 | vpc: { subnetIds: ["subnet-0"], securityGroupIds: ["sg-0"] }, |
| 702 | regions: ["us-east-1"], |
| 703 | }), |
| 704 | ), |
| 705 | ).toContain("`vpc` can't be combined with `regions`"); |
| 706 | |
| 707 | // Valid boundaries plan cleanly. |
| 708 | const ok = yield* stack.plan( |
| 709 | fn({ rateLimit: 0, maxEnvironments: 2, maxConcurrencyPerEnvironment: 128 }), |
| 710 | ); |
| 711 | expect(ok.resources.Invalid).toMatchObject({ action: "create" }); |
| 712 | }), |
| 713 | { tags, timeout: 60_000 }, |
| 714 | ); |