Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions DOCS.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@

## How-To Guides

| 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 |
| 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` |
| [Stream with status code and headers](./docs/how-to/streaming.md) | `awslambda.streamifyResponse`, `asResponseStreamHandler`, Function URL and CloudFront OAC |
| [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

Expand Down
17 changes: 16 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,22 @@ export const handler = async () => {

Invoke streaming functions using the AWS SDK's `InvokeWithResponseStream` API, or expose them via a Function URL with `invokeMode: InvokeMode.RESPONSE_STREAM`.

For HTTP streaming with custom status codes and response headers (e.g., `Content-Type: text/event-stream`), use [`asResponseStreamHandler`](#response-streaming-1) from `@beesolve/lambda-fetch-api`, which handles the HTTP metadata framing required by Function URLs.
#### Status code and headers on Function URLs

The runtime defines the `awslambda` global of the Node.js managed runtime (`awslambda.streamifyResponse` and `awslambda.HttpResponseStream.from`), so code written for it runs unchanged. [`asResponseStreamHandler`](#response-streaming-1) from `@beesolve/lambda-fetch-api` works, or use the global directly:

```ts
export const handler = awslambda.streamifyResponse(async (event, responseStream) => {
const stream = awslambda.HttpResponseStream.from(responseStream, {
statusCode: 201,
headers: { "content-type": "text/plain", "x-custom": "value" },
});
stream.write("hello ");
stream.end("world");
});
```

Without `HttpResponseStream.from` the stream is posted as plain bytes. If the handler throws before the first write, the error is reported normally. If it throws after streaming started, the request is aborted, because Bun's `fetch` cannot send the error trailers.

## Fetch API Support

Expand Down
124 changes: 124 additions & 0 deletions command/runtime.mts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ type Handler = (
context: LambdaContext,
) => Promise<StreamResponse | unknown> | StreamResponse | unknown;

interface ResponseStream {
write(chunk: StreamChunk): void;
end(chunk?: StreamChunk): void;
setContentType(type: string): void;
_onBeforeFirstWrite?: (write: (chunk: StreamChunk) => void) => void;
}

interface LambdaError {
errorType: string;
errorMessage: string;
Expand All @@ -41,6 +48,27 @@ const exportName = handlerEnv.substring(lastDot + 1);
const taskRoot = process.env.LAMBDA_TASK_ROOT ?? "/var/task";
const modulePath = `${taskRoot}/${filename}`;

const streamingMarker = Symbol.for("aws.lambda.runtime.handler.streaming");
const httpResponseContentType = "application/vnd.awslambda.http-integration-response";

// Mirrors the awslambda global of the Node.js managed runtime so that code written for it
// (e.g. asResponseStreamHandler from @beesolve/lambda-fetch-api) runs unchanged.
Object.assign(globalThis, {
awslambda: {
streamifyResponse: (fn: object) => Object.assign(fn, { [streamingMarker]: "response" }),
HttpResponseStream: {
from: (stream: ResponseStream, prelude: object) => {
stream.setContentType(httpResponseContentType);
stream._onBeforeFirstWrite = (write) => {
write(JSON.stringify(prelude));
write(new Uint8Array(8));
};
return stream;
},
},
},
});

const handler: Handler = await resolveHandler({ modulePath, exportName });

const functionName = process.env.AWS_LAMBDA_FUNCTION_NAME ?? "";
Expand Down Expand Up @@ -69,6 +97,28 @@ while (true) {
getRemainingTimeInMillis: () => deadlineMs - Date.now(),
};

const isStreamifiedHandler =
(handler as unknown as Record<symbol, unknown>)[streamingMarker] === "response";
if (isStreamifiedHandler) {
const responseStream = createResponseStream({
url: `${baseUrl}/runtime/invocation/${requestId}/response`,
});
try {
await (handler as unknown as StreamifiedHandler)(event, responseStream.stream, context);
responseStream.stream.end();
await responseStream.done();
} catch (err: unknown) {
if (!responseStream.started()) {
await postError({ path: `runtime/invocation/${requestId}/error`, error: err });
continue;
}
// Bun's fetch has no request trailers, so a mid-stream failure can only abort the request.
responseStream.abort({ error: err });
await responseStream.done().catch(() => undefined);
}
continue;
}

try {
const result = await handler(event, context);
if (isStream(result)) {
Expand Down Expand Up @@ -128,6 +178,80 @@ function formatError(props: { error: unknown }): LambdaError {
};
}

type StreamifiedHandler = (
event: unknown,
responseStream: ResponseStream,
context: LambdaContext,
) => Promise<unknown> | unknown;

function createResponseStream(props: { url: string }) {
const encoder = new TextEncoder();
const state: {
contentType?: string;
started: boolean;
ended: boolean;
post?: Promise<Response>;
controller?: ReadableStreamDefaultController<Uint8Array>;
} = { started: false, ended: false };
const body = new ReadableStream<Uint8Array>({
start(controller) {
state.controller = controller;
},
});

const enqueue = (chunk: StreamChunk) => {
const bytes = typeof chunk === "string" ? encoder.encode(chunk) : chunk;
if (bytes.length === 0) return;
state.controller?.enqueue(bytes);
};

// The content type is a request header, so the POST can only start once it is final.
const start = () => {
if (state.started) return;
state.started = true;
stream._onBeforeFirstWrite?.(enqueue);
state.post = fetch(props.url, {
method: "POST",
headers: {
"Lambda-Runtime-Function-Response-Mode": "streaming",
"Transfer-Encoding": "chunked",
...(state.contentType != null ? { "Content-Type": state.contentType } : {}),
},
body,
});
};

const stream: ResponseStream = {
write(chunk) {
start();
enqueue(chunk);
},
end(chunk) {
if (state.ended) return;
start();
if (chunk != null) enqueue(chunk);
state.ended = true;
state.controller?.close();
},
setContentType(type) {
state.contentType = type;
},
};

return {
stream,
started: () => state.started,
done: async () => {
await state.post;
},
abort: (abortProps: { error: unknown }) => {
if (state.ended) return;
state.ended = true;
state.controller?.error(abortProps.error);
},
};
}

function isStream(value: unknown): value is StreamResponse {
return (
value instanceof ReadableStream ||
Expand Down
24 changes: 23 additions & 1 deletion docs/aws-oidc-setup.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ bunx cdk bootstrap \

#### Scoped CDK execution policy

Save as `cfn-exec-policy.json`, replacing `<ACCOUNT_ID>` throughout. This covers everything CDK needs to deploy this specific stack (Lambda, API Gateway, S3, CloudWatch Logs, IAM execution roles).
Save as `cfn-exec-policy.json`, replacing `<ACCOUNT_ID>` throughout. This covers everything CDK needs to deploy this specific stack (Lambda, API Gateway, S3, CloudWatch Logs, IAM execution roles, and CloudFront with an origin access control for the streaming Function URL behind a distribution).

```json
{
Expand Down Expand Up @@ -224,6 +224,28 @@ Save as `cfn-exec-policy.json`, replacing `<ACCOUNT_ID>` throughout. This covers
],
"Resource": "arn:aws:logs:eu-central-1:<ACCOUNT_ID>:log-group:/aws/lambda/BunLayerInteg-*"
},
{
"Sid": "CloudFrontOac",
"Effect": "Allow",
"Action": [
"cloudfront:CreateDistribution",
"cloudfront:CreateDistributionWithTags",
"cloudfront:GetDistribution",
"cloudfront:UpdateDistribution",
"cloudfront:DeleteDistribution",
"cloudfront:TagResource",
"cloudfront:UntagResource",
"cloudfront:ListTagsForResource",
"cloudfront:CreateOriginAccessControl",
"cloudfront:GetOriginAccessControl",
"cloudfront:UpdateOriginAccessControl",
"cloudfront:DeleteOriginAccessControl"
],
"Resource": [
"arn:aws:cloudfront::<ACCOUNT_ID>:distribution/*",
"arn:aws:cloudfront::<ACCOUNT_ID>:origin-access-control/*"
]
},
{
"Sid": "SSMBootstrapVersion",
"Effect": "Allow",
Expand Down
91 changes: 91 additions & 0 deletions docs/how-to/streaming.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# How to: Stream responses with status code and headers

> Full working example: https://github.com/BeeSolve/lambda-bun-runtime/tree/main/examples/sample-app

Use this when a Function URL (`InvokeMode.RESPONSE_STREAM`) must stream the body and also set the HTTP status code and headers. The runtime provides the `awslambda` global of the Node.js managed runtime, so the same handler file runs on both.

## Prerequisites

- `@beesolve/lambda-bun-runtime` installed, with a function created by `BunFunction` or `BunFunctionWithLayer`
- Optional: `@beesolve/lambda-fetch-api` for the Fetch API handler in option A

## Steps

### 1. Write the handler

Option A, Fetch API (`@beesolve/lambda-fetch-api`):

```ts
import { asResponseStreamHandler } from "@beesolve/lambda-fetch-api";

export const handler = asResponseStreamHandler(async () => {
const stream = new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode("hello"));
controller.close();
},
});
return new Response(stream, { status: 201, headers: { "x-custom": "value" } });
});
```

Option B, the `awslambda` global directly:

```ts
export const handler = awslambda.streamifyResponse(async (event, responseStream) => {
const stream = awslambda.HttpResponseStream.from(responseStream, {
statusCode: 201,
headers: { "content-type": "text/plain", "x-custom": "value" },
});
stream.write("hello ");
stream.end("world");
});
```

The prelude has the Function URL payload v2 response shape: `statusCode`, `headers` and `cookies` (a string array).

### 2. Create the Function URL in streaming mode

```ts
import { FunctionUrlAuthType, InvokeMode } from "aws-cdk-lib/aws-lambda";
import { BunFunction } from "@beesolve/lambda-bun-runtime";

const streamingFn = new BunFunction(this, "StreamingFn", { entrypoint: "src/streaming.ts" });
streamingFn.addFunctionUrl({
authType: FunctionUrlAuthType.NONE,
invokeMode: InvokeMode.RESPONSE_STREAM,
});
```

### 3. Put CloudFront with OAC in front (optional)

```ts
import { Distribution, AllowedMethods, CachePolicy } from "aws-cdk-lib/aws-cloudfront";
import { FunctionUrlOrigin } from "aws-cdk-lib/aws-cloudfront-origins";

const url = streamingFn.addFunctionUrl({
authType: FunctionUrlAuthType.AWS_IAM,
invokeMode: InvokeMode.RESPONSE_STREAM,
});
new Distribution(this, "Distribution", {
defaultBehavior: {
origin: FunctionUrlOrigin.withOriginAccessControl(url),
cachePolicy: CachePolicy.CACHING_DISABLED,
allowedMethods: AllowedMethods.ALLOW_GET_HEAD,
},
});
```

## Verify

```sh
curl -sN -i https://<function-url>/
```

The status line and headers come from the prelude and the chunks arrive spaced in time.

## Behavior to know

- Without `HttpResponseStream.from`, the stream is sent as plain bytes with status 200.
- A handler that returns an async generator or a `ReadableStream` still streams plain bytes with no metadata.
- If the handler throws before the first write, the error is reported normally. If it throws after streaming started, the request is aborted, because Bun's `fetch` cannot send the error trailers.
44 changes: 44 additions & 0 deletions examples/sample-app/lib/sample-stack.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import * as path from "node:path";
import { CfnOutput, RemovalPolicy, Stack, StackProps } from "aws-cdk-lib";
import * as apigw from "aws-cdk-lib/aws-apigateway";
import * as cloudfront from "aws-cdk-lib/aws-cloudfront";
import * as origins from "aws-cdk-lib/aws-cloudfront-origins";
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";
Expand Down Expand Up @@ -70,6 +72,43 @@ export class SampleStack extends Stack {
bunLayer,
});

// Streaming with HTTP metadata (status code + headers) via Function URL, on the CMR and on
// the layer. Same source file, uses the awslambda global provided by the runtime.
const streamingHttpFn = new BunFunction(this, "StreamingHttpFn", {
entrypoint: src("streaming-http.ts"),
...(runtimeArn == null ? {} : { bunRuntime: { runtimeArn, runtimeAlias } }),
});
const streamingHttpUrl = streamingHttpFn.addFunctionUrl({
authType: lambda.FunctionUrlAuthType.NONE,
invokeMode: lambda.InvokeMode.RESPONSE_STREAM,
});
const streamingHttpLayerFn = new BunFunctionWithLayer(this, "StreamingHttpLayerFn", {
entrypoint: src("streaming-http.ts"),
bunLayer,
});
const streamingHttpLayerUrl = streamingHttpLayerFn.addFunctionUrl({
authType: lambda.FunctionUrlAuthType.NONE,
invokeMode: lambda.InvokeMode.RESPONSE_STREAM,
});

// Streaming behind CloudFront with OAC: the Function URL requires AWS_IAM and only the
// distribution can invoke it.
const streamingHttpOacFn = new BunFunction(this, "StreamingHttpOacFn", {
entrypoint: src("streaming-http.ts"),
...(runtimeArn == null ? {} : { bunRuntime: { runtimeArn, runtimeAlias } }),
});
const streamingHttpOacUrl = streamingHttpOacFn.addFunctionUrl({
authType: lambda.FunctionUrlAuthType.AWS_IAM,
invokeMode: lambda.InvokeMode.RESPONSE_STREAM,
});
const distribution = new cloudfront.Distribution(this, "StreamingDistribution", {
defaultBehavior: {
origin: origins.FunctionUrlOrigin.withOriginAccessControl(streamingHttpOacUrl),
cachePolicy: cloudfront.CachePolicy.CACHING_DISABLED,
allowedMethods: cloudfront.AllowedMethods.ALLOW_GET_HEAD,
},
});

// S3 writer — direct invoke, Bun-native S3
const testBucket = new s3.Bucket(this, "TestBucket", {
autoDeleteObjects: true,
Expand All @@ -96,6 +135,11 @@ export class SampleStack extends Stack {
new CfnOutput(this, "CmrEchoFnArn", { value: cmrEchoFn.functionArn });
new CfnOutput(this, "S3WriterFnArn", { value: s3WriterFn.functionArn });
new CfnOutput(this, "TestBucketName", { value: testBucket.bucketName });
new CfnOutput(this, "StreamingHttpUrl", { value: streamingHttpUrl.url });
new CfnOutput(this, "StreamingHttpLayerUrl", { value: streamingHttpLayerUrl.url });
new CfnOutput(this, "StreamingCloudFrontUrl", {
value: `https://${distribution.distributionDomainName}/`,
});
new CfnOutput(this, "StreamingFnArn", { value: streamingFn.functionArn });
}
}
Loading