diff --git a/.github/workflows/build-layer.yml b/.github/workflows/build-layer.yml index b1e0e3c..adb478b 100644 --- a/.github/workflows/build-layer.yml +++ b/.github/workflows/build-layer.yml @@ -51,7 +51,7 @@ jobs: run: | IFS='.' read -r MAJOR MINOR PATCH <<< "${{ inputs.version }}" PKG_MINOR=$((MAJOR * 10000 + MINOR * 100 + PATCH)) - echo "version=3.${PKG_MINOR}.0" >> "$GITHUB_OUTPUT" + echo "version=4.${PKG_MINOR}.0" >> "$GITHUB_OUTPUT" - name: Commit and create PR uses: peter-evans/create-pull-request@v8 @@ -70,8 +70,8 @@ jobs: - Updated `src/index.ts` version constant - Updated `README.md` version badge - The layer zip is built fresh during release — no binary committed. - Merging this PR will trigger the release workflow and publish `@beesolve/lambda-bun-runtime@${{ steps.pkg.outputs.version }}` to npm. + The layer zip is built fresh during release - no binary committed. + Merging this PR will trigger the release workflow: it publishes the public layer in all regions, runs the integration test against it and then publishes `@beesolve/lambda-bun-runtime@${{ steps.pkg.outputs.version }}` to npm. add-paths: | .bun-version src/index.ts diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 6434733..b838ddc 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -1,7 +1,12 @@ name: integration on: - workflow_call: {} + workflow_call: + inputs: + published-layer: + description: "Deploy the published layer (artifacts.json from the release run) instead of a layer built from source" + type: boolean + default: false workflow_dispatch: {} pull_request: paths: @@ -42,6 +47,23 @@ jobs: - run: bun install --frozen-lockfile + - name: Use the published layer + if: inputs.published-layer + uses: actions/download-artifact@v8 + with: + name: artifacts-json-first-region + path: src + + - name: Deploy the function on the published runtime too + if: inputs.published-layer + run: echo "BUN_CMR=1" >> "$GITHUB_ENV" + + - name: Build the layer from source + if: ${{ !inputs.published-layer }} + run: | + bun run build:layer + echo "BUN_LAYER_ZIP=$PWD/lib/bun-lambda-layer-$(cat .bun-version).zip" >> "$GITHUB_ENV" + - run: bun run build - run: bun run integ:deploy-test-destroy diff --git a/.github/workflows/publish-smoke.yml b/.github/workflows/publish-smoke.yml new file mode 100644 index 0000000..bba8453 --- /dev/null +++ b/.github/workflows/publish-smoke.yml @@ -0,0 +1,46 @@ +name: publish-smoke + +# Publishes the runtime to one region with a throwaway version and alias, to check the +# publish role, the AWS CLI and the Docker build. Not public, nothing goes to npm. +on: + workflow_dispatch: {} + push: + branches: [feat/v4-public-artifacts] + paths: [".github/workflows/publish-smoke.yml"] + +jobs: + publish-runtime: + runs-on: ubuntu-24.04 + permissions: + id-token: write + contents: read + steps: + - uses: actions/checkout@v6 + + - uses: oven-sh/setup-bun@v2 + with: + bun-version-file: .bun-version + + - run: bun install --frozen-lockfile + + - name: Install the latest AWS CLI + run: | + curl -sSf https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip -o awscliv2.zip + unzip -q awscliv2.zip + sudo ./aws/install --update + aws --version + + - uses: aws-actions/configure-aws-credentials@v6 + with: + role-to-assume: ${{ secrets.AWS_PUBLISH_ROLE_ARN }} + aws-region: eu-central-1 + + - name: Publish the runtime + run: | + bun command/publishRuntime.ts \ + --region eu-central-1 \ + "$(cat .bun-version)" \ + --version-name smoke-${{ github.run_id }} \ + --alias smoke-${{ github.run_id }} \ + --out runtime-result.json + cat runtime-result.json diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b46ef16..19cbb3d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -8,7 +8,7 @@ on: required: true type: string patch: - description: "Internal patch number (Y in 3.X.Y) for releases that do not change the Bun version" + description: "Internal patch number (Y in 4.X.Y) for releases that do not change the Bun version" required: false default: "0" type: string @@ -17,16 +17,14 @@ on: paths: [".bun-version"] jobs: - integration_test: - uses: ./.github/workflows/integration.yml - secrets: inherit - - release: - needs: integration_test + prepare: runs-on: ubuntu-24.04 permissions: - contents: write - id-token: write + contents: read + outputs: + bun-version: ${{ steps.bun.outputs.version }} + package-version: ${{ steps.pkg.outputs.version }} + skip: ${{ steps.check.outputs.skip }} steps: - uses: actions/checkout@v6 with: @@ -45,8 +43,8 @@ jobs: IFS='.' read -r MAJOR MINOR PATCH <<< "${{ steps.bun.outputs.version }}" PKG_MINOR=$((MAJOR * 10000 + MINOR * 100 + PATCH)) PKG_PATCH="${{ inputs.patch || '0' }}" - echo "version=3.${PKG_MINOR}.${PKG_PATCH}" >> "$GITHUB_OUTPUT" - echo "Package version: 3.${PKG_MINOR}.${PKG_PATCH} (from Bun v${{ steps.bun.outputs.version }})" + echo "version=4.${PKG_MINOR}.${PKG_PATCH}" >> "$GITHUB_OUTPUT" + echo "Package version: 4.${PKG_MINOR}.${PKG_PATCH} (from Bun v${{ steps.bun.outputs.version }})" - name: Check if already released id: check @@ -59,53 +57,247 @@ jobs: echo "skip=false" >> "$GITHUB_OUTPUT" fi + build-layer: + needs: prepare + if: needs.prepare.outputs.skip == 'false' + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v6 + + - uses: oven-sh/setup-bun@v2 + with: + bun-version-file: .bun-version + + - run: bun install --frozen-lockfile + + - name: Build layer zip + run: bun run build:layer + env: + BUN_VERSION: ${{ needs.prepare.outputs.bun-version }} + + - uses: actions/upload-artifact@v7 + with: + name: layer-zip + path: lib/bun-lambda-layer-*.zip + if-no-files-found: error + + # The first region is published on its own so the integration test can run against + # the published layer before the remaining regions and npm are touched. + publish-first-region: + needs: [prepare, build-layer] + runs-on: ubuntu-24.04 + permissions: + id-token: write + contents: read + steps: + - uses: actions/checkout@v6 + + - uses: oven-sh/setup-bun@v2 + with: + bun-version-file: .bun-version + + - run: bun install --frozen-lockfile + + - uses: actions/download-artifact@v8 + with: + name: layer-zip + path: lib + + - name: Install the latest AWS CLI + run: | + curl -sSf https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip -o awscliv2.zip + unzip -q awscliv2.zip + sudo ./aws/install --update + + - uses: aws-actions/configure-aws-credentials@v6 + with: + role-to-assume: ${{ secrets.AWS_PUBLISH_ROLE_ARN }} + aws-region: eu-central-1 + + - name: Publish layer in eu-central-1 + run: | + mkdir -p results + bun command/publishLayer.ts \ + --region eu-central-1 \ + --zip lib/bun-lambda-layer-${{ needs.prepare.outputs.bun-version }}.zip \ + --bun-version ${{ needs.prepare.outputs.bun-version }} \ + --package-version ${{ needs.prepare.outputs.package-version }} \ + --git-sha ${{ github.sha }} \ + --out results/eu-central-1.json + + # Only the alias named after the package version exists at this point. The moving aliases + # (x.y.z, x.y, x, latest) are set after the integration test passed. + - name: Publish runtime in eu-central-1 + run: | + bun command/publishRuntime.ts \ + --region eu-central-1 \ + ${{ needs.prepare.outputs.bun-version }} \ + --version-name ${{ needs.prepare.outputs.package-version }} \ + --alias pkg-${{ needs.prepare.outputs.package-version }} \ + --out results/eu-central-1-runtime.json + + - name: Write artifacts.json for the integration test + run: | + bun command/writeArtifacts.ts \ + --package-version ${{ needs.prepare.outputs.package-version }} \ + --bun-version ${{ needs.prepare.outputs.bun-version }} \ + results/eu-central-1.json results/eu-central-1-runtime.json + + - uses: actions/upload-artifact@v7 + with: + name: artifacts-json-first-region + path: src/artifacts.json + if-no-files-found: error + + integration_test: + needs: [prepare, publish-first-region] + uses: ./.github/workflows/integration.yml + with: + published-layer: true + secrets: inherit + + # All five regions, including the first one: publishing is idempotent, and this is where the + # moving aliases are set, after the integration test passed. + publish-regions: + needs: [prepare, integration_test] + runs-on: ubuntu-24.04 + permissions: + id-token: write + contents: read + strategy: + fail-fast: false + matrix: + region: [eu-central-1, eu-north-1, eu-west-1, us-east-1, us-west-2] + steps: + - uses: actions/checkout@v6 + + - uses: oven-sh/setup-bun@v2 + with: + bun-version-file: .bun-version + + - run: bun install --frozen-lockfile + + - uses: actions/download-artifact@v8 + with: + name: layer-zip + path: lib + + - name: Install the latest AWS CLI + run: | + curl -sSf https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip -o awscliv2.zip + unzip -q awscliv2.zip + sudo ./aws/install --update + + - uses: aws-actions/configure-aws-credentials@v6 + with: + role-to-assume: ${{ secrets.AWS_PUBLISH_ROLE_ARN }} + aws-region: ${{ matrix.region }} + + - name: Publish layer in ${{ matrix.region }} + run: | + mkdir -p results + bun command/publishLayer.ts \ + --region ${{ matrix.region }} \ + --zip lib/bun-lambda-layer-${{ needs.prepare.outputs.bun-version }}.zip \ + --bun-version ${{ needs.prepare.outputs.bun-version }} \ + --package-version ${{ needs.prepare.outputs.package-version }} \ + --git-sha ${{ github.sha }} \ + --out results/${{ matrix.region }}.json + + - name: Publish runtime in ${{ matrix.region }} + run: | + bun command/publishRuntime.ts \ + --region ${{ matrix.region }} \ + ${{ needs.prepare.outputs.bun-version }} \ + --version-name ${{ needs.prepare.outputs.package-version }} \ + --alias pkg-${{ needs.prepare.outputs.package-version }} \ + --release-aliases \ + --public \ + --out results/${{ matrix.region }}-runtime.json + + - uses: actions/upload-artifact@v7 + with: + name: region-result-${{ matrix.region }} + path: results/*.json + if-no-files-found: error + + release: + needs: [prepare, build-layer, publish-regions] + runs-on: ubuntu-24.04 + permissions: + contents: write + id-token: write + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + - uses: oven-sh/setup-bun@v2 - if: steps.check.outputs.skip == 'false' with: bun-version-file: .bun-version - uses: actions/setup-node@v6 - if: steps.check.outputs.skip == 'false' with: node-version: "24" registry-url: "https://registry.npmjs.org" - run: bun install --frozen-lockfile - if: steps.check.outputs.skip == 'false' + + - uses: actions/download-artifact@v8 + with: + name: layer-zip + path: lib + + - uses: actions/download-artifact@v8 + with: + pattern: region-result-* + merge-multiple: true + path: results + + - name: Write artifacts.json with all published regions + run: | + bun command/writeArtifacts.ts \ + --package-version ${{ needs.prepare.outputs.package-version }} \ + --bun-version ${{ needs.prepare.outputs.bun-version }} \ + results/*.json + cat src/artifacts.json - name: Build - if: steps.check.outputs.skip == 'false' run: bun run build env: - BUN_VERSION: ${{ steps.bun.outputs.version }} + BUN_VERSION: ${{ needs.prepare.outputs.bun-version }} - name: Set version and pack - if: steps.check.outputs.skip == 'false' run: | - npm version "${{ steps.pkg.outputs.version }}" --no-git-tag-version + npm version "${{ needs.prepare.outputs.package-version }}" --no-git-tag-version npm pack - name: Create GitHub Release - if: steps.check.outputs.skip == 'false' uses: softprops/action-gh-release@v3 with: - tag_name: "v${{ steps.pkg.outputs.version }}" - name: "v${{ steps.pkg.outputs.version }}" + tag_name: "v${{ needs.prepare.outputs.package-version }}" + name: "v${{ needs.prepare.outputs.package-version }}" body: | - ## Lambda Bun Runtime v${{ steps.pkg.outputs.version }} + ## Lambda Bun Runtime v${{ needs.prepare.outputs.package-version }} - Built with Bun v${{ steps.bun.outputs.version }} + Built with Bun v${{ needs.prepare.outputs.bun-version }} ### Versioning - Package version `3.X.Y` where `X = bun_major*10000 + bun_minor*100 + bun_patch` and `Y` is the internal patch. + Package version `4.X.Y` where `X = bun_major*10000 + bun_minor*100 + bun_patch` and `Y` is the internal patch. + + ### Published artifacts + The layer and the customer-managed runtime are public in `eu-north-1`, `eu-central-1`, `eu-west-1`, `us-east-1` and `us-west-2`. ARNs are in `artifacts.json`. + Runtime aliases: ``, `` (the `BunFunction` default, follows patch releases), `` and `latest`. ### Assets - - `bun-lambda-layer-${{ steps.bun.outputs.version }}.zip` — Prebuilt Lambda layer (Linux ARM64) - files: "dist/bun-lambda-layer-${{ steps.bun.outputs.version }}.zip" + - `bun-lambda-layer-${{ needs.prepare.outputs.bun-version }}.zip` - the layer zip (Linux ARM64) that was published + - `artifacts.json` - published layer and runtime ARNs per region + files: | + lib/bun-lambda-layer-${{ needs.prepare.outputs.bun-version }}.zip + src/artifacts.json fail_on_unmatched_files: true env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Publish to npm - if: steps.check.outputs.skip == 'false' run: npm publish *.tgz --provenance --access public diff --git a/.kiro/skills/sync-package-docs/SKILL.md b/.kiro/skills/sync-package-docs/SKILL.md index bf1ab06..8eff92c 100644 --- a/.kiro/skills/sync-package-docs/SKILL.md +++ b/.kiro/skills/sync-package-docs/SKILL.md @@ -12,7 +12,7 @@ This is the `@beesolve/lambda-bun-runtime` binding for the generic `agentic-pack - **Package:** `@beesolve/lambda-bun-runtime` - a SINGLE published package (not a monorepo). Docs live at the repo root (`DOCS.md`, `docs/how-to/`), not under `packages/`. - **Scope / repo / branch:** `@beesolve`, `https://github.com/BeeSolve/lambda-bun-runtime`, branch `main`. Org casing is `BeeSolve`. - **Install command:** `bun add` (primary); mention `npm install` as an alternative. `aws-cdk-lib` and `constructs` are peer dependencies. -- **Public API (verify in `src/index.ts` before writing):** constructs `BunFunction`, `BunLambdaLayer`; types `BunFunctionProps`, `BunLambdaLayerProps`. These are CDK constructs - samples are CDK stack code, not SDK calls. +- **Public API (verify in `src/index.ts` before writing):** constructs `BunFunction`, `BunFunctionWithLayer`, `BunLambdaLayer`; types `BunFunctionProps`, `BunFunctionWithLayerProps`, `BunRuntimeProps`, `BunLambdaLayerProps`. These are CDK constructs - samples are CDK stack code, not SDK calls. - **Example:** `examples/sample-app/` (a deployable CDK app, workspace member). It is the one Working Examples link. Confirm construct usage in `examples/sample-app/lib/sample-stack.ts`. - **Publish mechanism:** the `files` array in `package.json`. It must include `"dist/"`, `"docs/how-to"`, `"DOCS.md"`. There is no `.npmignore`. - **Keep OUT of the tarball:** `docs/adr-*.md` and any other `docs/*.md` that are not under `docs/how-to/` (e.g. `docs/aws-oidc-setup.md`). Never add the whole `"docs"` folder to `files`. diff --git a/.kiro/steering/product.md b/.kiro/steering/product.md index 5fff819..2037a06 100644 --- a/.kiro/steering/product.md +++ b/.kiro/steering/product.md @@ -6,7 +6,7 @@ - Packages the Bun binary into a Lambda Layer for ARM64/AL2023 - Provides a minimal custom runtime (~80 lines) that implements the Lambda Runtime API loop -- Exposes two CDK constructs: `BunLambdaLayer` and `BunFunction` +- Exposes CDK constructs: `BunFunction` (customer-managed runtime, default), `BunFunctionWithLayer` and `BunLambdaLayer` (layer path) - Handlers use the standard Node.js-style `(event, context) => response` signature (not Fetch API) - `.ts` entrypoints are automatically built with Bun during CDK synth; `.js` files are used directly diff --git a/.kiro/steering/structure.md b/.kiro/steering/structure.md index 434983f..701a0eb 100644 --- a/.kiro/steering/structure.md +++ b/.kiro/steering/structure.md @@ -2,10 +2,17 @@ ``` ├── src/ # Library source (CDK constructs) -│ └── index.ts # Exports BunFunction and BunLambdaLayer constructs +│ ├── index.ts # Exports BunFunction, BunFunctionWithLayer and BunLambdaLayer constructs +│ ├── artifacts.ts # Published artifact lookup by region +│ └── artifacts.json # Placeholder in git, generated by the release workflow ├── command/ # Build tooling scripts (run with Bun directly) -│ ├── build.ts # Full build orchestration (layer + bundle + declarations) -│ ├── buildLayer.ts # Downloads Bun binary, compiles runtime, creates layer zip +│ ├── build.ts # Package build (bundle + declarations + CLI) +│ ├── layer.ts # Downloads Bun binary, compiles runtime, creates layer zip +│ ├── buildLayer.ts # Script entry for layer.ts (bun run build:layer) +│ ├── cli.ts # bun-lambda-runtime CLI (build-layer), shipped as dist/cli.js +│ ├── publishLayer.ts # Publishes + shares the layer in one region (release workflow) +│ ├── publishRuntime.ts # Builds the runtime image, publishes the CMR + aliases (release workflow, CLI publish-runtime) +│ ├── writeArtifacts.ts # Merges publish results into src/artifacts.json │ └── runtime.mts # The actual Lambda custom runtime (deployed inside the layer) ├── test/ # Test files (run with `bun test`) │ ├── constructs.test.ts # CDK construct unit tests diff --git a/.kiro/steering/tech.md b/.kiro/steering/tech.md index 3800a14..2dc14b5 100644 --- a/.kiro/steering/tech.md +++ b/.kiro/steering/tech.md @@ -56,18 +56,19 @@ bun install ## Build Pipeline (`command/build.ts`) -1. Runs `command/buildLayer.ts` → produces `lib/bun-lambda-layer-{version}.zip` -2. Bundles `src/index.ts` with `Bun.build` → `dist/index.js` (ESM, externals: aws-cdk-lib, constructs) -3. Runs `tsc --emitDeclarationOnly` → `dist/index.d.ts` -4. Copies layer zip from `lib/` to `dist/` +1. Bundles `src/index.ts` with `Bun.build` -> `dist/index.js` (ESM, externals: aws-cdk-lib, constructs). `src/artifacts.json` is bundled in. +2. Runs `tsc --emitDeclarationOnly` -> `dist/index.d.ts` +3. Bundles `command/cli.ts` -> `dist/cli.js` (the `bun-lambda-runtime` bin) and copies `command/runtime.mts` to `dist/runtime.mts` -Published package contains only `dist/` (JS, declarations, layer zip). +The layer zip is built separately with `bun run build:layer` -> `lib/bun-lambda-layer-{version}.zip`. It is published as a public layer by the release workflow and attached to the GitHub release, it is NOT in the npm package. `src/artifacts.json` is an empty placeholder in git; the release workflow writes the real ARNs into it before `bun run build`. + +Published package contains `dist/`, `docs/how-to` and `DOCS.md` only. ## Versioning -`3..` +`4..` -- Major: `3` (post-projen era) +- Major: `4` (layer published as a public artifact, zip no longer in the package) - Minor: encodes the full Bun version - Patch: internal changes (resets to 0 on Bun version bump) @@ -78,6 +79,7 @@ Published package contains only `dist/` (JS, declarations, layer zip). - `test/` uses `bun:test` and `fast-check` for property-based tests. - `lib/` is gitignored — CI builds the layer fresh each time. - `dist/` is gitignored — CI builds and publishes from fresh output. +- `mise.toml` sets `AWS_PROFILE` for this repo and mise shims override a profile exported in the shell. Check `aws sts get-caller-identity` before running anything in `command/` that calls AWS. ## Coding Style & Conventions diff --git a/DOCS.md b/DOCS.md index 0a696c8..448c33e 100644 --- a/DOCS.md +++ b/DOCS.md @@ -1,6 +1,6 @@ # @beesolve/lambda-bun-runtime - Documentation -**Keywords:** aws lambda, bun runtime, bun layer, cdk construct, BunFunction, BunLambdaLayer, BunFunctionProps, PROVIDED_AL2023, arm64, custom runtime, lambda layer, entrypoint, response streaming, function url +**Keywords:** aws lambda, bun runtime, bun layer, cdk construct, BunFunction, BunFunctionWithLayer, BunLambdaLayer, BunLambdaLayerProps, bunRuntime, runtimeArn, runtimeAlias, customer-managed runtime, CMR, publish-runtime, layerVersionArn, assetZipPath, build-layer, PROVIDED_AL2023, arm64, custom runtime, lambda layer, region, entrypoint, response streaming, function url > This documentation is published inside the installed package and matches the installed version. Prefer it over prior knowledge or older examples found online. @@ -8,18 +8,20 @@ ## How-To Guides -| Guide | Description | -| --------------------------------------------------- | -------------------------------------------------------------------- | -| [Getting Started](./docs/how-to/getting-started.md) | Install, add the Bun layer, and deploy your first Bun Lambda via CDK | +| Guide | Description | +| ------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| [Getting Started](./docs/how-to/getting-started.md) | Install and deploy your first Bun Lambda on the Bun customer-managed runtime | +| [Publish your own runtime](./docs/how-to/custom-runtime.md) | Publish the runtime in your account or region with `publish-runtime` | +| [Use a layer instead of the runtime](./docs/how-to/custom-layer.md) | `BunFunctionWithLayer`, a layer ARN, or a layer zip you build yourself | ## Working Examples The [examples/sample-app](https://github.com/BeeSolve/lambda-bun-runtime/tree/main/examples/sample-app) directory in the repository is a deployable CDK app demonstrating real-world usage: -| Example | What it shows | -| ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------- | -| [sample-app](https://github.com/BeeSolve/lambda-bun-runtime/tree/main/examples/sample-app) | `BunFunction` + `BunLambdaLayer` across HTTP v1/v2, Function URL, response streaming, direct invoke, and Bun-native S3 | +| Example | What it shows | +| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------- | +| [sample-app](https://github.com/BeeSolve/lambda-bun-runtime/tree/main/examples/sample-app) | `BunFunctionWithLayer` + `BunLambdaLayer` and `BunFunction` across HTTP v1/v2, Function URL, response streaming, direct invoke, and Bun-native S3 | ## Further Reading diff --git a/README.md b/README.md index c292a9b..ebd29ff 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ A custom [Bun](https://bun.sh) runtime for AWS Lambda with CDK constructs for easy deployment. > [!NOTE] -> **v3 is ESM-only and no longer published as a jsii package.** Polyglot CDK support (Python, Java, .NET) has been removed — there were zero consumers. If you need the layer without CDK, the zip is available as a GitHub Release asset. See [ADR: Drop jsii](docs/adr-drop-jsii.md) for the full rationale. +> **v4 runs on a Lambda customer-managed runtime and no longer ships the layer zip in the npm package.** `BunFunction` uses a Bun runtime that BeeSolve publishes for each release in `eu-north-1`, `eu-central-1`, `eu-west-1`, `us-east-1` and `us-west-2`. It needs `aws-cdk-lib` 2.278.0 or newer. For other regions, [publish your own runtime](docs/how-to/custom-runtime.md) or [use a layer](docs/how-to/custom-layer.md) with `BunFunctionWithLayer`. v3 is the last version that works in every region without extra steps. v3 was ESM-only and no longer a jsii package, see [ADR: Drop jsii](docs/adr-drop-jsii.md). The reasoning for v4 is in [ADR: Public artifacts](docs/adr-public-artifacts.md). Current bun version: [1.4.5](https://bun.sh/blog/bun-v1.4.5) @@ -15,14 +15,12 @@ npm i @beesolve/lambda-bun-runtime ## Quick Start -Two constructs are provided: `BunLambdaLayer` (the runtime layer) and `BunFunction` (a Lambda function that uses it). +`BunFunction` runs your handler on the Bun [customer-managed runtime](https://docs.aws.amazon.com/lambda/) that BeeSolve publishes. No layer is involved. ```ts -import { BunLambdaLayer, BunFunction } from "@beesolve/lambda-bun-runtime"; +import { BunFunction } from "@beesolve/lambda-bun-runtime"; import { Duration } from "aws-cdk-lib"; -const bunLayer = new BunLambdaLayer(this, "BunLayer"); - const apiHandler = new BunFunction(this, "ApiHandler", { entrypoint: `${__dirname}/api.ts`, memorySize: 1024, @@ -30,10 +28,23 @@ const apiHandler = new BunFunction(this, "ApiHandler", { environment: { STAGE: "prod", }, - bunLayer, }); ``` +The stack needs a concrete region (`env: { region: "eu-central-1" }`), because the published runtime is looked up by region. It requires `aws-cdk-lib` 2.278.0 or newer. The default alias is `.` of the Bun version this package was built for, so Bun patch releases reach your function on its next cold start without a redeploy. To use a runtime you published yourself, or another alias, set `bunRuntime`: + +```ts +new BunFunction(this, "ApiHandler", { + entrypoint: `${__dirname}/api.ts`, + bunRuntime: { + runtimeArn: "arn:aws:lambda:eu-west-3:123456789012:runtime/bun", + runtimeAlias: "latest", + }, +}); +``` + +Where the customer-managed runtime is not an option, `BunFunctionWithLayer` runs Bun from a layer (`BunLambdaLayer`) on `provided.al2023`. See [Use a layer instead of the runtime](./docs/how-to/custom-layer.md). + `BunFunction` accepts `.ts` and `.js` entrypoints. TypeScript files are built with Bun automatically during CDK synth. JavaScript files are used as-is. By default, the Lambda handler string is derived as `.handler`. Override with the `exportName` prop. diff --git a/bun.lock b/bun.lock index 8219a0e..de027e3 100644 --- a/bun.lock +++ b/bun.lock @@ -10,7 +10,7 @@ "@beesolve/lint-config": "0.2.4", "@types/bun": "1.3.14", "@types/node": "24.12.4", - "aws-cdk-lib": "2.238.0", + "aws-cdk-lib": "2.278.0", "constructs": "10.4.5", "fast-check": "4.8.0", "oxfmt": "0.57.0", @@ -19,7 +19,7 @@ "typescript": "6.0.3", }, "peerDependencies": { - "aws-cdk-lib": "^2.238.0", + "aws-cdk-lib": "^2.278.0", "constructs": "^10.4.5", }, }, @@ -28,23 +28,23 @@ "dependencies": { "@beesolve/lambda-bun-runtime": "file:../..", "@beesolve/lambda-fetch-api": "^1.0.0", - "aws-cdk-lib": "^2.238.0", + "aws-cdk-lib": "^2.278.0", "constructs": "^10.4.5", }, "devDependencies": { "@aws-sdk/client-lambda": "^3", "@aws-sdk/client-s3": "^3", "@types/aws-lambda": "^8", - "aws-cdk": "^2.238.0", + "aws-cdk": "^2.1149.0", }, }, }, "packages": { - "@aws-cdk/asset-awscli-v1": ["@aws-cdk/asset-awscli-v1@2.2.263", "", {}, "sha512-X9JvcJhYcb7PHs8R7m4zMablO5C9PGb/hYfLnxds9h/rKJu6l7MiXE/SabCibuehxPnuO/vk+sVVJiUWrccarQ=="], + "@aws-cdk/asset-awscli-v1": ["@aws-cdk/asset-awscli-v1@2.2.297", "", {}, "sha512-8Fqkqn0ddOQoZHg3nTzwJ+ZZn9sogXy6G9JQO8lH3nbU8ZNSPXwfL+1yXFjwnchuL8AOfU5qrWaLl4JYcN40ZA=="], - "@aws-cdk/asset-node-proxy-agent-v6": ["@aws-cdk/asset-node-proxy-agent-v6@2.1.2", "", {}, "sha512-pDiuqH+qY3zM9lhhLjbKJ1tnKOHzQ2V4Wr/3qsxyKeKAkuPMI/BVGvZG1PbrikUw949cGVTfVEt4ETKKYnrj0Q=="], + "@aws-cdk/asset-node-proxy-agent-v6": ["@aws-cdk/asset-node-proxy-agent-v6@2.1.3", "", {}, "sha512-98We1QWfin9vtuuQtNFhIIAEWb8CreyYTAP0Vn8HqSBoNiFJM9nZgifJeQawT9Wq0NX1HCNFlxCyTccIrK1PSA=="], - "@aws-cdk/cloud-assembly-schema": ["@aws-cdk/cloud-assembly-schema@48.20.0", "", { "dependencies": { "jsonschema": "~1.4.1", "semver": "^7.7.2" } }, "sha512-+eeiav9LY4wbF/EFuCt/vfvi/Zoxo8bf94PW5clbMraChEliq83w4TbRVy0jB9jE0v1ooFTtIjSQkowSPkfISg=="], + "@aws-cdk/cloud-assembly-schema": ["@aws-cdk/cloud-assembly-schema@55.7.0", "", { "dependencies": { "jsonschema": "^1.5.0", "semver": "^7.8.6" } }, "sha512-sgGkFDggs9mKQgUrpnMgCDq/suZ6mVpT1925rpemR1M8wempVtVtbT6WeEWsS15jZoxKY9a9xqSQbyG+BdT5aA=="], "@aws-sdk/checksums": ["@aws-sdk/checksums@3.1000.10", "", { "dependencies": { "@aws-sdk/core": "^3.974.25", "@aws-sdk/types": "^3.973.14", "@smithy/core": "^3.28.0", "@smithy/types": "^4.15.0", "tslib": "^2.6.2" } }, "sha512-OUNjNcyA8Ai2OdlRUxW5jHUf6XJmqqZk3UddL+mDiUCtXrVqdmIHHkdDFWBlBRjhore/3ZBMgRXgcS0ggtvD0Q=="], @@ -186,9 +186,9 @@ "@types/node": ["@types/node@24.12.4", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-GUUEShf+PBCGW2KaXwcIt3Yk+e3pkKwWKb9GSyM9WQVE+ep2jzmHdGsHzu4wgcZy5fN9FBdVzjpBQsYlpfpgLA=="], - "aws-cdk": ["aws-cdk@2.1129.0", "", { "bin": { "cdk": "bin/cdk" } }, "sha512-M0EWbjeKW+baUsirjtKuWh7w/9dPxF8taEi2hqo9ecCjGeQxV1dzyosJf+caR3Jh7dFyyT3J8zEtRb/cU971Rw=="], + "aws-cdk": ["aws-cdk@2.1149.0", "", { "bin": { "cdk": "bin/cdk" } }, "sha512-Cj6iGj/lVCf8iSFNZeSjpTbh42yO1uINg9pSYcBJ3wfTwWRk0xQGu2YAi/iON+RWEWGJlJNT+TNewBx05Wd9Sw=="], - "aws-cdk-lib": ["aws-cdk-lib@2.238.0", "", { "dependencies": { "@aws-cdk/asset-awscli-v1": "2.2.263", "@aws-cdk/asset-node-proxy-agent-v6": "^2.1.0", "@aws-cdk/cloud-assembly-api": "^2.0.0", "@aws-cdk/cloud-assembly-schema": "^48.20.0", "@balena/dockerignore": "^1.0.2", "case": "1.6.3", "fs-extra": "^11.3.3", "ignore": "^5.3.2", "jsonschema": "^1.5.0", "mime-types": "^2.1.35", "minimatch": "^3.1.2", "punycode": "^2.3.1", "semver": "^7.7.3", "table": "^6.9.0", "yaml": "1.10.2" }, "peerDependencies": { "constructs": "^10.0.0" } }, "sha512-lmS7DEGcEjNhnl88Z7SynPA1UHdCOkx2pNSGiiBQG5I2jH8H2nnWnr6cZRWmxV2GyNeBmmd9wHdEcSBpkow53Q=="], + "aws-cdk-lib": ["aws-cdk-lib@2.278.0", "", { "dependencies": { "@aws-cdk/asset-awscli-v1": "2.2.297", "@aws-cdk/asset-node-proxy-agent-v6": "^2.1.3", "@aws-cdk/cloud-assembly-api": "^2.5.0", "@aws-cdk/cloud-assembly-schema": "^55.6.0", "@aws/cloudformation-validate": "~1.17.0", "@balena/dockerignore": "^1.0.2", "case": "1.6.3", "fs-extra": "^11.4.1", "ignore": "^5.3.2", "jsonschema": "^1.5.0", "mime-types": "^2.1.35", "minimatch": "^11.0.9", "punycode": "^2.3.1", "semver": "^7.8.6", "yaml": "1.10.3" }, "peerDependencies": { "constructs": "^10.5.0" } }, "sha512-E5OfaAeWGpZk9TWUodhsNLLCPzM8ObydK5BewEgfOGwYt6UA+8po/+SyLLuFr4DoSjw17vMZg9eCNP6nlymNJg=="], "bowser": ["bowser@2.14.1", "", {}, "sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg=="], @@ -218,87 +218,57 @@ "valibot": ["valibot@1.4.2", "", { "peerDependencies": { "typescript": ">=5" }, "optionalPeers": ["typescript"] }, "sha512-gjdCvJ6d3RyHAneqxMYMW9QMCwYMb3jpOO0IyHZV1bnRHFBHrX3VkIILt5XYR0WhwHiH7Mty8ovuPZ/O3gamrg=="], - "@aws-cdk/cloud-assembly-schema/jsonschema": ["jsonschema@1.4.1", "", { "bundled": true }, "sha512-S6cATIPVv1z0IlxdN+zUk5EPjkGCdnhN4wVSBlvoUO1tOLJootbo9CquNJmbIh4yikWHiUedhRYrNPn1arpEmQ=="], + "@aws-cdk/cloud-assembly-schema/jsonschema": ["jsonschema@1.5.0", "", { "bundled": true }, "sha512-K+A9hhqbn0f3pJX17Q/7H6yQfD/5OXgdrR5UE12gMXCiN9D5Xq2o5mddV2QEcX/bjla99ASsAAQUyMCCRWAEhw=="], - "@aws-cdk/cloud-assembly-schema/semver": ["semver@7.8.5", "", { "bundled": true, "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="], + "@aws-cdk/cloud-assembly-schema/semver": ["semver@7.8.6", "", { "bundled": true, "bin": { "semver": "bin/semver.js" } }, "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw=="], - "aws-cdk-lib/@aws-cdk/cloud-assembly-api": ["@aws-cdk/cloud-assembly-api@2.2.6", "", { "dependencies": { "jsonschema": "^1.5.0", "semver": "^7.8.4" }, "peerDependencies": { "@aws-cdk/cloud-assembly-schema": ">=54.5.0" }, "bundled": true }, "sha512-lw+Z5JT4e5rAMMR8tvj2yKSIQTvlxpBeYMUjfSgpJ4RN9d94vF6CpnvPqq6LsfO37n6jw0ufQrDNrR8ZHWKkuw=="], + "aws-cdk-lib/@aws-cdk/cloud-assembly-api": ["@aws-cdk/cloud-assembly-api@2.5.0", "", { "dependencies": { "json-source-map": "^0.6.1", "jsonschema": "^1.5.0", "semver": "^7.8.5" }, "peerDependencies": { "@aws-cdk/cloud-assembly-schema": ">=55.0.0" }, "bundled": true }, "sha512-cE19OP9Ad3f04wkvntxqMxwKXutvkVyymwiqHsvEnmBktXjdm6Ydjd2X7b9QcU3QvbL7Gdt4bc3d4STMROCjfg=="], - "aws-cdk-lib/@aws-cdk/cloud-assembly-schema": ["@aws-cdk/cloud-assembly-schema@48.20.0", "", { "dependencies": { "jsonschema": "~1.4.1", "semver": "^7.7.2" } }, "sha512-+eeiav9LY4wbF/EFuCt/vfvi/Zoxo8bf94PW5clbMraChEliq83w4TbRVy0jB9jE0v1ooFTtIjSQkowSPkfISg=="], + "aws-cdk-lib/@aws-cdk/cloud-assembly-schema": ["@aws-cdk/cloud-assembly-schema@55.7.0", "", { "dependencies": { "jsonschema": "^1.5.0", "semver": "^7.8.6" } }, "sha512-sgGkFDggs9mKQgUrpnMgCDq/suZ6mVpT1925rpemR1M8wempVtVtbT6WeEWsS15jZoxKY9a9xqSQbyG+BdT5aA=="], - "aws-cdk-lib/@balena/dockerignore": ["@balena/dockerignore@1.0.2", "", { "bundled": true }, "sha512-wMue2Sy4GAVTk6Ic4tJVcnfdau+gx2EnG7S+uAEe+TWJFqE4YoWN4/H8MSLj4eYJKxGg26lZwboEniNiNwZQ6Q=="], - - "aws-cdk-lib/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], - - "aws-cdk-lib/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], + "aws-cdk-lib/@aws/cloudformation-validate": ["@aws/cloudformation-validate@1.17.1", "", { "bundled": true }, "sha512-Rf3ISGZYfXq1c0fOSYYt33UvF5lSmphnl8JpCvlFMyAa5qc7GECXc8kPq1HL5+62leUQWMIiWceYjkuQhhJmZw=="], - "aws-cdk-lib/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], + "aws-cdk-lib/@balena/dockerignore": ["@balena/dockerignore@1.0.2", "", { "bundled": true }, "sha512-wMue2Sy4GAVTk6Ic4tJVcnfdau+gx2EnG7S+uAEe+TWJFqE4YoWN4/H8MSLj4eYJKxGg26lZwboEniNiNwZQ6Q=="], - "aws-cdk-lib/astral-regex": ["astral-regex@2.0.0", "", {}, "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ=="], + "aws-cdk-lib/@isaacs/nonrecursive-glob-match": ["@isaacs/nonrecursive-glob-match@1.1.0", "", {}, "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw=="], - "aws-cdk-lib/balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="], + "aws-cdk-lib/balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="], - "aws-cdk-lib/brace-expansion": ["brace-expansion@1.1.15", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg=="], + "aws-cdk-lib/brace-expansion": ["brace-expansion@5.1.0", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-aa11Dv491GKnYqxaul3aRJ0szew7yMJMfZPnqD44NjGrZXoj62l41OEDDpdpC4eE2P88vBFfLuSyRhpG91NUvg=="], "aws-cdk-lib/case": ["case@1.6.3", "", { "bundled": true }, "sha512-mzDSXIPaFwVDvZAHqZ9VlbyF4yyXRuX6IvB06WvPYkqJVO24kX1PPhv9bfpKNFZyxYFmmgo03HUiD8iklmJYRQ=="], - "aws-cdk-lib/color-convert": ["color-convert@2.0.1", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="], - - "aws-cdk-lib/color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="], - - "aws-cdk-lib/concat-map": ["concat-map@0.0.1", "", {}, "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="], - - "aws-cdk-lib/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], - - "aws-cdk-lib/fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="], - - "aws-cdk-lib/fast-uri": ["fast-uri@3.1.3", "", {}, "sha512-i70LwGWUduXqzicKXWshooq+sWL1K3WUU5rKZNG/0i3a1OSoX3HqhH5WbWwTmqWfor4urUakGPiRQcleRZTwOg=="], - - "aws-cdk-lib/fs-extra": ["fs-extra@11.3.6", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" }, "bundled": true }, "sha512-w8ZNZr2mKIc7qeNaQ9AVPT1+iFaI+Avd4xudVOvdDJ8VytREi1Ft5Ih7hd9jjehod8vAM5GMsfQ/TpPf4EyoEA=="], + "aws-cdk-lib/fs-extra": ["fs-extra@11.4.1", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" }, "bundled": true }, "sha512-KYAb4c9BJQI6QqGKthV68OHe0badztdXJWKo0WtBA9IuCFPTKvE5ZdUBglP833aMjhaSPNO4A5j/EkzZtGlKjA=="], "aws-cdk-lib/graceful-fs": ["graceful-fs@4.2.11", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="], "aws-cdk-lib/ignore": ["ignore@5.3.2", "", { "bundled": true }, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="], - "aws-cdk-lib/is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="], - - "aws-cdk-lib/json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="], + "aws-cdk-lib/json-source-map": ["json-source-map@0.6.1", "", {}, "sha512-1QoztHPsMQqhDq0hlXY5ZqcEdUzxQEIxgFkKl4WUp2pgShObl+9ovi4kRh2TfvAfxAoHOJ9vIMEqk3k4iex7tg=="], "aws-cdk-lib/jsonfile": ["jsonfile@6.2.1", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q=="], "aws-cdk-lib/jsonschema": ["jsonschema@1.5.0", "", { "bundled": true }, "sha512-K+A9hhqbn0f3pJX17Q/7H6yQfD/5OXgdrR5UE12gMXCiN9D5Xq2o5mddV2QEcX/bjla99ASsAAQUyMCCRWAEhw=="], - "aws-cdk-lib/lodash.truncate": ["lodash.truncate@4.4.2", "", {}, "sha512-jttmRe7bRse52OsWIMDLaXxWqRAmtIUccAQ3garviCqJjafXOfNMO0yMfNpdD6zbGaTU0P5Nz7e7gAT6cKmJRw=="], - "aws-cdk-lib/mime-db": ["mime-db@1.52.0", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="], "aws-cdk-lib/mime-types": ["mime-types@2.1.35", "", { "dependencies": { "mime-db": "1.52.0" }, "bundled": true }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="], - "aws-cdk-lib/minimatch": ["minimatch@3.1.5", "", { "dependencies": { "brace-expansion": "^1.1.7" }, "bundled": true }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="], + "aws-cdk-lib/minimatch": ["minimatch@11.0.9", "", { "dependencies": { "@isaacs/nonrecursive-glob-match": "^1.1.0", "brace-expansion": "^5.0.12" }, "bundled": true }, "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q=="], "aws-cdk-lib/punycode": ["punycode@2.3.1", "", { "bundled": true }, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="], - "aws-cdk-lib/require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="], - - "aws-cdk-lib/semver": ["semver@7.8.5", "", { "bundled": true, "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="], - - "aws-cdk-lib/slice-ansi": ["slice-ansi@4.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "astral-regex": "^2.0.0", "is-fullwidth-code-point": "^3.0.0" } }, "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ=="], - - "aws-cdk-lib/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], - - "aws-cdk-lib/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], - - "aws-cdk-lib/table": ["table@6.9.0", "", { "dependencies": { "ajv": "^8.0.1", "lodash.truncate": "^4.4.2", "slice-ansi": "^4.0.0", "string-width": "^4.2.3", "strip-ansi": "^6.0.1" }, "bundled": true }, "sha512-9kY+CygyYM6j02t5YFHbNz2FN5QmYGv9zAjVp4lCDjlCw7amdckXlEt/bjMhUIfj4ThGRE4gCUH5+yGnNuPo5A=="], + "aws-cdk-lib/semver": ["semver@7.8.6", "", { "bundled": true, "bin": { "semver": "bin/semver.js" } }, "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw=="], "aws-cdk-lib/universalify": ["universalify@2.0.1", "", {}, "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw=="], - "aws-cdk-lib/yaml": ["yaml@1.10.2", "", { "bundled": true }, "sha512-r3vXyErRCYJ7wg28yvBY5VSoAF8ZvlcW9/BwUzEtUsjvX/DKs24dIkuwjtuprwJJHsbyUbLApepYTR1BN4uHrg=="], + "aws-cdk-lib/yaml": ["yaml@1.10.3", "", { "bundled": true }, "sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA=="], "bun-types/@types/node": ["@types/node@26.1.0", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-O0A1G3xPGy4w7AgQdAQYUlQ+BKk2Oovw8eRpofyp5KdBZULnbe+WqaOVNrm705SHphCiG4XHsACrSmPu1f+Kgw=="], - "aws-cdk-lib/@aws-cdk/cloud-assembly-schema/jsonschema": ["jsonschema@1.4.1", "", { "bundled": true }, "sha512-S6cATIPVv1z0IlxdN+zUk5EPjkGCdnhN4wVSBlvoUO1tOLJootbo9CquNJmbIh4yikWHiUedhRYrNPn1arpEmQ=="], + "aws-cdk-lib/@aws-cdk/cloud-assembly-schema/jsonschema": ["jsonschema@1.5.0", "", { "bundled": true }, "sha512-K+A9hhqbn0f3pJX17Q/7H6yQfD/5OXgdrR5UE12gMXCiN9D5Xq2o5mddV2QEcX/bjla99ASsAAQUyMCCRWAEhw=="], - "aws-cdk-lib/@aws-cdk/cloud-assembly-schema/semver": ["semver@7.8.5", "", { "bundled": true, "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="], + "aws-cdk-lib/@aws-cdk/cloud-assembly-schema/semver": ["semver@7.8.6", "", { "bundled": true, "bin": { "semver": "bin/semver.js" } }, "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw=="], "bun-types/@types/node/undici-types": ["undici-types@8.3.0", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="], } diff --git a/command/build.ts b/command/build.ts index fb2939c..9b765c3 100644 --- a/command/build.ts +++ b/command/build.ts @@ -2,17 +2,18 @@ /** * Build orchestration script. * - * 1. Build the Lambda layer zip (downloads Bun binary, compiles runtime) - * 2. Bundle construct source (ESM, external CDK deps) - * 3. Generate .d.ts declaration files - * 4. Copy layer zip into dist/ so it's included in the published package + * 1. Bundle construct source (ESM, external CDK deps), including src/artifacts.json + * 2. Generate .d.ts declaration files + * 3. Bundle the `bun-lambda-runtime` CLI (dist/cli.js) and ship the runtime source + * (dist/runtime.mts) it compiles into the layer + * + * The layer zip is NOT part of the package. Build it with `bun run build:layer` + * (used by the release workflow and by `bun-lambda-runtime build-layer`). */ -import { cpSync, existsSync, mkdirSync, rmSync } from "node:fs"; +import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync } from "node:fs"; import { join, resolve } from "node:path"; -import { Glob } from "bun"; - const projectRoot = resolve(import.meta.dir, ".."); const distDir = join(projectRoot, "dist"); @@ -22,29 +23,13 @@ async function main(): Promise { } mkdirSync(distDir, { recursive: true }); - await buildLayer(); await bundleSource(); await generateDeclarations(); - copyLayerZip(); + await bundleCli(); console.log("\nBuild complete. Output in dist/"); } -async function buildLayer(): Promise { - console.log("=== Building Lambda layer ==="); - const proc = Bun.spawnSync(["bun", join(projectRoot, "command/buildLayer.ts")], { - cwd: projectRoot, - env: process.env, - stdout: "inherit", - stderr: "inherit", - }); - - if (proc.exitCode !== 0) { - console.error("Layer build failed."); - process.exit(1); - } -} - async function bundleSource(): Promise { console.log("\n=== Bundling construct source ==="); const result = await Bun.build({ @@ -67,6 +52,37 @@ async function bundleSource(): Promise { console.log("Bundled src/index.ts → dist/index.js"); } +async function bundleCli(): Promise { + console.log("\n=== Bundling CLI ==="); + const bunVersion = readFileSync(join(projectRoot, "src/index.ts"), "utf8").match( + /const bunVersion = "([^"]+)"/, + )?.[1]; + if (bunVersion == null) { + console.error("Could not read bunVersion from src/index.ts."); + process.exit(1); + } + + const result = await Bun.build({ + entrypoints: [join(projectRoot, "command/cli.ts")], + outdir: distDir, + target: "bun", + format: "esm", + define: { __BUN_VERSION__: JSON.stringify(bunVersion) }, + }); + + if (!result.success) { + const errors = result.logs + .filter((log) => log.level === "error") + .map((log) => log.message) + .join("\n"); + console.error(`CLI bundle failed: ${errors || "unknown error"}`); + process.exit(1); + } + + copyFileSync(join(projectRoot, "command/runtime.mts"), join(distDir, "runtime.mts")); + console.log("Bundled command/cli.ts → dist/cli.js, copied runtime.mts"); +} + async function generateDeclarations(): Promise { console.log("\n=== Generating declarations ==="); const proc = Bun.spawnSync(["bunx", "tsc", "--emitDeclarationOnly", "--outDir", distDir], { @@ -83,17 +99,4 @@ async function generateDeclarations(): Promise { console.log("Generated dist/index.d.ts"); } -function copyLayerZip(): void { - console.log("\n=== Copying layer zip to dist ==="); - const libDir = join(projectRoot, "lib"); - const glob = new Glob("bun-lambda-layer-*.zip"); - - for (const match of glob.scanSync({ cwd: libDir, absolute: true })) { - const filename = match.split("/").at(-1) ?? ""; - const destPath = join(distDir, filename); - cpSync(match, destPath); - console.log(`Copied ${match} → ${destPath}`); - } -} - await main(); diff --git a/command/buildLayer.ts b/command/buildLayer.ts index 5ae722f..7425293 100644 --- a/command/buildLayer.ts +++ b/command/buildLayer.ts @@ -1,225 +1,4 @@ #!/usr/bin/env bun -/** - * Downloads the Bun binary from GitHub releases, compiles the runtime, - * and packages everything into a Lambda layer zip file. - * - * Usage: - * bun command/buildLayer.ts [version] - * - * Version can be provided as: - * 1. CLI argument (takes precedence) - * 2. BUN_VERSION environment variable - */ +import { buildLayerCommand } from "./layer"; -import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { join, resolve } from "node:path"; - -import { Glob } from "bun"; - -async function main(): Promise { - const version = resolveVersion(); - validateVersion({ version }); - - const tmpDir = join(resolve(import.meta.dir, "..", ".build-tmp"), "layer-build"); - if (existsSync(tmpDir)) { - rmSync(tmpDir, { recursive: true, force: true }); - } - mkdirSync(tmpDir, { recursive: true }); - - try { - const zipPath = await downloadBunBinary({ version, tmpDir }); - const bunBinaryPath = await extractBunBinary({ zipPath, tmpDir }); - const runtimePath = await compileRuntime({ tmpDir }); - const bootstrapPath = generateBootstrap({ tmpDir }); - const outputZip = await createLayerZip({ - version, - bunBinaryPath, - runtimePath, - bootstrapPath, - }); - - console.log(`\nLayer built successfully: ${outputZip}`); - } finally { - rmSync(resolve(import.meta.dir, "..", ".build-tmp"), { - recursive: true, - force: true, - }); - } -} - -function resolveVersion(): string { - const cliArg = process.argv[2]; - const envVar = process.env.BUN_VERSION; - if (cliArg != null) return cliArg; - if (envVar != null) return envVar; - - const srcPath = resolve(import.meta.dir, "..", "src", "index.ts"); - const match = readFileSync(srcPath, "utf8").match(/const bunVersion = "([^"]+)"/); - if (match) return match[1]; - - console.error( - "No Bun version specified. Set BUN_VERSION, pass as argument, or define bunVersion in src/index.ts.", - ); - process.exit(1); -} - -function validateVersion(props: { version: string }): void { - const semverPattern = /^([1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/; - - if (!semverPattern.test(props.version)) { - console.error(`Invalid version format: ${props.version}. Expected semver (e.g., 1.3.13).`); - process.exit(1); - } -} - -async function downloadBunBinary(props: { version: string; tmpDir: string }): Promise { - const url = `https://github.com/oven-sh/bun/releases/download/bun-v${props.version}/bun-linux-aarch64.zip`; - - console.log(`Downloading Bun v${props.version} from ${url}...`); - - const response = await fetch(url).catch((err: unknown) => { - const message = err instanceof Error ? err.message : String(err); - console.error(`Failed to download Bun v${props.version}: ${message}`); - process.exit(1); - }); - - if (!response.ok) { - if (response.status === 404) { - console.error(`Failed to download Bun v${props.version}: release not found.`); - } else { - console.error( - `Failed to download Bun v${props.version}: HTTP ${response.status} ${response.statusText}`, - ); - } - process.exit(1); - } - - const zipPath = join(props.tmpDir, "bun-linux-aarch64.zip"); - const arrayBuffer = await response.arrayBuffer(); - await Bun.write(zipPath, arrayBuffer); - - return zipPath; -} - -async function extractBunBinary(props: { zipPath: string; tmpDir: string }): Promise { - console.log("Extracting Bun binary..."); - - const proc = Bun.spawnSync(["unzip", "-o", props.zipPath, "-d", props.tmpDir]); - - if (proc.exitCode !== 0) { - console.error(`Failed to extract Bun binary: ${proc.stderr.toString().trim()}`); - process.exit(1); - } - - const glob = new Glob("**/bun"); - for await (const match of glob.scan({ cwd: props.tmpDir, absolute: true })) { - if (!match.endsWith(".zip")) { - return match; - } - } - - console.error("Failed to extract Bun binary: bun executable not found in archive."); - process.exit(1); -} - -async function compileRuntime(props: { tmpDir: string }): Promise { - console.log("Compiling runtime..."); - - const runtimeSource = resolve(import.meta.dir, "runtime.mts"); - const outDir = join(props.tmpDir, "compiled"); - mkdirSync(outDir, { recursive: true }); - - const result = await Bun.build({ - entrypoints: [runtimeSource], - outdir: outDir, - target: "bun", - minify: true, - naming: "runtime.js", - }); - - if (!result.success) { - const errors = result.logs - .filter((log) => log.level === "error") - .map((log) => log.message) - .join("\n"); - console.error(`Failed to compile runtime: ${errors || "unknown error"}`); - process.exit(1); - } - - const outputPath = join(outDir, "runtime.js"); - if (!existsSync(outputPath)) { - console.error("Failed to compile runtime: output file not produced."); - process.exit(1); - } - - return outputPath; -} - -function generateBootstrap(props: { tmpDir: string }): string { - const bootstrapContent = "#!/bin/sh\nexec /opt/bun /opt/runtime.js\n"; - const bootstrapPath = join(props.tmpDir, "bootstrap"); - writeFileSync(bootstrapPath, bootstrapContent, { mode: 0o755 }); - return bootstrapPath; -} - -async function createLayerZip(props: { - version: string; - bunBinaryPath: string; - runtimePath: string; - bootstrapPath: string; -}): Promise { - console.log("Creating layer zip..."); - - const libDir = resolve(import.meta.dir, "..", "lib"); - mkdirSync(libDir, { recursive: true }); - - // Remove any existing layer zips so only the current version is packaged - const glob = new Glob("bun-lambda-layer-*.zip"); - for (const match of glob.scanSync({ cwd: libDir, absolute: true })) { - rmSync(match); - } - - const outputZip = join(libDir, `bun-lambda-layer-${props.version}.zip`); - - const stageDir = join(resolve(import.meta.dir, "..", ".build-tmp"), "stage"); - mkdirSync(stageDir, { recursive: true }); - - const cpBun = Bun.spawnSync(["cp", props.bunBinaryPath, join(stageDir, "bun")]); - if (cpBun.exitCode !== 0) { - console.error("Failed to create layer zip: could not copy bun binary"); - process.exit(1); - } - - const cpRuntime = Bun.spawnSync(["cp", props.runtimePath, join(stageDir, "runtime.js")]); - if (cpRuntime.exitCode !== 0) { - console.error("Failed to create layer zip: could not copy runtime.js"); - process.exit(1); - } - - const cpBootstrap = Bun.spawnSync(["cp", props.bootstrapPath, join(stageDir, "bootstrap")]); - if (cpBootstrap.exitCode !== 0) { - console.error("Failed to create layer zip: could not copy bootstrap"); - process.exit(1); - } - - Bun.spawnSync(["chmod", "+x", join(stageDir, "bun")]); - Bun.spawnSync(["chmod", "+x", join(stageDir, "bootstrap")]); - - const zipProc = Bun.spawnSync(["zip", "-j", outputZip, "bootstrap", "bun", "runtime.js"], { - cwd: stageDir, - }); - - if (zipProc.exitCode !== 0) { - console.error(`Failed to create layer zip: ${zipProc.stderr.toString().trim()}`); - process.exit(1); - } - - rmSync(resolve(import.meta.dir, "..", ".build-tmp"), { - recursive: true, - force: true, - }); - - return outputZip; -} - -await main(); +await buildLayerCommand(process.argv.slice(2)); diff --git a/command/cli.ts b/command/cli.ts new file mode 100644 index 0000000..efd405a --- /dev/null +++ b/command/cli.ts @@ -0,0 +1,23 @@ +#!/usr/bin/env bun +import { buildLayerCommand } from "./layer"; +import { publishRuntimeCommand } from "./publishRuntime"; + +const usage = `Usage: bun-lambda-runtime + +Commands: + build-layer [version] [--out ] Build the Bun Lambda layer zip (arm64, provided.al2023) + publish-runtime --region [version] [--name ] [--alias ]... + Build the Bun runtime image and publish it as a Lambda + customer-managed runtime in your account (needs the AWS + CLI and Docker with buildx)`; + +const [command, ...rest] = process.argv.slice(2); + +if (command === "build-layer") { + await buildLayerCommand(rest); +} else if (command === "publish-runtime") { + await publishRuntimeCommand(rest); +} else { + console.error(usage); + process.exit(command == null || command === "--help" ? 0 : 1); +} diff --git a/command/layer.ts b/command/layer.ts new file mode 100644 index 0000000..1197bb6 --- /dev/null +++ b/command/layer.ts @@ -0,0 +1,258 @@ +/** + * Downloads the Bun binary from GitHub releases, compiles the runtime, + * and packages everything into a Lambda layer zip file. + * + * Usage: + * bun command/buildLayer.ts [version] [--out ] (thin wrapper around this module) + * bun-lambda-runtime build-layer [version] [--out ] (installed package) + * + * Version can be provided as: + * 1. CLI argument (takes precedence) + * 2. BUN_VERSION environment variable + * 3. The Bun version this package was built for + * + * The zip is written to --out (default: ./lib in the repository, the current + * directory when run from the installed package). + */ + +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; + +import { Glob } from "bun"; + +// Replaced at package build time (see command/build.ts). Undefined in the repository. +declare const __BUN_VERSION__: string | undefined; + +export async function buildLayerCommand(argv: ReadonlyArray): Promise { + const args = parseArgs({ argv }); + const version = resolveVersion({ cliVersion: args.version }); + validateVersion({ version }); + + const tmpDir = mkdtempSync(join(tmpdir(), "bun-layer-")); + + try { + const zipPath = await downloadBunBinary({ version, tmpDir }); + const bunBinaryPath = await extractBunBinary({ zipPath, tmpDir }); + const runtimePath = await compileRuntime({ tmpDir }); + const bootstrapPath = generateBootstrap({ tmpDir }); + const outputZip = await createLayerZip({ + version, + bunBinaryPath, + runtimePath, + bootstrapPath, + tmpDir, + outDir: args.outDir ?? defaultOutDir(), + }); + + console.log(`\nLayer built successfully: ${outputZip}`); + } finally { + rmSync(tmpDir, { recursive: true, force: true }); + } +} + +function parseArgs(props: { argv: ReadonlyArray }): { version?: string; outDir?: string } { + const positional: Array = []; + let outDir: string | undefined; + for (let index = 0; index < props.argv.length; index++) { + const arg = props.argv[index]; + if (arg === "--out") { + outDir = props.argv[index + 1]; + if (outDir == null) { + console.error("--out needs a directory."); + process.exit(1); + } + index++; + continue; + } + positional.push(arg); + } + return { version: positional[0], outDir: outDir == null ? undefined : resolve(outDir) }; +} + +function isRepositoryLayout(): boolean { + return existsSync(resolve(import.meta.dir, "..", "src", "index.ts")); +} + +function defaultOutDir(): string { + return isRepositoryLayout() ? resolve(import.meta.dir, "..", "lib") : process.cwd(); +} + +export function resolveVersion(props: { cliVersion?: string }): string { + if (props.cliVersion != null) return props.cliVersion; + const envVar = process.env.BUN_VERSION; + if (envVar != null) return envVar; + if (typeof __BUN_VERSION__ !== "undefined") return __BUN_VERSION__; + + const srcPath = resolve(import.meta.dir, "..", "src", "index.ts"); + if (existsSync(srcPath)) { + const match = readFileSync(srcPath, "utf8").match(/const bunVersion = "([^"]+)"/); + if (match) return match[1]; + } + + console.error( + "No Bun version specified. Set BUN_VERSION, pass as argument, or define bunVersion in src/index.ts.", + ); + process.exit(1); +} + +export function validateVersion(props: { version: string }): void { + const semverPattern = /^([1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/; + + if (!semverPattern.test(props.version)) { + console.error(`Invalid version format: ${props.version}. Expected semver (e.g., 1.3.13).`); + process.exit(1); + } +} + +export async function downloadBunBinary(props: { + version: string; + tmpDir: string; +}): Promise { + const url = `https://github.com/oven-sh/bun/releases/download/bun-v${props.version}/bun-linux-aarch64.zip`; + + console.log(`Downloading Bun v${props.version} from ${url}...`); + + const response = await fetch(url).catch((err: unknown) => { + const message = err instanceof Error ? err.message : String(err); + console.error(`Failed to download Bun v${props.version}: ${message}`); + process.exit(1); + }); + + if (!response.ok) { + if (response.status === 404) { + console.error(`Failed to download Bun v${props.version}: release not found.`); + } else { + console.error( + `Failed to download Bun v${props.version}: HTTP ${response.status} ${response.statusText}`, + ); + } + process.exit(1); + } + + const zipPath = join(props.tmpDir, "bun-linux-aarch64.zip"); + const arrayBuffer = await response.arrayBuffer(); + await Bun.write(zipPath, arrayBuffer); + + return zipPath; +} + +export async function extractBunBinary(props: { + zipPath: string; + tmpDir: string; +}): Promise { + console.log("Extracting Bun binary..."); + + const proc = Bun.spawnSync(["unzip", "-o", props.zipPath, "-d", props.tmpDir]); + + if (proc.exitCode !== 0) { + console.error(`Failed to extract Bun binary: ${proc.stderr.toString().trim()}`); + process.exit(1); + } + + const glob = new Glob("**/bun"); + for await (const match of glob.scan({ cwd: props.tmpDir, absolute: true })) { + if (!match.endsWith(".zip")) { + return match; + } + } + + console.error("Failed to extract Bun binary: bun executable not found in archive."); + process.exit(1); +} + +export async function compileRuntime(props: { tmpDir: string }): Promise { + console.log("Compiling runtime..."); + + const runtimeSource = resolve(import.meta.dir, "runtime.mts"); + const outDir = join(props.tmpDir, "compiled"); + mkdirSync(outDir, { recursive: true }); + + const result = await Bun.build({ + entrypoints: [runtimeSource], + outdir: outDir, + target: "bun", + minify: true, + naming: "runtime.js", + }); + + if (!result.success) { + const errors = result.logs + .filter((log) => log.level === "error") + .map((log) => log.message) + .join("\n"); + console.error(`Failed to compile runtime: ${errors || "unknown error"}`); + process.exit(1); + } + + const outputPath = join(outDir, "runtime.js"); + if (!existsSync(outputPath)) { + console.error("Failed to compile runtime: output file not produced."); + process.exit(1); + } + + return outputPath; +} + +function generateBootstrap(props: { tmpDir: string }): string { + const bootstrapContent = "#!/bin/sh\nexec /opt/bun /opt/runtime.js\n"; + const bootstrapPath = join(props.tmpDir, "bootstrap"); + writeFileSync(bootstrapPath, bootstrapContent, { mode: 0o755 }); + return bootstrapPath; +} + +async function createLayerZip(props: { + version: string; + bunBinaryPath: string; + runtimePath: string; + bootstrapPath: string; + tmpDir: string; + outDir: string; +}): Promise { + console.log("Creating layer zip..."); + + mkdirSync(props.outDir, { recursive: true }); + + // Remove any existing layer zips so only the current version is packaged + const glob = new Glob("bun-lambda-layer-*.zip"); + for (const match of glob.scanSync({ cwd: props.outDir, absolute: true })) { + rmSync(match); + } + + const outputZip = join(props.outDir, `bun-lambda-layer-${props.version}.zip`); + + const stageDir = join(props.tmpDir, "stage"); + mkdirSync(stageDir, { recursive: true }); + + const cpBun = Bun.spawnSync(["cp", props.bunBinaryPath, join(stageDir, "bun")]); + if (cpBun.exitCode !== 0) { + console.error("Failed to create layer zip: could not copy bun binary"); + process.exit(1); + } + + const cpRuntime = Bun.spawnSync(["cp", props.runtimePath, join(stageDir, "runtime.js")]); + if (cpRuntime.exitCode !== 0) { + console.error("Failed to create layer zip: could not copy runtime.js"); + process.exit(1); + } + + const cpBootstrap = Bun.spawnSync(["cp", props.bootstrapPath, join(stageDir, "bootstrap")]); + if (cpBootstrap.exitCode !== 0) { + console.error("Failed to create layer zip: could not copy bootstrap"); + process.exit(1); + } + + Bun.spawnSync(["chmod", "+x", join(stageDir, "bun")]); + Bun.spawnSync(["chmod", "+x", join(stageDir, "bootstrap")]); + + const zipProc = Bun.spawnSync(["zip", "-j", outputZip, "bootstrap", "bun", "runtime.js"], { + cwd: stageDir, + }); + + if (zipProc.exitCode !== 0) { + console.error(`Failed to create layer zip: ${zipProc.stderr.toString().trim()}`); + process.exit(1); + } + + return outputZip; +} diff --git a/command/publishLayer.ts b/command/publishLayer.ts new file mode 100644 index 0000000..27480a2 --- /dev/null +++ b/command/publishLayer.ts @@ -0,0 +1,192 @@ +#!/usr/bin/env bun +/** + * Publishes the Bun layer zip to one region and shares it with all AWS accounts. + * Idempotent: a layer version whose description names this package version is reused. + * + * Usage: + * bun command/publishLayer.ts --region --zip --bun-version \ + * --package-version --git-sha --out + * + * Needs AWS credentials with lambda:PublishLayerVersion, lambda:ListLayerVersions and + * lambda:AddLayerVersionPermission on the BunRuntime layer in the region. + */ + +import { readFileSync, writeFileSync } from "node:fs"; + +import { + AddLayerVersionPermissionCommand, + LambdaClient, + ListLayerVersionsCommand, + PublishLayerVersionCommand, + ResourceConflictException, +} from "@aws-sdk/client-lambda"; + +export const layerName = "BunRuntime"; + +// Direct upload limit of PublishLayerVersion is 50 MiB (zipped). +const maxDirectUploadBytes = 50 * 1024 * 1024; + +export interface PublishLayerProps { + readonly region: string; + readonly zip: Uint8Array; + readonly bunVersion: string; + readonly packageVersion: string; + readonly gitSha: string; + readonly client?: Pick; +} + +export interface PublishLayerResult { + readonly region: string; + readonly layerVersionArn: string; + readonly reused: boolean; +} + +export function layerDescription(props: { + readonly bunVersion: string; + readonly packageVersion: string; + readonly gitSha: string; + readonly zipSha256: string; +}): string { + return `Bun v${props.bunVersion} | package v${props.packageVersion} | git ${props.gitSha.slice(0, 12)} | sha256 ${props.zipSha256.slice(0, 16)}`; +} + +export function descriptionMatchesPackage(props: { + readonly description: string | undefined; + readonly packageVersion: string; +}): boolean { + return (props.description ?? "").split(" | ").includes(`package v${props.packageVersion}`); +} + +export async function publishLayer(props: PublishLayerProps): Promise { + if (props.zip.byteLength > maxDirectUploadBytes) { + throw new Error( + `Layer zip is ${props.zip.byteLength} bytes, above the ${maxDirectUploadBytes} byte direct upload limit. Upload it through S3 instead.`, + ); + } + + const client = props.client ?? new LambdaClient({ region: props.region }); + + const existingArn = await findVersionArn({ client, packageVersion: props.packageVersion }); + const layerVersionArn = + existingArn ?? + (await publishNewVersion({ + client, + zip: props.zip, + bunVersion: props.bunVersion, + packageVersion: props.packageVersion, + gitSha: props.gitSha, + })); + + await makePublic({ client, layerVersionArn }); + + return { region: props.region, layerVersionArn, reused: existingArn != null }; +} + +async function findVersionArn(props: { + readonly client: Pick; + readonly packageVersion: string; +}): Promise { + let marker: string | undefined; + do { + const page = await props.client.send( + new ListLayerVersionsCommand({ + LayerName: layerName, + Marker: marker, + CompatibleArchitecture: "arm64", + }), + ); + const match = (page.LayerVersions ?? []).find((version) => + descriptionMatchesPackage({ + description: version.Description, + packageVersion: props.packageVersion, + }), + ); + if (match?.LayerVersionArn != null) return match.LayerVersionArn; + marker = page.NextMarker; + } while (marker != null); + return undefined; +} + +async function publishNewVersion(props: { + readonly client: Pick; + readonly zip: Uint8Array; + readonly bunVersion: string; + readonly packageVersion: string; + readonly gitSha: string; +}): Promise { + const zipSha256 = new Bun.CryptoHasher("sha256").update(props.zip).digest("hex"); + const published = await props.client.send( + new PublishLayerVersionCommand({ + LayerName: layerName, + Description: layerDescription({ + bunVersion: props.bunVersion, + packageVersion: props.packageVersion, + gitSha: props.gitSha, + zipSha256, + }), + Content: { ZipFile: props.zip }, + CompatibleArchitectures: ["arm64"], + CompatibleRuntimes: ["provided.al2023"], + LicenseInfo: "MIT", + }), + ); + if (published.LayerVersionArn == null) { + throw new Error("PublishLayerVersion returned no LayerVersionArn."); + } + return published.LayerVersionArn; +} + +async function makePublic(props: { + readonly client: Pick; + readonly layerVersionArn: string; +}): Promise { + const version = Number(props.layerVersionArn.split(":").at(-1)); + try { + await props.client.send( + new AddLayerVersionPermissionCommand({ + LayerName: layerName, + VersionNumber: version, + StatementId: "public", + Action: "lambda:GetLayerVersion", + Principal: "*", + }), + ); + } catch (error) { + if (error instanceof ResourceConflictException) return; + throw error; + } +} + +function parseArgs(props: { readonly argv: ReadonlyArray }): Record { + const values: Record = {}; + for (let index = 0; index < props.argv.length; index += 2) { + const flag = props.argv[index]; + const value = props.argv[index + 1]; + if (!flag.startsWith("--") || value == null) { + throw new Error(`Invalid arguments near "${flag}". Expected --name value pairs.`); + } + values[flag.slice(2)] = value; + } + return values; +} + +function required(props: { readonly args: Record; readonly name: string }): string { + const value = props.args[props.name]; + if (value == null) throw new Error(`Missing --${props.name}.`); + return value; +} + +if (import.meta.main) { + const args = parseArgs({ argv: process.argv.slice(2) }); + const result = await publishLayer({ + region: required({ args, name: "region" }), + zip: readFileSync(required({ args, name: "zip" })), + bunVersion: required({ args, name: "bun-version" }), + packageVersion: required({ args, name: "package-version" }), + gitSha: required({ args, name: "git-sha" }), + }); + writeFileSync(required({ args, name: "out" }), `${JSON.stringify(result, null, 2)}\n`); + console.log( + `${result.reused ? "Reused" : "Published"} ${result.layerVersionArn} (public) in ${result.region}`, + ); +} diff --git a/command/publishRuntime.ts b/command/publishRuntime.ts new file mode 100644 index 0000000..b10c243 --- /dev/null +++ b/command/publishRuntime.ts @@ -0,0 +1,570 @@ +#!/usr/bin/env bun +/** + * Builds the Bun runtime image and publishes it as a Lambda customer-managed runtime (CMR). + * Idempotent: an existing image tag, runtime version and alias are reused or updated. + * + * Usage: + * bun command/publishRuntime.ts --region [bun-version] [--name ] + * [--repository ] [--version-name ] [--alias ]... + * [--moving-alias ]... [--release-aliases] [--result-alias ] [--public] + * [--out ] + * bun-lambda-runtime publish-runtime --region [same options] + * + * --alias is always pointed at the version. --moving-alias is pointed at the version unless it + * already points to a newer one (version names are package versions such as 4.10405.0). + * --release-aliases adds , , and latest as moving aliases. + * --public lets every AWS account use the runtime. + * + * Needs the AWS CLI (with the lambda-core commands) and Docker with buildx, and credentials with + * ECR, lambda-core and lambda:PutResourcePolicy permissions. + */ + +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { + compileRuntime, + downloadBunBinary, + extractBunBinary, + resolveVersion, + validateVersion, +} from "./layer"; + +export const defaultRuntimeName = "bun"; + +export interface ExecResult { + readonly exitCode: number; + readonly stdout: string; + readonly stderr: string; +} + +export type Exec = (props: { + readonly command: ReadonlyArray; + readonly input?: string; +}) => ExecResult; + +export interface PublishRuntimeProps { + readonly region: string; + readonly contextDir: string; + readonly runtimeName: string; + readonly repositoryName: string; + readonly versionName: string; + readonly releaseNotes: string; + readonly aliases: ReadonlyArray; + readonly movingAliases: ReadonlyArray; + readonly resultAlias: string; + readonly isPublic: boolean; + readonly exec: Exec; +} + +export interface PublishRuntimeResult { + readonly region: string; + readonly runtimeArn: string; + readonly runtimeAlias: string; + readonly runtimeVersion: string; +} + +export function aliasNamesForBunVersion(props: { + readonly bunVersion: string; +}): ReadonlyArray { + const [major, minor] = props.bunVersion.split("."); + return [props.bunVersion, `${major}.${minor}`, major, "latest"]; +} + +export function compareVersionNames(props: { + readonly left: string; + readonly right: string; +}): number { + const left = props.left.split(".").map(Number); + const right = props.right.split(".").map(Number); + if ([...left, ...right].some((part) => Number.isNaN(part))) return 0; + for (let index = 0; index < Math.max(left.length, right.length); index++) { + const difference = (left[index] ?? 0) - (right[index] ?? 0); + if (difference !== 0) return difference; + } + return 0; +} + +export function runtimeImageFiles(): { readonly dockerfile: string; readonly bootstrap: string } { + return { + // No ENTRYPOINT or CMD: an ENTRYPOINT leaves _HANDLER empty. No RUN, so building the + // arm64 image needs no emulation on an x86 host. + dockerfile: [ + "FROM public.ecr.aws/lambda/provided:al2023", + "COPY --chmod=0755 bun /usr/local/bin/bun", + "COPY runtime.js /var/runtime/runtime.js", + "COPY --chmod=0755 bootstrap /var/runtime/bootstrap", + "", + ].join("\n"), + bootstrap: "#!/bin/sh\nexec /usr/local/bin/bun /var/runtime/runtime.js\n", + }; +} + +export function publishRuntime(props: PublishRuntimeProps): PublishRuntimeResult { + const accountId = aws({ + props, + args: ["sts", "get-caller-identity", "--query", "Account", "--output", "text"], + }); + const imageUri = `${accountId}.dkr.ecr.${props.region}.amazonaws.com/${props.repositoryName}`; + + ensureRepository({ props }); + ensureImage({ props, accountId, imageUri }); + const runtimeArn = ensureRuntime({ props }); + ensureVersion({ props, imageUri }); + + for (const alias of props.aliases) { + setAlias({ props, alias }); + } + for (const alias of props.movingAliases) { + if (isAliasAhead({ props, alias })) continue; + setAlias({ props, alias }); + } + if (props.isPublic) { + makePublic({ props, runtimeArn }); + } + + return { + region: props.region, + runtimeArn, + runtimeAlias: props.resultAlias, + runtimeVersion: props.versionName, + }; +} + +export async function publishRuntimeCommand(argv: ReadonlyArray): Promise { + const args = parseArgs({ argv }); + const region = args.single.region ?? process.env.AWS_REGION ?? process.env.AWS_DEFAULT_REGION; + if (region == null) throw new Error("Missing --region."); + + const bunVersion = resolveVersion({ cliVersion: args.positional[0] }); + validateVersion({ version: bunVersion }); + + const versionName = args.single["version-name"] ?? bunVersion; + const releaseAliases = args.flags.has("release-aliases") + ? aliasNamesForBunVersion({ bunVersion }) + : []; + const movingAliases = [...args.movingAliases, ...releaseAliases]; + const aliases = + args.aliases.length === 0 && movingAliases.length === 0 ? ["latest"] : args.aliases; + const resultAlias = + args.single["result-alias"] ?? releaseAliases[1] ?? aliases[0] ?? movingAliases[0] ?? "latest"; + + const tmpDir = mkdtempSync(join(tmpdir(), "bun-runtime-")); + try { + const contextDir = await stageContext({ bunVersion, tmpDir }); + const result = publishRuntime({ + region, + contextDir, + runtimeName: args.single.name ?? defaultRuntimeName, + repositoryName: args.single.repository ?? defaultRuntimeName, + versionName, + releaseNotes: `Bun v${bunVersion}${process.env.GITHUB_SHA == null ? "" : ` | git ${process.env.GITHUB_SHA.slice(0, 12)}`}`, + aliases, + movingAliases, + resultAlias, + isPublic: args.flags.has("public"), + exec: spawnExec, + }); + const out = args.single.out; + if (out != null) writeFileSync(out, `${JSON.stringify(result, null, 2)}\n`); + console.log( + `Published runtime ${result.runtimeArn} version ${result.runtimeVersion}, alias ${result.runtimeAlias} in ${region}`, + ); + } finally { + rmSync(tmpDir, { recursive: true, force: true }); + } +} + +async function stageContext(props: { + readonly bunVersion: string; + readonly tmpDir: string; +}): Promise { + const zipPath = await downloadBunBinary({ version: props.bunVersion, tmpDir: props.tmpDir }); + const bunBinaryPath = await extractBunBinary({ zipPath, tmpDir: props.tmpDir }); + const runtimePath = await compileRuntime({ tmpDir: props.tmpDir }); + + const contextDir = join(props.tmpDir, "image"); + mkdirSync(contextDir, { recursive: true }); + const files = runtimeImageFiles(); + writeFileSync(join(contextDir, "Dockerfile"), files.dockerfile); + writeFileSync(join(contextDir, "bootstrap"), files.bootstrap); + await Bun.write(join(contextDir, "bun"), Bun.file(bunBinaryPath)); + await Bun.write(join(contextDir, "runtime.js"), Bun.file(runtimePath)); + return contextDir; +} + +function ensureRepository(props: { readonly props: PublishRuntimeProps }): void { + const found = awsTry({ + props: props.props, + args: ["ecr", "describe-repositories", "--repository-names", props.props.repositoryName], + }); + if (found != null) return; + + aws({ + props: props.props, + args: ["ecr", "create-repository", "--repository-name", props.props.repositoryName], + }); + aws({ + props: props.props, + args: [ + "ecr", + "set-repository-policy", + "--repository-name", + props.props.repositoryName, + "--policy-text", + JSON.stringify({ + Version: "2012-10-17", + Statement: [ + { + Sid: "LambdaReadAccess", + Effect: "Allow", + Principal: { Service: "lambda.amazonaws.com" }, + Action: ["ecr:BatchGetImage", "ecr:DescribeImages", "ecr:GetDownloadUrlForLayer"], + }, + ], + }), + ], + }); +} + +function ensureImage(props: { + readonly props: PublishRuntimeProps; + readonly accountId: string; + readonly imageUri: string; +}): void { + const existing = awsTry({ + props: props.props, + args: [ + "ecr", + "describe-images", + "--repository-name", + props.props.repositoryName, + "--image-ids", + `imageTag=${props.props.versionName}`, + ], + }); + if (existing != null) return; + + const password = aws({ props: props.props, args: ["ecr", "get-login-password"] }); + run({ + props: props.props, + command: [ + "docker", + "login", + "--username", + "AWS", + "--password-stdin", + `${props.accountId}.dkr.ecr.${props.props.region}.amazonaws.com`, + ], + input: password, + }); + // The builder needs the docker-container driver for the image type output below. + const created = props.props.exec({ + command: ["docker", "buildx", "create", "--name", "bun-runtime-builder", "--use"], + }); + if (created.exitCode !== 0) { + run({ + props: props.props, + command: ["docker", "buildx", "use", "bun-runtime-builder"], + }); + } + // Docker v2 Schema 2 (oci-mediatypes=false) is what Lambda CMR images were verified with. + run({ + props: props.props, + command: [ + "docker", + "buildx", + "build", + "--platform", + "linux/arm64", + "--tag", + `${props.imageUri}:${props.props.versionName}`, + "--output", + "type=image,oci-mediatypes=false", + "--provenance=false", + "--sbom=false", + "--push", + props.props.contextDir, + ], + }); +} + +function ensureRuntime(props: { readonly props: PublishRuntimeProps }): string { + const state = awsTry({ + props: props.props, + args: [ + "lambda-core", + "get-runtime", + "--runtime-name", + props.props.runtimeName, + "--query", + "State", + "--output", + "text", + ], + }); + if (state === "PENDING_DELETION") { + throw new Error( + `Runtime ${props.props.runtimeName} is PENDING_DELETION and its name is reserved. Use another --name.`, + ); + } + if (state == null) { + aws({ + props: props.props, + args: [ + "lambda-core", + "create-runtime", + "--name", + props.props.runtimeName, + "--description", + "Bun runtime for AWS Lambda", + "--license-info", + "MIT", + ], + }); + } + return aws({ + props: props.props, + args: [ + "lambda-core", + "get-runtime", + "--runtime-name", + props.props.runtimeName, + "--query", + "Arn", + "--output", + "text", + ], + }); +} + +function ensureVersion(props: { + readonly props: PublishRuntimeProps; + readonly imageUri: string; +}): void { + const existing = awsTry({ + props: props.props, + args: [ + "lambda-core", + "get-runtime-version", + "--runtime-name", + props.props.runtimeName, + "--name", + props.props.versionName, + ], + }); + if (existing == null) { + aws({ + props: props.props, + args: [ + "lambda-core", + "create-runtime-version", + "--runtime-name", + props.props.runtimeName, + "--name", + props.props.versionName, + "--image-uri", + `${props.imageUri}:${props.props.versionName}`, + "--release-notes", + props.props.releaseNotes, + ], + }); + } + aws({ + props: props.props, + args: [ + "lambda-core", + "wait", + "runtime-version-active", + "--runtime-name", + props.props.runtimeName, + "--name", + props.props.versionName, + ], + }); +} + +function currentAliasVersion(props: { + readonly props: PublishRuntimeProps; + readonly alias: string; +}): string | undefined { + return awsTry({ + props: props.props, + args: [ + "lambda-core", + "get-runtime-alias", + "--runtime-name", + props.props.runtimeName, + "--name", + props.alias, + "--query", + "RuntimeVersion", + "--output", + "text", + ], + }); +} + +function isAliasAhead(props: { + readonly props: PublishRuntimeProps; + readonly alias: string; +}): boolean { + const current = currentAliasVersion(props); + if (current == null) return false; + return compareVersionNames({ left: current, right: props.props.versionName }) > 0; +} + +function setAlias(props: { readonly props: PublishRuntimeProps; readonly alias: string }): void { + const exists = currentAliasVersion(props) != null; + aws({ + props: props.props, + args: [ + "lambda-core", + exists ? "update-runtime-alias" : "create-runtime-alias", + "--runtime-name", + props.props.runtimeName, + "--name", + props.alias, + "--runtime-version", + props.props.versionName, + ], + }); + aws({ + props: props.props, + args: [ + "lambda-core", + "wait", + "runtime-alias-active", + "--runtime-name", + props.props.runtimeName, + "--name", + props.alias, + ], + }); +} + +// A policy on the runtime ARN is what works; policies on the alias or version ARN are rejected. +function makePublic(props: { + readonly props: PublishRuntimeProps; + readonly runtimeArn: string; +}): void { + const existing = awsTry({ + props: props.props, + args: ["lambda", "get-resource-policy", "--resource-arn", props.runtimeArn], + }); + if (existing?.includes("AssociateRuntimeAlias") === true) return; + + aws({ + props: props.props, + args: [ + "lambda", + "put-resource-policy", + "--resource-arn", + props.runtimeArn, + "--policy", + JSON.stringify({ + Version: "2012-10-17", + Statement: [ + { + Sid: "public", + Effect: "Allow", + Principal: "*", + Action: "lambda:AssociateRuntimeAlias", + Resource: [props.runtimeArn, `${props.runtimeArn}/*`], + }, + ], + }), + ], + }); +} + +function aws(props: { + readonly props: PublishRuntimeProps; + readonly args: ReadonlyArray; +}): string { + return run({ + props: props.props, + command: ["aws", ...props.args, "--region", props.props.region, "--no-cli-pager"], + }); +} + +function awsTry(props: { + readonly props: PublishRuntimeProps; + readonly args: ReadonlyArray; +}): string | undefined { + const result = props.props.exec({ + command: ["aws", ...props.args, "--region", props.props.region, "--no-cli-pager"], + }); + if (result.exitCode !== 0) return undefined; + return result.stdout.trim(); +} + +function run(props: { + readonly props: PublishRuntimeProps; + readonly command: ReadonlyArray; + readonly input?: string; +}): string { + const result = props.props.exec({ command: props.command, input: props.input }); + if (result.exitCode === 0) return result.stdout.trim(); + throw new Error( + `Command failed (${result.exitCode}): ${props.command.slice(0, 4).join(" ")}\n${result.stderr.trim()}`, + ); +} + +function spawnExec(props: { + readonly command: ReadonlyArray; + readonly input?: string; +}): ExecResult { + const processResult = Bun.spawnSync([...props.command], { + stdin: props.input == null ? "ignore" : new TextEncoder().encode(props.input), + }); + return { + exitCode: processResult.exitCode ?? -1, + stdout: processResult.stdout.toString(), + stderr: processResult.stderr.toString(), + }; +} + +interface ParsedArgs { + readonly positional: ReadonlyArray; + readonly single: Record; + readonly aliases: ReadonlyArray; + readonly movingAliases: ReadonlyArray; + readonly flags: ReadonlySet; +} + +function parseArgs(props: { readonly argv: ReadonlyArray }): ParsedArgs { + const positional: Array = []; + const single: Record = {}; + const aliases: Array = []; + const movingAliases: Array = []; + const flags = new Set(); + + for (let index = 0; index < props.argv.length; index++) { + const arg = props.argv[index]; + if (!arg.startsWith("--")) { + positional.push(arg); + continue; + } + const name = arg.slice(2); + if (name === "public" || name === "release-aliases") { + flags.add(name); + continue; + } + const value = props.argv[++index]; + if (value == null) throw new Error(`--${name} needs a value.`); + if (name === "alias") { + aliases.push(value); + } else if (name === "moving-alias") { + movingAliases.push(value); + } else { + single[name] = value; + } + } + return { positional, single, aliases, movingAliases, flags }; +} + +if (import.meta.main) { + await publishRuntimeCommand(process.argv.slice(2)); +} diff --git a/command/writeArtifacts.ts b/command/writeArtifacts.ts new file mode 100644 index 0000000..c56bbc3 --- /dev/null +++ b/command/writeArtifacts.ts @@ -0,0 +1,90 @@ +#!/usr/bin/env bun +/** + * Merges per-region publish results into src/artifacts.json (read by the package build). + * + * Usage: + * bun command/writeArtifacts.ts --package-version --bun-version ... + */ + +import { readFileSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; + +import type { Artifacts, RegionArtifacts } from "../src/artifacts"; + +export interface RegionResult { + readonly region: string; + readonly layerVersionArn?: string; + readonly runtimeArn?: string; + readonly runtimeAlias?: string; +} + +/** + * Results of the same region (layer and runtime publish steps) are merged into one entry. + */ +export function mergeArtifacts(props: { + readonly packageVersion: string; + readonly bunVersion: string; + readonly results: ReadonlyArray; +}): Artifacts { + const partial: Record> = {}; + for (const result of props.results) { + const { region, ...fields } = result; + const previous = partial[region] ?? {}; + for (const key of Object.keys(fields) as Array) { + if (previous[key] != null && fields[key] != null) { + throw new Error(`Duplicate result for region ${region}: ${key}.`); + } + } + partial[region] = { ...previous, ...fields }; + } + + const regions: Record = {}; + for (const [region, fields] of Object.entries(partial)) { + if (fields.layerVersionArn == null) { + throw new Error(`Missing layer result for region ${region}.`); + } + regions[region] = { + layerVersionArn: fields.layerVersionArn, + ...(fields.runtimeArn == null ? {} : { runtimeArn: fields.runtimeArn }), + ...(fields.runtimeAlias == null ? {} : { runtimeAlias: fields.runtimeAlias }), + }; + } + const sortedRegions = Object.fromEntries( + Object.entries(regions).sort(([left], [right]) => left.localeCompare(right)), + ); + return { + packageVersion: props.packageVersion, + bunVersion: props.bunVersion, + regions: sortedRegions, + }; +} + +if (import.meta.main) { + const argv = process.argv.slice(2); + const files: Array = []; + let packageVersion: string | undefined; + let bunVersion: string | undefined; + for (let index = 0; index < argv.length; index++) { + if (argv[index] === "--package-version") { + packageVersion = argv[++index]; + } else if (argv[index] === "--bun-version") { + bunVersion = argv[++index]; + } else { + files.push(argv[index]); + } + } + if (packageVersion == null || bunVersion == null || files.length === 0) { + throw new Error( + "Usage: writeArtifacts.ts --package-version --bun-version ...", + ); + } + + const artifacts = mergeArtifacts({ + packageVersion, + bunVersion, + results: files.map((file) => JSON.parse(readFileSync(file, "utf8")) as RegionResult), + }); + const target = resolve(import.meta.dir, "..", "src", "artifacts.json"); + writeFileSync(target, `${JSON.stringify(artifacts, null, 2)}\n`); + console.log(`Wrote ${Object.keys(artifacts.regions).length} region(s) to ${target}`); +} diff --git a/docs/adr-public-artifacts.md b/docs/adr-public-artifacts.md new file mode 100644 index 0000000..79cf830 --- /dev/null +++ b/docs/adr-public-artifacts.md @@ -0,0 +1,139 @@ +# ADR: Publish the Bun runtime as public AWS artifacts and slim the npm package + +## Status + +Accepted (targets v4.0) + +## Context + +Today the npm package ships the Bun layer zip (about 50 MB unpacked, `dist/bun-lambda-layer-.zip`). +`BunLambdaLayer` turns it into a CDK asset, so every consumer uploads and publishes their own copy +of the layer in their own account and region. This works everywhere with no trust relationship, +but it makes the package large and slow to install. + +Lambda customer-managed runtimes (CMR) reached GA. Findings from testing them against this runtime +(benchmark repo `beesolve/lambda-cmr-beta-bench`, Bun 1.4.0 and 1.4.4, eu-west-1): + +- A CMR is a runtime resource with immutable versions (container image) and aliases. Functions use it + with `aws lambda create-function --runtime custom --runtime-config RuntimeArn=...,RuntimeAlias=...`. +- **Sharing works.** A function in another account can use a runtime owned by account A once account A + puts a resource policy on the runtime ARN with `aws lambda put-resource-policy` (action + `lambda:AssociateRuntimeAlias`). It worked for a specific account and for `Principal: "*"`, including + from an account outside the owner's AWS Organization. Policies on the alias or version ARN are rejected. +- The consumer needs no ECR permission. The image stays in the owner's private ECR repository, readable + by the Lambda service principal. +- The runtime image must not set `ENTRYPOINT` or `CMD` (an `ENTRYPOINT` leaves `_HANDLER` empty), must + contain `/var/task` and `/etc/hosts` (use `provided:al2023`), and must not use `/opt`. +- Runtime deletion is soft: `PENDING_DELETION` for 30 days, name reserved. +- Cold start difference between CMR and the layer is real but modest for the Bun client + (p50 about 444-480 ms for CMR against about 620-660 ms for the layer). +- aws-cdk-lib 2.277.0 has no runtime resources and no `runtimeConfig` on `CfnFunction`. From 2.278.0 + the `lambda.mixins.FunctionRuntimeConfig` mixin sets `runtimeConfig` on a function. There are still no + CDK resources for creating runtimes, so publishing uses the AWS CLI. + +## Decision + +1. Publish the runtime as **public artifacts in a BeeSolve AWS account**, in these regions: + eu-north-1 (Stockholm), eu-central-1 (Frankfurt), eu-west-1 (Ireland), us-east-1, us-west-2 (Oregon). + Per Bun version, CI publishes: + - a Lambda layer version (shared with all accounts via `add-layer-version-permission --principal "*"`) + - a CMR runtime version plus a Bun-version alias and a `latest` alias, with a runtime resource policy + for `Principal: "*"` + - the runtime image in a private ECR repository per region +2. Publishing is done with the AWS CLI from GitHub Actions through OIDC, not with CDK. +3. The npm package **stops shipping the layer zip**. It ships a generated `artifacts.json` that maps the + package version to published ARNs per region. +4. `BunLambdaLayer` resolves the layer ARN from `artifacts.json` for the stack's region. If the region is + unresolved or unsupported it throws an `Error` that lists supported regions and the escape hatches. +5. Users can always bring their own artifacts: + - build the layer zip themselves with a shipped command and use it as a CDK asset + - publish their own CMR with a shipped command that uses the AWS CLI + - pass an explicit layer ARN or runtime ARN and alias +6. Published layer versions and runtime versions are **never deleted**, because consumers' functions + reference them. +7. **The customer-managed runtime is the default in v4.** `BunFunction` runs on the published CMR and + uses the `@beesolve/lambda-bun-runtime` ARN and alias for the stack's region from `artifacts.json`. + It applies `lambda.mixins.FunctionRuntimeConfig` (aws-cdk-lib 2.278.0 or newer). The optional prop + `bunRuntime: { runtimeArn, runtimeAlias }` overrides the ARN and alias, for internal tests and for + users who publish their own runtime. `BunFunctionWithLayer` is the separate construct for the layer + path. The two never share a construct. +8. **Runtime aliases follow the Bun minor line.** Bun is pre-2.0 and minor releases can break things, + so the alias unit is `major.minor` instead of only the major as in the Node.js managed runtimes. + Per published runtime version CI sets: + - `pkg-`: set once per package version and never moved, the target of the release + integration test + - ``: the Bun version pin, moves only for internal patch releases of the same Bun version + - ``: the latest patch of the minor line, the default of `BunFunction` + - ``: the latest release of the major, opt-in + - `latest`: the newest release, for internal tests + + Patch releases move `` and `` automatically, but only after the integration test + passes against the new runtime version, and an alias never moves to an older version. A new minor creates a new `` alias and leaves the + previous one in place. Only the newest minor line is patched automatically. Older lines keep their + last patch, because Bun does not maintain release branches for old minors. Users who need an old + line fix can pass an explicit alias or publish their own runtime. A new major creates `` and + `` and moves nothing across the boundary. Each package version pins its default alias in + `artifacts.json`. + +9. Versioning keeps the scheme `..`, with the + major bumped to 4. + +## Consequences + +### Positive + +- The tarball shrinks from tens of MB to a few KB, install is fast. +- One layer per region instead of one per consumer stack and account. +- CMR is the default, so consumers get the faster cold start without building anything. +- Patch fixes in Bun reach `` users without a redeploy. + +### Negative + +- **Breaking change.** `BunFunction` is now CMR only, the layer path moved to `BunFunctionWithLayer`, and + aws-cdk-lib 2.278.0 or newer is required. Consumers outside the five regions must build the layer themselves or pass an ARN. + The 3.x line remains the last version that works in every region. +- Consumers depend on artifacts in a third-party account. Mitigations: never delete versions, put the + git SHA and the zip SHA-256 in each layer version description and in the GitHub release notes, keep the + build script so users can reproduce the layer. +- Moving an alias changes running functions on their next cold start. A broken Bun patch would reach + `` users, which is why the alias moves only after the integration test passes. +- Release now has a publish step that must succeed in all five regions before `npm publish`, and must be + idempotent for reruns. +- The integration test needs a published layer for the version under test (see open questions). + +### Neutral + +- The layer zip stays a GitHub Release asset. + +## Alternatives considered + +1. **Keep shipping the zip.** No new trust or failure modes, but the package stays large. +2. **Public S3 zip as the layer source.** `PublishLayerVersion` accepts an S3 location, but it has to be + in the same region as the layer, so it needs a public bucket per region and consumers still publish + their own copy. A shared layer is simpler. +3. **CMR only, drop the layer.** Not possible for all users: CMR is new, needs a recent CLI and + aws-cdk-lib, and tenancy settings are account-gated in some accounts. The layer stays as + `BunFunctionWithLayer`. +4. **Per-consumer CMR built at deploy time (CDK asset and custom resource).** Needs Docker at synth and a + custom resource that AWS will replace with a native resource. + +## Resolved questions + +1. **Integration test ordering.** The release publishes to `eu-central-1` first, runs the integration + test against that published layer and runtime (alias `pkg-`), and only then publishes all regions + again (idempotent), sets the moving aliases, and publishes to npm. Pull request + runs have no published layer and deploy a layer built from source (`BUN_LAYER_ZIP`). +2. **Designated account.** The BeeSolve artifacts account, reached from GitHub Actions through an OIDC + role limited to this repository and the `main` branch. Setup is in `docs/aws-oidc-setup-publish.md`. +3. **Runtime image base.** The image is `provided:al2023` with the Bun binary from the GitHub release zip + that also goes into the layer, so layer and runtime contain the same binary by construction. The image + has no `ENTRYPOINT`, `CMD` or `RUN`. The runtime version name is the package version and the image + tag is the same name, so an internal patch release creates a new version. +4. **API shape.** `BunFunction` is CMR. `BunFunctionWithLayer` takes `bunLayer`. `new BunLambdaLayer(scope, id)` resolves the published layer. Props `layerVersionArn` + or `assetZipPath` (mutually exclusive) select your own layer. `BunFunctionWithLayer.bunLayer` accepts any + `ILayerVersion`. The shipped CLI `bun-lambda-runtime build-layer` builds the zip for `assetZipPath`. + +## Open questions + +1. Adding regions later is a one-line change to the region list, opt-in regions need extra account setup. +2. Whether to patch the previous minor line automatically as well (current decision: no). diff --git a/docs/aws-oidc-setup-publish.md b/docs/aws-oidc-setup-publish.md new file mode 100644 index 0000000..03c3b32 --- /dev/null +++ b/docs/aws-oidc-setup-publish.md @@ -0,0 +1,213 @@ +# AWS OIDC Trust Setup for Publishing Artifacts + +One-time setup so the `release.yml` workflow can publish the public Bun layer to the BeeSolve +artifacts account without long-lived credentials. This is separate from the integration test role in +[aws-oidc-setup.md](./aws-oidc-setup.md), which lives in a sandbox account. + +The role can publish and share one layer (`BunRuntime`) and one customer-managed runtime (`bun`, +with its ECR repository `bun`) in five regions. It cannot touch anything else. + +Regions: `eu-north-1`, `eu-central-1`, `eu-west-1`, `us-east-1`, `us-west-2`. + +## Prerequisites + +- AWS CLI with admin access to the artifacts account (profile `customer-managed-runtimes-prod`) +- GitHub CLI (`gh`) authenticated to the repo +- No SCP in the account or organization that blocks `lambda:AddLayerVersionPermission` or + `lambda:PutResourcePolicy` with `Principal: "*"` + +Set these once for the commands below: + +```bash +export AWS_PROFILE=customer-managed-runtimes-prod +ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text) +``` + +--- + +## Step 1 - Create the OIDC provider (once per account) + +Skip if it exists (`aws iam list-open-id-connect-providers`). + +```bash +aws iam create-open-id-connect-provider \ + --url https://token.actions.githubusercontent.com \ + --client-id-list sts.amazonaws.com \ + --thumbprint-list 6938fd4d98bab03faadb97b34396831e3780aea1 +``` + +--- + +## Step 2 - Trust policy + +Only workflows running on `main` of this repository can assume the role. + +```bash +cat > trust.json < publish-policy.json < The runtime and ECR actions come from the Lambda documentation on customer-managed runtimes +> (`ecr:BatchGetImage` and `ecr:GetDownloadUrlForLayer` are required to create a runtime version). The +> resource types of `ListLayerVersions` and `PublishLayerVersion` were not verified against the IAM reference. If the first release fails with `AccessDenied`, read the denied action and +> resource from the error message and adjust this policy. Do not widen it to `lambda:*` on `*`. + +--- + +## Step 4 - Create the role + +```bash +aws iam create-role \ + --role-name GhActionsBunPublish \ + --assume-role-policy-document file://trust.json + +aws iam put-role-policy \ + --role-name GhActionsBunPublish \ + --policy-name PublishBunLayer \ + --policy-document file://publish-policy.json + +ROLE_ARN=$(aws iam get-role --role-name GhActionsBunPublish --query Role.Arn --output text) +``` + +--- + +## Step 5 - Store the role ARN in GitHub + +```bash +gh secret set AWS_PUBLISH_ROLE_ARN --repo BeeSolve/lambda-bun-runtime --body "$ROLE_ARN" +``` + +The release workflow reads `secrets.AWS_PUBLISH_ROLE_ARN`. The integration role keeps using +`secrets.AWS_INTEG_ROLE_ARN`. + +--- + +## Step 6 - Let the integration account use the published layer + +The integration test deploys a function that uses the published layer from the artifacts account. +The CloudFormation execution role in the integration account needs `lambda:GetLayerVersion` on it. Add this +statement to the scoped policy in [aws-oidc-setup.md](./aws-oidc-setup.md) (already listed there) with the +artifacts account ID in place of ``. + +--- + +## What the release does with this role + +1. Publishes the layer and the runtime version in `eu-central-1`. The runtime gets only the alias + `pkg-`. The integration test runs against it. +2. In all five regions, publishes the layer and the runtime version (idempotent), sets the moving aliases + ``, ``, `` and `latest`, and makes the runtime public. +3. Only then publishes to npm. + +Layer versions and runtime versions are never deleted: consumers' functions reference them. Reruns are safe. +A layer version whose description names the package version is reused, and so are an existing image tag +and runtime version. A moving alias never moves to an older version. diff --git a/docs/aws-oidc-setup.md b/docs/aws-oidc-setup.md index 7c5f8f1..9ce68e1 100644 --- a/docs/aws-oidc-setup.md +++ b/docs/aws-oidc-setup.md @@ -169,6 +169,15 @@ Save as `cfn-exec-policy.json`, replacing `` throughout. This covers "arn:aws:lambda:eu-central-1::layer:BunRuntime:*" ] }, + { + "Sid": "UsePublishedBunArtifacts", + "Effect": "Allow", + "Action": ["lambda:GetLayerVersion", "lambda:AssociateRuntimeAlias"], + "Resource": [ + "arn:aws:lambda:eu-central-1::layer:BunRuntime:*", + "arn:aws:lambda:eu-central-1::runtime/bun/alias/*" + ] + }, { "Sid": "IAMPassAndManageLambdaRoles", "Effect": "Allow", diff --git a/docs/how-to/custom-layer.md b/docs/how-to/custom-layer.md new file mode 100644 index 0000000..ff3c1ee --- /dev/null +++ b/docs/how-to/custom-layer.md @@ -0,0 +1,67 @@ +# How to: Use a layer instead of the runtime + +> Full working example: https://github.com/BeeSolve/lambda-bun-runtime/tree/main/examples/sample-app + +`BunFunctionWithLayer` runs Bun from a layer on `provided.al2023` instead of the customer-managed +runtime. Create the layer with `BunLambdaLayer` and pass it as `bunLayer`: + +```ts +const bunLayer = new BunLambdaLayer(this, "BunLayer"); +new BunFunctionWithLayer(this, "ApiFn", { entrypoint: `${__dirname}/api.ts`, bunLayer }); +``` + +`new BunLambdaLayer(this, "BunLayer")` looks up the layer BeeSolve publishes for this +package version in the stack's region (`eu-north-1`, `eu-central-1`, `eu-west-1`, +`us-east-1`, `us-west-2`). It throws at synth when the stack has no concrete region or the +region has no published layer. Two props cover those cases. + +## Prerequisites + +- `@beesolve/lambda-bun-runtime` installed +- [Bun](https://bun.sh) installed (only for building the layer yourself) + +## Steps + +### 1. Use an existing layer ARN + +If you already published the layer (or want to pin a specific published version), pass its ARN: + +```ts +import { BunLambdaLayer } from "@beesolve/lambda-bun-runtime"; + +const bunLayer = new BunLambdaLayer(this, "BunLayer", { + layerVersionArn: "arn:aws:lambda:eu-west-3:123456789012:layer:BunRuntime:1", +}); +``` + +### 2. Or build the layer zip and deploy it as a CDK asset + +Build the zip for the Bun version this package targets (downloads the Bun binary from +the official GitHub release, no AWS access needed): + +```sh +bunx bun-lambda-runtime build-layer --out lib +``` + +Pass a version as the first argument to build a different Bun release, for example +`bunx bun-lambda-runtime build-layer 1.4.4 --out lib`. Then use the zip: + +```ts +const bunLayer = new BunLambdaLayer(this, "BunLayer", { + assetZipPath: "lib/bun-lambda-layer-1.4.4.zip", +}); +``` + +CDK publishes the layer in your own account during `cdk deploy`. + +## Common Pitfalls + +- **Only one option at a time.** `layerVersionArn` and `assetZipPath` are mutually exclusive. +- **arm64 only.** The layer is built for `arm64` and `PROVIDED_AL2023`. +- **Environment-agnostic stacks.** Without `env.region` and no prop, the published layer cannot be + resolved. Set the region on the stack or pass one of the props above. + +## See Also + +- [Getting Started](./getting-started.md) +- [Full example](https://github.com/BeeSolve/lambda-bun-runtime/tree/main/examples/sample-app) diff --git a/docs/how-to/custom-runtime.md b/docs/how-to/custom-runtime.md new file mode 100644 index 0000000..98aa288 --- /dev/null +++ b/docs/how-to/custom-runtime.md @@ -0,0 +1,58 @@ +# How to: Publish your own Bun runtime + +> Full working example: https://github.com/BeeSolve/lambda-bun-runtime/tree/main/examples/sample-app + +Use this when your region has no published runtime, or when you want to own the runtime your +functions run on. The command builds the runtime image, pushes it to a private ECR repository in your +account, and creates the customer-managed runtime, its version and an alias. + +## Prerequisites + +- `@beesolve/lambda-bun-runtime` installed +- A recent AWS CLI that has the `aws lambda-core` commands, and credentials for the target account +- Docker with buildx (the image is built for `linux/arm64`; the build runs no emulated commands) + +## Steps + +### 1. Publish the runtime + +```sh +bunx bun-lambda-runtime publish-runtime --region eu-west-3 --alias latest +``` + +Pass a Bun version as the first positional argument to publish another release. Options: + +- `--name ` and `--repository `: both default to `bun` +- `--version-name `: defaults to the Bun version. Runtime versions are immutable +- `--alias `: repeatable, always pointed at the version. Defaults to `latest` +- `--public`: let every AWS account use the runtime (a resource policy on the runtime ARN) +- `--out `: write the result as JSON + +The command is safe to rerun: an existing image tag, runtime and version are reused, and aliases are updated. + +### 2. Use it in CDK + +```ts +const fn = new BunFunction(this, "ApiFn", { + entrypoint: `${__dirname}/api.ts`, + bunRuntime: { + runtimeArn: "arn:aws:lambda:eu-west-3:123456789012:runtime/bun", + runtimeAlias: "latest", + }, +}); +``` + +`runtimeAlias` defaults to `latest` when you pass only `runtimeArn`. + +## Common Pitfalls + +- **Deleted runtimes keep their name.** Deleting a runtime is soft (`PENDING_DELETION` for 30 days), so + the name cannot be reused. The command stops with an error; pick another `--name`. +- **Same account or shared.** Functions in other accounts can use the runtime only after `--public` + or a resource policy for their account. +- **Do not delete versions that functions use.** + +## See Also + +- [Getting Started](./getting-started.md) +- [Use a layer instead of the runtime](./custom-layer.md) diff --git a/docs/how-to/getting-started.md b/docs/how-to/getting-started.md index aed326e..4551999 100644 --- a/docs/how-to/getting-started.md +++ b/docs/how-to/getting-started.md @@ -2,13 +2,15 @@ > Full working example: https://github.com/BeeSolve/lambda-bun-runtime/tree/main/examples/sample-app -This package provides two AWS CDK constructs: `BunLambdaLayer` (the prebuilt Bun -runtime layer) and `BunFunction` (a `lambda.Function` that runs on it). Functions -run on `PROVIDED_AL2023` / `arm64`. +`BunFunction` is a `lambda.Function` that runs on the Bun customer-managed runtime (CMR) +BeeSolve publishes for this package version. It uses the `custom` runtime on `arm64` and sets +`runtimeConfig` with the `lambda.mixins.FunctionRuntimeConfig` mixin. ## Prerequisites -- An AWS CDK app (`aws-cdk-lib` v2) +- An AWS CDK app with `aws-cdk-lib` 2.278.0 or newer and a stack that has a concrete region + (`env: { region: "eu-central-1" }`). Published runtimes exist in `eu-north-1`, + `eu-central-1`, `eu-west-1`, `us-east-1` and `us-west-2` - A handler file written for Bun (`.ts` or precompiled `.js`) ## Steps @@ -24,28 +26,24 @@ bun add @beesolve/lambda-bun-runtime `aws-cdk-lib` and `constructs` are peer dependencies - install them if your app does not already have them. -### 2. Create the layer once, then wrap each handler +### 2. Wrap each handler -Add the layer a single time per stack and pass it to every `BunFunction`. Point -`entrypoint` at a `.ts` file (built with Bun during CDK synth) or a precompiled +Point `entrypoint` at a `.ts` file (built with Bun during CDK synth) or a precompiled `.js` file. ```ts import * as path from "node:path"; import { Stack } from "aws-cdk-lib"; import { FunctionUrlAuthType } from "aws-cdk-lib/aws-lambda"; -import { BunFunction, BunLambdaLayer } from "@beesolve/lambda-bun-runtime"; +import { BunFunction } from "@beesolve/lambda-bun-runtime"; import type { Construct } from "constructs"; export class ApiStack extends Stack { constructor(scope: Construct, id: string) { super(scope, id); - const bunLayer = new BunLambdaLayer(this, "BunLayer"); - const api = new BunFunction(this, "ApiFn", { entrypoint: path.join(__dirname, "../src/http-v2.ts"), - bunLayer, }); api.addFunctionUrl({ authType: FunctionUrlAuthType.NONE }); @@ -56,16 +54,33 @@ export class ApiStack extends Stack { The handler export defaults to `handler`. Override it with `exportName` if your file exports a differently-named function. +### 3. Optional: choose the runtime alias + +By default the function uses the alias `.` for the Bun version of this package +version. Patch releases of Bun move that alias, and your function picks them up on its next cold +start. Pass `bunRuntime.runtimeAlias` to choose another published alias: + +| Alias | Moves to | +| -------- | ------------------------------------------------- | +| `1.4.5` | the Bun version, only for internal patch releases | +| `1.4` | the latest patch of the minor line (the default) | +| `1` | the latest 1.x release | +| `latest` | the newest release | + ## Common Pitfalls -- **The layer is required.** `BunFunction` needs `bunLayer` - create one - `BunLambdaLayer` per stack and reuse it across functions. +- **Region must be known and published.** An environment-agnostic stack or a region + without a published runtime throws at synth. Set `bunRuntime.runtimeArn` to a runtime you + published, see [Publish your own runtime](./custom-runtime.md). +- **Do not combine runtime and layer.** `BunFunction` never uses a layer. Use + `BunFunctionWithLayer` for the layer path, see [Use a layer instead of the runtime](./custom-layer.md). - **Entrypoint extension matters.** A `.ts` entrypoint is built with Bun at synth time; a `.js` entrypoint is used as-is. The type only accepts `.ts` or `.js`. -- **arm64 only.** The layer is published for `arm64` / `PROVIDED_AL2023`; do not - override `architecture` or `runtime`. +- **arm64 only.** Do not override `architecture` or `runtime`. ## See Also +- [Publish your own runtime](./custom-runtime.md) +- [Use a layer instead of the runtime](./custom-layer.md) - [README](../../README.md) - handler signatures, Fetch API support, and response streaming - [Full example on GitHub](https://github.com/BeeSolve/lambda-bun-runtime/tree/main/examples/sample-app) diff --git a/examples/sample-app/bin/app.ts b/examples/sample-app/bin/app.ts index e633267..5d29d71 100644 --- a/examples/sample-app/bin/app.ts +++ b/examples/sample-app/bin/app.ts @@ -3,4 +3,9 @@ import { App } from "aws-cdk-lib"; import { SampleStack } from "../lib/sample-stack"; const app = new App(); -new SampleStack(app, process.env.INTEG_STACK_NAME ?? "BunLayerInteg-local"); +new SampleStack(app, process.env.INTEG_STACK_NAME ?? "BunLayerInteg-local", { + env: { + account: process.env.CDK_DEFAULT_ACCOUNT, + region: process.env.CDK_DEFAULT_REGION, + }, +}); diff --git a/examples/sample-app/lib/sample-stack.ts b/examples/sample-app/lib/sample-stack.ts index d4b7fa7..74cfdc4 100644 --- a/examples/sample-app/lib/sample-stack.ts +++ b/examples/sample-app/lib/sample-stack.ts @@ -4,7 +4,7 @@ import * as apigw from "aws-cdk-lib/aws-apigateway"; import * as iam from "aws-cdk-lib/aws-iam"; import * as lambda from "aws-cdk-lib/aws-lambda"; import * as s3 from "aws-cdk-lib/aws-s3"; -import { BunFunction, BunLambdaLayer } from "@beesolve/lambda-bun-runtime"; +import { BunFunction, BunFunctionWithLayer, BunLambdaLayer } from "@beesolve/lambda-bun-runtime"; import { Construct } from "constructs"; const src = (file: string) => path.join(__dirname, "../src", file); @@ -13,10 +13,15 @@ export class SampleStack extends Stack { constructor(scope: Construct, id: string, props?: StackProps) { super(scope, id, props); - const bunLayer = new BunLambdaLayer(this, "BunLayer"); + // Published layer by default. Set BUN_LAYER_ZIP to deploy a locally built layer zip + // (PR integration runs, where no layer is published yet). + const layerZip = process.env.BUN_LAYER_ZIP; + const bunLayer = new BunLambdaLayer(this, "BunLayer", { + ...(layerZip == null ? {} : { assetZipPath: layerZip }), + }); // HTTP v2 — Function URL - const httpV2Fn = new BunFunction(this, "HttpV2Fn", { + const httpV2Fn = new BunFunctionWithLayer(this, "HttpV2Fn", { entrypoint: src("http-v2.ts"), bunLayer, }); @@ -25,7 +30,7 @@ export class SampleStack extends Stack { }); // HTTP v2 plain (raw event, no adapter) — Function URL - const httpV2PlainFn = new BunFunction(this, "HttpV2PlainFn", { + const httpV2PlainFn = new BunFunctionWithLayer(this, "HttpV2PlainFn", { entrypoint: src("http-v2-plain.ts"), bunLayer, }); @@ -34,7 +39,7 @@ export class SampleStack extends Stack { }); // HTTP v1 — REST API - const httpV1Fn = new BunFunction(this, "HttpV1Fn", { + const httpV1Fn = new BunFunctionWithLayer(this, "HttpV1Fn", { entrypoint: src("http-v1.ts"), bunLayer, }); @@ -44,13 +49,20 @@ export class SampleStack extends Stack { }); // Echo — direct invoke - const echoFn = new BunFunction(this, "EchoFn", { + const echoFn = new BunFunctionWithLayer(this, "EchoFn", { entrypoint: src("echo.ts"), bunLayer, }); + // Echo on the customer-managed runtime. Needs the published runtime for the stack's region, + // so it is only deployed when BUN_CMR=1 (release runs). + const cmrEchoFn = + process.env.BUN_CMR === "1" + ? new BunFunction(this, "CmrEchoFn", { entrypoint: src("echo.ts") }) + : undefined; + // Streaming — async generator handler, invoked via InvokeWithResponseStream - const streamingFn = new BunFunction(this, "StreamingFn", { + const streamingFn = new BunFunctionWithLayer(this, "StreamingFn", { entrypoint: src("streaming.ts"), bunLayer, }); @@ -60,7 +72,7 @@ export class SampleStack extends Stack { autoDeleteObjects: true, removalPolicy: RemovalPolicy.DESTROY, }); - const s3WriterFn = new BunFunction(this, "S3WriterFn", { + const s3WriterFn = new BunFunctionWithLayer(this, "S3WriterFn", { entrypoint: src("s3-writer.ts"), bunLayer, environment: { BUCKET_NAME: testBucket.bucketName }, @@ -78,6 +90,9 @@ export class SampleStack extends Stack { new CfnOutput(this, "HttpV2PlainFunctionUrl", { value: plainFnUrl.url }); new CfnOutput(this, "HttpV1RestApiUrl", { value: restApi.url }); new CfnOutput(this, "EchoFnArn", { value: echoFn.functionArn }); + if (cmrEchoFn != null) { + new CfnOutput(this, "CmrEchoFnArn", { value: cmrEchoFn.functionArn }); + } new CfnOutput(this, "S3WriterFnArn", { value: s3WriterFn.functionArn }); new CfnOutput(this, "TestBucketName", { value: testBucket.bucketName }); new CfnOutput(this, "StreamingFnArn", { value: streamingFn.functionArn }); diff --git a/examples/sample-app/package.json b/examples/sample-app/package.json index 9c99735..3bf436a 100644 --- a/examples/sample-app/package.json +++ b/examples/sample-app/package.json @@ -10,13 +10,13 @@ "dependencies": { "@beesolve/lambda-bun-runtime": "file:../..", "@beesolve/lambda-fetch-api": "^1.0.0", - "aws-cdk-lib": "^2.238.0", + "aws-cdk-lib": "^2.278.0", "constructs": "^10.4.5" }, "devDependencies": { "@aws-sdk/client-lambda": "^3", "@aws-sdk/client-s3": "^3", "@types/aws-lambda": "^8", - "aws-cdk": "^2.238.0" + "aws-cdk": "^2.1149.0" } } diff --git a/package.json b/package.json index f180714..9ed8c2c 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,9 @@ "type": "git", "url": "git+https://github.com/BeeSolve/lambda-bun-runtime" }, + "bin": { + "bun-lambda-runtime": "./dist/cli.js" + }, "workspaces": [ "examples/sample-app" ], @@ -57,7 +60,7 @@ "@beesolve/lint-config": "0.2.4", "@types/bun": "1.3.14", "@types/node": "24.12.4", - "aws-cdk-lib": "2.238.0", + "aws-cdk-lib": "2.278.0", "constructs": "10.4.5", "fast-check": "4.8.0", "oxfmt": "0.57.0", @@ -66,7 +69,7 @@ "typescript": "6.0.3" }, "peerDependencies": { - "aws-cdk-lib": "^2.238.0", + "aws-cdk-lib": "^2.278.0", "constructs": "^10.4.5" } } diff --git a/src/artifacts.json b/src/artifacts.json new file mode 100644 index 0000000..2b24d67 --- /dev/null +++ b/src/artifacts.json @@ -0,0 +1,3 @@ +{ + "regions": {} +} diff --git a/src/artifacts.ts b/src/artifacts.ts new file mode 100644 index 0000000..5314e5c --- /dev/null +++ b/src/artifacts.ts @@ -0,0 +1,35 @@ +import artifactsJson from "./artifacts.json" with { type: "json" }; + +export interface RegionArtifacts { + readonly layerVersionArn: string; + readonly runtimeArn?: string; + readonly runtimeAlias?: string; +} + +export interface Artifacts { + readonly packageVersion?: string; + readonly bunVersion?: string; + readonly regions: Record; +} + +/** + * Published artifacts for this package version. The file in the repository is an + * empty placeholder; the release workflow overwrites it with the real ARNs + * before the package is built. + */ +export const publishedArtifacts: Artifacts = artifactsJson; + +export function resolveRegionArtifacts(props: { + readonly region: string; + readonly artifacts: Artifacts; +}): RegionArtifacts { + const found = props.artifacts.regions[props.region]; + if (found != null) return found; + + const supported = Object.keys(props.artifacts.regions).sort(); + const supportedText = supported.length === 0 ? "none" : supported.join(", "); + throw new Error( + `No published Bun layer for region "${props.region}". Published regions: ${supportedText}. ` + + `Pass layerVersionArn to use your own layer, or build the layer zip yourself and pass assetZipPath.`, + ); +} diff --git a/src/index.ts b/src/index.ts index 5bd26cc..47237df 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,15 +1,26 @@ -import { basename, dirname, join } from "node:path"; +import { basename, dirname } from "node:path"; -import { RemovalPolicy, Stack } from "aws-cdk-lib"; -import { Architecture, Code, Function, LayerVersion, Runtime } from "aws-cdk-lib/aws-lambda"; -import type { FunctionProps } from "aws-cdk-lib/aws-lambda"; -import type { LayerVersionProps } from "aws-cdk-lib/aws-lambda"; +import { RemovalPolicy, Resource, Stack, Token } from "aws-cdk-lib"; +import { + Architecture, + Code, + Function, + LayerVersion, + Runtime, + RuntimeFamily, + mixins, +} from "aws-cdk-lib/aws-lambda"; +import type { FunctionProps, ILayerVersion, LayerVersionPermission } from "aws-cdk-lib/aws-lambda"; import { LogGroup, RetentionDays } from "aws-cdk-lib/aws-logs"; import type { Construct } from "constructs"; +import { publishedArtifacts, resolveRegionArtifacts } from "./artifacts"; + const bunVersion = "1.4.5"; -export interface BunFunctionProps extends Omit< +const customRuntime = new Runtime("custom", RuntimeFamily.OTHER); + +export interface BunFunctionBaseProps extends Omit< FunctionProps, "runtime" | "architecture" | "handler" | "code" > { @@ -27,59 +38,190 @@ export interface BunFunctionProps extends Omit< * @default "handler" */ readonly exportName?: string; +} + +export interface BunRuntimeProps { + /** + * ARN of the customer-managed runtime. Defaults to the runtime BeeSolve publishes + * in the stack's region. Set it to use a runtime you built and published yourself. + */ + readonly runtimeArn?: string; + + /** + * Runtime alias. Defaults to the alias published with this package version, + * or `latest` when `runtimeArn` is given. + */ + readonly runtimeAlias?: string; +} +export interface BunFunctionProps extends BunFunctionBaseProps { /** - * Bun layer needs to be set. + * Override the customer-managed runtime. Without it the function uses the + * runtime BeeSolve publishes for this package version. */ - readonly bunLayer: BunLambdaLayer; + readonly bunRuntime?: BunRuntimeProps; } +/** + * A Lambda function running on the Bun customer-managed runtime (CMR). + */ export class BunFunction extends Function { constructor(scope: Construct, id: string, props: BunFunctionProps) { - const derivedBasename = deriveBasename({ entrypoint: props.entrypoint }); - const handler = `${derivedBasename}.${props.exportName ?? "handler"}`; - const code = resolveCode({ entrypoint: props.entrypoint, derivedBasename }); + const runtimeConfig = resolveRuntimeConfig({ scope, runtime: props.bunRuntime ?? {} }); + + super(scope, id, { + ...baseFunctionProps({ scope, id, props }), + runtime: customRuntime, + }); + + this.with(runtimeConfig); + } +} + +export interface BunFunctionWithLayerProps extends BunFunctionBaseProps { + /** + * The Bun layer the function runs on. + */ + readonly bunLayer: ILayerVersion; +} +/** + * A Lambda function running Bun from a layer on `provided.al2023`. + * Use it where the customer-managed runtime is not available. + */ +export class BunFunctionWithLayer extends Function { + constructor(scope: Construct, id: string, props: BunFunctionWithLayerProps) { super(scope, id, { - logGroup: - props.logGroup ?? - new LogGroup(scope, `${id}LogGroup`, { - logGroupName: `/aws/lambda/${Stack.of(scope).stackName}-${id}`, - removalPolicy: RemovalPolicy.DESTROY, - retention: RetentionDays.TWO_WEEKS, - }), - ...props, - code, - handler, + ...baseFunctionProps({ scope, id, props }), runtime: Runtime.PROVIDED_AL2023, - architecture: Architecture.ARM_64, layers: [props.bunLayer, ...(props.layers ?? [])], }); } } -export type BunLambdaLayerProps = Omit< - LayerVersionProps, - | "description" - | "removalPolicy" - | "code" - | "compatibleArchitectures" - | "compatibleRuntimes" - | "layerVersionName" ->; - -export class BunLambdaLayer extends LayerVersion { - constructor(scope: Construct, id: string, props?: BunLambdaLayerProps) { - super(scope, id, { - ...props, - description: `Bun v${bunVersion} Lambda runtime layer.`, - removalPolicy: RemovalPolicy.DESTROY, - code: Code.fromAsset(join(import.meta.dirname, `bun-lambda-layer-${bunVersion}.zip`)), - compatibleArchitectures: [Architecture.ARM_64], - compatibleRuntimes: [Runtime.PROVIDED_AL2023], - layerVersionName: "BunRuntime", +export type BunLambdaLayerProps = + | { + /** + * Use an existing layer version instead of the published BeeSolve layer. + */ + readonly layerVersionArn: string; + readonly assetZipPath?: never; + } + | { + /** + * Path to a layer zip built with the `build-layer` command. The zip is + * uploaded as a CDK asset and published as a layer in your account. + */ + readonly assetZipPath: string; + readonly layerVersionArn?: never; + } + | { + readonly layerVersionArn?: never; + readonly assetZipPath?: never; + }; + +/** + * The Bun runtime layer. By default it references the layer BeeSolve publishes + * for this package version in the stack's region. Pass `layerVersionArn` or + * `assetZipPath` to use your own layer (needed for regions without a published layer). + */ +export class BunLambdaLayer extends Resource implements ILayerVersion { + public readonly layerVersionArn: string; + public readonly compatibleRuntimes: Array = [Runtime.PROVIDED_AL2023]; + + private readonly layer: ILayerVersion; + + constructor(scope: Construct, id: string, props: BunLambdaLayerProps = {}) { + super(scope, id); + + if (props.assetZipPath != null) { + this.layer = new LayerVersion(this, "Layer", { + description: `Bun v${bunVersion} Lambda runtime layer.`, + removalPolicy: RemovalPolicy.DESTROY, + code: Code.fromAsset(props.assetZipPath), + compatibleArchitectures: [Architecture.ARM_64], + compatibleRuntimes: [Runtime.PROVIDED_AL2023], + layerVersionName: "BunRuntime", + }); + } else { + const arn = + props.layerVersionArn ?? + resolveRegionArtifacts({ + region: concreteRegion({ scope }), + artifacts: publishedArtifacts, + }).layerVersionArn; + this.layer = LayerVersion.fromLayerVersionArn(this, "Layer", arn); + } + + this.layerVersionArn = this.layer.layerVersionArn; + } + + public get layerVersionRef(): ILayerVersion["layerVersionRef"] { + return { layerVersionArn: this.layerVersionArn }; + } + + public addPermission(id: string, permission: LayerVersionPermission): void { + this.layer.addPermission(id, permission); + } +} + +function baseFunctionProps(props: { + readonly scope: Construct; + readonly id: string; + readonly props: BunFunctionBaseProps; +}): FunctionProps { + const derivedBasename = deriveBasename({ entrypoint: props.props.entrypoint }); + return { + logGroup: + props.props.logGroup ?? + new LogGroup(props.scope, `${props.id}LogGroup`, { + logGroupName: `/aws/lambda/${Stack.of(props.scope).stackName}-${props.id}`, + removalPolicy: RemovalPolicy.DESTROY, + retention: RetentionDays.TWO_WEEKS, + }), + ...props.props, + code: resolveCode({ entrypoint: props.props.entrypoint, derivedBasename }), + handler: `${derivedBasename}.${props.props.exportName ?? "handler"}`, + runtime: customRuntime, + architecture: Architecture.ARM_64, + }; +} + +function resolveRuntimeConfig(props: { + readonly scope: Construct; + readonly runtime: BunRuntimeProps; +}): mixins.FunctionRuntimeConfig { + if (props.runtime.runtimeArn != null) { + return new mixins.FunctionRuntimeConfig({ + runtimeArn: props.runtime.runtimeArn, + runtimeAlias: props.runtime.runtimeAlias ?? "latest", }); } + + const published = resolveRegionArtifacts({ + region: concreteRegion({ scope: props.scope }), + artifacts: publishedArtifacts, + }); + if (published.runtimeArn == null || published.runtimeAlias == null) { + throw new Error( + "No published Bun runtime for this region. Set bunRuntime.runtimeArn to use your own runtime, or use BunFunctionWithLayer.", + ); + } + return new mixins.FunctionRuntimeConfig({ + runtimeArn: published.runtimeArn, + runtimeAlias: props.runtime.runtimeAlias ?? published.runtimeAlias, + }); +} + +function concreteRegion(props: { readonly scope: Construct }): string { + const region = Stack.of(props.scope).region; + if (Token.isUnresolved(region)) { + throw new Error( + "BunLambdaLayer needs a concrete region to find the published layer. " + + "Set env.region on the stack, or pass layerVersionArn or assetZipPath.", + ); + } + return region; } function deriveBasename(props: { entrypoint: string }): string { diff --git a/test/artifacts.test.ts b/test/artifacts.test.ts new file mode 100644 index 0000000..561aba4 --- /dev/null +++ b/test/artifacts.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, test } from "bun:test"; + +import * as fc from "fast-check"; + +import { resolveRegionArtifacts } from "../src/artifacts"; +import type { Artifacts } from "../src/artifacts"; + +const artifacts: Artifacts = { + regions: { + "eu-central-1": { + layerVersionArn: "arn:aws:lambda:eu-central-1:123456789012:layer:BunRuntime:7", + runtimeArn: "arn:aws:lambda:eu-central-1:123456789012:runtime/bun", + runtimeAlias: "1.4.4", + }, + "us-east-1": { + layerVersionArn: "arn:aws:lambda:us-east-1:123456789012:layer:BunRuntime:9", + }, + }, +}; + +describe("resolveRegionArtifacts", () => { + test("returns the artifacts of a published region", () => { + expect(resolveRegionArtifacts({ region: "eu-central-1", artifacts }).layerVersionArn).toBe( + "arn:aws:lambda:eu-central-1:123456789012:layer:BunRuntime:7", + ); + }); + + test("runtime fields are optional per region", () => { + expect(resolveRegionArtifacts({ region: "us-east-1", artifacts }).runtimeArn).toBeUndefined(); + }); + + test("the error lists the published regions sorted", () => { + expect(() => resolveRegionArtifacts({ region: "ap-south-1", artifacts })).toThrow( + "Published regions: eu-central-1, us-east-1.", + ); + }); + + test("the error says none when nothing is published", () => { + expect(() => + resolveRegionArtifacts({ region: "eu-west-1", artifacts: { regions: {} } }), + ).toThrow("Published regions: none."); + }); + + test("any region that is not published throws", () => { + fc.assert( + fc.property( + fc + .stringMatching(/^[a-z]{2}-[a-z]+-[1-9]$/) + .filter((region) => artifacts.regions[region] == null), + (region) => { + expect(() => resolveRegionArtifacts({ region, artifacts })).toThrow( + `No published Bun layer for region "${region}"`, + ); + }, + ), + { numRuns: 100 }, + ); + }); +}); diff --git a/test/cli.test.ts b/test/cli.test.ts new file mode 100644 index 0000000..e314a4d --- /dev/null +++ b/test/cli.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, test } from "bun:test"; + +function runCli(args: Array): { output: string; exitCode: number } { + const proc = Bun.spawnSync(["bun", "command/cli.ts", ...args]); + return { + output: proc.stdout.toString() + proc.stderr.toString(), + exitCode: proc.exitCode ?? -1, + }; +} + +describe("bun-lambda-runtime cli", () => { + test("prints usage and exits 0 without a command", () => { + const { output, exitCode } = runCli([]); + expect(exitCode).toBe(0); + expect(output).toContain("build-layer"); + }); + + test("prints usage and exits 1 for an unknown command", () => { + const { output, exitCode } = runCli(["nope"]); + expect(exitCode).toBe(1); + expect(output).toContain("Usage: bun-lambda-runtime"); + }); + + test("build-layer rejects --out without a directory", () => { + const { output, exitCode } = runCli(["build-layer", "1.0.999", "--out"]); + expect(exitCode).toBe(1); + expect(output).toContain("--out needs a directory"); + }); + + test("build-layer uses the version argument (fails at download for a missing release)", () => { + const { output, exitCode } = runCli(["build-layer", "1.0.999"]); + expect(exitCode).toBe(1); + expect(output).toContain("Bun v1.0.999"); + }); +}); diff --git a/test/constructs.test.ts b/test/constructs.test.ts index fc707ce..09122ba 100644 --- a/test/constructs.test.ts +++ b/test/constructs.test.ts @@ -1,26 +1,23 @@ import { describe, expect, test, beforeAll, afterAll } from "bun:test"; -import { existsSync, readFileSync, writeFileSync, unlinkSync } from "node:fs"; +import { existsSync, writeFileSync, unlinkSync } from "node:fs"; +import { tmpdir } from "node:os"; import { resolve } from "node:path"; import { App, Stack } from "aws-cdk-lib"; -import { Template } from "aws-cdk-lib/assertions"; +import { Match, Template } from "aws-cdk-lib/assertions"; import * as fc from "fast-check"; -import { BunFunction, BunLambdaLayer } from "../src/index"; +import { BunFunction, BunFunctionWithLayer, BunLambdaLayer } from "../src/index"; -const srcIndex = readFileSync(resolve(__dirname, "../src/index.ts"), "utf8"); -const bunVersion = srcIndex.match(/const bunVersion = "([^"]+)"/)?.[1] ?? ""; +const testLayerArn = "arn:aws:lambda:eu-central-1:123456789012:layer:BunRuntime:7"; // CDK's Code.fromAsset requires the zip to exist on disk during synth -const dummyZipPath = resolve(__dirname, `../src/bun-lambda-layer-${bunVersion}.zip`); +const dummyZipPath = resolve(tmpdir(), `bun-lambda-layer-test-${process.pid}.zip`); beforeAll(() => { - if (!existsSync(dummyZipPath)) { - // Create a minimal valid zip (PK header + empty) - const proc = Bun.spawnSync(["zip", "-j", dummyZipPath, "/dev/null"]); - if (proc.exitCode !== 0) { - writeFileSync(dummyZipPath, Buffer.alloc(0)); - } + const proc = Bun.spawnSync(["zip", "-j", dummyZipPath, "/dev/null"]); + if (proc.exitCode !== 0) { + writeFileSync(dummyZipPath, Buffer.alloc(0)); } }); @@ -95,12 +92,12 @@ describe("BunFunction handler derivation (Property 5)", () => { }); describe("CDK construct unit tests", () => { - test("BunFunction with .js entrypoint produces correct handler string", () => { + test("BunFunctionWithLayer with .js entrypoint produces correct handler string", () => { const app = new App(); const stack = new Stack(app, "TestStack"); - const bunLayer = new BunLambdaLayer(stack, "Layer"); + const bunLayer = new BunLambdaLayer(stack, "Layer", { layerVersionArn: testLayerArn }); - new BunFunction(stack, "Fn", { + new BunFunctionWithLayer(stack, "Fn", { entrypoint: `${__dirname}/fixtures/api.js`, bunLayer, }); @@ -111,12 +108,12 @@ describe("CDK construct unit tests", () => { }); }); - test("BunFunction with .ts entrypoint uses Code.fromCustomCommand", () => { + test("BunFunctionWithLayer with .ts entrypoint uses Code.fromCustomCommand", () => { const app = new App(); const stack = new Stack(app, "TestStack"); - const bunLayer = new BunLambdaLayer(stack, "Layer"); + const bunLayer = new BunLambdaLayer(stack, "Layer", { layerVersionArn: testLayerArn }); - new BunFunction(stack, "Fn", { + new BunFunctionWithLayer(stack, "Fn", { entrypoint: `${__dirname}/fixtures/handler.ts`, bunLayer, }); @@ -127,12 +124,12 @@ describe("CDK construct unit tests", () => { }); }); - test("BunFunction with explicit exportName uses provided value", () => { + test("BunFunctionWithLayer with explicit exportName uses provided value", () => { const app = new App(); const stack = new Stack(app, "TestStack"); - const bunLayer = new BunLambdaLayer(stack, "Layer"); + const bunLayer = new BunLambdaLayer(stack, "Layer", { layerVersionArn: testLayerArn }); - new BunFunction(stack, "Fn", { + new BunFunctionWithLayer(stack, "Fn", { entrypoint: `${__dirname}/fixtures/api.js`, exportName: "myExport", bunLayer, @@ -144,12 +141,12 @@ describe("CDK construct unit tests", () => { }); }); - test("BunFunction does NOT use .fetch as default export", () => { + test("BunFunctionWithLayer does NOT use .fetch as default export", () => { const app = new App(); const stack = new Stack(app, "TestStack"); - const bunLayer = new BunLambdaLayer(stack, "Layer"); + const bunLayer = new BunLambdaLayer(stack, "Layer", { layerVersionArn: testLayerArn }); - new BunFunction(stack, "Fn", { + new BunFunctionWithLayer(stack, "Fn", { entrypoint: `${__dirname}/fixtures/api.js`, bunLayer, }); @@ -162,11 +159,11 @@ describe("CDK construct unit tests", () => { } }); - test("BunLambdaLayer creates layer with correct properties", () => { + test("BunLambdaLayer with assetZipPath creates a layer with correct properties", () => { const app = new App(); const stack = new Stack(app, "TestStack"); - new BunLambdaLayer(stack, "Layer"); + new BunLambdaLayer(stack, "Layer", { assetZipPath: dummyZipPath }); const template = Template.fromStack(stack); template.hasResourceProperties("AWS::Lambda::LayerVersion", { @@ -176,12 +173,47 @@ describe("CDK construct unit tests", () => { }); }); - test("BunFunction uses PROVIDED_AL2023 runtime and ARM_64 architecture", () => { + test("BunLambdaLayer with layerVersionArn creates no layer and attaches the ARN", () => { const app = new App(); const stack = new Stack(app, "TestStack"); - const bunLayer = new BunLambdaLayer(stack, "Layer"); + const bunLayer = new BunLambdaLayer(stack, "Layer", { layerVersionArn: testLayerArn }); - new BunFunction(stack, "Fn", { + new BunFunctionWithLayer(stack, "Fn", { + entrypoint: `${__dirname}/fixtures/api.js`, + bunLayer, + }); + + const template = Template.fromStack(stack); + template.resourceCountIs("AWS::Lambda::LayerVersion", 0); + template.hasResourceProperties("AWS::Lambda::Function", { + Layers: [testLayerArn], + }); + }); + + test("BunLambdaLayer without props throws for a region with no published layer", () => { + const app = new App(); + const stack = new Stack(app, "TestStack", { + env: { account: "123456789012", region: "eu-west-3" }, + }); + + expect(() => new BunLambdaLayer(stack, "Layer")).toThrow( + /No published Bun layer for region "eu-west-3"/, + ); + }); + + test("BunLambdaLayer without props throws for an environment-agnostic stack", () => { + const app = new App(); + const stack = new Stack(app, "TestStack"); + + expect(() => new BunLambdaLayer(stack, "Layer")).toThrow(/needs a concrete region/); + }); + + test("BunFunctionWithLayer uses PROVIDED_AL2023 runtime and ARM_64 architecture", () => { + const app = new App(); + const stack = new Stack(app, "TestStack"); + const bunLayer = new BunLambdaLayer(stack, "Layer", { layerVersionArn: testLayerArn }); + + new BunFunctionWithLayer(stack, "Fn", { entrypoint: `${__dirname}/fixtures/api.js`, bunLayer, }); @@ -193,3 +225,35 @@ describe("CDK construct unit tests", () => { }); }); }); + +describe("BunFunction on a customer-managed runtime", () => { + const runtimeArn = "arn:aws:lambda:eu-central-1:123456789012:runtime/bun"; + const entrypoint = `${import.meta.dir}/fixtures/api.js` as const; + + test("sets runtimeConfig, the custom runtime and no layer", () => { + const stack = new Stack(new App(), "Cmr", { env: { region: "eu-central-1" } }); + new BunFunction(stack, "Fn", { + entrypoint, + bunRuntime: { runtimeArn, runtimeAlias: "stable" }, + }); + Template.fromStack(stack).hasResourceProperties("AWS::Lambda::Function", { + Runtime: "custom", + Architectures: ["arm64"], + RuntimeConfig: { RuntimeArn: runtimeArn, RuntimeAlias: "stable" }, + Layers: Match.absent(), + }); + }); + + test("alias defaults to latest when only the ARN is given", () => { + const stack = new Stack(new App(), "CmrDefault", { env: { region: "eu-central-1" } }); + new BunFunction(stack, "Fn", { entrypoint, bunRuntime: { runtimeArn } }); + Template.fromStack(stack).hasResourceProperties("AWS::Lambda::Function", { + RuntimeConfig: { RuntimeArn: runtimeArn, RuntimeAlias: "latest" }, + }); + }); + + test("without an override it needs a published runtime for the region", () => { + const stack = new Stack(new App(), "CmrNone", { env: { region: "eu-central-1" } }); + expect(() => new BunFunction(stack, "Fn", { entrypoint })).toThrow("No published Bun layer"); + }); +}); diff --git a/test/integration/deploy-destroy.test.ts b/test/integration/deploy-destroy.test.ts index 58a6723..e8a0282 100644 --- a/test/integration/deploy-destroy.test.ts +++ b/test/integration/deploy-destroy.test.ts @@ -29,6 +29,7 @@ interface StackOutputs { HttpV2PlainFunctionUrl: string; HttpV1RestApiUrl: string; EchoFnArn: string; + CmrEchoFnArn?: string; S3WriterFnArn: string; TestBucketName: string; StreamingFnArn: string; @@ -127,6 +128,12 @@ describeInteg( assertSetCookieHeader(res.headers); }); + test("direct invoke echo on the customer-managed runtime", async () => { + if (outputs.CmrEchoFnArn == null) return; + const result = await invokeLambda(outputs.CmrEchoFnArn, { hello: "cmr" }); + expect((result as { echo: unknown }).echo).toEqual({ hello: "cmr" }); + }); + test("direct invoke echo", async () => { const result = await invokeLambda(outputs.EchoFnArn, { hello: "world" }); expect((result as { echo: unknown }).echo).toEqual({ hello: "world" }); diff --git a/test/publishLayer.test.ts b/test/publishLayer.test.ts new file mode 100644 index 0000000..f598f6c --- /dev/null +++ b/test/publishLayer.test.ts @@ -0,0 +1,175 @@ +import { describe, expect, test } from "bun:test"; + +import { + AddLayerVersionPermissionCommand, + ListLayerVersionsCommand, + PublishLayerVersionCommand, + ResourceConflictException, +} from "@aws-sdk/client-lambda"; + +import { descriptionMatchesPackage, layerDescription, publishLayer } from "../command/publishLayer"; +import { mergeArtifacts } from "../command/writeArtifacts"; + +const arnBase = "arn:aws:lambda:eu-central-1:123456789012:layer:BunRuntime"; + +interface FakeOptions { + readonly existing?: ReadonlyArray<{ Description: string; LayerVersionArn: string }>; + readonly conflictOnPermission?: boolean; +} + +function fakeClient(options: FakeOptions = {}) { + const sent: Array = []; + const client = { + send: async (command: unknown): Promise => { + sent.push(command); + if (command instanceof ListLayerVersionsCommand) { + return { LayerVersions: options.existing ?? [] }; + } + if (command instanceof PublishLayerVersionCommand) { + return { LayerVersionArn: `${arnBase}:5` }; + } + if (command instanceof AddLayerVersionPermissionCommand) { + if (options.conflictOnPermission === true) { + throw new ResourceConflictException({ message: "exists", $metadata: {} }); + } + return {}; + } + throw new Error("unexpected command"); + }, + }; + return { client: client as never, sent }; +} + +const baseProps = { + region: "eu-central-1", + zip: new Uint8Array([1, 2, 3]), + bunVersion: "1.4.4", + packageVersion: "4.10404.0", + gitSha: "0123456789abcdef0123", +}; + +describe("layer description", () => { + test("names bun version, package version, git sha and zip hash", () => { + const description = layerDescription({ + bunVersion: "1.4.4", + packageVersion: "4.10404.0", + gitSha: "0123456789abcdef0123", + zipSha256: "a".repeat(64), + }); + expect(description).toBe( + "Bun v1.4.4 | package v4.10404.0 | git 0123456789ab | sha256 aaaaaaaaaaaaaaaa", + ); + expect(description.length).toBeLessThanOrEqual(256); + }); + + test("matches only the exact package version", () => { + const description = "Bun v1.4.4 | package v4.10404.0 | git abc | sha256 def"; + expect(descriptionMatchesPackage({ description, packageVersion: "4.10404.0" })).toBe(true); + expect(descriptionMatchesPackage({ description, packageVersion: "4.10404.1" })).toBe(false); + expect(descriptionMatchesPackage({ description: undefined, packageVersion: "4.10404.0" })).toBe( + false, + ); + }); +}); + +describe("publishLayer", () => { + test("publishes a new version and makes it public", async () => { + const { client, sent } = fakeClient(); + const result = await publishLayer({ ...baseProps, client }); + + expect(result).toEqual({ + region: "eu-central-1", + layerVersionArn: `${arnBase}:5`, + reused: false, + }); + const permission = sent.find((command) => command instanceof AddLayerVersionPermissionCommand); + expect((permission as AddLayerVersionPermissionCommand).input).toMatchObject({ + VersionNumber: 5, + Principal: "*", + Action: "lambda:GetLayerVersion", + }); + }); + + test("reuses an existing version for the same package version", async () => { + const { client, sent } = fakeClient({ + existing: [ + { + Description: "Bun v1.4.4 | package v4.10404.0 | git abc | sha256 def", + LayerVersionArn: `${arnBase}:3`, + }, + ], + }); + const result = await publishLayer({ ...baseProps, client }); + + expect(result.reused).toBe(true); + expect(result.layerVersionArn).toBe(`${arnBase}:3`); + expect(sent.some((command) => command instanceof PublishLayerVersionCommand)).toBe(false); + }); + + test("an already existing public permission is not an error", async () => { + const { client } = fakeClient({ conflictOnPermission: true }); + const result = await publishLayer({ ...baseProps, client }); + expect(result.layerVersionArn).toBe(`${arnBase}:5`); + }); + + test("rejects a zip above the direct upload limit", async () => { + const { client } = fakeClient(); + await expect( + publishLayer({ ...baseProps, zip: new Uint8Array(50 * 1024 * 1024 + 1), client }), + ).rejects.toThrow("direct upload limit"); + }); +}); + +describe("mergeArtifacts", () => { + test("merges results sorted by region", () => { + const artifacts = mergeArtifacts({ + packageVersion: "4.10404.0", + bunVersion: "1.4.4", + results: [ + { region: "us-east-1", layerVersionArn: "arn:b" }, + { region: "eu-central-1", layerVersionArn: "arn:a" }, + ], + }); + expect(Object.keys(artifacts.regions)).toEqual(["eu-central-1", "us-east-1"]); + expect(artifacts.regions["eu-central-1"]).toEqual({ layerVersionArn: "arn:a" }); + }); + + test("rejects duplicate regions", () => { + expect(() => + mergeArtifacts({ + packageVersion: "4.10404.0", + bunVersion: "1.4.4", + results: [ + { region: "eu-central-1", layerVersionArn: "arn:a" }, + { region: "eu-central-1", layerVersionArn: "arn:b" }, + ], + }), + ).toThrow("Duplicate result"); + }); + + test("merges layer and runtime results of the same region", () => { + const artifacts = mergeArtifacts({ + packageVersion: "4.10404.0", + bunVersion: "1.4.4", + results: [ + { region: "eu-central-1", layerVersionArn: "arn:a" }, + { region: "eu-central-1", runtimeArn: "arn:r", runtimeAlias: "1.4" }, + ], + }); + expect(artifacts.regions["eu-central-1"]).toEqual({ + layerVersionArn: "arn:a", + runtimeArn: "arn:r", + runtimeAlias: "1.4", + }); + }); + + test("rejects a region without a layer result", () => { + expect(() => + mergeArtifacts({ + packageVersion: "4.10404.0", + bunVersion: "1.4.4", + results: [{ region: "eu-central-1", runtimeArn: "arn:r", runtimeAlias: "1.4" }], + }), + ).toThrow("Missing layer result"); + }); +}); diff --git a/test/publishRuntime.test.ts b/test/publishRuntime.test.ts new file mode 100644 index 0000000..4359e9f --- /dev/null +++ b/test/publishRuntime.test.ts @@ -0,0 +1,202 @@ +import { describe, expect, test } from "bun:test"; + +import { + aliasNamesForBunVersion, + compareVersionNames, + publishRuntime, + runtimeImageFiles, +} from "../command/publishRuntime"; +import type { Exec, PublishRuntimeProps } from "../command/publishRuntime"; + +const runtimeArn = "arn:aws:lambda:eu-central-1:123456789012:runtime/bun"; + +interface FakeState { + readonly repository?: boolean; + readonly image?: boolean; + readonly runtimeState?: string; + readonly version?: boolean; + readonly aliases?: Record; + readonly policy?: boolean; +} + +function fakeExec(state: FakeState = {}) { + const commands: Array> = []; + const exec: Exec = (props) => { + commands.push(props.command); + const line = props.command.join(" "); + const ok = (stdout = "") => ({ exitCode: 0, stdout, stderr: "" }); + const fail = () => ({ exitCode: 254, stdout: "", stderr: "not found" }); + if (line.includes("sts get-caller-identity")) return ok("123456789012"); + if (line.includes("ecr describe-repositories")) + return state.repository === true ? ok() : fail(); + if (line.includes("ecr describe-images")) return state.image === true ? ok() : fail(); + if (line.includes("ecr get-login-password")) return ok("secret"); + if (line.includes("buildx create")) return ok(); + if (line.includes("lambda-core get-runtime --runtime-name") && line.includes("State")) { + return state.runtimeState == null ? fail() : ok(state.runtimeState); + } + if (line.includes("lambda-core get-runtime --runtime-name") && line.includes("Arn")) { + return ok(runtimeArn); + } + if (line.includes("lambda-core get-runtime-version")) { + return state.version === true ? ok("{}") : fail(); + } + if (line.includes("lambda-core get-runtime-alias")) { + const name = props.command[props.command.indexOf("--name") + 1]; + const current = state.aliases?.[name]; + return current == null ? fail() : ok(current); + } + if (line.includes("lambda get-resource-policy")) { + return state.policy === true ? ok("AssociateRuntimeAlias") : fail(); + } + return ok(); + }; + return { exec, commands }; +} + +function props(overrides: Partial, exec: Exec): PublishRuntimeProps { + return { + region: "eu-central-1", + contextDir: "/tmp/context", + runtimeName: "bun", + repositoryName: "bun", + versionName: "4.10405.0", + releaseNotes: "Bun v1.4.5", + aliases: ["pkg-4.10405.0"], + movingAliases: [], + resultAlias: "pkg-4.10405.0", + isPublic: false, + exec, + ...overrides, + }; +} + +function lines(commands: ReadonlyArray>): ReadonlyArray { + return commands.map((command) => command.join(" ")); +} + +describe("alias names", () => { + test("a Bun version produces exact, minor, major and latest aliases", () => { + expect(aliasNamesForBunVersion({ bunVersion: "1.4.5" })).toEqual([ + "1.4.5", + "1.4", + "1", + "latest", + ]); + }); + + test("version names compare numerically", () => { + expect(compareVersionNames({ left: "4.10405.0", right: "4.10404.9" })).toBeGreaterThan(0); + expect(compareVersionNames({ left: "4.10405.0", right: "4.10405.1" })).toBeLessThan(0); + expect(compareVersionNames({ left: "4.10405.0", right: "4.10405.0" })).toBe(0); + expect(compareVersionNames({ left: "4.10405.0", right: "bench" })).toBe(0); + }); +}); + +describe("runtime image", () => { + test("has no ENTRYPOINT, CMD or RUN and ships the bootstrap", () => { + const files = runtimeImageFiles(); + expect(files.dockerfile).not.toMatch(/^(ENTRYPOINT|CMD|RUN)/m); + expect(files.dockerfile).toContain("/var/runtime/bootstrap"); + expect(files.bootstrap).toContain("exec /usr/local/bin/bun /var/runtime/runtime.js"); + }); +}); + +describe("publishRuntime", () => { + test("creates repository, image, runtime, version and alias on a fresh account", () => { + const { exec, commands } = fakeExec(); + const result = publishRuntime(props({}, exec)); + const executed = lines(commands); + + expect(result).toEqual({ + region: "eu-central-1", + runtimeArn, + runtimeAlias: "pkg-4.10405.0", + runtimeVersion: "4.10405.0", + }); + expect(executed.some((line) => line.includes("ecr create-repository"))).toBe(true); + expect(executed.some((line) => line.includes("ecr set-repository-policy"))).toBe(true); + expect( + executed.some( + (line) => + line.includes("docker buildx build") && + line.includes("--platform linux/arm64") && + line.includes("123456789012.dkr.ecr.eu-central-1.amazonaws.com/bun:4.10405.0"), + ), + ).toBe(true); + expect(executed.some((line) => line.includes("lambda-core create-runtime "))).toBe(true); + expect(executed.some((line) => line.includes("lambda-core create-runtime-version"))).toBe(true); + expect(executed.some((line) => line.includes("lambda-core create-runtime-alias"))).toBe(true); + expect(executed.some((line) => line.includes("put-resource-policy"))).toBe(false); + }); + + test("a rerun reuses repository, image, runtime and version", () => { + const { exec, commands } = fakeExec({ + repository: true, + image: true, + runtimeState: "ACTIVE", + version: true, + aliases: { "pkg-4.10405.0": "4.10405.0" }, + }); + publishRuntime(props({}, exec)); + const executed = lines(commands); + + for (const forbidden of [ + "ecr create-repository", + "docker buildx build", + "lambda-core create-runtime ", + "lambda-core create-runtime-version", + "lambda-core create-runtime-alias", + ]) { + expect(executed.some((line) => line.includes(forbidden))).toBe(false); + } + expect(executed.some((line) => line.includes("lambda-core update-runtime-alias"))).toBe(true); + }); + + test("a moving alias does not move backwards but a plain alias does", () => { + const { exec, commands } = fakeExec({ + repository: true, + image: true, + runtimeState: "ACTIVE", + version: true, + aliases: { "1.4": "4.10406.0", "1": "4.10404.0" }, + }); + publishRuntime(props({ aliases: [], movingAliases: ["1.4", "1", "latest"] }, exec)); + const updates = lines(commands).filter( + (line) => line.includes("-runtime-alias --runtime-name") && !line.includes("get-"), + ); + + expect(updates.some((line) => line.includes("--name 1.4 "))).toBe(false); + expect( + updates.some((line) => line.includes("update-runtime-alias") && line.includes("--name 1 ")), + ).toBe(true); + expect( + updates.some( + (line) => line.includes("create-runtime-alias") && line.includes("--name latest "), + ), + ).toBe(true); + }); + + test("--public puts a policy for every principal on the runtime ARN", () => { + const { exec, commands } = fakeExec({ repository: true, image: true }); + publishRuntime(props({ isPublic: true }, exec)); + const put = commands.find((command) => command.includes("put-resource-policy")); + + expect(put).toBeDefined(); + expect(put?.[put.indexOf("--resource-arn") + 1]).toBe(runtimeArn); + const policy = JSON.parse(put?.[put.indexOf("--policy") + 1] ?? "{}"); + expect(policy.Statement[0].Principal).toBe("*"); + expect(policy.Statement[0].Action).toBe("lambda:AssociateRuntimeAlias"); + }); + + test("an existing public policy is left alone", () => { + const { exec, commands } = fakeExec({ repository: true, image: true, policy: true }); + publishRuntime(props({ isPublic: true }, exec)); + expect(lines(commands).some((line) => line.includes("put-resource-policy"))).toBe(false); + }); + + test("a runtime pending deletion is an error", () => { + const { exec } = fakeExec({ repository: true, image: true, runtimeState: "PENDING_DELETION" }); + expect(() => publishRuntime(props({}, exec))).toThrow("PENDING_DELETION"); + }); +}); diff --git a/tsconfig.json b/tsconfig.json index 5e82ea5..336c058 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -4,6 +4,7 @@ "target": "ES2023", "module": "Preserve", "moduleResolution": "Bundler", + "resolveJsonModule": true, "verbatimModuleSyntax": true, "declaration": true, "emitDeclarationOnly": true, @@ -15,6 +16,6 @@ "noUnusedParameters": true, "noFallthroughCasesInSwitch": true }, - "include": ["src/**/*.ts"], + "include": ["src/**/*.ts", "src/artifacts.json"], "exclude": ["node_modules"] }