diff --git a/DOCS.md b/DOCS.md index 4962f4e..9e5980d 100644 --- a/DOCS.md +++ b/DOCS.md @@ -13,6 +13,7 @@ | [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 | +| [Run work after the response](./docs/how-to/wait-until.md) | `context.waitUntil`, `awslambda.waitUntil`, and `BUN_LAMBDA_WAIT_UNTIL_MARGIN_MS` | | [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 0a10dd4..7b6c148 100644 --- a/README.md +++ b/README.md @@ -127,6 +127,10 @@ export const handler = async (event: SQSEvent): Promise => { }; ``` +### Background work with waitUntil + +Call `context.waitUntil(promise)` (or `awslambda.waitUntil(promise)`) to let work finish after the response is sent. The runtime waits for it before asking Lambda for the next invocation, up to the deadline minus `BUN_LAMBDA_WAIT_UNTIL_MARGIN_MS` (default 1000). Work that is neither awaited nor registered is still frozen by Lambda. See [the how-to](./docs/how-to/wait-until.md). + ### Response Streaming Return a `ReadableStream` or any `AsyncIterable` (including async generators) to stream the response. The runtime detects the return type automatically and sends it using HTTP chunked transfer encoding with the `Lambda-Runtime-Function-Response-Mode: streaming` header — no wrapper or import required. diff --git a/command/runtime.mts b/command/runtime.mts index e311280..07ef198 100755 --- a/command/runtime.mts +++ b/command/runtime.mts @@ -7,6 +7,7 @@ interface LambdaContext { logGroupName: string; logStreamName: string; getRemainingTimeInMillis(): number; + waitUntil(promise: Promise): void; } type StreamChunk = Uint8Array | string; @@ -69,6 +70,23 @@ Object.assign(globalThis, { }, }); +const defaultWaitUntilMarginMs = 1000; +const parsedMarginMs = Number( + process.env.BUN_LAMBDA_WAIT_UNTIL_MARGIN_MS ?? defaultWaitUntilMarginMs, +); +const waitUntilMarginMs = + Number.isFinite(parsedMarginMs) && parsedMarginMs >= 0 + ? parsedMarginMs + : defaultWaitUntilMarginMs; + +// awslambda.waitUntil is global, so it needs to find the invocation currently being served. +const currentInvocation: { pending: Set> } = { pending: new Set() }; + +Object.assign((globalThis as unknown as { awslambda: object }).awslambda, { + waitUntil: (promise: Promise) => + trackPromise({ pending: currentInvocation.pending, promise }), +}); + const handler: Handler = await resolveHandler({ modulePath, exportName }); const functionName = process.env.AWS_LAMBDA_FUNCTION_NAME ?? ""; @@ -86,6 +104,9 @@ while (true) { const event: unknown = await res.json(); + const pending = new Set>(); + currentInvocation.pending = pending; + const context: LambdaContext = { functionName, functionVersion, @@ -95,6 +116,7 @@ while (true) { logGroupName, logStreamName, getRemainingTimeInMillis: () => deadlineMs - Date.now(), + waitUntil: (promise) => trackPromise({ pending, promise }), }; const isStreamifiedHandler = @@ -110,12 +132,14 @@ while (true) { } catch (err: unknown) { if (!responseStream.started()) { await postError({ path: `runtime/invocation/${requestId}/error`, error: err }); + await drainPending({ pending, deadlineMs, marginMs: waitUntilMarginMs }); 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); } + await drainPending({ pending, deadlineMs, marginMs: waitUntilMarginMs }); continue; } @@ -143,6 +167,7 @@ while (true) { error: err, }); } + await drainPending({ pending, deadlineMs, marginMs: waitUntilMarginMs }); } async function resolveHandler(props: { modulePath: string; exportName: string }): Promise { @@ -164,6 +189,39 @@ async function resolveHandler(props: { modulePath: string; exportName: string }) throw new Error("Unreachable"); } +function trackPromise(props: { pending: Set>; promise: Promise }): void { + const tracked: Promise = Promise.resolve(props.promise) + .catch((err: unknown) => { + console.error("waitUntil promise rejected:", err); + }) + .finally(() => { + props.pending.delete(tracked); + }); + props.pending.add(tracked); +} + +// The response is already sent when this runs, so it never throws and never changes the result. +// Promises added while draining are picked up by the next loop pass. +async function drainPending(props: { + pending: Set>; + deadlineMs: number; + marginMs: number; +}): Promise { + while (props.pending.size > 0) { + const budgetMs = props.deadlineMs - props.marginMs - Date.now(); + const timeout = Promise.withResolvers<"timeout">(); + const timer = setTimeout(() => timeout.resolve("timeout"), Math.max(budgetMs, 0)); + const outcome = await Promise.race([Promise.allSettled(props.pending), timeout.promise]); + clearTimeout(timer); + if (outcome === "timeout") { + console.warn( + `waitUntil: ${props.pending.size} task(s) still pending at the drain deadline, continuing`, + ); + return; + } + } +} + function formatError(props: { error: unknown }): LambdaError { if (props.error instanceof Error) { return { diff --git a/docs/how-to/wait-until.md b/docs/how-to/wait-until.md new file mode 100644 index 0000000..e2da4b2 --- /dev/null +++ b/docs/how-to/wait-until.md @@ -0,0 +1,33 @@ +# How to: Finish background work after the response with waitUntil + +Use this when the handler can answer the caller first and still has work to do, such as writing logs, flushing metrics or updating a cache. + +## Usage + +```ts +export const handler = async ( + event: unknown, + context: { waitUntil(promise: Promise): void }, +) => { + context.waitUntil(flushMetrics()); + return { ok: true }; +}; +``` + +`awslambda.waitUntil(promise)` does the same and is bound to the invocation that is currently running, so it works from code that has no access to `context`. + +## How it works + +1. The runtime posts the response. Lambda sends it to the caller at that point. +2. The runtime waits for every promise passed to `waitUntil`, including promises registered while it is already waiting. +3. Only then does it call `/runtime/invocation/next`. The invocation ends at that call, and Lambda may freeze the environment afterwards. + +The same applies when the handler throws (the error is posted first) and to streaming handlers (the wait starts after `end()` and the stream is done). Verify the timing on real Lambda for your use case. + +## Behavior to know + +- Work that is neither awaited nor registered with `waitUntil` is still frozen by Lambda. The runtime cannot see it. A floating promise is not protected. +- The wait stops at the invocation deadline minus a margin. The default margin is 1000 ms. Set `BUN_LAMBDA_WAIT_UNTIL_MARGIN_MS` on the function to change it. When time runs out, the runtime logs a warning with the number of unfinished tasks and moves on. +- A rejected promise is logged with `console.error`. It does not change the result, because the response is already sent. +- Registered promises are not carried over to the next invocation. +- Handlers that never call `waitUntil` behave as before. diff --git a/test/runtime.test.ts b/test/runtime.test.ts index 880686c..59ccce9 100644 --- a/test/runtime.test.ts +++ b/test/runtime.test.ts @@ -762,3 +762,205 @@ describe("event passthrough (Property 2)", () => { rmSync(tmpDir, { recursive: true, force: true }); }); }); + +describe("waitUntil", () => { + async function runWaitUntil(props: { + port: number; + name: string; + source: string; + deadlineInMs?: number; + marginMs?: number; + settleMs: number; + }) { + const tmpDir = `/tmp/test-${props.name}`; + mkdirSync(tmpDir, { recursive: true }); + writeFileSync(`${tmpDir}/h.js`, props.source); + const timeline: Array = []; + 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") { + const count = timeline.filter((entry) => entry.startsWith("next")).length; + timeline.push(`next-${count + 1}`); + return new Response(JSON.stringify({}), { + headers: { + "Lambda-Runtime-Aws-Request-Id": `req-${count + 1}`, + "Lambda-Runtime-Invoked-Function-Arn": "arn:test", + "Lambda-Runtime-Deadline-Ms": String(Date.now() + (props.deadlineInMs ?? 30000)), + }, + }); + } + if (url.pathname.endsWith("/response")) { + await req.arrayBuffer(); + timeline.push("response"); + } + if (url.pathname.endsWith("/error")) { + await req.text(); + timeline.push("error"); + } + if (url.pathname.startsWith("/marker/")) timeline.push(url.pathname.slice(8)); + 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, + ...(props.marginMs != null + ? { BUN_LAMBDA_WAIT_UNTIL_MARGIN_MS: String(props.marginMs) } + : {}), + }, + stdout: "pipe", + stderr: "pipe", + }); + await new Promise((r) => setTimeout(r, props.settleMs)); + proc.kill(); + await proc.exited; + server.stop(); + const stderr = await new Response(proc.stderr).text(); + rmSync(tmpDir, { recursive: true, force: true }); + return { timeline, stderr }; + } + + const mark = (name: string, port: number) => `fetch("http://127.0.0.1:${port}/marker/${name}")`; + + test("task finishes after the response and before the next invocation is requested", async () => { + const port = 19280; + const { timeline } = await runWaitUntil({ + port, + name: "wu-order", + settleMs: 2500, + source: `export const handler = async (event, context) => { + context.waitUntil(new Promise((r) => setTimeout(r, 400)).then(() => ${mark("done", port)})); + return { ok: true }; + };`, + }); + expect(timeline.slice(0, 4)).toEqual(["next-1", "response", "done", "next-2"]); + }); + + test("awslambda.waitUntil is bound to the current invocation", async () => { + const port = 19281; + const { timeline } = await runWaitUntil({ + port, + name: "wu-global", + settleMs: 2500, + source: `export const handler = async () => { + awslambda.waitUntil(new Promise((r) => setTimeout(r, 300)).then(() => ${mark("done", port)})); + return 1; + };`, + }); + expect(timeline.slice(0, 4)).toEqual(["next-1", "response", "done", "next-2"]); + }); + + test("tasks added while draining are also awaited", async () => { + const port = 19282; + const { timeline } = await runWaitUntil({ + port, + name: "wu-nested", + settleMs: 2500, + source: `export const handler = async (event, context) => { + context.waitUntil(new Promise((r) => setTimeout(r, 200)).then(() => { + context.waitUntil(new Promise((r) => setTimeout(r, 200)).then(() => ${mark("second", port)})); + return ${mark("first", port)}; + })); + return 1; + };`, + }); + expect(timeline.slice(0, 5)).toEqual(["next-1", "response", "first", "second", "next-2"]); + }); + + test("drain stops at the deadline minus margin and warns", async () => { + const port = 19283; + const startedAt = Date.now(); + const { timeline, stderr } = await runWaitUntil({ + port, + name: "wu-deadline", + deadlineInMs: 2000, + marginMs: 1000, + settleMs: 3500, + source: `export const handler = async (event, context) => { + context.waitUntil(new Promise((r) => setTimeout(r, 10000)).then(() => ${mark("late", port)})); + return 1; + };`, + }); + expect(Date.now() - startedAt).toBeGreaterThan(1000); + expect(timeline).not.toContain("late"); + expect(timeline.slice(0, 3)).toEqual(["next-1", "response", "next-2"]); + expect(stderr).toContain("1 task(s) still pending"); + }); + + test("error path posts the error, then drains", async () => { + const port = 19284; + const { timeline } = await runWaitUntil({ + port, + name: "wu-error", + settleMs: 2500, + source: `export const handler = async (event, context) => { + context.waitUntil(new Promise((r) => setTimeout(r, 300)).then(() => ${mark("done", port)})); + throw new Error("boom"); + };`, + }); + expect(timeline.slice(0, 4)).toEqual(["next-1", "error", "done", "next-2"]); + }); + + test("rejected task is logged and does not change the result", async () => { + const port = 19285; + const { timeline, stderr } = await runWaitUntil({ + port, + name: "wu-reject", + settleMs: 2500, + source: `export const handler = async (event, context) => { + context.waitUntil(Promise.reject(new Error("bg-failure"))); + return 1; + };`, + }); + expect(timeline.slice(0, 3)).toEqual(["next-1", "response", "next-2"]); + expect(stderr).toContain("bg-failure"); + }); + + test("streamified handler drains after the stream is done", async () => { + const port = 19286; + const { timeline } = await runWaitUntil({ + port, + name: "wu-stream", + settleMs: 2500, + source: `export const handler = awslambda.streamifyResponse(async (event, stream, context) => { + context.waitUntil(new Promise((r) => setTimeout(r, 300)).then(() => ${mark("done", port)})); + stream.end("hi"); + });`, + }); + expect(timeline.slice(0, 4)).toEqual(["next-1", "response", "done", "next-2"]); + }); + + test("tasks do not leak into the next invocation", async () => { + const port = 19287; + const { timeline } = await runWaitUntil({ + port, + name: "wu-leak", + settleMs: 3000, + source: `let calls = 0; + export const handler = async (event, context) => { + calls++; + if (calls === 1) context.waitUntil(${mark("first", port)}); + return calls; + };`, + }); + expect(timeline.filter((entry) => entry === "first")).toHaveLength(1); + expect(timeline.indexOf("first")).toBeLessThan(timeline.indexOf("next-2")); + }); + + test("handlers that never call waitUntil proceed immediately", async () => { + const port = 19288; + const { timeline, stderr } = await runWaitUntil({ + port, + name: "wu-unused", + settleMs: 1500, + source: `export const handler = async () => 1;`, + }); + expect(timeline.slice(0, 3)).toEqual(["next-1", "response", "next-2"]); + expect(stderr).not.toContain("waitUntil"); + }); +});