@nestjs/observe 0.3.4 → 0.3.6
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/README.md +98 -5
- package/dist/agent/observe-agent.shared-buffer.js +7 -3
- package/dist/agent/telemetry-wire-contract.js +30 -12
- package/dist/custom-metrics/counter.d.ts +7 -3
- package/dist/custom-metrics/counter.js +34 -7
- package/dist/custom-metrics/finite-value.util.d.ts +20 -0
- package/dist/custom-metrics/finite-value.util.js +29 -0
- package/dist/custom-metrics/gauge.d.ts +2 -0
- package/dist/custom-metrics/gauge.js +31 -7
- package/dist/custom-metrics/summary.d.ts +5 -0
- package/dist/custom-metrics/summary.js +10 -3
- package/dist/encoders/custom-metrics.encoder.js +63 -1
- package/dist/encoders/trace.encoder.js +34 -0
- package/dist/instrument/create-instance-decorator.instrument.js +20 -4
- package/dist/interfaces/custom-metric.interface.d.ts +5 -0
- package/dist/interfaces/observe-options.interface.d.ts +28 -14
- package/dist/observe.module.js +36 -7
- package/dist/protocols/http-observe-agent.service.d.ts +13 -0
- package/dist/protocols/http-observe-agent.service.js +34 -8
- package/dist/protocols/rpc-observe-agent.service.js +0 -2
- package/dist/protocols/schedule-observe-agent.service.js +7 -3
- package/dist/services/node-runtime-metrics.service.d.ts +12 -0
- package/dist/services/node-runtime-metrics.service.js +95 -41
- package/dist/services/operation-trace.registry.js +0 -6
- package/dist/services/stdout-forwarder.service.js +2 -2
- package/dist/services/tracer.service.js +0 -3
- package/dist/utils/fit-service-version.util.d.ts +16 -0
- package/dist/utils/fit-service-version.util.js +26 -0
- package/dist/utils/fit-to-length.util.d.ts +10 -0
- package/dist/utils/fit-to-length.util.js +44 -0
- package/dist/utils/infer-service-version.util.js +9 -11
- package/package.json +5 -3
- package/dist/.tsbuildinfo +0 -1
|
@@ -1,4 +1,57 @@
|
|
|
1
|
+
import { fitToLength } from "../utils/fit-to-length.util.js";
|
|
1
2
|
import { remapKeys } from "./remap-keys.util.js";
|
|
3
|
+
/**
|
|
4
|
+
* The longest name, description and label the collector accepts, and the most
|
|
5
|
+
* labels. It refuses the whole batch over a longer one rather than cutting it,
|
|
6
|
+
* so each is cut to fit here, on the way out - the metric itself keeps what
|
|
7
|
+
* the application gave it, which is what its own label checks compare
|
|
8
|
+
* against. A counter's and a gauge's series keys are bounded where they are
|
|
9
|
+
* made, by `admitsSeries`; a summary's are its labels, and cut with them.
|
|
10
|
+
*/
|
|
11
|
+
const MAX_NAME_LENGTH = 100;
|
|
12
|
+
const MAX_DESCRIPTION_LENGTH = 255;
|
|
13
|
+
const MAX_LABEL_LENGTH = 255;
|
|
14
|
+
const MAX_LABELS = 1_000;
|
|
15
|
+
/**
|
|
16
|
+
* Each metric's cut fields, so each is reported once rather than on every
|
|
17
|
+
* flush. Bounded: past it, cuts still happen, silently.
|
|
18
|
+
*/
|
|
19
|
+
const reported = new Set();
|
|
20
|
+
const MAX_REPORTED = 100;
|
|
21
|
+
/** `value` cut to `maxLength`, reporting the first cut of this field for this metric. */
|
|
22
|
+
function fit(metricName, field, value, maxLength) {
|
|
23
|
+
const sent = fitToLength(value, maxLength);
|
|
24
|
+
const key = `${field}\u0000${metricName}`;
|
|
25
|
+
if (sent !== value && !reported.has(key) && reported.size < MAX_REPORTED) {
|
|
26
|
+
reported.add(key);
|
|
27
|
+
console.warn(`[observe] Custom metric "${metricName}" has a ${field} of ${value.length} characters, sent as "${sent}": ` +
|
|
28
|
+
`the collector takes at most ${maxLength} and refuses the whole batch over a longer one.`);
|
|
29
|
+
}
|
|
30
|
+
return sent;
|
|
31
|
+
}
|
|
32
|
+
/** At most `MAX_LABELS` labels, each cut to `MAX_LABEL_LENGTH`. */
|
|
33
|
+
function fitLabels(metricName, labels) {
|
|
34
|
+
if (labels.length <= MAX_LABELS &&
|
|
35
|
+
labels.every((label) => label.length <= MAX_LABEL_LENGTH)) {
|
|
36
|
+
return labels;
|
|
37
|
+
}
|
|
38
|
+
return labels
|
|
39
|
+
.slice(0, MAX_LABELS)
|
|
40
|
+
.map((label) => fit(metricName, "label", label, MAX_LABEL_LENGTH));
|
|
41
|
+
}
|
|
42
|
+
/** A summary's map, its label keys cut as `fitLabels` cuts the labels. */
|
|
43
|
+
function fitSummaryKeys(metricName, values) {
|
|
44
|
+
const keys = Object.keys(values);
|
|
45
|
+
if (keys.length <= MAX_LABELS &&
|
|
46
|
+
keys.every((key) => key.length <= MAX_LABEL_LENGTH)) {
|
|
47
|
+
return values;
|
|
48
|
+
}
|
|
49
|
+
const fitted = {};
|
|
50
|
+
for (const key of keys.slice(0, MAX_LABELS)) {
|
|
51
|
+
fitted[fit(metricName, "label", key, MAX_LABEL_LENGTH)] = values[key];
|
|
52
|
+
}
|
|
53
|
+
return fitted;
|
|
54
|
+
}
|
|
2
55
|
const CUSTOM_METRICS_KEY_MAP = {
|
|
3
56
|
name: "n",
|
|
4
57
|
type: "t",
|
|
@@ -59,10 +112,19 @@ export class CustomMetricsEncoder {
|
|
|
59
112
|
// exist, but the pairing is not something the compiler can follow
|
|
60
113
|
// through the indirection.
|
|
61
114
|
encoded[CUSTOM_METRICS_KEY_MAP[key]] =
|
|
62
|
-
value;
|
|
115
|
+
fitSummaryKeys(metric.name, value);
|
|
63
116
|
}
|
|
64
117
|
}
|
|
65
118
|
}
|
|
119
|
+
if (typeof encoded.n === "string") {
|
|
120
|
+
encoded.n = fit(metric.name, "name", encoded.n, MAX_NAME_LENGTH);
|
|
121
|
+
}
|
|
122
|
+
if (typeof encoded.d === "string") {
|
|
123
|
+
encoded.d = fit(metric.name, "description", encoded.d, MAX_DESCRIPTION_LENGTH);
|
|
124
|
+
}
|
|
125
|
+
if (Array.isArray(encoded.l)) {
|
|
126
|
+
encoded.l = fitLabels(metric.name, encoded.l);
|
|
127
|
+
}
|
|
66
128
|
return encoded;
|
|
67
129
|
}
|
|
68
130
|
}
|
|
@@ -1,4 +1,27 @@
|
|
|
1
|
+
import { fitToLength } from "../utils/fit-to-length.util.js";
|
|
1
2
|
import { remapKeys } from "./remap-keys.util.js";
|
|
3
|
+
/**
|
|
4
|
+
* The longest span name, class name and method name the collector accepts. It
|
|
5
|
+
* refuses the whole batch over a longer one rather than cutting it, so each is
|
|
6
|
+
* cut to fit here - the same way every time, so a span's numbers still add up
|
|
7
|
+
* under one name.
|
|
8
|
+
*/
|
|
9
|
+
const MAX_SPAN_TEXT_LENGTH = 255;
|
|
10
|
+
/** Whether a cut has been reported: once for the process, not per span. */
|
|
11
|
+
let reportedCut = false;
|
|
12
|
+
function fitSpanText(value) {
|
|
13
|
+
if (value.length <= MAX_SPAN_TEXT_LENGTH) {
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
const sent = fitToLength(value, MAX_SPAN_TEXT_LENGTH);
|
|
17
|
+
if (!reportedCut) {
|
|
18
|
+
reportedCut = true;
|
|
19
|
+
console.warn(`[observe] A span name, class name or method name of ${value.length} characters is sent as "${sent}": ` +
|
|
20
|
+
`the collector takes at most ${MAX_SPAN_TEXT_LENGTH} and refuses the whole batch over a longer one. ` +
|
|
21
|
+
`Others are cut the same way, without another warning.`);
|
|
22
|
+
}
|
|
23
|
+
return sent;
|
|
24
|
+
}
|
|
2
25
|
export const TRACE_KEY_MAP = {
|
|
3
26
|
name: "n",
|
|
4
27
|
origin: "o",
|
|
@@ -20,6 +43,17 @@ export const TRACE_KEY_MAP = {
|
|
|
20
43
|
*/
|
|
21
44
|
export function encodeTrace(trace) {
|
|
22
45
|
const encoded = remapKeys(trace, TRACE_KEY_MAP);
|
|
46
|
+
// Assigned only where present: a key added as `undefined` would change
|
|
47
|
+
// which keys a span carries.
|
|
48
|
+
if (typeof encoded.n === "string") {
|
|
49
|
+
encoded.n = fitSpanText(encoded.n);
|
|
50
|
+
}
|
|
51
|
+
if (typeof encoded.c === "string") {
|
|
52
|
+
encoded.c = fitSpanText(encoded.c);
|
|
53
|
+
}
|
|
54
|
+
if (typeof encoded.m === "string") {
|
|
55
|
+
encoded.m = fitSpanText(encoded.m);
|
|
56
|
+
}
|
|
23
57
|
// Outside the key remapping above, deliberately. Done inside that loop, every
|
|
24
58
|
// own key of a node re-encoded that node's whole subtree, so the work was
|
|
25
59
|
// keys^depth rather than one visit per node - a trace a few levels deeper
|
|
@@ -86,7 +86,7 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
86
86
|
const instrumentFunction = (fn) => {
|
|
87
87
|
// Classes are functions too, but calling one is a construction, not the
|
|
88
88
|
// kind of call this decorator traces.
|
|
89
|
-
if (
|
|
89
|
+
if (isConstructor(fn) || options.skipInstrumentation(fn)) {
|
|
90
90
|
return fn;
|
|
91
91
|
}
|
|
92
92
|
const methodName = fn.name || "anonymous";
|
|
@@ -161,7 +161,10 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
161
161
|
const attributeValue = Reflect.get(target, prop);
|
|
162
162
|
const isFunction = typeof attributeValue === "function" && prop !== "constructor";
|
|
163
163
|
const shouldProxy = isFunction &&
|
|
164
|
-
|
|
164
|
+
// A constructor held in a field - pg-pool's `this.Promise` - is
|
|
165
|
+
// invoked with `new` and read for statics (`this.Promise.reject`);
|
|
166
|
+
// the traced wrapper supports neither.
|
|
167
|
+
!isConstructor(attributeValue) &&
|
|
165
168
|
// A callable *object* - a Mongoose model, an Axios instance, an
|
|
166
169
|
// EventEmitter-backed client - is a field, not a method. The traced
|
|
167
170
|
// wrapper is a fresh bound function, so wrapping one silently drops
|
|
@@ -291,8 +294,21 @@ function relabelProxyFrame(err, className, methodName) {
|
|
|
291
294
|
function escapeRegExp(value) {
|
|
292
295
|
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
293
296
|
}
|
|
294
|
-
|
|
295
|
-
|
|
297
|
+
/**
|
|
298
|
+
* Whether a function is meant to be invoked with `new`: a `class`, or a
|
|
299
|
+
* constructor that predates the syntax - a built-in like `Promise`, or an
|
|
300
|
+
* ES5-style (or down-compiled) class - told apart by a `prototype` carrying
|
|
301
|
+
* members of its own. Methods have no `prototype` at all, and a plain
|
|
302
|
+
* `function` gets one holding only `constructor`.
|
|
303
|
+
*/
|
|
304
|
+
function isConstructor(value) {
|
|
305
|
+
if (/^\s*class\s+/.test(Function.prototype.toString.call(value))) {
|
|
306
|
+
return true;
|
|
307
|
+
}
|
|
308
|
+
const prototype = value.prototype;
|
|
309
|
+
return (typeof prototype === "object" &&
|
|
310
|
+
prototype !== null &&
|
|
311
|
+
Reflect.ownKeys(prototype).some((key) => key !== "constructor"));
|
|
296
312
|
}
|
|
297
313
|
/**
|
|
298
314
|
* The prototypes every ordinary function - plain, async, generator, async
|
|
@@ -4,6 +4,9 @@ export interface CustomMetric<TLabel extends string = "default"> {
|
|
|
4
4
|
* The name of the custom metric.
|
|
5
5
|
* This should be a descriptive name that identifies the metric.
|
|
6
6
|
* For example, "user_login_count" or "api_response_time".
|
|
7
|
+
*
|
|
8
|
+
* At most 100 characters reach the collector: a longer name is sent as its
|
|
9
|
+
* first 91 and a hash of the whole, with a warning.
|
|
7
10
|
*/
|
|
8
11
|
name: string;
|
|
9
12
|
/**
|
|
@@ -19,6 +22,7 @@ export interface CustomMetric<TLabel extends string = "default"> {
|
|
|
19
22
|
* Description for the custom metric.
|
|
20
23
|
* This can be used to provide additional context about what the metric represents.
|
|
21
24
|
* For example, "Number of user logins in the last hour" or "Average response time for API requests".
|
|
25
|
+
* At most 255 characters are sent; a longer one is cut the same way as a name.
|
|
22
26
|
*/
|
|
23
27
|
description?: string;
|
|
24
28
|
/**
|
|
@@ -34,6 +38,7 @@ export interface CustomMetric<TLabel extends string = "default"> {
|
|
|
34
38
|
* Optional labels for the custom metric.
|
|
35
39
|
* Labels are key-value pairs that can be used to add additional context to the metric.
|
|
36
40
|
* For example, you might use labels to indicate the environment (e.g., "production", "development") or the service (e.g., "user-service", "order-service").
|
|
41
|
+
* At most 1000 labels of at most 255 characters each are sent; a longer one is cut the same way as a name.
|
|
37
42
|
*/
|
|
38
43
|
labels?: TLabel[];
|
|
39
44
|
/**
|
|
@@ -166,6 +166,10 @@ export interface ObserveOptions {
|
|
|
166
166
|
* If you anticipate running multiple instances of the same service,
|
|
167
167
|
* consider using a unique identifier such as a hostname or container ID.
|
|
168
168
|
* This helps in distinguishing between different instances of the service in the APM.
|
|
169
|
+
*
|
|
170
|
+
* At most 100 characters, the longest the collector accepts. A longer one is
|
|
171
|
+
* cut to fit, with a warning when the application starts: its first 91 and a
|
|
172
|
+
* hash of the whole, so two ids that differ only past the cut stay apart.
|
|
169
173
|
*/
|
|
170
174
|
serviceId: string;
|
|
171
175
|
/**
|
|
@@ -178,6 +182,11 @@ export interface ObserveOptions {
|
|
|
178
182
|
* (`VERCEL_GIT_COMMIT_SHA`, `RENDER_GIT_COMMIT`, `GITHUB_SHA`, ...), else the
|
|
179
183
|
* commit checked out where the process runs, else a container platform's
|
|
180
184
|
* revision name. `false` reports no release at all.
|
|
185
|
+
*
|
|
186
|
+
* At most 50 characters, the longest the collector accepts. A longer one is
|
|
187
|
+
* cut to fit, with a warning when the application starts: a commit keeps its
|
|
188
|
+
* first 50, anything else its first 41 and a hash of the whole, so two
|
|
189
|
+
* releases that differ only past the cut stay apart.
|
|
181
190
|
*/
|
|
182
191
|
serviceVersion?: string | false;
|
|
183
192
|
/**
|
|
@@ -221,9 +230,11 @@ export interface ObserveOptions {
|
|
|
221
230
|
/**
|
|
222
231
|
* The sample rate for traces, which determines the percentage of traces that are sent to the Agent.
|
|
223
232
|
* A value of 1.0 means all traces are sent, while a value of 0.1 means 10% of traces are sent.
|
|
233
|
+
* A value of 0 reads as unset, so it sends every trace rather than none - pass
|
|
234
|
+
* `() => false` to send none.
|
|
224
235
|
* @default 1.0
|
|
225
236
|
*/
|
|
226
|
-
tracesSampleRate?: number | ((
|
|
237
|
+
tracesSampleRate?: number | ((protocol: "http" | "rpc" | "grpc" | "graphql" | "ws", attributes: any) => boolean);
|
|
227
238
|
/**
|
|
228
239
|
* Maximum number of traces per batch that can be sent to the Agent.
|
|
229
240
|
* This is useful for controlling the volume of traces sent, especially in high-traffic applications.
|
|
@@ -411,19 +422,21 @@ export interface ObserveOptions {
|
|
|
411
422
|
tags?: Record<string, string>;
|
|
412
423
|
/**
|
|
413
424
|
* A function to generate additional attributes for RPC requests.
|
|
414
|
-
* This function receives the
|
|
425
|
+
* This function receives the transport and the message context - the
|
|
426
|
+
* transport's own subclass, such as `NatsContext` or `KafkaContext` - and
|
|
427
|
+
* should return an object containing key-value pairs.
|
|
415
428
|
* These attributes can be retrieved later within the trace.
|
|
416
|
-
* @example (ctx) => ({
|
|
417
|
-
* @default (ctx) => ({})
|
|
429
|
+
* @example (transportId, ctx) => (ctx instanceof NatsContext ? { subject: ctx.getSubject() } : {})
|
|
430
|
+
* @default (transportId, ctx) => ({})
|
|
418
431
|
*/
|
|
419
432
|
setAttributes?: (transportId: Transport | symbol, ctx: BaseRpcContext) => {
|
|
420
433
|
[key: string]: string | number | boolean;
|
|
421
434
|
};
|
|
422
435
|
/**
|
|
423
|
-
* A function to associate a user identifier with the
|
|
424
|
-
* This function receives the
|
|
425
|
-
* If not provided, no user ID will be associated with the
|
|
426
|
-
* @example (transportId, ctx) => ctx.
|
|
436
|
+
* A function to associate a user identifier with the RPC message.
|
|
437
|
+
* This function receives the transport and the message context and should return a string representing the user ID.
|
|
438
|
+
* If not provided, no user ID will be associated with the message.
|
|
439
|
+
* @example (transportId, ctx) => (ctx instanceof NatsContext && ctx.getHeaders()?.get("user-id")) || 'anonymous'
|
|
427
440
|
* @default undefined
|
|
428
441
|
*/
|
|
429
442
|
getUserId?: (transportId: Transport | symbol, ctx: BaseRpcContext) => string;
|
|
@@ -503,19 +516,20 @@ export interface ObserveOptions {
|
|
|
503
516
|
tags?: Record<string, string>;
|
|
504
517
|
/**
|
|
505
518
|
* A function to generate additional attributes for gRPC requests.
|
|
506
|
-
* This function receives the gRPC call
|
|
519
|
+
* This function receives the gRPC call - its `request`, `metadata` and
|
|
520
|
+
* `operationId` - and should return an object containing key-value pairs.
|
|
507
521
|
* These attributes can be retrieved later within the trace.
|
|
508
|
-
* @example (call) => ({
|
|
522
|
+
* @example (call) => ({ operation: call.operationId })
|
|
509
523
|
* @default (call) => ({})
|
|
510
524
|
* */
|
|
511
525
|
setAttributes?: (call: any) => {
|
|
512
526
|
[key: string]: string | number | boolean;
|
|
513
527
|
};
|
|
514
528
|
/**
|
|
515
|
-
* A function to associate a user identifier with the
|
|
516
|
-
* This function receives the
|
|
517
|
-
* If not provided, no user ID will be associated with the
|
|
518
|
-
* @example (call) => call.metadata.
|
|
529
|
+
* A function to associate a user identifier with the gRPC call.
|
|
530
|
+
* This function receives the call and should return a string representing the user ID.
|
|
531
|
+
* If not provided, no user ID will be associated with the call.
|
|
532
|
+
* @example (call) => String(call.metadata.get('user-id')[0] ?? 'anonymous')
|
|
519
533
|
* @default undefined
|
|
520
534
|
*/
|
|
521
535
|
getUserId?: (call: any) => string;
|
package/dist/observe.module.js
CHANGED
|
@@ -36,6 +36,8 @@ import { TraceSamplerService } from "./services/trace-sampler.service.js";
|
|
|
36
36
|
import { TracerService } from "./services/tracer.service.js";
|
|
37
37
|
import { assertModuleOptions } from "./utils/assert-module-options.util.js";
|
|
38
38
|
import { defaultTraceIdGenerator } from "./utils/default-trace-id-generator.util.js";
|
|
39
|
+
import { fitServiceVersion, MAX_SERVICE_VERSION_LENGTH, } from "./utils/fit-service-version.util.js";
|
|
40
|
+
import { fitToLength } from "./utils/fit-to-length.util.js";
|
|
39
41
|
import { inferServiceVersion } from "./utils/infer-service-version.util.js";
|
|
40
42
|
import { LogRedactor } from "./utils/log-redactor.js";
|
|
41
43
|
/**
|
|
@@ -44,14 +46,41 @@ import { LogRedactor } from "./utils/log-redactor.js";
|
|
|
44
46
|
* otherwise try to resolve, which fails much later with no mention of why.
|
|
45
47
|
*/
|
|
46
48
|
const MISSING_ASYNC_OPTIONS_PROVIDER = 'ObserveModule.forRootAsync() requires one of "useFactory", "useClass" or "useExisting".';
|
|
49
|
+
/**
|
|
50
|
+
* The longest `serviceId` the collector accepts. It rides on every batch, and
|
|
51
|
+
* a longer one is not cut there: every batch would be refused.
|
|
52
|
+
*/
|
|
53
|
+
const MAX_SERVICE_ID_LENGTH = 100;
|
|
54
|
+
/**
|
|
55
|
+
* `serviceId`, cut to what the collector accepts the way a named release is,
|
|
56
|
+
* with a warning when the application starts.
|
|
57
|
+
*/
|
|
58
|
+
function withServiceId(options) {
|
|
59
|
+
const named = options.serviceId;
|
|
60
|
+
if (typeof named !== "string" || named.length <= MAX_SERVICE_ID_LENGTH) {
|
|
61
|
+
return options;
|
|
62
|
+
}
|
|
63
|
+
const sent = fitToLength(named, MAX_SERVICE_ID_LENGTH);
|
|
64
|
+
new Logger("ObserveModule").warn(`serviceId "${named}" is sent as "${sent}": the collector takes at most ${MAX_SERVICE_ID_LENGTH} characters.`);
|
|
65
|
+
return { ...options, serviceId: sent };
|
|
66
|
+
}
|
|
47
67
|
/**
|
|
48
68
|
* Names the release when the application did not, so Releases, regressions
|
|
49
69
|
* and fix verification work without anyone threading a version through the
|
|
50
70
|
* build. Resolved once, with the rest of the options: the answer cannot change
|
|
51
71
|
* while the process runs. `serviceVersion: false` opts out.
|
|
72
|
+
*
|
|
73
|
+
* A release the application names is cut to what the collector accepts, as
|
|
74
|
+
* an inferred one is - sent whole, it would cost every batch it rides in.
|
|
52
75
|
*/
|
|
53
76
|
function withServiceVersion(options) {
|
|
54
|
-
|
|
77
|
+
const named = options.serviceVersion;
|
|
78
|
+
if (typeof named === "string" && named.length > MAX_SERVICE_VERSION_LENGTH) {
|
|
79
|
+
const sent = fitServiceVersion(named);
|
|
80
|
+
new Logger("ObserveModule").warn(`serviceVersion "${named}" is sent as "${sent}": the collector takes at most ${MAX_SERVICE_VERSION_LENGTH} characters.`);
|
|
81
|
+
return { ...options, serviceVersion: sent };
|
|
82
|
+
}
|
|
83
|
+
if (named || named === false) {
|
|
55
84
|
return options;
|
|
56
85
|
}
|
|
57
86
|
const inferred = inferServiceVersion();
|
|
@@ -87,10 +116,10 @@ export function createObserveModule(options = {}) {
|
|
|
87
116
|
providers: [
|
|
88
117
|
{
|
|
89
118
|
provide: OBSERVE_OPTIONS,
|
|
90
|
-
useValue: withServiceVersion({
|
|
119
|
+
useValue: withServiceVersion(withServiceId({
|
|
91
120
|
...options,
|
|
92
121
|
...observeOpts,
|
|
93
|
-
}),
|
|
122
|
+
})),
|
|
94
123
|
},
|
|
95
124
|
],
|
|
96
125
|
};
|
|
@@ -129,10 +158,10 @@ export function createObserveModule(options = {}) {
|
|
|
129
158
|
provide: OBSERVE_OPTIONS,
|
|
130
159
|
useFactory: async (...args) => {
|
|
131
160
|
const opts = await useFactory(...args);
|
|
132
|
-
return withServiceVersion({
|
|
161
|
+
return withServiceVersion(withServiceId({
|
|
133
162
|
...options,
|
|
134
163
|
...opts,
|
|
135
|
-
});
|
|
164
|
+
}));
|
|
136
165
|
},
|
|
137
166
|
inject: asyncOptions.inject || [],
|
|
138
167
|
};
|
|
@@ -143,10 +172,10 @@ export function createObserveModule(options = {}) {
|
|
|
143
172
|
}
|
|
144
173
|
return {
|
|
145
174
|
provide: OBSERVE_OPTIONS,
|
|
146
|
-
useFactory: async (optionsFactory) => withServiceVersion({
|
|
175
|
+
useFactory: async (optionsFactory) => withServiceVersion(withServiceId({
|
|
147
176
|
...options,
|
|
148
177
|
...(await optionsFactory.createObserveOptions()),
|
|
149
|
-
}),
|
|
178
|
+
})),
|
|
150
179
|
inject: [optionsFactoryToken],
|
|
151
180
|
};
|
|
152
181
|
}
|
|
@@ -13,6 +13,8 @@ export declare class HttpObserveAgentService<Store extends Record<string, unknow
|
|
|
13
13
|
private readonly operationTraceRegistry;
|
|
14
14
|
private readonly observeAgentSharedBuffer;
|
|
15
15
|
private readonly traceSamplerService;
|
|
16
|
+
private readonly logger;
|
|
17
|
+
private warnedAboutHooks;
|
|
16
18
|
private httpAdapterInitSubscription;
|
|
17
19
|
/**
|
|
18
20
|
* `http.queryParamsObfuscateRegex`, rebuilt with the global flag when it was
|
|
@@ -54,5 +56,16 @@ export declare class HttpObserveAgentService<Store extends Record<string, unknow
|
|
|
54
56
|
* a shutting-down process open.
|
|
55
57
|
*/
|
|
56
58
|
private evictTraceOnClientAbort;
|
|
59
|
+
/**
|
|
60
|
+
* Whether the adapter has the hooks requests are traced through, warning
|
|
61
|
+
* the first time it does not.
|
|
62
|
+
*
|
|
63
|
+
* A missing framework hook is a no-op, never an error. Nest added all three
|
|
64
|
+
* in 11.1.4, and this used to throw from the constructor when one was absent
|
|
65
|
+
* - so an application on an earlier 11.x, inside the supported range, did
|
|
66
|
+
* not start at all. Without the hooks there is no request to attach a trace
|
|
67
|
+
* to, so the HTTP side stands aside and everything else is still reported.
|
|
68
|
+
*/
|
|
69
|
+
private hasRequestHooks;
|
|
57
70
|
private shouldIgnoreRequest;
|
|
58
71
|
}
|
|
@@ -10,7 +10,8 @@ var __metadata = (this && this.__metadata) || function (k, v) {
|
|
|
10
10
|
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
11
11
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
12
|
};
|
|
13
|
-
|
|
13
|
+
var HttpObserveAgentService_1;
|
|
14
|
+
import { Inject, Injectable, Logger, } from "@nestjs/common";
|
|
14
15
|
import { captureRequest, shouldCaptureRequest, } from "../utils/capture-request.util.js";
|
|
15
16
|
import { HttpAdapterHost } from "@nestjs/core";
|
|
16
17
|
import { AsyncLocalStorage } from "async_hooks";
|
|
@@ -26,13 +27,21 @@ import { uuidv7 } from "../utils/uuid-v7.util.js";
|
|
|
26
27
|
* next to a leak that never frees.
|
|
27
28
|
*/
|
|
28
29
|
const ABORTED_TRACE_EVICTION_GRACE_MS = 30_000;
|
|
29
|
-
|
|
30
|
+
/** The adapter hooks requests are traced through, all added in Nest 11.1.4. */
|
|
31
|
+
const REQUEST_HOOKS = [
|
|
32
|
+
"setOnRequestHook",
|
|
33
|
+
"setOnResponseHook",
|
|
34
|
+
"setOnRouteTriggered",
|
|
35
|
+
];
|
|
36
|
+
let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgentService {
|
|
30
37
|
httpAdapterHost;
|
|
31
38
|
asyncLocalStorage;
|
|
32
39
|
options;
|
|
33
40
|
operationTraceRegistry;
|
|
34
41
|
observeAgentSharedBuffer;
|
|
35
42
|
traceSamplerService;
|
|
43
|
+
logger = new Logger(HttpObserveAgentService_1.name);
|
|
44
|
+
warnedAboutHooks = false;
|
|
36
45
|
httpAdapterInitSubscription;
|
|
37
46
|
/**
|
|
38
47
|
* `http.queryParamsObfuscateRegex`, rebuilt with the global flag when it was
|
|
@@ -53,12 +62,9 @@ let HttpObserveAgentService = class HttpObserveAgentService {
|
|
|
53
62
|
// The "setOnRouteTriggered" hook must be set immediately
|
|
54
63
|
// to ensure that route metadata is captured correctly.
|
|
55
64
|
const { httpAdapter } = this.httpAdapterHost;
|
|
56
|
-
if (!httpAdapter) {
|
|
65
|
+
if (!httpAdapter || !this.hasRequestHooks(httpAdapter)) {
|
|
57
66
|
return;
|
|
58
67
|
}
|
|
59
|
-
if (!("setOnRouteTriggered" in httpAdapter)) {
|
|
60
|
-
throw new Error("The HTTP adapter does not support the 'setOnRouteTriggered' method. Please ensure you are using the latest version of the NestJS HTTP adapter that supports this method.");
|
|
61
|
-
}
|
|
62
68
|
httpAdapter.setOnRouteTriggered((requestMethod, path) => {
|
|
63
69
|
const store = this.asyncLocalStorage.getStore();
|
|
64
70
|
if (!store) {
|
|
@@ -82,7 +88,7 @@ let HttpObserveAgentService = class HttpObserveAgentService {
|
|
|
82
88
|
}
|
|
83
89
|
registerHttpHooks() {
|
|
84
90
|
const { httpAdapter } = this.httpAdapterHost;
|
|
85
|
-
if (!httpAdapter) {
|
|
91
|
+
if (!httpAdapter || !this.hasRequestHooks(httpAdapter)) {
|
|
86
92
|
return;
|
|
87
93
|
}
|
|
88
94
|
httpAdapter.setOnRequestHook((req, res, done) => {
|
|
@@ -212,6 +218,26 @@ let HttpObserveAgentService = class HttpObserveAgentService {
|
|
|
212
218
|
timer.unref?.();
|
|
213
219
|
});
|
|
214
220
|
}
|
|
221
|
+
/**
|
|
222
|
+
* Whether the adapter has the hooks requests are traced through, warning
|
|
223
|
+
* the first time it does not.
|
|
224
|
+
*
|
|
225
|
+
* A missing framework hook is a no-op, never an error. Nest added all three
|
|
226
|
+
* in 11.1.4, and this used to throw from the constructor when one was absent
|
|
227
|
+
* - so an application on an earlier 11.x, inside the supported range, did
|
|
228
|
+
* not start at all. Without the hooks there is no request to attach a trace
|
|
229
|
+
* to, so the HTTP side stands aside and everything else is still reported.
|
|
230
|
+
*/
|
|
231
|
+
hasRequestHooks(httpAdapter) {
|
|
232
|
+
if (REQUEST_HOOKS.every((hook) => hook in httpAdapter)) {
|
|
233
|
+
return true;
|
|
234
|
+
}
|
|
235
|
+
if (!this.warnedAboutHooks) {
|
|
236
|
+
this.warnedAboutHooks = true;
|
|
237
|
+
this.logger.warn("HTTP requests will not be traced: this HTTP adapter has no request hooks, which Nest added in 11.1.4. Upgrade @nestjs/core and your @nestjs/platform-* package to trace them.");
|
|
238
|
+
}
|
|
239
|
+
return false;
|
|
240
|
+
}
|
|
215
241
|
shouldIgnoreRequest(req) {
|
|
216
242
|
if (typeof this.options.http?.ignore === "function") {
|
|
217
243
|
return this.options.http.ignore(req);
|
|
@@ -237,7 +263,7 @@ let HttpObserveAgentService = class HttpObserveAgentService {
|
|
|
237
263
|
return false;
|
|
238
264
|
}
|
|
239
265
|
};
|
|
240
|
-
HttpObserveAgentService = __decorate([
|
|
266
|
+
HttpObserveAgentService = HttpObserveAgentService_1 = __decorate([
|
|
241
267
|
Injectable(),
|
|
242
268
|
__param(2, Inject(OBSERVE_OPTIONS)),
|
|
243
269
|
__metadata("design:paramtypes", [HttpAdapterHost,
|
|
@@ -120,7 +120,6 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
120
120
|
}
|
|
121
121
|
}
|
|
122
122
|
}
|
|
123
|
-
// setImmediate(() => {
|
|
124
123
|
if (this.options.rpc?.ignore?.(transportId, ctx)) {
|
|
125
124
|
return done();
|
|
126
125
|
}
|
|
@@ -137,7 +136,6 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
137
136
|
tags: this.options.rpc?.tags,
|
|
138
137
|
});
|
|
139
138
|
return done();
|
|
140
|
-
// });
|
|
141
139
|
});
|
|
142
140
|
}
|
|
143
141
|
startGrpcRequestTracing(transportId, call, done) {
|
|
@@ -71,12 +71,16 @@ let ScheduleObserveAgentService = ScheduleObserveAgentService_1 = class Schedule
|
|
|
71
71
|
* guarantee of landing before the explorer's `onModuleInit` has already
|
|
72
72
|
* wrapped every handler.
|
|
73
73
|
*/
|
|
74
|
-
loadScheduleExplorer(
|
|
74
|
+
loadScheduleExplorer(
|
|
75
|
+
// A parameter only so the specs can stand in for the package: the version
|
|
76
|
+
// installed here exports the explorer, which would otherwise leave the
|
|
77
|
+
// deep-path fallback below running in no test at all.
|
|
78
|
+
load = loadOptionalPeer) {
|
|
75
79
|
// The entry point is the supported source, but it only re-exports the
|
|
76
80
|
// explorer from 12.0.1 onwards; every earlier version keeps it behind a
|
|
77
81
|
// deep path. Try the public export first, then the file, so a supported
|
|
78
82
|
// import is preferred wherever one exists.
|
|
79
|
-
const entryPoint =
|
|
83
|
+
const entryPoint = load("@nestjs/schedule");
|
|
80
84
|
if (!entryPoint.installed) {
|
|
81
85
|
// Nothing scheduled, nothing to patch, and that is not a
|
|
82
86
|
// misconfiguration.
|
|
@@ -85,7 +89,7 @@ let ScheduleObserveAgentService = ScheduleObserveAgentService_1 = class Schedule
|
|
|
85
89
|
if (entryPoint.module?.ScheduleExplorer) {
|
|
86
90
|
return entryPoint.module.ScheduleExplorer;
|
|
87
91
|
}
|
|
88
|
-
const deepPath =
|
|
92
|
+
const deepPath = load("@nestjs/schedule", "@nestjs/schedule/dist/schedule.explorer.js");
|
|
89
93
|
if (deepPath.installed && deepPath.module?.ScheduleExplorer) {
|
|
90
94
|
return deepPath.module.ScheduleExplorer;
|
|
91
95
|
}
|
|
@@ -5,18 +5,30 @@ export declare class NodeRuntimeMetricsService implements OnModuleInit, OnApplic
|
|
|
5
5
|
private readonly options;
|
|
6
6
|
private readonly logger;
|
|
7
7
|
private eventLoopDelayMonitor;
|
|
8
|
+
/**
|
|
9
|
+
* The histogram's sample count and running sum of delays (ns) as of the
|
|
10
|
+
* previous sample, so that each sample reports its own window. Differenced
|
|
11
|
+
* rather than reset: `reset()` also forgets when the histogram last ticked,
|
|
12
|
+
* so a stall that started before its next tick - one in the same timers pass
|
|
13
|
+
* as a collection, say - was recorded in neither window. A double holds the
|
|
14
|
+
* sum to within a few nanoseconds even after a year of uptime.
|
|
15
|
+
*/
|
|
16
|
+
private lastDelayCount;
|
|
17
|
+
private lastDelayTotal;
|
|
8
18
|
private gcObserver;
|
|
9
19
|
private gcCount;
|
|
10
20
|
private gcTotalDuration;
|
|
11
21
|
private gcBreakdown;
|
|
12
22
|
private lastCpuUsage;
|
|
13
23
|
private lastCpuUsageTimestamp;
|
|
24
|
+
private lastEventLoopUtilization;
|
|
14
25
|
private osTotalMemory;
|
|
15
26
|
constructor(options: ObserveModuleOptionsWithDefaults);
|
|
16
27
|
onModuleInit(): void;
|
|
17
28
|
onApplicationShutdown(): Promise<void>;
|
|
18
29
|
monitorEventLoopDelay(): void;
|
|
19
30
|
observeGcPerformance(): void;
|
|
31
|
+
private recordGarbageCollection;
|
|
20
32
|
collectNodeRuntimeMetrics(): NodeRuntimeMetrics;
|
|
21
33
|
private resetGcMetrics;
|
|
22
34
|
private updateLastCpuUsage;
|