Skip to content

Commit 1a1b0f4

Browse files
committed
fix(bb-logger,core): read the request id through bb-utils, guard the store, keep init outside the first request
- bb-logger reads the id with currentRequestId() from @aws-blocks/core/bb-utils instead of a duplicated globalThis key - core ignores a non-store value at the globalThis key instead of throwing on every log call - the backend import and Building Block constructors run outside the first invocation's request-id scope - the degraded line written on a serialization failure keeps requestId and traceId
1 parent 56b3be1 commit 1a1b0f4

6 files changed

Lines changed: 82 additions & 24 deletions

File tree

‎packages/bb-logger/src/request-id.test.ts‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,14 @@
99
import { test } from 'node:test';
1010
import assert from 'node:assert';
1111
import { AsyncLocalStorage } from 'node:async_hooks';
12-
import { buildEntry } from './serializer.js';
12+
import { buildEntry, safeStringify } from './serializer.js';
1313

14+
// The serializer reads the id through `currentRequestId()` from core's bb-utils,
15+
// which registers core's own store here on load. Use that real store, not a stand-in.
1416
const globals = globalThis as { __BLOCKS_REQUEST_ID_STORE__?: AsyncLocalStorage<string | undefined> };
15-
// Core registers this store when its handler loads; stand in for it here.
16-
if (!globals.__BLOCKS_REQUEST_ID_STORE__) globals.__BLOCKS_REQUEST_ID_STORE__ = new AsyncLocalStorage();
17-
const store: AsyncLocalStorage<string | undefined> = globals.__BLOCKS_REQUEST_ID_STORE__;
17+
const registered = globals.__BLOCKS_REQUEST_ID_STORE__;
18+
assert.ok(registered instanceof AsyncLocalStorage, "core's request-id store is registered once the serializer loads");
19+
const store: AsyncLocalStorage<string | undefined> = registered;
1820

1921
const parse = (line: string) => JSON.parse(line) as Record<string, unknown>;
2022

@@ -47,3 +49,19 @@ test('the structural fields keep their order, with requestId after logger', () =
4749
const entry = store.run('req-1', () => parse(buildEntry('warn', 'm', 'app', [{ k: 1 }])));
4850
assert.deepStrictEqual(Object.keys(entry).slice(0, 5), ['level', 'message', 'timestamp', 'logger', 'requestId']);
4951
});
52+
53+
test('the degraded line written on a serialization failure keeps requestId and traceId', () => {
54+
const unserializable = { toJSON() { throw new Error('boom'); } };
55+
const line = parse(
56+
safeStringify({ level: 'error', message: 'm', timestamp: 't', logger: 'app', requestId: 'req-9', traceId: '1-abc', bad: unserializable }),
57+
);
58+
assert.strictEqual(line._serializationError, 'SerializationFailedException');
59+
assert.strictEqual(line.requestId, 'req-9');
60+
assert.strictEqual(line.traceId, '1-abc');
61+
});
62+
63+
test('the degraded line drops a non-string requestId rather than failing again', () => {
64+
const unserializable = { toJSON() { throw new Error('boom'); } };
65+
const line = parse(safeStringify({ level: 'error', message: 'm', timestamp: 't', logger: 'app', requestId: 1n, bad: unserializable }));
66+
assert.strictEqual('requestId' in line, false);
67+
});

‎packages/bb-logger/src/serializer.ts‎

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,22 +7,10 @@
77
* BigInt conversion, Error object extraction, and log level filtering.
88
*/
99

10+
import { currentRequestId } from '@aws-blocks/core/bb-utils';
1011
import type { LogLevel } from './types.js';
1112
import { LoggingErrors } from './errors.js';
1213

13-
/**
14-
* The id of the request being handled, from the per-invocation store core's
15-
* Lambda handler populates (`request-context.ts` in `@aws-blocks/core`). Read
16-
* through its `globalThis` registration rather than an import, so the CDK entry
17-
* (which shares this serializer) doesn't load core's runtime handler at synth,
18-
* and a separately resolved copy of core still sees the same store.
19-
*/
20-
function currentRequestId(): string | undefined {
21-
const store = (globalThis as { __BLOCKS_REQUEST_ID_STORE__?: { getStore(): unknown } }).__BLOCKS_REQUEST_ID_STORE__;
22-
const id = store?.getStore();
23-
return typeof id === 'string' && id.length > 0 ? id : undefined;
24-
}
25-
2614
const LEVEL_PRIORITY: Record<LogLevel, number> = {
2715
debug: 0,
2816
info: 1,
@@ -72,6 +60,9 @@ export function safeStringify(obj: Record<string, unknown>): string {
7260
message: obj.message,
7361
timestamp: obj.timestamp,
7462
logger: obj.logger,
63+
// Keep the correlation ids: degraded lines are the ones most worth tracing.
64+
requestId: typeof obj.requestId === 'string' ? obj.requestId : undefined,
65+
traceId: typeof obj.traceId === 'string' ? obj.traceId : undefined,
7566
_serializationError: LoggingErrors.SerializationFailed,
7667
});
7768
}

‎packages/core/src/bb-utils.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ export { getMockDataDir } from './common/mock-data.js';
1111
export { assertNotMockInDeployedEnv } from './common/runtime-guard.js';
1212
export { API_NAMESPACE_MARKER } from './api.js';
1313
export { EventSourceMapping } from './lambda-handler.js';
14+
export { currentRequestId } from './request-context.js';
1415
export { constantTimeEquals } from './common/crypto.js';
1516
export { isLoopbackHost, isWildcardHost, isIpLiteral } from './common/loopback.js';
1617
// Defined in the config module (it owns the config-key contract), re-exported

‎packages/core/src/lambda-handler.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2335,4 +2335,40 @@ describe('createLambdaHandler — request id in scope', () => {
23352335
it('has no request id outside an invocation', () => {
23362336
assert.strictEqual(readStore(), undefined);
23372337
});
2338+
2339+
it('imports the backend outside the first invocation request id', async () => {
2340+
let idAtImport: unknown = 'not-imported';
2341+
const backend = { api: (_c: BlocksContext) => ({ async who() { return { id: readStore() ?? null }; } }) };
2342+
const handler = createLambdaHandler(async () => {
2343+
idAtImport = readStore();
2344+
return backend;
2345+
});
2346+
const res: any = await handler(makeEvent({ body: JSON.stringify({ jsonrpc: '2.0', method: 'api.who', params: [], id: 1 }) }), ctx('req-first'));
2347+
assert.strictEqual(idAtImport, undefined);
2348+
assert.deepStrictEqual(decodeRpcResponse(JSON.parse(res.body)), { id: 'req-first' });
2349+
});
2350+
});
2351+
2352+
describe('request-context — request id store registration', () => {
2353+
const KEY = '__BLOCKS_REQUEST_ID_STORE__';
2354+
const globals = globalThis as unknown as Record<string, unknown>;
2355+
2356+
it('replaces a non-store value at the globalThis key instead of throwing on use', async () => {
2357+
const original = globals[KEY];
2358+
globals[KEY] = { not: 'a store' };
2359+
try {
2360+
const fresh = await import(`./request-context.js?non-store-${Date.now()}`);
2361+
assert.strictEqual(fresh.currentRequestId(), undefined);
2362+
assert.strictEqual(fresh.requestIdStore.run('req-x', () => fresh.currentRequestId()), 'req-x');
2363+
assert.strictEqual(globals[KEY], fresh.requestIdStore);
2364+
} finally {
2365+
globals[KEY] = original;
2366+
}
2367+
});
2368+
2369+
it('a second copy of core reuses the registered store', async () => {
2370+
const original = globals[KEY];
2371+
const fresh = await import(`./request-context.js?second-copy-${Date.now()}`);
2372+
assert.strictEqual(fresh.requestIdStore, original);
2373+
});
23382374
});

‎packages/core/src/lambda-handler.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,7 @@ export function computeHttpDeadlineMs(context?: LambdaContext): number {
227227
*/
228228
export interface LambdaContext {
229229
getRemainingTimeInMillis(): number;
230-
/** The invocation's request id; carried through the invocation by {@link currentRequestId}. */
230+
/** The invocation's request id; Building Blocks read it with `currentRequestId()` from `@aws-blocks/core/bb-utils`. */
231231
awsRequestId?: string;
232232
}
233233

@@ -296,7 +296,7 @@ export function createLambdaHandler(backendFactory: () => Promise<any>) {
296296
}
297297

298298
// Each invocation runs with its request id in scope, so Building Blocks can
299-
// tag their output with it (see currentRequestId in request-context.ts).
299+
// tag their output with it (`currentRequestId()` in request-context.ts).
300300
return (event: any, context?: LambdaContext) => requestIdStore.run(context?.awsRequestId, () => invoke(event, context));
301301

302302
async function invoke(event: any, context?: LambdaContext) {
@@ -308,7 +308,10 @@ export function createLambdaHandler(backendFactory: () => Promise<any>) {
308308
// Resetting initPromise lets the next invocation re-run initialize() (config.ts re-fetches,
309309
// since it doesn't cache failures), so the handler self-heals once config is available.
310310
if (!initPromise) {
311-
initPromise = initialize().catch((err) => {
311+
// Run init outside this invocation's request-id scope: the backend import and the
312+
// Building Block constructors create long-lived state (timers, pool listeners) that
313+
// must not keep the first request's id for the life of the container.
314+
initPromise = requestIdStore.exit(() => initialize()).catch((err) => {
312315
initPromise = null;
313316
throw err;
314317
});

‎packages/core/src/request-context.ts‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,18 +38,27 @@ export const requestClientUserAgent = new AsyncLocalStorage<string | undefined>(
3838
* the store the handler populated.
3939
*/
4040
const REQUEST_ID_STORE_KEY = '__BLOCKS_REQUEST_ID_STORE__';
41-
const globalStores = globalThis as unknown as Record<string, AsyncLocalStorage<string | undefined> | undefined>;
42-
export const requestIdStore: AsyncLocalStorage<string | undefined> =
43-
globalStores[REQUEST_ID_STORE_KEY] ?? new AsyncLocalStorage<string | undefined>();
41+
const globalStores = globalThis as unknown as Record<string, unknown>;
42+
const isStore = (value: unknown): value is AsyncLocalStorage<string | undefined> =>
43+
typeof (value as { getStore?: unknown } | undefined)?.getStore === 'function' &&
44+
typeof (value as { run?: unknown } | undefined)?.run === 'function';
45+
const existingRequestIdStore = globalStores[REQUEST_ID_STORE_KEY];
46+
// Reuse the store another copy of core registered; anything else at the key is replaced.
47+
export const requestIdStore: AsyncLocalStorage<string | undefined> = isStore(existingRequestIdStore)
48+
? existingRequestIdStore
49+
: new AsyncLocalStorage<string | undefined>();
4450
globalStores[REQUEST_ID_STORE_KEY] = requestIdStore;
4551

4652
/**
4753
* The id of the request being handled, or `undefined` outside one. On AWS
4854
* Lambda this is the invocation's `awsRequestId` (the id in the function's
4955
* `START`/`END`/`REPORT` log lines). The local dev server sets none.
56+
*
57+
* Exported for Building Block authors from `@aws-blocks/core/bb-utils`.
5058
*/
5159
export function currentRequestId(): string | undefined {
52-
return requestIdStore.getStore();
60+
const id = requestIdStore.getStore();
61+
return typeof id === 'string' && id.length > 0 ? id : undefined;
5362
}
5463

5564
/**

0 commit comments

Comments
 (0)