@nathapp/nestjs-observability 3.3.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.
- package/.eslintrc.js +8 -0
- package/.nax/features/nestjs-observability/.nax-acceptance.test.ts +797 -0
- package/.turbo/turbo-build.log +4 -0
- package/CHANGELOG.md +15 -0
- package/README.md +71 -0
- package/dist/constant/index.d.ts +1 -0
- package/dist/constant/index.js +18 -0
- package/dist/constant/index.js.map +1 -0
- package/dist/constant/observability.constants.d.ts +7 -0
- package/dist/constant/observability.constants.js +13 -0
- package/dist/constant/observability.constants.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +29 -0
- package/dist/index.js.map +1 -0
- package/dist/interface/index.d.ts +2 -0
- package/dist/interface/index.js +19 -0
- package/dist/interface/index.js.map +1 -0
- package/dist/interface/observability-module-options.interface.d.ts +26 -0
- package/dist/interface/observability-module-options.interface.js +3 -0
- package/dist/interface/observability-module-options.interface.js.map +1 -0
- package/dist/interface/tracing-bootstrap-options.interface.d.ts +7 -0
- package/dist/interface/tracing-bootstrap-options.interface.js +3 -0
- package/dist/interface/tracing-bootstrap-options.interface.js.map +1 -0
- package/dist/metrics/http-metrics.interceptor.d.ts +16 -0
- package/dist/metrics/http-metrics.interceptor.js +123 -0
- package/dist/metrics/http-metrics.interceptor.js.map +1 -0
- package/dist/metrics/index.d.ts +2 -0
- package/dist/metrics/index.js +11 -0
- package/dist/metrics/index.js.map +1 -0
- package/dist/metrics/metrics.providers.d.ts +6 -0
- package/dist/metrics/metrics.providers.js +81 -0
- package/dist/metrics/metrics.providers.js.map +1 -0
- package/dist/module/index.d.ts +1 -0
- package/dist/module/index.js +18 -0
- package/dist/module/index.js.map +1 -0
- package/dist/module/observability.module.d.ts +8 -0
- package/dist/module/observability.module.js +172 -0
- package/dist/module/observability.module.js.map +1 -0
- package/dist/tracing/index.d.ts +4 -0
- package/dist/tracing/index.js +21 -0
- package/dist/tracing/index.js.map +1 -0
- package/dist/tracing/init-tracing.d.ts +7 -0
- package/dist/tracing/init-tracing.js +72 -0
- package/dist/tracing/init-tracing.js.map +1 -0
- package/dist/tracing/shutdown.d.ts +2 -0
- package/dist/tracing/shutdown.js +19 -0
- package/dist/tracing/shutdown.js.map +1 -0
- package/dist/tracing/trace-context.interceptor.d.ts +8 -0
- package/dist/tracing/trace-context.interceptor.js +44 -0
- package/dist/tracing/trace-context.interceptor.js.map +1 -0
- package/dist/tracing/trace-internal.d.ts +3 -0
- package/dist/tracing/trace-internal.js +19 -0
- package/dist/tracing/trace-internal.js.map +1 -0
- package/dist/tracing/trace.decorator.d.ts +1 -0
- package/dist/tracing/trace.decorator.js +55 -0
- package/dist/tracing/trace.decorator.js.map +1 -0
- package/dist/tracing/trace.service.d.ts +5 -0
- package/dist/tracing/trace.service.js +55 -0
- package/dist/tracing/trace.service.js.map +1 -0
- package/lib/constant/index.ts +1 -0
- package/lib/constant/observability.constants.ts +21 -0
- package/lib/index.ts +17 -0
- package/lib/interface/index.ts +2 -0
- package/lib/interface/observability-module-options.interface.ts +47 -0
- package/lib/interface/tracing-bootstrap-options.interface.ts +17 -0
- package/lib/metrics/http-metrics.interceptor.ts +174 -0
- package/lib/metrics/index.ts +7 -0
- package/lib/metrics/metrics.providers.ts +134 -0
- package/lib/module/index.ts +1 -0
- package/lib/module/observability.module.ts +236 -0
- package/lib/tracing/index.ts +4 -0
- package/lib/tracing/init-tracing.ts +92 -0
- package/lib/tracing/shutdown.ts +28 -0
- package/lib/tracing/trace-context.interceptor.ts +42 -0
- package/lib/tracing/trace-internal.ts +19 -0
- package/lib/tracing/trace.decorator.ts +63 -0
- package/lib/tracing/trace.service.ts +48 -0
- package/package.json +60 -0
- package/test/jest-nax.json +27 -0
- package/test/jest-test.json +28 -0
- package/test/metrics/http-metrics.interceptor.spec.ts +453 -0
- package/test/metrics/metrics.providers.spec.ts +97 -0
- package/test/module/observability.module.spec.ts +229 -0
- package/test/tracing/build-node-sdk.spec.ts +224 -0
- package/test/tracing/init-tracing.idempotency.spec.ts +64 -0
- package/test/tracing/init-tracing.shutdown.spec.ts +88 -0
- package/test/tracing/shutdown.spec.ts +109 -0
- package/test/tracing/trace-context.interceptor.spec.ts +221 -0
- package/test/tracing/trace.decorator.spec.ts +153 -0
- package/test/tracing/trace.service.spec.ts +205 -0
- package/tsconfig.json +9 -0
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { ModuleMetadata, Type } from '@nestjs/common';
|
|
2
|
+
|
|
3
|
+
/** Metrics (Prometheus) options. Omit fields to accept the defaults. */
|
|
4
|
+
export interface MetricsOptions {
|
|
5
|
+
/** Enable the RED HTTP interceptor and the /metrics endpoint. Default true. */
|
|
6
|
+
enabled?: boolean;
|
|
7
|
+
/** Collect default Node/process metrics (prom-client). Default true. */
|
|
8
|
+
defaultMetrics?: boolean;
|
|
9
|
+
/** Prometheus scrape path. Default '/metrics'. */
|
|
10
|
+
path?: string;
|
|
11
|
+
/** Prefix applied to all metric names. Default '' (no prefix). */
|
|
12
|
+
prefix?: string;
|
|
13
|
+
/** Duration histogram buckets in seconds. Default DEFAULT_DURATION_BUCKETS. */
|
|
14
|
+
buckets?: number[];
|
|
15
|
+
/** Routes excluded from RED metrics (e.g. ['/metrics', '/health']). */
|
|
16
|
+
ignoreRoutes?: string[];
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** In-app tracing options (helpers + ALS bridge). The SDK itself is started by initTracing(). */
|
|
20
|
+
export interface TracingOptions {
|
|
21
|
+
/** Enable the trace-context interceptor and TraceService. Default true. */
|
|
22
|
+
enabled?: boolean;
|
|
23
|
+
/** Bridge the correlation id <-> active span both ways. Default true. */
|
|
24
|
+
correlationBridge?: boolean;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Override options for ObservabilityModule. */
|
|
28
|
+
export interface ObservabilityModuleOptions {
|
|
29
|
+
metrics?: MetricsOptions;
|
|
30
|
+
tracing?: TracingOptions;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Factory contract for the `useClass`/`useExisting` async path; method name matches the
|
|
34
|
+
* in-repo ConfigurableModuleBuilder default ('createOptions'). */
|
|
35
|
+
export interface ObservabilityModuleOptionsFactory {
|
|
36
|
+
createOptions(): Promise<ObservabilityModuleOptions> | ObservabilityModuleOptions;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Async registration options for ObservabilityModule. */
|
|
40
|
+
export interface ObservabilityAsyncModuleOptions extends Pick<ModuleMetadata, 'imports'> {
|
|
41
|
+
useExisting?: Type<ObservabilityModuleOptionsFactory>;
|
|
42
|
+
useClass?: Type<ObservabilityModuleOptionsFactory>;
|
|
43
|
+
useFactory?: (
|
|
44
|
+
...args: any[]
|
|
45
|
+
) => Promise<ObservabilityModuleOptions> | ObservabilityModuleOptions;
|
|
46
|
+
inject?: any[];
|
|
47
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Options for initTracing() — the pre-bootstrap OpenTelemetry NodeSDK setup. */
|
|
2
|
+
export interface TracingBootstrapOptions {
|
|
3
|
+
/** Logical service name reported on every span (OTel resource service.name). */
|
|
4
|
+
serviceName: string;
|
|
5
|
+
/** Span exporter. 'otlp' -> OTLP/HTTP, 'console' -> dev stdout, 'none' -> no export. Default 'otlp'. */
|
|
6
|
+
exporter?: 'otlp' | 'console' | 'none';
|
|
7
|
+
/** OTLP/HTTP endpoint used when exporter === 'otlp'. */
|
|
8
|
+
otlpUrl?: string;
|
|
9
|
+
/** Head sampling ratio in [0, 1]. Default 1.0 (sample everything). */
|
|
10
|
+
samplingRatio?: number;
|
|
11
|
+
/**
|
|
12
|
+
* Advanced: override the auto-instrumentation set. When omitted, the full
|
|
13
|
+
* `@opentelemetry/auto-instrumentations-node` default set is enabled (HTTP,
|
|
14
|
+
* express/fastify, and every other supported library instrumentation).
|
|
15
|
+
*/
|
|
16
|
+
instrumentations?: unknown[];
|
|
17
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CallHandler,
|
|
3
|
+
ExecutionContext,
|
|
4
|
+
HttpException,
|
|
5
|
+
Inject,
|
|
6
|
+
Injectable,
|
|
7
|
+
NestInterceptor,
|
|
8
|
+
Optional,
|
|
9
|
+
} from '@nestjs/common';
|
|
10
|
+
import { Observable } from 'rxjs';
|
|
11
|
+
import { catchError, tap } from 'rxjs/operators';
|
|
12
|
+
import {
|
|
13
|
+
PROM_METRIC_HTTP_REQUEST_DURATION_SECONDS,
|
|
14
|
+
PROM_METRIC_HTTP_REQUEST_ERRORS_TOTAL,
|
|
15
|
+
PROM_METRIC_HTTP_REQUESTS_TOTAL,
|
|
16
|
+
} from './metrics.providers';
|
|
17
|
+
|
|
18
|
+
interface HttpMetric {
|
|
19
|
+
inc?: (labels: Record<string, string>) => void;
|
|
20
|
+
observe?: (labels: Record<string, string>, value: number) => void;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
interface RequestLike {
|
|
24
|
+
method?: string;
|
|
25
|
+
url?: string;
|
|
26
|
+
route?: { path?: string };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
interface ResponseLike {
|
|
30
|
+
statusCode?: number;
|
|
31
|
+
raw?: { statusCode?: number };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const safeExecute = (fn: () => void): void => {
|
|
35
|
+
try {
|
|
36
|
+
fn();
|
|
37
|
+
} catch {
|
|
38
|
+
/* swallow — metric recording is best-effort */
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const stripQuery = (url: string): string => {
|
|
43
|
+
const qIndex = url.indexOf('?');
|
|
44
|
+
return qIndex === -1 ? url : url.slice(0, qIndex);
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
const resolveRoute = (request: RequestLike | undefined): string => {
|
|
48
|
+
const pattern = request?.route?.path;
|
|
49
|
+
if (pattern) {
|
|
50
|
+
return pattern;
|
|
51
|
+
}
|
|
52
|
+
const url = request?.url;
|
|
53
|
+
if (url) {
|
|
54
|
+
return stripQuery(url);
|
|
55
|
+
}
|
|
56
|
+
return 'UNKNOWN';
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const resolveStatus = (context: ExecutionContext, fallback = 200): number => {
|
|
60
|
+
try {
|
|
61
|
+
const response = context.switchToHttp().getResponse?.() as
|
|
62
|
+
| ResponseLike
|
|
63
|
+
| undefined;
|
|
64
|
+
if (response) {
|
|
65
|
+
if (typeof response.statusCode === 'number') {
|
|
66
|
+
return response.statusCode;
|
|
67
|
+
}
|
|
68
|
+
if (typeof response.raw?.statusCode === 'number') {
|
|
69
|
+
return response.raw.statusCode;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return fallback;
|
|
73
|
+
} catch {
|
|
74
|
+
return fallback;
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
const statusFromError = (err: unknown): number =>
|
|
79
|
+
err instanceof HttpException ? err.getStatus() : 500;
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* RED HTTP metrics interceptor: records request count, error count (status >= 500),
|
|
83
|
+
* and a duration histogram labelled method/route/status. Recording is best-effort —
|
|
84
|
+
* a metrics failure must never break the request. Routes listed in `ignoreRoutes`
|
|
85
|
+
* are passed through without any metric being incremented.
|
|
86
|
+
*
|
|
87
|
+
* Route identity: the `route` label prefers `request.route.path` (the NestJS route
|
|
88
|
+
* template, e.g. `/users/:id`) and falls back to `request.url` with the query
|
|
89
|
+
* string stripped (e.g. `/users?id=42` → `/users`). This keeps label cardinality
|
|
90
|
+
* bounded. As a consequence, `setIgnoreRoutes(['/users/:id'])` matches all concrete
|
|
91
|
+
* URLs under that template — entry strings must be route patterns, not URLs.
|
|
92
|
+
*
|
|
93
|
+
* Instantiation:
|
|
94
|
+
* - Direct: `new HttpMetricsInterceptor()`. Call `.setIgnoreRoutes([...])` to skip
|
|
95
|
+
* metrics on specific routes.
|
|
96
|
+
* - Via Nest DI: Nest resolves each prom-client metric instance under the
|
|
97
|
+
* `PROM_METRIC_HTTP_REQUESTS_TOTAL`, `PROM_METRIC_HTTP_REQUEST_ERRORS_TOTAL`, and
|
|
98
|
+
* `PROM_METRIC_HTTP_REQUEST_DURATION_SECONDS` tokens (all optional).
|
|
99
|
+
*
|
|
100
|
+
* Fastify compatibility: `resolveStatus` reads `response.statusCode`, falling back
|
|
101
|
+
* to `response.raw.statusCode` for the Fastify adapter.
|
|
102
|
+
*/
|
|
103
|
+
@Injectable()
|
|
104
|
+
export class HttpMetricsInterceptor implements NestInterceptor {
|
|
105
|
+
private ignoreRoutes: ReadonlySet<string> = new Set();
|
|
106
|
+
|
|
107
|
+
constructor(
|
|
108
|
+
@Optional() @Inject(PROM_METRIC_HTTP_REQUESTS_TOTAL)
|
|
109
|
+
private readonly requests?: HttpMetric,
|
|
110
|
+
@Optional() @Inject(PROM_METRIC_HTTP_REQUEST_ERRORS_TOTAL)
|
|
111
|
+
private readonly errors?: HttpMetric,
|
|
112
|
+
@Optional() @Inject(PROM_METRIC_HTTP_REQUEST_DURATION_SECONDS)
|
|
113
|
+
private readonly duration?: HttpMetric,
|
|
114
|
+
) {}
|
|
115
|
+
|
|
116
|
+
setIgnoreRoutes(routes: string[]): this {
|
|
117
|
+
this.ignoreRoutes = new Set(routes);
|
|
118
|
+
return this;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
|
122
|
+
if (context.getType() !== 'http') {
|
|
123
|
+
// Non-HTTP contexts (rpc, ws, graphql, etc.) have no HTTP request/response
|
|
124
|
+
// to inspect; skip HTTP metric recording instead of polluting metrics with
|
|
125
|
+
// UNKNOWN method/route and a defaulted 200 status.
|
|
126
|
+
return next.handle();
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const request = context.switchToHttp().getRequest<RequestLike>();
|
|
130
|
+
const method = request?.method ?? 'UNKNOWN';
|
|
131
|
+
const route = resolveRoute(request);
|
|
132
|
+
const startedAt = process.hrtime.bigint();
|
|
133
|
+
|
|
134
|
+
if (this.ignoreRoutes.has(route)) {
|
|
135
|
+
return next.handle();
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const elapsedSeconds = (): number => {
|
|
139
|
+
const ns = process.hrtime.bigint() - startedAt;
|
|
140
|
+
return Number(ns) / 1_000_000_000;
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
const recordRequests = (status: string): void => {
|
|
144
|
+
safeExecute(() => this.requests?.inc?.({ method, route, status }));
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
const recordDuration = (status: string): void => {
|
|
148
|
+
safeExecute(() =>
|
|
149
|
+
this.duration?.observe?.({ method, route, status }, elapsedSeconds()),
|
|
150
|
+
);
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
const recordErrors = (status: string): void => {
|
|
154
|
+
safeExecute(() => this.errors?.inc?.({ method, route, status }));
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
return next.handle().pipe(
|
|
158
|
+
tap(() => {
|
|
159
|
+
const status = String(resolveStatus(context));
|
|
160
|
+
recordRequests(status);
|
|
161
|
+
recordDuration(status);
|
|
162
|
+
}),
|
|
163
|
+
catchError((err: unknown) => {
|
|
164
|
+
const status = String(statusFromError(err));
|
|
165
|
+
recordRequests(status);
|
|
166
|
+
recordDuration(status);
|
|
167
|
+
if (Number(status) >= 500) {
|
|
168
|
+
recordErrors(status);
|
|
169
|
+
}
|
|
170
|
+
throw err;
|
|
171
|
+
}),
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import type { Provider } from '@nestjs/common';
|
|
2
|
+
import { Counter, Histogram } from 'prom-client';
|
|
3
|
+
import {
|
|
4
|
+
DEFAULT_DURATION_BUCKETS,
|
|
5
|
+
HTTP_REQUEST_DURATION_SECONDS,
|
|
6
|
+
HTTP_REQUEST_ERRORS_TOTAL,
|
|
7
|
+
HTTP_REQUESTS_TOTAL,
|
|
8
|
+
OBSERVABILITY_MODULE_OPTIONS,
|
|
9
|
+
} from '../constant';
|
|
10
|
+
import type { ObservabilityModuleOptions } from '../interface';
|
|
11
|
+
|
|
12
|
+
/** DI token under which HttpMetricsInterceptor looks up the requests counter. */
|
|
13
|
+
export const PROM_METRIC_HTTP_REQUESTS_TOTAL = 'PROM_METRIC_HTTP_REQUESTS_TOTAL';
|
|
14
|
+
|
|
15
|
+
/** DI token under which HttpMetricsInterceptor looks up the errors counter. */
|
|
16
|
+
export const PROM_METRIC_HTTP_REQUEST_ERRORS_TOTAL =
|
|
17
|
+
'PROM_METRIC_HTTP_REQUEST_ERRORS_TOTAL';
|
|
18
|
+
|
|
19
|
+
/** DI token under which HttpMetricsInterceptor looks up the duration histogram. */
|
|
20
|
+
export const PROM_METRIC_HTTP_REQUEST_DURATION_SECONDS =
|
|
21
|
+
'PROM_METRIC_HTTP_REQUEST_DURATION_SECONDS';
|
|
22
|
+
|
|
23
|
+
const METHOD_ROUTE_STATUS_LABELS = ['method', 'route', 'status'] as const;
|
|
24
|
+
|
|
25
|
+
type RedMetrics = {
|
|
26
|
+
requests: Counter<(typeof METHOD_ROUTE_STATUS_LABELS)[number]>;
|
|
27
|
+
errors: Counter<(typeof METHOD_ROUTE_STATUS_LABELS)[number]>;
|
|
28
|
+
duration: Histogram<(typeof METHOD_ROUTE_STATUS_LABELS)[number]>;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Constructs the three RED prom-client instances (requests total, errors total,
|
|
33
|
+
* duration histogram), honouring the configured prefix and histogram buckets. Shared
|
|
34
|
+
* by both the sync (`register`) and async (`registerAsync`) provider builders below
|
|
35
|
+
* so the metric names/help/labels are defined in exactly one place.
|
|
36
|
+
*/
|
|
37
|
+
function createRedMetrics(prefix: string, buckets: number[]): RedMetrics {
|
|
38
|
+
return {
|
|
39
|
+
requests: new Counter({
|
|
40
|
+
name: `${prefix}${HTTP_REQUESTS_TOTAL}`,
|
|
41
|
+
help: 'Total number of HTTP requests handled, labelled by method/route/status.',
|
|
42
|
+
labelNames: [...METHOD_ROUTE_STATUS_LABELS],
|
|
43
|
+
}),
|
|
44
|
+
errors: new Counter({
|
|
45
|
+
name: `${prefix}${HTTP_REQUEST_ERRORS_TOTAL}`,
|
|
46
|
+
help: 'Total number of HTTP requests that failed with status >= 500.',
|
|
47
|
+
labelNames: [...METHOD_ROUTE_STATUS_LABELS],
|
|
48
|
+
}),
|
|
49
|
+
duration: new Histogram({
|
|
50
|
+
name: `${prefix}${HTTP_REQUEST_DURATION_SECONDS}`,
|
|
51
|
+
help: 'HTTP request duration in seconds, labelled by method/route/status.',
|
|
52
|
+
labelNames: [...METHOD_ROUTE_STATUS_LABELS],
|
|
53
|
+
buckets: [...buckets],
|
|
54
|
+
}),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Builds the DI providers for the built-in RED metrics for the sync `register()` path,
|
|
60
|
+
* where the prefix/buckets are already resolved.
|
|
61
|
+
*
|
|
62
|
+
* Each provider is bound under a `PROM_METRIC_<NAME>` token and exposes the live
|
|
63
|
+
* prom-client Counter / Histogram instance (with `inc` / `observe` methods
|
|
64
|
+
* respectively). HttpMetricsInterceptor looks them up via the same tokens.
|
|
65
|
+
*/
|
|
66
|
+
export function buildRedMetricProviders(prefix: string, buckets: number[]): Provider[] {
|
|
67
|
+
const metrics = createRedMetrics(prefix, buckets);
|
|
68
|
+
return [
|
|
69
|
+
{ provide: PROM_METRIC_HTTP_REQUESTS_TOTAL, useValue: metrics.requests },
|
|
70
|
+
{ provide: PROM_METRIC_HTTP_REQUEST_ERRORS_TOTAL, useValue: metrics.errors },
|
|
71
|
+
{ provide: PROM_METRIC_HTTP_REQUEST_DURATION_SECONDS, useValue: metrics.duration },
|
|
72
|
+
];
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const resolveOptionsPrefix = (options: ObservabilityModuleOptions | undefined): string =>
|
|
76
|
+
options?.metrics?.prefix ?? '';
|
|
77
|
+
|
|
78
|
+
const resolveOptionsBuckets = (options: ObservabilityModuleOptions | undefined): number[] =>
|
|
79
|
+
options?.metrics?.buckets ?? DEFAULT_DURATION_BUCKETS;
|
|
80
|
+
|
|
81
|
+
const isOptionsMetricsEnabled = (options: ObservabilityModuleOptions | undefined): boolean =>
|
|
82
|
+
options?.metrics?.enabled !== false;
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Builds the DI providers for the built-in RED metrics for the `registerAsync()` path,
|
|
86
|
+
* where the prefix/buckets are only known once `OBSERVABILITY_MODULE_OPTIONS` resolves
|
|
87
|
+
* at DI time. Each token constructs only its own metric — sharing a single
|
|
88
|
+
* `createRedMetrics()` call across all three tokens would construct (and attempt to
|
|
89
|
+
* register) every metric three times over, once per token's factory invocation. When
|
|
90
|
+
* `metrics.enabled` resolves to `false`, each factory returns `undefined` instead of
|
|
91
|
+
* registering a metric, mirroring the sync `register()` path skipping registration
|
|
92
|
+
* entirely.
|
|
93
|
+
*/
|
|
94
|
+
export function buildRedMetricProvidersFromOptionsToken(): Provider[] {
|
|
95
|
+
return [
|
|
96
|
+
{
|
|
97
|
+
provide: PROM_METRIC_HTTP_REQUESTS_TOTAL,
|
|
98
|
+
inject: [OBSERVABILITY_MODULE_OPTIONS],
|
|
99
|
+
useFactory: (options: ObservabilityModuleOptions | undefined) =>
|
|
100
|
+
isOptionsMetricsEnabled(options)
|
|
101
|
+
? new Counter({
|
|
102
|
+
name: `${resolveOptionsPrefix(options)}${HTTP_REQUESTS_TOTAL}`,
|
|
103
|
+
help: 'Total number of HTTP requests handled, labelled by method/route/status.',
|
|
104
|
+
labelNames: [...METHOD_ROUTE_STATUS_LABELS],
|
|
105
|
+
})
|
|
106
|
+
: undefined,
|
|
107
|
+
},
|
|
108
|
+
{
|
|
109
|
+
provide: PROM_METRIC_HTTP_REQUEST_ERRORS_TOTAL,
|
|
110
|
+
inject: [OBSERVABILITY_MODULE_OPTIONS],
|
|
111
|
+
useFactory: (options: ObservabilityModuleOptions | undefined) =>
|
|
112
|
+
isOptionsMetricsEnabled(options)
|
|
113
|
+
? new Counter({
|
|
114
|
+
name: `${resolveOptionsPrefix(options)}${HTTP_REQUEST_ERRORS_TOTAL}`,
|
|
115
|
+
help: 'Total number of HTTP requests that failed with status >= 500.',
|
|
116
|
+
labelNames: [...METHOD_ROUTE_STATUS_LABELS],
|
|
117
|
+
})
|
|
118
|
+
: undefined,
|
|
119
|
+
},
|
|
120
|
+
{
|
|
121
|
+
provide: PROM_METRIC_HTTP_REQUEST_DURATION_SECONDS,
|
|
122
|
+
inject: [OBSERVABILITY_MODULE_OPTIONS],
|
|
123
|
+
useFactory: (options: ObservabilityModuleOptions | undefined) =>
|
|
124
|
+
isOptionsMetricsEnabled(options)
|
|
125
|
+
? new Histogram({
|
|
126
|
+
name: `${resolveOptionsPrefix(options)}${HTTP_REQUEST_DURATION_SECONDS}`,
|
|
127
|
+
help: 'HTTP request duration in seconds, labelled by method/route/status.',
|
|
128
|
+
labelNames: [...METHOD_ROUTE_STATUS_LABELS],
|
|
129
|
+
buckets: resolveOptionsBuckets(options),
|
|
130
|
+
})
|
|
131
|
+
: undefined,
|
|
132
|
+
},
|
|
133
|
+
];
|
|
134
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './observability.module';
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { DynamicModule, Module, Provider } from '@nestjs/common';
|
|
2
|
+
import { APP_INTERCEPTOR } from '@nestjs/core';
|
|
3
|
+
import { PrometheusModule } from '@willsoto/nestjs-prometheus';
|
|
4
|
+
import { ConfigurableModuleClass } from '@nathapp/nestjs-common';
|
|
5
|
+
import { RequestContextService } from '@nathapp/nestjs-logging';
|
|
6
|
+
import {
|
|
7
|
+
DEFAULT_DURATION_BUCKETS,
|
|
8
|
+
DEFAULT_METRICS_PATH,
|
|
9
|
+
OBSERVABILITY_MODULE_OPTIONS,
|
|
10
|
+
} from '../constant';
|
|
11
|
+
import {
|
|
12
|
+
ObservabilityAsyncModuleOptions,
|
|
13
|
+
ObservabilityModuleOptions,
|
|
14
|
+
} from '../interface';
|
|
15
|
+
import { HttpMetricsInterceptor } from '../metrics/http-metrics.interceptor';
|
|
16
|
+
import {
|
|
17
|
+
buildRedMetricProviders,
|
|
18
|
+
buildRedMetricProvidersFromOptionsToken,
|
|
19
|
+
PROM_METRIC_HTTP_REQUEST_DURATION_SECONDS,
|
|
20
|
+
PROM_METRIC_HTTP_REQUEST_ERRORS_TOTAL,
|
|
21
|
+
PROM_METRIC_HTTP_REQUESTS_TOTAL,
|
|
22
|
+
} from '../metrics/metrics.providers';
|
|
23
|
+
import { TraceContextInterceptor } from '../tracing/trace-context.interceptor';
|
|
24
|
+
import { TraceService } from '../tracing/trace.service';
|
|
25
|
+
|
|
26
|
+
const isTraceEnabled = (opts: ObservabilityModuleOptions | undefined): boolean =>
|
|
27
|
+
opts?.tracing?.enabled !== false;
|
|
28
|
+
|
|
29
|
+
const isMetricsEnabled = (opts: ObservabilityModuleOptions | undefined): boolean =>
|
|
30
|
+
opts?.metrics?.enabled !== false;
|
|
31
|
+
|
|
32
|
+
const isCorrelationBridgeEnabled = (opts: ObservabilityModuleOptions | undefined): boolean =>
|
|
33
|
+
opts?.tracing?.correlationBridge !== false;
|
|
34
|
+
|
|
35
|
+
const resolvePrefix = (opts: ObservabilityModuleOptions | undefined): string =>
|
|
36
|
+
opts?.metrics?.prefix ?? '';
|
|
37
|
+
|
|
38
|
+
const resolvePath = (opts: ObservabilityModuleOptions | undefined): string =>
|
|
39
|
+
opts?.metrics?.path ?? DEFAULT_METRICS_PATH;
|
|
40
|
+
|
|
41
|
+
const resolveBuckets = (opts: ObservabilityModuleOptions | undefined): number[] =>
|
|
42
|
+
opts?.metrics?.buckets ?? DEFAULT_DURATION_BUCKETS;
|
|
43
|
+
|
|
44
|
+
const resolveIgnoreRoutes = (opts: ObservabilityModuleOptions | undefined): string[] =>
|
|
45
|
+
opts?.metrics?.ignoreRoutes ?? [];
|
|
46
|
+
|
|
47
|
+
const buildPrometheusOptions = (opts: ObservabilityModuleOptions): {
|
|
48
|
+
path: string;
|
|
49
|
+
defaultMetrics: { enabled: boolean };
|
|
50
|
+
} => ({
|
|
51
|
+
path: resolvePath(opts),
|
|
52
|
+
defaultMetrics: { enabled: opts.metrics?.defaultMetrics !== false },
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Global module wiring Prometheus metrics + OTel trace helpers.
|
|
57
|
+
*
|
|
58
|
+
* Wires (per design): PrometheusModule (path/defaultMetrics), RED metric providers,
|
|
59
|
+
* HttpMetricsInterceptor + TraceContextInterceptor as APP_INTERCEPTORs, TraceService, and
|
|
60
|
+
* RequestContextService for the ALS bridge. Mirrors AuditModule's register/registerAsync.
|
|
61
|
+
*/
|
|
62
|
+
@Module({
|
|
63
|
+
providers: [TraceService, RequestContextService],
|
|
64
|
+
exports: [TraceService, RequestContextService],
|
|
65
|
+
})
|
|
66
|
+
export class ObservabilityModule extends ConfigurableModuleClass<ObservabilityModuleOptions>(
|
|
67
|
+
OBSERVABILITY_MODULE_OPTIONS,
|
|
68
|
+
) {
|
|
69
|
+
static register(options?: ObservabilityModuleOptions): DynamicModule {
|
|
70
|
+
const opts = options ?? {};
|
|
71
|
+
const base = super.register(opts);
|
|
72
|
+
const metricsEnabled = isMetricsEnabled(opts);
|
|
73
|
+
return {
|
|
74
|
+
...base,
|
|
75
|
+
module: ObservabilityModule,
|
|
76
|
+
global: true,
|
|
77
|
+
imports: [
|
|
78
|
+
...(metricsEnabled
|
|
79
|
+
? [PrometheusModule.register(buildPrometheusOptions(opts))]
|
|
80
|
+
: []),
|
|
81
|
+
...(base.imports ?? []),
|
|
82
|
+
],
|
|
83
|
+
providers: [
|
|
84
|
+
...(base.providers ?? []),
|
|
85
|
+
...(metricsEnabled
|
|
86
|
+
? buildRedMetricProviders(resolvePrefix(opts), resolveBuckets(opts))
|
|
87
|
+
: []),
|
|
88
|
+
...buildInterceptors(opts),
|
|
89
|
+
],
|
|
90
|
+
exports: [...(base.exports ?? [])],
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
static registerAsync(options: ObservabilityAsyncModuleOptions): DynamicModule {
|
|
95
|
+
if (!options.useFactory) {
|
|
96
|
+
throw new Error(
|
|
97
|
+
'ObservabilityModule.registerAsync requires `useFactory`. ' +
|
|
98
|
+
'`useClass` and `useExisting` are not supported.',
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
const base = super.registerAsync(options);
|
|
102
|
+
return {
|
|
103
|
+
...base,
|
|
104
|
+
module: ObservabilityModule,
|
|
105
|
+
global: true,
|
|
106
|
+
imports: [
|
|
107
|
+
PrometheusModule.registerAsync({
|
|
108
|
+
useFactory: async (...args: unknown[]) => {
|
|
109
|
+
const factoryOptions = await options.useFactory!(...args);
|
|
110
|
+
return isMetricsEnabled(factoryOptions)
|
|
111
|
+
? buildPrometheusOptions(factoryOptions)
|
|
112
|
+
: { path: DEFAULT_METRICS_PATH, defaultMetrics: { enabled: false } };
|
|
113
|
+
},
|
|
114
|
+
inject: options.inject ?? [],
|
|
115
|
+
}),
|
|
116
|
+
...(base.imports ?? []),
|
|
117
|
+
...(options.imports ?? []),
|
|
118
|
+
],
|
|
119
|
+
providers: [
|
|
120
|
+
...(base.providers ?? []),
|
|
121
|
+
...buildRedMetricProvidersFromOptionsToken(),
|
|
122
|
+
...buildInterceptorsAsync(),
|
|
123
|
+
],
|
|
124
|
+
exports: [...(base.exports ?? [])],
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Sync (register) path: options are resolved synchronously, so we build concrete
|
|
131
|
+
* Counter/Histogram instances using the resolved prefix/buckets, register
|
|
132
|
+
* HttpMetricsInterceptor + TraceContextInterceptor as regular providers (so
|
|
133
|
+
* consumers can also `app.get(...)` them), and expose them via APP_INTERCEPTOR.
|
|
134
|
+
*/
|
|
135
|
+
const buildInterceptors = (opts: ObservabilityModuleOptions): Provider[] => {
|
|
136
|
+
const providers: Provider[] = [];
|
|
137
|
+
|
|
138
|
+
if (isMetricsEnabled(opts)) {
|
|
139
|
+
providers.push({
|
|
140
|
+
provide: HttpMetricsInterceptor,
|
|
141
|
+
inject: [
|
|
142
|
+
PROM_METRIC_HTTP_REQUESTS_TOTAL,
|
|
143
|
+
PROM_METRIC_HTTP_REQUEST_ERRORS_TOTAL,
|
|
144
|
+
PROM_METRIC_HTTP_REQUEST_DURATION_SECONDS,
|
|
145
|
+
],
|
|
146
|
+
useFactory: (
|
|
147
|
+
requests: import('prom-client').Counter<string> | undefined,
|
|
148
|
+
errors: import('prom-client').Counter<string> | undefined,
|
|
149
|
+
duration: import('prom-client').Histogram<string> | undefined,
|
|
150
|
+
) => {
|
|
151
|
+
const interceptor = new HttpMetricsInterceptor(requests, errors, duration);
|
|
152
|
+
interceptor.setIgnoreRoutes(resolveIgnoreRoutes(opts));
|
|
153
|
+
return interceptor;
|
|
154
|
+
},
|
|
155
|
+
});
|
|
156
|
+
providers.push({
|
|
157
|
+
provide: APP_INTERCEPTOR,
|
|
158
|
+
useExisting: HttpMetricsInterceptor,
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
if (isTraceEnabled(opts) && isCorrelationBridgeEnabled(opts)) {
|
|
163
|
+
providers.push({
|
|
164
|
+
provide: TraceContextInterceptor,
|
|
165
|
+
inject: [RequestContextService],
|
|
166
|
+
useFactory: (context: RequestContextService) =>
|
|
167
|
+
new TraceContextInterceptor(context),
|
|
168
|
+
});
|
|
169
|
+
providers.push({
|
|
170
|
+
provide: APP_INTERCEPTOR,
|
|
171
|
+
useExisting: TraceContextInterceptor,
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return providers;
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Async (registerAsync) path: options are resolved via the injected factory at
|
|
180
|
+
* DI time. RED metrics + the two interceptors are all bound to factories that
|
|
181
|
+
* read OBSERVABILITY_MODULE_OPTIONS so the resolved values drive the wiring.
|
|
182
|
+
*
|
|
183
|
+
* Mirrors `buildInterceptors` (sync): when metrics or tracing are disabled, the
|
|
184
|
+
* class provider returns `null` from its factory so DI skips wiring an actual
|
|
185
|
+
* interceptor instance and APP_INTERCEPTOR registration has nothing to expose.
|
|
186
|
+
*/
|
|
187
|
+
const buildInterceptorsAsync = (): Provider[] => [
|
|
188
|
+
{
|
|
189
|
+
provide: HttpMetricsInterceptor,
|
|
190
|
+
inject: [
|
|
191
|
+
OBSERVABILITY_MODULE_OPTIONS,
|
|
192
|
+
PROM_METRIC_HTTP_REQUESTS_TOTAL,
|
|
193
|
+
PROM_METRIC_HTTP_REQUEST_ERRORS_TOTAL,
|
|
194
|
+
PROM_METRIC_HTTP_REQUEST_DURATION_SECONDS,
|
|
195
|
+
],
|
|
196
|
+
useFactory: (
|
|
197
|
+
options: ObservabilityModuleOptions | undefined,
|
|
198
|
+
requests: import('prom-client').Counter<string> | undefined,
|
|
199
|
+
errors: import('prom-client').Counter<string> | undefined,
|
|
200
|
+
duration: import('prom-client').Histogram<string> | undefined,
|
|
201
|
+
) => {
|
|
202
|
+
if (!isMetricsEnabled(options)) return null;
|
|
203
|
+
const interceptor = new HttpMetricsInterceptor(requests, errors, duration);
|
|
204
|
+
interceptor.setIgnoreRoutes(resolveIgnoreRoutes(options));
|
|
205
|
+
return interceptor;
|
|
206
|
+
},
|
|
207
|
+
},
|
|
208
|
+
{
|
|
209
|
+
provide: APP_INTERCEPTOR,
|
|
210
|
+
inject: [OBSERVABILITY_MODULE_OPTIONS, HttpMetricsInterceptor],
|
|
211
|
+
useFactory: (
|
|
212
|
+
options: ObservabilityModuleOptions | undefined,
|
|
213
|
+
interceptor: HttpMetricsInterceptor | null,
|
|
214
|
+
) => (isMetricsEnabled(options) ? interceptor : null),
|
|
215
|
+
},
|
|
216
|
+
{
|
|
217
|
+
provide: TraceContextInterceptor,
|
|
218
|
+
inject: [OBSERVABILITY_MODULE_OPTIONS, RequestContextService],
|
|
219
|
+
useFactory: (
|
|
220
|
+
options: ObservabilityModuleOptions | undefined,
|
|
221
|
+
context: RequestContextService,
|
|
222
|
+
) => {
|
|
223
|
+
if (!isTraceEnabled(options) || !isCorrelationBridgeEnabled(options)) return null;
|
|
224
|
+
return new TraceContextInterceptor(context);
|
|
225
|
+
},
|
|
226
|
+
},
|
|
227
|
+
{
|
|
228
|
+
provide: APP_INTERCEPTOR,
|
|
229
|
+
inject: [OBSERVABILITY_MODULE_OPTIONS, TraceContextInterceptor],
|
|
230
|
+
useFactory: (
|
|
231
|
+
options: ObservabilityModuleOptions | undefined,
|
|
232
|
+
interceptor: TraceContextInterceptor | null,
|
|
233
|
+
) =>
|
|
234
|
+
isTraceEnabled(options) && isCorrelationBridgeEnabled(options) ? interceptor : null,
|
|
235
|
+
},
|
|
236
|
+
];
|