The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { createHash } from "node:crypto"; |
| 2 | import * as logs from "@distilled.cloud/aws/cloudwatch-logs"; |
| 3 | import type { Credentials } from "@distilled.cloud/aws/Credentials"; |
| 4 | import * as iam from "@distilled.cloud/aws/iam"; |
| 5 | import type { CreateFunctionRequest } from "@distilled.cloud/aws/lambda"; |
| 6 | import * as Lambda from "@distilled.cloud/aws/lambda"; |
| 7 | import { Region } from "@distilled.cloud/aws/Region"; |
| 8 | import { Unowned, Unresolved, UnresolvedIdentity } from "alchemy/AdoptPolicy"; |
| 9 | import * as Binding from "alchemy/Binding"; |
| 10 | import type * as Bundle from "alchemy/Bundle/Bundle"; |
| 11 | import type { PackageInstall } from "alchemy/Bundle/InstalledPackages"; |
| 12 | import { deepEqual, havePropsChanged, isResolved, stripEffects } from "alchemy/Diff"; |
| 13 | import { isScopeEjected, type HttpEffect } from "alchemy/Http"; |
| 14 | import * as Output from "alchemy/Output"; |
| 15 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 16 | import { Platform, type Main, type PlatformProps } from "alchemy/Platform"; |
| 17 | import type { LogLine, LogsInput } from "alchemy/Provider"; |
| 18 | import * as Provider from "alchemy/Provider"; |
| 19 | import { Resource, type ResourceBinding } from "alchemy/Resource"; |
| 20 | import type { FunctionContext, FunctionListener } from "alchemy/Runtime/Function"; |
| 21 | import { packEnvValue, RuntimeContext, unpackEnvValue } from "alchemy/RuntimeContext"; |
| 22 | import { Stack } from "alchemy/Stack"; |
| 23 | import { Stage } from "alchemy/Stage"; |
| 24 | import { createInternalTags, createTagsList, hasAlchemyTags, hasTags } from "alchemy/Tags"; |
| 25 | import { buildEventTelemetry } from "alchemy/Telemetry"; |
| 26 | import { sha256 } from "alchemy/Util/sha256"; |
| 27 | import { zipCode } from "alchemy/Util/zip"; |
| 28 | import type * as lambda from "aws-lambda"; |
| 29 | import * as Cause from "effect/Cause"; |
| 30 | import * as Context from "effect/Context"; |
| 31 | import * as Data from "effect/Data"; |
| 32 | import * as Duration from "effect/Duration"; |
| 33 | import * as Effect from "effect/Effect"; |
| 34 | import * as Exit from "effect/Exit"; |
| 35 | import type { HttpClient } from "effect/http/HttpClient"; |
| 36 | import * as Layer from "effect/Layer"; |
| 37 | import * as Option from "effect/Option"; |
| 38 | import * as Redacted from "effect/Redacted"; |
| 39 | import * as Schedule from "effect/Schedule"; |
| 40 | import * as Scope from "effect/Scope"; |
| 41 | import * as Stream from "effect/Stream"; |
| 42 | import type * as rolldown from "rolldown"; |
| 43 | import { Assets } from "../Assets.ts"; |
| 44 | import { AWSEnvironment } from "../Environment.ts"; |
| 45 | import * as IAM from "../IAM/index.ts"; |
| 46 | import type { PolicyStatement } from "../IAM/Policy.ts"; |
| 47 | import { syncLogGroupRetention, type LogRetentionConfig } from "../Logs/LogRetention.ts"; |
| 48 | import type { Providers } from "../Providers.ts"; |
| 49 | import { |
| 50 | observeEventInvokeConfig, |
| 51 | syncEventInvokeConfig, |
| 52 | type EventInvokeConfig, |
| 53 | type ObservedEventInvokeConfig, |
| 54 | } from "./EventInvokeConfig.ts"; |
| 55 | import { makeFunctionBundler } from "./FunctionBundle.ts"; |
| 56 | import { composeFunctionDomain, functionDomainUrl, type FunctionDomain } from "./FunctionDomain.ts"; |
| 57 | import { |
| 58 | decodeFunctionImageSource, |
| 59 | type FunctionImageAttributes, |
| 60 | type FunctionImageIdentity, |
| 61 | type FunctionImageSource, |
| 62 | makeFunctionImage, |
| 63 | } from "./FunctionImage.ts"; |
| 64 | import { |
| 65 | isResponseStreaming, |
| 66 | makeFunctionHttpHandler, |
| 67 | RESPONSE_STREAM_ENV, |
| 68 | streamifyHandler, |
| 69 | } from "./HttpServer.ts"; |
| 70 | import { |
| 71 | HandlerContext, |
| 72 | InvocationDeadlineState, |
| 73 | lambdaTimeoutOf, |
| 74 | TIMEOUT_GRACE_ENV, |
| 75 | toDurationMillis, |
| 76 | withInvocationDeadline, |
| 77 | } from "./InvocationDeadline.ts"; |
| 78 | |
| 79 | export class LambdaFunctionInvalidProps extends Data.TaggedError("LambdaFunctionInvalidProps")<{ |
| 80 | readonly message: string; |
| 81 | readonly cause?: unknown; |
| 82 | }> {} |
| 83 | |
| 84 | export type { FunctionImageSource } from "./FunctionImage.ts"; |
| 85 | export { |
| 86 | InvalidFunctionDomain, |
| 87 | type FunctionDomain, |
| 88 | type FunctionDomainConfig, |
| 89 | } from "./FunctionDomain.ts"; |
| 90 | |
| 91 | export const FunctionTypeId = "AWS.Lambda.Function" as const; |
| 92 | export type FunctionTypeId = typeof FunctionTypeId; |
| 93 | |
| 94 | class FunctionUpdatePending extends Data.TaggedError("FunctionUpdatePending")<{ |
| 95 | functionName: string; |
| 96 | state?: string; |
| 97 | stateReason?: string; |
| 98 | lastUpdateStatus?: string; |
| 99 | lastUpdateStatusReason?: string; |
| 100 | }> { |
| 101 | override get message() { |
| 102 | return `Lambda function ${this.functionName} is not ready: state=${this.state ?? "unknown"} (${this.stateReason ?? "no reason"}), update=${this.lastUpdateStatus ?? "unknown"} (${this.lastUpdateStatusReason ?? "no reason"})`; |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | class FunctionUpdateFailed extends Data.TaggedError("FunctionUpdateFailed")<{ |
| 107 | functionName: string; |
| 108 | reason?: string; |
| 109 | /** `LastUpdateStatusReasonCode` (or `StateReasonCode` for a failed create). */ |
| 110 | reasonCode?: string; |
| 111 | }> { |
| 112 | override get message() { |
| 113 | return `Lambda function ${this.functionName} update failed: ${this.reason ?? "unknown reason"}`; |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | export const isFunction = (value: any): value is Function => |
| 118 | typeof value === "object" && |
| 119 | value !== null && |
| 120 | "Type" in value && |
| 121 | value.Type === "AWS.Lambda.Function"; |
| 122 | |
| 123 | export interface FunctionBuildOptions |
| 124 | extends Partial<rolldown.InputOptions>, Bundle.BundleExtraOptions { |
| 125 | /** |
| 126 | * Native or Node-only packages to install into the Lambda artifact with npm, |
| 127 | * targeting Linux and the function's architecture. |
| 128 | * |
| 129 | * @example |
| 130 | * ```typescript |
| 131 | * build: { install: ["sharp"] } |
| 132 | * ``` |
| 133 | * |
| 134 | * @example |
| 135 | * ```typescript |
| 136 | * build: { install: { sharp: "^0.33.5" } } |
| 137 | * ``` |
| 138 | */ |
| 139 | readonly install?: PackageInstall; |
| 140 | /** |
| 141 | * Rolldown output options. The bundle is minified with `keepNames` by |
| 142 | * default; source maps ship with it and Node maps stack traces back to your |
| 143 | * source. Set `minify: false` to ship readable code. |
| 144 | */ |
| 145 | readonly output?: Partial<rolldown.OutputOptions>; |
| 146 | } |
| 147 | |
| 148 | export type FunctionArchitecture = "x86_64" | "arm64"; |
| 149 | |
| 150 | /** |
| 151 | * Overrides for instructions declared by a Lambda container image. Set |
| 152 | * directly on {@link FunctionImageProps.image} alongside the image source; |
| 153 | * omit to use the image's own `CMD` / `ENTRYPOINT` / `WORKDIR`. |
| 154 | */ |
| 155 | export interface FunctionImageConfig { |
| 156 | /** Parameters passed to the image entry point, overriding Dockerfile `CMD`. */ |
| 157 | command?: readonly string[]; |
| 158 | /** Runtime executable, overriding Dockerfile `ENTRYPOINT`. */ |
| 159 | entryPoint?: readonly string[]; |
| 160 | /** Working directory, overriding Dockerfile `WORKDIR`. */ |
| 161 | workingDirectory?: string; |
| 162 | } |
| 163 | |
| 164 | /** |
| 165 | * Reference to an EFS access point: a raw access point ARN or anything |
| 166 | * exposing an `accessPointArn` attribute (e.g. an `AWS.EFS.AccessPoint` |
| 167 | * resource). |
| 168 | */ |
| 169 | export type AccessPointRef = string | { accessPointArn: string }; |
| 170 | |
| 171 | /** |
| 172 | * Reference to a Lambda layer version: a raw layer version ARN or anything |
| 173 | * exposing a `layerVersionArn` attribute (e.g. an `AWS.Lambda.LayerVersion` |
| 174 | * resource). |
| 175 | */ |
| 176 | export type LayerRef = string | { layerVersionArn: string }; |
| 177 | |
| 178 | /** Resolve a {@link LayerRef} to its layer version ARN. */ |
| 179 | export const layerVersionArnOf = (layer: LayerRef): string => |
| 180 | typeof layer === "string" ? layer : layer.layerVersionArn; |
| 181 | |
| 182 | /** |
| 183 | * Resolve an {@link AccessPointRef} (or the legacy raw-`arn` field) on a |
| 184 | * `fileSystemConfigs` entry to the access point ARN. |
| 185 | */ |
| 186 | /** Inline policy denying the execution role `logs:CreateLogGroup` on its own group. */ |
| 187 | const logGroupGuardPolicyName = "AlchemyDenyLogGroupCreate"; |
| 188 | |
| 189 | const accessPointArnOf = (config: { |
| 190 | accessPoint?: AccessPointRef; |
| 191 | arn?: string; |
| 192 | }): string | undefined => |
| 193 | typeof config.accessPoint === "string" |
| 194 | ? config.accessPoint |
| 195 | : typeof (config.accessPoint as { accessPointArn?: unknown } | undefined)?.accessPointArn === |
| 196 | "string" |
| 197 | ? (config.accessPoint as { accessPointArn: string }).accessPointArn |
| 198 | : config.arn; |
| 199 | |
| 200 | export interface FunctionUrlConfig { |
| 201 | /** |
| 202 | * Authentication type for the Lambda function URL. |
| 203 | * `NONE` creates a public endpoint. `AWS_IAM` requires SigV4-signed callers. |
| 204 | * @default "NONE" |
| 205 | */ |
| 206 | authType?: Lambda.FunctionUrlAuthType; |
| 207 | /** |
| 208 | * Cross-origin resource sharing configuration for the function URL. |
| 209 | */ |
| 210 | cors?: Lambda.Cors; |
| 211 | /** |
| 212 | * Invocation mode for the function URL. `RESPONSE_STREAM` streams an |
| 213 | * Effect handler's `HttpServerResponse` body to the client as it is |
| 214 | * produced; `BUFFERED` returns it once complete (up to 6 MB). |
| 215 | * @default "BUFFERED" |
| 216 | */ |
| 217 | invokeMode?: Lambda.InvokeMode; |
| 218 | } |
| 219 | |
| 220 | export interface FunctionCommonProps extends PlatformProps { |
| 221 | /** |
| 222 | * Whether to create a Lambda function URL, or its configuration. |
| 223 | * |
| 224 | * Omitting it creates a **public, unauthenticated** Function URL: the same |
| 225 | * as `functionUrl: true`, which sets `authType: "NONE"` and grants |
| 226 | * `lambda:InvokeFunctionUrl` and `lambda:InvokeFunction` (via the URL) to |
| 227 | * `Principal: "*"`. |
| 228 | * Set `functionUrl: false` for Functions that only consume events, or |
| 229 | * `{ authType: "AWS_IAM" }` to require SigV4-signed requests. |
| 230 | * @default true |
| 231 | */ |
| 232 | functionUrl?: boolean | FunctionUrlConfig; |
| 233 | /** |
| 234 | * Route every invocation through a Lambda alias of this name. |
| 235 | * |
| 236 | * Each deploy publishes a version (Lambda reuses the latest one when the |
| 237 | * code and configuration are unchanged) and points the alias at it. The |
| 238 | * function URL, event-source mappings, invoke permissions, API Gateway |
| 239 | * integrations, the custom `domain`, and the function-level |
| 240 | * `eventInvokeConfig`, and the durable executions a `DurableFunction` or |
| 241 | * `WorkflowFunction` starts all target the alias instead of `$LATEST`, so rolling |
| 242 | * back is a single `UpdateAlias` call to a previous version. Published |
| 243 | * versions are retained. |
| 244 | * |
| 245 | * Adding or removing `alias` moves the function URL to a new address |
| 246 | * (qualified and unqualified URLs differ). |
| 247 | */ |
| 248 | alias?: string; |
| 249 | /** |
| 250 | * Serve the Function on a custom domain. Function URLs cannot take custom |
| 251 | * hostnames, so this composes an API Gateway v2 HTTP API in front of the |
| 252 | * Function (`$default` route, payload 2.0 — the Function URL event shape, |
| 253 | * so an Effect `fetch` handler works unchanged), a regional ACM |
| 254 | * certificate, an API Gateway domain name + API mapping per hostname, and |
| 255 | * the DNS records. The Function's `domainUrl` attribute is |
| 256 | * `https://{name}`. |
| 257 | * |
| 258 | * A string is a hostname in a Route 53 hosted zone. Use the object form |
| 259 | * for aliases, a pinned hosted zone, or another DNS host via `dns` (e.g. |
| 260 | * `Cloudflare.DNS.Adapter()`). |
| 261 | * |
| 262 | * Not composed while the Function runs locally under `alchemy dev` |
| 263 | * (pipe it through `Alchemy.remote()` to serve the domain in dev). |
| 264 | */ |
| 265 | domain?: FunctionDomain; |
| 266 | functionName?: string; |
| 267 | /** |
| 268 | * Instruction set architecture for the Lambda function. |
| 269 | */ |
| 270 | architecture?: FunctionArchitecture; |
| 271 | /** |
| 272 | * Memory allocated to the function, in MB. |
| 273 | * |
| 274 | * @default 128 |
| 275 | */ |
| 276 | memorySize?: number; |
| 277 | env?: Record<string, any>; |
| 278 | /** |
| 279 | * Attach the function to a VPC for private AWS connectivity such as Aurora. |
| 280 | */ |
| 281 | vpc?: { |
| 282 | subnetIds: string[]; |
| 283 | securityGroupIds: string[]; |
| 284 | }; |
| 285 | /** |
| 286 | * EFS file systems to mount into the function's execution environment. |
| 287 | * Each entry mounts an EFS access point — pass the `AWS.EFS.AccessPoint` |
| 288 | * resource itself (or its ARN) — at a local path that must begin with |
| 289 | * `/mnt/`. Requires `vpc`: the function must be attached to a VPC that can |
| 290 | * reach an available EFS mount target for the file system. The execution |
| 291 | * role is automatically granted EFS client access |
| 292 | * (`AmazonElasticFileSystemClientReadWriteAccess`). |
| 293 | * |
| 294 | * Prefer the host-agnostic `AWS.EFS.Mount` binding |
| 295 | * (`yield* AWS.EFS.mount(accessPoint, { path: "/mnt/data" })` inside the |
| 296 | * function body with the `AWS.EFS.MountLive` layer) — it wires the same |
| 297 | * config plus least-privilege IAM through the binding channel and also |
| 298 | * works on ECS. |
| 299 | */ |
| 300 | fileSystemConfigs?: { |
| 301 | /** |
| 302 | * The EFS access point to mount — an `AWS.EFS.AccessPoint` resource or |
| 303 | * its ARN. Exactly one of `accessPoint` or `arn` is required. |
| 304 | */ |
| 305 | accessPoint?: AccessPointRef; |
| 306 | /** |
| 307 | * ARN of the EFS access point to mount |
| 308 | * (e.g. `accessPoint.accessPointArn`). Alias of {@link accessPoint} for |
| 309 | * raw-string configs. |
| 310 | */ |
| 311 | arn?: string; |
| 312 | /** |
| 313 | * Local mount path inside the function. Must begin with `/mnt/` |
| 314 | * (e.g. `/mnt/files`). |
| 315 | */ |
| 316 | localMountPath: string; |
| 317 | }[]; |
| 318 | /** |
| 319 | * Maximum execution time of an invocation. |
| 320 | * |
| 321 | * At the timeout the runtime interrupts the handler, like `runMain` does on |
| 322 | * SIGTERM: `acquireRelease`, `ensuring` and scope finalizers run, every |
| 323 | * open span ends with an `AWS.Lambda.InvocationTimeoutError`. Lambda |
| 324 | * itself is configured with `timeout + timeoutMargin`, rounded up to whole |
| 325 | * seconds, so the cleanup and the telemetry flush run in that margin |
| 326 | * instead of being cut off. The invocation is then held until Lambda's own |
| 327 | * timeout ends it, so Lambda still logs, counts and retries a timeout and |
| 328 | * resets the sandbox, and work that ignored the interruption cannot leak |
| 329 | * into the next invocation. |
| 330 | * |
| 331 | * Functions alchemy's runtime does not run (`image`, `isExternal`, |
| 332 | * `bundle: false`) and durable functions are never interrupted: Lambda is |
| 333 | * configured with the timeout as-is, rounded up to whole seconds. |
| 334 | * |
| 335 | * @default 3 seconds (AWS Lambda default) |
| 336 | */ |
| 337 | timeout?: Duration.Duration; |
| 338 | /** |
| 339 | * Extra time Lambda gives an invocation after {@link timeout} interrupts |
| 340 | * it, for finalizers and the telemetry flush. Lambda's timeout is |
| 341 | * configured as `timeout + timeoutMargin`, rounded up to whole seconds; |
| 342 | * the margin is billed only when an invocation actually runs past its |
| 343 | * timeout. `timeout + timeoutMargin` must fit in Lambda's 900-second |
| 344 | * maximum, and a queue an SQS event source reads needs a |
| 345 | * `visibilityTimeout` of at least that sum (SQS's default is 30 seconds). |
| 346 | * |
| 347 | * If cleanup is still running 500 ms before Lambda's own timeout, the |
| 348 | * runtime ends the invocation's root span, logs a warning and drains the |
| 349 | * exporters, so the trace is exported even if Lambda kills the process. |
| 350 | * |
| 351 | * Set to `Duration.zero` to never interrupt the handler: Lambda kills the |
| 352 | * invocation at {@link timeout} and the runtime only flushes telemetry |
| 353 | * 500 ms before that. |
| 354 | * |
| 355 | * @default 1 second |
| 356 | */ |
| 357 | timeoutMargin?: Duration.Duration; |
| 358 | /** |
| 359 | * Maximum number of concurrent executions reserved for this function. |
| 360 | * Omit to remove the function-level reserved concurrency limit. |
| 361 | */ |
| 362 | reservedConcurrentExecutions?: number; |
| 363 | /** |
| 364 | * AWS X-Ray tracing mode for the function. |
| 365 | * |
| 366 | * `"Active"` samples and records incoming requests as X-Ray traces and |
| 367 | * attaches the `AWSXRayDaemonWriteAccess` managed policy to the execution |
| 368 | * role so the runtime can publish trace segments. `"PassThrough"` only |
| 369 | * forwards an upstream trace header without sampling. |
| 370 | * |
| 371 | * @default "PassThrough" |
| 372 | */ |
| 373 | tracing?: "Active" | "PassThrough"; |
| 374 | /** |
| 375 | * Asynchronous invocation settings (retries, event age, destinations) for |
| 376 | * the unqualified function. Omit to remove any existing config and fall |
| 377 | * back to Lambda's defaults (2 retries, 6-hour max event age, no |
| 378 | * destinations). Use {@link AliasProps.eventInvokeConfig} to scope the |
| 379 | * config to an alias instead. |
| 380 | */ |
| 381 | eventInvokeConfig?: EventInvokeConfig; |
| 382 | /** |
| 383 | * Retention for the function's CloudWatch log group |
| 384 | * (`/aws/lambda/<functionName>`), e.g. `{ retention: "2 weeks" }` or |
| 385 | * `{ retention: "forever" }`. When set, Alchemy creates (or adopts) the |
| 386 | * log group so the policy applies before the first invocation, and |
| 387 | * deletes it with the function. When omitted the log group is left to |
| 388 | * Lambda, which creates it on first invoke with no expiry. |
| 389 | */ |
| 390 | logging?: LogRetentionConfig; |
| 391 | } |
| 392 | |
| 393 | export interface FunctionZipProps extends FunctionCommonProps { |
| 394 | /** |
| 395 | * Entry module for the bundled Lambda function. |
| 396 | */ |
| 397 | main: string; |
| 398 | /** |
| 399 | * Set to `false` to skip bundling and deploy `main`'s directory as-is: |
| 400 | * every file in the directory containing `main` ships in the code |
| 401 | * archive, preserving relative paths. Use for framework outputs that are |
| 402 | * already self-contained deployment units (e.g. nitro's |
| 403 | * `.output/server`, OpenNext's server functions) where re-bundling can |
| 404 | * break `require`s of packaged `node_modules`. Implies external mode: |
| 405 | * `handler` names an export of `main`, and the Lambda handler string is |
| 406 | * derived from `main`'s basename (e.g. `index.mjs` → `index.default`). |
| 407 | * @default true |
| 408 | */ |
| 409 | bundle?: false; |
| 410 | image?: never; |
| 411 | /** |
| 412 | * Name of the export in `main` that Lambda invokes. Only applies to async |
| 413 | * handlers (`main` exports a plain Lambda handler); Effect Functions are |
| 414 | * wrapped in a generated entry and ignore it. |
| 415 | * @default "default" |
| 416 | */ |
| 417 | handler?: string; |
| 418 | // TODO(sam): use a Layer instead so we can manage Effect platform? |
| 419 | runtime?: "nodejs22.x" | "nodejs24.x"; |
| 420 | /** |
| 421 | * Lambda layers to attach — pass an `AWS.Lambda.LayerVersion` resource |
| 422 | * directly, or a raw layer version ARN (e.g. an AWS-managed layer). Layers |
| 423 | * are extracted into `/opt` in the order given. Omit or pass `[]` to detach |
| 424 | * every layer. |
| 425 | */ |
| 426 | layers?: LayerRef[]; |
| 427 | /** |
| 428 | * Bundler configuration for {@link main}: rolldown input options, `output` |
| 429 | * overrides, `install` for native packages, `pure`, and the bundle analyzer. |
| 430 | * Unused code is tree-shaken. `effect`, alchemy, and `@distilled.cloud` |
| 431 | * are marked pure so unused parts prune more aggressively. List extra |
| 432 | * packages with `pure.packages`, or disable with `pure: false`. |
| 433 | */ |
| 434 | build?: FunctionBuildOptions; |
| 435 | uploadSourceMap?: boolean; |
| 436 | exports?: string[]; |
| 437 | /** |
| 438 | * Wire-level `DurableConfig` applied at `CreateFunction`. |
| 439 | * |
| 440 | * @internal Set exclusively by the `AWS.Lambda.DurableFunction` wrapper — |
| 441 | * never set this directly. Durability is a **create-time** property of a |
| 442 | * Lambda function, so a presence change replaces the function (see `diff`). |
| 443 | * The base Function is otherwise durability-agnostic; author durable |
| 444 | * orchestrators with `AWS.Lambda.DurableFunction`. |
| 445 | */ |
| 446 | durableConfig?: Lambda.DurableConfig; |
| 447 | } |
| 448 | |
| 449 | export interface FunctionImageProps extends FunctionCommonProps { |
| 450 | main?: never; |
| 451 | /** |
| 452 | * Instruction set architecture for the Lambda function and its image build. |
| 453 | * `x86_64` builds `linux/amd64`; `arm64` builds `linux/arm64`. |
| 454 | */ |
| 455 | architecture: FunctionArchitecture; |
| 456 | /** |
| 457 | * Deploy an existing private ECR image, or build a Lambda-compatible image |
| 458 | * from a local Docker context. Local builds use a managed private ECR |
| 459 | * repository with content-addressed tags. |
| 460 | */ |
| 461 | image: FunctionImageSource; |
| 462 | handler?: never; |
| 463 | runtime?: never; |
| 464 | layers?: never; |
| 465 | build?: never; |
| 466 | uploadSourceMap?: never; |
| 467 | exports?: never; |
| 468 | // Durability needs a `main` for the orchestrator body — see |
| 469 | // DurableFunctionProps. |
| 470 | durableConfig?: never; |
| 471 | } |
| 472 | |
| 473 | export type FunctionProps = FunctionZipProps | FunctionImageProps; |
| 474 | |
| 475 | const isFunctionImageProps = (props: FunctionProps): props is FunctionImageProps => |
| 476 | props.image !== undefined; |
| 477 | |
| 478 | interface FunctionPackageValidationProps { |
| 479 | image?: unknown; |
| 480 | main?: unknown; |
| 481 | handler?: unknown; |
| 482 | runtime?: unknown; |
| 483 | layers?: unknown; |
| 484 | build?: unknown; |
| 485 | uploadSourceMap?: unknown; |
| 486 | exports?: unknown; |
| 487 | durableConfig?: unknown; |
| 488 | } |
| 489 | |
| 490 | /** |
| 491 | * Validate package-mode exclusivity before any Lambda or ECR mutation. |
| 492 | * @internal |
| 493 | */ |
| 494 | export const validateFunctionPackageProps = Effect.fn("AWS.Lambda.validateFunctionPackageProps")( |
| 495 | function* (id: string, props: FunctionPackageValidationProps) { |
| 496 | if (props.image === undefined) { |
| 497 | if (props.main === undefined) { |
| 498 | return yield* new LambdaFunctionInvalidProps({ |
| 499 | message: `Function(${id}): declare exactly one of main or image`, |
| 500 | }); |
| 501 | } |
| 502 | return; |
| 503 | } |
| 504 | |
| 505 | const incompatible = [ |
| 506 | ["main", props.main], |
| 507 | ["handler", props.handler], |
| 508 | ["runtime", props.runtime], |
| 509 | ["layers", props.layers], |
| 510 | ["build", props.build], |
| 511 | ["uploadSourceMap", props.uploadSourceMap], |
| 512 | ["exports", props.exports], |
| 513 | ["durableConfig", props.durableConfig], |
| 514 | ].flatMap(([name, value]) => (value === undefined ? [] : [name])); |
| 515 | if (incompatible.length > 0) { |
| 516 | return yield* new LambdaFunctionInvalidProps({ |
| 517 | message: `Function(${id}): image functions cannot use ZIP/runtime options: ${incompatible.join(", ")}`, |
| 518 | }); |
| 519 | } |
| 520 | }, |
| 521 | ); |
| 522 | |
| 523 | /** |
| 524 | * The Lambda `ImageConfig` for an image source's overrides; `undefined` when |
| 525 | * the source declares none, so the image's own instructions apply. |
| 526 | */ |
| 527 | const toLambdaImageConfig = ( |
| 528 | config: FunctionImageConfig | undefined, |
| 529 | ): Lambda.ImageConfig | undefined => |
| 530 | config === undefined || |
| 531 | (config.command === undefined && |
| 532 | config.entryPoint === undefined && |
| 533 | config.workingDirectory === undefined) |
| 534 | ? undefined |
| 535 | : { |
| 536 | Command: config.command === undefined ? undefined : [...config.command], |
| 537 | EntryPoint: config.entryPoint === undefined ? undefined : [...config.entryPoint], |
| 538 | WorkingDirectory: config.workingDirectory, |
| 539 | }; |
| 540 | |
| 541 | /** |
| 542 | * `UpdateFunctionConfiguration` preserves old image overrides when the field |
| 543 | * is omitted. An empty object therefore means "clear overrides" on update. |
| 544 | */ |
| 545 | const imageConfigForUpdate = (props: FunctionProps): Lambda.ImageConfig | undefined => |
| 546 | isFunctionImageProps(props) ? (toLambdaImageConfig(props.image) ?? {}) : undefined; |
| 547 | |
| 548 | /** |
| 549 | * Whether alchemy's runtime interrupts the function's invocations at its |
| 550 | * `timeout` (see `withInvocationDeadline`). Images, external handlers and |
| 551 | * prebuilt bundles run the user's own entrypoint; durable invocations are |
| 552 | * replayed from checkpoints and never interrupted. |
| 553 | */ |
| 554 | const interruptsAtTimeout = (props: FunctionProps): boolean => |
| 555 | !isFunctionImageProps(props) && |
| 556 | !props.isExternal && |
| 557 | props.bundle !== false && |
| 558 | props.durableConfig === undefined; |
| 559 | |
| 560 | /** |
| 561 | * The Lambda `Handler` string for a function's props: `<file>.<export>`. |
| 562 | * Bundled functions always emit `index.js`; prebuilt directories |
| 563 | * (`bundle: false`) keep `main`'s own basename. The export half honors |
| 564 | * `handler` only outside Effect mode (see the note at the call site). |
| 565 | */ |
| 566 | const handlerStringOf = (props: FunctionZipProps): string => { |
| 567 | const externalMode = props.isExternal || props.bundle === false; |
| 568 | // `main` may be an unresolved Output during precreate (the stub's mock |
| 569 | // code exports `index.*` anyway); the real Handler is applied at |
| 570 | // reconcile, where props are resolved. |
| 571 | const base = |
| 572 | props.bundle === false && typeof props.main === "string" |
| 573 | ? props.main |
| 574 | .slice(Math.max(props.main.lastIndexOf("/"), props.main.lastIndexOf("\\")) + 1) |
| 575 | .replace(/\.[^.]+$/, "") |
| 576 | : "index"; |
| 577 | return `${base}.${externalMode ? (props.handler ?? "default") : "default"}`; |
| 578 | }; |
| 579 | |
| 580 | /** |
| 581 | * Normalize a {@link FunctionProps.timeout} to whole seconds. |
| 582 | * |
| 583 | * State JSON round-trips flatten a `Duration` to its `toJSON` shape |
| 584 | * (`{_id:"Duration",_tag:"Millis"|"Nanos"|"Infinity",...}`), which is not a |
| 585 | * valid `Duration.Input`. Reconstruct an input that `Duration.toSeconds` |
| 586 | * accepts before delegating. |
| 587 | */ |
| 588 | export const toTimeoutSeconds = (timeout: Duration.Duration | undefined): number | undefined => { |
| 589 | if (timeout === undefined) return undefined; |
| 590 | const json = timeout as { |
| 591 | _id?: unknown; |
| 592 | _tag?: "Millis" | "Nanos" | "Infinity" | "NegativeInfinity"; |
| 593 | millis?: number; |
| 594 | nanos?: string; |
| 595 | }; |
| 596 | const input: Duration.Input = |
| 597 | json._id === "Duration" |
| 598 | ? json._tag === "Millis" |
| 599 | ? json.millis! |
| 600 | : json._tag === "Nanos" |
| 601 | ? BigInt(json.nanos!) |
| 602 | : "Infinity" |
| 603 | : timeout; |
| 604 | const seconds = Duration.toSeconds(input); |
| 605 | return Number.isFinite(seconds) ? Math.max(1, Math.ceil(seconds)) : undefined; |
| 606 | }; |
| 607 | |
| 608 | export interface Function extends Resource< |
| 609 | FunctionTypeId, |
| 610 | FunctionProps, |
| 611 | { |
| 612 | functionArn: string; |
| 613 | functionName: string; |
| 614 | /** |
| 615 | * ARN that invokes the Function: the alias ARN |
| 616 | * (`arn:…:function:name:alias`) when `alias` is set, otherwise the |
| 617 | * unqualified {@link functionArn}. Use {@link qualifiedArnOf} to wire it. |
| 618 | */ |
| 619 | qualifiedArn: string; |
| 620 | /** |
| 621 | * Name of the alias every consumer invokes, when `alias` is set. |
| 622 | */ |
| 623 | aliasName?: string; |
| 624 | /** |
| 625 | * Version the alias points at, when `alias` is set. |
| 626 | */ |
| 627 | version?: string; |
| 628 | functionUrl: string | undefined; |
| 629 | /** |
| 630 | * `https://{domain.name}` when the Function has a custom `domain`. |
| 631 | */ |
| 632 | domainUrl?: string; |
| 633 | roleName: string; |
| 634 | roleArn: string; |
| 635 | code: { |
| 636 | hash: string; |
| 637 | image?: Omit<FunctionImageAttributes, "hash">; |
| 638 | }; |
| 639 | reservedConcurrentExecutions?: number; |
| 640 | /** |
| 641 | * Memory allocated to the function, in MB, as observed on the deployed |
| 642 | * function. Lets `alchemy drift` detect out-of-band changes. |
| 643 | */ |
| 644 | memorySize?: number; |
| 645 | /** |
| 646 | * Timeout of the function, in seconds, as observed on the deployed |
| 647 | * function. Lets `alchemy drift` detect out-of-band changes. |
| 648 | */ |
| 649 | timeoutSeconds?: number; |
| 650 | /** |
| 651 | * Runtime of the function (ZIP packages only), as observed on the |
| 652 | * deployed function. Lets `alchemy drift` detect out-of-band changes. |
| 653 | */ |
| 654 | runtime?: string; |
| 655 | /** |
| 656 | * Handler string of the function (ZIP packages only), as observed on the |
| 657 | * deployed function. Lets `alchemy drift` detect out-of-band changes. |
| 658 | */ |
| 659 | handler?: string; |
| 660 | /** |
| 661 | * Instruction set architecture, as observed on the deployed function. |
| 662 | * Lets `alchemy drift` detect out-of-band changes. |
| 663 | */ |
| 664 | architecture?: string; |
| 665 | /** |
| 666 | * ARNs of the attached layer versions, in order, as observed on the |
| 667 | * deployed function. Lets `alchemy drift` detect out-of-band changes. |
| 668 | */ |
| 669 | layers?: string[]; |
| 670 | /** |
| 671 | * Environment variables of the deployed function, each value replaced by |
| 672 | * a SHA-256 fingerprint so secrets never reach state. Lets |
| 673 | * `alchemy drift` detect out-of-band additions, removals and edits. |
| 674 | */ |
| 675 | environment?: Record<string, string>; |
| 676 | /** |
| 677 | * VPC attachment, as observed on the deployed function. Lets |
| 678 | * `alchemy drift` detect out-of-band changes. |
| 679 | */ |
| 680 | vpcConfig?: { |
| 681 | subnetIds: string[]; |
| 682 | securityGroupIds: string[]; |
| 683 | }; |
| 684 | /** |
| 685 | * EFS mounts, as observed on the deployed function. Lets `alchemy drift` |
| 686 | * detect out-of-band changes. |
| 687 | */ |
| 688 | fileSystemConfigs?: { |
| 689 | arn: string; |
| 690 | localMountPath: string; |
| 691 | }[]; |
| 692 | /** |
| 693 | * X-Ray tracing mode, as observed on the deployed function. Lets |
| 694 | * `alchemy drift` detect out-of-band changes. |
| 695 | */ |
| 696 | tracing?: string; |
| 697 | /** |
| 698 | * SHA-256 of the deployed code package, as reported by Lambda. Lets |
| 699 | * `alchemy drift` detect code replaced out-of-band. |
| 700 | */ |
| 701 | codeSha256?: string; |
| 702 | /** |
| 703 | * Function URL settings, as observed on the deployed URL. Lets |
| 704 | * `alchemy drift` detect out-of-band authentication or CORS changes. |
| 705 | */ |
| 706 | functionUrlConfig?: { |
| 707 | authType?: string; |
| 708 | invokeMode?: string; |
| 709 | cors?: Lambda.Cors; |
| 710 | }; |
| 711 | /** |
| 712 | * Retention of the function's log group in days (`undefined` when logs |
| 713 | * never expire), observed when `logging.retention` is set. Lets |
| 714 | * `alchemy drift` detect out-of-band changes. |
| 715 | */ |
| 716 | logRetentionInDays?: number; |
| 717 | /** |
| 718 | * Policies Alchemy manages on the execution role, as observed: the AWS |
| 719 | * managed policies Alchemy attaches, and the inline policy documents it |
| 720 | * writes (binding statements and the log-group guard). Lets |
| 721 | * `alchemy drift` detect out-of-band detaches and edits. |
| 722 | */ |
| 723 | executionRole?: { |
| 724 | managedPolicyArns: string[]; |
| 725 | inlinePolicies: Record<string, unknown>; |
| 726 | }; |
| 727 | /** |
| 728 | * Asynchronous invocation config (retries, maximum event age, |
| 729 | * destinations) of the function, or of its alias when `alias` is set, |
| 730 | * as observed. Lets `alchemy drift` detect out-of-band changes. |
| 731 | */ |
| 732 | eventInvokeConfig?: ObservedEventInvokeConfig; |
| 733 | /** |
| 734 | * Durable execution settings (execution timeout and history retention), |
| 735 | * as observed on durable functions. Lets `alchemy drift` detect |
| 736 | * out-of-band changes. |
| 737 | */ |
| 738 | durableConfig?: { |
| 739 | executionTimeout?: number; |
| 740 | retentionPeriodInDays?: number; |
| 741 | }; |
| 742 | }, |
| 743 | { |
| 744 | env?: Record<string, any>; |
| 745 | policyStatements?: PolicyStatement[]; |
| 746 | /** |
| 747 | * VPC attachment requested by a binding (e.g. `RDS.Connect` with |
| 748 | * `subnetIds`/`securityGroupIds`). Merged (set-union) with the |
| 749 | * Function's own `vpc` prop and any other bindings' requests — both |
| 750 | * paths converge on the same underlying Lambda VPC config. |
| 751 | */ |
| 752 | vpc?: { |
| 753 | subnetIds: string[]; |
| 754 | securityGroupIds: string[]; |
| 755 | }; |
| 756 | /** |
| 757 | * EFS mounts requested through the binding channel (e.g. `EFS.Mount`). |
| 758 | * Merged (deduped by `localMountPath`) with the Function's own |
| 759 | * `fileSystemConfigs` prop. |
| 760 | */ |
| 761 | fileSystemConfigs?: { |
| 762 | /** ARN of the EFS access point to mount. */ |
| 763 | arn: string; |
| 764 | /** Local mount path inside the function (must begin with `/mnt/`). */ |
| 765 | localMountPath: string; |
| 766 | }[]; |
| 767 | }, |
| 768 | Providers |
| 769 | > {} |
| 770 | |
| 771 | /** |
| 772 | * Lambda refused to publish a version or create the alias for a Function |
| 773 | * with `alias`. Published versions are retained, so they count toward the |
| 774 | * account's code-storage quota until you delete the ones no alias serves. |
| 775 | */ |
| 776 | export class FunctionAliasPublishFailed extends Data.TaggedError("FunctionAliasPublishFailed")<{ |
| 777 | functionName: string; |
| 778 | alias: string; |
| 779 | reason: "CodeStorageExceeded" | "VersionLimitExceeded" | "AliasLimitExceeded"; |
| 780 | message: string; |
| 781 | }> {} |
| 782 | |
| 783 | /** An event source was used inside a Lambda Web Function. */ |
| 784 | export class EventSourceRequiresFunction extends Data.TaggedError("EventSourceRequiresFunction")<{ |
| 785 | eventSource: string; |
| 786 | message: string; |
| 787 | }> {} |
| 788 | |
| 789 | /** |
| 790 | * The `AWS.Lambda.Function` an event source attaches to. A Lambda Web |
| 791 | * Function only receives HTTP and can't be an event source target, so name |
| 792 | * the problem there instead of failing with a missing-service error (the |
| 793 | * typed API already rejects it; this covers untyped JavaScript). |
| 794 | */ |
| 795 | export const eventSourceHost = (eventSource: string) => |
| 796 | Effect.flatMap(Binding.Host, (host) => |
| 797 | host?.Type === "AWS.Lambda.WebFunction" |
| 798 | ? Effect.die( |
| 799 | new EventSourceRequiresFunction({ |
| 800 | eventSource, |
| 801 | message: `${eventSource} needs an AWS.Lambda.Function, but "${host.LogicalId}" is an AWS.Lambda.WebFunction, which only receives HTTP. Consume the event source from an AWS.Lambda.Function instead.`, |
| 802 | }), |
| 803 | ) |
| 804 | : Function, |
| 805 | ); |
| 806 | |
| 807 | export { qualifiedArnOf, qualifiedNameOf } from "./QualifiedArn.ts"; |
| 808 | |
| 809 | export type FunctionServices = |
| 810 | | Credentials |
| 811 | | Region |
| 812 | | AWSEnvironment |
| 813 | // The host itself, provided to the implementation at runtime (like Cloudflare's Worker). |
| 814 | | Function; |
| 815 | |
| 816 | export type FunctionShape = Main<FunctionServices>; |
| 817 | |
| 818 | export interface NormalizedFunctionUrlConfig { |
| 819 | authType: Lambda.FunctionUrlAuthType; |
| 820 | cors?: Lambda.Cors; |
| 821 | invokeMode: Lambda.InvokeMode; |
| 822 | } |
| 823 | |
| 824 | export const normalizeFunctionUrl = ( |
| 825 | url: FunctionProps["functionUrl"] = true, |
| 826 | ): NormalizedFunctionUrlConfig | undefined => { |
| 827 | if (url === false) { |
| 828 | return undefined; |
| 829 | } |
| 830 | if (url === true || url === undefined) { |
| 831 | return { |
| 832 | authType: "NONE", |
| 833 | invokeMode: "BUFFERED", |
| 834 | }; |
| 835 | } |
| 836 | return { |
| 837 | authType: url.authType ?? "NONE", |
| 838 | cors: url.cors, |
| 839 | invokeMode: url.invokeMode ?? "BUFFERED", |
| 840 | }; |
| 841 | }; |
| 842 | |
| 843 | /** |
| 844 | * An AWS Lambda host resource that combines code bundling, IAM role |
| 845 | * provisioning, and runtime binding collection. |
| 846 | * |
| 847 | * `Function` is the canonical runtime host for AWS. It can either bundle a |
| 848 | * TypeScript entry module into a zip artifact or build a user-authored |
| 849 | * Dockerfile into a Lambda container image. In both modes Alchemy creates the |
| 850 | * execution role and applies bindings; image mode additionally owns the |
| 851 | * private ECR repository and Lambda pull policy. |
| 852 | * |
| 853 | * Zip-packaged functions can be defined in two ways: |
| 854 | * |
| 855 | * - **Async** — plain handler export, no Effect runtime in the bundle. |
| 856 | * - **Effect** — Effect implementation with typed bindings and event sources. |
| 857 | * |
| 858 | * See [Effect handlers vs async handlers](/infrastructure-as-effects/runtime#effect-handlers-vs-async-handlers) |
| 859 | * for plain handler patterns, or the |
| 860 | * [Lambda guide](/aws/compute/lambda) |
| 861 | * for the full Effect-based approach with bindings, event sources, and sinks. |
| 862 | * |
| 863 | * :::caution[Request finalizers block the response — there is no `waitUntil` on Lambda] |
| 864 | * `Effect.addFinalizer` in a handler runs **before the response is |
| 865 | * returned**: a buffered invocation's response is not released until the |
| 866 | * Invoke phase completes, and no deferral scheme is reliable (dangling |
| 867 | * promises are dropped on crash/timeout resets and their sockets rarely |
| 868 | * survive the freeze — silent data loss). Keep request finalizers cheap |
| 869 | * (closing a pool is milliseconds), and write anything that must not be |
| 870 | * lost durably — a queue, a table — inside the handler itself. Init-level |
| 871 | * finalizers instead run in the 500 ms `SIGTERM` window at sandbox |
| 872 | * shutdown, which the generated entry obtains by registering an internal |
| 873 | * extension. See |
| 874 | * [Sandbox scope vs invocation scope](/aws/compute/lambda#sandbox-scope-vs-invocation-scope). |
| 875 | * ::: |
| 876 | * ### Async Functions |
| 877 | * Point `main` at a file that exports a standard Lambda handler. No |
| 878 | * Effect runtime is included in the bundle. Useful when migrating |
| 879 | * existing Lambda functions or when you don't need Effect. |
| 880 | * |
| 881 | * **Example:** Defining an async Lambda in your stack |
| 882 | * ```typescript |
| 883 | * // alchemy.run.ts |
| 884 | * import * as AWS from "@alchemy.run/aws"; |
| 885 | * |
| 886 | * const func = yield* AWS.Lambda.Function("ApiFunction", { |
| 887 | * main: "./src/handler.ts", |
| 888 | * functionUrl: true, |
| 889 | * }); |
| 890 | * ``` |
| 891 | * |
| 892 | * **Example:** Function using ARM64 |
| 893 | * ```typescript |
| 894 | * const func = yield* AWS.Lambda.Function("ArmFunction", { |
| 895 | * main: "./src/handler.ts", |
| 896 | * architecture: "arm64", |
| 897 | * }); |
| 898 | * ``` |
| 899 | * |
| 900 | * **Example:** Function with a native package (Sharp) |
| 901 | * ```typescript |
| 902 | * const func = yield* AWS.Lambda.Function("ImageProcessor", { |
| 903 | * main: "./src/handler.ts", |
| 904 | * architecture: "arm64", |
| 905 | * build: { |
| 906 | * install: ["sharp"], |
| 907 | * }, |
| 908 | * }); |
| 909 | * ``` |
| 910 | * |
| 911 | * **Example:** Writing the async handler |
| 912 | * ```typescript |
| 913 | * // src/handler.ts |
| 914 | * export default async (event: any) => { |
| 915 | * return { |
| 916 | * statusCode: 200, |
| 917 | * body: JSON.stringify({ message: "Hello from Lambda!" }), |
| 918 | * }; |
| 919 | * }; |
| 920 | * ``` |
| 921 | * |
| 922 | * **Example:** Invoking a named export |
| 923 | * ```typescript |
| 924 | * // src/handler.ts exports `handler` instead of a default export |
| 925 | * const func = yield* AWS.Lambda.Function("ApiFunction", { |
| 926 | * main: "./src/handler.ts", |
| 927 | * handler: "handler", |
| 928 | * }); |
| 929 | * ``` |
| 930 | * |
| 931 | * ### Container Image Functions |
| 932 | * Set `image` instead of `main` to deploy an existing private ECR image or to |
| 933 | * build and publish a local Docker context. Image sources must be literal |
| 934 | * because Lambda's pre-create phase needs the deployable image before normal |
| 935 | * Output resolution. |
| 936 | * |
| 937 | * #### Existing ECR image with runtime overrides |
| 938 | * ```typescript |
| 939 | * const func = yield* AWS.Lambda.Function("Worker", { |
| 940 | * image: { |
| 941 | * uri: "123456789012.dkr.ecr.us-east-1.amazonaws.com/worker@sha256:...", |
| 942 | * command: ["app.handler"], |
| 943 | * entryPoint: ["/lambda-entrypoint.sh"], |
| 944 | * workingDirectory: "/var/task", |
| 945 | * }, |
| 946 | * architecture: "x86_64", |
| 947 | * }); |
| 948 | * ``` |
| 949 | * |
| 950 | * Tagged URIs are resolved through ECR on each plan. If a tag is repointed to |
| 951 | * a new digest, Alchemy updates the Lambda function even though the URI string |
| 952 | * is unchanged. External repositories are never modified or deleted. |
| 953 | * |
| 954 | * #### Build a Lambda container image |
| 955 | * ```typescript |
| 956 | * const func = yield* AWS.Lambda.Function("JavaFunction", { |
| 957 | * image: { |
| 958 | * context: "./lambda", |
| 959 | * dockerfile: "Dockerfile", |
| 960 | * buildArgs: { |
| 961 | * APP_ENV: "production", |
| 962 | * }, |
| 963 | * }, |
| 964 | * architecture: "arm64", |
| 965 | * functionUrl: false, |
| 966 | * }); |
| 967 | * ``` |
| 968 | * |
| 969 | * The Dockerfile owns the runtime and handler. Alchemy does not generate a |
| 970 | * Node.js adapter or otherwise impose a language. For example, |
| 971 | * `./lambda/Dockerfile` can use AWS's Java base image: |
| 972 | * |
| 973 | * ```dockerfile |
| 974 | * FROM public.ecr.aws/lambda/java:21 |
| 975 | * COPY target/function.jar ${LAMBDA_TASK_ROOT}/lib/ |
| 976 | * CMD ["com.example.Handler::handleRequest"] |
| 977 | * ``` |
| 978 | * |
| 979 | * ### Effect Functions |
| 980 | * Pass the Effect implementation as the third argument. Bindings |
| 981 | * attach IAM permissions and environment variables at deploy time, |
| 982 | * while the runtime execution context collects listeners and exports. |
| 983 | * |
| 984 | * **Example:** Effect Function with HTTP handler |
| 985 | * ```typescript |
| 986 | * export default class ApiFunction extends AWS.Lambda.Function<ApiFunction>()( |
| 987 | * "ApiFunction", |
| 988 | * { main: import.meta.url, functionUrl: true }, |
| 989 | * Effect.gen(function* () { |
| 990 | * // init: bind resources |
| 991 | * const getItem = yield* AWS.DynamoDB.GetItem(table); |
| 992 | * |
| 993 | * return { |
| 994 | * // runtime: use them |
| 995 | * fetch: Effect.gen(function* () { |
| 996 | * const request = yield* HttpServerRequest; |
| 997 | * const url = new URL(request.url); |
| 998 | * const id = url.searchParams.get("id"); |
| 999 | * const result = yield* getItem({ Key: { pk: { S: id! } } }); |
| 1000 | * return yield* HttpServerResponse.json(result.Item); |
| 1001 | * }), |
| 1002 | * }; |
| 1003 | * }), |
| 1004 | * ) {} |
| 1005 | * ``` |
| 1006 | * |
| 1007 | * ### Function URL access |
| 1008 | * Every Function gets a public, unauthenticated Function URL unless you |
| 1009 | * opt out. `functionUrl` has three access choices: `false` (no URL), |
| 1010 | * `true` (public, the default), and `{ authType: "AWS_IAM" }` (signed |
| 1011 | * requests only). |
| 1012 | * |
| 1013 | * **Example:** Public Function URL |
| 1014 | * ```typescript |
| 1015 | * const func = yield* AWS.Lambda.Function("ApiFunction", { |
| 1016 | * main: "./src/handler.ts", |
| 1017 | * functionUrl: true, |
| 1018 | * }); |
| 1019 | * ``` |
| 1020 | * |
| 1021 | * **Example:** Event consumer without a Function URL |
| 1022 | * ```typescript |
| 1023 | * const func = yield* AWS.Lambda.Function("JobsWorker", { |
| 1024 | * main: "./src/worker.ts", |
| 1025 | * functionUrl: false, |
| 1026 | * }); |
| 1027 | * ``` |
| 1028 | * |
| 1029 | * **Example:** Function URL with IAM auth |
| 1030 | * ```typescript |
| 1031 | * const func = yield* AWS.Lambda.Function("ApiFunction", { |
| 1032 | * main: "./src/handler.ts", |
| 1033 | * functionUrl: { |
| 1034 | * authType: "AWS_IAM", |
| 1035 | * }, |
| 1036 | * }); |
| 1037 | * ``` |
| 1038 | * |
| 1039 | * ### Streaming responses |
| 1040 | * Set the Function URL's `invokeMode` to `"RESPONSE_STREAM"` and a streamed |
| 1041 | * `HttpServerResponse` reaches the client chunk by chunk instead of being |
| 1042 | * buffered. Use it for server-sent events, LLM tokens, progressive HTML, and |
| 1043 | * responses over the 6 MB buffered limit (streams go up to 20 MB). |
| 1044 | * |
| 1045 | * **Example:** Server-sent events |
| 1046 | * ```typescript |
| 1047 | * // src/events.ts |
| 1048 | * import * as AWS from "@alchemy.run/aws"; |
| 1049 | * import * as Effect from "effect/Effect"; |
| 1050 | * import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 1051 | * import * as Stream from "effect/Stream"; |
| 1052 | * |
| 1053 | * export default class Events extends AWS.Lambda.Function<Events>()( |
| 1054 | * "Events", |
| 1055 | * { main: import.meta.url, functionUrl: { invokeMode: "RESPONSE_STREAM" } }, |
| 1056 | * Effect.gen(function* () { |
| 1057 | * return { |
| 1058 | * fetch: Effect.succeed( |
| 1059 | * HttpServerResponse.stream( |
| 1060 | * Stream.make("data: one\n\n", "data: two\n\n").pipe( |
| 1061 | * Stream.tap(() => Effect.sleep("1 second")), |
| 1062 | * Stream.encodeText, |
| 1063 | * ), |
| 1064 | * { contentType: "text/event-stream" }, |
| 1065 | * ), |
| 1066 | * ), |
| 1067 | * }; |
| 1068 | * }), |
| 1069 | * ) {} |
| 1070 | * ``` |
| 1071 | * |
| 1072 | * ### Configuration |
| 1073 | * **Example:** Function in a VPC |
| 1074 | * ```typescript |
| 1075 | * const func = yield* AWS.Lambda.Function("VpcFunction", { |
| 1076 | * main: "./src/handler.ts", |
| 1077 | * vpc: { |
| 1078 | * subnetIds: ["subnet-abc123", "subnet-def456"], |
| 1079 | * securityGroupIds: ["sg-xyz789"], |
| 1080 | * }, |
| 1081 | * }); |
| 1082 | * ``` |
| 1083 | * |
| 1084 | * **Example:** Async invocation retries and failure destination |
| 1085 | * ```typescript |
| 1086 | * const func = yield* AWS.Lambda.Function("AsyncFunction", { |
| 1087 | * main: "./src/handler.ts", |
| 1088 | * eventInvokeConfig: { |
| 1089 | * maximumRetryAttempts: 0, |
| 1090 | * maximumEventAge: "1 minute", |
| 1091 | * destinationConfig: { |
| 1092 | * OnFailure: { |
| 1093 | * Destination: queue.queueArn, |
| 1094 | * }, |
| 1095 | * }, |
| 1096 | * }, |
| 1097 | * }); |
| 1098 | * ``` |
| 1099 | * |
| 1100 | * ### Custom Domains |
| 1101 | * Function URLs cannot serve a custom hostname, so `domain` puts an API |
| 1102 | * Gateway v2 HTTP API in front of the Function (payload 2.0 — the same |
| 1103 | * event shape as a Function URL, so a `fetch` handler works unchanged), |
| 1104 | * with a regional ACM certificate, an API Gateway domain name per |
| 1105 | * hostname, and the DNS records. `domainUrl` is `https://{domain.name}`. |
| 1106 | * |
| 1107 | * **Example:** Domain in Route 53 (default) |
| 1108 | * ```typescript |
| 1109 | * const func = yield* AWS.Lambda.Function("Api", { |
| 1110 | * main: "./src/handler.ts", |
| 1111 | * domain: "api.example.com", |
| 1112 | * }); |
| 1113 | * // func.domainUrl -> "https://api.example.com" |
| 1114 | * ``` |
| 1115 | * |
| 1116 | * **Example:** Aliases and a pinned hosted zone |
| 1117 | * ```typescript |
| 1118 | * const func = yield* AWS.Lambda.Function("Api", { |
| 1119 | * main: "./src/handler.ts", |
| 1120 | * domain: { |
| 1121 | * name: "api.example.com", |
| 1122 | * aliases: ["www.api.example.com"], |
| 1123 | * hostedZoneId: "Z1234567890", |
| 1124 | * }, |
| 1125 | * }); |
| 1126 | * ``` |
| 1127 | * |
| 1128 | * **Example:** Domain whose DNS lives in Cloudflare |
| 1129 | * The certificate is validated and each hostname CNAMEd through Cloudflare; |
| 1130 | * the stack's providers must include `Cloudflare.providers()`. |
| 1131 | * ```typescript |
| 1132 | * import * as Cloudflare from "alchemy/Cloudflare"; |
| 1133 | * |
| 1134 | * const func = yield* AWS.Lambda.Function("Api", { |
| 1135 | * main: "./src/handler.ts", |
| 1136 | * domain: { |
| 1137 | * name: "api.example.com", |
| 1138 | * dns: Cloudflare.DNS.Adapter({ zone: "example.com" }), |
| 1139 | * }, |
| 1140 | * }); |
| 1141 | * ``` |
| 1142 | * |
| 1143 | * ### Bundling & Tree-shaking |
| 1144 | * `main` is bundled with rolldown at deploy time. Unused code is |
| 1145 | * tree-shaken. `effect`, alchemy, and `@distilled.cloud` are marked |
| 1146 | * pure so unused parts prune more aggressively. Your app is not |
| 1147 | * marked pure. |
| 1148 | * |
| 1149 | * **Example:** Mark additional packages as pure |
| 1150 | * Only list packages with no top-level side effects. |
| 1151 | * ```typescript |
| 1152 | * const func = yield* AWS.Lambda.Function("ApiFunction", { |
| 1153 | * main: "./src/handler.ts", |
| 1154 | * build: { |
| 1155 | * pure: { packages: ["my-lib", "@my-scope/*"] }, |
| 1156 | * }, |
| 1157 | * }); |
| 1158 | * ``` |
| 1159 | * |
| 1160 | * **Example:** Turn it off |
| 1161 | * ```typescript |
| 1162 | * const func = yield* AWS.Lambda.Function("ApiFunction", { |
| 1163 | * main: "./src/handler.ts", |
| 1164 | * build: { pure: false }, |
| 1165 | * }); |
| 1166 | * ``` |
| 1167 | * |
| 1168 | * ### EFS File Systems |
| 1169 | * Mount an EFS access point into the function's `/mnt/…` file system. The |
| 1170 | * function must be attached to a VPC that can reach an EFS mount target for |
| 1171 | * the file system. |
| 1172 | * |
| 1173 | * **Example:** Mount an EFS access point via props |
| 1174 | * ```typescript |
| 1175 | * const accessPoint = yield* AWS.EFS.AccessPoint("FilesAccess", { |
| 1176 | * fileSystemId: fileSystem.fileSystemId, |
| 1177 | * posixUser: { uid: 1000, gid: 1000 }, |
| 1178 | * }); |
| 1179 | * |
| 1180 | * const func = yield* AWS.Lambda.Function("FilesFunction", { |
| 1181 | * main: "./src/handler.ts", |
| 1182 | * vpc: { subnetIds, securityGroupIds }, |
| 1183 | * fileSystemConfigs: [ |
| 1184 | * // pass the AccessPoint resource itself (or its ARN via `arn`) |
| 1185 | * { accessPoint, localMountPath: "/mnt/files" }, |
| 1186 | * ], |
| 1187 | * }); |
| 1188 | * ``` |
| 1189 | * |
| 1190 | * **Example:** Mount via the host-agnostic EFS.mount binding |
| 1191 | * `EFS.mount` wires the same mount config plus least-privilege IAM through |
| 1192 | * the binding channel and works on both Lambda and ECS hosts. |
| 1193 | * ```typescript |
| 1194 | * export default class FilesFunction extends AWS.Lambda.Function<FilesFunction>()( |
| 1195 | * "FilesFunction", |
| 1196 | * { main: import.meta.url, vpc: { subnetIds, securityGroupIds } }, |
| 1197 | * Effect.gen(function* () { |
| 1198 | * const files = yield* AWS.EFS.mount(accessPoint, { path: "/mnt/files" }); |
| 1199 | * return Effect.fn(function* (event: unknown) { |
| 1200 | * return { mountedAt: files.path }; |
| 1201 | * }); |
| 1202 | * }).pipe(Effect.provide(AWS.EFS.MountLive)), |
| 1203 | * ) {} |
| 1204 | * ``` |
| 1205 | * |
| 1206 | * ### S3 Bindings |
| 1207 | * Bind S3 operations in the init phase to give the function IAM |
| 1208 | * permissions and inject the bucket name as an environment variable. |
| 1209 | * |
| 1210 | * **Example:** Read and write S3 objects |
| 1211 | * ```typescript |
| 1212 | * // init |
| 1213 | * const getObject = yield* S3.GetObject(bucket); |
| 1214 | * const putObject = yield* S3.PutObject(bucket); |
| 1215 | * |
| 1216 | * return { |
| 1217 | * fetch: Effect.gen(function* () { |
| 1218 | * // runtime |
| 1219 | * yield* putObject({ Key: "hello.txt", Body: "Hello!" }); |
| 1220 | * const obj = yield* getObject({ Key: "hello.txt" }); |
| 1221 | * return HttpServerResponse.text("OK"); |
| 1222 | * }), |
| 1223 | * }; |
| 1224 | * ``` |
| 1225 | * |
| 1226 | * ### DynamoDB Bindings |
| 1227 | * Bind DynamoDB operations in the init phase to grant table-scoped |
| 1228 | * IAM permissions. |
| 1229 | * |
| 1230 | * **Example:** Get and put items |
| 1231 | * ```typescript |
| 1232 | * // init |
| 1233 | * const getItem = yield* AWS.DynamoDB.GetItem(table); |
| 1234 | * const putItem = yield* AWS.DynamoDB.PutItem(table); |
| 1235 | * |
| 1236 | * return { |
| 1237 | * fetch: Effect.gen(function* () { |
| 1238 | * // runtime |
| 1239 | * yield* putItem({ Item: { pk: { S: "user#1" }, name: { S: "Alice" } } }); |
| 1240 | * const result = yield* getItem({ Key: { pk: { S: "user#1" } } }); |
| 1241 | * return yield* HttpServerResponse.json(result.Item); |
| 1242 | * }), |
| 1243 | * }; |
| 1244 | * ``` |
| 1245 | * |
| 1246 | * ### SQS Bindings |
| 1247 | * Bind SQS operations in the init phase to send messages to a queue. |
| 1248 | * |
| 1249 | * **Example:** Send a message |
| 1250 | * ```typescript |
| 1251 | * // init |
| 1252 | * const sendMessage = yield* SQS.SendMessage(queue); |
| 1253 | * |
| 1254 | * return { |
| 1255 | * fetch: Effect.gen(function* () { |
| 1256 | * // runtime |
| 1257 | * yield* sendMessage({ |
| 1258 | * MessageBody: JSON.stringify({ orderId: "123" }), |
| 1259 | * }); |
| 1260 | * return HttpServerResponse.text("Queued"); |
| 1261 | * }), |
| 1262 | * }; |
| 1263 | * ``` |
| 1264 | * |
| 1265 | * ### SNS Bindings |
| 1266 | * Bind SNS operations in the init phase to publish messages to a |
| 1267 | * topic. |
| 1268 | * |
| 1269 | * **Example:** Publish a notification |
| 1270 | * ```typescript |
| 1271 | * // init |
| 1272 | * const publish = yield* AWS.SNS.Publish(topic); |
| 1273 | * |
| 1274 | * return { |
| 1275 | * fetch: Effect.gen(function* () { |
| 1276 | * // runtime |
| 1277 | * yield* publish({ |
| 1278 | * Message: JSON.stringify({ event: "order.created" }), |
| 1279 | * Subject: "OrderCreated", |
| 1280 | * }); |
| 1281 | * return HttpServerResponse.text("Published"); |
| 1282 | * }), |
| 1283 | * }; |
| 1284 | * ``` |
| 1285 | * |
| 1286 | * ### Kinesis Bindings |
| 1287 | * Bind Kinesis operations in the init phase to put records into a |
| 1288 | * stream. |
| 1289 | * |
| 1290 | * **Example:** Put a record |
| 1291 | * ```typescript |
| 1292 | * // init |
| 1293 | * const putRecord = yield* AWS.Kinesis.PutRecord(stream); |
| 1294 | * |
| 1295 | * return { |
| 1296 | * fetch: Effect.gen(function* () { |
| 1297 | * // runtime |
| 1298 | * yield* putRecord({ |
| 1299 | * PartitionKey: "order-123", |
| 1300 | * Data: new TextEncoder().encode(JSON.stringify({ orderId: "123" })), |
| 1301 | * }); |
| 1302 | * return HttpServerResponse.text("Sent"); |
| 1303 | * }), |
| 1304 | * }; |
| 1305 | * ``` |
| 1306 | * |
| 1307 | * ### GCP Bindings |
| 1308 | * A GCP binding reaches Google Cloud through workload identity federation: |
| 1309 | * the function's role may impersonate a service account that holds the |
| 1310 | * binding's roles, so no service account key is created. A new grant can |
| 1311 | * take a few minutes to start working. |
| 1312 | * |
| 1313 | * **Example:** Publish to a Pub/Sub topic |
| 1314 | * ```typescript |
| 1315 | * // init |
| 1316 | * const publish = yield* GCP.PubSub.Publish(topic); |
| 1317 | * |
| 1318 | * return { |
| 1319 | * fetch: Effect.gen(function* () { |
| 1320 | * // runtime |
| 1321 | * yield* publish({ body: { messages: [{ data: btoa("hello") }] } }); |
| 1322 | * return HttpServerResponse.text("Published"); |
| 1323 | * }), |
| 1324 | * }; |
| 1325 | * ``` |
| 1326 | * |
| 1327 | * ### Event Sources |
| 1328 | * Lambda functions can be triggered by event sources like SQS queues, |
| 1329 | * DynamoDB streams, S3 notifications, SNS topics, and Kinesis streams. |
| 1330 | * |
| 1331 | * **Example:** Process SQS messages |
| 1332 | * ```typescript |
| 1333 | * yield* SQS.consumeQueueMessages( |
| 1334 | * queue, |
| 1335 | * Effect.fn(function* (event) { |
| 1336 | * for (const message of event.Records) { |
| 1337 | * yield* Effect.log(`Received: ${message.body}`); |
| 1338 | * } |
| 1339 | * }), |
| 1340 | * ); |
| 1341 | * ``` |
| 1342 | * |
| 1343 | * **Example:** Process DynamoDB stream changes |
| 1344 | * ```typescript |
| 1345 | * yield* AWS.DynamoDB.consumeTableChanges( |
| 1346 | * table, |
| 1347 | * { streamViewType: "NEW_AND_OLD_IMAGES" }, |
| 1348 | * Effect.fn(function* (event) { |
| 1349 | * for (const record of event.Records) { |
| 1350 | * yield* Effect.log(`Change: ${record.eventName}`); |
| 1351 | * } |
| 1352 | * }), |
| 1353 | * ); |
| 1354 | * ``` |
| 1355 | * |
| 1356 | * **Example:** Process S3 notifications |
| 1357 | * ```typescript |
| 1358 | * yield* AWS.S3.consumeBucketEvents(bucket, { |
| 1359 | * events: ["s3:ObjectCreated:*"], |
| 1360 | * }, (stream) => |
| 1361 | * stream.pipe( |
| 1362 | * Stream.runForEach((event) => |
| 1363 | * Effect.log(`New object: ${event.key}`), |
| 1364 | * ), |
| 1365 | * ), |
| 1366 | * ); |
| 1367 | * ``` |
| 1368 | * |
| 1369 | * @resource |
| 1370 | */ |
| 1371 | export const Function: Platform< |
| 1372 | Function, |
| 1373 | FunctionServices, |
| 1374 | FunctionShape, |
| 1375 | FunctionContext, |
| 1376 | {}, |
| 1377 | FunctionZipProps |
| 1378 | > = Platform(FunctionTypeId, { |
| 1379 | // The custom-domain front door integrates the Function's own ARN, so it |
| 1380 | // composes AFTER the Function resource is declared. |
| 1381 | onCreate: (resource, props) => |
| 1382 | composeFunctionDomain(resource as Function, (props as FunctionProps | undefined)?.domain), |
| 1383 | createRuntimeContext: (id: string): FunctionContext => { |
| 1384 | const listeners: Effect.Effect<FunctionListener>[] = []; |
| 1385 | const env: Record<string, any> = {}; |
| 1386 | |
| 1387 | const ctx = { |
| 1388 | Type: FunctionTypeId, |
| 1389 | id, |
| 1390 | env, |
| 1391 | set: (id: string, output: Output.Output) => |
| 1392 | Effect.sync(() => { |
| 1393 | // Key is already canonical (see RuntimeContext.sanitizeKey); store it |
| 1394 | // verbatim. `packEnvValue` marker-packs Redacted values so they |
| 1395 | // survive the Output → Lambda env var round-trip. |
| 1396 | const key = id; |
| 1397 | env[key] = output.pipe(Output.map(packEnvValue)); |
| 1398 | return key; |
| 1399 | }), |
| 1400 | get: <T>(key: string) => |
| 1401 | // Key is already canonical (see RuntimeContext.sanitizeKey). Read |
| 1402 | // straight from `process.env` — see `unpackEnvValue` for why this |
| 1403 | // must never resolve through `Config.String`. |
| 1404 | Effect.sync(() => unpackEnvValue<T>(process.env[key])), |
| 1405 | serve: (handler: HttpEffect) => |
| 1406 | ctx.listen( |
| 1407 | // @ts-ignore |
| 1408 | Effect.map(isResponseStreaming, (responseStream) => |
| 1409 | makeFunctionHttpHandler(handler, { responseStream }), |
| 1410 | ), |
| 1411 | ), |
| 1412 | listen: ((handler: FunctionListener | Effect.Effect<FunctionListener>) => |
| 1413 | Effect.sync(() => |
| 1414 | Effect.isEffect(handler) |
| 1415 | ? listeners.push(handler) |
| 1416 | : listeners.push(Effect.succeed(handler)), |
| 1417 | )) as any as FunctionContext["listen"], |
| 1418 | exports: Effect.sync(() => ({ |
| 1419 | // construct an Effect that produces the Function's entrypoint |
| 1420 | // Effect<(event, context) => Promise<any>> |
| 1421 | handler: Effect.gen(function* () { |
| 1422 | const handlers = yield* Effect.all(listeners, { |
| 1423 | concurrency: "unbounded", |
| 1424 | }); |
| 1425 | // Sandbox-lifetime services, captured so each invocation can |
| 1426 | // build its telemetry exporters and run the handler effect |
| 1427 | // against the same context the init phase saw (mirrors |
| 1428 | // WorkerBridge). The build's memo map is stripped so a Layer the |
| 1429 | // user `Effect.provide`s inside a handler builds per invocation. |
| 1430 | const services = Context.omit(Layer.CurrentMemoMap)(yield* Effect.context<never>()); |
| 1431 | const dispatch = async (event: any, context: lambda.Context): Promise<any> => { |
| 1432 | for (const handler of handlers) { |
| 1433 | const eff = handler(event); |
| 1434 | if (Effect.isEffect(eff)) { |
| 1435 | // Each invocation gets a fresh request scope, matching the |
| 1436 | // Worker / Durable Object / Workflow bridges. The scope is |
| 1437 | // settled inline before returning: a buffered Lambda |
| 1438 | // response is not released to the caller until the Invoke |
| 1439 | // phase completes, so deferring cleanup (e.g. via an |
| 1440 | // INVOKE-subscribed extension window) shows up as response |
| 1441 | // latency anyway — keep request finalizers fast. A failing |
| 1442 | // finalizer is logged and ignored so it can't mask the |
| 1443 | // invocation's outcome. |
| 1444 | // |
| 1445 | // `withInvocationDeadline` interrupts the handler at the |
| 1446 | // Function's `timeout`, so its finalizers run and its spans |
| 1447 | // end inside Lambda's `timeoutMargin`, before this scope |
| 1448 | // flushes the telemetry. |
| 1449 | const scope = Scope.makeUnsafe(); |
| 1450 | const deadline = { fired: false }; |
| 1451 | const exit = await eff.pipe( |
| 1452 | withInvocationDeadline(), |
| 1453 | Effect.provide( |
| 1454 | Layer.mergeAll( |
| 1455 | Layer.succeed(HandlerContext, context), |
| 1456 | Layer.succeed(InvocationDeadlineState, deadline), |
| 1457 | Layer.succeed(Scope.Scope, scope), |
| 1458 | // Runtime readers (e.g. bindings that read their |
| 1459 | // values through `RuntimeContext.get`) run in the |
| 1460 | // handler, like on every other host bridge. |
| 1461 | Layer.succeed(RuntimeContext, ctx as FunctionContext), |
| 1462 | // The configured telemetry exporters, attached to the |
| 1463 | // invocation scope by `buildEventTelemetry` so |
| 1464 | // buffered spans/logs/metrics flush when it settles |
| 1465 | // below. |
| 1466 | Layer.effectContext( |
| 1467 | buildEventTelemetry(services, scope, (ctx as FunctionContext).telemetry), |
| 1468 | ), |
| 1469 | ).pipe(Layer.provideMerge(Layer.succeedContext(services))), |
| 1470 | ), |
| 1471 | Effect.tap(Effect.logDebug), |
| 1472 | Effect.runPromiseExit, |
| 1473 | ); |
| 1474 | if (!isScopeEjected(scope)) { |
| 1475 | // The HttpMiddleware tracer ends the request's root span |
| 1476 | // in a dispatcher task scheduled after the handler effect |
| 1477 | // resolves; yield one macrotask so it reaches the |
| 1478 | // telemetry exporter's buffer before the flush finalizer. |
| 1479 | await new Promise((resolve) => setTimeout(resolve, 0)); |
| 1480 | await Scope.close(scope, exit).pipe( |
| 1481 | Effect.ignoreCause({ |
| 1482 | log: "Warn", |
| 1483 | message: "Lambda invocation scope close failed", |
| 1484 | }), |
| 1485 | Effect.runPromise, |
| 1486 | ); |
| 1487 | } |
| 1488 | if (deadline.fired) { |
| 1489 | // The handler ran past its `timeout`: it was interrupted, |
| 1490 | // its finalizers ran and its telemetry flushed. Hold the |
| 1491 | // invocation until Lambda's own timeout ends it, so Lambda |
| 1492 | // reports and retries a real timeout and resets the |
| 1493 | // sandbox — work that ignored the interruption can never |
| 1494 | // resume in the next invocation. |
| 1495 | await new Promise<never>(() => {}); |
| 1496 | } |
| 1497 | if (Exit.isSuccess(exit)) { |
| 1498 | return exit.value; |
| 1499 | } |
| 1500 | throw Cause.squash(exit.cause); |
| 1501 | } |
| 1502 | } |
| 1503 | throw new Error("No event handler found"); |
| 1504 | }; |
| 1505 | // `invokeMode: "RESPONSE_STREAM"` needs a streaming handler. |
| 1506 | return (yield* isResponseStreaming) ? streamifyHandler(dispatch) : dispatch; |
| 1507 | }), |
| 1508 | })), |
| 1509 | }; |
| 1510 | return ctx; |
| 1511 | }, |
| 1512 | }); |
| 1513 | |
| 1514 | export const FunctionProvider = () => |
| 1515 | Provider.effect( |
| 1516 | Function, |
| 1517 | Effect.gen(function* () { |
| 1518 | const stack = yield* Stack; |
| 1519 | |
| 1520 | // Code bundling lives in FunctionBundle.ts so the floci local |
| 1521 | // provider's watch loop can rebuild the identical artifact. |
| 1522 | const { bundleCode } = yield* makeFunctionBundler; |
| 1523 | const functionImage = yield* makeFunctionImage; |
| 1524 | const alchemyEnv = { |
| 1525 | ALCHEMY_STACK_NAME: stack.name, |
| 1526 | ALCHEMY_STAGE: stack.stage, |
| 1527 | ALCHEMY_PHASE: "runtime", |
| 1528 | }; |
| 1529 | |
| 1530 | const createFunctionName = (id: string, functionName: string | undefined) => |
| 1531 | Effect.gen(function* () { |
| 1532 | return functionName ?? (yield* createPhysicalName({ id, maxLength: 64 })); |
| 1533 | }); |
| 1534 | |
| 1535 | const createRoleName = (id: string) => createPhysicalName({ id, maxLength: 64 }); |
| 1536 | |
| 1537 | const createPolicyName = (id: string) => createPhysicalName({ id, maxLength: 128 }); |
| 1538 | |
| 1539 | const hashBundle = (code: Uint8Array<ArrayBufferLike>) => sha256(code); |
| 1540 | |
| 1541 | const createNames = (id: string, functionName: string | undefined) => |
| 1542 | Effect.gen(function* () { |
| 1543 | const { accountId, region } = yield* AWSEnvironment.current; |
| 1544 | const roleName = yield* createRoleName(id); |
| 1545 | const policyName = yield* createPolicyName(id); |
| 1546 | const fn = yield* createFunctionName(id, functionName); |
| 1547 | return { |
| 1548 | roleName, |
| 1549 | policyName, |
| 1550 | functionName: fn, |
| 1551 | roleArn: `arn:aws:iam::${accountId}:role/${roleName}`, |
| 1552 | functionArn: `arn:aws:lambda:${region}:${accountId}:function:${fn}`, |
| 1553 | }; |
| 1554 | }); |
| 1555 | |
| 1556 | const attachBindings = Effect.fn(function* ({ |
| 1557 | roleName, |
| 1558 | policyName, |
| 1559 | // functionArn, |
| 1560 | // functionName, |
| 1561 | bindings, |
| 1562 | }: { |
| 1563 | roleName: string; |
| 1564 | policyName: string; |
| 1565 | functionArn: string; |
| 1566 | functionName: string; |
| 1567 | bindings: ResourceBinding<Function["Binding"]>[]; |
| 1568 | }) { |
| 1569 | const activeBindings = bindings.filter( |
| 1570 | (binding: ResourceBinding<Function["Binding"]> & { action?: string }) => |
| 1571 | binding.action !== "delete", |
| 1572 | ); |
| 1573 | const env = activeBindings |
| 1574 | .map((binding) => binding?.data?.env) |
| 1575 | .reduce((acc, env) => ({ ...acc, ...env }), {}); |
| 1576 | const policyStatements = activeBindings.flatMap( |
| 1577 | (binding) => |
| 1578 | binding?.data?.policyStatements?.map((stmt: IAM.PolicyStatement) => ({ |
| 1579 | ...stmt, |
| 1580 | Sid: stmt.Sid?.replace(/[^A-Za-z0-9]+/gi, ""), |
| 1581 | })) ?? [], |
| 1582 | ); |
| 1583 | // VPC attachments requested through the binding channel (DECISION |
| 1584 | // #5) — set-union across bindings; merged with the `vpc` prop in |
| 1585 | // `reconcile`. |
| 1586 | const vpcRequests = activeBindings.flatMap((binding) => |
| 1587 | binding?.data?.vpc ? [binding.data.vpc] : [], |
| 1588 | ); |
| 1589 | const vpc = |
| 1590 | vpcRequests.length > 0 |
| 1591 | ? { |
| 1592 | subnetIds: [...new Set(vpcRequests.flatMap((v) => v.subnetIds))], |
| 1593 | securityGroupIds: [...new Set(vpcRequests.flatMap((v) => v.securityGroupIds))], |
| 1594 | } |
| 1595 | : undefined; |
| 1596 | // EFS mounts requested through the binding channel (`EFS.Mount`) — |
| 1597 | // deduped by mount path; merged with the `fileSystemConfigs` prop in |
| 1598 | // `reconcile`. |
| 1599 | const fileSystemConfigs = [ |
| 1600 | ...new Map( |
| 1601 | activeBindings |
| 1602 | .flatMap((binding) => binding?.data?.fileSystemConfigs ?? []) |
| 1603 | .map((config) => [config.localMountPath, config] as const), |
| 1604 | ).values(), |
| 1605 | ]; |
| 1606 | |
| 1607 | if (policyStatements.length > 0) { |
| 1608 | yield* iam.putRolePolicy({ |
| 1609 | RoleName: roleName, |
| 1610 | PolicyName: policyName, |
| 1611 | PolicyDocument: JSON.stringify({ |
| 1612 | Version: "2012-10-17", |
| 1613 | Statement: policyStatements, |
| 1614 | } satisfies IAM.PolicyDocument), |
| 1615 | }); |
| 1616 | } else { |
| 1617 | yield* iam |
| 1618 | .deleteRolePolicy({ |
| 1619 | RoleName: roleName, |
| 1620 | PolicyName: policyName, |
| 1621 | }) |
| 1622 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)); |
| 1623 | } |
| 1624 | |
| 1625 | return { env, vpc, fileSystemConfigs }; |
| 1626 | }); |
| 1627 | |
| 1628 | const xrayWriteAccessPolicyArn = "arn:aws:iam::aws:policy/AWSXRayDaemonWriteAccess"; |
| 1629 | |
| 1630 | /** |
| 1631 | * Converge the X-Ray write managed policy on the execution role with |
| 1632 | * the desired tracing mode. Attaching is idempotent; detaching is only |
| 1633 | * attempted when the previous state may have had it attached (routine |
| 1634 | * update from `Active`, or adoption where the prior props are unknown) |
| 1635 | * to avoid a wasted IAM call on every deploy. |
| 1636 | */ |
| 1637 | const syncTracingPolicy = Effect.fn(function* ({ |
| 1638 | roleName, |
| 1639 | tracing, |
| 1640 | mayHaveBeenActive, |
| 1641 | }: { |
| 1642 | roleName: string; |
| 1643 | tracing: FunctionProps["tracing"]; |
| 1644 | mayHaveBeenActive: boolean; |
| 1645 | }) { |
| 1646 | if (tracing === "Active") { |
| 1647 | yield* iam.attachRolePolicy({ |
| 1648 | RoleName: roleName, |
| 1649 | PolicyArn: xrayWriteAccessPolicyArn, |
| 1650 | }); |
| 1651 | } else if (mayHaveBeenActive) { |
| 1652 | yield* iam |
| 1653 | .detachRolePolicy({ |
| 1654 | RoleName: roleName, |
| 1655 | PolicyArn: xrayWriteAccessPolicyArn, |
| 1656 | }) |
| 1657 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)); |
| 1658 | } |
| 1659 | }); |
| 1660 | |
| 1661 | const createRoleIfNotExists = Effect.fn(function* ({ |
| 1662 | id, |
| 1663 | roleName, |
| 1664 | vpc, |
| 1665 | }: { |
| 1666 | id: string; |
| 1667 | roleName: string; |
| 1668 | vpc?: FunctionProps["vpc"]; |
| 1669 | }) { |
| 1670 | yield* Effect.logDebug(`creating role ${id}`); |
| 1671 | const tags = yield* createInternalTags(id); |
| 1672 | // Observe before ensure. Reconcile calls this even with persisted |
| 1673 | // output so an execution role deleted out-of-band is recreated, but |
| 1674 | // the normal update path avoids provoking an expected |
| 1675 | // EntityAlreadyExists exception (important under high concurrency). |
| 1676 | let role = yield* iam |
| 1677 | .getRole({ RoleName: roleName }) |
| 1678 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.undefined)); |
| 1679 | if (role === undefined) { |
| 1680 | // Engine has cleared us via `read` or `observe` — foreign-tagged |
| 1681 | // functions are surfaced as `Unowned` and require `--adopt`. On a race between |
| 1682 | // observe and create, read the role created by the peer reconciler. |
| 1683 | role = yield* iam |
| 1684 | .createRole({ |
| 1685 | RoleName: roleName, |
| 1686 | AssumeRolePolicyDocument: JSON.stringify({ |
| 1687 | Version: "2012-10-17", |
| 1688 | Statement: [ |
| 1689 | { |
| 1690 | Effect: "Allow", |
| 1691 | Principal: { |
| 1692 | Service: "lambda.amazonaws.com", |
| 1693 | }, |
| 1694 | Action: "sts:AssumeRole", |
| 1695 | }, |
| 1696 | ], |
| 1697 | }), |
| 1698 | Tags: createTagsList(tags), |
| 1699 | }) |
| 1700 | .pipe( |
| 1701 | Effect.catchTag("EntityAlreadyExistsException", () => |
| 1702 | iam.getRole({ RoleName: roleName }), |
| 1703 | ), |
| 1704 | ); |
| 1705 | } |
| 1706 | |
| 1707 | yield* Effect.logDebug(`attaching policy ${id}`); |
| 1708 | yield* iam |
| 1709 | .attachRolePolicy({ |
| 1710 | RoleName: roleName, |
| 1711 | PolicyArn: "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole", |
| 1712 | }) |
| 1713 | .pipe(Effect.tapError(Effect.logDebug), Effect.tap(Effect.logDebug)); |
| 1714 | |
| 1715 | if (vpc) { |
| 1716 | yield* iam |
| 1717 | .attachRolePolicy({ |
| 1718 | RoleName: roleName, |
| 1719 | PolicyArn: "arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole", |
| 1720 | }) |
| 1721 | .pipe(Effect.tapError(Effect.logDebug), Effect.tap(Effect.logDebug)); |
| 1722 | } |
| 1723 | |
| 1724 | yield* Effect.logDebug(`attached policy ${id}`); |
| 1725 | return role; |
| 1726 | }); |
| 1727 | |
| 1728 | /** |
| 1729 | * Deny the execution role `logs:CreateLogGroup` on the function's own |
| 1730 | * `/aws/lambda/<name>` group. The managed `AWSLambdaBasicExecutionRole` |
| 1731 | * allows it on `*`, which lets Lambda create the group with no tags or |
| 1732 | * retention on first invoke, and lets a log batch flushed after |
| 1733 | * `deleteFunction` silently re-create a group we just deleted. With the |
| 1734 | * Deny, Alchemy owns the group (see {@link ensureLogGroup}): Lambda only |
| 1735 | * writes into it, and `delete` removes it once. |
| 1736 | */ |
| 1737 | const syncLogGroupGuard = Effect.fn(function* ({ |
| 1738 | roleName, |
| 1739 | functionName, |
| 1740 | }: { |
| 1741 | roleName: string; |
| 1742 | functionName: string; |
| 1743 | }) { |
| 1744 | const { accountId, region } = yield* AWSEnvironment.current; |
| 1745 | const document = JSON.stringify({ |
| 1746 | Version: "2012-10-17", |
| 1747 | Statement: [ |
| 1748 | { |
| 1749 | Effect: "Deny", |
| 1750 | Action: "logs:CreateLogGroup", |
| 1751 | Resource: `arn:aws:logs:${region}:${accountId}:log-group:/aws/lambda/${functionName}:*`, |
| 1752 | }, |
| 1753 | ], |
| 1754 | }); |
| 1755 | const observed = yield* iam |
| 1756 | .getRolePolicy({ RoleName: roleName, PolicyName: logGroupGuardPolicyName }) |
| 1757 | .pipe( |
| 1758 | Effect.map((policy) => decodeURIComponent(policy.PolicyDocument)), |
| 1759 | Effect.catchTag("NoSuchEntityException", () => Effect.undefined), |
| 1760 | ); |
| 1761 | if (observed !== document) { |
| 1762 | yield* iam.putRolePolicy({ |
| 1763 | RoleName: roleName, |
| 1764 | PolicyName: logGroupGuardPolicyName, |
| 1765 | PolicyDocument: document, |
| 1766 | }); |
| 1767 | } |
| 1768 | }); |
| 1769 | |
| 1770 | /** |
| 1771 | * Create (or adopt) `/aws/lambda/<name>` before the function can run. |
| 1772 | * The execution role cannot create it (see {@link syncLogGroupGuard}), |
| 1773 | * so without this the function's logs would be dropped. |
| 1774 | */ |
| 1775 | const ensureLogGroup = Effect.fn(function* ({ |
| 1776 | id, |
| 1777 | functionName, |
| 1778 | retention, |
| 1779 | }: { |
| 1780 | id: string; |
| 1781 | functionName: string; |
| 1782 | retention: LogRetentionConfig["retention"] | undefined; |
| 1783 | }) { |
| 1784 | const logGroupName = `/aws/lambda/${functionName}`; |
| 1785 | yield* logs |
| 1786 | .createLogGroup({ logGroupName, tags: yield* createInternalTags(id) }) |
| 1787 | .pipe(Effect.catchTag("ResourceAlreadyExistsException", () => Effect.void)); |
| 1788 | yield* syncLogGroupRetention({ logGroupName, retention }); |
| 1789 | }); |
| 1790 | |
| 1791 | const withNodeSourceMaps = ( |
| 1792 | env: Record<string, string> | undefined, |
| 1793 | props: FunctionZipProps, |
| 1794 | ) => { |
| 1795 | const sourcemap = props.build?.output?.sourcemap ?? true; |
| 1796 | const uploadSourceMap = props.uploadSourceMap ?? true; |
| 1797 | const shouldEnableSourceMaps = |
| 1798 | sourcemap === "inline" || |
| 1799 | (uploadSourceMap && (sourcemap === true || sourcemap === "hidden")); |
| 1800 | |
| 1801 | if (!shouldEnableSourceMaps) { |
| 1802 | return env; |
| 1803 | } |
| 1804 | |
| 1805 | const current = env?.NODE_OPTIONS; |
| 1806 | if (current?.split(/\s+/).includes("--enable-source-maps")) { |
| 1807 | return env; |
| 1808 | } |
| 1809 | |
| 1810 | return { |
| 1811 | ...env, |
| 1812 | NODE_OPTIONS: current ? `${current} --enable-source-maps` : "--enable-source-maps", |
| 1813 | }; |
| 1814 | }; |
| 1815 | |
| 1816 | // The runtime reads the grace between the Function's `timeout` and |
| 1817 | // Lambda's per invocation (see `withInvocationDeadline`); only |
| 1818 | // written when the handler is interrupted at all. |
| 1819 | const timeoutGraceEnv = (graceMs: number): Record<string, string> => |
| 1820 | graceMs > 0 ? { [TIMEOUT_GRACE_ENV]: String(graceMs) } : {}; |
| 1821 | |
| 1822 | // A `RESPONSE_STREAM` Function URL tells the runtime to export its |
| 1823 | // handler through `awslambda.streamifyResponse`. |
| 1824 | const responseStreamEnv = (url: FunctionProps["functionUrl"]): Record<string, string> => |
| 1825 | normalizeFunctionUrl(url)?.invokeMode === "RESPONSE_STREAM" |
| 1826 | ? { [RESPONSE_STREAM_ENV]: "true" } |
| 1827 | : {}; |
| 1828 | |
| 1829 | const retryFunctionMutation = Effect.retry({ |
| 1830 | while: (e: any) => |
| 1831 | e._tag === "ResourceConflictException" || e._tag === "TooManyRequestsException", |
| 1832 | schedule: Schedule.max([Schedule.exponential(100), Schedule.recurs(30)]), |
| 1833 | }) as <A, R, Err>(self: Effect.Effect<A, Err, R>) => Effect.Effect<A, Err, R>; |
| 1834 | |
| 1835 | const waitForFunctionUpdate = Effect.fn(function* ( |
| 1836 | functionName: string, |
| 1837 | session: { note: (note: string) => Effect.Effect<void> }, |
| 1838 | vpc: boolean, |
| 1839 | ) { |
| 1840 | return yield* Effect.gen(function* () { |
| 1841 | const configuration = (yield* Lambda.getFunction({ |
| 1842 | FunctionName: functionName, |
| 1843 | })).Configuration; |
| 1844 | if (configuration?.State === "Failed" || configuration?.LastUpdateStatus === "Failed") { |
| 1845 | return yield* new FunctionUpdateFailed({ |
| 1846 | functionName, |
| 1847 | reason: configuration.LastUpdateStatusReason ?? configuration.StateReason, |
| 1848 | reasonCode: |
| 1849 | configuration.LastUpdateStatus === "Failed" |
| 1850 | ? configuration.LastUpdateStatusReasonCode |
| 1851 | : configuration.StateReasonCode, |
| 1852 | }); |
| 1853 | } |
| 1854 | if ( |
| 1855 | configuration?.State === "Active" && |
| 1856 | (configuration.LastUpdateStatus === undefined || |
| 1857 | configuration.LastUpdateStatus === "Successful") |
| 1858 | ) { |
| 1859 | return configuration; |
| 1860 | } |
| 1861 | return yield* new FunctionUpdatePending({ |
| 1862 | functionName, |
| 1863 | state: configuration?.State, |
| 1864 | stateReason: configuration?.StateReason, |
| 1865 | lastUpdateStatus: configuration?.LastUpdateStatus, |
| 1866 | lastUpdateStatusReason: configuration?.LastUpdateStatusReason, |
| 1867 | }); |
| 1868 | }).pipe( |
| 1869 | Effect.retry({ |
| 1870 | while: (error) => error._tag === "FunctionUpdatePending", |
| 1871 | schedule: Schedule.spaced("2 seconds").pipe( |
| 1872 | Schedule.tap(({ attempt }) => |
| 1873 | session.note( |
| 1874 | `Waiting for Lambda function update: ${functionName} (${attempt * 2}s)`, |
| 1875 | ), |
| 1876 | ), |
| 1877 | ), |
| 1878 | // New VPC attachments can spend several minutes provisioning Hyperplane ENIs. |
| 1879 | times: vpc ? 150 : 30, |
| 1880 | }), |
| 1881 | ); |
| 1882 | }); |
| 1883 | |
| 1884 | const getReservedConcurrentExecutions = Effect.fn(function* (functionName: string) { |
| 1885 | return yield* Lambda.getFunctionConcurrency({ |
| 1886 | FunctionName: functionName, |
| 1887 | }).pipe( |
| 1888 | Effect.map((config) => config.ReservedConcurrentExecutions), |
| 1889 | Effect.catchTag("ResourceNotFoundException", () => Effect.undefined), |
| 1890 | ); |
| 1891 | }); |
| 1892 | |
| 1893 | const readFunctionUrlConfig = (functionName: string, qualifier: string | undefined) => |
| 1894 | Lambda.getFunctionUrlConfig({ |
| 1895 | FunctionName: functionName, |
| 1896 | Qualifier: qualifier, |
| 1897 | }).pipe( |
| 1898 | Effect.retry({ |
| 1899 | while: (e: any) => e._tag === "ResourceConflictException", |
| 1900 | schedule: Schedule.exponential(100), |
| 1901 | }), |
| 1902 | Effect.catchTag("ResourceNotFoundException", () => Effect.undefined), |
| 1903 | ); |
| 1904 | |
| 1905 | // AWS managed policies Alchemy attaches to the execution role. Other |
| 1906 | // attachments (e.g. an `IAM.RolePolicyAttachment` on `roleName`) are |
| 1907 | // not ours to observe. |
| 1908 | const managedExecutionPolicyArns = new Set([ |
| 1909 | "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole", |
| 1910 | "arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole", |
| 1911 | "arn:aws:iam::aws:policy/AmazonElasticFileSystemClientReadWriteAccess", |
| 1912 | xrayWriteAccessPolicyArn, |
| 1913 | ]); |
| 1914 | |
| 1915 | /** |
| 1916 | * Project the configuration `alchemy drift` compares: every setting |
| 1917 | * reconcile converges, as observed on the deployed function. `read` |
| 1918 | * and `reconcile` share it so a converged function reads unchanged. |
| 1919 | */ |
| 1920 | const observeFunctionConfiguration = Effect.fn(function* ({ |
| 1921 | id, |
| 1922 | configuration: fn, |
| 1923 | qualifier, |
| 1924 | roleName, |
| 1925 | logging, |
| 1926 | }: { |
| 1927 | id: string; |
| 1928 | configuration: Lambda.FunctionConfiguration; |
| 1929 | qualifier: string | undefined; |
| 1930 | roleName: string; |
| 1931 | logging: FunctionProps["logging"]; |
| 1932 | }) { |
| 1933 | const functionName = fn.FunctionName!; |
| 1934 | const policyName = yield* createPolicyName(id); |
| 1935 | const readInlinePolicy = (PolicyName: string) => |
| 1936 | iam.getRolePolicy({ RoleName: roleName, PolicyName }).pipe( |
| 1937 | Effect.map((policy) => JSON.parse(decodeURIComponent(policy.PolicyDocument))), |
| 1938 | Effect.catchTag("NoSuchEntityException", () => Effect.undefined), |
| 1939 | ); |
| 1940 | const [urlConfig, logRetentionInDays, attached, bindingPolicy, guardPolicy, invokeConfig] = |
| 1941 | yield* Effect.all( |
| 1942 | [ |
| 1943 | readFunctionUrlConfig(functionName, qualifier), |
| 1944 | logging?.retention === undefined |
| 1945 | ? Effect.undefined |
| 1946 | : logs |
| 1947 | .describeLogGroups({ logGroupNamePrefix: `/aws/lambda/${functionName}` }) |
| 1948 | .pipe( |
| 1949 | Effect.map( |
| 1950 | (result) => |
| 1951 | result.logGroups?.find( |
| 1952 | (group) => group.logGroupName === `/aws/lambda/${functionName}`, |
| 1953 | )?.retentionInDays, |
| 1954 | ), |
| 1955 | ), |
| 1956 | iam.listAttachedRolePolicies({ RoleName: roleName }).pipe( |
| 1957 | Effect.map((result) => |
| 1958 | (result.AttachedPolicies ?? []).flatMap((policy) => |
| 1959 | policy.PolicyArn && managedExecutionPolicyArns.has(policy.PolicyArn) |
| 1960 | ? [policy.PolicyArn] |
| 1961 | : [], |
| 1962 | ), |
| 1963 | ), |
| 1964 | Effect.catchTag("NoSuchEntityException", () => Effect.succeed([] as string[])), |
| 1965 | ), |
| 1966 | readInlinePolicy(policyName), |
| 1967 | readInlinePolicy(logGroupGuardPolicyName), |
| 1968 | observeEventInvokeConfig(functionName, qualifier), |
| 1969 | ], |
| 1970 | { concurrency: "unbounded" }, |
| 1971 | ); |
| 1972 | const environment = yield* Effect.sync(() => |
| 1973 | Object.fromEntries( |
| 1974 | Object.entries(fn.Environment?.Variables ?? {}) |
| 1975 | .sort(([a], [b]) => a.localeCompare(b)) |
| 1976 | .map(([key, value]) => [ |
| 1977 | key, |
| 1978 | createHash("sha256") |
| 1979 | .update(Redacted.isRedacted(value) ? Redacted.value(value) : (value ?? "")) |
| 1980 | .digest("hex"), |
| 1981 | ]), |
| 1982 | ), |
| 1983 | ); |
| 1984 | const subnetIds = [...(fn.VpcConfig?.SubnetIds ?? [])].sort(); |
| 1985 | const fileSystemConfigs = (fn.FileSystemConfigs ?? []) |
| 1986 | .map((config) => ({ arn: config.Arn, localMountPath: config.LocalMountPath })) |
| 1987 | .sort((a, b) => a.localMountPath.localeCompare(b.localMountPath)); |
| 1988 | const cors = urlConfig?.Cors; |
| 1989 | return { |
| 1990 | memorySize: fn.MemorySize, |
| 1991 | timeoutSeconds: fn.Timeout, |
| 1992 | runtime: fn.Runtime, |
| 1993 | handler: fn.Handler, |
| 1994 | architecture: fn.Architectures?.[0], |
| 1995 | layers: (fn.Layers ?? []).flatMap((layer) => (layer.Arn ? [layer.Arn] : [])), |
| 1996 | environment, |
| 1997 | vpcConfig: |
| 1998 | subnetIds.length > 0 |
| 1999 | ? { |
| 2000 | subnetIds, |
| 2001 | securityGroupIds: [...(fn.VpcConfig?.SecurityGroupIds ?? [])].sort(), |
| 2002 | } |
| 2003 | : undefined, |
| 2004 | fileSystemConfigs: fileSystemConfigs.length > 0 ? fileSystemConfigs : undefined, |
| 2005 | tracing: fn.TracingConfig?.Mode, |
| 2006 | codeSha256: fn.CodeSha256, |
| 2007 | functionUrlConfig: urlConfig |
| 2008 | ? { |
| 2009 | authType: urlConfig.AuthType, |
| 2010 | invokeMode: urlConfig.InvokeMode, |
| 2011 | // A cleared CORS config reads back as an empty object. |
| 2012 | cors: |
| 2013 | cors && Object.values(cors).some((value) => value !== undefined) |
| 2014 | ? cors |
| 2015 | : undefined, |
| 2016 | } |
| 2017 | : undefined, |
| 2018 | logRetentionInDays, |
| 2019 | executionRole: { |
| 2020 | managedPolicyArns: attached.sort(), |
| 2021 | inlinePolicies: { |
| 2022 | ...(bindingPolicy === undefined ? {} : { [policyName]: bindingPolicy }), |
| 2023 | ...(guardPolicy === undefined ? {} : { [logGroupGuardPolicyName]: guardPolicy }), |
| 2024 | }, |
| 2025 | }, |
| 2026 | eventInvokeConfig: invokeConfig, |
| 2027 | durableConfig: fn.DurableConfig |
| 2028 | ? { |
| 2029 | executionTimeout: fn.DurableConfig.ExecutionTimeout, |
| 2030 | retentionPeriodInDays: fn.DurableConfig.RetentionPeriodInDays, |
| 2031 | } |
| 2032 | : undefined, |
| 2033 | } satisfies Partial<Function["Attributes"]>; |
| 2034 | }); |
| 2035 | |
| 2036 | const syncReservedConcurrentExecutions = Effect.fn(function* ({ |
| 2037 | functionName, |
| 2038 | reservedConcurrentExecutions, |
| 2039 | }: { |
| 2040 | functionName: string; |
| 2041 | reservedConcurrentExecutions: number | undefined; |
| 2042 | }) { |
| 2043 | const current = yield* getReservedConcurrentExecutions(functionName); |
| 2044 | if (current === reservedConcurrentExecutions) { |
| 2045 | return current; |
| 2046 | } |
| 2047 | |
| 2048 | if (reservedConcurrentExecutions === undefined) { |
| 2049 | yield* Lambda.deleteFunctionConcurrency({ |
| 2050 | FunctionName: functionName, |
| 2051 | }).pipe( |
| 2052 | retryFunctionMutation, |
| 2053 | Effect.catchTag("ResourceNotFoundException", () => Effect.void), |
| 2054 | ); |
| 2055 | return undefined; |
| 2056 | } |
| 2057 | |
| 2058 | const updated = yield* Lambda.putFunctionConcurrency({ |
| 2059 | FunctionName: functionName, |
| 2060 | ReservedConcurrentExecutions: reservedConcurrentExecutions, |
| 2061 | }).pipe(retryFunctionMutation); |
| 2062 | return updated.ReservedConcurrentExecutions ?? reservedConcurrentExecutions; |
| 2063 | }); |
| 2064 | |
| 2065 | type FunctionDeploymentCode = |
| 2066 | | { |
| 2067 | packageType: "Zip"; |
| 2068 | archive: Uint8Array<ArrayBufferLike>; |
| 2069 | hash: string; |
| 2070 | } |
| 2071 | | { |
| 2072 | packageType: "Image"; |
| 2073 | imageUri: string; |
| 2074 | hash: string; |
| 2075 | }; |
| 2076 | |
| 2077 | interface PreparedFunctionCode { |
| 2078 | deployment: FunctionDeploymentCode; |
| 2079 | attributes: Function["Attributes"]["code"]; |
| 2080 | } |
| 2081 | |
| 2082 | const prepareImageFunctionCode = Effect.fn(function* ({ |
| 2083 | id, |
| 2084 | props, |
| 2085 | previousImage, |
| 2086 | session, |
| 2087 | }: { |
| 2088 | id: string; |
| 2089 | props: FunctionImageProps; |
| 2090 | previousImage?: Omit<FunctionImageAttributes, "hash">; |
| 2091 | session: { note: (note: string) => Effect.Effect<void> }; |
| 2092 | }) { |
| 2093 | const { hash, ...image } = yield* functionImage.resolve({ |
| 2094 | id, |
| 2095 | source: props.image, |
| 2096 | architecture: props.architecture, |
| 2097 | previousImage, |
| 2098 | session, |
| 2099 | }); |
| 2100 | return { |
| 2101 | deployment: { |
| 2102 | packageType: "Image", |
| 2103 | imageUri: image.imageUri, |
| 2104 | hash, |
| 2105 | }, |
| 2106 | attributes: { hash, image }, |
| 2107 | } satisfies PreparedFunctionCode; |
| 2108 | }); |
| 2109 | |
| 2110 | const preparePrecreatedFunctionCode = Effect.fn(function* ({ |
| 2111 | id, |
| 2112 | props, |
| 2113 | session, |
| 2114 | }: { |
| 2115 | id: string; |
| 2116 | props: FunctionProps; |
| 2117 | session: { note: (note: string) => Effect.Effect<void> }; |
| 2118 | }) { |
| 2119 | if (isFunctionImageProps(props)) { |
| 2120 | return yield* prepareImageFunctionCode({ id, props, session }); |
| 2121 | } |
| 2122 | |
| 2123 | // The precreated stub responds 503 until reconciliation installs the |
| 2124 | // real handler and waits for its configuration to become active. |
| 2125 | const code = new TextEncoder().encode( |
| 2126 | `export default () => ({ statusCode: 503, headers: { "content-type": "application/json" }, body: JSON.stringify({ error: "function initializing" }) })`, |
| 2127 | ); |
| 2128 | const archive = yield* zipCode(code); |
| 2129 | const hash = yield* hashBundle(code); |
| 2130 | return { |
| 2131 | deployment: { |
| 2132 | packageType: "Zip", |
| 2133 | archive, |
| 2134 | hash, |
| 2135 | }, |
| 2136 | attributes: { hash }, |
| 2137 | } satisfies PreparedFunctionCode; |
| 2138 | }); |
| 2139 | |
| 2140 | const prepareFunctionCode = Effect.fn(function* ({ |
| 2141 | id, |
| 2142 | props, |
| 2143 | previousImage, |
| 2144 | session, |
| 2145 | }: { |
| 2146 | id: string; |
| 2147 | props: FunctionProps; |
| 2148 | previousImage?: Omit<FunctionImageAttributes, "hash">; |
| 2149 | session: { note: (note: string) => Effect.Effect<void> }; |
| 2150 | }) { |
| 2151 | if (isFunctionImageProps(props)) { |
| 2152 | return yield* prepareImageFunctionCode({ |
| 2153 | id, |
| 2154 | props, |
| 2155 | previousImage, |
| 2156 | session, |
| 2157 | }); |
| 2158 | } |
| 2159 | |
| 2160 | const { identityHash, buildArchive } = yield* bundleCode(id, props); |
| 2161 | const { archive, archiveHash } = yield* buildArchive; |
| 2162 | return { |
| 2163 | deployment: { |
| 2164 | packageType: "Zip", |
| 2165 | archive, |
| 2166 | hash: archiveHash, |
| 2167 | }, |
| 2168 | attributes: { hash: identityHash }, |
| 2169 | } satisfies PreparedFunctionCode; |
| 2170 | }); |
| 2171 | |
| 2172 | const createOrUpdateFunction: (input: { |
| 2173 | id: string; |
| 2174 | news: FunctionProps; |
| 2175 | roleArn: string; |
| 2176 | code: FunctionDeploymentCode; |
| 2177 | env: Record<string, string> | undefined; |
| 2178 | functionName: string; |
| 2179 | preferUpdate?: boolean; |
| 2180 | // Resolved EFS mounts. `undefined` leaves the function's existing |
| 2181 | // config untouched (precreate stub); `[]` explicitly clears mounts. |
| 2182 | fileSystemConfigs?: Lambda.FileSystemConfig[]; |
| 2183 | // Effective VPC attachment (prop ∪ binding-channel requests). |
| 2184 | // Omitted for the precreate stub: `news` is UNRESOLVED at precreate |
| 2185 | // (Output-valued subnet/security-group ids would fail to serialize), |
| 2186 | // and the stub doesn't need connectivity — `reconcile` attaches the |
| 2187 | // resolved VPC config afterwards. |
| 2188 | vpc?: FunctionProps["vpc"]; |
| 2189 | session: { note: (note: string) => Effect.Effect<void> }; |
| 2190 | }) => Effect.Effect< |
| 2191 | void, |
| 2192 | any, |
| 2193 | Credentials | Region | HttpClient | Stack | Stage | AWSEnvironment |
| 2194 | > = Effect.fn(function* ({ |
| 2195 | id, |
| 2196 | news, |
| 2197 | roleArn, |
| 2198 | code, |
| 2199 | env, |
| 2200 | functionName, |
| 2201 | preferUpdate, |
| 2202 | fileSystemConfigs, |
| 2203 | vpc, |
| 2204 | session, |
| 2205 | }: { |
| 2206 | id: string; |
| 2207 | news: FunctionProps; |
| 2208 | roleArn: string; |
| 2209 | code: FunctionDeploymentCode; |
| 2210 | env: Record<string, string> | undefined; |
| 2211 | functionName: string; |
| 2212 | preferUpdate?: boolean; |
| 2213 | fileSystemConfigs?: Lambda.FileSystemConfig[]; |
| 2214 | vpc?: FunctionProps["vpc"]; |
| 2215 | session: { note: (note: string) => Effect.Effect<void> }; |
| 2216 | }) { |
| 2217 | yield* Effect.logDebug(`creating function ${id}`); |
| 2218 | const waitStartedAt = Date.now(); |
| 2219 | |
| 2220 | // A just-created role (or its freshly attached policies, KMS grant |
| 2221 | // principal, or security group) isn't visible to Lambda yet. |
| 2222 | const isRolePropagationError = ( |
| 2223 | e: |
| 2224 | | Lambda.CreateFunctionError |
| 2225 | | Lambda.UpdateFunctionCodeError |
| 2226 | | Lambda.UpdateFunctionConfigurationError, |
| 2227 | ) => |
| 2228 | e._tag === "ExecutionRoleNotAssumable" || |
| 2229 | e._tag === "ExecutionRoleMissingVpcPermissions" || |
| 2230 | e._tag === "KmsGrantPrincipalNotReady"; |
| 2231 | |
| 2232 | const isSecurityGroupPropagationError = (e: Lambda.CreateFunctionError) => |
| 2233 | e._tag === "SecurityGroupNotFound"; |
| 2234 | |
| 2235 | const noteCreateDependencyWait = () => |
| 2236 | session.note( |
| 2237 | `Waiting for Lambda creation dependencies to propagate: ${functionName} (${Math.ceil((Date.now() - waitStartedAt) / 1000)}s)`, |
| 2238 | ); |
| 2239 | |
| 2240 | const tags = yield* createInternalTags(id); |
| 2241 | |
| 2242 | const resolveCodeLocation = Effect.gen(function* () { |
| 2243 | if (code.packageType === "Image") { |
| 2244 | return { ImageUri: code.imageUri } as const; |
| 2245 | } |
| 2246 | // Try to use S3 if the assets bucket is available, otherwise fall |
| 2247 | // back to an inline ZipFile. |
| 2248 | const assets = (yield* Effect.serviceOption(Assets)).pipe(Option.getOrUndefined); |
| 2249 | if (!assets) { |
| 2250 | return { ZipFile: code.archive } as const; |
| 2251 | } |
| 2252 | const key = yield* assets.uploadAsset(code.hash, code.archive); |
| 2253 | yield* Effect.logDebug(`Using S3 for code: s3://${yield* assets.bucketName}/${key}`); |
| 2254 | return { |
| 2255 | S3Bucket: yield* assets.bucketName, |
| 2256 | S3Key: key, |
| 2257 | } as const; |
| 2258 | }); |
| 2259 | const codeLocation = yield* resolveCodeLocation; |
| 2260 | const runtimeEnv = isFunctionImageProps(news) ? env : withNodeSourceMaps(env, news); |
| 2261 | const lambdaTimeout = yield* lambdaTimeoutOf({ |
| 2262 | id, |
| 2263 | timeout: news.timeout, |
| 2264 | timeoutMargin: news.timeoutMargin, |
| 2265 | interrupt: interruptsAtTimeout(news), |
| 2266 | }); |
| 2267 | |
| 2268 | const createFunctionRequest: CreateFunctionRequest = { |
| 2269 | FunctionName: functionName, |
| 2270 | Role: roleArn, |
| 2271 | Code: codeLocation, |
| 2272 | ...(isFunctionImageProps(news) |
| 2273 | ? { |
| 2274 | PackageType: "Image" as const, |
| 2275 | ImageConfig: toLambdaImageConfig(news.image), |
| 2276 | } |
| 2277 | : { |
| 2278 | // Effect-mode functions are wrapped in a generated entry whose |
| 2279 | // ONLY export is `default` — `handler` names an export of the |
| 2280 | // USER's module and can only address it when the module is |
| 2281 | // bundled as-is (isExternal). Honoring it in Effect mode |
| 2282 | // deploys a Lambda that dies at init with |
| 2283 | // Runtime.HandlerNotFound. |
| 2284 | Handler: handlerStringOf(news), |
| 2285 | Runtime: news.runtime ?? "nodejs24.x", |
| 2286 | PackageType: "Zip" as const, |
| 2287 | }), |
| 2288 | Architectures: [news.architecture ?? "x86_64"], |
| 2289 | // Defaults are explicit so removing the prop (or repairing drift on |
| 2290 | // a function that never set it) converges back to AWS's default; |
| 2291 | // `UpdateFunctionConfiguration` treats omitted fields as "leave as-is". |
| 2292 | MemorySize: news.memorySize ?? 128, |
| 2293 | // Always explicit: `UpdateFunctionConfiguration` treats an omitted |
| 2294 | // `Layers` as "leave as-is", so removing the prop would strand the |
| 2295 | // previously-attached layers. |
| 2296 | Layers: isFunctionImageProps(news) |
| 2297 | ? undefined |
| 2298 | : (news.layers ?? []).map(layerVersionArnOf), |
| 2299 | Environment: { |
| 2300 | Variables: { |
| 2301 | ...runtimeEnv, |
| 2302 | ...alchemyEnv, |
| 2303 | ...timeoutGraceEnv(lambdaTimeout.graceMs), |
| 2304 | ...responseStreamEnv(news.functionUrl), |
| 2305 | }, |
| 2306 | }, |
| 2307 | Tags: tags, |
| 2308 | Timeout: lambdaTimeout.timeoutSeconds, |
| 2309 | // Always explicit so removing the `tracing` prop converges back to |
| 2310 | // the AWS default on update. |
| 2311 | TracingConfig: { Mode: news.tracing ?? "PassThrough" }, |
| 2312 | // Durability is create-time-only; a presence flip is a replacement |
| 2313 | // (see `diff`), so passing the same value on update is a no-op. |
| 2314 | DurableConfig: news.durableConfig, |
| 2315 | VpcConfig: vpc |
| 2316 | ? { |
| 2317 | SubnetIds: vpc.subnetIds, |
| 2318 | SecurityGroupIds: vpc.securityGroupIds, |
| 2319 | } |
| 2320 | : undefined, |
| 2321 | FileSystemConfigs: fileSystemConfigs, |
| 2322 | }; |
| 2323 | |
| 2324 | // Update an existing function in place. Only an engine-admitted |
| 2325 | // function reaches this directly — see `preferUpdate`. |
| 2326 | const update = Effect.gen(function* () { |
| 2327 | yield* Effect.logDebug(`updating function code ${id}`); |
| 2328 | yield* Lambda.updateFunctionCode({ |
| 2329 | FunctionName: createFunctionRequest.FunctionName, |
| 2330 | Architectures: createFunctionRequest.Architectures, |
| 2331 | ...codeLocation, |
| 2332 | }).pipe( |
| 2333 | Effect.tapError((e) => |
| 2334 | isRolePropagationError(e) ? noteCreateDependencyWait() : Effect.void, |
| 2335 | ), |
| 2336 | Effect.retry({ |
| 2337 | while: (e) => e._tag === "ResourceConflictException" || isRolePropagationError(e), |
| 2338 | schedule: Schedule.exponential(100), |
| 2339 | }), |
| 2340 | ); |
| 2341 | yield* Effect.logDebug(`updated function code ${id}`); |
| 2342 | const configured = yield* Lambda.updateFunctionConfiguration({ |
| 2343 | FunctionName: createFunctionRequest.FunctionName, |
| 2344 | DeadLetterConfig: createFunctionRequest.DeadLetterConfig, |
| 2345 | Description: createFunctionRequest.Description, |
| 2346 | Environment: createFunctionRequest.Environment, |
| 2347 | EphemeralStorage: createFunctionRequest.EphemeralStorage, |
| 2348 | FileSystemConfigs: createFunctionRequest.FileSystemConfigs, |
| 2349 | Handler: createFunctionRequest.Handler, |
| 2350 | ImageConfig: imageConfigForUpdate(news), |
| 2351 | KMSKeyArn: createFunctionRequest.KMSKeyArn, |
| 2352 | Layers: createFunctionRequest.Layers, |
| 2353 | LoggingConfig: createFunctionRequest.LoggingConfig, |
| 2354 | MemorySize: createFunctionRequest.MemorySize, |
| 2355 | // RevisionId: "???" |
| 2356 | Role: createFunctionRequest.Role, |
| 2357 | Runtime: createFunctionRequest.Runtime, |
| 2358 | SnapStart: createFunctionRequest.SnapStart, |
| 2359 | Timeout: createFunctionRequest.Timeout, |
| 2360 | TracingConfig: createFunctionRequest.TracingConfig, |
| 2361 | VpcConfig: createFunctionRequest.VpcConfig, |
| 2362 | DurableConfig: createFunctionRequest.DurableConfig, |
| 2363 | }).pipe( |
| 2364 | Effect.tapError((e) => |
| 2365 | isRolePropagationError(e) ? noteCreateDependencyWait() : Effect.void, |
| 2366 | ), |
| 2367 | Effect.retry({ |
| 2368 | while: (e) => e._tag === "ResourceConflictException" || isRolePropagationError(e), |
| 2369 | schedule: Schedule.exponential(100), |
| 2370 | }), |
| 2371 | ); |
| 2372 | yield* Effect.logDebug(`updated function configuration ${id}`); |
| 2373 | // An adopted function still carries its previous owner's tags. |
| 2374 | // Brand it from the observed tags, keeping any added out-of-band. |
| 2375 | if (configured.FunctionArn !== undefined) { |
| 2376 | const observed = yield* Lambda.listTags({ Resource: configured.FunctionArn }); |
| 2377 | if (!hasTags(tags, observed.Tags ?? {})) { |
| 2378 | yield* Lambda.tagResource({ Resource: configured.FunctionArn, Tags: tags }); |
| 2379 | } |
| 2380 | } |
| 2381 | }) as Effect.Effect<any, any, Credentials | Region | HttpClient>; |
| 2382 | |
| 2383 | const getAndUpdate = Lambda.getFunction({ |
| 2384 | FunctionName: functionName, |
| 2385 | }).pipe( |
| 2386 | // If it exists and contains these tags, we will assume it was created |
| 2387 | // by alchemy but state was lost, so if it exists, let's adopt it. |
| 2388 | // Some backends (e.g. local emulators) omit `Tags` on GetFunction — |
| 2389 | // fall back to ListTags before concluding the function is foreign. |
| 2390 | Effect.flatMap((f) => |
| 2391 | f.Tags !== undefined |
| 2392 | ? Effect.succeed(hasTags(tags, f.Tags)) |
| 2393 | : Lambda.listTags({ |
| 2394 | Resource: f.Configuration?.FunctionArn ?? "", |
| 2395 | }).pipe( |
| 2396 | Effect.map((r) => hasTags(tags, r.Tags ?? {})), |
| 2397 | Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(false)), |
| 2398 | ), |
| 2399 | ), |
| 2400 | Effect.filterOrFail( |
| 2401 | (owned) => owned, |
| 2402 | () => |
| 2403 | // TODO(sam): add custom |
| 2404 | new Error("Function tags do not match expected values"), |
| 2405 | ), |
| 2406 | Effect.andThen(update), |
| 2407 | ) as Effect.Effect<any, any, Credentials | Region | HttpClient>; |
| 2408 | |
| 2409 | const create = Lambda.createFunction(createFunctionRequest).pipe( |
| 2410 | Effect.tapError((e) => Effect.logDebug(e)), |
| 2411 | Effect.retry({ |
| 2412 | while: (e) => isRolePropagationError(e) || isSecurityGroupPropagationError(e), |
| 2413 | schedule: Schedule.fixed(1000).pipe(Schedule.tap(() => noteCreateDependencyWait())), |
| 2414 | }), |
| 2415 | Effect.catchTags({ |
| 2416 | ResourceConflictException: () => getAndUpdate, |
| 2417 | }), |
| 2418 | ) as Effect.Effect<any, any, Credentials | Region | HttpClient>; |
| 2419 | |
| 2420 | if (preferUpdate) { |
| 2421 | // The engine has admitted this function (`read`/`observe`, or |
| 2422 | // `--adopt`), so a foreign tag set is no reason to refuse. |
| 2423 | yield* update.pipe( |
| 2424 | Effect.catchTags({ |
| 2425 | ResourceNotFoundException: () => create, |
| 2426 | }), |
| 2427 | ); |
| 2428 | } else { |
| 2429 | yield* create; |
| 2430 | } |
| 2431 | }); |
| 2432 | |
| 2433 | const publicUrlAccessStatementId = "FunctionURLAllowPublicAccess"; |
| 2434 | const publicUrlInvokeStatementId = "FunctionURLAllowPublicInvoke"; |
| 2435 | |
| 2436 | const removePublicFunctionUrlPermissions = Effect.fn(function* ( |
| 2437 | functionName: string, |
| 2438 | qualifier: string | undefined, |
| 2439 | ) { |
| 2440 | yield* Effect.all( |
| 2441 | [ |
| 2442 | Lambda.removePermission({ |
| 2443 | FunctionName: functionName, |
| 2444 | Qualifier: qualifier, |
| 2445 | StatementId: publicUrlAccessStatementId, |
| 2446 | }).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)), |
| 2447 | Lambda.removePermission({ |
| 2448 | FunctionName: functionName, |
| 2449 | Qualifier: qualifier, |
| 2450 | StatementId: publicUrlInvokeStatementId, |
| 2451 | }).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)), |
| 2452 | ], |
| 2453 | { concurrency: "unbounded" }, |
| 2454 | ); |
| 2455 | }); |
| 2456 | |
| 2457 | const upsertPermission = (permission: Lambda.AddPermissionRequest) => |
| 2458 | Lambda.addPermission(permission).pipe( |
| 2459 | Effect.catchTag("ResourceConflictException", () => |
| 2460 | Effect.gen(function* () { |
| 2461 | yield* Lambda.removePermission({ |
| 2462 | FunctionName: permission.FunctionName, |
| 2463 | Qualifier: permission.Qualifier, |
| 2464 | StatementId: permission.StatementId, |
| 2465 | }).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)); |
| 2466 | yield* Lambda.addPermission(permission); |
| 2467 | }), |
| 2468 | ), |
| 2469 | retryFunctionMutation, |
| 2470 | ); |
| 2471 | |
| 2472 | const upsertPublicFunctionUrlPermissions = Effect.fn(function* ( |
| 2473 | functionName: string, |
| 2474 | qualifier: string | undefined, |
| 2475 | ) { |
| 2476 | yield* Effect.all( |
| 2477 | [ |
| 2478 | upsertPermission({ |
| 2479 | FunctionName: functionName, |
| 2480 | Qualifier: qualifier, |
| 2481 | StatementId: publicUrlAccessStatementId, |
| 2482 | Action: "lambda:InvokeFunctionUrl", |
| 2483 | Principal: "*", |
| 2484 | FunctionUrlAuthType: "NONE", |
| 2485 | }), |
| 2486 | upsertPermission({ |
| 2487 | FunctionName: functionName, |
| 2488 | Qualifier: qualifier, |
| 2489 | StatementId: publicUrlInvokeStatementId, |
| 2490 | Action: "lambda:InvokeFunction", |
| 2491 | Principal: "*", |
| 2492 | InvokedViaFunctionUrl: true, |
| 2493 | }), |
| 2494 | ], |
| 2495 | { concurrency: "unbounded" }, |
| 2496 | ); |
| 2497 | }); |
| 2498 | |
| 2499 | const deleteFunctionUrl = Effect.fn(function* ( |
| 2500 | functionName: string, |
| 2501 | qualifier: string | undefined, |
| 2502 | ) { |
| 2503 | yield* Effect.logDebug(`deleting function url config ${functionName}`); |
| 2504 | yield* Effect.all([ |
| 2505 | Lambda.deleteFunctionUrlConfig({ |
| 2506 | FunctionName: functionName, |
| 2507 | Qualifier: qualifier, |
| 2508 | }).pipe( |
| 2509 | retryFunctionMutation, |
| 2510 | Effect.catchTag("ResourceNotFoundException", () => Effect.void), |
| 2511 | ), |
| 2512 | removePublicFunctionUrlPermissions(functionName, qualifier), |
| 2513 | ]); |
| 2514 | yield* Effect.logDebug(`deleted function url config ${functionName}`); |
| 2515 | }); |
| 2516 | |
| 2517 | const createOrUpdateFunctionUrl = Effect.fn(function* ({ |
| 2518 | functionName, |
| 2519 | qualifier, |
| 2520 | previousQualifier, |
| 2521 | url, |
| 2522 | oldUrl, |
| 2523 | currentFunctionUrl, |
| 2524 | }: { |
| 2525 | functionName: string; |
| 2526 | /** Alias the URL is attached to; `undefined` for the unqualified function. */ |
| 2527 | qualifier: string | undefined; |
| 2528 | /** Alias the URL was attached to before this reconcile. */ |
| 2529 | previousQualifier: string | undefined; |
| 2530 | url: FunctionProps["functionUrl"]; |
| 2531 | oldUrl?: FunctionProps["functionUrl"]; |
| 2532 | currentFunctionUrl?: string; |
| 2533 | }) { |
| 2534 | const desired = normalizeFunctionUrl(url); |
| 2535 | const previous = normalizeFunctionUrl(oldUrl); |
| 2536 | const hadFunctionUrl = previous !== undefined || !!currentFunctionUrl; |
| 2537 | |
| 2538 | // A URL config belongs to one qualifier. Moving between the |
| 2539 | // unqualified function and an alias (or between aliases) retires the |
| 2540 | // old URL and its public permissions before the new one is created. |
| 2541 | if (hadFunctionUrl && previousQualifier !== qualifier) { |
| 2542 | yield* deleteFunctionUrl(functionName, previousQualifier); |
| 2543 | } |
| 2544 | |
| 2545 | if (desired) { |
| 2546 | yield* Effect.logDebug(`creating function url config ${functionName}`); |
| 2547 | const shouldClearCors = desired.cors === undefined && previous?.cors !== undefined; |
| 2548 | const config = { |
| 2549 | FunctionName: functionName, |
| 2550 | Qualifier: qualifier, |
| 2551 | AuthType: desired.authType, |
| 2552 | Cors: desired.cors ?? (shouldClearCors ? {} : undefined), |
| 2553 | InvokeMode: desired.invokeMode, |
| 2554 | } satisfies Lambda.CreateFunctionUrlConfigRequest | Lambda.UpdateFunctionUrlConfigRequest; |
| 2555 | const { FunctionUrl } = yield* Lambda.createFunctionUrlConfig(config).pipe( |
| 2556 | Effect.catchTag("ResourceConflictException", () => |
| 2557 | // An omitted Cors leaves the URL's CORS as-is; clear it so CORS |
| 2558 | // added out-of-band is removed. |
| 2559 | Lambda.updateFunctionUrlConfig({ ...config, Cors: config.Cors ?? {} }), |
| 2560 | ), |
| 2561 | retryFunctionMutation, |
| 2562 | ); |
| 2563 | |
| 2564 | if (desired.authType === "NONE") { |
| 2565 | yield* upsertPublicFunctionUrlPermissions(functionName, qualifier); |
| 2566 | } else { |
| 2567 | yield* removePublicFunctionUrlPermissions(functionName, qualifier); |
| 2568 | } |
| 2569 | |
| 2570 | yield* Effect.logDebug(`created function url config ${functionName}`); |
| 2571 | return FunctionUrl; |
| 2572 | } else if (hadFunctionUrl) { |
| 2573 | yield* deleteFunctionUrl(functionName, qualifier); |
| 2574 | } |
| 2575 | return undefined; |
| 2576 | }); |
| 2577 | |
| 2578 | /** |
| 2579 | * Publish the settled `$LATEST` as a version and point `alias` at it. |
| 2580 | * Lambda hands back the latest version when nothing changed since it |
| 2581 | * was published, so an unchanged deploy publishes nothing new. |
| 2582 | */ |
| 2583 | const syncAlias = Effect.fn(function* ({ |
| 2584 | functionName, |
| 2585 | functionArn, |
| 2586 | alias, |
| 2587 | }: { |
| 2588 | functionName: string; |
| 2589 | functionArn: string; |
| 2590 | alias: string; |
| 2591 | }) { |
| 2592 | const deleteHint = `Delete versions no alias serves (\`aws lambda list-versions-by-function --function-name ${functionName}\`, then \`aws lambda delete-function --function-name ${functionName} --qualifier <version>\`)`; |
| 2593 | const published = yield* Lambda.publishVersion({ FunctionName: functionName }).pipe( |
| 2594 | retryFunctionMutation, |
| 2595 | Effect.catchTags({ |
| 2596 | CodeStorageExceededException: (cause) => |
| 2597 | Effect.fail( |
| 2598 | new FunctionAliasPublishFailed({ |
| 2599 | functionName, |
| 2600 | alias, |
| 2601 | reason: "CodeStorageExceeded", |
| 2602 | message: `Cannot publish a version of ${functionName} for alias "${alias}": the account's Lambda code storage quota is full (${cause.message ?? "CodeStorageExceededException"}). Published versions are retained. ${deleteHint} or request a code storage quota increase.`, |
| 2603 | }), |
| 2604 | ), |
| 2605 | FunctionVersionsPerCapacityProviderLimitExceededException: (cause) => |
| 2606 | Effect.fail( |
| 2607 | new FunctionAliasPublishFailed({ |
| 2608 | functionName, |
| 2609 | alias, |
| 2610 | reason: "VersionLimitExceeded", |
| 2611 | message: `Cannot publish a version of ${functionName} for alias "${alias}": its capacity provider has reached its version limit (${cause.message ?? "FunctionVersionsPerCapacityProviderLimitExceededException"}). ${deleteHint}.`, |
| 2612 | }), |
| 2613 | ), |
| 2614 | }), |
| 2615 | ); |
| 2616 | const version = published.Version!; |
| 2617 | const desired = { |
| 2618 | FunctionName: functionName, |
| 2619 | Name: alias, |
| 2620 | FunctionVersion: version, |
| 2621 | // Clears weights another tool may have added; the alias serves |
| 2622 | // exactly the version this deploy published. |
| 2623 | RoutingConfig: { AdditionalVersionWeights: {} }, |
| 2624 | }; |
| 2625 | const observed = yield* Lambda.getAlias({ FunctionName: functionName, Name: alias }).pipe( |
| 2626 | Effect.catchTag("ResourceNotFoundException", () => Effect.undefined), |
| 2627 | ); |
| 2628 | if (observed === undefined) { |
| 2629 | yield* Lambda.createAlias({ |
| 2630 | FunctionName: functionName, |
| 2631 | Name: alias, |
| 2632 | FunctionVersion: version, |
| 2633 | }).pipe( |
| 2634 | // Created by a concurrent or interrupted reconcile. |
| 2635 | Effect.catchTag("ResourceConflictException", () => Lambda.updateAlias(desired)), |
| 2636 | retryFunctionMutation, |
| 2637 | Effect.catchTag("AliasLimitExceededException", (cause) => |
| 2638 | Effect.fail( |
| 2639 | new FunctionAliasPublishFailed({ |
| 2640 | functionName, |
| 2641 | alias, |
| 2642 | reason: "AliasLimitExceeded", |
| 2643 | message: `Cannot create alias "${alias}" on ${functionName}: the function has reached Lambda's alias limit (${cause.message ?? "AliasLimitExceededException"}). Delete aliases it no longer uses (\`aws lambda list-aliases --function-name ${functionName}\`, then \`aws lambda delete-alias --function-name ${functionName} --name <alias>\`).`, |
| 2644 | }), |
| 2645 | ), |
| 2646 | ), |
| 2647 | ); |
| 2648 | } else if ( |
| 2649 | observed.FunctionVersion !== version || |
| 2650 | Object.keys(observed.RoutingConfig?.AdditionalVersionWeights ?? {}).length > 0 |
| 2651 | ) { |
| 2652 | yield* Lambda.updateAlias(desired).pipe(retryFunctionMutation); |
| 2653 | } |
| 2654 | return { version, qualifiedArn: `${functionArn}:${alias}` }; |
| 2655 | }); |
| 2656 | |
| 2657 | const deleteAlias = (functionName: string, alias: string) => |
| 2658 | Lambda.deleteAlias({ FunctionName: functionName, Name: alias }).pipe( |
| 2659 | retryFunctionMutation, |
| 2660 | Effect.catchTag("ResourceNotFoundException", () => Effect.void), |
| 2661 | ); |
| 2662 | |
| 2663 | const summary = (code: FunctionDeploymentCode) => |
| 2664 | code.packageType === "Image" |
| 2665 | ? code.imageUri |
| 2666 | : code.archive.length >= 1024 * 1024 |
| 2667 | ? `${(code.archive.length / (1024 * 1024)).toFixed(2)}MB` |
| 2668 | : code.archive.length >= 1024 |
| 2669 | ? `${(code.archive.length / 1024).toFixed(2)}KB` |
| 2670 | : `${code.archive.length}B`; |
| 2671 | |
| 2672 | const refreshPersistedFunctionCode = ({ |
| 2673 | output, |
| 2674 | packageType, |
| 2675 | observed, |
| 2676 | }: { |
| 2677 | output: Function["Attributes"] | undefined; |
| 2678 | packageType: Lambda.PackageType | undefined; |
| 2679 | observed: |
| 2680 | | { |
| 2681 | ImageUri?: string; |
| 2682 | ResolvedImageUri?: string; |
| 2683 | } |
| 2684 | | undefined; |
| 2685 | }): Function["Attributes"]["code"] => { |
| 2686 | if (output?.code === undefined) { |
| 2687 | // Cold adoption has no persisted source hash. Return a complete |
| 2688 | // Attributes shape and let the forced post-adoption reconcile write |
| 2689 | // the desired code and replace this placeholder. |
| 2690 | return { hash: "" }; |
| 2691 | } |
| 2692 | if (packageType !== "Image" || output.code.image === undefined) { |
| 2693 | return output.code; |
| 2694 | } |
| 2695 | |
| 2696 | // Lambda can refresh the deployed URI and digest, but it cannot |
| 2697 | // reconstruct Alchemy's source hash or prove repository ownership. |
| 2698 | // Preserve that metadata from state instead of inferring a managed |
| 2699 | // repository from an arbitrary image during adoption. |
| 2700 | const resolvedImageUri = observed?.ResolvedImageUri; |
| 2701 | const digest = resolvedImageUri?.split("@").at(-1); |
| 2702 | return { |
| 2703 | ...output.code, |
| 2704 | image: { |
| 2705 | ...output.code.image, |
| 2706 | ...(observed?.ImageUri === undefined ? {} : { imageUri: observed.ImageUri }), |
| 2707 | ...(resolvedImageUri === undefined ? {} : { resolvedImageUri }), |
| 2708 | ...(digest === undefined ? {} : { digest }), |
| 2709 | }, |
| 2710 | }; |
| 2711 | }; |
| 2712 | |
| 2713 | return { |
| 2714 | stables: ["functionArn", "functionName", "roleName", "qualifiedArn", "aliasName"], |
| 2715 | diff: Effect.fn(function* ({ id, olds, news: desired, output, oldBindings, newBindings }) { |
| 2716 | // Effect-native runtime exports remain unevaluated during planning. |
| 2717 | // Their identity is represented by the bundle hash, so they must not |
| 2718 | // prevent source changes from reaching the hash comparison below. |
| 2719 | const news = |
| 2720 | typeof desired === "object" && desired !== null && "exports" in desired |
| 2721 | ? ({ |
| 2722 | ...desired, |
| 2723 | exports: stripEffects(desired.exports), |
| 2724 | } as typeof desired) |
| 2725 | : desired; |
| 2726 | if (!isResolved(news)) return; |
| 2727 | yield* validateFunctionPackageProps(id, news); |
| 2728 | if (isFunctionImageProps(news)) { |
| 2729 | yield* decodeFunctionImageSource(id, news.image); |
| 2730 | } |
| 2731 | // If output is undefined (resource in creating state), defer to default diff |
| 2732 | if (!output) { |
| 2733 | return undefined; |
| 2734 | } |
| 2735 | // Auto-generated names are engine-owned: the deployed name stays |
| 2736 | // authoritative even if the generator would name this id |
| 2737 | // differently today. Only an explicit user-provided functionName |
| 2738 | // can force a replace. |
| 2739 | const newFunctionName = news.functionName ?? output.functionName; |
| 2740 | if (output.functionName !== newFunctionName) { |
| 2741 | // The new physical name differs from the deployed name, so it can |
| 2742 | // be created before dependents switch over and the old function is |
| 2743 | // deleted. delete-first is only needed by replacements that reuse |
| 2744 | // the same explicit name below. |
| 2745 | return { action: "replace" }; |
| 2746 | } |
| 2747 | if (isFunctionImageProps(olds) !== isFunctionImageProps(news)) { |
| 2748 | return { |
| 2749 | action: "replace", |
| 2750 | deleteFirst: news.functionName !== undefined, |
| 2751 | }; |
| 2752 | } |
| 2753 | if ( |
| 2754 | !isFunctionImageProps(olds) && |
| 2755 | !isFunctionImageProps(news) && |
| 2756 | !!olds.durableConfig !== !!news.durableConfig |
| 2757 | ) { |
| 2758 | // DurableConfig can only be enabled/disabled at CreateFunction — |
| 2759 | // switching a logical id between Function and DurableFunction (or |
| 2760 | // vice versa) must replace the physical function. |
| 2761 | return { |
| 2762 | action: "replace", |
| 2763 | deleteFirst: news.functionName !== undefined, |
| 2764 | }; |
| 2765 | } |
| 2766 | if (olds.alias !== news.alias) { |
| 2767 | // Consumers move to (or off) the alias: its ARN is not known |
| 2768 | // until reconcile publishes and creates it. |
| 2769 | return { action: "update", stables: ["functionArn", "functionName", "roleName"] }; |
| 2770 | } |
| 2771 | if ( |
| 2772 | !deepEqual( |
| 2773 | normalizeFunctionUrl(olds.functionUrl), |
| 2774 | normalizeFunctionUrl(news.functionUrl), |
| 2775 | ) |
| 2776 | ) { |
| 2777 | return { action: "update" }; |
| 2778 | } |
| 2779 | let imageIdentity: FunctionImageIdentity | undefined; |
| 2780 | let codeHash: string; |
| 2781 | if (isFunctionImageProps(news)) { |
| 2782 | imageIdentity = yield* functionImage.identity(id, news.image, news.architecture); |
| 2783 | codeHash = imageIdentity.hash; |
| 2784 | } else { |
| 2785 | codeHash = (yield* bundleCode(id, news)).identityHash; |
| 2786 | } |
| 2787 | if (output.code.hash !== codeHash) { |
| 2788 | // code changed |
| 2789 | return { action: "update" }; |
| 2790 | } |
| 2791 | if (isFunctionImageProps(news)) { |
| 2792 | const image = output.code.image; |
| 2793 | if ( |
| 2794 | image === undefined || |
| 2795 | image.source !== imageIdentity?.source || |
| 2796 | (imageIdentity?.source === "uri" |
| 2797 | ? image.imageUri !== imageIdentity.imageUri || |
| 2798 | image.resolvedImageUri !== imageIdentity.resolvedImageUri |
| 2799 | : image.imageUri !== `${image.repositoryUri}:${codeHash}` || |
| 2800 | !(yield* functionImage.isReady(id, image.repositoryName, codeHash))) |
| 2801 | ) { |
| 2802 | return { action: "update" }; |
| 2803 | } |
| 2804 | if ( |
| 2805 | isFunctionImageProps(olds) && |
| 2806 | !deepEqual(toLambdaImageConfig(olds.image), toLambdaImageConfig(news.image)) |
| 2807 | ) { |
| 2808 | return { action: "update" }; |
| 2809 | } |
| 2810 | } |
| 2811 | if (toDurationMillis(olds.timeout) !== toDurationMillis(news.timeout)) { |
| 2812 | return { action: "update" }; |
| 2813 | } |
| 2814 | if (toDurationMillis(olds.timeoutMargin) !== toDurationMillis(news.timeoutMargin)) { |
| 2815 | return { action: "update" }; |
| 2816 | } |
| 2817 | if (olds.architecture !== news.architecture) { |
| 2818 | return { action: "update" }; |
| 2819 | } |
| 2820 | if (olds.reservedConcurrentExecutions !== news.reservedConcurrentExecutions) { |
| 2821 | return { action: "update" }; |
| 2822 | } |
| 2823 | // `layers` accepts a LayerVersion resource or a raw ARN, and the |
| 2824 | // two forms are structurally different props even when they name |
| 2825 | // the same layer. Compare them normalized so switching between the |
| 2826 | // forms isn't a phantom change; everything else still falls through |
| 2827 | // to the engine's default props comparison. |
| 2828 | const normalizeLayers = (props: FunctionProps) => ({ |
| 2829 | ...props, |
| 2830 | layers: (props.layers ?? []).map(layerVersionArnOf), |
| 2831 | }); |
| 2832 | if (!havePropsChanged(normalizeLayers(olds), normalizeLayers(news))) { |
| 2833 | // Bindings (env / policies from `bind`) are not props. An explicit |
| 2834 | // noop would skip the engine's binding comparison, so defer to it |
| 2835 | // whenever they may have changed. |
| 2836 | if (!isResolved(newBindings) || !deepEqual(oldBindings, newBindings)) { |
| 2837 | return undefined; |
| 2838 | } |
| 2839 | return { action: "noop" }; |
| 2840 | } |
| 2841 | }), |
| 2842 | read: Effect.fn(function* ({ id, olds, output }) { |
| 2843 | const functionName = |
| 2844 | output?.functionName ?? (yield* createFunctionName(id, olds?.functionName)); |
| 2845 | yield* Effect.logDebug(`reading function ${functionName}`); |
| 2846 | const result = yield* Lambda.getFunction({ |
| 2847 | FunctionName: functionName, |
| 2848 | }).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 2849 | const fn = result?.Configuration; |
| 2850 | if (!fn?.FunctionArn || !fn.FunctionName || !fn.Role) { |
| 2851 | return undefined; |
| 2852 | } |
| 2853 | const tagsResult = yield* Lambda.listTags({ |
| 2854 | Resource: fn.FunctionArn, |
| 2855 | }).pipe( |
| 2856 | Effect.map((r) => r.Tags ?? {}), |
| 2857 | Effect.catchTag("ResourceNotFoundException", () => |
| 2858 | Effect.succeed({} as Record<string, string>), |
| 2859 | ), |
| 2860 | ); |
| 2861 | const aliasName = olds?.alias ?? output?.aliasName; |
| 2862 | const alias = aliasName |
| 2863 | ? yield* Lambda.getAlias({ FunctionName: fn.FunctionName, Name: aliasName }).pipe( |
| 2864 | Effect.catchTag("ResourceNotFoundException", () => Effect.undefined), |
| 2865 | ) |
| 2866 | : undefined; |
| 2867 | const roleName = output?.roleName ?? fn.Role.split("/").pop()!; |
| 2868 | const observed = yield* observeFunctionConfiguration({ |
| 2869 | id, |
| 2870 | configuration: fn, |
| 2871 | qualifier: alias?.Name, |
| 2872 | roleName, |
| 2873 | logging: olds?.logging, |
| 2874 | }); |
| 2875 | const functionUrl = yield* readFunctionUrlConfig(fn.FunctionName, alias?.Name).pipe( |
| 2876 | Effect.map((config) => config?.FunctionUrl), |
| 2877 | ); |
| 2878 | const reservedConcurrentExecutions = yield* getReservedConcurrentExecutions( |
| 2879 | fn.FunctionName, |
| 2880 | ); |
| 2881 | // Reuse the persisted output where we have it (e.g. code hash) so |
| 2882 | // diff doesn't see drift it can't reconstruct from the API. |
| 2883 | const attrs = { |
| 2884 | ...output, |
| 2885 | ...observed, |
| 2886 | functionArn: fn.FunctionArn, |
| 2887 | functionName: fn.FunctionName, |
| 2888 | qualifiedArn: alias?.AliasArn ?? fn.FunctionArn, |
| 2889 | aliasName: alias?.Name, |
| 2890 | version: alias?.FunctionVersion, |
| 2891 | functionUrl, |
| 2892 | roleArn: fn.Role, |
| 2893 | roleName, |
| 2894 | code: refreshPersistedFunctionCode({ |
| 2895 | output, |
| 2896 | packageType: fn.PackageType, |
| 2897 | observed: result?.Code, |
| 2898 | }), |
| 2899 | reservedConcurrentExecutions, |
| 2900 | } satisfies Function["Attributes"]; |
| 2901 | return (yield* hasAlchemyTags(id, tagsResult)) ? attrs : Unowned(attrs); |
| 2902 | }), |
| 2903 | // Account/region collection: exhaustively paginate `listFunctions` |
| 2904 | // (its `Functions` items are `FunctionConfiguration`s, the same shape |
| 2905 | // `read` pulls from `getFunction().Configuration`), then hydrate each |
| 2906 | // into the exact `read` Attributes shape with a bounded fan-out. The |
| 2907 | // code hash is not recoverable from the API (it lives in persisted |
| 2908 | // state), so it is left empty — `delete`/nuke only needs the |
| 2909 | // function/role identifiers. |
| 2910 | list: () => |
| 2911 | Effect.gen(function* () { |
| 2912 | const configs = yield* Lambda.listFunctions.items({}).pipe( |
| 2913 | Stream.runCollect, |
| 2914 | Effect.map((chunk) => Array.from(chunk)), |
| 2915 | ); |
| 2916 | const rows = yield* Effect.forEach( |
| 2917 | configs, |
| 2918 | (fn) => |
| 2919 | Effect.gen(function* () { |
| 2920 | if (!fn.FunctionArn || !fn.FunctionName || !fn.Role) { |
| 2921 | return undefined; |
| 2922 | } |
| 2923 | const functionUrl = yield* Lambda.getFunctionUrlConfig({ |
| 2924 | FunctionName: fn.FunctionName, |
| 2925 | }).pipe( |
| 2926 | Effect.map((f) => f.FunctionUrl), |
| 2927 | // No URL config (or the function vanished between the |
| 2928 | // list and the hydrate) — surface `undefined`, matching |
| 2929 | // `read`. |
| 2930 | Effect.catchTag("ResourceNotFoundException", () => Effect.undefined), |
| 2931 | ); |
| 2932 | const reservedConcurrentExecutions = yield* getReservedConcurrentExecutions( |
| 2933 | fn.FunctionName, |
| 2934 | ); |
| 2935 | return { |
| 2936 | functionArn: fn.FunctionArn, |
| 2937 | functionName: fn.FunctionName, |
| 2938 | qualifiedArn: fn.FunctionArn, |
| 2939 | functionUrl, |
| 2940 | roleArn: fn.Role, |
| 2941 | roleName: fn.Role.split("/").pop()!, |
| 2942 | code: { hash: "" }, |
| 2943 | ...(reservedConcurrentExecutions === undefined |
| 2944 | ? {} |
| 2945 | : { reservedConcurrentExecutions }), |
| 2946 | ...(fn.MemorySize === undefined ? {} : { memorySize: fn.MemorySize }), |
| 2947 | ...(fn.Timeout === undefined ? {} : { timeoutSeconds: fn.Timeout }), |
| 2948 | } satisfies Function["Attributes"]; |
| 2949 | }), |
| 2950 | { concurrency: 10 }, |
| 2951 | ); |
| 2952 | return rows.filter((row): row is Function["Attributes"] => row !== undefined); |
| 2953 | }), |
| 2954 | |
| 2955 | observe: Effect.fn(function* ({ id, news }) { |
| 2956 | // Precreate creates — or updates — the function named here. Its |
| 2957 | // execution role is named from the logical id alone. |
| 2958 | if (!isResolved(news.functionName)) return Unresolved; |
| 2959 | const functionName = yield* createFunctionName(id, news.functionName); |
| 2960 | const result = yield* Lambda.getFunction({ FunctionName: functionName }).pipe( |
| 2961 | Effect.catchTag("ResourceNotFoundException", () => Effect.undefined), |
| 2962 | ); |
| 2963 | const functionArn = result?.Configuration?.FunctionArn; |
| 2964 | if (functionArn === undefined) return undefined; |
| 2965 | const tags = yield* Lambda.listTags({ Resource: functionArn }).pipe( |
| 2966 | Effect.map((r) => r.Tags ?? {}), |
| 2967 | Effect.catchTag("ResourceNotFoundException", () => |
| 2968 | Effect.succeed({} as Record<string, string>), |
| 2969 | ), |
| 2970 | ); |
| 2971 | const observed = { functionArn, functionName }; |
| 2972 | return (yield* hasAlchemyTags(id, tags)) ? observed : Unowned(observed); |
| 2973 | }), |
| 2974 | precreate: Effect.fn(function* ({ id, news, session }) { |
| 2975 | if (!isResolved(news.functionName)) { |
| 2976 | return yield* new UnresolvedIdentity({ |
| 2977 | message: |
| 2978 | `Function(${id}): \`functionName\` depends on a resource in this ` + |
| 2979 | "Function's dependency cycle, so precreate cannot name the function. " + |
| 2980 | "Use a literal name, or one from outside the cycle.", |
| 2981 | resourceType: "AWS.Lambda.Function", |
| 2982 | logicalId: id, |
| 2983 | }); |
| 2984 | } |
| 2985 | yield* validateFunctionPackageProps(id, news); |
| 2986 | if (isFunctionImageProps(news)) { |
| 2987 | // Resolve and validate the image before creating the execution |
| 2988 | // role. External references perform only ECR reads here; local |
| 2989 | // sources only hash their build inputs. A bad URI, wrong region, |
| 2990 | // inaccessible image, or invalid build source therefore cannot |
| 2991 | // strand an IAM role when pre-create fails before persisting state. |
| 2992 | yield* functionImage.identity(id, news.image, news.architecture); |
| 2993 | } |
| 2994 | const { accountId, region } = yield* AWSEnvironment.current; |
| 2995 | const { roleName, functionName, roleArn } = yield* createNames(id, news.functionName); |
| 2996 | |
| 2997 | const role = yield* createRoleIfNotExists({ |
| 2998 | id, |
| 2999 | roleName, |
| 3000 | vpc: news.vpc, |
| 3001 | }); |
| 3002 | yield* syncLogGroupGuard({ roleName, functionName }); |
| 3003 | yield* ensureLogGroup({ id, functionName, retention: news.logging?.retention }); |
| 3004 | |
| 3005 | const prepared = yield* preparePrecreatedFunctionCode({ |
| 3006 | id, |
| 3007 | props: news, |
| 3008 | session, |
| 3009 | }); |
| 3010 | |
| 3011 | yield* createOrUpdateFunction({ |
| 3012 | id, |
| 3013 | news, |
| 3014 | roleArn: role.Role.Arn, |
| 3015 | code: prepared.deployment, |
| 3016 | functionName, |
| 3017 | env: alchemyEnv, |
| 3018 | session, |
| 3019 | // `observe` (or `read`) has already admitted an existing function. |
| 3020 | preferUpdate: true, |
| 3021 | }); |
| 3022 | |
| 3023 | const functionArn = `arn:aws:lambda:${region}:${accountId}:function:${functionName}`; |
| 3024 | // Consumers in a cycle with this Function wire the alias before |
| 3025 | // reconcile runs, so the alias must already exist (serving the |
| 3026 | // stub until reconcile advances it). |
| 3027 | const alias = |
| 3028 | typeof news.alias === "string" |
| 3029 | ? yield* syncAlias({ functionName, functionArn, alias: news.alias }) |
| 3030 | : undefined; |
| 3031 | |
| 3032 | return { |
| 3033 | functionArn, |
| 3034 | functionName, |
| 3035 | qualifiedArn: alias?.qualifiedArn ?? functionArn, |
| 3036 | aliasName: alias === undefined ? undefined : news.alias, |
| 3037 | version: alias?.version, |
| 3038 | functionUrl: undefined, |
| 3039 | roleName, |
| 3040 | code: prepared.attributes, |
| 3041 | roleArn, |
| 3042 | }; |
| 3043 | }), |
| 3044 | reconcile: Effect.fn(function* ({ id, news, olds, bindings, output, session }) { |
| 3045 | yield* validateFunctionPackageProps(id, news); |
| 3046 | if (isFunctionImageProps(news)) { |
| 3047 | yield* decodeFunctionImageSource(id, news.image); |
| 3048 | } |
| 3049 | const generated = yield* createNames(id, news.functionName); |
| 3050 | // Prefer the deployed identifiers: regenerating would target |
| 3051 | // different physical resources if the generator's output for this |
| 3052 | // id ever drifts. (An explicit functionName change arrives here as |
| 3053 | // a fresh replacement instance with no output.) |
| 3054 | const functionName = output?.functionName ?? generated.functionName; |
| 3055 | const roleName = output?.roleName ?? generated.roleName; |
| 3056 | const functionArn = output?.functionArn ?? generated.functionArn; |
| 3057 | const policyName = generated.policyName; |
| 3058 | |
| 3059 | // State is only a cache: the execution role may have been removed |
| 3060 | // out-of-band (or by a previously interrupted cleanup) while the |
| 3061 | // function output remains persisted. Always observe/ensure the |
| 3062 | // deterministic role before syncing binding policies so reconcile |
| 3063 | // can recover from that partial state instead of failing the first |
| 3064 | // `putRolePolicy` with `NoSuchEntityException`. |
| 3065 | const ensuredRole = yield* createRoleIfNotExists({ |
| 3066 | id, |
| 3067 | roleName, |
| 3068 | vpc: news.vpc, |
| 3069 | }); |
| 3070 | const roleArn = ensuredRole.Role.Arn ?? output?.roleArn; |
| 3071 | yield* syncLogGroupGuard({ roleName, functionName }); |
| 3072 | yield* ensureLogGroup({ id, functionName, retention: news.logging?.retention }); |
| 3073 | |
| 3074 | const { |
| 3075 | env, |
| 3076 | vpc: bindingVpc, |
| 3077 | fileSystemConfigs: bindingFileSystemConfigs, |
| 3078 | } = yield* attachBindings({ |
| 3079 | roleName, |
| 3080 | policyName, |
| 3081 | functionArn, |
| 3082 | functionName, |
| 3083 | bindings, |
| 3084 | }); |
| 3085 | |
| 3086 | // Both VPC paths (the `vpc` prop and binding-channel requests) |
| 3087 | // converge on one Lambda VPC config: set-union of subnets and |
| 3088 | // security groups. |
| 3089 | const vpc = |
| 3090 | news.vpc || bindingVpc |
| 3091 | ? { |
| 3092 | subnetIds: [ |
| 3093 | ...new Set([...(news.vpc?.subnetIds ?? []), ...(bindingVpc?.subnetIds ?? [])]), |
| 3094 | ], |
| 3095 | securityGroupIds: [ |
| 3096 | ...new Set([ |
| 3097 | ...(news.vpc?.securityGroupIds ?? []), |
| 3098 | ...(bindingVpc?.securityGroupIds ?? []), |
| 3099 | ]), |
| 3100 | ], |
| 3101 | } |
| 3102 | : undefined; |
| 3103 | |
| 3104 | // The role may predate the VPC request (precreate stub, or a |
| 3105 | // binding newly asking for attachment) — the ENI permissions must |
| 3106 | // be on the role before the function config references the VPC. |
| 3107 | // Attaching is idempotent. |
| 3108 | if (vpc) { |
| 3109 | yield* iam.attachRolePolicy({ |
| 3110 | RoleName: roleName, |
| 3111 | PolicyArn: "arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole", |
| 3112 | }); |
| 3113 | } |
| 3114 | |
| 3115 | yield* syncTracingPolicy({ |
| 3116 | roleName, |
| 3117 | tracing: news.tracing, |
| 3118 | // Routine update from Active, or adoption (output without olds) |
| 3119 | // where the prior tracing mode is unknown. |
| 3120 | mayHaveBeenActive: |
| 3121 | olds?.tracing === "Active" || (olds === undefined && output !== undefined), |
| 3122 | }); |
| 3123 | |
| 3124 | // Desired EFS mounts: the `fileSystemConfigs` prop (access-point |
| 3125 | // references resolved to ARNs) merged with binding-channel |
| 3126 | // requests (`EFS.Mount`), deduped by mount path. |
| 3127 | const desiredFileSystemConfigs = [ |
| 3128 | ...new Map( |
| 3129 | [ |
| 3130 | ...(news.fileSystemConfigs ?? []).map((c) => { |
| 3131 | const arn = accessPointArnOf(c); |
| 3132 | if (arn === undefined) { |
| 3133 | throw new Error( |
| 3134 | `Function(${id}): fileSystemConfigs entry for ${c.localMountPath} needs an access point — set \`accessPoint\` (an AWS.EFS.AccessPoint resource or its ARN) or \`arn\``, |
| 3135 | ); |
| 3136 | } |
| 3137 | return { Arn: arn, LocalMountPath: c.localMountPath }; |
| 3138 | }), |
| 3139 | ...bindingFileSystemConfigs.map((c) => ({ |
| 3140 | Arn: c.arn, |
| 3141 | LocalMountPath: c.localMountPath, |
| 3142 | })), |
| 3143 | ].map((config) => [config.LocalMountPath, config] as const), |
| 3144 | ).values(), |
| 3145 | ]; |
| 3146 | |
| 3147 | // EFS mounts authenticate the execution role against the access |
| 3148 | // point at sandbox start — grant client access before the function |
| 3149 | // configuration references the file system. Attaching is |
| 3150 | // idempotent; the policy is detached with the rest on delete. |
| 3151 | if (desiredFileSystemConfigs.length > 0) { |
| 3152 | yield* iam.attachRolePolicy({ |
| 3153 | RoleName: roleName, |
| 3154 | PolicyArn: "arn:aws:iam::aws:policy/AmazonElasticFileSystemClientReadWriteAccess", |
| 3155 | }); |
| 3156 | } |
| 3157 | |
| 3158 | const prepared = yield* prepareFunctionCode({ |
| 3159 | id, |
| 3160 | props: news, |
| 3161 | previousImage: output?.code?.image, |
| 3162 | session, |
| 3163 | }); |
| 3164 | |
| 3165 | yield* createOrUpdateFunction({ |
| 3166 | id, |
| 3167 | news, |
| 3168 | roleArn, |
| 3169 | code: prepared.deployment, |
| 3170 | env: { |
| 3171 | ...env, |
| 3172 | ...news.env, |
| 3173 | }, |
| 3174 | functionName, |
| 3175 | // On update an omitted VpcConfig means "leave as-is"; detach |
| 3176 | // explicitly so a VPC attached out-of-band is removed. |
| 3177 | vpc: |
| 3178 | vpc ?? (output !== undefined ? { subnetIds: [], securityGroupIds: [] } : undefined), |
| 3179 | preferUpdate: output !== undefined, |
| 3180 | // `[]` (when the prop/bindings were removed on a function that |
| 3181 | // previously had mounts) explicitly clears the file-system |
| 3182 | // config; `undefined` when it never had any leaves it untouched. |
| 3183 | fileSystemConfigs: |
| 3184 | desiredFileSystemConfigs.length > 0 |
| 3185 | ? desiredFileSystemConfigs |
| 3186 | : olds?.fileSystemConfigs || output !== undefined |
| 3187 | ? [] |
| 3188 | : undefined, |
| 3189 | session, |
| 3190 | }).pipe( |
| 3191 | Effect.andThen(waitForFunctionUpdate(functionName, session, vpc !== undefined)), |
| 3192 | // The create/update call can succeed while Lambda's ASYNC |
| 3193 | // provisioning (VPC ENIs, EFS mounts) still fails with |
| 3194 | // `InsufficientRolePermissions` — "The function's execution role |
| 3195 | // doesn't have permission to perform this operation." — because |
| 3196 | // the just-attached AWSLambdaVPCAccessExecutionRole / |
| 3197 | // EFS client policy has not propagated yet. That is IAM eventual |
| 3198 | // consistency, not a misconfiguration: re-apply the function |
| 3199 | // (the create path falls through to update on conflict, which |
| 3200 | // re-triggers provisioning) and wait again, bounded. |
| 3201 | Effect.tapError((e) => |
| 3202 | e._tag === "FunctionUpdateFailed" && e.reasonCode === "InsufficientRolePermissions" |
| 3203 | ? session.note( |
| 3204 | `Waiting for Lambda execution role permissions to propagate: ${functionName}`, |
| 3205 | ) |
| 3206 | : Effect.void, |
| 3207 | ), |
| 3208 | Effect.retry({ |
| 3209 | while: (e) => |
| 3210 | e._tag === "FunctionUpdateFailed" && e.reasonCode === "InsufficientRolePermissions", |
| 3211 | schedule: Schedule.spaced("10 seconds"), |
| 3212 | times: 6, |
| 3213 | }), |
| 3214 | ); |
| 3215 | |
| 3216 | const previousImage = output?.code.image; |
| 3217 | const nextImage = "image" in prepared.attributes ? prepared.attributes.image : undefined; |
| 3218 | if ( |
| 3219 | previousImage?.ownsRepository === true && |
| 3220 | previousImage.repositoryUri !== nextImage?.repositoryUri |
| 3221 | ) { |
| 3222 | // Lambda has adopted the new image; the previous managed |
| 3223 | // repository is no longer referenced. |
| 3224 | yield* functionImage.deleteRepository(previousImage.repositoryName); |
| 3225 | } |
| 3226 | |
| 3227 | const reservedConcurrentExecutions = yield* syncReservedConcurrentExecutions({ |
| 3228 | functionName, |
| 3229 | reservedConcurrentExecutions: news.reservedConcurrentExecutions, |
| 3230 | }); |
| 3231 | |
| 3232 | // With an alias, every consumer invokes the alias: publish the |
| 3233 | // settled code as a version and advance the alias before the URL |
| 3234 | // and async-invoke config are attached to it. |
| 3235 | const alias = news.alias |
| 3236 | ? yield* syncAlias({ functionName, functionArn, alias: news.alias }) |
| 3237 | : undefined; |
| 3238 | const previousAlias = output?.aliasName; |
| 3239 | |
| 3240 | yield* syncEventInvokeConfig({ |
| 3241 | functionName, |
| 3242 | qualifier: news.alias, |
| 3243 | config: news.eventInvokeConfig, |
| 3244 | }); |
| 3245 | if (news.alias) { |
| 3246 | // The config moved to the alias; `$LATEST` falls back to defaults. |
| 3247 | yield* syncEventInvokeConfig({ functionName, config: undefined }); |
| 3248 | } |
| 3249 | |
| 3250 | const functionUrl = yield* createOrUpdateFunctionUrl({ |
| 3251 | functionName, |
| 3252 | qualifier: news.alias, |
| 3253 | previousQualifier: previousAlias, |
| 3254 | url: news.functionUrl, |
| 3255 | oldUrl: olds?.functionUrl, |
| 3256 | currentFunctionUrl: output?.functionUrl, |
| 3257 | }); |
| 3258 | |
| 3259 | // Consumers and the URL have moved off the previous alias. |
| 3260 | if (previousAlias !== undefined && previousAlias !== news.alias) { |
| 3261 | yield* deleteAlias(functionName, previousAlias); |
| 3262 | } |
| 3263 | |
| 3264 | yield* session.note(summary(prepared.deployment)); |
| 3265 | |
| 3266 | // Re-read rather than reuse the create/update response, which omits |
| 3267 | // settings such as `DurableConfig` that `read` observes. |
| 3268 | const observed = yield* observeFunctionConfiguration({ |
| 3269 | id, |
| 3270 | configuration: yield* Lambda.getFunctionConfiguration({ FunctionName: functionName }), |
| 3271 | qualifier: news.alias, |
| 3272 | roleName, |
| 3273 | logging: news.logging, |
| 3274 | }); |
| 3275 | |
| 3276 | return { |
| 3277 | ...output, |
| 3278 | functionArn, |
| 3279 | functionName, |
| 3280 | qualifiedArn: alias?.qualifiedArn ?? functionArn, |
| 3281 | aliasName: news.alias, |
| 3282 | version: alias?.version, |
| 3283 | functionUrl: functionUrl as any, |
| 3284 | domainUrl: functionDomainUrl(news.domain), |
| 3285 | roleName, |
| 3286 | roleArn, |
| 3287 | code: prepared.attributes, |
| 3288 | reservedConcurrentExecutions, |
| 3289 | ...observed, |
| 3290 | }; |
| 3291 | }), |
| 3292 | delete: Effect.fn(function* ({ output }) { |
| 3293 | // The role may already be gone (e.g. deleted out-of-band or by a |
| 3294 | // previous partial delete) — treat every step as idempotent. |
| 3295 | yield* iam |
| 3296 | .listRolePolicies({ |
| 3297 | RoleName: output.roleName, |
| 3298 | }) |
| 3299 | .pipe( |
| 3300 | Effect.flatMap((policies) => |
| 3301 | Effect.forEach( |
| 3302 | // The log-group guard stays until the function is deleted. |
| 3303 | (policies.PolicyNames ?? []).filter( |
| 3304 | (policyName) => policyName !== logGroupGuardPolicyName, |
| 3305 | ), |
| 3306 | (policyName) => |
| 3307 | iam |
| 3308 | .deleteRolePolicy({ |
| 3309 | RoleName: output.roleName, |
| 3310 | PolicyName: policyName, |
| 3311 | }) |
| 3312 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)), |
| 3313 | ), |
| 3314 | ), |
| 3315 | Effect.catchTag("NoSuchEntityException", () => Effect.void), |
| 3316 | ); |
| 3317 | |
| 3318 | yield* iam |
| 3319 | .listAttachedRolePolicies({ |
| 3320 | RoleName: output.roleName, |
| 3321 | }) |
| 3322 | .pipe( |
| 3323 | Effect.flatMap((policies) => |
| 3324 | Effect.forEach(policies.AttachedPolicies ?? [], (policy) => |
| 3325 | iam |
| 3326 | .detachRolePolicy({ |
| 3327 | RoleName: output.roleName, |
| 3328 | PolicyArn: policy.PolicyArn!, |
| 3329 | }) |
| 3330 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)), |
| 3331 | ), |
| 3332 | ), |
| 3333 | Effect.catchTag("NoSuchEntityException", () => Effect.void), |
| 3334 | ); |
| 3335 | |
| 3336 | yield* Lambda.deleteFunction({ |
| 3337 | FunctionName: output.functionName, |
| 3338 | }).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)); |
| 3339 | |
| 3340 | if (output.code.image?.ownsRepository) { |
| 3341 | // Lambda must release its image before the owned repository is |
| 3342 | // force-deleted. Both operations are idempotent, so an interrupted |
| 3343 | // destroy converges on the next run. |
| 3344 | yield* functionImage.deleteRepository(output.code.image.repositoryName); |
| 3345 | } |
| 3346 | |
| 3347 | // The managed policies were detached before deleteFunction, so the |
| 3348 | // role no longer allows logs:CreateLogGroup and the guard can go with |
| 3349 | // it. IAM can briefly report a just-detached role as still in use, so |
| 3350 | // retry those eventual-consistency conflicts on a bounded schedule. |
| 3351 | yield* iam |
| 3352 | .deleteRolePolicy({ RoleName: output.roleName, PolicyName: logGroupGuardPolicyName }) |
| 3353 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)); |
| 3354 | yield* iam.deleteRole({ RoleName: output.roleName }).pipe( |
| 3355 | Effect.catchTag("NoSuchEntityException", () => Effect.void), |
| 3356 | Effect.retry({ |
| 3357 | while: (error) => |
| 3358 | error._tag === "DeleteConflictException" || |
| 3359 | error._tag === "ConcurrentModificationException", |
| 3360 | schedule: Schedule.spaced("2 seconds"), |
| 3361 | times: 10, |
| 3362 | }), |
| 3363 | ); |
| 3364 | |
| 3365 | // Alchemy created /aws/lambda/<name> and the role could never |
| 3366 | // create it (see `syncLogGroupGuard`), so a late log flush after |
| 3367 | // deleteFunction is dropped instead of re-creating the group: one |
| 3368 | // delete is enough. |
| 3369 | yield* logs |
| 3370 | .deleteLogGroup({ logGroupName: `/aws/lambda/${output.functionName}` }) |
| 3371 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)); |
| 3372 | |
| 3373 | return null as any; |
| 3374 | }), |
| 3375 | tail: ({ output }) => { |
| 3376 | const runTailSession = Effect.gen(function* () { |
| 3377 | const { accountId, region } = yield* AWSEnvironment.current; |
| 3378 | |
| 3379 | const logGroupArn = `arn:aws:logs:${region}:${accountId}:log-group:/aws/lambda/${output.functionName}`; |
| 3380 | const response = yield* logs.startLiveTail({ |
| 3381 | logGroupIdentifiers: [logGroupArn], |
| 3382 | }); |
| 3383 | |
| 3384 | if (!response.responseStream) { |
| 3385 | return Stream.empty as Stream.Stream<LogLine>; |
| 3386 | } |
| 3387 | |
| 3388 | return response.responseStream.pipe( |
| 3389 | Stream.flatMap((event) => { |
| 3390 | if ("sessionUpdate" in event && event.sessionUpdate) { |
| 3391 | const lines: LogLine[] = (event.sessionUpdate.sessionResults ?? []).flatMap( |
| 3392 | (result) => { |
| 3393 | if (!result.message) return []; |
| 3394 | return [ |
| 3395 | { |
| 3396 | timestamp: new Date(result.timestamp ?? Date.now()), |
| 3397 | message: result.message.trimEnd(), |
| 3398 | }, |
| 3399 | ]; |
| 3400 | }, |
| 3401 | ); |
| 3402 | return Stream.fromIterable(lines); |
| 3403 | } |
| 3404 | return Stream.empty; |
| 3405 | }), |
| 3406 | ); |
| 3407 | }); |
| 3408 | |
| 3409 | return Stream.unwrap(runTailSession).pipe(Stream.retry(Schedule.spaced("1 second"))); |
| 3410 | }, |
| 3411 | logs: ({ output, options }: { output: Function["Attributes"]; options: LogsInput }) => |
| 3412 | logs |
| 3413 | .filterLogEvents({ |
| 3414 | logGroupName: `/aws/lambda/${output.functionName}`, |
| 3415 | startTime: options.since?.getTime(), |
| 3416 | limit: options.limit ?? 100, |
| 3417 | }) |
| 3418 | .pipe( |
| 3419 | Effect.map((response) => |
| 3420 | (response.events ?? []).flatMap((event): LogLine[] => { |
| 3421 | if (!event.message) return []; |
| 3422 | return [ |
| 3423 | { |
| 3424 | timestamp: new Date(event.timestamp ?? Date.now()), |
| 3425 | message: event.message.trimEnd(), |
| 3426 | }, |
| 3427 | ]; |
| 3428 | }), |
| 3429 | ), |
| 3430 | Effect.catchTag("ResourceNotFoundException", () => Effect.succeed([] as LogLine[])), |
| 3431 | ), |
| 3432 | }; |
| 3433 | }), |
| 3434 | ); |