autotel 4.1.0 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/package.json +1 -2
  2. package/src/attribute-redacting-processor.test.ts +0 -763
  3. package/src/attribute-redacting-processor.ts +0 -621
  4. package/src/attributes/attachers.ts +0 -161
  5. package/src/attributes/builders.ts +0 -529
  6. package/src/attributes/domains.ts +0 -42
  7. package/src/attributes/index.ts +0 -81
  8. package/src/attributes/registry.ts +0 -323
  9. package/src/attributes/types.ts +0 -211
  10. package/src/attributes/utils.ts +0 -64
  11. package/src/attributes/validators.ts +0 -266
  12. package/src/attributes.test.ts +0 -292
  13. package/src/auto.ts +0 -67
  14. package/src/autotel-logger.test.ts +0 -548
  15. package/src/autotel-logger.ts +0 -364
  16. package/src/baggage-span-processor.test.ts +0 -202
  17. package/src/baggage-span-processor.ts +0 -100
  18. package/src/business-baggage.test.ts +0 -500
  19. package/src/business-baggage.ts +0 -669
  20. package/src/circuit-breaker.test.ts +0 -341
  21. package/src/circuit-breaker.ts +0 -184
  22. package/src/config.test.ts +0 -94
  23. package/src/config.ts +0 -172
  24. package/src/correlated-events.test.ts +0 -151
  25. package/src/correlated-events.ts +0 -47
  26. package/src/correlation-id.test.ts +0 -163
  27. package/src/correlation-id.ts +0 -206
  28. package/src/db.test.ts +0 -252
  29. package/src/db.ts +0 -447
  30. package/src/decorators.test.ts +0 -153
  31. package/src/decorators.ts +0 -188
  32. package/src/define-event.test.ts +0 -41
  33. package/src/define-event.ts +0 -58
  34. package/src/devtools.ts +0 -60
  35. package/src/drain-pipeline.test.ts +0 -68
  36. package/src/drain-pipeline.ts +0 -199
  37. package/src/drain-toolkit.test.ts +0 -113
  38. package/src/drain-toolkit.ts +0 -129
  39. package/src/enricher-toolkit.test.ts +0 -67
  40. package/src/enricher-toolkit.ts +0 -79
  41. package/src/enrichers.test.ts +0 -150
  42. package/src/enrichers.ts +0 -145
  43. package/src/env-config.test.ts +0 -323
  44. package/src/env-config.ts +0 -309
  45. package/src/error-catalog.test.ts +0 -133
  46. package/src/error-catalog.ts +0 -262
  47. package/src/event-queue.test.ts +0 -864
  48. package/src/event-queue.ts +0 -699
  49. package/src/event-subscriber.ts +0 -262
  50. package/src/event-testing.ts +0 -197
  51. package/src/event.test.ts +0 -1104
  52. package/src/event.ts +0 -988
  53. package/src/events-config.ts +0 -235
  54. package/src/exporters.ts +0 -165
  55. package/src/filtering-span-processor.test.ts +0 -281
  56. package/src/filtering-span-processor.ts +0 -111
  57. package/src/flatten-attributes.test.ts +0 -76
  58. package/src/flatten-attributes.ts +0 -80
  59. package/src/functional.strict-types.typecheck.ts +0 -53
  60. package/src/functional.test.ts +0 -1464
  61. package/src/functional.ts +0 -2539
  62. package/src/functional.types.test.ts +0 -135
  63. package/src/hook.mjs +0 -15
  64. package/src/http.test.ts +0 -485
  65. package/src/http.ts +0 -424
  66. package/src/index.ts +0 -433
  67. package/src/init-auto-redactor.test.ts +0 -53
  68. package/src/init-redactor.test.ts +0 -8
  69. package/src/init.customization.test.ts +0 -665
  70. package/src/init.integrations.test.ts +0 -399
  71. package/src/init.openllmetry.test.ts +0 -194
  72. package/src/init.protocol.test.ts +0 -215
  73. package/src/init.ts +0 -2439
  74. package/src/instrumentation.test.ts +0 -108
  75. package/src/instrumentation.ts +0 -319
  76. package/src/logger.test.ts +0 -125
  77. package/src/logger.ts +0 -341
  78. package/src/messaging-adapters.test.ts +0 -595
  79. package/src/messaging-adapters.ts +0 -583
  80. package/src/messaging-testing.test.ts +0 -573
  81. package/src/messaging-testing.ts +0 -935
  82. package/src/messaging.test.ts +0 -1646
  83. package/src/messaging.ts +0 -2245
  84. package/src/metric-helpers.ts +0 -47
  85. package/src/metric-testing.ts +0 -197
  86. package/src/metric.ts +0 -446
  87. package/src/metrics.test.ts +0 -241
  88. package/src/node-require.ts +0 -123
  89. package/src/operation-context.ts +0 -93
  90. package/src/parse-error.test.ts +0 -73
  91. package/src/parse-error.ts +0 -112
  92. package/src/posthog-logs.test.ts +0 -115
  93. package/src/posthog-logs.ts +0 -77
  94. package/src/pretty-console-exporter.test.ts +0 -545
  95. package/src/pretty-console-exporter.ts +0 -413
  96. package/src/pretty-log-formatter.test.ts +0 -123
  97. package/src/pretty-log-formatter.ts +0 -210
  98. package/src/processors/canonical-log-line-processor.test.ts +0 -523
  99. package/src/processors/canonical-log-line-processor.ts +0 -396
  100. package/src/processors.ts +0 -152
  101. package/src/rate-limiter.test.ts +0 -199
  102. package/src/rate-limiter.ts +0 -98
  103. package/src/redact-values.test.ts +0 -90
  104. package/src/redact-values.ts +0 -34
  105. package/src/register.ts +0 -37
  106. package/src/request-logger.test.ts +0 -545
  107. package/src/request-logger.ts +0 -342
  108. package/src/sampling.test.ts +0 -1060
  109. package/src/sampling.ts +0 -737
  110. package/src/security-schema.test.ts +0 -45
  111. package/src/security-schema.ts +0 -107
  112. package/src/semantic-conventions.ts +0 -15
  113. package/src/semantic-helpers.test.ts +0 -226
  114. package/src/semantic-helpers.ts +0 -438
  115. package/src/shutdown.test.ts +0 -364
  116. package/src/shutdown.ts +0 -246
  117. package/src/span-name-normalizer.test.ts +0 -377
  118. package/src/span-name-normalizer.ts +0 -213
  119. package/src/stable-hash.ts +0 -27
  120. package/src/structured-error.test.ts +0 -191
  121. package/src/structured-error.ts +0 -157
  122. package/src/stub.integration.test.ts +0 -361
  123. package/src/tail-sampling-processor.test.ts +0 -230
  124. package/src/tail-sampling-processor.ts +0 -55
  125. package/src/test-span-collector.test.ts +0 -234
  126. package/src/test-span-collector.ts +0 -150
  127. package/src/testing.ts +0 -705
  128. package/src/trace-context.test.ts +0 -73
  129. package/src/trace-context.ts +0 -567
  130. package/src/trace-helpers.new.test.ts +0 -278
  131. package/src/trace-helpers.test.ts +0 -290
  132. package/src/trace-helpers.ts +0 -710
  133. package/src/trace-hybrid.test.ts +0 -42
  134. package/src/trace-hybrid.ts +0 -37
  135. package/src/tracer-provider.test.ts +0 -183
  136. package/src/tracer-provider.ts +0 -266
  137. package/src/track.test.ts +0 -154
  138. package/src/track.ts +0 -216
  139. package/src/validate.test.ts +0 -287
  140. package/src/validate.ts +0 -307
  141. package/src/validation-attributes.ts +0 -43
  142. package/src/validation.test.ts +0 -330
  143. package/src/validation.ts +0 -246
  144. package/src/variable-name-inference.test.ts +0 -178
  145. package/src/variable-name-inference.ts +0 -242
  146. package/src/webhook.test.ts +0 -649
  147. package/src/webhook.ts +0 -637
  148. package/src/workflow-distributed.test.ts +0 -786
  149. package/src/workflow-distributed.ts +0 -916
  150. package/src/workflow.async-safety.integration.test.ts +0 -345
  151. package/src/workflow.test.ts +0 -647
  152. package/src/workflow.ts +0 -810
  153. package/src/yaml-config.test.ts +0 -373
  154. package/src/yaml-config.ts +0 -351
@@ -1,545 +0,0 @@
1
- import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
2
- import { trace as otelTrace } from '@opentelemetry/api';
3
- import {
4
- createNoopRequestLogger,
5
- getRequestLogger,
6
- getRequestLoggerSafe,
7
- hasRequestContext,
8
- runWithRequestContext,
9
- } from './request-logger';
10
- import type { TraceContext } from './trace-context';
11
-
12
- function createMockContext(): TraceContext {
13
- return {
14
- traceId: 'trace-id',
15
- spanId: 'span-id',
16
- correlationId: 'corr-id',
17
- setAttribute: vi.fn(),
18
- setAttributes: vi.fn(),
19
- setStatus: vi.fn(),
20
- recordException: vi.fn(),
21
- addEvent: vi.fn(),
22
- addLink: vi.fn(),
23
- addLinks: vi.fn(),
24
- updateName: vi.fn(),
25
- isRecording: vi.fn(() => true),
26
- getBaggage: vi.fn(),
27
- setBaggage: vi.fn(),
28
- deleteBaggage: vi.fn(),
29
- getAllBaggage: vi.fn(() => new Map()),
30
- } as unknown as TraceContext;
31
- }
32
-
33
- afterEach(() => {
34
- vi.restoreAllMocks();
35
- });
36
-
37
- describe('post-emit warnings', () => {
38
- let ctx: TraceContext;
39
- let log: ReturnType<typeof getRequestLogger>;
40
- let warnSpy: ReturnType<typeof vi.spyOn>;
41
-
42
- beforeEach(() => {
43
- ctx = createMockContext();
44
- log = getRequestLogger(ctx);
45
- warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
46
- });
47
-
48
- afterEach(() => {
49
- warnSpy.mockRestore();
50
- });
51
-
52
- it('warns when set() is called after emitNow()', () => {
53
- log.emitNow();
54
- log.set({ dropped: 'value' });
55
-
56
- expect(warnSpy).toHaveBeenCalledWith(
57
- expect.stringContaining(
58
- '[autotel] log.set() called after the wide event was emitted',
59
- ),
60
- );
61
- expect(warnSpy).toHaveBeenCalledWith(
62
- expect.stringContaining('Keys dropped: dropped'),
63
- );
64
- });
65
-
66
- it('warns when info() is called after emitNow()', () => {
67
- log.emitNow();
68
- log.info('after emit', { extra: 'data' });
69
-
70
- expect(warnSpy).toHaveBeenCalledWith(
71
- expect.stringContaining(
72
- '[autotel] log.info() called after the wide event was emitted',
73
- ),
74
- );
75
- expect(warnSpy).toHaveBeenCalledWith(
76
- expect.stringContaining('Keys dropped: message, extra'),
77
- );
78
- });
79
-
80
- it('warns when warn() is called after emitNow()', () => {
81
- log.emitNow();
82
- log.warn('after emit', { extra: 'data' });
83
-
84
- expect(warnSpy).toHaveBeenCalledWith(
85
- expect.stringContaining(
86
- '[autotel] log.warn() called after the wide event was emitted',
87
- ),
88
- );
89
- });
90
-
91
- it('warns when error() is called after emitNow()', () => {
92
- log.emitNow();
93
- log.error(new Error('after emit'), { step: 'cleanup' });
94
-
95
- expect(warnSpy).toHaveBeenCalledWith(
96
- expect.stringContaining(
97
- '[autotel] log.error() called after the wide event was emitted',
98
- ),
99
- );
100
- expect(warnSpy).toHaveBeenCalledWith(
101
- expect.stringContaining('Keys dropped: step, error'),
102
- );
103
- });
104
-
105
- it('warns on duplicate emitNow()', () => {
106
- const first = log.emitNow();
107
- const second = log.emitNow();
108
-
109
- expect(warnSpy).toHaveBeenCalledWith(
110
- expect.stringContaining(
111
- '[autotel] log.emitNow() called after the wide event was emitted',
112
- ),
113
- );
114
- expect(warnSpy).toHaveBeenCalledWith(
115
- expect.stringContaining('Ignoring duplicate emit'),
116
- );
117
- expect(second).toBe(first);
118
- });
119
-
120
- it('does not warn when calls are made before emitNow()', () => {
121
- log.set({ user: { id: 'u1' } });
122
- log.info('step', { stage: 'payment' });
123
- log.warn('slow');
124
- log.error(new Error('fail'));
125
- log.emitNow();
126
-
127
- expect(warnSpy).not.toHaveBeenCalled();
128
- });
129
- });
130
-
131
- describe('array concatenation in set()', () => {
132
- let ctx: TraceContext;
133
- let log: ReturnType<typeof getRequestLogger>;
134
-
135
- beforeEach(() => {
136
- ctx = createMockContext();
137
- log = getRequestLogger(ctx);
138
- });
139
-
140
- it('concatenates arrays when both values are arrays', () => {
141
- log.set({ tags: ['initial', 'setup'] });
142
- log.set({ tags: ['payment', 'complete'] });
143
-
144
- expect(log.getContext()).toEqual({
145
- tags: ['initial', 'setup', 'payment', 'complete'],
146
- });
147
- });
148
-
149
- it('replaces array with non-array value', () => {
150
- log.set({ tags: ['a', 'b'] });
151
- log.set({ tags: 'single' });
152
-
153
- expect(log.getContext()).toEqual({
154
- tags: 'single',
155
- });
156
- });
157
-
158
- it('replaces non-array with array', () => {
159
- log.set({ tags: 'single' });
160
- log.set({ tags: ['a', 'b'] });
161
-
162
- expect(log.getContext()).toEqual({
163
- tags: ['a', 'b'],
164
- });
165
- });
166
-
167
- it('deep merges objects while concatenating nested arrays', () => {
168
- log.set({
169
- user: { id: 'u1', roles: ['admin'] },
170
- });
171
- log.set({
172
- user: { name: 'Alice', roles: ['editor'] },
173
- });
174
-
175
- expect(log.getContext()).toEqual({
176
- user: {
177
- id: 'u1',
178
- name: 'Alice',
179
- roles: ['admin', 'editor'],
180
- },
181
- });
182
- });
183
- });
184
-
185
- describe('log.fork()', () => {
186
- let ctx: TraceContext;
187
- let log: ReturnType<typeof getRequestLogger>;
188
-
189
- beforeEach(() => {
190
- ctx = createMockContext();
191
- log = getRequestLogger(ctx);
192
- });
193
-
194
- it('throws when parent has no correlationId', () => {
195
- const noCorrCtx = createMockContext();
196
- (noCorrCtx as Record<string, unknown>).correlationId = '';
197
- const noCorrLog = getRequestLogger(noCorrCtx);
198
-
199
- expect(() => noCorrLog.fork('test', () => {})).toThrow(
200
- '[autotel] log.fork() requires the parent logger to have a correlationId',
201
- );
202
- });
203
-
204
- it('fork method exists on the logger interface', () => {
205
- expect(typeof log.fork).toBe('function');
206
- });
207
-
208
- it('uses an isolated child span context for forked work', async () => {
209
- const childSpan = {
210
- spanContext: () => ({
211
- traceId: 'a'.repeat(32),
212
- spanId: 'b'.repeat(16),
213
- }),
214
- setAttribute: vi.fn(),
215
- setAttributes: vi.fn(),
216
- setStatus: vi.fn(),
217
- recordException: vi.fn(),
218
- addEvent: vi.fn(),
219
- addLink: vi.fn(),
220
- addLinks: vi.fn(),
221
- updateName: vi.fn(),
222
- isRecording: vi.fn(() => true),
223
- end: vi.fn(),
224
- };
225
-
226
- const tracer = {
227
- startActiveSpan: (
228
- _name: string,
229
- cb: (span: typeof childSpan) => void,
230
- ) => {
231
- cb(childSpan);
232
- },
233
- };
234
-
235
- const tracerSpy = vi
236
- .spyOn(otelTrace, 'getTracer')
237
- .mockReturnValue(
238
- tracer as unknown as ReturnType<typeof otelTrace.getTracer>,
239
- );
240
-
241
- log.fork('background-work', async () => {
242
- const childLog = getRequestLogger();
243
- childLog.info('running child task', { phase: 'upload' });
244
- });
245
-
246
- await new Promise((resolve) => setImmediate(resolve));
247
- await new Promise((resolve) => setImmediate(resolve));
248
-
249
- expect(tracerSpy).toHaveBeenCalledWith('autotel.request-logger');
250
- expect(childSpan.setAttributes).toHaveBeenCalledWith(
251
- expect.objectContaining({
252
- operation: 'background-work',
253
- _parentCorrelationId: 'corr-id',
254
- }),
255
- );
256
- expect(childSpan.addEvent).toHaveBeenCalledWith(
257
- 'log.emit.manual',
258
- expect.any(Object),
259
- );
260
- expect(ctx.setAttributes).not.toHaveBeenCalled();
261
- expect(childSpan.end).toHaveBeenCalledTimes(1);
262
- });
263
-
264
- it('fork lifecycle hooks fire around child handler', async () => {
265
- const ctx = createMockContext();
266
- const log = getRequestLogger(ctx);
267
- const childSpan = {
268
- spanContext: () => ({
269
- traceId: 'a'.repeat(32),
270
- spanId: 'b'.repeat(16),
271
- }),
272
- setAttribute: vi.fn(),
273
- setAttributes: vi.fn(),
274
- setStatus: vi.fn(),
275
- recordException: vi.fn(),
276
- addEvent: vi.fn(),
277
- addLink: vi.fn(),
278
- addLinks: vi.fn(),
279
- updateName: vi.fn(),
280
- isRecording: vi.fn(() => true),
281
- end: vi.fn(),
282
- };
283
-
284
- vi.spyOn(otelTrace, 'getTracer').mockReturnValue({
285
- startActiveSpan: (
286
- _name: string,
287
- cb: (span: typeof childSpan) => Promise<void>,
288
- ) => cb(childSpan),
289
- } as unknown as ReturnType<typeof otelTrace.getTracer>);
290
-
291
- const calls: string[] = [];
292
- const onChildEnter = vi.fn(() => calls.push('enter'));
293
- const onChildExit = vi.fn(() => calls.push('exit'));
294
-
295
- log.fork(
296
- 'bg',
297
- async () => {
298
- calls.push('handler');
299
- },
300
- { lifecycle: { onChildEnter, onChildExit } },
301
- );
302
-
303
- await new Promise((resolve) => setImmediate(resolve));
304
- await new Promise((resolve) => setImmediate(resolve));
305
-
306
- expect(onChildEnter).toHaveBeenCalledTimes(1);
307
- expect(onChildExit).toHaveBeenCalledTimes(1);
308
- expect(calls).toEqual(['enter', 'handler', 'exit']);
309
- });
310
-
311
- it('fork onChildExit hook errors do not crash fork cleanup', async () => {
312
- const ctx = createMockContext();
313
- const log = getRequestLogger(ctx);
314
- const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
315
- const childSpan = {
316
- spanContext: () => ({
317
- traceId: 'a'.repeat(32),
318
- spanId: 'b'.repeat(16),
319
- }),
320
- setAttribute: vi.fn(),
321
- setAttributes: vi.fn(),
322
- setStatus: vi.fn(),
323
- recordException: vi.fn(),
324
- addEvent: vi.fn(),
325
- addLink: vi.fn(),
326
- addLinks: vi.fn(),
327
- updateName: vi.fn(),
328
- isRecording: vi.fn(() => true),
329
- end: vi.fn(),
330
- };
331
-
332
- vi.spyOn(otelTrace, 'getTracer').mockReturnValue({
333
- startActiveSpan: (
334
- _name: string,
335
- cb: (span: typeof childSpan) => Promise<void>,
336
- ) => cb(childSpan),
337
- } as unknown as ReturnType<typeof otelTrace.getTracer>);
338
-
339
- log.fork('bg', async () => {}, {
340
- lifecycle: {
341
- onChildExit: () => {
342
- throw new Error('hook exploded');
343
- },
344
- },
345
- });
346
-
347
- await new Promise((resolve) => setImmediate(resolve));
348
- await new Promise((resolve) => setImmediate(resolve));
349
-
350
- expect(childSpan.end).toHaveBeenCalledTimes(1);
351
- expect(consoleSpy).toHaveBeenCalled();
352
- consoleSpy.mockRestore();
353
- });
354
- });
355
-
356
- describe('getRequestLogger', () => {
357
- it('sets flattened fields onto active span context', () => {
358
- const ctx = createMockContext();
359
- const log = getRequestLogger(ctx);
360
-
361
- log.set({
362
- user: { id: 'u1', plan: 'pro' },
363
- attempts: 3,
364
- success: true,
365
- });
366
-
367
- expect(ctx.setAttributes).toHaveBeenCalledWith({
368
- 'user.id': 'u1',
369
- 'user.plan': 'pro',
370
- attempts: 3,
371
- success: true,
372
- });
373
- });
374
-
375
- it('adds warning events and sets warning level marker', () => {
376
- const ctx = createMockContext();
377
- const log = getRequestLogger(ctx);
378
-
379
- log.warn('slow request', {
380
- http: { route: '/checkout' },
381
- duration_ms: 1350,
382
- });
383
-
384
- expect(ctx.addEvent).toHaveBeenCalledWith('log.warn', {
385
- message: 'slow request',
386
- 'http.route': '/checkout',
387
- duration_ms: 1350,
388
- });
389
- expect(ctx.setAttribute).toHaveBeenCalledWith('autotel.log.level', 'warn');
390
- });
391
-
392
- it('records and annotates errors with structured diagnostics', () => {
393
- const ctx = createMockContext();
394
- const log = getRequestLogger(ctx);
395
-
396
- log.error(new Error('payment processor unavailable'), {
397
- step: 'payment',
398
- });
399
-
400
- expect(ctx.recordException).toHaveBeenCalled();
401
- expect(ctx.addEvent).toHaveBeenCalledWith('log.error', {
402
- message: 'payment processor unavailable',
403
- step: 'payment',
404
- });
405
- expect(ctx.setAttributes).toHaveBeenCalledWith(
406
- expect.objectContaining({
407
- 'error.message': 'payment processor unavailable',
408
- }),
409
- );
410
- });
411
-
412
- it('returns accumulated context via getContext()', () => {
413
- const ctx = createMockContext();
414
- const log = getRequestLogger(ctx);
415
-
416
- log.set({ user: { id: 'u1' } });
417
- log.info('step', { checkout: { step: 'payment' } });
418
-
419
- expect(log.getContext()).toEqual({
420
- user: { id: 'u1' },
421
- checkout: { step: 'payment' },
422
- });
423
- });
424
-
425
- it('emitNow records manual event and returns snapshot', async () => {
426
- const ctx = createMockContext();
427
- const onEmit = vi.fn(async () => {});
428
- const log = getRequestLogger(ctx, { onEmit });
429
-
430
- log.set({ user: { id: 'u1' } });
431
- const snapshot = log.emitNow({ stage: 'preflight' });
432
-
433
- expect(snapshot).toMatchObject({
434
- traceId: 'trace-id',
435
- spanId: 'span-id',
436
- correlationId: 'corr-id',
437
- context: {
438
- user: { id: 'u1' },
439
- stage: 'preflight',
440
- },
441
- timestamp: expect.any(String),
442
- });
443
- expect(ctx.addEvent).toHaveBeenCalledWith(
444
- 'log.emit.manual',
445
- expect.objectContaining({
446
- 'user.id': 'u1',
447
- stage: 'preflight',
448
- }),
449
- );
450
-
451
- await new Promise((resolve) => setImmediate(resolve));
452
- expect(onEmit).toHaveBeenCalledWith(snapshot);
453
- });
454
-
455
- it('resolves context from AsyncLocalStorage when no args given', () => {
456
- const ctx = createMockContext();
457
-
458
- runWithRequestContext(ctx, () => {
459
- const log = getRequestLogger();
460
- log.set({ user: { id: 'als-user' } });
461
-
462
- expect(ctx.setAttributes).toHaveBeenCalledWith({
463
- 'user.id': 'als-user',
464
- });
465
- });
466
- });
467
-
468
- it('resolves context from the active OTel span when no args and no ALS context', () => {
469
- const activeSpan = {
470
- spanContext: () => ({
471
- traceId: 'c'.repeat(32),
472
- spanId: 'd'.repeat(16),
473
- }),
474
- setAttribute: vi.fn(),
475
- setAttributes: vi.fn(),
476
- setStatus: vi.fn(),
477
- recordException: vi.fn(),
478
- addEvent: vi.fn(),
479
- addLink: vi.fn(),
480
- addLinks: vi.fn(),
481
- updateName: vi.fn(),
482
- isRecording: vi.fn(() => true),
483
- };
484
-
485
- const spanSpy = vi
486
- .spyOn(otelTrace, 'getActiveSpan')
487
- .mockReturnValue(
488
- activeSpan as unknown as ReturnType<typeof otelTrace.getActiveSpan>,
489
- );
490
-
491
- const log = getRequestLogger();
492
- log.set({ order: { id: 'o-1' } });
493
-
494
- expect(spanSpy).toHaveBeenCalled();
495
- expect(activeSpan.setAttributes).toHaveBeenCalledWith({
496
- 'order.id': 'o-1',
497
- });
498
- });
499
- });
500
-
501
- describe('best-effort helpers', () => {
502
- it('hasRequestContext is false with no ctx, ALS, or active span', () => {
503
- vi.spyOn(otelTrace, 'getActiveSpan').mockReturnValue(undefined);
504
- expect(hasRequestContext()).toBe(false);
505
- });
506
-
507
- it('hasRequestContext is true when an explicit ctx is passed', () => {
508
- vi.spyOn(otelTrace, 'getActiveSpan').mockReturnValue(undefined);
509
- expect(hasRequestContext(createMockContext())).toBe(true);
510
- });
511
-
512
- it('hasRequestContext is true inside runWithRequestContext', () => {
513
- vi.spyOn(otelTrace, 'getActiveSpan').mockReturnValue(undefined);
514
- runWithRequestContext(createMockContext(), () => {
515
- expect(hasRequestContext()).toBe(true);
516
- });
517
- });
518
-
519
- it('getRequestLoggerSafe returns null when no context is available', () => {
520
- vi.spyOn(otelTrace, 'getActiveSpan').mockReturnValue(undefined);
521
- expect(getRequestLoggerSafe()).toBeNull();
522
- });
523
-
524
- it('getRequestLoggerSafe returns a working logger when ctx is provided', () => {
525
- const ctx = createMockContext();
526
- const log = getRequestLoggerSafe(ctx);
527
- expect(log).not.toBeNull();
528
- log?.set({ user: { id: 'safe-user' } });
529
- expect(ctx.setAttributes).toHaveBeenCalledWith({ 'user.id': 'safe-user' });
530
- });
531
-
532
- it('createNoopRequestLogger never throws and emits an empty snapshot', () => {
533
- const log = createNoopRequestLogger();
534
- expect(() => {
535
- log.set({ a: 1 });
536
- log.info('hi', { b: 2 });
537
- log.warn('careful');
538
- log.error(new Error('boom'));
539
- }).not.toThrow();
540
- expect(log.getContext()).toEqual({});
541
- const snapshot = log.emitNow();
542
- expect(snapshot.traceId).toBe('');
543
- expect(snapshot.context).toEqual({});
544
- });
545
- });