@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, 04:45 UTC

main
ts 1,534 lines 58.9 KB
Raw
1 import * as logs from "@distilled.cloud/aws/cloudwatch-logs";
2 import type { Credentials } from "@distilled.cloud/aws/Credentials";
3 import * as iam from "@distilled.cloud/aws/iam";
4 import * as LambdaWeb from "@distilled.cloud/aws/lambda-web";
5 import type { Region } from "@distilled.cloud/aws/Region";
6 import { Unowned } from "alchemy/AdoptPolicy";
7 import { deepEqual, havePropsChanged, isResolved, stripEffects } from "alchemy/Diff";
8 import * as Output from "alchemy/Output";
9 import { createPhysicalName } from "alchemy/PhysicalName";
10 import { Platform, type Main, type PlatformProps } from "alchemy/Platform";
11 import type { LogLine, LogsInput } from "alchemy/Provider";
12 import * as Provider from "alchemy/Provider";
13 import type { ScopedPlanStatusSession } from "alchemy/Report";
14 import { Resource, type ResourceBinding } from "alchemy/Resource";
15 import { createHostRuntimeContext, type HostRuntimeContext } from "alchemy/Runtime/Process";
16 import { Stack } from "alchemy/Stack";
17 import {
18 createInternalTags,
19 createTagsList,
20 diffTags,
21 hasAlchemyTags,
22 tagRecord,
23 } from "alchemy/Tags";
24 import * as Data from "effect/Data";
25 import * as Duration from "effect/Duration";
26 import * as Effect from "effect/Effect";
27 import * as Schedule from "effect/Schedule";
28 import * as Stream from "effect/Stream";
29 import { Assets, ensureLambdaWebCodeAccess } from "../Assets.ts";
30 import { AWSEnvironment } from "../Environment.ts";
31 import type { PolicyDocument, PolicyStatement } from "../IAM/Policy.ts";
32 import type { Providers } from "../Providers.ts";
33 import type { FunctionBuildOptions, FunctionZipProps } from "./Function.ts";
34 import { makeFunctionBundler, type FunctionBundleOptions } from "./FunctionBundle.ts";
35 import type { NetworkConnectorProps } from "./NetworkConnector.ts";
36 import { createConnector, getConnector, syncConnector } from "./NetworkConnectorLifecycle.ts";
37 import {
38 connectorOfRevision,
39 deleteConnectorAndRole,
40 deleteOperatorRole,
41 EGRESS_POLICY,
42 releaseEgressConnector,
43 sameConnector,
44 } from "./WebFunctionEgress.ts";
45 import {
46 createEndpointConfig,
47 deleteEndpoint,
48 endpointTypeOf,
49 endpointLimits,
50 getEndpoint,
51 latestRevisionId,
52 servedRevisions,
53 syncEndpoint,
54 validateWebFunctionSettings,
55 WebFunctionFailed,
56 WebFunctionNotReady,
57 type WebFunctionAuthType,
58 type WebFunctionCanary,
59 type WebFunctionEndpointSpec,
60 type WebFunctionEndpointType,
61 type WebFunctionRevisionWeight,
62 } from "./WebFunctionEndpointSync.ts";
63
64 export type {
65 WebFunctionAuthType,
66 WebFunctionCanary,
67 WebFunctionEndpointType,
68 WebFunctionRevisionWeight,
69 } from "./WebFunctionEndpointSync.ts";
70
71 export const WebFunctionTypeId = "AWS.Lambda.WebFunction" as const;
72 export type WebFunctionTypeId = typeof WebFunctionTypeId;
73
74 /** Name of the built-in endpoint unless `endpointName` is set. */
75 const DEFAULT_ENDPOINT_NAME = "default";
76
77 /** Entry file inside the archive (see `zipCode`). */
78 const ENTRY_FILE = "index.mjs";
79
80 /** Inline policy denying the execution role `logs:CreateLogGroup` on its own groups. */
81 const LOG_GROUP_GUARD_POLICY = "AlchemyDenyLogGroupCreate";
82
83 const DEFAULT_TIMEOUT_SECONDS = 30;
84 const DEFAULT_MAX_CONCURRENCY = 64;
85
86 export const isWebFunction = (value: unknown): value is WebFunction =>
87 typeof value === "object" &&
88 value !== null &&
89 "Type" in value &&
90 (value as { Type?: unknown }).Type === WebFunctionTypeId;
91
92 /** Subnets and security groups for a Web Function's outbound VPC traffic. */
93 export interface WebFunctionVpc {
94 /** Subnets the connector creates network interfaces in. */
95 subnetIds: string[];
96 /** Security groups applied to the connector's network interfaces. */
97 securityGroupIds: string[];
98 }
99
100 /** `vpc` was combined with `regions`; VPC egress works only in the home Region. */
101 export class WebFunctionVpcRequiresHomeRegion extends Data.TaggedError(
102 "WebFunctionVpcRequiresHomeRegion",
103 )<{ functionId: string; message: string }> {}
104
105 export interface WebFunctionProps extends PlatformProps {
106 /**
107 * Entry module of the web server.
108 *
109 * With an Effect implementation (the class form), Alchemy serves the
110 * returned `fetch` handler. Without one, `main` is your own Node server
111 * and is bundled as-is: it must listen on the `host:port` Lambda passes
112 * in `AWS_LAMBDA_HTTP_ENDPOINT`.
113 */
114 main: string;
115 /**
116 * Set to `false` to skip bundling and deploy `main`'s directory as-is,
117 * e.g. a framework's standalone server output (`.output/server`,
118 * Next.js `.next/standalone`). Lambda starts `main`, which must listen
119 * on `AWS_LAMBDA_HTTP_ENDPOINT`.
120 * @default true
121 */
122 bundle?: false;
123 /**
124 * Name of the Web Function. If omitted, a unique name is generated from
125 * the stack, stage, and logical ID. Changing it replaces the function.
126 */
127 functionName?: string;
128 /**
129 * Description recorded on each revision.
130 */
131 description?: string;
132 /**
133 * Node.js runtime of the revision. Web Functions run on Arm64.
134 * @default "nodejs24.x"
135 */
136 runtime?: "nodejs24.x";
137 /**
138 * Environment variables available to the server. Each change creates a
139 * new revision.
140 */
141 env?: Record<string, any>;
142 /**
143 * Maximum time a single HTTP request can run, rounded up to whole
144 * seconds. Valid range: 3 seconds to 15 minutes.
145 * @default 30 seconds
146 */
147 timeout?: Duration.Duration;
148 /**
149 * Upper bound on concurrent HTTP requests per execution environment.
150 * Lambda manages a dynamic per-environment limit that can be lower, but
151 * never exceeds this value. This is not a total: the endpoint's peak is
152 * `maxEnvironments × maxConcurrencyPerEnvironment`. Valid range: 1–128.
153 * Lower it for CPU- or memory-bound servers: every environment has a
154 * fixed 2 GB of memory and 2 vCPUs. Changing it creates a new revision.
155 * @default 64
156 */
157 maxConcurrencyPerEnvironment?: number;
158 /**
159 * Who may call the built-in endpoint. `"ApplicationManaged"` forwards
160 * every request (a public endpoint; authenticate in your application).
161 * `"IamAuth"` requires SigV4-signed requests from principals with
162 * `lambda:InvokeWebFunctionEndpoint`, such as a CloudFront distribution
163 * with origin access control. Changes apply in place.
164 */
165 authType: WebFunctionAuthType;
166 /**
167 * Name of the built-in endpoint. Your server receives it in the
168 * `lambda-web-endpoint-name` request header. Changing it recreates the
169 * endpoint, which gets a new URL.
170 * @default "default"
171 */
172 endpointName?: string;
173 /**
174 * Additional AWS Regions the built-in endpoint serves from. When set, the
175 * endpoint is `MultiRegion`: one global domain with latency-based routing
176 * across the home Region and these Regions. Changing it recreates the
177 * endpoint, which gets a new URL.
178 */
179 regions?: string[];
180 /**
181 * Maximum number of execution environments the built-in endpoint uses per
182 * Region (2–10,000). Changes apply in place.
183 */
184 maxEnvironments?: number;
185 /**
186 * Maximum requests per second the built-in endpoint accepts, enforced per
187 * Region. Excess requests receive HTTP 429; `0` disables the endpoint.
188 * Changes apply in place.
189 */
190 rateLimit?: number;
191 /**
192 * Roll out deploys gradually on the built-in endpoint: the revision a
193 * deploy publishes gets `weight` percent of traffic and the revision it
194 * served before keeps the rest. Raise `weight` to shift more traffic,
195 * set it to `100` (or remove `canary`) to promote, or `0` to roll back.
196 * Each endpoint has its own split.
197 */
198 canary?: WebFunctionCanary;
199 /**
200 * Route the server's outbound traffic through your VPC so it can reach
201 * private resources such as RDS. Alchemy creates a Lambda network
202 * connector (and the operator role Lambda uses to manage its network
203 * interfaces) in these subnets and attaches it to every revision. Use at
204 * least two subnets in different Availability Zones; private subnets need
205 * a NAT gateway to reach the internet. Bindings such as `AWS.RDS.Connect`
206 * can request the same access, and both are merged.
207 *
208 * VPC access works only with single-Region endpoints, so it can't be
209 * combined with `regions`. Changing it creates a new revision. Removing
210 * it deletes the connector and its operator role once no endpoint serves
211 * a revision that uses them.
212 */
213 vpc?: WebFunctionVpc;
214 /**
215 * Tags applied to the Web Function.
216 */
217 tags?: Record<string, string>;
218 /**
219 * Bundler configuration for {@link main}: rolldown input options,
220 * `output` overrides, `install` for native packages (built for Linux
221 * Arm64), `pure`, and the bundle analyzer.
222 */
223 build?: FunctionBuildOptions;
224 /**
225 * Ship source maps with the bundle and enable `--enable-source-maps`.
226 * @default true
227 */
228 uploadSourceMap?: boolean;
229 exports?: string[];
230 }
231
232 export interface WebFunction extends Resource<
233 WebFunctionTypeId,
234 WebFunctionProps,
235 {
236 /** Name of the Web Function. */
237 functionName: string;
238 /** ARN of the Web Function (`arn:aws:lambda:…:web-function/<name>`). */
239 functionArn: string;
240 /** Name of the built-in endpoint. */
241 endpointName: string;
242 /** ARN of the built-in endpoint, the resource for `lambda:InvokeWebFunctionEndpoint`. */
243 endpointArn: string;
244 /** Lambda-allocated domain of the built-in endpoint. */
245 domainName: string;
246 /** HTTPS URL of the built-in endpoint (`https://<domainName>`). */
247 url: string;
248 /** Auth type of the built-in endpoint. */
249 authType: WebFunctionAuthType;
250 /**
251 * `HomeRegion`, or `MultiRegion` when `regions` is set: one global
252 * domain that routes each request to the nearest Region.
253 */
254 endpointType: WebFunctionEndpointType;
255 /**
256 * Revision the latest deploy published. Endpoints route all traffic to
257 * it, or `canary.weight` percent while a canary runs.
258 */
259 revisionId: string;
260 /**
261 * How the built-in endpoint splits traffic: one revision at 100, or the
262 * stable revision and the canary while a canary runs.
263 */
264 revisionWeights: WebFunctionRevisionWeight[];
265 /** Name of the execution role. */
266 roleName: string;
267 /** ARN of the execution role. */
268 roleArn: string;
269 code: {
270 hash: string;
271 };
272 /**
273 * Requests per second the built-in endpoint allows, as observed. Lets
274 * `alchemy drift` detect out-of-band changes.
275 */
276 rateLimit?: number;
277 /**
278 * Cap on the built-in endpoint's execution environments, as observed.
279 * Lets `alchemy drift` detect out-of-band changes.
280 */
281 maxEnvironments?: number;
282 /**
283 * Tags on the web function, as observed. Lets `alchemy drift` detect
284 * out-of-band changes.
285 */
286 tags?: Record<string, string>;
287 /**
288 * Inline policies Alchemy writes on the execution role (binding grants
289 * and the log-group guard), as observed. Lets `alchemy drift` detect
290 * out-of-band edits.
291 */
292 executionRolePolicies?: Record<string, unknown>;
293 },
294 {
295 env?: Record<string, any>;
296 policyStatements?: PolicyStatement[];
297 /**
298 * VPC access requested by a binding (e.g. `AWS.RDS.Connect` with
299 * `subnetIds`/`securityGroupIds`). Merged with the `vpc` prop.
300 */
301 vpc?: WebFunctionVpc;
302 },
303 Providers
304 > {}
305
306 export type WebFunctionServices = Credentials | Region | AWSEnvironment | WebFunction;
307
308 export type WebFunctionShape = Main<WebFunctionServices>;
309
310 /** HTTP-only host context: `serve` registers the `fetch` handler. */
311 export type WebFunctionRuntimeContext = Omit<HostRuntimeContext, "run">;
312
313 /**
314 * An AWS Lambda Web Function: a serverless HTTP server. Lambda runs your
315 * Node.js server in execution environments that each serve many concurrent
316 * requests (up to 128), streams responses to the client as they are
317 * produced, scales to zero, and gives every function an HTTPS endpoint.
318 *
319 * Use a Web Function for anything that answers HTTP — APIs, server-rendered
320 * apps, streaming AI responses. Use `AWS.Lambda.Function` for event sources
321 * (SQS, DynamoDB Streams, S3 notifications, schedules) and direct invokes;
322 * a Web Function only receives HTTP. Event sources and background loops
323 * (`ServerHost.run`) are type errors in a Web Function and fail at plan.
324 * Web Functions launched in `us-east-1`, `us-east-2`, `us-west-2`,
325 * `eu-west-1`, and `ap-northeast-1`, and AWS is adding Regions; see the
326 * [Lambda pricing page](https://aws.amazon.com/lambda/pricing/) for where
327 * they run today. Alchemy doesn't restrict the Region.
328 *
329 * Every deploy uploads the bundle to the Alchemy assets bucket, creates an
330 * immutable revision, and shifts the endpoint's traffic to it. Lambda keeps
331 * the 50 most recent revisions.
332 *
333 * ### Effect Web Functions
334 * Return a `fetch` handler. Alchemy serves it with Effect's Node HTTP
335 * server on the address Lambda assigns, so streamed `HttpServerResponse`
336 * bodies reach the client chunk by chunk. Bindings grant IAM permissions to
337 * the function's execution role exactly as on `AWS.Lambda.Function`.
338 *
339 * **Example:** Effect Web Function with a DynamoDB binding
340 * ```typescript
341 * // src/api.ts
342 * import * as AWS from "@alchemy.run/aws";
343 * import * as Effect from "effect/Effect";
344 * import { HttpServerRequest } from "effect/http/HttpServerRequest";
345 * import * as HttpServerResponse from "effect/http/HttpServerResponse";
346 *
347 * export default class Api extends AWS.Lambda.WebFunction<Api>()(
348 * "Api",
349 * { main: import.meta.url, authType: "ApplicationManaged" },
350 * Effect.gen(function* () {
351 * const table = yield* AWS.DynamoDB.Table("Items", {
352 * partitionKey: "pk",
353 * attributes: { pk: "S" },
354 * });
355 * const getItem = yield* AWS.DynamoDB.GetItem(table);
356 * return {
357 * fetch: Effect.gen(function* () {
358 * const request = yield* HttpServerRequest;
359 * const id = new URL(request.originalUrl).searchParams.get("id")!;
360 * const { Item } = yield* getItem({ Key: { pk: { S: id } } });
361 * return yield* HttpServerResponse.json(Item ?? null);
362 * }),
363 * };
364 * }).pipe(Effect.provide(AWS.DynamoDB.GetItemHttp)),
365 * ) {}
366 * ```
367 *
368 * **Example:** Streaming a response
369 * ```typescript
370 * export default class Chat extends AWS.Lambda.WebFunction<Chat>()(
371 * "Chat",
372 * { main: import.meta.url, authType: "ApplicationManaged" },
373 * Effect.gen(function* () {
374 * return {
375 * fetch: Effect.succeed(
376 * HttpServerResponse.stream(
377 * Stream.make("Hello", " from", " Lambda").pipe(
378 * Stream.tap(() => Effect.sleep("100 millis")),
379 * Stream.encodeText,
380 * ),
381 * { contentType: "text/plain" },
382 * ),
383 * ),
384 * };
385 * }),
386 * ) {}
387 * ```
388 *
389 * ### Async Web Functions
390 * Point `main` at your own Node server. Alchemy bundles it as-is, with no
391 * Effect runtime and no wrapper. Listen on the `host:port` Lambda passes in
392 * `AWS_LAMBDA_HTTP_ENDPOINT`.
393 *
394 * **Example:** Hono
395 * ```typescript
396 * // src/server.ts
397 * import { serve } from "@hono/node-server";
398 * import { Hono } from "hono";
399 *
400 * const app = new Hono();
401 * app.get("/", (c) => c.text("Hello from Hono"));
402 *
403 * const [hostname, port] = (process.env.AWS_LAMBDA_HTTP_ENDPOINT ?? "localhost:3000").split(":");
404 * serve({ fetch: app.fetch, hostname, port: Number(port) });
405 * ```
406 *
407 * ```typescript
408 * // alchemy.run.ts
409 * const api = yield* AWS.Lambda.WebFunction("Api", {
410 * main: "./src/server.ts",
411 * authType: "ApplicationManaged",
412 * });
413 * ```
414 *
415 * **Example:** Express
416 * ```typescript
417 * // src/server.ts
418 * import express from "express";
419 *
420 * const app = express();
421 * app.get("/", (_req, res) => res.send("Hello from Express"));
422 *
423 * const [host, port] = (process.env.AWS_LAMBDA_HTTP_ENDPOINT ?? "localhost:3000").split(":");
424 * app.listen(Number(port), host);
425 * ```
426 *
427 * **Example:** A framework's standalone server output
428 * ```typescript
429 * const site = yield* AWS.Lambda.WebFunction("Site", {
430 * main: "./.output/server/index.mjs",
431 * bundle: false,
432 * authType: "ApplicationManaged",
433 * });
434 * ```
435 *
436 * ### Configuration
437 * **Example:** Concurrency, timeout, and traffic limits
438 * ```typescript
439 * const api = yield* AWS.Lambda.WebFunction("Api", {
440 * main: "./src/server.ts",
441 * authType: "ApplicationManaged",
442 * maxConcurrencyPerEnvironment: 128,
443 * timeout: Duration.minutes(5),
444 * maxEnvironments: 10,
445 * rateLimit: 500,
446 * });
447 * ```
448 *
449 * **Example:** Serving from several Regions behind one domain
450 * ```typescript
451 * const api = yield* AWS.Lambda.WebFunction("Api", {
452 * main: "./src/server.ts",
453 * authType: "ApplicationManaged",
454 * regions: ["us-east-1", "eu-west-1"],
455 * });
456 * ```
457 *
458 * **Example:** Requiring SigV4-signed callers
459 * ```typescript
460 * const internal = yield* AWS.Lambda.WebFunction("Internal", {
461 * main: "./src/server.ts",
462 * authType: "IamAuth",
463 * });
464 * ```
465 *
466 * ### Canary deploys
467 * **Example:** Send 10% of traffic to each new deploy
468 * ```typescript
469 * const api = yield* AWS.Lambda.WebFunction("Api", {
470 * main: "./src/server.ts",
471 * authType: "ApplicationManaged",
472 * // 90% stays on the previous revision. Raise it to shift more, set
473 * // 100 (or remove `canary`) to promote, or 0 to roll back.
474 * canary: { weight: 10 },
475 * });
476 *
477 * api.revisionWeights; // [{ revisionId: "<previous>", weight: 90 }, { revisionId: api.revisionId, weight: 10 }]
478 * ```
479 *
480 * Put CloudFront in front with a `CloudFront.Distribution` origin
481 * `{ webFunction: internal }`, which grants only that distribution access.
482 * Grant other callers with `AWS.Lambda.WebFunctionPermission`.
483 *
484 * ### Private network access
485 * Set `vpc` to send the server's outbound traffic through your VPC, for
486 * example to reach an RDS database in private subnets. Alchemy creates and
487 * manages the Lambda network connector this needs.
488 *
489 * **Example:** Reaching resources in private subnets
490 * ```typescript
491 * const network = yield* AWS.EC2.Network("Network", {
492 * cidrBlock: "10.0.0.0/16",
493 * nat: "single",
494 * });
495 * const appSg = yield* AWS.EC2.SecurityGroup("AppSg", { vpcId: network.vpcId });
496 *
497 * const api = yield* AWS.Lambda.WebFunction("Api", {
498 * main: "./src/server.ts",
499 * authType: "ApplicationManaged",
500 * vpc: {
501 * subnetIds: network.privateSubnetIds,
502 * securityGroupIds: [appSg.groupId],
503 * },
504 * });
505 * ```
506 *
507 * ### Additional endpoints
508 * The settings above configure the function's built-in endpoint, whose
509 * domain is `url`. Add more endpoints, each with its own URL, auth, and
510 * limits, with `AWS.Lambda.WebFunctionEndpoint`. All endpoints serve the
511 * same code; your server tells them apart by the `lambda-web-endpoint-name`
512 * request header.
513 *
514 * **Example:** A private endpoint for CloudFront and a public one for webhooks
515 * ```typescript
516 * const api = yield* AWS.Lambda.WebFunction("Api", {
517 * main: "./src/server.ts",
518 * authType: "IamAuth",
519 * maxEnvironments: 50,
520 * });
521 *
522 * const webhooks = yield* AWS.Lambda.WebFunctionEndpoint("Webhooks", {
523 * function: api,
524 * authType: "ApplicationManaged",
525 * rateLimit: 100,
526 * });
527 * ```
528 *
529 * For a class-form Web Function, pass the class: `function: Api`.
530 *
531 * @resource
532 */
533 /** `vpc` and `regions` together: VPC egress needs a single-Region endpoint. */
534 const requireHomeRegion = (
535 id: string,
536 vpc: WebFunctionVpc | undefined,
537 regions: string[] | undefined,
538 ) =>
539 vpc !== undefined && regions !== undefined && regions.length > 0
540 ? Effect.fail(
541 new WebFunctionVpcRequiresHomeRegion({
542 functionId: id,
543 message: `AWS.Lambda.WebFunction "${id}": \`vpc\` can't be combined with \`regions\`: Lambda routes VPC egress only for single-Region endpoints`,
544 }),
545 )
546 : Effect.void;
547
548 /** The settings Lambda limits, as numbers (Outputs resolve at deploy). */
549 const checkWebFunctionProps = (id: string, props: WebFunctionProps) =>
550 Effect.gen(function* () {
551 const number = (value: unknown) => (typeof value === "number" ? value : undefined);
552 yield* requireHomeRegion(
553 id,
554 props.vpc,
555 Array.isArray(props.regions) ? props.regions : undefined,
556 );
557 yield* validateWebFunctionSettings(`AWS.Lambda.WebFunction "${id}"`, {
558 rateLimit: number(props.rateLimit),
559 maxEnvironments: number(props.maxEnvironments),
560 maxConcurrencyPerEnvironment: number(props.maxConcurrencyPerEnvironment),
561 timeoutSeconds:
562 props.timeout === undefined || Output.isOutput(props.timeout)
563 ? undefined
564 : toTimeoutSeconds(props.timeout),
565 canary:
566 props.canary === undefined || number(props.canary.weight) === undefined
567 ? undefined
568 : props.canary,
569 });
570 });
571
572 export const WebFunction: Platform<
573 WebFunction,
574 WebFunctionServices,
575 WebFunctionShape,
576 WebFunctionRuntimeContext,
577 {},
578 WebFunctionProps
579 > = Platform(WebFunctionTypeId, {
580 // Check limits where the function is declared, so a first deploy fails
581 // at plan too (the provider's diff only runs once state exists).
582 transformProps: (id: string, props: WebFunctionProps) =>
583 globalThis.__ALCHEMY_RUNTIME__
584 ? Effect.succeed(props)
585 : checkWebFunctionProps(id, props).pipe(Effect.as(props)),
586 createRuntimeContext: (id: string): WebFunctionRuntimeContext => {
587 // No `run`: environments exist only while HTTP traffic keeps them warm,
588 // so background loops (e.g. queue pollers via `ServerHost`) would stop
589 // at scale-to-zero and multiply per environment. Without `run`, the
590 // platform never provides `ServerHost`, and such code fails to type
591 // check and fails at plan instead of deploying a poller that silently
592 // stops consuming.
593 const { run: _run, ...context } = createHostRuntimeContext(WebFunctionTypeId)(id);
594 return context;
595 },
596 });
597
598 /** Generated entry for Effect web functions. */
599 const effectEntry = (importPath: string) => `
600 import { bootstrap } from "@alchemy.run/aws/Bootstrap/LambdaWeb";
601 import entrypoint from ${JSON.stringify(importPath)};
602
603 bootstrap(entrypoint);
604 `;
605
606 const mainBasename = (main: string) =>
607 main.slice(Math.max(main.lastIndexOf("/"), main.lastIndexOf("\\")) + 1);
608
609 /** Only the Effect form gets a generated entry; async servers ship as-is. */
610 const bundleOptions: FunctionBundleOptions = { entry: effectEntry };
611
612 /** The bundler reads the Event Function zip props; Web Functions run on Arm64. */
613 const toZipProps = (props: WebFunctionProps): FunctionZipProps =>
614 ({ ...props, architecture: "arm64" }) as FunctionZipProps;
615
616 const toTimeoutSeconds = (timeout: Duration.Duration | undefined): number => {
617 if (timeout === undefined) return DEFAULT_TIMEOUT_SECONDS;
618 // State JSON flattens a Duration to its `toJSON` shape.
619 const json = timeout as { _id?: unknown; _tag?: string; millis?: number; nanos?: string };
620 const input: Duration.Input =
621 json._id === "Duration"
622 ? json._tag === "Millis"
623 ? json.millis!
624 : json._tag === "Nanos"
625 ? BigInt(json.nanos!)
626 : "Infinity"
627 : timeout;
628 return Math.max(1, Math.ceil(Duration.toSeconds(input)));
629 };
630
631 export const WebFunctionProvider = () =>
632 Provider.effect(
633 WebFunction,
634 Effect.gen(function* () {
635 const stack = yield* Stack;
636 const { bundleCode } = yield* makeFunctionBundler;
637 const assets = yield* Assets;
638
639 const alchemyEnv = {
640 ALCHEMY_STACK_NAME: stack.name,
641 ALCHEMY_STAGE: stack.stage,
642 ALCHEMY_PHASE: "runtime",
643 };
644
645 const bundle = (id: string, props: WebFunctionProps) =>
646 bundleCode(id, toZipProps(props), bundleOptions);
647
648 const createNames = Effect.fn(function* (id: string, functionName: string | undefined) {
649 return {
650 functionName: functionName ?? (yield* createPhysicalName({ id, maxLength: 64 })),
651 roleName: yield* createPhysicalName({ id, maxLength: 64 }),
652 policyName: yield* createPhysicalName({ id, maxLength: 128 }),
653 };
654 });
655
656 const ensureRole = Effect.fn(function* (id: string, roleName: string) {
657 const existing = yield* iam
658 .getRole({ RoleName: roleName })
659 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.undefined));
660 const role =
661 existing ??
662 (yield* iam
663 .createRole({
664 RoleName: roleName,
665 AssumeRolePolicyDocument: JSON.stringify({
666 Version: "2012-10-17",
667 Statement: [
668 {
669 Effect: "Allow",
670 Principal: { Service: "lambda.amazonaws.com" },
671 Action: "sts:AssumeRole",
672 },
673 ],
674 }),
675 Tags: createTagsList(yield* createInternalTags(id)),
676 })
677 .pipe(
678 Effect.catchTag("EntityAlreadyExistsException", () =>
679 iam.getRole({ RoleName: roleName }),
680 ),
681 ));
682 yield* iam.attachRolePolicy({
683 RoleName: roleName,
684 PolicyArn: "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",
685 });
686 return role.Role.Arn;
687 });
688
689 const syncBindings = Effect.fn(function* ({
690 roleName,
691 policyName,
692 bindings,
693 }: {
694 roleName: string;
695 policyName: string;
696 bindings: ResourceBinding<WebFunction["Binding"]>[];
697 }) {
698 const active = bindings.filter(
699 (binding: ResourceBinding<WebFunction["Binding"]> & { action?: string }) =>
700 binding.action !== "delete",
701 );
702 const env = active
703 .map((binding) => binding?.data?.env)
704 .reduce((acc, env) => ({ ...acc, ...env }), {});
705 const policyStatements = active.flatMap(
706 (binding) =>
707 binding?.data?.policyStatements?.map((stmt: PolicyStatement) => ({
708 ...stmt,
709 Sid: stmt.Sid?.replace(/[^A-Za-z0-9]+/gi, ""),
710 })) ?? [],
711 );
712 const vpcRequests = active.flatMap((binding) =>
713 binding?.data?.vpc ? [binding.data.vpc] : [],
714 );
715 if (policyStatements.length > 0) {
716 yield* iam.putRolePolicy({
717 RoleName: roleName,
718 PolicyName: policyName,
719 PolicyDocument: JSON.stringify({
720 Version: "2012-10-17",
721 Statement: policyStatements,
722 } satisfies PolicyDocument),
723 });
724 } else {
725 yield* iam
726 .deleteRolePolicy({ RoleName: roleName, PolicyName: policyName })
727 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
728 }
729 return { env, vpcRequests };
730 });
731
732 /** The `vpc` prop and binding requests, merged (set-union). */
733 const mergeVpc = (
734 prop: WebFunctionVpc | undefined,
735 requests: WebFunctionVpc[],
736 ): WebFunctionVpc | undefined => {
737 const all = [...(prop ? [prop] : []), ...requests];
738 return all.length === 0
739 ? undefined
740 : {
741 subnetIds: [...new Set(all.flatMap((v) => v.subnetIds))].sort(),
742 securityGroupIds: [...new Set(all.flatMap((v) => v.securityGroupIds))].sort(),
743 };
744 };
745
746 /** Name shared by the egress connector and its operator role. */
747 const egressName = (id: string) =>
748 createPhysicalName({ id: `${id}-egress`, maxLength: 64, delimiter: "-" });
749
750 /**
751 * The role Lambda assumes to create and tag the connector's network
752 * interfaces in your subnets (the permissions AWS documents for Web
753 * Function connectors).
754 */
755 const ensureOperatorRole = Effect.fn(function* (id: string, roleName: string) {
756 const existing = yield* iam
757 .getRole({ RoleName: roleName })
758 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.undefined));
759 const role =
760 existing ??
761 (yield* iam
762 .createRole({
763 RoleName: roleName,
764 AssumeRolePolicyDocument: JSON.stringify({
765 Version: "2012-10-17",
766 Statement: [
767 {
768 Effect: "Allow",
769 Principal: { Service: "lambda.amazonaws.com" },
770 Action: "sts:AssumeRole",
771 },
772 ],
773 }),
774 Tags: createTagsList(yield* createInternalTags(id)),
775 })
776 .pipe(
777 Effect.catchTag("EntityAlreadyExistsException", () =>
778 iam.getRole({ RoleName: roleName }),
779 ),
780 ));
781 yield* iam.putRolePolicy({
782 RoleName: roleName,
783 PolicyName: EGRESS_POLICY,
784 PolicyDocument: JSON.stringify({
785 Version: "2012-10-17",
786 Statement: [
787 {
788 Effect: "Allow",
789 Action: ["ec2:CreateNetworkInterface"],
790 Resource: [
791 "arn:aws:ec2:*:*:network-interface/*",
792 "arn:aws:ec2:*:*:subnet/*",
793 "arn:aws:ec2:*:*:security-group/*",
794 ],
795 },
796 {
797 Effect: "Allow",
798 Action: ["ec2:CreateTags"],
799 Resource: "arn:aws:ec2:*:*:network-interface/*",
800 Condition: {
801 StringEquals: {
802 "ec2:ManagedResourceOperator": "network-connectors.lambda.amazonaws.com",
803 },
804 },
805 },
806 ],
807 } satisfies PolicyDocument),
808 });
809 return role.Role.Arn;
810 });
811
812 /**
813 * Ensure the egress connector for `vpc` and return the version-qualified
814 * ARN a revision references. A config change publishes a new connector
815 * version, which the next revision picks up.
816 */
817 const syncEgress = Effect.fn(function* ({
818 id,
819 vpc,
820 session,
821 }: {
822 id: string;
823 vpc: WebFunctionVpc;
824 session: ScopedPlanStatusSession;
825 }) {
826 const name = yield* egressName(id);
827 const operatorRole = yield* ensureOperatorRole(id, name);
828 const props: NetworkConnectorProps = {
829 subnetIds: vpc.subnetIds,
830 securityGroupIds: vpc.securityGroupIds,
831 associatedComputeResourceTypes: ["WebFunction"],
832 operatorRole,
833 };
834 const found = yield* getConnector(name);
835 const observed = found && found.State !== "DELETE_FAILED" ? found : undefined;
836 const connector = observed
837 ? yield* syncConnector(observed, name, props, session)
838 : yield* createConnector(name, props, id, session);
839 return (
840 connector.LatestVersionArn ??
841 connector.VersionArn ??
842 `${connector.Arn}:${connector.LatestVersion ?? connector.Version}`
843 );
844 });
845
846 /**
847 * Delete the egress connector and its operator role, if any. The role
848 * goes last: Lambda uses it to remove the connector's interfaces.
849 */
850 const deleteEgress = Effect.fn(function* (id: string, session: ScopedPlanStatusSession) {
851 const name = yield* egressName(id);
852 yield* deleteConnectorAndRole(name, session);
853 // The role can outlive a connector whose create failed.
854 yield* deleteOperatorRole(name);
855 });
856
857 const getFunction = (functionName: string) =>
858 LambdaWeb.getWebFunction({ functionName }).pipe(
859 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
860 );
861
862 const getRevision = (functionName: string, revisionId: string) =>
863 LambdaWeb.getWebFunctionRevision({ functionName, revisionId }).pipe(
864 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
865 );
866
867 const waitForFunctionActive = (
868 functionName: string,
869 session: { note: (note: string) => Effect.Effect<void> },
870 ) =>
871 Effect.gen(function* () {
872 const fn = yield* getFunction(functionName);
873 if (fn?.state === "Active") return fn;
874 if (fn?.state === "Failed") {
875 return yield* new WebFunctionFailed({
876 functionName,
877 resource: "function",
878 reason: fn.stateReason,
879 });
880 }
881 return yield* new WebFunctionNotReady({
882 functionName,
883 resource: "function",
884 state: fn?.state,
885 });
886 }).pipe(
887 Effect.tapError((e) =>
888 e._tag === "WebFunctionNotReady" ? session.note(e.message) : Effect.void,
889 ),
890 Effect.retry({
891 while: (e) => e._tag === "WebFunctionNotReady",
892 schedule: Schedule.spaced("2 seconds"),
893 times: 45,
894 }),
895 );
896
897 const waitForRevisionActive = (
898 functionName: string,
899 revisionId: string,
900 session: { note: (note: string) => Effect.Effect<void> },
901 ) =>
902 Effect.gen(function* () {
903 const revision = yield* getRevision(functionName, revisionId);
904 if (revision?.state === "Active") return revision;
905 if (revision?.state === "Failed") {
906 return yield* new WebFunctionFailed({
907 functionName,
908 resource: `revision ${revisionId}`,
909 reason: [
910 revision.stateReason,
911 ...(revision.errors ?? []).map(
912 (e) => `${e.attribute}: ${e.errorCode} ${e.errorMessage}`,
913 ),
914 ].join("; "),
915 });
916 }
917 return yield* new WebFunctionNotReady({
918 functionName,
919 resource: `revision ${revisionId}`,
920 state: revision?.state,
921 });
922 }).pipe(
923 Effect.tapError((e) =>
924 e._tag === "WebFunctionNotReady" ? session.note(e.message) : Effect.void,
925 ),
926 Effect.retry({
927 while: (e) => e._tag === "WebFunctionNotReady",
928 schedule: Schedule.spaced("2 seconds"),
929 times: 60,
930 }),
931 );
932
933 const waitForFunctionGone = (functionName: string) =>
934 Effect.gen(function* () {
935 const fn = yield* getFunction(functionName);
936 if (fn === undefined) return;
937 return yield* new WebFunctionNotReady({
938 functionName,
939 resource: "function",
940 state: fn.state,
941 });
942 }).pipe(
943 Effect.retry({
944 while: (e) => e._tag === "WebFunctionNotReady",
945 schedule: Schedule.spaced("2 seconds"),
946 times: 45,
947 }),
948 );
949
950 /**
951 * Lambda rejects a just-created execution role until IAM propagates
952 * it; a concurrent mutation of the same function is a conflict.
953 */
954 const retryRolePropagation = <A, E extends { _tag: string }, R>(
955 effect: Effect.Effect<A, E, R>,
956 session: { note: (note: string) => Effect.Effect<void> },
957 functionName: string,
958 ) =>
959 effect.pipe(
960 Effect.tapError((e) =>
961 e._tag === "ExecutionRoleNotAssumable"
962 ? session.note(`Waiting for execution role to propagate: ${functionName}`)
963 : Effect.void,
964 ),
965 Effect.retry({
966 while: (e) => e._tag === "ExecutionRoleNotAssumable" || e._tag === "ConflictException",
967 schedule: Schedule.spaced("3 seconds"),
968 times: 20,
969 }),
970 );
971
972 /** Observed revision matches the desired build and service config. */
973 const revisionMatches = (
974 observed: LambdaWeb.GetWebFunctionRevisionResponse,
975 desired: LambdaWeb.RevisionConfig,
976 ) =>
977 observed.state !== "Failed" &&
978 observed.buildConfig.codeConfig.s3Object.bucket ===
979 desired.buildConfig.codeConfig.s3Object.bucket &&
980 observed.buildConfig.codeConfig.s3Object.key ===
981 desired.buildConfig.codeConfig.s3Object.key &&
982 observed.buildConfig.runtimeConfig.runtime === desired.buildConfig.runtimeConfig.runtime &&
983 (observed.description ?? "") === (desired.description ?? "") &&
984 observed.serviceConfig.executionRoleArn === desired.serviceConfig.executionRoleArn &&
985 (observed.serviceConfig.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS) ===
986 desired.serviceConfig.timeoutSeconds &&
987 (observed.serviceConfig.maxConcurrencyPerEnvironment ?? DEFAULT_MAX_CONCURRENCY) ===
988 desired.serviceConfig.maxConcurrencyPerEnvironment &&
989 (observed.serviceConfig.egressNetworkConnectorArn ?? undefined) ===
990 desired.serviceConfig.egressNetworkConnectorArn &&
991 deepEqual(
992 observed.serviceConfig.environmentVariables ?? {},
993 desired.serviceConfig.environmentVariables ?? {},
994 );
995
996 const toAttributes = (
997 fn: { functionName: string; functionArn: string },
998 endpoint: LambdaWeb.GetWebFunctionEndpointResponse,
999 role: { roleName: string; roleArn: string },
1000 code: WebFunction["Attributes"]["code"],
1001 revisionId: string,
1002 ): WebFunction["Attributes"] => ({
1003 functionName: fn.functionName,
1004 functionArn: fn.functionArn,
1005 endpointName: endpoint.endpointName,
1006 endpointArn: endpoint.endpointArn,
1007 domainName: endpoint.domainName,
1008 url: `https://${endpoint.domainName}`,
1009 authType: endpoint.authType as WebFunctionAuthType,
1010 endpointType: endpoint.endpointType as WebFunctionEndpointType,
1011 revisionId,
1012 revisionWeights: servedRevisions(endpoint),
1013 roleName: role.roleName,
1014 roleArn: role.roleArn,
1015 code,
1016 ...endpointLimits(endpoint),
1017 });
1018
1019 /**
1020 * Tags and Alchemy's execution-role inline policies, as observed.
1021 * `read` and `reconcile` share it so a converged function reads
1022 * unchanged.
1023 */
1024 const observeFunctionExtras = Effect.fn(function* ({
1025 functionArn,
1026 roleName,
1027 policyName,
1028 }: {
1029 functionArn: string;
1030 roleName: string;
1031 policyName: string;
1032 }) {
1033 const readInlinePolicy = (PolicyName: string) =>
1034 iam.getRolePolicy({ RoleName: roleName, PolicyName }).pipe(
1035 Effect.map((policy): unknown => JSON.parse(decodeURIComponent(policy.PolicyDocument))),
1036 Effect.catchTag("NoSuchEntityException", () => Effect.undefined),
1037 );
1038 const [tags, bindingPolicy, guardPolicy] = yield* Effect.all(
1039 [
1040 LambdaWeb.listTags({ resource: functionArn }).pipe(
1041 Effect.map((r) => tagRecord(r.tags)),
1042 Effect.catchTag("ResourceNotFoundException", () =>
1043 Effect.succeed({} as Record<string, string>),
1044 ),
1045 ),
1046 readInlinePolicy(policyName),
1047 readInlinePolicy(LOG_GROUP_GUARD_POLICY),
1048 ],
1049 { concurrency: "unbounded" },
1050 );
1051 return {
1052 tags,
1053 executionRolePolicies: {
1054 ...(bindingPolicy === undefined ? {} : { [policyName]: bindingPolicy }),
1055 ...(guardPolicy === undefined ? {} : { [LOG_GROUP_GUARD_POLICY]: guardPolicy }),
1056 },
1057 };
1058 });
1059
1060 const logGroupNames = (functionName: string) => [
1061 `/aws/lambda/web/${functionName}`,
1062 `/aws/lambda/web/${functionName}.local`,
1063 ];
1064
1065 /**
1066 * Alchemy owns the home-Region log groups: it creates them before the
1067 * first request and denies the execution role `logs:CreateLogGroup`
1068 * on them, so a log flush that lands after `delete` cannot re-create
1069 * a group that was just removed.
1070 */
1071 const syncLogGroups = Effect.fn(function* ({
1072 id,
1073 functionName,
1074 roleName,
1075 }: {
1076 id: string;
1077 functionName: string;
1078 roleName: string;
1079 }) {
1080 const { accountId, region } = yield* AWSEnvironment.current;
1081 const document = JSON.stringify({
1082 Version: "2012-10-17",
1083 Statement: [
1084 {
1085 Effect: "Deny",
1086 Action: "logs:CreateLogGroup",
1087 Resource: logGroupNames(functionName).map(
1088 (name) => `arn:aws:logs:${region}:${accountId}:log-group:${name}:*`,
1089 ),
1090 },
1091 ],
1092 });
1093 const observed = yield* iam
1094 .getRolePolicy({ RoleName: roleName, PolicyName: LOG_GROUP_GUARD_POLICY })
1095 .pipe(
1096 Effect.map((policy) => decodeURIComponent(policy.PolicyDocument)),
1097 Effect.catchTag("NoSuchEntityException", () => Effect.undefined),
1098 );
1099 if (observed !== document) {
1100 yield* iam.putRolePolicy({
1101 RoleName: roleName,
1102 PolicyName: LOG_GROUP_GUARD_POLICY,
1103 PolicyDocument: document,
1104 });
1105 }
1106 const tags = yield* createInternalTags(id);
1107 yield* Effect.forEach(logGroupNames(functionName), (logGroupName) =>
1108 logs
1109 .createLogGroup({ logGroupName, tags })
1110 .pipe(Effect.catchTag("ResourceAlreadyExistsException", () => Effect.void)),
1111 );
1112 });
1113
1114 return {
1115 stables: ["functionArn", "functionName", "roleName"],
1116 diff: Effect.fn(function* ({ id, olds, news: desired, output, oldBindings, newBindings }) {
1117 // Effect-native runtime exports remain unevaluated during
1118 // planning; the bundle hash below represents them.
1119 const news =
1120 typeof desired === "object" && desired !== null && "exports" in desired
1121 ? ({ ...desired, exports: stripEffects(desired.exports) } as typeof desired)
1122 : desired;
1123 if (!isResolved(news)) return;
1124 yield* checkWebFunctionProps(id, news);
1125 // Creating, or adopted without prior props: reconcile converges.
1126 if (!output || !olds) return undefined;
1127 // Generated names are engine-owned; only an explicit functionName
1128 // change replaces.
1129 if ((news.functionName ?? output.functionName) !== output.functionName) {
1130 return { action: "replace" };
1131 }
1132 if ((yield* bundle(id, news)).identityHash !== output.code.hash) {
1133 return { action: "update" };
1134 }
1135 if (!havePropsChanged(olds, news)) {
1136 if (!isResolved(newBindings) || !deepEqual(oldBindings, newBindings)) {
1137 return undefined;
1138 }
1139 return { action: "noop" };
1140 }
1141 }),
1142 read: Effect.fn(function* ({ id, olds, output }) {
1143 const functionName =
1144 output?.functionName ?? (yield* createNames(id, olds?.functionName)).functionName;
1145 const fn = yield* getFunction(functionName);
1146 const names = yield* createNames(id, olds?.functionName);
1147 const endpointName = output?.endpointName ?? olds?.endpointName ?? DEFAULT_ENDPOINT_NAME;
1148 const { accountId, region } = yield* AWSEnvironment.current;
1149 const roleName = output?.roleName ?? names.roleName;
1150 if (fn === undefined) {
1151 // A create that failed after the execution role was made (e.g.
1152 // the function create was rejected) leaves only the role. Report
1153 // it so the engine can re-drive the create or delete the role on
1154 // destroy instead of orphaning it.
1155 const role = yield* iam
1156 .getRole({ RoleName: roleName })
1157 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.undefined));
1158 if (output !== undefined || role === undefined) return undefined;
1159 const attrs = {
1160 functionName,
1161 functionArn: `arn:aws:lambda:${region}:${accountId}:web-function/${functionName}`,
1162 endpointName,
1163 endpointArn: `arn:aws:lambda:${region}:${accountId}:web-function/${functionName}/endpoint/${endpointName}`,
1164 domainName: "",
1165 url: "",
1166 authType: olds?.authType ?? "IamAuth",
1167 endpointType: endpointTypeOf(olds?.regions),
1168 revisionId: "",
1169 revisionWeights: [],
1170 roleName,
1171 roleArn: role.Role.Arn,
1172 code: { hash: "" },
1173 } satisfies WebFunction["Attributes"];
1174 return (yield* hasAlchemyTags(id, role.Role.Tags)) ? attrs : Unowned(attrs);
1175 }
1176 // A missing built-in endpoint reports no address, revision or
1177 // traffic, so drift sees it is gone instead of the last persisted
1178 // values.
1179 const endpoint = yield* getEndpoint(functionName, endpointName);
1180 const extras = yield* observeFunctionExtras({
1181 functionArn: fn.functionArn,
1182 roleName,
1183 policyName: names.policyName,
1184 });
1185 const attrs = {
1186 ...output,
1187 functionName: fn.functionName,
1188 functionArn: fn.functionArn,
1189 endpointName,
1190 endpointArn: endpoint?.endpointArn ?? `${fn.functionArn}/endpoint/${endpointName}`,
1191 domainName: endpoint?.domainName ?? "",
1192 url: endpoint ? `https://${endpoint.domainName}` : "",
1193 authType: (endpoint?.authType ??
1194 output?.authType ??
1195 olds?.authType ??
1196 "IamAuth") as WebFunctionAuthType,
1197 endpointType: (endpoint?.endpointType ??
1198 output?.endpointType ??
1199 endpointTypeOf(olds?.regions)) as WebFunctionEndpointType,
1200 revisionId: endpoint ? latestRevisionId(endpoint, output?.revisionId) : "",
1201 revisionWeights: endpoint ? servedRevisions(endpoint) : [],
1202 roleName,
1203 roleArn: output?.roleArn ?? `arn:aws:iam::${accountId}:role/${roleName}`,
1204 code: output?.code ?? { hash: "" },
1205 ...(endpoint
1206 ? endpointLimits(endpoint)
1207 : { rateLimit: undefined, maxEnvironments: undefined }),
1208 ...extras,
1209 } satisfies WebFunction["Attributes"];
1210 return (yield* hasAlchemyTags(id, extras.tags)) ? attrs : Unowned(attrs);
1211 }),
1212 reconcile: Effect.fn(function* ({ id, news, output, bindings, session }) {
1213 // Values that were Outputs at plan are resolved now.
1214 yield* checkWebFunctionProps(id, news);
1215 const names = yield* createNames(id, news.functionName);
1216 // Prefer deployed identifiers over regenerated ones.
1217 const functionName = output?.functionName ?? names.functionName;
1218 const roleName = output?.roleName ?? names.roleName;
1219
1220 // Execution role + binding grants.
1221 const roleArn = yield* ensureRole(id, roleName);
1222 const { env: bindingEnv, vpcRequests } = yield* syncBindings({
1223 roleName,
1224 policyName: names.policyName,
1225 bindings,
1226 });
1227 const vpc = mergeVpc(news.vpc, vpcRequests);
1228 yield* requireHomeRegion(id, vpc, news.regions);
1229 const egressNetworkConnectorArn = vpc
1230 ? yield* syncEgress({ id, vpc, session })
1231 : undefined;
1232 yield* syncLogGroups({ id, functionName, roleName });
1233
1234 // Code: bundle, then upload to the versioned assets bucket Lambda
1235 // reads revisions from.
1236 const { identityHash, buildArchive } = yield* bundle(id, news);
1237 const { archive, archiveHash } = yield* buildArchive;
1238 const bucket = yield* assets.bucketName;
1239 yield* ensureLambdaWebCodeAccess(bucket);
1240 const key = yield* assets.uploadAsset(`web/${archiveHash}`, archive);
1241
1242 const sourcemap = news.build?.output?.sourcemap ?? true;
1243 const enableSourceMaps =
1244 news.bundle !== false &&
1245 (sourcemap === "inline" ||
1246 ((news.uploadSourceMap ?? true) && (sourcemap === true || sourcemap === "hidden")));
1247 const userEnv = Object.fromEntries(
1248 Object.entries({ ...bindingEnv, ...news.env }).map(([k, v]) => [
1249 k,
1250 typeof v === "string" ? v : JSON.stringify(v),
1251 ]),
1252 );
1253 const nodeOptions = [
1254 userEnv.NODE_OPTIONS,
1255 enableSourceMaps ? "--enable-source-maps" : undefined,
1256 ]
1257 .filter((v): v is string => !!v)
1258 .join(" ");
1259 const desiredRevision: LambdaWeb.RevisionConfig = {
1260 description: news.description,
1261 buildConfig: {
1262 codeConfig: { s3Object: { bucket, key } },
1263 runtimeConfig: { runtime: news.runtime ?? "nodejs24.x" },
1264 },
1265 serviceConfig: {
1266 executionRoleArn: roleArn,
1267 timeoutSeconds: toTimeoutSeconds(news.timeout),
1268 maxConcurrencyPerEnvironment:
1269 news.maxConcurrencyPerEnvironment ?? DEFAULT_MAX_CONCURRENCY,
1270 ...(egressNetworkConnectorArn ? { egressNetworkConnectorArn } : {}),
1271 environmentVariables: {
1272 ...userEnv,
1273 ...(nodeOptions ? { NODE_OPTIONS: nodeOptions } : {}),
1274 ...alchemyEnv,
1275 AWS_LAMBDA_NODEJS_ENTRYPOINT:
1276 news.bundle === false ? mainBasename(news.main) : ENTRY_FILE,
1277 },
1278 },
1279 };
1280
1281 const endpoint: WebFunctionEndpointSpec = {
1282 endpointName: news.endpointName ?? DEFAULT_ENDPOINT_NAME,
1283 authType: news.authType,
1284 regions: news.regions,
1285 maxEnvironments: news.maxEnvironments,
1286 rateLimit: news.rateLimit,
1287 canary: news.canary,
1288 };
1289
1290 // Observe → ensure the function. `CreateWebFunction` creates the
1291 // first revision and the endpoint together; both are re-observed
1292 // and synced below like any existing function.
1293 const internalTags = yield* createInternalTags(id);
1294 const desiredTags = { ...news.tags, ...internalTags };
1295 let created: LambdaWeb.CreateWebFunctionResponse | undefined;
1296 if ((yield* getFunction(functionName)) === undefined) {
1297 created = yield* retryRolePropagation(
1298 LambdaWeb.createWebFunction({
1299 functionName,
1300 revisionConfig: desiredRevision,
1301 endpointConfig: createEndpointConfig(endpoint),
1302 tags: desiredTags,
1303 }),
1304 session,
1305 functionName,
1306 ).pipe(
1307 // Lost a create race: the function exists, converge on it.
1308 Effect.catchTag("ConflictException", () => Effect.undefined),
1309 );
1310 }
1311 const fn = yield* waitForFunctionActive(functionName, session);
1312
1313 // Sync the revision: reuse the one the built-in endpoint, the last
1314 // deploy, or the create points at when it already matches the
1315 // desired config (the endpoint is missing after a rename).
1316 const observedEndpoint = yield* getEndpoint(functionName, endpoint.endpointName);
1317 const candidateIds = [
1318 ...(observedEndpoint?.revisionWeights
1319 .filter((w) => w.weight > 0)
1320 .map((w) => w.revisionId) ?? []),
1321 ...(output?.revisionId ? [output.revisionId] : []),
1322 ...(created?.revision ? [created.revision.revisionId] : []),
1323 ];
1324 let revisionId: string | undefined;
1325 for (const candidate of candidateIds) {
1326 const observed = yield* getRevision(functionName, candidate);
1327 if (observed !== undefined && revisionMatches(observed, desiredRevision)) {
1328 revisionId = candidate;
1329 break;
1330 }
1331 }
1332 if (revisionId === undefined) {
1333 const revision = yield* retryRolePropagation(
1334 LambdaWeb.createWebFunctionRevision({
1335 functionName,
1336 description: desiredRevision.description,
1337 buildConfig: desiredRevision.buildConfig,
1338 serviceConfig: desiredRevision.serviceConfig,
1339 }),
1340 session,
1341 functionName,
1342 );
1343 revisionId = revision.revisionId;
1344 }
1345 yield* waitForRevisionActive(functionName, revisionId, session);
1346
1347 // Sync the built-in endpoint onto the revision. A renamed endpoint is
1348 // a new endpoint: create it, then remove the previous one.
1349 const settled = yield* syncEndpoint({
1350 functionName,
1351 spec: endpoint,
1352 revisionId,
1353 published: output?.revisionId,
1354 session,
1355 });
1356 // Moving off a revision whose egress connector the new one no
1357 // longer uses (e.g. `vpc` removed) may leave it unused.
1358 const stillServed = new Set(servedRevisions(settled).map((w) => w.revisionId));
1359 for (const { revisionId: previous } of observedEndpoint
1360 ? servedRevisions(observedEndpoint)
1361 : []) {
1362 if (stillServed.has(previous)) continue;
1363 const previousConnector = yield* connectorOfRevision(functionName, previous);
1364 if (
1365 previousConnector !== undefined &&
1366 !sameConnector(previousConnector, egressNetworkConnectorArn)
1367 ) {
1368 yield* releaseEgressConnector({
1369 functionName,
1370 connectorArn: previousConnector,
1371 session,
1372 });
1373 }
1374 }
1375 const previousEndpointName = output?.endpointName;
1376 if (
1377 previousEndpointName !== undefined &&
1378 previousEndpointName !== endpoint.endpointName
1379 ) {
1380 yield* deleteEndpoint(functionName, previousEndpointName);
1381 }
1382
1383 // Sync tags against the observed cloud tags.
1384 const observedTags = yield* LambdaWeb.listTags({ resource: fn.functionArn }).pipe(
1385 Effect.map((r) => r.tags ?? {}),
1386 );
1387 const { removed, upsert } = diffTags(
1388 Object.fromEntries(
1389 Object.entries(observedTags).filter(
1390 (entry): entry is [string, string] => entry[1] !== undefined,
1391 ),
1392 ),
1393 desiredTags,
1394 );
1395 if (upsert.length > 0) {
1396 yield* LambdaWeb.tagResource({
1397 resource: fn.functionArn,
1398 tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
1399 });
1400 }
1401 if (removed.length > 0) {
1402 yield* LambdaWeb.untagResource({ resource: fn.functionArn, tagKeys: removed });
1403 }
1404
1405 yield* session.note(`https://${settled.domainName}`);
1406 const extras = yield* observeFunctionExtras({
1407 functionArn: fn.functionArn,
1408 roleName,
1409 policyName: names.policyName,
1410 });
1411 return {
1412 ...toAttributes(fn, settled, { roleName, roleArn }, { hash: identityHash }, revisionId),
1413 ...extras,
1414 tags: desiredTags,
1415 };
1416 }),
1417 delete: Effect.fn(function* ({ id, output, session }) {
1418 // The role may already be gone — every step is idempotent. Grants
1419 // go first; the log-group guard stays until the function is gone.
1420 yield* iam.listRolePolicies({ RoleName: output.roleName }).pipe(
1421 Effect.flatMap((policies) =>
1422 Effect.forEach(
1423 (policies.PolicyNames ?? []).filter((name) => name !== LOG_GROUP_GUARD_POLICY),
1424 (policyName) =>
1425 iam
1426 .deleteRolePolicy({ RoleName: output.roleName, PolicyName: policyName })
1427 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)),
1428 ),
1429 ),
1430 Effect.catchTag("NoSuchEntityException", () => Effect.void),
1431 );
1432 yield* iam.listAttachedRolePolicies({ RoleName: output.roleName }).pipe(
1433 Effect.flatMap((policies) =>
1434 Effect.forEach(policies.AttachedPolicies ?? [], (policy) =>
1435 iam
1436 .detachRolePolicy({ RoleName: output.roleName, PolicyArn: policy.PolicyArn! })
1437 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)),
1438 ),
1439 ),
1440 Effect.catchTag("NoSuchEntityException", () => Effect.void),
1441 );
1442
1443 yield* LambdaWeb.deleteWebFunction({ functionName: output.functionName }).pipe(
1444 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
1445 Effect.retry({
1446 while: (e) => e._tag === "ConflictException",
1447 schedule: Schedule.spaced("2 seconds"),
1448 times: 15,
1449 }),
1450 );
1451 yield* waitForFunctionGone(output.functionName);
1452 // A connector still referenced at delete time (e.g. by an endpoint
1453 // that never moved off it) goes with the function.
1454 yield* deleteEgress(id, session);
1455
1456 yield* iam
1457 .deleteRolePolicy({ RoleName: output.roleName, PolicyName: LOG_GROUP_GUARD_POLICY })
1458 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
1459 yield* iam.deleteRole({ RoleName: output.roleName }).pipe(
1460 Effect.catchTag("NoSuchEntityException", () => Effect.void),
1461 Effect.retry({
1462 while: (error) =>
1463 error._tag === "DeleteConflictException" ||
1464 error._tag === "ConcurrentModificationException",
1465 schedule: Schedule.spaced("2 seconds"),
1466 times: 10,
1467 }),
1468 );
1469
1470 // The role could never create these groups (see `syncLogGroups`),
1471 // so one delete is final.
1472 yield* Effect.forEach(logGroupNames(output.functionName), (logGroupName) =>
1473 logs
1474 .deleteLogGroup({ logGroupName })
1475 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)),
1476 );
1477 }),
1478 tail: ({ output }) => {
1479 const session = Effect.gen(function* () {
1480 const { accountId, region } = yield* AWSEnvironment.current;
1481 const response = yield* logs.startLiveTail({
1482 logGroupIdentifiers: [
1483 `arn:aws:logs:${region}:${accountId}:log-group:${logGroupNames(output.functionName)[0]}`,
1484 ],
1485 });
1486 if (!response.responseStream) {
1487 return Stream.empty as Stream.Stream<LogLine>;
1488 }
1489 return response.responseStream.pipe(
1490 Stream.flatMap((event) =>
1491 "sessionUpdate" in event && event.sessionUpdate
1492 ? Stream.fromIterable(
1493 (event.sessionUpdate.sessionResults ?? []).flatMap((result): LogLine[] =>
1494 result.message
1495 ? [
1496 {
1497 timestamp: new Date(result.timestamp ?? Date.now()),
1498 message: result.message.trimEnd(),
1499 },
1500 ]
1501 : [],
1502 ),
1503 )
1504 : Stream.empty,
1505 ),
1506 );
1507 });
1508 return Stream.unwrap(session).pipe(Stream.retry(Schedule.spaced("1 second")));
1509 },
1510 logs: ({ output, options }: { output: WebFunction["Attributes"]; options: LogsInput }) =>
1511 logs
1512 .filterLogEvents({
1513 logGroupName: logGroupNames(output.functionName)[0],
1514 startTime: options.since?.getTime(),
1515 limit: options.limit ?? 100,
1516 })
1517 .pipe(
1518 Effect.map((response) =>
1519 (response.events ?? []).flatMap((event): LogLine[] =>
1520 event.message
1521 ? [
1522 {
1523 timestamp: new Date(event.timestamp ?? Date.now()),
1524 message: event.message.trimEnd(),
1525 },
1526 ]
1527 : [],
1528 ),
1529 ),
1530 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed([] as LogLine[])),
1531 ),
1532 };
1533 }),
1534 );