diff --git a/DOCS.md b/DOCS.md index 448c33e..4962f4e 100644 --- a/DOCS.md +++ b/DOCS.md @@ -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 diff --git a/README.md b/README.md index ebd29ff..0a10dd4 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/command/runtime.mts b/command/runtime.mts index bc9c000..e311280 100755 --- a/command/runtime.mts +++ b/command/runtime.mts @@ -16,6 +16,13 @@ type Handler = ( context: LambdaContext, ) => Promise | 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; @@ -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 ?? ""; @@ -69,6 +97,28 @@ while (true) { getRemainingTimeInMillis: () => deadlineMs - Date.now(), }; + const isStreamifiedHandler = + (handler as unknown as Record)[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)) { @@ -128,6 +178,80 @@ function formatError(props: { error: unknown }): LambdaError { }; } +type StreamifiedHandler = ( + event: unknown, + responseStream: ResponseStream, + context: LambdaContext, +) => Promise | unknown; + +function createResponseStream(props: { url: string }) { + const encoder = new TextEncoder(); + const state: { + contentType?: string; + started: boolean; + ended: boolean; + post?: Promise; + controller?: ReadableStreamDefaultController; + } = { started: false, ended: false }; + const body = new ReadableStream({ + 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 || diff --git a/docs/aws-oidc-setup.md b/docs/aws-oidc-setup.md index 9ce68e1..cb294b3 100644 --- a/docs/aws-oidc-setup.md +++ b/docs/aws-oidc-setup.md @@ -147,7 +147,7 @@ bunx cdk bootstrap \ #### Scoped CDK execution policy -Save as `cfn-exec-policy.json`, replacing `` 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 `` 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 { @@ -224,6 +224,28 @@ Save as `cfn-exec-policy.json`, replacing `` throughout. This covers ], "Resource": "arn:aws:logs:eu-central-1::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:::distribution/*", + "arn:aws:cloudfront:::origin-access-control/*" + ] + }, { "Sid": "SSMBootstrapVersion", "Effect": "Allow", diff --git a/docs/how-to/streaming.md b/docs/how-to/streaming.md new file mode 100644 index 0000000..79565d6 --- /dev/null +++ b/docs/how-to/streaming.md @@ -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:/// +``` + +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. diff --git a/examples/sample-app/lib/sample-stack.ts b/examples/sample-app/lib/sample-stack.ts index ef5318c..383e979 100644 --- a/examples/sample-app/lib/sample-stack.ts +++ b/examples/sample-app/lib/sample-stack.ts @@ -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"; @@ -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, @@ -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 }); } } diff --git a/examples/sample-app/src/streaming-http.ts b/examples/sample-app/src/streaming-http.ts new file mode 100644 index 0000000..7ea64d0 --- /dev/null +++ b/examples/sample-app/src/streaming-http.ts @@ -0,0 +1,20 @@ +import { asResponseStreamHandler } from "@beesolve/lambda-fetch-api"; + +const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +export const handler = asResponseStreamHandler(async (): Promise => { + const encoder = new TextEncoder(); + const stream = new ReadableStream({ + async start(controller) { + for (const index of [1, 2, 3, 4, 5]) { + controller.enqueue(encoder.encode(`chunk ${index}\n`)); + await delay(300); + } + controller.close(); + }, + }); + return new Response(stream, { + status: 201, + headers: { "content-type": "text/plain", "x-custom": "prelude" }, + }); +}); diff --git a/test/integration/deploy-destroy.test.ts b/test/integration/deploy-destroy.test.ts index ecb6886..7bb35a9 100644 --- a/test/integration/deploy-destroy.test.ts +++ b/test/integration/deploy-destroy.test.ts @@ -33,6 +33,9 @@ interface StackOutputs { S3WriterFnArn: string; TestBucketName: string; StreamingFnArn: string; + StreamingHttpUrl: string; + StreamingHttpLayerUrl: string; + StreamingCloudFrontUrl: string; } function run(cmd: string, cwd = sampleApp) { @@ -158,6 +161,40 @@ describeInteg( expect(body).toBe("hello from streaming"); }); + // PR runs point the CMR functions at the runtime of the latest release (BUN_RUNTIME_ARN), which + // predates the streaming support. They only run against freshly published artifacts. + const usesReleasedRuntime = process.env.BUN_RUNTIME_ARN != null; + for (const [label, urlKey] of [ + ["customer-managed runtime", "StreamingHttpUrl"], + ["layer", "StreamingHttpLayerUrl"], + ["customer-managed runtime behind CloudFront with OAC", "StreamingCloudFrontUrl"], + ] as const) { + const isCmr = label.startsWith("customer-managed runtime"); + test.skipIf(isCmr && usesReleasedRuntime)( + `Function URL streaming keeps status, headers and chunk timing on the ${label}`, + async () => { + const startedAt = Date.now(); + const res = await fetch(outputs[urlKey]); + expect(res.status).toBe(201); + expect(res.headers.get("x-custom")).toBe("prelude"); + expect(res.headers.get("content-type")).toContain("text/plain"); + if (res.body == null) throw new Error("Response has no body"); + const decoder = new TextDecoder(); + const arrivals: Array = []; + let body = ""; + for await (const chunk of res.body) { + arrivals.push(Date.now() - startedAt); + body += decoder.decode(chunk, { stream: true }); + } + expect(body).toBe("chunk 1\nchunk 2\nchunk 3\nchunk 4\nchunk 5\n"); + // Unbuffered: the first and last bytes are separated by about 4 x 300 ms. + const first = arrivals[0] ?? 0; + const last = arrivals[arrivals.length - 1] ?? 0; + expect(last - first).toBeGreaterThan(900); + }, + ); + } + test("Bun-native S3 write", async () => { await invokeLambda(outputs.S3WriterFnArn, { key: "integ-test.txt", diff --git a/test/runtime.test.ts b/test/runtime.test.ts index 7245611..880686c 100644 --- a/test/runtime.test.ts +++ b/test/runtime.test.ts @@ -602,6 +602,107 @@ describe("streaming response", () => { }); }); +describe("streaming with HTTP metadata", () => { + async function runStreamifiedHandler(props: { port: number; name: string; source: string }) { + const tmpDir = `/tmp/test-${props.name}`; + mkdirSync(tmpDir, { recursive: true }); + writeFileSync(`${tmpDir}/h.js`, props.source); + const seen: { + contentType: string | null; + mode: string | null; + body: Uint8Array | null; + errorBody: string | null; + } = { contentType: null, mode: null, body: null, errorBody: null }; + const server = Bun.serve({ + port: props.port, + async fetch(req) { + const url = new URL(req.url); + if (url.pathname === "/2018-06-01/runtime/invocation/next") { + return new Response(JSON.stringify({}), { + headers: { + "Lambda-Runtime-Aws-Request-Id": "req-meta", + "Lambda-Runtime-Invoked-Function-Arn": "arn:test", + "Lambda-Runtime-Deadline-Ms": String(Date.now() + 30000), + }, + }); + } + if (url.pathname.endsWith("/response")) { + seen.contentType = req.headers.get("Content-Type"); + seen.mode = req.headers.get("Lambda-Runtime-Function-Response-Mode"); + seen.body = new Uint8Array(await req.arrayBuffer()); + } + if (url.pathname.endsWith("/error")) seen.errorBody = await req.text(); + return new Response("OK"); + }, + }); + const proc = spawn(["bun", "command/runtime.mts"], { + env: { + ...process.env, + AWS_LAMBDA_RUNTIME_API: `127.0.0.1:${props.port}`, + _HANDLER: "h.handler", + LAMBDA_TASK_ROOT: tmpDir, + }, + stdout: "pipe", + stderr: "pipe", + }); + await waitFor({ + condition: () => seen.body != null || seen.errorBody != null, + timeoutMs: 15000, + }); + proc.kill(); + await proc.exited; + server.stop(); + rmSync(tmpDir, { recursive: true, force: true }); + return seen; + } + + test("HttpResponseStream.from sends content type, JSON prelude, 8 zero bytes and body", async () => { + const prelude = { statusCode: 201, headers: { "x-custom": "prelude" } }; + const seen = await runStreamifiedHandler({ + port: 19270, + name: "meta-prelude", + source: `export const handler = awslambda.streamifyResponse(async (event, stream) => { + stream = awslambda.HttpResponseStream.from(stream, ${JSON.stringify(prelude)}); + stream.write(""); + stream.write("hello "); + stream.end("world"); + });`, + }); + const expected = Buffer.concat([ + Buffer.from(JSON.stringify(prelude)), + Buffer.alloc(8), + Buffer.from("hello world"), + ]); + expect(seen.contentType).toBe("application/vnd.awslambda.http-integration-response"); + expect(seen.mode).toBe("streaming"); + expect(Buffer.from(seen.body ?? new Uint8Array()).equals(expected)).toBe(true); + }); + + test("streamified handler without HttpResponseStream.from posts no content type", async () => { + const seen = await runStreamifiedHandler({ + port: 19271, + name: "meta-plain", + source: `export const handler = awslambda.streamifyResponse(async (event, stream) => { + stream.write("a"); + stream.end("b"); + });`, + }); + expect(seen.contentType).toBeNull(); + expect(new TextDecoder().decode(seen.body ?? new Uint8Array())).toBe("ab"); + }); + + test("throw before the first write posts to the error endpoint", async () => { + const seen = await runStreamifiedHandler({ + port: 19272, + name: "meta-error", + source: `export const handler = awslambda.streamifyResponse(async () => { + throw new Error("boom"); + });`, + }); + expect(seen.errorBody).toContain("boom"); + }); +}); + describe("event passthrough (Property 2)", () => { test("preserves arbitrary JSON data through handler", async () => { const tmpDir = "/tmp/test-passthrough";