@nathapp/nestjs-observability 4.0.0 → 4.0.2
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/metrics/http-metrics.interceptor.d.ts +12 -0
- package/dist/metrics/http-metrics.interceptor.js +15 -4
- package/dist/metrics/http-metrics.interceptor.js.map +1 -1
- package/dist/metrics/index.d.ts +1 -1
- package/dist/metrics/index.js +2 -1
- package/dist/metrics/index.js.map +1 -1
- package/dist/module/observability.module.d.ts +7 -0
- package/dist/module/observability.module.js +23 -16
- package/dist/module/observability.module.js.map +1 -1
- package/package.json +6 -6
- package/.eslintrc.js +0 -8
- package/.nax/features/nestjs-observability/.nax-acceptance.test.ts +0 -797
- package/.turbo/turbo-build.log +0 -4
- package/CHANGELOG.md +0 -43
- package/lib/constant/index.ts +0 -1
- package/lib/constant/observability.constants.ts +0 -21
- package/lib/index.ts +0 -17
- package/lib/interface/index.ts +0 -2
- package/lib/interface/observability-module-options.interface.ts +0 -47
- package/lib/interface/tracing-bootstrap-options.interface.ts +0 -17
- package/lib/metrics/http-metrics.interceptor.ts +0 -174
- package/lib/metrics/index.ts +0 -7
- package/lib/metrics/metrics.providers.ts +0 -134
- package/lib/module/index.ts +0 -1
- package/lib/module/observability.module.ts +0 -236
- package/lib/tracing/index.ts +0 -4
- package/lib/tracing/init-tracing.ts +0 -92
- package/lib/tracing/shutdown.ts +0 -28
- package/lib/tracing/trace-context.interceptor.ts +0 -42
- package/lib/tracing/trace-internal.ts +0 -19
- package/lib/tracing/trace.decorator.ts +0 -63
- package/lib/tracing/trace.service.ts +0 -48
- package/test/jest-nax.json +0 -27
- package/test/jest-test.json +0 -28
- package/test/metrics/http-metrics.interceptor.spec.ts +0 -453
- package/test/metrics/metrics.providers.spec.ts +0 -97
- package/test/module/observability.module.spec.ts +0 -229
- package/test/tracing/build-node-sdk.spec.ts +0 -224
- package/test/tracing/init-tracing.idempotency.spec.ts +0 -64
- package/test/tracing/init-tracing.shutdown.spec.ts +0 -88
- package/test/tracing/shutdown.spec.ts +0 -109
- package/test/tracing/trace-context.interceptor.spec.ts +0 -221
- package/test/tracing/trace.decorator.spec.ts +0 -153
- package/test/tracing/trace.service.spec.ts +0 -205
- package/tsconfig.json +0 -9
|
@@ -1,229 +0,0 @@
|
|
|
1
|
-
import { afterAll, beforeAll, describe, expect, it } from '@jest/globals';
|
|
2
|
-
import { Controller, Get, INestApplication } from '@nestjs/common';
|
|
3
|
-
import { Test } from '@nestjs/testing';
|
|
4
|
-
import { trace as otelTrace, type Tracer } from '@opentelemetry/api';
|
|
5
|
-
import { RequestContextService, runWithContext } from '@nathapp/nestjs-logging';
|
|
6
|
-
|
|
7
|
-
import { register as promRegister } from 'prom-client';
|
|
8
|
-
import * as request from 'supertest';
|
|
9
|
-
import { initTracing } from '../../lib/tracing/init-tracing';
|
|
10
|
-
import { ObservabilityModule } from '../../lib/module/observability.module';
|
|
11
|
-
import { TraceContextInterceptor } from '../../lib/tracing/trace-context.interceptor';
|
|
12
|
-
import { TraceService } from '../../lib/tracing/trace.service';
|
|
13
|
-
|
|
14
|
-
// Start a real OpenTelemetry SDK once per test file so a tracer produces real
|
|
15
|
-
// (non-zero) trace ids when we call `tracer.startActiveSpan(...)` below. The
|
|
16
|
-
// bridge under test depends only on `trace.getActiveSpan()`, which the SDK
|
|
17
|
-
// populates via its AsyncLocalStorage context manager.
|
|
18
|
-
initTracing({ serviceName: 'nestjs-observability-tests', exporter: 'none' });
|
|
19
|
-
|
|
20
|
-
const tracer: Tracer = otelTrace.getTracer('nestjs-observability-tests');
|
|
21
|
-
|
|
22
|
-
// `PrometheusModule.register()` calls `promClient.collectDefaultMetrics()` which
|
|
23
|
-
// registers default Node/process metrics on the global registry; re-registering
|
|
24
|
-
// them across tests throws "metric … already been registered", so reset before
|
|
25
|
-
// each test that exercises the module.
|
|
26
|
-
const resetPromRegistry = (): void => {
|
|
27
|
-
promRegister.clear();
|
|
28
|
-
};
|
|
29
|
-
|
|
30
|
-
@Controller()
|
|
31
|
-
class SampleController {
|
|
32
|
-
@Get('test-route')
|
|
33
|
-
test(): { ok: true } {
|
|
34
|
-
return { ok: true };
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
describe('ObservabilityModule', () => {
|
|
39
|
-
describe('AC-1: register() returns a DynamicModule with module === ObservabilityModule and global: true', () => {
|
|
40
|
-
it('register() with no arguments returns a DynamicModule with module === ObservabilityModule and global === true', () => {
|
|
41
|
-
resetPromRegistry();
|
|
42
|
-
const result = ObservabilityModule.register();
|
|
43
|
-
expect(result).toBeDefined();
|
|
44
|
-
expect(result.module).toBe(ObservabilityModule);
|
|
45
|
-
expect((result as { global?: boolean }).global).toBe(true);
|
|
46
|
-
});
|
|
47
|
-
|
|
48
|
-
it('register({ metrics: { path: "/custom-metrics" } }) still returns module === ObservabilityModule and global === true', () => {
|
|
49
|
-
resetPromRegistry();
|
|
50
|
-
const result = ObservabilityModule.register({ metrics: { path: '/custom-metrics' } });
|
|
51
|
-
expect(result.module).toBe(ObservabilityModule);
|
|
52
|
-
expect((result as { global?: boolean }).global).toBe(true);
|
|
53
|
-
});
|
|
54
|
-
});
|
|
55
|
-
|
|
56
|
-
describe('Prometheus exposition endpoint wiring (AC-2, AC-3, AC-4, AC-8)', () => {
|
|
57
|
-
let app: INestApplication | undefined;
|
|
58
|
-
|
|
59
|
-
afterAll(async () => {
|
|
60
|
-
if (app) await app.close();
|
|
61
|
-
});
|
|
62
|
-
|
|
63
|
-
it('AC-2: with register() and no metrics path override, GET /metrics returns 200 with text/plain', async () => {
|
|
64
|
-
resetPromRegistry();
|
|
65
|
-
const moduleRef = await Test.createTestingModule({
|
|
66
|
-
imports: [ObservabilityModule.register()],
|
|
67
|
-
controllers: [SampleController],
|
|
68
|
-
}).compile();
|
|
69
|
-
const localApp = moduleRef.createNestApplication();
|
|
70
|
-
await localApp.init();
|
|
71
|
-
|
|
72
|
-
try {
|
|
73
|
-
const res = await request(localApp.getHttpServer()).get('/metrics');
|
|
74
|
-
expect(res.status).toBe(200);
|
|
75
|
-
expect(res.headers['content-type']).toMatch(/text\/plain/);
|
|
76
|
-
} finally {
|
|
77
|
-
await localApp.close();
|
|
78
|
-
}
|
|
79
|
-
});
|
|
80
|
-
|
|
81
|
-
it('AC-3: register({ metrics: { path: "/custom-metrics" } }) serves the exposition endpoint at /custom-metrics', async () => {
|
|
82
|
-
resetPromRegistry();
|
|
83
|
-
const moduleRef = await Test.createTestingModule({
|
|
84
|
-
imports: [ObservabilityModule.register({ metrics: { path: '/custom-metrics' } })],
|
|
85
|
-
controllers: [SampleController],
|
|
86
|
-
}).compile();
|
|
87
|
-
const localApp = moduleRef.createNestApplication();
|
|
88
|
-
await localApp.init();
|
|
89
|
-
|
|
90
|
-
try {
|
|
91
|
-
const res = await request(localApp.getHttpServer()).get('/custom-metrics');
|
|
92
|
-
expect(res.status).toBe(200);
|
|
93
|
-
expect(res.headers['content-type']).toMatch(/text\/plain/);
|
|
94
|
-
} finally {
|
|
95
|
-
await localApp.close();
|
|
96
|
-
}
|
|
97
|
-
});
|
|
98
|
-
|
|
99
|
-
it('AC-4: with default metrics enabled, the /metrics response contains a nodejs_ or process_ series', async () => {
|
|
100
|
-
resetPromRegistry();
|
|
101
|
-
const moduleRef = await Test.createTestingModule({
|
|
102
|
-
imports: [ObservabilityModule.register()],
|
|
103
|
-
controllers: [SampleController],
|
|
104
|
-
}).compile();
|
|
105
|
-
const localApp = moduleRef.createNestApplication();
|
|
106
|
-
await localApp.init();
|
|
107
|
-
|
|
108
|
-
try {
|
|
109
|
-
const res = await request(localApp.getHttpServer()).get('/metrics');
|
|
110
|
-
expect(res.status).toBe(200);
|
|
111
|
-
expect(res.text).toMatch(/(^|\n)(nodejs_|process_)/);
|
|
112
|
-
} finally {
|
|
113
|
-
await localApp.close();
|
|
114
|
-
}
|
|
115
|
-
});
|
|
116
|
-
|
|
117
|
-
it('AC-8: registerAsync({ useFactory }) returning { metrics: { path: "/async-metrics" } } exposes the endpoint at /async-metrics', async () => {
|
|
118
|
-
resetPromRegistry();
|
|
119
|
-
const moduleRef = await Test.createTestingModule({
|
|
120
|
-
imports: [
|
|
121
|
-
ObservabilityModule.registerAsync({
|
|
122
|
-
useFactory: () => ({ metrics: { path: '/async-metrics' } }),
|
|
123
|
-
}),
|
|
124
|
-
],
|
|
125
|
-
controllers: [SampleController],
|
|
126
|
-
}).compile();
|
|
127
|
-
const localApp = moduleRef.createNestApplication();
|
|
128
|
-
await localApp.init();
|
|
129
|
-
|
|
130
|
-
try {
|
|
131
|
-
const res = await request(localApp.getHttpServer()).get('/async-metrics');
|
|
132
|
-
expect(res.status).toBe(200);
|
|
133
|
-
expect(res.headers['content-type']).toMatch(/text\/plain/);
|
|
134
|
-
} finally {
|
|
135
|
-
await localApp.close();
|
|
136
|
-
}
|
|
137
|
-
});
|
|
138
|
-
|
|
139
|
-
it('registerAsync without useFactory throws synchronously (useClass/useExisting are not supported)', () => {
|
|
140
|
-
// The supported async contract is `useFactory` only; calling with neither
|
|
141
|
-
// would silently produce an empty-options module, so we surface the gap.
|
|
142
|
-
expect(() =>
|
|
143
|
-
ObservabilityModule.registerAsync({} as never),
|
|
144
|
-
).toThrow(/useFactory/);
|
|
145
|
-
});
|
|
146
|
-
});
|
|
147
|
-
|
|
148
|
-
describe('Cross-cutting interceptors register as APP_INTERCEPTOR (AC-5, AC-6, AC-7)', () => {
|
|
149
|
-
let app: INestApplication | undefined;
|
|
150
|
-
|
|
151
|
-
beforeAll(async () => {
|
|
152
|
-
resetPromRegistry();
|
|
153
|
-
const moduleRef = await Test.createTestingModule({
|
|
154
|
-
imports: [ObservabilityModule.register()],
|
|
155
|
-
controllers: [SampleController],
|
|
156
|
-
}).compile();
|
|
157
|
-
app = moduleRef.createNestApplication();
|
|
158
|
-
await app.init();
|
|
159
|
-
});
|
|
160
|
-
|
|
161
|
-
afterAll(async () => {
|
|
162
|
-
if (app) await app.close();
|
|
163
|
-
});
|
|
164
|
-
|
|
165
|
-
it('AC-5: after a normal request, http_requests_total appears in /metrics with value >= 1 (RED interceptor wired as APP_INTERCEPTOR)', async () => {
|
|
166
|
-
await tracer.startActiveSpan('ac5', async () => {
|
|
167
|
-
await request(app!.getHttpServer()).get('/test-route');
|
|
168
|
-
});
|
|
169
|
-
const res = await request(app!.getHttpServer()).get('/metrics');
|
|
170
|
-
expect(res.status).toBe(200);
|
|
171
|
-
expect(res.text).toContain('http_requests_total');
|
|
172
|
-
const lines = res.text
|
|
173
|
-
.split('\n')
|
|
174
|
-
.filter((l: string) => !l.startsWith('#') && l.includes('http_requests_total'));
|
|
175
|
-
const total = lines
|
|
176
|
-
.map((l: string) => parseFloat(l.split(' ').pop() ?? '0'))
|
|
177
|
-
.reduce((a: number, b: number) => a + b, 0);
|
|
178
|
-
expect(total).toBeGreaterThanOrEqual(1);
|
|
179
|
-
});
|
|
180
|
-
|
|
181
|
-
it('AC-6: TraceContextInterceptor is wired to RequestContextService and writes the active span\'s trace_id/span_id (APP_INTERCEPTOR bridge)', async () => {
|
|
182
|
-
const requestContext = app!.get(RequestContextService);
|
|
183
|
-
const interceptor = app!.get(TraceContextInterceptor);
|
|
184
|
-
expect(interceptor).toBeInstanceOf(TraceContextInterceptor);
|
|
185
|
-
|
|
186
|
-
// Drive the bridge through Nest's APP_INTERCEPTOR pipeline: send a real HTTP
|
|
187
|
-
// request through the wired app. Active OTel span comes from `tracer.startActiveSpan`
|
|
188
|
-
// wrapping the call (no HTTP auto-instrumentation in the test environment).
|
|
189
|
-
// nestjs-logging's ALS store — which `RequestContextService.set/get` reads —
|
|
190
|
-
// is normally initialised by nestjs-logging's ContextMiddleware at request
|
|
191
|
-
// time; we initialise it explicitly via `runWithContext({}, ...)` to mirror
|
|
192
|
-
// that, then read the keys back inside the same ALS frame.
|
|
193
|
-
await tracer.startActiveSpan('ac6', async (span) => {
|
|
194
|
-
const expectedTraceId = span.spanContext().traceId;
|
|
195
|
-
const expectedSpanId = span.spanContext().spanId;
|
|
196
|
-
let observedTraceId: string | undefined;
|
|
197
|
-
let observedSpanId: string | undefined;
|
|
198
|
-
await new Promise<void>((resolve, reject) => {
|
|
199
|
-
runWithContext({}, () => {
|
|
200
|
-
request(app!.getHttpServer())
|
|
201
|
-
.get('/test-route')
|
|
202
|
-
.end((err: unknown) => {
|
|
203
|
-
if (err) {
|
|
204
|
-
reject(err as Error);
|
|
205
|
-
return;
|
|
206
|
-
}
|
|
207
|
-
observedTraceId = requestContext.get('traceId') as string | undefined;
|
|
208
|
-
observedSpanId = requestContext.get('spanId') as string | undefined;
|
|
209
|
-
resolve();
|
|
210
|
-
});
|
|
211
|
-
});
|
|
212
|
-
});
|
|
213
|
-
expect(observedTraceId).toBe(expectedTraceId);
|
|
214
|
-
expect(observedSpanId).toBe(expectedSpanId);
|
|
215
|
-
});
|
|
216
|
-
|
|
217
|
-
// Sanity check that `app.get(TraceContextInterceptor)` returns the same
|
|
218
|
-
// instance the framework wired (no manual new TraceContextInterceptor() here).
|
|
219
|
-
expect(interceptor.intercept).toBeDefined();
|
|
220
|
-
expect(typeof interceptor.intercept).toBe('function');
|
|
221
|
-
});
|
|
222
|
-
|
|
223
|
-
it('AC-7: TraceService resolves from a module assembled by ObservabilityModule.register()', () => {
|
|
224
|
-
const svc = app!.get(TraceService);
|
|
225
|
-
expect(svc).toBeInstanceOf(TraceService);
|
|
226
|
-
expect(typeof svc.startActiveSpan).toBe('function');
|
|
227
|
-
});
|
|
228
|
-
});
|
|
229
|
-
});
|
|
@@ -1,224 +0,0 @@
|
|
|
1
|
-
import { afterEach, describe, expect, it, jest } from '@jest/globals';
|
|
2
|
-
|
|
3
|
-
const nodeSdkCtor = jest.fn();
|
|
4
|
-
const otlpCtor = jest.fn();
|
|
5
|
-
const consoleCtor = jest.fn();
|
|
6
|
-
const alwaysOnCtor = jest.fn();
|
|
7
|
-
const alwaysOffCtor = jest.fn();
|
|
8
|
-
const ratioCtor = jest.fn();
|
|
9
|
-
const resourceCtor = jest.fn();
|
|
10
|
-
const autoInstrumentations = jest.fn(() => ({ instrumentations: 'auto' }));
|
|
11
|
-
|
|
12
|
-
jest.mock('@opentelemetry/sdk-node', () => ({
|
|
13
|
-
NodeSDK: jest.fn().mockImplementation((config: unknown) => {
|
|
14
|
-
nodeSdkCtor(config);
|
|
15
|
-
return { start: jest.fn(), shutdown: jest.fn() };
|
|
16
|
-
}),
|
|
17
|
-
}));
|
|
18
|
-
|
|
19
|
-
jest.mock('@opentelemetry/exporter-trace-otlp-http', () => ({
|
|
20
|
-
OTLPTraceExporter: jest.fn().mockImplementation((config: unknown) => {
|
|
21
|
-
otlpCtor(config);
|
|
22
|
-
return { kind: 'otlp' };
|
|
23
|
-
}),
|
|
24
|
-
}));
|
|
25
|
-
|
|
26
|
-
jest.mock('@opentelemetry/sdk-trace-base', () => ({
|
|
27
|
-
ConsoleSpanExporter: jest.fn().mockImplementation(() => {
|
|
28
|
-
consoleCtor();
|
|
29
|
-
return { kind: 'console' };
|
|
30
|
-
}),
|
|
31
|
-
AlwaysOnSampler: jest.fn().mockImplementation(() => {
|
|
32
|
-
alwaysOnCtor();
|
|
33
|
-
return {
|
|
34
|
-
kind: 'on',
|
|
35
|
-
shouldSample: () => ({ decision: 2 }),
|
|
36
|
-
};
|
|
37
|
-
}),
|
|
38
|
-
AlwaysOffSampler: jest.fn().mockImplementation(() => {
|
|
39
|
-
alwaysOffCtor();
|
|
40
|
-
return {
|
|
41
|
-
kind: 'off',
|
|
42
|
-
shouldSample: () => ({ decision: 0 }),
|
|
43
|
-
};
|
|
44
|
-
}),
|
|
45
|
-
TraceIdRatioBasedSampler: jest.fn().mockImplementation((ratio: number) => {
|
|
46
|
-
ratioCtor(ratio);
|
|
47
|
-
return { kind: 'ratio', ratio, shouldSample: () => ({ decision: 1 }) };
|
|
48
|
-
}),
|
|
49
|
-
}));
|
|
50
|
-
|
|
51
|
-
jest.mock('@opentelemetry/resources', () => ({
|
|
52
|
-
resourceFromAttributes: jest.fn().mockImplementation((attrs: unknown) => {
|
|
53
|
-
resourceCtor(attrs);
|
|
54
|
-
return { kind: 'resource', attrs };
|
|
55
|
-
}),
|
|
56
|
-
}));
|
|
57
|
-
|
|
58
|
-
jest.mock('@opentelemetry/auto-instrumentations-node', () => ({
|
|
59
|
-
getNodeAutoInstrumentations: autoInstrumentations,
|
|
60
|
-
}));
|
|
61
|
-
|
|
62
|
-
const clearMocks = (): void => {
|
|
63
|
-
nodeSdkCtor.mockClear();
|
|
64
|
-
otlpCtor.mockClear();
|
|
65
|
-
consoleCtor.mockClear();
|
|
66
|
-
alwaysOnCtor.mockClear();
|
|
67
|
-
alwaysOffCtor.mockClear();
|
|
68
|
-
ratioCtor.mockClear();
|
|
69
|
-
resourceCtor.mockClear();
|
|
70
|
-
autoInstrumentations.mockClear();
|
|
71
|
-
};
|
|
72
|
-
|
|
73
|
-
afterEach(() => {
|
|
74
|
-
clearMocks();
|
|
75
|
-
jest.resetModules();
|
|
76
|
-
});
|
|
77
|
-
|
|
78
|
-
const loadBuildNodeSdk = () => {
|
|
79
|
-
let mod: typeof import('../../lib/tracing/init-tracing') | undefined;
|
|
80
|
-
jest.isolateModules(() => {
|
|
81
|
-
mod = require('../../lib/tracing/init-tracing');
|
|
82
|
-
});
|
|
83
|
-
if (!mod) throw new Error('init-tracing module not loaded');
|
|
84
|
-
return mod.buildNodeSdk;
|
|
85
|
-
};
|
|
86
|
-
|
|
87
|
-
describe('buildNodeSdk — exporter selection (AC-3, AC-4, AC-5)', () => {
|
|
88
|
-
it('AC-3: with exporter="console" configures a ConsoleSpanExporter', () => {
|
|
89
|
-
const buildNodeSdk = loadBuildNodeSdk();
|
|
90
|
-
buildNodeSdk({ serviceName: 'svc', exporter: 'console' });
|
|
91
|
-
|
|
92
|
-
expect(consoleCtor).toHaveBeenCalledTimes(1);
|
|
93
|
-
expect(otlpCtor).not.toHaveBeenCalled();
|
|
94
|
-
|
|
95
|
-
const config = nodeSdkCtor.mock.calls[0]?.[0] as {
|
|
96
|
-
traceExporter: unknown;
|
|
97
|
-
};
|
|
98
|
-
expect(config.traceExporter).toEqual({ kind: 'console' });
|
|
99
|
-
});
|
|
100
|
-
|
|
101
|
-
it('AC-4: with exporter="otlp" configures an OTLPTraceExporter targeting otlpUrl', () => {
|
|
102
|
-
const buildNodeSdk = loadBuildNodeSdk();
|
|
103
|
-
const otlpUrl = 'http://collector.example.com:4318/v1/traces';
|
|
104
|
-
buildNodeSdk({ serviceName: 'svc', exporter: 'otlp', otlpUrl });
|
|
105
|
-
|
|
106
|
-
expect(otlpCtor).toHaveBeenCalledTimes(1);
|
|
107
|
-
expect(otlpCtor).toHaveBeenCalledWith({ url: otlpUrl });
|
|
108
|
-
expect(consoleCtor).not.toHaveBeenCalled();
|
|
109
|
-
|
|
110
|
-
const config = nodeSdkCtor.mock.calls[0]?.[0] as {
|
|
111
|
-
traceExporter: unknown;
|
|
112
|
-
};
|
|
113
|
-
expect(config.traceExporter).toEqual({ kind: 'otlp' });
|
|
114
|
-
});
|
|
115
|
-
|
|
116
|
-
it('AC-5: with exporter="none" configures no exporter', () => {
|
|
117
|
-
const buildNodeSdk = loadBuildNodeSdk();
|
|
118
|
-
buildNodeSdk({ serviceName: 'svc', exporter: 'none' });
|
|
119
|
-
|
|
120
|
-
expect(consoleCtor).not.toHaveBeenCalled();
|
|
121
|
-
expect(otlpCtor).not.toHaveBeenCalled();
|
|
122
|
-
|
|
123
|
-
const config = nodeSdkCtor.mock.calls[0]?.[0] as {
|
|
124
|
-
traceExporter: unknown;
|
|
125
|
-
};
|
|
126
|
-
expect(config.traceExporter).toBeUndefined();
|
|
127
|
-
});
|
|
128
|
-
|
|
129
|
-
it('AC-4 (default): with no exporter specified, the OTLP exporter is used', () => {
|
|
130
|
-
const buildNodeSdk = loadBuildNodeSdk();
|
|
131
|
-
buildNodeSdk({ serviceName: 'svc', otlpUrl: 'http://collector.example.com:4318/v1/traces' });
|
|
132
|
-
|
|
133
|
-
expect(otlpCtor).toHaveBeenCalledTimes(1);
|
|
134
|
-
expect(consoleCtor).not.toHaveBeenCalled();
|
|
135
|
-
});
|
|
136
|
-
});
|
|
137
|
-
|
|
138
|
-
describe('buildNodeSdk — sampling configuration (AC-6, AC-7)', () => {
|
|
139
|
-
it('AC-6: with samplingRatio=0 the AlwaysOff sampler is selected and no spans are sampled', () => {
|
|
140
|
-
const buildNodeSdk = loadBuildNodeSdk();
|
|
141
|
-
buildNodeSdk({ serviceName: 'svc', samplingRatio: 0 });
|
|
142
|
-
|
|
143
|
-
expect(alwaysOffCtor).toHaveBeenCalledTimes(1);
|
|
144
|
-
expect(alwaysOnCtor).not.toHaveBeenCalled();
|
|
145
|
-
expect(ratioCtor).not.toHaveBeenCalled();
|
|
146
|
-
|
|
147
|
-
const config = nodeSdkCtor.mock.calls[0]?.[0] as {
|
|
148
|
-
sampler: { shouldSample: () => { decision: number } };
|
|
149
|
-
};
|
|
150
|
-
expect(config.sampler).toBeDefined();
|
|
151
|
-
const decision = config.sampler.shouldSample();
|
|
152
|
-
expect(decision.decision).toBe(0);
|
|
153
|
-
});
|
|
154
|
-
|
|
155
|
-
it('AC-7: with samplingRatio=1 the AlwaysOn sampler is selected and every span is sampled', () => {
|
|
156
|
-
const buildNodeSdk = loadBuildNodeSdk();
|
|
157
|
-
buildNodeSdk({ serviceName: 'svc', samplingRatio: 1 });
|
|
158
|
-
|
|
159
|
-
expect(alwaysOnCtor).toHaveBeenCalledTimes(1);
|
|
160
|
-
expect(alwaysOffCtor).not.toHaveBeenCalled();
|
|
161
|
-
expect(ratioCtor).not.toHaveBeenCalled();
|
|
162
|
-
|
|
163
|
-
const config = nodeSdkCtor.mock.calls[0]?.[0] as {
|
|
164
|
-
sampler: { shouldSample: () => { decision: number } };
|
|
165
|
-
};
|
|
166
|
-
expect(config.sampler).toBeDefined();
|
|
167
|
-
const decision = config.sampler.shouldSample();
|
|
168
|
-
expect(decision.decision).toBe(2);
|
|
169
|
-
});
|
|
170
|
-
|
|
171
|
-
it('with an intermediate samplingRatio the TraceIdRatioBasedSampler is used', () => {
|
|
172
|
-
const buildNodeSdk = loadBuildNodeSdk();
|
|
173
|
-
buildNodeSdk({ serviceName: 'svc', samplingRatio: 0.25 });
|
|
174
|
-
|
|
175
|
-
expect(ratioCtor).toHaveBeenCalledWith(0.25);
|
|
176
|
-
expect(alwaysOnCtor).not.toHaveBeenCalled();
|
|
177
|
-
expect(alwaysOffCtor).not.toHaveBeenCalled();
|
|
178
|
-
});
|
|
179
|
-
|
|
180
|
-
it('rejects NaN samplingRatio instead of forwarding it to TraceIdRatioBasedSampler', () => {
|
|
181
|
-
const buildNodeSdk = loadBuildNodeSdk();
|
|
182
|
-
expect(() => buildNodeSdk({ serviceName: 'svc', samplingRatio: NaN })).toThrow(
|
|
183
|
-
/samplingRatio must be a finite number in \[0, 1\]/,
|
|
184
|
-
);
|
|
185
|
-
|
|
186
|
-
expect(ratioCtor).not.toHaveBeenCalled();
|
|
187
|
-
});
|
|
188
|
-
});
|
|
189
|
-
|
|
190
|
-
describe('buildNodeSdk — resource & instrumentations wiring', () => {
|
|
191
|
-
it('attaches a Resource with service.name and the configured instrumentations set', () => {
|
|
192
|
-
const buildNodeSdk = loadBuildNodeSdk();
|
|
193
|
-
const instrumentations = [{ id: 'custom' }];
|
|
194
|
-
buildNodeSdk({
|
|
195
|
-
serviceName: 'svc',
|
|
196
|
-
instrumentations,
|
|
197
|
-
});
|
|
198
|
-
|
|
199
|
-
expect(resourceCtor).toHaveBeenCalledTimes(1);
|
|
200
|
-
expect(autoInstrumentations).not.toHaveBeenCalled();
|
|
201
|
-
|
|
202
|
-
const resourceAttrs = resourceCtor.mock.calls[0]?.[0] as {
|
|
203
|
-
[k: string]: string;
|
|
204
|
-
};
|
|
205
|
-
expect(resourceAttrs).toEqual({ 'service.name': 'svc' });
|
|
206
|
-
|
|
207
|
-
const config = nodeSdkCtor.mock.calls[0]?.[0] as {
|
|
208
|
-
resource: { kind: string; attrs: { [k: string]: string } };
|
|
209
|
-
instrumentations: unknown;
|
|
210
|
-
};
|
|
211
|
-
expect(config.resource).toEqual({
|
|
212
|
-
kind: 'resource',
|
|
213
|
-
attrs: { 'service.name': 'svc' },
|
|
214
|
-
});
|
|
215
|
-
expect(config.instrumentations).toBe(instrumentations);
|
|
216
|
-
});
|
|
217
|
-
|
|
218
|
-
it('uses auto-instrumentations when no instrumentations override is provided', () => {
|
|
219
|
-
const buildNodeSdk = loadBuildNodeSdk();
|
|
220
|
-
buildNodeSdk({ serviceName: 'svc' });
|
|
221
|
-
|
|
222
|
-
expect(autoInstrumentations).toHaveBeenCalledTimes(1);
|
|
223
|
-
});
|
|
224
|
-
});
|
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it, jest } from '@jest/globals';
|
|
2
|
-
import type { TracingBootstrapOptions } from '../../lib/interface';
|
|
3
|
-
|
|
4
|
-
type SdkLike = {
|
|
5
|
-
start: jest.Mock<() => void>;
|
|
6
|
-
shutdown: jest.Mock<() => Promise<void>>;
|
|
7
|
-
};
|
|
8
|
-
|
|
9
|
-
jest.mock('../../lib/tracing/shutdown', () => ({
|
|
10
|
-
registerShutdown: jest.fn(),
|
|
11
|
-
}));
|
|
12
|
-
|
|
13
|
-
describe('initTracing — idempotent start', () => {
|
|
14
|
-
it('AC-1: invokes the injected factory start exactly once on a single call', () => {
|
|
15
|
-
jest.isolateModules(() => {
|
|
16
|
-
const sdk: SdkLike = {
|
|
17
|
-
start: jest.fn<() => void>(),
|
|
18
|
-
shutdown: jest.fn<() => Promise<void>>().mockResolvedValue(undefined),
|
|
19
|
-
};
|
|
20
|
-
const sdkFactory = jest.fn((_opts: TracingBootstrapOptions) => sdk);
|
|
21
|
-
const { initTracing } = require('../../lib/tracing/init-tracing');
|
|
22
|
-
|
|
23
|
-
initTracing({ serviceName: 'svc' }, sdkFactory);
|
|
24
|
-
|
|
25
|
-
expect(sdkFactory).toHaveBeenCalledTimes(1);
|
|
26
|
-
expect(sdk.start).toHaveBeenCalledTimes(1);
|
|
27
|
-
});
|
|
28
|
-
});
|
|
29
|
-
|
|
30
|
-
it('AC-2: a second initTracing call in the same process does not start the SDK again', () => {
|
|
31
|
-
jest.isolateModules(() => {
|
|
32
|
-
const sdk: SdkLike = {
|
|
33
|
-
start: jest.fn<() => void>(),
|
|
34
|
-
shutdown: jest.fn<() => Promise<void>>().mockResolvedValue(undefined),
|
|
35
|
-
};
|
|
36
|
-
const sdkFactory = jest.fn((_opts: TracingBootstrapOptions) => sdk);
|
|
37
|
-
const { initTracing } = require('../../lib/tracing/init-tracing');
|
|
38
|
-
|
|
39
|
-
initTracing({ serviceName: 'svc' }, sdkFactory);
|
|
40
|
-
initTracing({ serviceName: 'svc' }, sdkFactory);
|
|
41
|
-
|
|
42
|
-
expect(sdkFactory).toHaveBeenCalledTimes(1);
|
|
43
|
-
expect(sdk.start).toHaveBeenCalledTimes(1);
|
|
44
|
-
});
|
|
45
|
-
});
|
|
46
|
-
|
|
47
|
-
it('AC-8: when the injected factory start throws, initTracing returns without throwing', () => {
|
|
48
|
-
jest.isolateModules(() => {
|
|
49
|
-
const sdk: SdkLike = {
|
|
50
|
-
start: jest.fn<() => void>(() => {
|
|
51
|
-
throw new Error('boom');
|
|
52
|
-
}),
|
|
53
|
-
shutdown: jest.fn<() => Promise<void>>().mockResolvedValue(undefined),
|
|
54
|
-
};
|
|
55
|
-
const sdkFactory = jest.fn((_opts: TracingBootstrapOptions) => sdk);
|
|
56
|
-
const { initTracing } = require('../../lib/tracing/init-tracing');
|
|
57
|
-
|
|
58
|
-
expect(() => initTracing({ serviceName: 'svc' }, sdkFactory)).not.toThrow();
|
|
59
|
-
|
|
60
|
-
expect(sdkFactory).toHaveBeenCalledTimes(1);
|
|
61
|
-
expect(sdk.start).toHaveBeenCalledTimes(1);
|
|
62
|
-
});
|
|
63
|
-
});
|
|
64
|
-
});
|
|
@@ -1,88 +0,0 @@
|
|
|
1
|
-
import { afterEach, beforeEach, describe, expect, it, jest } from '@jest/globals';
|
|
2
|
-
import type { TracingBootstrapOptions } from '../../lib/interface';
|
|
3
|
-
|
|
4
|
-
type ShutdownHandler = () => Promise<void> | void;
|
|
5
|
-
|
|
6
|
-
type SdkLike = {
|
|
7
|
-
start: jest.Mock<() => void>;
|
|
8
|
-
shutdown: jest.Mock<() => Promise<void>>;
|
|
9
|
-
};
|
|
10
|
-
|
|
11
|
-
const capturedHandlers: ShutdownHandler[] = [];
|
|
12
|
-
const registerShutdown = jest.fn((handler: ShutdownHandler) => {
|
|
13
|
-
capturedHandlers.push(handler);
|
|
14
|
-
});
|
|
15
|
-
|
|
16
|
-
jest.mock('../../lib/tracing/shutdown', () => ({
|
|
17
|
-
registerShutdown,
|
|
18
|
-
}));
|
|
19
|
-
|
|
20
|
-
const loadInitTracing = () => {
|
|
21
|
-
let mod: typeof import('../../lib/tracing/init-tracing') | undefined;
|
|
22
|
-
jest.isolateModules(() => {
|
|
23
|
-
mod = require('../../lib/tracing/init-tracing');
|
|
24
|
-
});
|
|
25
|
-
if (!mod) throw new Error('init-tracing module not loaded');
|
|
26
|
-
return mod.initTracing;
|
|
27
|
-
};
|
|
28
|
-
|
|
29
|
-
beforeEach(() => {
|
|
30
|
-
capturedHandlers.length = 0;
|
|
31
|
-
registerShutdown.mockClear();
|
|
32
|
-
jest.resetModules();
|
|
33
|
-
});
|
|
34
|
-
|
|
35
|
-
afterEach(() => {
|
|
36
|
-
jest.resetModules();
|
|
37
|
-
});
|
|
38
|
-
|
|
39
|
-
describe('initTracing — shutdown registration', () => {
|
|
40
|
-
it('AC-9: registered shutdown handler invokes sdk.shutdown exactly once', async () => {
|
|
41
|
-
const shutdown = jest
|
|
42
|
-
.fn<() => Promise<void>>()
|
|
43
|
-
.mockResolvedValue(undefined);
|
|
44
|
-
const sdk: SdkLike = {
|
|
45
|
-
start: jest.fn<() => void>(),
|
|
46
|
-
shutdown,
|
|
47
|
-
};
|
|
48
|
-
const sdkFactory = jest.fn((_opts: TracingBootstrapOptions) => sdk);
|
|
49
|
-
|
|
50
|
-
const initTracing = loadInitTracing();
|
|
51
|
-
|
|
52
|
-
initTracing({ serviceName: 'svc' }, sdkFactory);
|
|
53
|
-
|
|
54
|
-
expect(registerShutdown).toHaveBeenCalledTimes(1);
|
|
55
|
-
expect(capturedHandlers).toHaveLength(1);
|
|
56
|
-
|
|
57
|
-
await capturedHandlers[0]!();
|
|
58
|
-
|
|
59
|
-
expect(shutdown).toHaveBeenCalledTimes(1);
|
|
60
|
-
});
|
|
61
|
-
|
|
62
|
-
it('retries initTracing if registerShutdown throws on the first call', () => {
|
|
63
|
-
let failing = true;
|
|
64
|
-
(registerShutdown as jest.Mock).mockImplementation(() => {
|
|
65
|
-
if (failing) throw new Error('shutdown register blew up');
|
|
66
|
-
});
|
|
67
|
-
|
|
68
|
-
const sdk: SdkLike = {
|
|
69
|
-
start: jest.fn<() => void>(),
|
|
70
|
-
shutdown: jest.fn<() => Promise<void>>().mockResolvedValue(undefined),
|
|
71
|
-
};
|
|
72
|
-
const sdkFactory = jest.fn((_opts: TracingBootstrapOptions) => sdk);
|
|
73
|
-
|
|
74
|
-
const initTracing = loadInitTracing();
|
|
75
|
-
|
|
76
|
-
expect(() => initTracing({ serviceName: 'svc' }, sdkFactory)).not.toThrow();
|
|
77
|
-
expect(sdk.start).toHaveBeenCalledTimes(1);
|
|
78
|
-
|
|
79
|
-
failing = false;
|
|
80
|
-
(registerShutdown as jest.Mock).mockImplementation((handler: ShutdownHandler) => {
|
|
81
|
-
capturedHandlers.push(handler);
|
|
82
|
-
});
|
|
83
|
-
|
|
84
|
-
expect(() => initTracing({ serviceName: 'svc' }, sdkFactory)).not.toThrow();
|
|
85
|
-
expect(sdk.start).toHaveBeenCalledTimes(2);
|
|
86
|
-
expect(registerShutdown).toHaveBeenCalledTimes(2);
|
|
87
|
-
});
|
|
88
|
-
});
|