Repository navigation
feat(bb-logger,core): backend Lambda log lines carry the invocation's requestId #1325
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 1 commit
56b3be1
1a1b0f4
9d8ba5f
d287cae
1adfc9b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
…requestId Logs from one request couldn't be tied together. Core's createLambdaHandler now runs each invocation inside an AsyncLocalStorage scope holding its awsRequestId (registered on globalThis so every copy of core shares it), and bb-logger adds it to each line as requestId. A requestId passed in context still wins; local dev sets none.
- Loading branch information
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| --- | ||
| "@aws-blocks/bb-logger": minor | ||
| "@aws-blocks/core": patch | ||
| "@aws-blocks/blocks": patch | ||
| --- | ||
|
|
||
| On AWS Lambda, every `Logger` line now carries `requestId`, the invocation's request id, so you can correlate everything one request logged (for example `filter requestId = "<id>"` in CloudWatch Logs Insights). Core's `createLambdaHandler` runs each invocation with its `awsRequestId` in scope, and overlapping invocations on one container each see their own id. A `requestId` you pass in context still takes precedence. Local dev sets no request id, so the field is absent there. | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| /** | ||
| * On AWS, core's Lambda handler runs each invocation with its awsRequestId in | ||
| * the `__BLOCKS_REQUEST_ID_STORE__` store (see core's request-context.ts), and | ||
| * every log line carries it as `requestId`. | ||
| */ | ||
| import { test } from 'node:test'; | ||
| import assert from 'node:assert'; | ||
| import { AsyncLocalStorage } from 'node:async_hooks'; | ||
| import { buildEntry } from './serializer.js'; | ||
|
|
||
| const globals = globalThis as { __BLOCKS_REQUEST_ID_STORE__?: AsyncLocalStorage<string | undefined> }; | ||
| // Core registers this store when its handler loads; stand in for it here. | ||
| if (!globals.__BLOCKS_REQUEST_ID_STORE__) globals.__BLOCKS_REQUEST_ID_STORE__ = new AsyncLocalStorage(); | ||
| const store: AsyncLocalStorage<string | undefined> = globals.__BLOCKS_REQUEST_ID_STORE__; | ||
|
|
||
| const parse = (line: string) => JSON.parse(line) as Record<string, unknown>; | ||
|
|
||
| test('a line logged inside an invocation carries its request id', () => { | ||
| const entry = store.run('req-123', () => parse(buildEntry('info', 'hello', 'app', []))); | ||
| assert.strictEqual(entry.requestId, 'req-123'); | ||
| }); | ||
|
|
||
| test('a line logged outside an invocation has no request id', () => { | ||
| assert.strictEqual('requestId' in parse(buildEntry('info', 'hello', 'app', [])), false); | ||
| }); | ||
|
|
||
| test('a requestId the caller passes in context wins', () => { | ||
| const entry = store.run('req-123', () => parse(buildEntry('info', 'hello', 'app', [{ requestId: 'mine' }]))); | ||
| assert.strictEqual(entry.requestId, 'mine'); | ||
| }); | ||
|
|
||
| test('overlapping invocations each log their own id', async () => { | ||
| const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); | ||
| const logAfter = (id: string, ms: number) => | ||
| store.run(id, async () => { | ||
| await sleep(ms); | ||
| return parse(buildEntry('info', id, 'app', [])).requestId; | ||
| }); | ||
| const [a, b] = await Promise.all([logAfter('req-a', 30), logAfter('req-b', 5)]); | ||
| assert.deepStrictEqual([a, b], ['req-a', 'req-b']); | ||
| }); | ||
|
|
||
| test('the structural fields keep their order, with requestId after logger', () => { | ||
| const entry = store.run('req-1', () => parse(buildEntry('warn', 'm', 'app', [{ k: 1 }]))); | ||
| assert.deepStrictEqual(Object.keys(entry).slice(0, 5), ['level', 'message', 'timestamp', 'logger', 'requestId']); | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,6 +10,19 @@ | |
| import type { LogLevel } from './types.js'; | ||
| import { LoggingErrors } from './errors.js'; | ||
|
|
||
| /** | ||
| * The id of the request being handled, from the per-invocation store core's | ||
| * Lambda handler populates (`request-context.ts` in `@aws-blocks/core`). Read | ||
| * through its `globalThis` registration rather than an import, so the CDK entry | ||
| * (which shares this serializer) doesn't load core's runtime handler at synth, | ||
| * and a separately resolved copy of core still sees the same store. | ||
| */ | ||
| function currentRequestId(): string | undefined { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The other readers of
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in 1a1b0f4. bb-logger no longer reads the global directly; it calls |
||
| const store = (globalThis as { __BLOCKS_REQUEST_ID_STORE__?: { getStore(): unknown } }).__BLOCKS_REQUEST_ID_STORE__; | ||
| const id = store?.getStore(); | ||
| return typeof id === 'string' && id.length > 0 ? id : undefined; | ||
| } | ||
|
|
||
| const LEVEL_PRIORITY: Record<LogLevel, number> = { | ||
| debug: 0, | ||
| info: 1, | ||
|
|
@@ -98,6 +111,12 @@ export function buildEntry( | |
| logger: loggerName, | ||
| }; | ||
|
|
||
| // The id of the request being handled (the Lambda invocation's awsRequestId), | ||
| // so every line one request logs can be correlated. Not a reserved field: a | ||
| // `requestId` the caller puts in context still wins below. | ||
| const requestId = currentRequestId(); | ||
| if (requestId) entry.requestId = requestId; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
So Could this go under its own key in
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in d287cae. The Lambda id is now logged as |
||
|
|
||
| // Merge user context — reserved keys are skipped (structural fields already written above). | ||
| for (const ctx of contexts) { | ||
| for (const [key, value] of Object.entries(ctx)) { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -17,6 +17,7 @@ | |
| // The request-scoped stores and the forwarded-host gate live in request-context.ts | ||
| // so the container HTTP server shares them; re-exported here for existing imports. | ||
| export { requestCookies, requestClientUserAgent, isLoopbackForwardedHost } from './request-context.js'; | ||
| import { requestIdStore } from './request-context.js'; | ||
|
|
||
| /** | ||
| * Event source mapping identifiers used by AWS when pushing records to Lambda. | ||
|
|
@@ -226,6 +227,8 @@ | |
| */ | ||
| export interface LambdaContext { | ||
| getRemainingTimeInMillis(): number; | ||
| /** The invocation's request id; carried through the invocation by {@link currentRequestId}. */ | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in 1a1b0f4. The JSDoc now names |
||
| awsRequestId?: string; | ||
| } | ||
|
|
||
| /** | ||
|
|
@@ -292,7 +295,11 @@ | |
| lockRouteRegistry(); | ||
| } | ||
|
|
||
| return async (event: any, context?: LambdaContext) => { | ||
| // Each invocation runs with its request id in scope, so Building Blocks can | ||
| // tag their output with it (see currentRequestId in request-context.ts). | ||
| return (event: any, context?: LambdaContext) => requestIdStore.run(context?.awsRequestId, () => invoke(event, context)); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in 1a1b0f4: |
||
|
|
||
| async function invoke(event: any, context?: LambdaContext) { | ||
| if (!handler) { | ||
| // Retry init on failure instead of caching the rejection. If initialize() throws (most often | ||
| // because loadConfigToProcessEnv() couldn't read blocks-config.json during the brief | ||
|
|
@@ -312,7 +319,7 @@ | |
| // Only apply the HTTP timeout guard to API Gateway requests; async event | ||
| // sources (SQS, EventBridge, WebSocket) have their own retry semantics. | ||
| if (!isApiGatewayHttpEvent(event)) { | ||
| return handler!(event); | ||
| } | ||
|
|
||
| // Race the handler against a timeout so we can return a proper 504 before | ||
|
|
@@ -320,7 +327,7 @@ | |
| const deadlineMs = computeHttpDeadlineMs(context); | ||
| const abortController = new AbortController(); | ||
|
|
||
| const handlerPromise = handler!(event, abortController.signal); | ||
| // After a timeout we abort in-flight fetches/SDK calls via the signal. | ||
| // Those will reject with AbortError, but we've already returned the 504 | ||
| // response — attach a no-op catch to prevent unhandled-rejection crashes. | ||
|
|
@@ -341,10 +348,10 @@ | |
| try { | ||
| // Whichever settles first wins: handler success or timeout rejection. | ||
| const result = await Promise.race([handlerPromise, timeoutPromise]); | ||
| clearTimeout(timer!); | ||
| return result; | ||
| } catch (err) { | ||
| clearTimeout(timer!); | ||
| if (err instanceof HandlerTimeoutError) { | ||
| // Timeout won the race — build a 504 response. Format depends on | ||
| // whether the request targeted an RPC endpoint (structured JSON-RPC | ||
|
|
@@ -366,7 +373,7 @@ | |
| // Non-timeout errors (handler threw before deadline) propagate normally. | ||
| throw err; | ||
| } | ||
| }; | ||
| } | ||
| } | ||
|
|
||
| class HandlerTimeoutError extends Error { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -27,6 +27,31 @@ export const requestCookies = new AsyncLocalStorage<string>(); | |
| export const requestClientUserAgent = new AsyncLocalStorage<string | undefined>(); | ||
| (globalThis as any).__BLOCKS_REQUEST_CLIENT_USER_AGENT_STORE__ = requestClientUserAgent; | ||
|
|
||
| /** | ||
| * Per-invocation store for the id of the request being handled: the Lambda | ||
| * `awsRequestId` while `createLambdaHandler` runs an invocation. Building Blocks | ||
| * read it through {@link currentRequestId} to tag their output (bb-logger adds it | ||
| * to every log line), so everything one request logs can be correlated. | ||
| * | ||
| * Registered on `globalThis.__BLOCKS_REQUEST_ID_STORE__` and read from there, so | ||
| * a Building Block that resolves its own copy of `@aws-blocks/core` still sees | ||
| * the store the handler populated. | ||
| */ | ||
| const REQUEST_ID_STORE_KEY = '__BLOCKS_REQUEST_ID_STORE__'; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. On the decision for review: core's CDK entry ( As it is, this string key is duplicated in bb-logger, and no test runs core and bb-logger together. A rename on one side would pass both suites.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done in 1a1b0f4. |
||
| const globalStores = globalThis as unknown as Record<string, AsyncLocalStorage<string | undefined> | undefined>; | ||
| export const requestIdStore: AsyncLocalStorage<string | undefined> = | ||
| globalStores[REQUEST_ID_STORE_KEY] ?? new AsyncLocalStorage<string | undefined>(); | ||
| globalStores[REQUEST_ID_STORE_KEY] = requestIdStore; | ||
|
|
||
| /** | ||
| * The id of the request being handled, or `undefined` outside one. On AWS | ||
| * Lambda this is the invocation's `awsRequestId` (the id in the function's | ||
| * `START`/`END`/`REPORT` log lines). The local dev server sets none. | ||
| */ | ||
| export function currentRequestId(): string | undefined { | ||
| return requestIdStore.getStore(); | ||
| } | ||
|
|
||
| /** | ||
| * Hostnames that count as loopback for the trusted-forwarded-host gate. | ||
| * | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Two things:
createLambdaHandler, so "everyLoggerline" on Lambda overclaims.@aws-blocks/core ^0.8.0, and there's no fixed release group. An app that upgrades only bb-logger gets no field and no warning. Worth raising the floor to the core version that ships this.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Both addressed in 9d8ba5f. The changeset, README and DESIGN now scope the field to functions built with
createLambdaHandler(the backend API and its event handlers), and say that SSR hosting web functions and container compute set no id. On the floor:updateInternalDependenciesispatchin.changeset/config.json, sochangeset versionraises bb-logger's@aws-blocks/corerange to the core release that ships this. bb-logger also importscurrentRequestIdfrom core now, so an older core fails at import instead of silently dropping the field.