autotel 2.26.0 → 2.26.1
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.
- package/dist/attribute-redacting-processor.cjs +14 -6
- package/dist/attribute-redacting-processor.d.cts +63 -1
- package/dist/attribute-redacting-processor.d.ts +63 -1
- package/dist/attribute-redacting-processor.js +1 -1
- package/dist/attributes.cjs +21 -21
- package/dist/attributes.js +2 -2
- package/dist/auto.cjs +8 -8
- package/dist/auto.js +6 -6
- package/dist/{chunk-RUD7KS4R.js → chunk-3SDILILG.js} +3 -3
- package/dist/{chunk-RUD7KS4R.js.map → chunk-3SDILILG.js.map} +1 -1
- package/dist/{chunk-B33XPEKY.js → chunk-55ER2KD5.js} +4 -4
- package/dist/chunk-55ER2KD5.js.map +1 -0
- package/dist/{chunk-UJJPTSEI.cjs → chunk-563EL6O6.cjs} +81 -14
- package/dist/chunk-563EL6O6.cjs.map +1 -0
- package/dist/{chunk-TS7IHIRW.cjs → chunk-6YGUN7IY.cjs} +5 -5
- package/dist/{chunk-TS7IHIRW.cjs.map → chunk-6YGUN7IY.cjs.map} +1 -1
- package/dist/{chunk-XDKK53OL.js → chunk-A4E5AQFK.js} +3 -3
- package/dist/{chunk-XDKK53OL.js.map → chunk-A4E5AQFK.js.map} +1 -1
- package/dist/{chunk-WAB4CHBU.js → chunk-BJ2XPN77.js} +3 -3
- package/dist/{chunk-WAB4CHBU.js.map → chunk-BJ2XPN77.js.map} +1 -1
- package/dist/{chunk-KZEC4CHV.cjs → chunk-CEAQK2QY.cjs} +5 -5
- package/dist/{chunk-KZEC4CHV.cjs.map → chunk-CEAQK2QY.cjs.map} +1 -1
- package/dist/chunk-CMNGGTQL.cjs +349 -0
- package/dist/chunk-CMNGGTQL.cjs.map +1 -0
- package/dist/{chunk-VYA6QDNA.js → chunk-DPSA4QLA.js} +4 -2
- package/dist/chunk-DPSA4QLA.js.map +1 -0
- package/dist/{chunk-M4US3P4K.js → chunk-ER43K7ES.js} +3 -3
- package/dist/{chunk-M4US3P4K.js.map → chunk-ER43K7ES.js.map} +1 -1
- package/dist/{chunk-AZ24DJAG.cjs → chunk-FU6R566Y.cjs} +4 -4
- package/dist/chunk-FU6R566Y.cjs.map +1 -0
- package/dist/{chunk-4PTCDOZY.js → chunk-HPUGKUMZ.js} +4 -4
- package/dist/{chunk-4PTCDOZY.js.map → chunk-HPUGKUMZ.js.map} +1 -1
- package/dist/{chunk-XRBP4RYL.cjs → chunk-JKIMEPI2.cjs} +4 -4
- package/dist/{chunk-XRBP4RYL.cjs.map → chunk-JKIMEPI2.cjs.map} +1 -1
- package/dist/{chunk-N344PVE5.cjs → chunk-OBWXM4NN.cjs} +9 -9
- package/dist/{chunk-N344PVE5.cjs.map → chunk-OBWXM4NN.cjs.map} +1 -1
- package/dist/{chunk-OFPZULMQ.cjs → chunk-OC6X2VIN.cjs} +8 -8
- package/dist/{chunk-OFPZULMQ.cjs.map → chunk-OC6X2VIN.cjs.map} +1 -1
- package/dist/{chunk-GTD3NXOS.js → chunk-QC5MNKVF.js} +4 -4
- package/dist/{chunk-GTD3NXOS.js.map → chunk-QC5MNKVF.js.map} +1 -1
- package/dist/chunk-TDNKIHKT.js +341 -0
- package/dist/chunk-TDNKIHKT.js.map +1 -0
- package/dist/{chunk-DGPUZ6TE.js → chunk-U54FTVFH.js} +3 -3
- package/dist/{chunk-DGPUZ6TE.js.map → chunk-U54FTVFH.js.map} +1 -1
- package/dist/{chunk-ZJ5GXCOT.cjs → chunk-UTZR7P7E.cjs} +36 -36
- package/dist/{chunk-ZJ5GXCOT.cjs.map → chunk-UTZR7P7E.cjs.map} +1 -1
- package/dist/{chunk-7FIGORWI.cjs → chunk-VH77IPJN.cjs} +4 -2
- package/dist/chunk-VH77IPJN.cjs.map +1 -0
- package/dist/{chunk-EXOXDI5A.js → chunk-W35FVJBC.js} +73 -8
- package/dist/chunk-W35FVJBC.js.map +1 -0
- package/dist/{chunk-II7GFVAF.cjs → chunk-WZOKY3PW.cjs} +13 -13
- package/dist/{chunk-II7GFVAF.cjs.map → chunk-WZOKY3PW.cjs.map} +1 -1
- package/dist/{chunk-CMADDTHY.cjs → chunk-YEVCD6DR.cjs} +7 -7
- package/dist/{chunk-CMADDTHY.cjs.map → chunk-YEVCD6DR.cjs.map} +1 -1
- package/dist/{chunk-RXFZKLRQ.js → chunk-YN7USLHW.js} +3 -3
- package/dist/{chunk-RXFZKLRQ.js.map → chunk-YN7USLHW.js.map} +1 -1
- package/dist/decorators.cjs +7 -7
- package/dist/decorators.js +7 -7
- package/dist/event.cjs +10 -10
- package/dist/event.js +7 -7
- package/dist/functional.cjs +14 -14
- package/dist/functional.js +7 -7
- package/dist/index.cjs +214 -97
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +8 -2
- package/dist/index.d.ts +8 -2
- package/dist/index.js +141 -33
- package/dist/index.js.map +1 -1
- package/dist/{init-QSj7X6zU.d.cts → init-CMuTaFAV.d.cts} +26 -1
- package/dist/{init-FiR_glVc.d.ts → init-D6JfWEjL.d.ts} +26 -1
- package/dist/instrumentation.cjs +14 -14
- package/dist/instrumentation.js +6 -6
- package/dist/logger.cjs +8 -8
- package/dist/logger.js +1 -1
- package/dist/messaging.cjs +11 -11
- package/dist/messaging.js +8 -8
- package/dist/metric.cjs +1 -1
- package/dist/metric.js +1 -1
- package/dist/sampling.cjs +15 -15
- package/dist/sampling.js +2 -2
- package/dist/semantic-helpers.cjs +12 -12
- package/dist/semantic-helpers.js +8 -8
- package/dist/tail-sampling-processor.cjs +4 -4
- package/dist/tail-sampling-processor.js +3 -3
- package/dist/testing.cjs +1 -1
- package/dist/testing.js +1 -1
- package/dist/webhook.cjs +9 -8
- package/dist/webhook.cjs.map +1 -1
- package/dist/webhook.js +8 -7
- package/dist/webhook.js.map +1 -1
- package/dist/workflow-distributed.cjs +9 -9
- package/dist/workflow-distributed.js +7 -7
- package/dist/workflow.cjs +12 -12
- package/dist/workflow.js +8 -8
- package/dist/yaml-config.cjs +6 -6
- package/dist/yaml-config.d.cts +1 -1
- package/dist/yaml-config.d.ts +1 -1
- package/dist/yaml-config.js +3 -3
- package/package.json +1 -1
- package/src/attribute-redacting-processor.test.ts +81 -16
- package/src/attribute-redacting-processor.ts +278 -24
- package/src/autotel-logger.ts +2 -2
- package/src/index.ts +2 -1
- package/src/init.ts +117 -2
- package/src/request-logger.test.ts +266 -1
- package/src/request-logger.ts +115 -16
- package/src/structured-error.ts +54 -1
- package/dist/chunk-7FIGORWI.cjs.map +0 -1
- package/dist/chunk-AZ24DJAG.cjs.map +0 -1
- package/dist/chunk-B33XPEKY.js.map +0 -1
- package/dist/chunk-ELW34S4C.cjs +0 -173
- package/dist/chunk-ELW34S4C.cjs.map +0 -1
- package/dist/chunk-EXOXDI5A.js.map +0 -1
- package/dist/chunk-SNINLBEE.js +0 -167
- package/dist/chunk-SNINLBEE.js.map +0 -1
- package/dist/chunk-UJJPTSEI.cjs.map +0 -1
- package/dist/chunk-VYA6QDNA.js.map +0 -1
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { describe, expect, it, vi } from 'vitest';
|
|
1
|
+
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
|
|
2
|
+
import { trace as otelTrace } from '@opentelemetry/api';
|
|
2
3
|
import { getRequestLogger, runWithRequestContext } from './request-logger';
|
|
3
4
|
import type { TraceContext } from './trace-context';
|
|
4
5
|
|
|
@@ -23,6 +24,238 @@ function createMockContext(): TraceContext {
|
|
|
23
24
|
} as unknown as TraceContext;
|
|
24
25
|
}
|
|
25
26
|
|
|
27
|
+
afterEach(() => {
|
|
28
|
+
vi.restoreAllMocks();
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
describe('post-emit warnings', () => {
|
|
32
|
+
let ctx: TraceContext;
|
|
33
|
+
let log: ReturnType<typeof getRequestLogger>;
|
|
34
|
+
let warnSpy: ReturnType<typeof vi.spyOn>;
|
|
35
|
+
|
|
36
|
+
beforeEach(() => {
|
|
37
|
+
ctx = createMockContext();
|
|
38
|
+
log = getRequestLogger(ctx);
|
|
39
|
+
warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
afterEach(() => {
|
|
43
|
+
warnSpy.mockRestore();
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('warns when set() is called after emitNow()', () => {
|
|
47
|
+
log.emitNow();
|
|
48
|
+
log.set({ dropped: 'value' });
|
|
49
|
+
|
|
50
|
+
expect(warnSpy).toHaveBeenCalledWith(
|
|
51
|
+
expect.stringContaining(
|
|
52
|
+
'[autotel] log.set() called after the wide event was emitted',
|
|
53
|
+
),
|
|
54
|
+
);
|
|
55
|
+
expect(warnSpy).toHaveBeenCalledWith(
|
|
56
|
+
expect.stringContaining('Keys dropped: dropped'),
|
|
57
|
+
);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it('warns when info() is called after emitNow()', () => {
|
|
61
|
+
log.emitNow();
|
|
62
|
+
log.info('after emit', { extra: 'data' });
|
|
63
|
+
|
|
64
|
+
expect(warnSpy).toHaveBeenCalledWith(
|
|
65
|
+
expect.stringContaining(
|
|
66
|
+
'[autotel] log.info() called after the wide event was emitted',
|
|
67
|
+
),
|
|
68
|
+
);
|
|
69
|
+
expect(warnSpy).toHaveBeenCalledWith(
|
|
70
|
+
expect.stringContaining('Keys dropped: message, extra'),
|
|
71
|
+
);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it('warns when warn() is called after emitNow()', () => {
|
|
75
|
+
log.emitNow();
|
|
76
|
+
log.warn('after emit', { extra: 'data' });
|
|
77
|
+
|
|
78
|
+
expect(warnSpy).toHaveBeenCalledWith(
|
|
79
|
+
expect.stringContaining(
|
|
80
|
+
'[autotel] log.warn() called after the wide event was emitted',
|
|
81
|
+
),
|
|
82
|
+
);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it('warns when error() is called after emitNow()', () => {
|
|
86
|
+
log.emitNow();
|
|
87
|
+
log.error(new Error('after emit'), { step: 'cleanup' });
|
|
88
|
+
|
|
89
|
+
expect(warnSpy).toHaveBeenCalledWith(
|
|
90
|
+
expect.stringContaining(
|
|
91
|
+
'[autotel] log.error() called after the wide event was emitted',
|
|
92
|
+
),
|
|
93
|
+
);
|
|
94
|
+
expect(warnSpy).toHaveBeenCalledWith(
|
|
95
|
+
expect.stringContaining('Keys dropped: step, error'),
|
|
96
|
+
);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it('warns on duplicate emitNow()', () => {
|
|
100
|
+
const first = log.emitNow();
|
|
101
|
+
const second = log.emitNow();
|
|
102
|
+
|
|
103
|
+
expect(warnSpy).toHaveBeenCalledWith(
|
|
104
|
+
expect.stringContaining(
|
|
105
|
+
'[autotel] log.emitNow() called after the wide event was emitted',
|
|
106
|
+
),
|
|
107
|
+
);
|
|
108
|
+
expect(warnSpy).toHaveBeenCalledWith(
|
|
109
|
+
expect.stringContaining('Ignoring duplicate emit'),
|
|
110
|
+
);
|
|
111
|
+
expect(second).toBe(first);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it('does not warn when calls are made before emitNow()', () => {
|
|
115
|
+
log.set({ user: { id: 'u1' } });
|
|
116
|
+
log.info('step', { stage: 'payment' });
|
|
117
|
+
log.warn('slow');
|
|
118
|
+
log.error(new Error('fail'));
|
|
119
|
+
log.emitNow();
|
|
120
|
+
|
|
121
|
+
expect(warnSpy).not.toHaveBeenCalled();
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
describe('array concatenation in set()', () => {
|
|
126
|
+
let ctx: TraceContext;
|
|
127
|
+
let log: ReturnType<typeof getRequestLogger>;
|
|
128
|
+
|
|
129
|
+
beforeEach(() => {
|
|
130
|
+
ctx = createMockContext();
|
|
131
|
+
log = getRequestLogger(ctx);
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
it('concatenates arrays when both values are arrays', () => {
|
|
135
|
+
log.set({ tags: ['initial', 'setup'] });
|
|
136
|
+
log.set({ tags: ['payment', 'complete'] });
|
|
137
|
+
|
|
138
|
+
expect(log.getContext()).toEqual({
|
|
139
|
+
tags: ['initial', 'setup', 'payment', 'complete'],
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it('replaces array with non-array value', () => {
|
|
144
|
+
log.set({ tags: ['a', 'b'] });
|
|
145
|
+
log.set({ tags: 'single' });
|
|
146
|
+
|
|
147
|
+
expect(log.getContext()).toEqual({
|
|
148
|
+
tags: 'single',
|
|
149
|
+
});
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
it('replaces non-array with array', () => {
|
|
153
|
+
log.set({ tags: 'single' });
|
|
154
|
+
log.set({ tags: ['a', 'b'] });
|
|
155
|
+
|
|
156
|
+
expect(log.getContext()).toEqual({
|
|
157
|
+
tags: ['a', 'b'],
|
|
158
|
+
});
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
it('deep merges objects while concatenating nested arrays', () => {
|
|
162
|
+
log.set({
|
|
163
|
+
user: { id: 'u1', roles: ['admin'] },
|
|
164
|
+
});
|
|
165
|
+
log.set({
|
|
166
|
+
user: { name: 'Alice', roles: ['editor'] },
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
expect(log.getContext()).toEqual({
|
|
170
|
+
user: {
|
|
171
|
+
id: 'u1',
|
|
172
|
+
name: 'Alice',
|
|
173
|
+
roles: ['admin', 'editor'],
|
|
174
|
+
},
|
|
175
|
+
});
|
|
176
|
+
});
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
describe('log.fork()', () => {
|
|
180
|
+
let ctx: TraceContext;
|
|
181
|
+
let log: ReturnType<typeof getRequestLogger>;
|
|
182
|
+
|
|
183
|
+
beforeEach(() => {
|
|
184
|
+
ctx = createMockContext();
|
|
185
|
+
log = getRequestLogger(ctx);
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
it('throws when parent has no correlationId', () => {
|
|
189
|
+
const noCorrCtx = createMockContext();
|
|
190
|
+
(noCorrCtx as Record<string, unknown>).correlationId = '';
|
|
191
|
+
const noCorrLog = getRequestLogger(noCorrCtx);
|
|
192
|
+
|
|
193
|
+
expect(() => noCorrLog.fork('test', () => {})).toThrow(
|
|
194
|
+
'[autotel] log.fork() requires the parent logger to have a correlationId',
|
|
195
|
+
);
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
it('fork method exists on the logger interface', () => {
|
|
199
|
+
expect(typeof log.fork).toBe('function');
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
it('uses an isolated child span context for forked work', async () => {
|
|
203
|
+
const childSpan = {
|
|
204
|
+
spanContext: () => ({
|
|
205
|
+
traceId: 'a'.repeat(32),
|
|
206
|
+
spanId: 'b'.repeat(16),
|
|
207
|
+
}),
|
|
208
|
+
setAttribute: vi.fn(),
|
|
209
|
+
setAttributes: vi.fn(),
|
|
210
|
+
setStatus: vi.fn(),
|
|
211
|
+
recordException: vi.fn(),
|
|
212
|
+
addEvent: vi.fn(),
|
|
213
|
+
addLink: vi.fn(),
|
|
214
|
+
addLinks: vi.fn(),
|
|
215
|
+
updateName: vi.fn(),
|
|
216
|
+
isRecording: vi.fn(() => true),
|
|
217
|
+
end: vi.fn(),
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
const tracer = {
|
|
221
|
+
startActiveSpan: (
|
|
222
|
+
_name: string,
|
|
223
|
+
cb: (span: typeof childSpan) => void,
|
|
224
|
+
) => {
|
|
225
|
+
cb(childSpan);
|
|
226
|
+
},
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
const tracerSpy = vi
|
|
230
|
+
.spyOn(otelTrace, 'getTracer')
|
|
231
|
+
.mockReturnValue(
|
|
232
|
+
tracer as unknown as ReturnType<typeof otelTrace.getTracer>,
|
|
233
|
+
);
|
|
234
|
+
|
|
235
|
+
log.fork('background-work', async () => {
|
|
236
|
+
const childLog = getRequestLogger();
|
|
237
|
+
childLog.info('running child task', { phase: 'upload' });
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
241
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
242
|
+
|
|
243
|
+
expect(tracerSpy).toHaveBeenCalledWith('autotel.request-logger');
|
|
244
|
+
expect(childSpan.setAttributes).toHaveBeenCalledWith(
|
|
245
|
+
expect.objectContaining({
|
|
246
|
+
operation: 'background-work',
|
|
247
|
+
_parentCorrelationId: 'corr-id',
|
|
248
|
+
}),
|
|
249
|
+
);
|
|
250
|
+
expect(childSpan.addEvent).toHaveBeenCalledWith(
|
|
251
|
+
'log.emit.manual',
|
|
252
|
+
expect.any(Object),
|
|
253
|
+
);
|
|
254
|
+
expect(ctx.setAttributes).not.toHaveBeenCalled();
|
|
255
|
+
expect(childSpan.end).toHaveBeenCalledTimes(1);
|
|
256
|
+
});
|
|
257
|
+
});
|
|
258
|
+
|
|
26
259
|
describe('getRequestLogger', () => {
|
|
27
260
|
it('sets flattened fields onto active span context', () => {
|
|
28
261
|
const ctx = createMockContext();
|
|
@@ -134,4 +367,36 @@ describe('getRequestLogger', () => {
|
|
|
134
367
|
});
|
|
135
368
|
});
|
|
136
369
|
});
|
|
370
|
+
|
|
371
|
+
it('resolves context from the active OTel span when no args and no ALS context', () => {
|
|
372
|
+
const activeSpan = {
|
|
373
|
+
spanContext: () => ({
|
|
374
|
+
traceId: 'c'.repeat(32),
|
|
375
|
+
spanId: 'd'.repeat(16),
|
|
376
|
+
}),
|
|
377
|
+
setAttribute: vi.fn(),
|
|
378
|
+
setAttributes: vi.fn(),
|
|
379
|
+
setStatus: vi.fn(),
|
|
380
|
+
recordException: vi.fn(),
|
|
381
|
+
addEvent: vi.fn(),
|
|
382
|
+
addLink: vi.fn(),
|
|
383
|
+
addLinks: vi.fn(),
|
|
384
|
+
updateName: vi.fn(),
|
|
385
|
+
isRecording: vi.fn(() => true),
|
|
386
|
+
};
|
|
387
|
+
|
|
388
|
+
const spanSpy = vi
|
|
389
|
+
.spyOn(otelTrace, 'getActiveSpan')
|
|
390
|
+
.mockReturnValue(
|
|
391
|
+
activeSpan as unknown as ReturnType<typeof otelTrace.getActiveSpan>,
|
|
392
|
+
);
|
|
393
|
+
|
|
394
|
+
const log = getRequestLogger();
|
|
395
|
+
log.set({ order: { id: 'o-1' } });
|
|
396
|
+
|
|
397
|
+
expect(spanSpy).toHaveBeenCalled();
|
|
398
|
+
expect(activeSpan.setAttributes).toHaveBeenCalledWith({
|
|
399
|
+
'order.id': 'o-1',
|
|
400
|
+
});
|
|
401
|
+
});
|
|
137
402
|
});
|
package/src/request-logger.ts
CHANGED
|
@@ -5,6 +5,43 @@ import { createTraceContext } from './trace-context';
|
|
|
5
5
|
import { recordStructuredError } from './structured-error';
|
|
6
6
|
import { flattenToAttributes } from './flatten-attributes';
|
|
7
7
|
|
|
8
|
+
const POST_EMIT_FORK_HINT =
|
|
9
|
+
"For intentional background work tied to this request, use log.fork('label', fn) when available.";
|
|
10
|
+
|
|
11
|
+
function warnPostEmit(method: string, detail: string): void {
|
|
12
|
+
console.warn(
|
|
13
|
+
`[autotel] ${method} called after the wide event was emitted — ${detail} This data will not appear in observability. ${POST_EMIT_FORK_HINT}`,
|
|
14
|
+
);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function mergeInto(
|
|
18
|
+
target: Record<string, unknown>,
|
|
19
|
+
source: Record<string, unknown>,
|
|
20
|
+
): void {
|
|
21
|
+
for (const key in source) {
|
|
22
|
+
const sourceVal = source[key];
|
|
23
|
+
if (sourceVal === undefined) continue;
|
|
24
|
+
const targetVal = target[key];
|
|
25
|
+
if (
|
|
26
|
+
sourceVal !== null &&
|
|
27
|
+
typeof sourceVal === 'object' &&
|
|
28
|
+
!Array.isArray(sourceVal) &&
|
|
29
|
+
targetVal !== null &&
|
|
30
|
+
typeof targetVal === 'object' &&
|
|
31
|
+
!Array.isArray(targetVal)
|
|
32
|
+
) {
|
|
33
|
+
mergeInto(
|
|
34
|
+
targetVal as Record<string, unknown>,
|
|
35
|
+
sourceVal as Record<string, unknown>,
|
|
36
|
+
);
|
|
37
|
+
} else if (Array.isArray(targetVal) && Array.isArray(sourceVal)) {
|
|
38
|
+
target[key] = [...targetVal, ...sourceVal];
|
|
39
|
+
} else {
|
|
40
|
+
target[key] = sourceVal;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
8
45
|
const requestContextStore = new AsyncLocalStorage<TraceContext>();
|
|
9
46
|
|
|
10
47
|
export function runWithRequestContext<T>(ctx: TraceContext, fn: () => T): T {
|
|
@@ -18,6 +55,7 @@ export interface RequestLogger {
|
|
|
18
55
|
error(error: Error | string, fields?: Record<string, unknown>): void;
|
|
19
56
|
getContext(): Record<string, unknown>;
|
|
20
57
|
emitNow(overrides?: Record<string, unknown>): RequestLogSnapshot;
|
|
58
|
+
fork(label: string, fn: () => void | Promise<void>): void;
|
|
21
59
|
}
|
|
22
60
|
|
|
23
61
|
export interface RequestLogSnapshot {
|
|
@@ -54,6 +92,8 @@ export function getRequestLogger(
|
|
|
54
92
|
): RequestLogger {
|
|
55
93
|
const activeContext = resolveContext(ctx);
|
|
56
94
|
let contextState: Record<string, unknown> = {};
|
|
95
|
+
let emitted = false;
|
|
96
|
+
let lastSnapshot: RequestLogSnapshot | null = null;
|
|
57
97
|
|
|
58
98
|
const addLogEvent = (
|
|
59
99
|
level: 'info' | 'warn' | 'error',
|
|
@@ -67,48 +107,60 @@ export function getRequestLogger(
|
|
|
67
107
|
});
|
|
68
108
|
};
|
|
69
109
|
|
|
110
|
+
const sealCheck = (method: string, keys: string[]): void => {
|
|
111
|
+
if (emitted) {
|
|
112
|
+
warnPostEmit(
|
|
113
|
+
method,
|
|
114
|
+
`Keys dropped: ${keys.length ? keys.join(', ') : '(empty)'}.`,
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
|
|
70
119
|
return {
|
|
71
120
|
set(fields: Record<string, unknown>) {
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
};
|
|
121
|
+
sealCheck('log.set()', Object.keys(fields));
|
|
122
|
+
if (emitted) return;
|
|
123
|
+
mergeInto(contextState, fields);
|
|
76
124
|
activeContext.setAttributes(flattenToAttributes(fields));
|
|
77
125
|
},
|
|
78
126
|
|
|
79
127
|
info(message: string, fields?: Record<string, unknown>) {
|
|
128
|
+
const keys = fields
|
|
129
|
+
? ['message', ...Object.keys(fields).filter((k) => k !== 'requestLogs')]
|
|
130
|
+
: ['message'];
|
|
131
|
+
sealCheck('log.info()', keys);
|
|
132
|
+
if (emitted) return;
|
|
80
133
|
addLogEvent('info', message, fields);
|
|
81
134
|
if (fields) {
|
|
82
|
-
contextState
|
|
83
|
-
...contextState,
|
|
84
|
-
...fields,
|
|
85
|
-
};
|
|
135
|
+
mergeInto(contextState, fields);
|
|
86
136
|
activeContext.setAttributes(flattenToAttributes(fields));
|
|
87
137
|
}
|
|
88
138
|
},
|
|
89
139
|
|
|
90
140
|
warn(message: string, fields?: Record<string, unknown>) {
|
|
141
|
+
const keys = fields
|
|
142
|
+
? ['message', ...Object.keys(fields).filter((k) => k !== 'requestLogs')]
|
|
143
|
+
: ['message'];
|
|
144
|
+
sealCheck('log.warn()', keys);
|
|
145
|
+
if (emitted) return;
|
|
91
146
|
addLogEvent('warn', message, fields);
|
|
92
147
|
activeContext.setAttribute('autotel.log.level', 'warn');
|
|
93
148
|
if (fields) {
|
|
94
|
-
contextState
|
|
95
|
-
...contextState,
|
|
96
|
-
...fields,
|
|
97
|
-
};
|
|
149
|
+
mergeInto(contextState, fields);
|
|
98
150
|
activeContext.setAttributes(flattenToAttributes(fields));
|
|
99
151
|
}
|
|
100
152
|
},
|
|
101
153
|
|
|
102
154
|
error(error: Error | string, fields?: Record<string, unknown>) {
|
|
155
|
+
const keys = fields ? [...Object.keys(fields), 'error'] : ['error'];
|
|
156
|
+
sealCheck('log.error()', keys);
|
|
157
|
+
if (emitted) return;
|
|
103
158
|
const err = typeof error === 'string' ? new Error(error) : error;
|
|
104
159
|
recordStructuredError(activeContext, err);
|
|
105
160
|
addLogEvent('error', err.message, fields);
|
|
106
161
|
|
|
107
162
|
if (fields) {
|
|
108
|
-
contextState
|
|
109
|
-
...contextState,
|
|
110
|
-
...fields,
|
|
111
|
-
};
|
|
163
|
+
mergeInto(contextState, fields);
|
|
112
164
|
activeContext.setAttributes(flattenToAttributes(fields));
|
|
113
165
|
}
|
|
114
166
|
activeContext.setAttribute('autotel.log.level', 'error');
|
|
@@ -119,6 +171,11 @@ export function getRequestLogger(
|
|
|
119
171
|
},
|
|
120
172
|
|
|
121
173
|
emitNow(overrides?: Record<string, unknown>): RequestLogSnapshot {
|
|
174
|
+
if (emitted) {
|
|
175
|
+
warnPostEmit('log.emitNow()', 'Ignoring duplicate emit.');
|
|
176
|
+
return lastSnapshot as RequestLogSnapshot;
|
|
177
|
+
}
|
|
178
|
+
|
|
122
179
|
const mergedContext = {
|
|
123
180
|
...contextState,
|
|
124
181
|
...(overrides ?? {}),
|
|
@@ -144,7 +201,49 @@ export function getRequestLogger(
|
|
|
144
201
|
});
|
|
145
202
|
}
|
|
146
203
|
|
|
204
|
+
emitted = true;
|
|
205
|
+
lastSnapshot = snapshot;
|
|
147
206
|
return snapshot;
|
|
148
207
|
},
|
|
208
|
+
|
|
209
|
+
fork(label: string, fn: () => void | Promise<void>): void {
|
|
210
|
+
const parentRequestId = activeContext.correlationId;
|
|
211
|
+
if (typeof parentRequestId !== 'string' || parentRequestId.length === 0) {
|
|
212
|
+
throw new Error(
|
|
213
|
+
'[autotel] log.fork() requires the parent logger to have a correlationId. ' +
|
|
214
|
+
'Ensure the request was created by autotel middleware.',
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const tracer = otelTrace.getTracer('autotel.request-logger');
|
|
219
|
+
void tracer.startActiveSpan(`request.fork:${label}`, (childSpan) => {
|
|
220
|
+
const childContext: TraceContext = {
|
|
221
|
+
...createTraceContext(childSpan),
|
|
222
|
+
correlationId: crypto.randomUUID(),
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
requestContextStore.run(childContext, () => {
|
|
226
|
+
const childLog = getRequestLogger(childContext);
|
|
227
|
+
childLog.set({
|
|
228
|
+
operation: label,
|
|
229
|
+
_parentCorrelationId: parentRequestId,
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
void Promise.resolve()
|
|
233
|
+
.then(() => fn())
|
|
234
|
+
.then(() => {
|
|
235
|
+
childLog.emitNow();
|
|
236
|
+
})
|
|
237
|
+
.catch((err: unknown) => {
|
|
238
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
239
|
+
childLog.error(error);
|
|
240
|
+
childLog.emitNow();
|
|
241
|
+
})
|
|
242
|
+
.finally(() => {
|
|
243
|
+
childSpan.end();
|
|
244
|
+
});
|
|
245
|
+
});
|
|
246
|
+
});
|
|
247
|
+
},
|
|
149
248
|
};
|
|
150
249
|
}
|
package/src/structured-error.ts
CHANGED
|
@@ -2,6 +2,8 @@ import { SpanStatusCode } from '@opentelemetry/api';
|
|
|
2
2
|
import type { AttributeValue, TraceContext } from './trace-context';
|
|
3
3
|
import { flattenToAttributes } from './flatten-attributes';
|
|
4
4
|
|
|
5
|
+
const internalKey = Symbol.for('autotel.error.internal');
|
|
6
|
+
|
|
5
7
|
export interface StructuredErrorInput {
|
|
6
8
|
message: string;
|
|
7
9
|
why?: string;
|
|
@@ -12,6 +14,8 @@ export interface StructuredErrorInput {
|
|
|
12
14
|
cause?: unknown;
|
|
13
15
|
details?: Record<string, unknown>;
|
|
14
16
|
name?: string;
|
|
17
|
+
/** Backend-only context. Omitted from toJSON() and never serialized to clients. */
|
|
18
|
+
internal?: Record<string, unknown>;
|
|
15
19
|
}
|
|
16
20
|
|
|
17
21
|
export interface StructuredError extends Error {
|
|
@@ -21,6 +25,8 @@ export interface StructuredError extends Error {
|
|
|
21
25
|
code?: string | number;
|
|
22
26
|
status?: number;
|
|
23
27
|
details?: Record<string, unknown>;
|
|
28
|
+
/** Backend-only context. Omitted from toJSON() and never serialized to clients. */
|
|
29
|
+
readonly internal?: Record<string, unknown>;
|
|
24
30
|
}
|
|
25
31
|
|
|
26
32
|
export function createStructuredError(
|
|
@@ -38,6 +44,25 @@ export function createStructuredError(
|
|
|
38
44
|
if (input.status !== undefined) error.status = input.status;
|
|
39
45
|
if (input.details !== undefined) error.details = input.details;
|
|
40
46
|
|
|
47
|
+
if (input.internal !== undefined) {
|
|
48
|
+
Object.defineProperty(error, internalKey, {
|
|
49
|
+
value: input.internal,
|
|
50
|
+
enumerable: false,
|
|
51
|
+
writable: false,
|
|
52
|
+
configurable: true,
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
Object.defineProperty(error, 'internal', {
|
|
57
|
+
get() {
|
|
58
|
+
return (
|
|
59
|
+
this as StructuredError & { [internalKey]?: Record<string, unknown> }
|
|
60
|
+
)[internalKey];
|
|
61
|
+
},
|
|
62
|
+
enumerable: false,
|
|
63
|
+
configurable: true,
|
|
64
|
+
});
|
|
65
|
+
|
|
41
66
|
error.toString = () => {
|
|
42
67
|
const lines = [`${error.name}: ${error.message}`];
|
|
43
68
|
if (error.why) lines.push(` Why: ${error.why}`);
|
|
@@ -45,13 +70,41 @@ export function createStructuredError(
|
|
|
45
70
|
if (error.link) lines.push(` Link: ${error.link}`);
|
|
46
71
|
if (error.code !== undefined) lines.push(` Code: ${error.code}`);
|
|
47
72
|
if (error.status !== undefined) lines.push(` Status: ${error.status}`);
|
|
48
|
-
if (error.cause)
|
|
73
|
+
if (error.cause) {
|
|
74
|
+
const cause = error.cause as Error;
|
|
75
|
+
lines.push(` Caused by: ${cause.name}: ${cause.message}`);
|
|
76
|
+
}
|
|
49
77
|
return lines.join('\n');
|
|
50
78
|
};
|
|
51
79
|
|
|
52
80
|
return error;
|
|
53
81
|
}
|
|
54
82
|
|
|
83
|
+
export function structuredErrorToJSON(
|
|
84
|
+
error: StructuredError,
|
|
85
|
+
): Record<string, unknown> {
|
|
86
|
+
const result: Record<string, unknown> = {
|
|
87
|
+
name: error.name,
|
|
88
|
+
message: error.message,
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
if (error.status !== undefined) result.status = error.status;
|
|
92
|
+
if (error.why || error.fix || error.link) {
|
|
93
|
+
result.data = {
|
|
94
|
+
...(error.why && { why: error.why }),
|
|
95
|
+
...(error.fix && { fix: error.fix }),
|
|
96
|
+
...(error.link && { link: error.link }),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
if (error.code !== undefined) result.code = error.code;
|
|
100
|
+
if (error.details) result.details = error.details;
|
|
101
|
+
if (error.cause instanceof Error) {
|
|
102
|
+
result.cause = { name: error.cause.name, message: error.cause.message };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return result;
|
|
106
|
+
}
|
|
107
|
+
|
|
55
108
|
export function getStructuredErrorAttributes(
|
|
56
109
|
error: Error,
|
|
57
110
|
): Record<string, AttributeValue> {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sampling.ts"],"names":["TraceFlags"],"mappings":";;;;;AA+BO,IAAM,0BAAA,GAA6B;AACnC,IAAM,+BAAA,GACX;AAmEK,IAAM,gBAAN,MAAuC;AAAA,EAC5C,YAA6B,UAAA,EAAoB;AAApB,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAC3B,IAAA,IAAI,UAAA,GAAa,CAAA,IAAK,UAAA,GAAa,CAAA,EAAG;AACpC,MAAA,MAAM,IAAI,MAAM,qCAAqC,CAAA;AAAA,IACvD;AAAA,EACF;AAAA;AAAA,EAGA,aAAa,QAAA,EAAoC;AAC/C,IAAA,OAAO,IAAA,CAAK,MAAA,EAAO,GAAI,IAAA,CAAK,UAAA;AAAA,EAC9B;AACF;AAKO,IAAM,gBAAN,MAAuC;AAAA;AAAA,EAE5C,aAAa,QAAA,EAAoC;AAC/C,IAAA,OAAO,IAAA;AAAA,EACT;AACF;AAKO,IAAM,eAAN,MAAsC;AAAA;AAA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AG;AAC9B,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,MAAM,OAAA,GAAU,MAAM,CAAC,CAAA;AACvB,EAAA,MAAM,OAAA,GAAU,MAAM,CAAC,CAAA;AACvB,EAAA,MAAM,MAAA,GAAS,MAAM,CAAC,CAAA;AACtB,EAAA,MAAM,KAAA,GAAQ,MAAM,CAAC,CAAA;AAGrB,EAAA,IAAI,CAAC,OAAA,IAAW,CAAC,WAAW,CAAC,MAAA,IAAU,CAAC,KAAA,EAAO;AAC7C,IAAA,OAAO,IAAA;AAAA,EACT;AAGA,EAAA,IAAI,YAAY,IAAA,EAAM;AAEpB,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,OAAO;AAAA,IACL,OAAA;AAAA,IACA,MAAA;AAAA,IACA,UAAA,EAAY,MAAA,CAAO,QAAA,CAAS,KAAA,EAAO,EAAE,CAAA;AAAA,IACrC,QAAA,EAAU;AAAA,GACZ;AACF;AAKA,SAAS,mBACP,WAAA,EACyD;AACzD,EAAA,IAAI,CAAC,aAAa,OAAO,KAAA;AAGzB,EAAA,OACE,WAAA,CAAY,OAAA,KAAY,kCAAA,IACxB,WAAA,CAAY,MAAA,KAAW,kBAAA;AAE3B","file":"chunk-7FIGORWI.cjs","sourcesContent":["/**\n * Sampling Strategies\n *\n * Provides intelligent sampling beyond simple random rates.\n * Helps reduce telemetry costs while capturing critical data.\n *\n * Key strategies:\n * - Always trace errors and slow requests (critical for debugging)\n * - Sample by user ID for consistent request tracing\n * - Adaptive sampling based on load\n * - Sample by feature flags for A/B testing correlation\n *\n * @example\n * ```typescript\n * import { AlwaysOnErrorSampler, UserIdSampler } from './sampling'\n *\n * @Instrumented({\n * serviceName: 'user',\n * sampler: new AlwaysOnErrorSampler(0.1) // 10% baseline, 100% on errors\n * })\n * class UserService { }\n * ```\n */\n\nimport type { Link, Attributes } from '@opentelemetry/api';\nimport { TraceFlags } from '@opentelemetry/api';\nimport { type Logger } from './logger';\n\n/**\n * Tail sampling attribute keys (autotel-internal, not OTel semconv)\n */\nexport const AUTOTEL_SAMPLING_TAIL_KEEP = 'autotel.sampling.tail.keep';\nexport const AUTOTEL_SAMPLING_TAIL_EVALUATED =\n 'autotel.sampling.tail.evaluated';\n\n/**\n * Sampler interface - return true to trace, false to skip\n */\nexport interface Sampler {\n /**\n * Decide whether to trace this operation\n *\n * @param context - Sampling context\n * @returns true to trace, false to skip\n */\n shouldSample(context: SamplingContext): boolean;\n\n /**\n * Whether this sampler needs tail sampling (post-execution decision)\n * If true, spans are always created and shouldKeepTrace() is called after execution\n *\n * @returns true if this sampler needs to evaluate after operation completes\n */\n needsTailSampling?(): boolean;\n\n /**\n * Re-evaluate sampling decision after operation completes (tail sampling)\n * Only called if needsTailSampling() returns true\n *\n * @param context - Sampling context\n * @param result - Operation result\n * @returns true if this trace should be kept, false to drop it\n */\n shouldKeepTrace?(context: SamplingContext, result: OperationResult): boolean;\n}\n\n/**\n * Context information for sampling decisions\n */\nexport interface SamplingContext {\n /** Operation name */\n operationName: string;\n /** Method arguments (for extracting user IDs, etc.) */\n args: unknown[];\n /** Optional metadata (e.g., feature flags, request headers) */\n metadata?: Record<string, unknown>;\n /** Optional span links for links-based sampling */\n links?: Link[];\n}\n\n/**\n * Result of a trace operation (for post-execution sampling)\n */\nexport interface OperationResult {\n /** Whether the operation succeeded */\n success: boolean;\n /** Duration in milliseconds */\n duration: number;\n /** Error if operation failed */\n error?: Error;\n}\n\n/**\n * Simple random sampler\n *\n * @example\n * ```typescript\n * new RandomSampler(0.1) // Sample 10% of requests\n * ```\n */\nexport class RandomSampler implements Sampler {\n constructor(private readonly sampleRate: number) {\n if (sampleRate < 0 || sampleRate > 1) {\n throw new Error('Sample rate must be between 0 and 1');\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n shouldSample(_context: SamplingContext): boolean {\n return Math.random() < this.sampleRate;\n }\n}\n\n/**\n * Always sample (100% tracing)\n */\nexport class AlwaysSampler implements Sampler {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n shouldSample(_context: SamplingContext): boolean {\n return true;\n }\n}\n\n/**\n * Never sample (0% tracing)\n */\nexport class NeverSampler implements Sampler {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n shouldSample(_context: SamplingContext): boolean {\n return false;\n }\n}\n\n/**\n * Adaptive sampler that always traces errors and slow requests\n *\n * This is the recommended sampler for production use.\n * It ensures you never miss critical issues while keeping costs down.\n *\n * Strategy:\n * - Always trace errors (critical for debugging)\n * - Always trace slow requests (performance issues)\n * - Use baseline sample rate for successful fast requests\n *\n * **IMPORTANT - Tail Sampling Requirement:**\n * This sampler uses tail sampling (makes decisions AFTER execution).\n * You MUST use TailSamplingSpanProcessor for it to work correctly:\n *\n * - If using initInstrumentation(): TailSamplingSpanProcessor is auto-configured\n * - If using custom TracerProvider: You MUST manually register TailSamplingSpanProcessor\n *\n * Without TailSamplingSpanProcessor, ALL spans are exported (defeating the cost savings).\n *\n * @see TailSamplingSpanProcessor\n * @see README.md \"Tail Sampling with Custom Providers\" section\n *\n * @example\n * ```typescript\n * new AdaptiveSampler({\n * baselineSampleRate: 0.1, // 10% of normal requests\n * slowThresholdMs: 1000, // Requests > 1s are \"slow\"\n * alwaysSampleErrors: true, // Always trace errors\n * alwaysSampleSlow: true // Always trace slow requests\n * })\n * ```\n */\nexport class AdaptiveSampler implements Sampler {\n private baselineSampleRate: number;\n private slowThresholdMs: number;\n private alwaysSampleErrors: boolean;\n private alwaysSampleSlow: boolean;\n private linksBased: boolean;\n private linksRate: number;\n private logger?: Logger;\n\n // Track whether we should sample this request\n private readonly samplingDecisions = new WeakMap<unknown[], boolean>();\n // Track operation results to enable post-execution decision\n private readonly operationResults = new WeakMap<unknown[], OperationResult>();\n\n constructor(\n options: {\n baselineSampleRate?: number;\n slowThresholdMs?: number;\n alwaysSampleErrors?: boolean;\n alwaysSampleSlow?: boolean;\n /** Enable links-based sampling for event-driven architectures */\n linksBased?: boolean;\n /** Sampling rate for spans linked to sampled spans (0.0-1.0) */\n linksRate?: number;\n logger?: Logger;\n } = {},\n ) {\n this.baselineSampleRate = options.baselineSampleRate ?? 0.1;\n this.slowThresholdMs = options.slowThresholdMs ?? 1000;\n this.alwaysSampleErrors = options.alwaysSampleErrors ?? true;\n this.alwaysSampleSlow = options.alwaysSampleSlow ?? true;\n this.linksBased = options.linksBased ?? false;\n this.linksRate = options.linksRate ?? 1;\n this.logger = options.logger;\n\n if (this.baselineSampleRate < 0 || this.baselineSampleRate > 1) {\n throw new Error('Baseline sample rate must be between 0 and 1');\n }\n if (this.linksRate < 0 || this.linksRate > 1) {\n throw new Error('Links rate must be between 0 and 1');\n }\n }\n\n needsTailSampling(): boolean {\n // AdaptiveSampler ALWAYS needs tail sampling to implement error/slow capture\n return true;\n }\n\n shouldSample(context: SamplingContext): boolean {\n // For tail sampling, we optimistically create spans for all requests\n // The real decision happens in shouldKeepTrace() after execution\n // We still store the baseline decision for shouldKeepTrace() to use\n const baselineDecision = Math.random() < this.baselineSampleRate;\n this.samplingDecisions.set(context.args, baselineDecision);\n\n // Always return true to create the span (tail sampling will decide if we keep it)\n return true;\n }\n\n /**\n * Check if any links point to sampled spans.\n *\n * A span is considered linked to a sampled span if any of its links\n * have trace_flags with the sampled bit set (0x01).\n *\n * @param links - Array of span links to check\n * @returns true if any linked span is sampled, false otherwise\n */\n hasSampledLink(links: Link[]): boolean {\n if (!links || links.length === 0) {\n return false;\n }\n return links.some(\n (link) =>\n link.context && (link.context.traceFlags & TraceFlags.SAMPLED) !== 0,\n );\n }\n\n /**\n * Re-evaluate sampling decision after operation completes\n *\n * This allows us to always capture errors and slow requests,\n * even if they weren't initially sampled.\n *\n * @param context - Sampling context\n * @param result - Operation result\n * @returns true if this operation should be kept (not discarded)\n */\n shouldKeepTrace(context: SamplingContext, result: OperationResult): boolean {\n const baselineDecision = this.samplingDecisions.get(context.args) ?? false;\n\n // Always keep errors\n if (this.alwaysSampleErrors && !result.success) {\n if (!baselineDecision) {\n this.logger?.debug(\n {\n operation: context.operationName,\n error: result.error?.message,\n },\n 'Adaptive sampling: Keeping error trace',\n );\n }\n return true;\n }\n\n // Always keep slow requests\n if (this.alwaysSampleSlow && result.duration >= this.slowThresholdMs) {\n if (!baselineDecision) {\n this.logger?.debug(\n {\n operation: context.operationName,\n duration: result.duration,\n },\n 'Adaptive sampling: Keeping slow trace',\n );\n }\n return true;\n }\n\n // Check for sampled links (links-based sampling for event-driven systems)\n if (\n this.linksBased &&\n context.links &&\n this.hasSampledLink(context.links)\n ) {\n // Use linksRate to decide whether to keep the linked span\n const keepLinked = Math.random() < this.linksRate;\n if (keepLinked && !baselineDecision) {\n this.logger?.debug(\n {\n operation: context.operationName,\n linkCount: context.links.length,\n },\n 'Adaptive sampling: Keeping trace due to sampled link',\n );\n }\n return keepLinked;\n }\n\n // Otherwise, use baseline decision\n return baselineDecision;\n }\n}\n\n/**\n * User-based sampler for consistent tracing\n *\n * Always samples requests from specific user IDs.\n * Useful for debugging specific user issues or monitoring VIP users.\n *\n * @example\n * ```typescript\n * new UserIdSampler({\n * baselineSampleRate: 0.01, // 1% of normal users\n * alwaysSampleUsers: ['vip_123'], // Always trace VIP users\n * extractUserId: (args) => args[0]?.userId // Extract user ID from first arg\n * })\n * ```\n */\nexport class UserIdSampler implements Sampler {\n private baselineSampleRate: number;\n private alwaysSampleUsers: Set<string>;\n private extractUserId: (args: unknown[]) => string | undefined;\n private logger?: Logger;\n\n constructor(options: {\n baselineSampleRate?: number;\n alwaysSampleUsers?: string[];\n extractUserId: (args: unknown[]) => string | undefined;\n logger?: Logger;\n }) {\n this.baselineSampleRate = options.baselineSampleRate ?? 0.1;\n this.alwaysSampleUsers = new Set(options.alwaysSampleUsers || []);\n this.extractUserId = options.extractUserId;\n this.logger = options.logger;\n }\n\n shouldSample(context: SamplingContext): boolean {\n const userId = this.extractUserId(context.args);\n\n // Always sample specific users\n if (userId && this.alwaysSampleUsers.has(userId)) {\n this.logger?.debug(\n {\n operation: context.operationName,\n userId,\n },\n 'Sampling user request',\n );\n return true;\n }\n\n // For consistent per-user sampling, hash the user ID\n if (userId) {\n const hash = this.hashString(userId);\n return hash < this.baselineSampleRate;\n }\n\n // Fallback to random sampling if no user ID\n return Math.random() < this.baselineSampleRate;\n }\n\n /**\n * Add user IDs to always-sample list\n */\n addAlwaysSampleUsers(...userIds: string[]): void {\n for (const userId of userIds) {\n this.alwaysSampleUsers.add(userId);\n }\n }\n\n /**\n * Remove user IDs from always-sample list\n */\n removeAlwaysSampleUsers(...userIds: string[]): void {\n for (const userId of userIds) {\n this.alwaysSampleUsers.delete(userId);\n }\n }\n\n /**\n * Simple hash function for consistent user sampling\n */\n private hashString(str: string): number {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n const char = str.codePointAt(i) ?? 0;\n hash = (hash << 5) - hash + char;\n hash = hash & hash; // Convert to 32-bit integer\n }\n return Math.abs(hash) / 2_147_483_647; // Normalize to 0-1\n }\n}\n\n/**\n * Composite sampler that combines multiple samplers\n *\n * Samples if ANY of the child samplers returns true.\n *\n * @example\n * ```typescript\n * new CompositeSampler([\n * new UserIdSampler({ extractUserId: (args) => args[0]?.userId }),\n * new AdaptiveSampler({ baselineSampleRate: 0.1 })\n * ])\n * ```\n */\nexport class CompositeSampler implements Sampler {\n constructor(private readonly samplers: Sampler[]) {\n if (samplers.length === 0) {\n throw new Error('CompositeSampler requires at least one child sampler');\n }\n }\n\n shouldSample(context: SamplingContext): boolean {\n return this.samplers.some((sampler) => sampler.shouldSample(context));\n }\n}\n\n/**\n * Feature flag sampler\n *\n * Always samples requests with specific feature flags enabled.\n * Perfect for correlating A/B test experiments with metrics.\n *\n * @example\n * ```typescript\n * new FeatureFlagSampler({\n * baselineSampleRate: 0.01,\n * alwaysSampleFlags: ['new_checkout', 'experimental_ui'],\n * extractFlags: (args, metadata) => metadata?.featureFlags\n * })\n * ```\n */\nexport class FeatureFlagSampler implements Sampler {\n private baselineSampleRate: number;\n private alwaysSampleFlags: Set<string>;\n private extractFlags: (\n args: unknown[],\n metadata?: Record<string, unknown>,\n ) => string[] | undefined;\n private logger?: Logger;\n\n constructor(options: {\n baselineSampleRate?: number;\n alwaysSampleFlags?: string[];\n extractFlags: (\n args: unknown[],\n metadata?: Record<string, unknown>,\n ) => string[] | undefined;\n logger?: Logger;\n }) {\n this.baselineSampleRate = options.baselineSampleRate ?? 0.1;\n this.alwaysSampleFlags = new Set(options.alwaysSampleFlags || []);\n this.extractFlags = options.extractFlags;\n this.logger = options.logger;\n }\n\n shouldSample(context: SamplingContext): boolean {\n const flags = this.extractFlags(context.args, context.metadata);\n\n // Always sample if any monitored flag is enabled\n if (flags && flags.some((flag) => this.alwaysSampleFlags.has(flag))) {\n this.logger?.debug(\n {\n operation: context.operationName,\n flags,\n },\n 'Sampling feature flag request',\n );\n return true;\n }\n\n // Fallback to random sampling\n return Math.random() < this.baselineSampleRate;\n }\n\n /**\n * Add feature flags to always-sample list\n */\n addAlwaysSampleFlags(...flags: string[]): void {\n for (const flag of flags) {\n this.alwaysSampleFlags.add(flag);\n }\n }\n\n /**\n * Remove feature flags from always-sample list\n */\n removeAlwaysSampleFlags(...flags: string[]): void {\n for (const flag of flags) {\n this.alwaysSampleFlags.delete(flag);\n }\n }\n}\n\n// ============================================================================\n// Sampling Presets\n// ============================================================================\n\n/**\n * Named sampling presets for common environments.\n * Use with `init({ sampling: 'production' })` or directly via factories.\n */\nexport type SamplingPreset =\n | 'development'\n | 'errors-only'\n | 'production'\n | 'off';\n\n/**\n * Sampling preset factories.\n *\n * For most users, the string shorthand on `init()` is simpler:\n * ```typescript\n * init({ service: 'my-app', sampling: 'production' })\n * ```\n *\n * Use factories when you need to customize:\n * ```typescript\n * init({ service: 'my-app', sampler: samplingPresets.production({ baselineSampleRate: 0.05 }) })\n * ```\n */\nexport const samplingPresets = {\n /** Capture everything — best for local development and debugging */\n development: () => new AlwaysSampler(),\n\n /** Only bad outcomes — zero baseline, errors always kept */\n errorsOnly: () =>\n new AdaptiveSampler({\n baselineSampleRate: 0,\n alwaysSampleErrors: true,\n }),\n\n /**\n * Balanced production defaults — 10% baseline + errors + slow traces.\n * Pass overrides to tune (uses the same option names as AdaptiveSampler).\n */\n production: (overrides?: {\n baselineSampleRate?: number;\n slowThresholdMs?: number;\n alwaysSampleErrors?: boolean;\n alwaysSampleSlow?: boolean;\n }) =>\n new AdaptiveSampler({\n baselineSampleRate: 0.1,\n alwaysSampleErrors: true,\n alwaysSampleSlow: true,\n slowThresholdMs: 1000,\n ...overrides,\n }),\n\n /** Disable sampling entirely */\n off: () => new NeverSampler(),\n};\n\n/**\n * Resolve a preset string to a Sampler instance.\n * Used internally by `init()` when `sampling` string is provided.\n *\n * @throws Error if preset is not recognized\n */\nexport function resolveSamplingPreset(preset: SamplingPreset): Sampler {\n switch (preset) {\n case 'development':\n return samplingPresets.development();\n case 'errors-only':\n return samplingPresets.errorsOnly();\n case 'production':\n return samplingPresets.production();\n case 'off':\n return samplingPresets.off();\n default:\n throw new Error(\n `Unknown sampling preset: \"${preset}\". Valid presets: development, errors-only, production, off`,\n );\n }\n}\n\n// ============================================================================\n// Link Helper Functions\n// ============================================================================\n\n/**\n * Create a Link from W3C trace context headers (e.g., from a message queue).\n *\n * This is useful for message consumers that need to link to the producer span.\n * The headers should contain at least a `traceparent` header in W3C format.\n *\n * @param headers - Dictionary containing traceparent/tracestate headers\n * @param attributes - Optional attributes for the link\n * @returns Link object if context could be extracted, null otherwise\n *\n * @example\n * ```typescript\n * // In a Kafka consumer\n * const headers = { traceparent: '00-abc123...-def456...-01' };\n * const link = createLinkFromHeaders(headers);\n * if (link) {\n * // Use with tracer.startActiveSpan options or ctx.addLink()\n * tracer.startActiveSpan('process.message', { links: [link] }, span => { ... });\n * }\n * ```\n */\nexport function createLinkFromHeaders(\n headers: Record<string, string>,\n attributes?: Attributes,\n): Link | null {\n // Parse W3C traceparent header directly for reliability\n // Format: version-traceId-spanId-traceFlags (e.g., 00-abc123...-def456...-01)\n const traceparent = headers.traceparent || headers['traceparent'];\n if (!traceparent) {\n return null;\n }\n\n const spanContext = parseTraceparent(traceparent);\n if (!spanContext || !isValidSpanContext(spanContext)) {\n return null;\n }\n\n return {\n context: spanContext,\n attributes: attributes ?? {},\n };\n}\n\n/**\n * Extract Links from a batch of messages for fan-in scenarios.\n *\n * Useful for batch processing where multiple producer spans should be linked.\n * This enables tracing causality in event-driven architectures where a single\n * consumer processes messages from multiple producers.\n *\n * @param messages - List of message objects\n * @param headersKey - Key in each message containing trace headers (default: 'headers')\n * @returns List of Link objects for all valid trace contexts\n *\n * @example\n * ```typescript\n * // Processing a batch of SQS/Kafka messages\n * const messages = [\n * { body: '...', headers: { traceparent: '...' } },\n * { body: '...', headers: { traceparent: '...' } },\n * ];\n * const links = extractLinksFromBatch(messages);\n *\n * tracer.startActiveSpan('process.batch', { links }, span => {\n * for (const msg of messages) {\n * processMessage(msg);\n * }\n * });\n * ```\n */\nexport function extractLinksFromBatch(\n messages: Array<{ [key: string]: unknown }>,\n headersKey: string = 'headers',\n): Link[] {\n const links: Link[] = [];\n\n for (const msg of messages) {\n const msgHeaders = msg[headersKey];\n if (msgHeaders && typeof msgHeaders === 'object' && msgHeaders !== null) {\n const link = createLinkFromHeaders(msgHeaders as Record<string, string>, {\n 'messaging.batch.message_index': links.length,\n });\n if (link) {\n links.push(link);\n }\n }\n }\n\n return links;\n}\n\n/**\n * Parse W3C traceparent header into SpanContext\n * Format: version-traceId-spanId-traceFlags (e.g., 00-abc123...-def456...-01)\n *\n * @see https://www.w3.org/TR/trace-context/#traceparent-header\n */\nfunction parseTraceparent(\n traceparent: string,\n): import('@opentelemetry/api').SpanContext | null {\n // W3C traceparent format: version-traceId-parentId-traceFlags\n // Example: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01\n const TRACEPARENT_REGEX =\n /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/i;\n\n const match = traceparent.match(TRACEPARENT_REGEX);\n if (!match || match.length < 5) {\n return null;\n }\n\n const version = match[1];\n const traceId = match[2];\n const spanId = match[3];\n const flags = match[4];\n\n // Validate all parts are present (TypeScript narrowing)\n if (!version || !traceId || !spanId || !flags) {\n return null;\n }\n\n // Version 00 is currently the only version, but we should be forward compatible\n if (version === 'ff') {\n // Version ff is invalid according to spec\n return null;\n }\n\n return {\n traceId,\n spanId,\n traceFlags: Number.parseInt(flags, 16),\n isRemote: true,\n };\n}\n\n/**\n * Check if a SpanContext is valid (has non-zero trace and span IDs)\n */\nfunction isValidSpanContext(\n spanContext: import('@opentelemetry/api').SpanContext | null,\n): spanContext is import('@opentelemetry/api').SpanContext {\n if (!spanContext) return false;\n // TraceId should not be all zeros (00000000000000000000000000000000)\n // SpanId should not be all zeros (0000000000000000)\n return (\n spanContext.traceId !== '00000000000000000000000000000000' &&\n spanContext.spanId !== '0000000000000000'\n );\n}\n"]}
|