Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
feat(bb-logger,core): every log line on AWS carries the invocation's …
…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
osama-rizk committed Nov 6, 2026
commit 56b3be1ab14221f924a00cead2092a8dc6943d9a
7 changes: 7 additions & 0 deletions .changeset/logger-request-id.md
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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two things:

  • SSR hosting web functions run on Lambda without createLambdaHandler, so "every Logger line" on Lambda overclaims.
  • bb-logger still depends on @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.

Copy link
Copy Markdown
Contributor Author

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: updateInternalDependencies is patch in .changeset/config.json, so changeset version raises bb-logger's @aws-blocks/core range to the core release that ships this. bb-logger also imports currentRequestId from core now, so an older core fails at import instead of silently dropping the field.

1 change: 1 addition & 0 deletions packages/bb-logger/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export interface LogEntry {
logger: string;
// (undocumented)
message: string;
requestId?: string;
timestamp: string;
traceId?: string;
}
Expand Down
2 changes: 2 additions & 0 deletions packages/bb-logger/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ Fields:
- `timestamp` — ISO 8601 timestamp from `new Date().toISOString()`.
- `logger` — The `id` passed to the constructor.
- `traceId` — X-Ray trace ID (auto-injected from `_X_AMZN_TRACE_ID` env var when present).
- `requestId` — the Lambda invocation's `awsRequestId`. Core's `createLambdaHandler` runs each invocation inside an `AsyncLocalStorage` scope holding it (`request-context.ts`, registered on `globalThis.__BLOCKS_REQUEST_ID_STORE__`), and the serializer reads that store when it builds a line. It is read through the global rather than imported, so the CDK entry, which shares the serializer, doesn't load core's runtime handler at synth, and a separately resolved copy of core still sees the same store. It is not a reserved field: a `requestId` in context overrides it. Overlapping invocations on one container each see their own id.
- Spread fields from `defaultContext`, `child()` context, and per-call `context` (later wins).

### Serialization Safety
Expand Down Expand Up @@ -98,3 +99,4 @@ The mock entry point (`index.mock.ts`) re-exports the AWS runtime (`index.aws.ts
| No log retention enforcement | Logs are ephemeral in local terminal | No mitigation needed — local logs don't persist |
| No log group/stream structure | Cannot test subscription filters | Sandbox testing covers these |
| No X-Ray trace ID injection | `traceId` field absent locally | Set `_X_AMZN_TRACE_ID` env var manually if needed |
| No request id | `requestId` field absent locally (the dev server sets none) | Pass a `requestId` in `child()` context if you need correlation locally |
4 changes: 4 additions & 0 deletions packages/bb-logger/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,13 @@ Every log entry is a JSON object written to stdout (or stderr for errors):
"message": "User logged in",
"timestamp": "2024-01-15T10:30:00.000Z",
"logger": "app",
"requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
"userId": "user-123"
}
```

On AWS Lambda, `requestId` is the invocation's request id (the same id as in the function's `START`/`END`/`REPORT` lines), added to every line automatically, so you can find everything one request logged, for example with CloudWatch Logs Insights: `filter requestId = "<id>"`. A `requestId` you pass in context takes precedence. Local dev has no request id, so the field is absent there.

### Child Loggers

Create request-scoped loggers that inherit context:
Expand Down Expand Up @@ -147,6 +150,7 @@ In local dev (`npm run dev`), the Logger BB:
- Does NOT create any files in `.bb-data/`
- Retention has no local effect (it is a cloud-only, compute-level setting)
- Log level comes from the `Logger`'s `level` option (default `'info'`)
- Lines have no `requestId` field: the dev server doesn't set a request id

## Errors

Expand Down
49 changes: 49 additions & 0 deletions packages/bb-logger/src/request-id.test.ts
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']);
});
19 changes: 19 additions & 0 deletions packages/bb-logger/src/serializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The other readers of globalThis stores check typeof store.getStore !== 'function' (withAuth.ts:14, client-user-agent.ts:70, client/index.ts:19). Without that check, a non-store value at this key makes every log call throw, and writeLog doesn't catch it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The 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 currentRequestId() from core. Core now reuses the value at the key only when it has both getStore and run functions, and replaces anything else. currentRequestId() also returns only a non-empty string. Test: request-context — request id store registration in lambda-handler.test.ts loads a fresh copy of the module with a non-store at the key.

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,
Expand Down Expand Up @@ -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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

requestId isn't in RESERVED_FIELDS, so an app's own requestId in context replaces the Lambda id. That splits one request across two ids.

  • Lines from child({ requestId }) carry the app's id. The README example at line 81 does this, and so does the comprehensive test app.
  • Building Block loggers in the same invocation carry the Lambda id.

So filter requestId = "<id>" doesn't return everything one request logged. There's also child({ requestId: headers['x-request-id'] }). With the header missing, it writes undefined and drops the field. With the header present, the client chooses the logged id.

Could this go under its own key in RESERVED_FIELDS, e.g. awsRequestId? That leaves the app's field alone and fixes the E2E failure.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d287cae. The Lambda id is now logged as awsRequestId, which is in RESERVED_FIELDS. A context value under that key is ignored, and an app's own requestId (from child({ requestId }), the README example or a header) stays a separate field, so it can't replace the invocation id. Every line one request logs now shares one awsRequestId. Tests in request-id.test.ts: a context requestId is kept beside the invocation id, and a context awsRequestId is ignored both inside and outside an invocation. The README, DESIGN, changeset and the regenerated API.md (1adfc9b) use the new name.


// 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)) {
Expand Down
6 changes: 6 additions & 0 deletions packages/bb-logger/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ export interface LogEntry {
logger: string;
/** X-Ray trace ID. Auto-injected when running in Lambda with X-Ray enabled. */
traceId?: string;
/**
* The id of the request that logged this line: the Lambda invocation's
* `awsRequestId`. Auto-injected on AWS Lambda; absent in local dev. A
* `requestId` you pass in context takes precedence.
*/
requestId?: string;
[key: string]: unknown;
}

Expand Down
41 changes: 41 additions & 0 deletions packages/core/src/lambda-handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@

const reader = (capturedBody as ReadableStream<Uint8Array>).getReader();
const { value } = await reader.read();
const text = new TextDecoder().decode(value!);

Check warning on line 381 in packages/core/src/lambda-handler.test.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/style/noNonNullAssertion

Forbidden non-null assertion.
assert.strictEqual(text, webhookPayload);
});

Expand Down Expand Up @@ -1560,7 +1560,7 @@

assert.strictEqual(result.statusCode, 504);
assert.ok(capturedSignal, 'signal should be passed to handler');
assert.strictEqual(capturedSignal!.aborted, true, 'signal should be aborted after timeout');

Check warning on line 1563 in packages/core/src/lambda-handler.test.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/style/noNonNullAssertion

Forbidden non-null assertion.
});

it('handler errors that are not timeouts propagate normally', async () => {
Expand Down Expand Up @@ -1763,7 +1763,7 @@

assert.strictEqual(result.statusCode, 200);
assert.ok(capturedSignal, 'signal should be passed to handler');
assert.strictEqual(capturedSignal!.aborted, false, 'signal should not be aborted for successful requests');

Check warning on line 1766 in packages/core/src/lambda-handler.test.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/style/noNonNullAssertion

Forbidden non-null assertion.
});

it('signal is available in RawRoute handler and aborted on timeout', async () => {
Expand All @@ -1789,7 +1789,7 @@

assert.strictEqual(result.statusCode, 504);
assert.ok(capturedSignal, 'signal should be passed to RawRoute handler');
assert.strictEqual(capturedSignal!.aborted, true, 'signal should be aborted after timeout');

Check warning on line 1792 in packages/core/src/lambda-handler.test.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/style/noNonNullAssertion

Forbidden non-null assertion.
});
});

Expand Down Expand Up @@ -2295,3 +2295,44 @@
assert.deepStrictEqual(JSON.parse(result.body).result, { m: 'hi' });
});
});

// ── request id in scope ─────────────────────────────────────────────────────
// Each invocation runs with its Lambda awsRequestId in scope, so Building Blocks
// (bb-logger) can tag their output with it. Overlapping invocations on one
// container must each see their own id.

describe('createLambdaHandler — request id in scope', () => {
const ctx = (awsRequestId: string): LambdaContext => ({ awsRequestId, getRemainingTimeInMillis: () => 30_000 });
const readStore = () =>
(globalThis as { __BLOCKS_REQUEST_ID_STORE__?: { getStore(): unknown } }).__BLOCKS_REQUEST_ID_STORE__?.getStore();

it('makes the invocation awsRequestId visible to the backend method', async () => {
const backend = { api: (_c: BlocksContext) => ({ async who() { return { id: readStore() ?? null }; } }) };
const handler = createLambdaHandler(async () => backend);
const res: any = await handler(makeEvent({ body: JSON.stringify({ jsonrpc: '2.0', method: 'api.who', params: [], id: 1 }) }), ctx('req-111'));
assert.deepStrictEqual(decodeRpcResponse(JSON.parse(res.body)), { id: 'req-111' });
});

it('keeps overlapping invocations apart', async () => {
let release!: () => void;
const gate = new Promise<void>((r) => { release = r; });
const backend = {
api: (_c: BlocksContext) => ({
async slow() { await gate; return { id: readStore() ?? null }; },
async fast() { return { id: readStore() ?? null }; },
}),
};
const handler = createLambdaHandler(async () => backend);
const call = (method: string, id: string) =>
handler(makeEvent({ body: JSON.stringify({ jsonrpc: '2.0', method: `api.${method}`, params: [], id: 1 }) }), ctx(id)) as Promise<any>;
const slow = call('slow', 'req-slow');
const fast = await call('fast', 'req-fast');
release();
assert.deepStrictEqual(decodeRpcResponse(JSON.parse(fast.body)), { id: 'req-fast' });
assert.deepStrictEqual(decodeRpcResponse(JSON.parse((await slow).body)), { id: 'req-slow' });
});

it('has no request id outside an invocation', () => {
assert.strictEqual(readStore(), undefined);
});
});
11 changes: 9 additions & 2 deletions packages/core/src/lambda-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -226,6 +227,8 @@
*/
export interface LambdaContext {
getRemainingTimeInMillis(): number;
/** The invocation's request id; carried through the invocation by {@link currentRequestId}. */

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

currentRequestId isn't imported here or exported from core's entry points, so this {@link} won't resolve.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1a1b0f4. The JSDoc now names currentRequestId() from @aws-blocks/core/bb-utils in backticks instead of a {@link}.

awsRequestId?: string;
}

/**
Expand Down Expand Up @@ -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));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

initialize() runs inside this run(), so the backend import and the Building Block constructors execute in the first invocation's scope. Anything long-lived created there keeps request #1's id for the life of the container, e.g. a module-scope setInterval or a pool's on('error') listener. initPromise = requestIdStore.exit(() => initialize()).catch(...) avoids this. The trade-off is that init-time lines get no id.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1a1b0f4: initPromise = requestIdStore.exit(() => initialize()), with a comment on why. Init-time lines get no id, as you noted. Test: imports the backend outside the first invocation request id checks the factory sees no id and the method still sees req-first. It fails on the previous head.


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
Expand All @@ -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);

Check warning on line 322 in packages/core/src/lambda-handler.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/style/noNonNullAssertion

Forbidden non-null assertion.
}

// Race the handler against a timeout so we can return a proper 504 before
Expand All @@ -320,7 +327,7 @@
const deadlineMs = computeHttpDeadlineMs(context);
const abortController = new AbortController();

const handlerPromise = handler!(event, abortController.signal);

Check warning on line 330 in packages/core/src/lambda-handler.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/style/noNonNullAssertion

Forbidden non-null assertion.
// 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.
Expand All @@ -341,10 +348,10 @@
try {
// Whichever settles first wins: handler success or timeout rejection.
const result = await Promise.race([handlerPromise, timeoutPromise]);
clearTimeout(timer!);

Check warning on line 351 in packages/core/src/lambda-handler.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/style/noNonNullAssertion

Forbidden non-null assertion.
return result;
} catch (err) {
clearTimeout(timer!);

Check warning on line 354 in packages/core/src/lambda-handler.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/style/noNonNullAssertion

Forbidden non-null assertion.
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
Expand All @@ -366,7 +373,7 @@
// Non-timeout errors (handler threw before deadline) propagate normally.
throw err;
}
};
}
}

class HandlerTimeoutError extends Error {
Expand Down
25 changes: 25 additions & 0 deletions packages/core/src/request-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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__';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On the decision for review: core's CDK entry (index.cdk.ts:119) and bb-utils.ts:13 already load lambda-handler.js, and through it this module. So a typed accessor from @aws-blocks/core/bb-utils wouldn't add anything to the synth path.

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. currentRequestId() below is also unused. Could bb-logger import it from bb-utils instead?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 1a1b0f4. currentRequestId() is exported from @aws-blocks/core/bb-utils, and the bb-logger serializer imports it, so the key lives only in core. The bb-logger test now uses the store core registers when the serializer loads, not a stand-in, so it runs core and bb-logger together. A second test checks that a second copy of core reuses the registered store.

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.
*
Expand Down
Loading