|
9 | 9 | import { test } from 'node:test'; |
10 | 10 | import assert from 'node:assert'; |
11 | 11 | import { AsyncLocalStorage } from 'node:async_hooks'; |
12 | | -import { buildEntry } from './serializer.js'; |
| 12 | +import { buildEntry, safeStringify } from './serializer.js'; |
13 | 13 |
|
| 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. |
14 | 16 | 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; |
18 | 20 |
|
19 | 21 | const parse = (line: string) => JSON.parse(line) as Record<string, unknown>; |
20 | 22 |
|
@@ -47,3 +49,19 @@ test('the structural fields keep their order, with requestId after logger', () = |
47 | 49 | const entry = store.run('req-1', () => parse(buildEntry('warn', 'm', 'app', [{ k: 1 }]))); |
48 | 50 | assert.deepStrictEqual(Object.keys(entry).slice(0, 5), ['level', 'message', 'timestamp', 'logger', 'requestId']); |
49 | 51 | }); |
| 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 | +}); |
0 commit comments