@nestjs/observe 0.3.3 → 0.3.5
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 +32 -0
- package/dist/.tsbuildinfo +1 -1
- package/dist/agent/observe-agent.shared-buffer.d.ts +3 -1
- package/dist/agent/observe-agent.shared-buffer.js +24 -3
- package/dist/agent/telemetry-wire-contract.js +26 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/instrument/create-instance-decorator.instrument.js +20 -4
- package/dist/interfaces/observe-options.interface.d.ts +16 -7
- package/dist/objectives/index.d.ts +1 -0
- package/dist/objectives/index.js +1 -0
- package/dist/objectives/objective.decorator.d.ts +59 -0
- package/dist/objectives/objective.decorator.js +102 -0
- package/dist/objectives/objectives.registry.d.ts +58 -0
- package/dist/objectives/objectives.registry.js +204 -0
- package/dist/observe.module.js +41 -5
- package/dist/utils/fit-service-version.util.d.ts +16 -0
- package/dist/utils/fit-service-version.util.js +32 -0
- package/dist/utils/infer-service-version.util.d.ts +15 -0
- package/dist/utils/infer-service-version.util.js +183 -0
- package/package.json +1 -1
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Counter, Gauge, Summary } from "../custom-metrics/index.js";
|
|
2
|
+
import { ObjectivesRegistry } from "../objectives/objectives.registry.js";
|
|
2
3
|
import { JobSnapshot } from "../interfaces/job-snapshot.interface.js";
|
|
3
4
|
import { NodeRuntimeMetrics } from "../interfaces/node-runtime-metrics.interface.js";
|
|
4
5
|
import { ObserveModuleOptionsWithDefaults } from "../interfaces/observe-options.interface.js";
|
|
@@ -44,6 +45,7 @@ interface BufferedLogEntry {
|
|
|
44
45
|
}
|
|
45
46
|
export declare class ObserveAgentSharedBuffer {
|
|
46
47
|
private readonly options;
|
|
48
|
+
private readonly objectivesRegistry?;
|
|
47
49
|
private readonly _sharedBuffer;
|
|
48
50
|
private readonly lock;
|
|
49
51
|
private readonly sharedBytes;
|
|
@@ -63,7 +65,7 @@ export declare class ObserveAgentSharedBuffer {
|
|
|
63
65
|
*/
|
|
64
66
|
private readonly _awaitingFlushAck;
|
|
65
67
|
get sharedBuffer(): SharedArrayBuffer;
|
|
66
|
-
constructor(options: ObserveModuleOptionsWithDefaults);
|
|
68
|
+
constructor(options: ObserveModuleOptionsWithDefaults, objectivesRegistry?: ObjectivesRegistry | undefined);
|
|
67
69
|
insertRequestSnapshot(snapshot: RequestSnapshot): void;
|
|
68
70
|
insertJobSnapshot(jobSnapshot: JobSnapshot): void;
|
|
69
71
|
/**
|
|
@@ -12,8 +12,9 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
12
12
|
};
|
|
13
13
|
var ObserveAgentSharedBuffer_1;
|
|
14
14
|
import { countTraceNodes, DEGRADED_TTL_MS, isNotableSnapshot, } from "./degraded-ingest.protocol.js";
|
|
15
|
-
import { Inject, Injectable, Logger } from "@nestjs/common";
|
|
15
|
+
import { Inject, Injectable, Logger, Optional } from "@nestjs/common";
|
|
16
16
|
import { Counter, Summary } from "../custom-metrics/index.js";
|
|
17
|
+
import { ObjectivesRegistry, } from "../objectives/objectives.registry.js";
|
|
17
18
|
import { CustomMetricsEncoder, } from "../encoders/custom-metrics.encoder.js";
|
|
18
19
|
import { JobSnapshotEncoder, } from "../encoders/job-snapshot.encoder.js";
|
|
19
20
|
import { RequestSnapshotEncoder, } from "../encoders/request-snapshot.encoder.js";
|
|
@@ -53,8 +54,11 @@ const TRUNCATION_SUFFIX = "... [truncated by observe]";
|
|
|
53
54
|
* process down with it is not.
|
|
54
55
|
*/
|
|
55
56
|
const MAX_PENDING_LOGS = 2000;
|
|
57
|
+
/** Declarations one batch carries at most - the collector's own limit. */
|
|
58
|
+
const MAX_OBJECTIVES_PER_BATCH = 100;
|
|
56
59
|
let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSharedBuffer {
|
|
57
60
|
options;
|
|
61
|
+
objectivesRegistry;
|
|
58
62
|
_sharedBuffer = new SharedArrayBuffer(SHARED_BUFFER_SIZE);
|
|
59
63
|
lock = new Int32Array(this._sharedBuffer, 0, 1);
|
|
60
64
|
sharedBytes = new Uint8Array(this._sharedBuffer);
|
|
@@ -76,8 +80,9 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
76
80
|
get sharedBuffer() {
|
|
77
81
|
return this._sharedBuffer;
|
|
78
82
|
}
|
|
79
|
-
constructor(options) {
|
|
83
|
+
constructor(options, objectivesRegistry) {
|
|
80
84
|
this.options = options;
|
|
85
|
+
this.objectivesRegistry = objectivesRegistry;
|
|
81
86
|
}
|
|
82
87
|
insertRequestSnapshot(snapshot) {
|
|
83
88
|
// A request can end before its route metadata is ever captured - an auth
|
|
@@ -114,6 +119,21 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
114
119
|
delete encodedSnapshot.t;
|
|
115
120
|
}
|
|
116
121
|
this._mainThreadBuffer.snapshots.push(encodedSnapshot);
|
|
122
|
+
// Read off the raw snapshot: the handler's span carries `Class.method`,
|
|
123
|
+
// which is what `@Objective` declarations are keyed by. Declarations are
|
|
124
|
+
// not telemetry, so they ride even a degraded batch - but a batch holds
|
|
125
|
+
// only as many as the collector accepts, and one that did not fit is left
|
|
126
|
+
// for a later request to bring due.
|
|
127
|
+
const objectives = (this._mainThreadBuffer.objectives ??= []);
|
|
128
|
+
if (objectives.length < MAX_OBJECTIVES_PER_BATCH) {
|
|
129
|
+
const declaration = this.objectivesRegistry?.declarationFor(snapshot);
|
|
130
|
+
if (declaration) {
|
|
131
|
+
objectives.push(declaration);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (objectives.length === 0) {
|
|
135
|
+
delete this._mainThreadBuffer.objectives;
|
|
136
|
+
}
|
|
117
137
|
}
|
|
118
138
|
insertJobSnapshot(jobSnapshot) {
|
|
119
139
|
if (!this._mainThreadBuffer) {
|
|
@@ -370,6 +390,7 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
370
390
|
ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = __decorate([
|
|
371
391
|
Injectable(),
|
|
372
392
|
__param(0, Inject(OBSERVE_OPTIONS)),
|
|
373
|
-
|
|
393
|
+
__param(1, Optional()),
|
|
394
|
+
__metadata("design:paramtypes", [Object, ObjectivesRegistry])
|
|
374
395
|
], ObserveAgentSharedBuffer);
|
|
375
396
|
export { ObserveAgentSharedBuffer };
|
|
@@ -149,6 +149,31 @@ const LOG_ENTRY = {
|
|
|
149
149
|
context: { type: "string" },
|
|
150
150
|
attributes: { type: "object" },
|
|
151
151
|
};
|
|
152
|
+
/** One `@Objective(...)` as a handler declares it. */
|
|
153
|
+
const DECLARED_OBJECTIVE = {
|
|
154
|
+
availability: { type: "number" },
|
|
155
|
+
latency: {
|
|
156
|
+
type: "object",
|
|
157
|
+
shape: {
|
|
158
|
+
underMs: { type: "number", required: true },
|
|
159
|
+
target: { type: "number", required: true },
|
|
160
|
+
},
|
|
161
|
+
},
|
|
162
|
+
windowDays: { type: "number" },
|
|
163
|
+
name: { type: "string" },
|
|
164
|
+
};
|
|
165
|
+
/** A handler's objectives, with the route it was seen to serve. */
|
|
166
|
+
const OBJECTIVE_DECLARATION = {
|
|
167
|
+
handler: { type: "string", required: true },
|
|
168
|
+
operationId: { type: "string", required: true },
|
|
169
|
+
method: { type: "string" },
|
|
170
|
+
objectives: {
|
|
171
|
+
type: "object",
|
|
172
|
+
array: true,
|
|
173
|
+
required: true,
|
|
174
|
+
shape: DECLARED_OBJECTIVE,
|
|
175
|
+
},
|
|
176
|
+
};
|
|
152
177
|
/** The batch body the agent POSTs to the collector. */
|
|
153
178
|
export const TELEMETRY_BATCH = {
|
|
154
179
|
serviceId: { type: "string", required: true },
|
|
@@ -159,6 +184,7 @@ export const TELEMETRY_BATCH = {
|
|
|
159
184
|
runtime: { type: "object", shape: RUNTIME_METRICS },
|
|
160
185
|
custom: { type: "object", array: true, shape: CUSTOM_METRIC },
|
|
161
186
|
logs: { type: "object", array: true, shape: LOG_ENTRY },
|
|
187
|
+
objectives: { type: "object", array: true, shape: OBJECTIVE_DECLARATION },
|
|
162
188
|
};
|
|
163
189
|
/**
|
|
164
190
|
* The sections of a batch whose entries are individually expendable. Maps each
|
package/dist/index.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ export * from "./custom-metrics/index.js";
|
|
|
2
2
|
export * from "./instrument/create-instance-decorator.instrument.js";
|
|
3
3
|
export * from "./interfaces/index.js";
|
|
4
4
|
export * from "./observe.constants.js";
|
|
5
|
+
export * from "./objectives/index.js";
|
|
5
6
|
export * from "./observe.module.js";
|
|
6
7
|
export * from "./services/index.js";
|
|
7
8
|
export * from "./trace-span.delegate.js";
|
package/dist/index.js
CHANGED
|
@@ -2,6 +2,7 @@ export * from "./custom-metrics/index.js";
|
|
|
2
2
|
export * from "./instrument/create-instance-decorator.instrument.js";
|
|
3
3
|
export * from "./interfaces/index.js";
|
|
4
4
|
export * from "./observe.constants.js";
|
|
5
|
+
export * from "./objectives/index.js";
|
|
5
6
|
export * from "./observe.module.js";
|
|
6
7
|
export * from "./services/index.js";
|
|
7
8
|
export * from "./trace-span.delegate.js";
|
|
@@ -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
|
|
@@ -169,13 +169,22 @@ export interface ObserveOptions {
|
|
|
169
169
|
*/
|
|
170
170
|
serviceId: string;
|
|
171
171
|
/**
|
|
172
|
-
*
|
|
173
|
-
*
|
|
174
|
-
*
|
|
175
|
-
*
|
|
176
|
-
*
|
|
177
|
-
|
|
178
|
-
|
|
172
|
+
* The release this process is running - what Releases, regressions and fix
|
|
173
|
+
* verification attribute a change to. A semantic version, a commit hash,
|
|
174
|
+
* anything that changes with each deploy.
|
|
175
|
+
*
|
|
176
|
+
* Leave it unset and the SDK infers one: `OBSERVE_SERVICE_VERSION` if the
|
|
177
|
+
* environment sets it, else the commit a hosting platform or CI job exposes
|
|
178
|
+
* (`VERCEL_GIT_COMMIT_SHA`, `RENDER_GIT_COMMIT`, `GITHUB_SHA`, ...), else the
|
|
179
|
+
* commit checked out where the process runs, else a container platform's
|
|
180
|
+
* revision name. `false` reports no release at all.
|
|
181
|
+
*
|
|
182
|
+
* At most 50 characters, the longest the collector accepts. A longer one is
|
|
183
|
+
* cut to fit, with a warning when the application starts: a commit keeps its
|
|
184
|
+
* first 50, anything else its first 41 and a hash of the whole, so two
|
|
185
|
+
* releases that differ only past the cut stay apart.
|
|
186
|
+
*/
|
|
187
|
+
serviceVersion?: string | false;
|
|
179
188
|
/**
|
|
180
189
|
* Interval in milliseconds at which the tracer submits traces to the Agent.
|
|
181
190
|
* The default value is 5000 milliseconds (5 seconds).
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./objective.decorator.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./objective.decorator.js";
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/** Where `@Objective` keeps what a handler declares. */
|
|
2
|
+
export declare const OBJECTIVES_METADATA = "observe:objectives";
|
|
3
|
+
/**
|
|
4
|
+
* A promise one route makes, stated next to the code that has to keep it.
|
|
5
|
+
*
|
|
6
|
+
* Declare either promise, or both; each becomes its own SLO in Observe, which
|
|
7
|
+
* then tracks its error budget, alerts on its burn rate, and checks releases
|
|
8
|
+
* against it - exactly as if it had been made in the dashboard, except that
|
|
9
|
+
* the code owns it: change it here and the next deploy updates the SLO.
|
|
10
|
+
*/
|
|
11
|
+
export interface ObjectiveOptions {
|
|
12
|
+
/**
|
|
13
|
+
* Percent of requests that must not fail with an unhandled error - `99.9`
|
|
14
|
+
* for three nines. Between 90 and 99.999.
|
|
15
|
+
*/
|
|
16
|
+
availability?: number;
|
|
17
|
+
/**
|
|
18
|
+
* Percent of requests (`target`) that must finish under `underMs`:
|
|
19
|
+
* `{ underMs: 300, target: 99 }` promises 99% under 300ms.
|
|
20
|
+
*/
|
|
21
|
+
latency?: {
|
|
22
|
+
underMs: number;
|
|
23
|
+
target: number;
|
|
24
|
+
};
|
|
25
|
+
/** The rolling window the promise is judged over, in days. Default 28. */
|
|
26
|
+
windowDays?: 7 | 14 | 28 | 30;
|
|
27
|
+
/** What the dashboard calls it. Defaults to the route and the promise. */
|
|
28
|
+
name?: string;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Declares an objective for this route.
|
|
32
|
+
*
|
|
33
|
+
* ```ts
|
|
34
|
+
* @Post()
|
|
35
|
+
* @Objective({ availability: 99.9, latency: { underMs: 300, target: 99 } })
|
|
36
|
+
* create(@Body() dto: CreateOrderDto) {}
|
|
37
|
+
* ```
|
|
38
|
+
*
|
|
39
|
+
* Nothing is sent at boot. The agent pairs the declaration with the route the
|
|
40
|
+
* handler actually serves on its first request - so a global prefix,
|
|
41
|
+
* versioning and RouterModule paths are always right - and reports it with the
|
|
42
|
+
* next batch. Applied more than once, every declaration counts.
|
|
43
|
+
*/
|
|
44
|
+
export declare function Objective(options: ObjectiveOptions): MethodDecorator;
|
|
45
|
+
/**
|
|
46
|
+
* Why a declaration cannot be sent, or nothing. Mirrors what the collector
|
|
47
|
+
* accepts: a batch carrying a declaration it refuses is refused whole, so a
|
|
48
|
+
* bad one has to be dropped - loudly - before it can cost any telemetry.
|
|
49
|
+
*/
|
|
50
|
+
export declare function objectiveProblems(options: ObjectiveOptions): string[];
|
|
51
|
+
/**
|
|
52
|
+
* Fields an objective carries that the collector does not declare. TypeScript
|
|
53
|
+
* catches them in an object literal, not in options built elsewhere - and the
|
|
54
|
+
* collector refuses a batch with one whole, so they are left out rather than
|
|
55
|
+
* sent.
|
|
56
|
+
*/
|
|
57
|
+
export declare function unknownObjectiveFields(options: ObjectiveOptions): string[];
|
|
58
|
+
/** An objective as it is sent: the fields the collector declares, and no others. */
|
|
59
|
+
export declare function toDeclaredObjective(options: ObjectiveOptions): ObjectiveOptions;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/** Where `@Objective` keeps what a handler declares. */
|
|
2
|
+
export const OBJECTIVES_METADATA = "observe:objectives";
|
|
3
|
+
/**
|
|
4
|
+
* Declares an objective for this route.
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* @Post()
|
|
8
|
+
* @Objective({ availability: 99.9, latency: { underMs: 300, target: 99 } })
|
|
9
|
+
* create(@Body() dto: CreateOrderDto) {}
|
|
10
|
+
* ```
|
|
11
|
+
*
|
|
12
|
+
* Nothing is sent at boot. The agent pairs the declaration with the route the
|
|
13
|
+
* handler actually serves on its first request - so a global prefix,
|
|
14
|
+
* versioning and RouterModule paths are always right - and reports it with the
|
|
15
|
+
* next batch. Applied more than once, every declaration counts.
|
|
16
|
+
*/
|
|
17
|
+
export function Objective(options) {
|
|
18
|
+
return (_target, _key, descriptor) => {
|
|
19
|
+
const declared = Reflect.getMetadata(OBJECTIVES_METADATA, descriptor.value) ?? [];
|
|
20
|
+
// Decorators apply bottom-up; prepending keeps them in the order written.
|
|
21
|
+
Reflect.defineMetadata(OBJECTIVES_METADATA, [options, ...declared], descriptor.value);
|
|
22
|
+
return descriptor;
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
/** The collector's own bounds, so a bad declaration is caught at boot. */
|
|
26
|
+
const MIN_TARGET = 90;
|
|
27
|
+
const MAX_TARGET = 99.999;
|
|
28
|
+
const WINDOW_DAYS = [7, 14, 28, 30];
|
|
29
|
+
const isTarget = (value) => typeof value === "number" && value >= MIN_TARGET && value <= MAX_TARGET;
|
|
30
|
+
/**
|
|
31
|
+
* Why a declaration cannot be sent, or nothing. Mirrors what the collector
|
|
32
|
+
* accepts: a batch carrying a declaration it refuses is refused whole, so a
|
|
33
|
+
* bad one has to be dropped - loudly - before it can cost any telemetry.
|
|
34
|
+
*/
|
|
35
|
+
export function objectiveProblems(options) {
|
|
36
|
+
const problems = [];
|
|
37
|
+
if (options.availability === undefined && options.latency === undefined) {
|
|
38
|
+
problems.push("declares neither availability nor latency");
|
|
39
|
+
}
|
|
40
|
+
if (options.availability !== undefined && !isTarget(options.availability)) {
|
|
41
|
+
problems.push(`availability must be a percentage from ${MIN_TARGET} to ${MAX_TARGET}`);
|
|
42
|
+
}
|
|
43
|
+
if (options.latency !== undefined) {
|
|
44
|
+
const { underMs, target } = options.latency;
|
|
45
|
+
if (!Number.isInteger(underMs) || underMs < 1 || underMs > 600_000) {
|
|
46
|
+
problems.push("latency.underMs must be whole milliseconds, up to 600000");
|
|
47
|
+
}
|
|
48
|
+
if (!isTarget(target)) {
|
|
49
|
+
problems.push(`latency.target must be a percentage from ${MIN_TARGET} to ${MAX_TARGET}`);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
if (options.windowDays !== undefined &&
|
|
53
|
+
!WINDOW_DAYS.includes(options.windowDays)) {
|
|
54
|
+
problems.push(`windowDays must be one of ${WINDOW_DAYS.join(", ")}`);
|
|
55
|
+
}
|
|
56
|
+
if (options.name !== undefined && options.name.length > 120) {
|
|
57
|
+
problems.push("name must be at most 120 characters");
|
|
58
|
+
}
|
|
59
|
+
return problems;
|
|
60
|
+
}
|
|
61
|
+
const OBJECTIVE_FIELDS = new Set([
|
|
62
|
+
"availability",
|
|
63
|
+
"latency",
|
|
64
|
+
"windowDays",
|
|
65
|
+
"name",
|
|
66
|
+
]);
|
|
67
|
+
const LATENCY_FIELDS = new Set(["underMs", "target"]);
|
|
68
|
+
/**
|
|
69
|
+
* Fields an objective carries that the collector does not declare. TypeScript
|
|
70
|
+
* catches them in an object literal, not in options built elsewhere - and the
|
|
71
|
+
* collector refuses a batch with one whole, so they are left out rather than
|
|
72
|
+
* sent.
|
|
73
|
+
*/
|
|
74
|
+
export function unknownObjectiveFields(options) {
|
|
75
|
+
const unknown = Object.keys(options).filter((field) => !OBJECTIVE_FIELDS.has(field));
|
|
76
|
+
if (options.latency && typeof options.latency === "object") {
|
|
77
|
+
unknown.push(...Object.keys(options.latency)
|
|
78
|
+
.filter((field) => !LATENCY_FIELDS.has(field))
|
|
79
|
+
.map((field) => `latency.${field}`));
|
|
80
|
+
}
|
|
81
|
+
return unknown;
|
|
82
|
+
}
|
|
83
|
+
/** An objective as it is sent: the fields the collector declares, and no others. */
|
|
84
|
+
export function toDeclaredObjective(options) {
|
|
85
|
+
return {
|
|
86
|
+
...(options.availability === undefined
|
|
87
|
+
? {}
|
|
88
|
+
: { availability: options.availability }),
|
|
89
|
+
...(options.latency === undefined
|
|
90
|
+
? {}
|
|
91
|
+
: {
|
|
92
|
+
latency: {
|
|
93
|
+
underMs: options.latency.underMs,
|
|
94
|
+
target: options.latency.target,
|
|
95
|
+
},
|
|
96
|
+
}),
|
|
97
|
+
...(options.windowDays === undefined
|
|
98
|
+
? {}
|
|
99
|
+
: { windowDays: options.windowDays }),
|
|
100
|
+
...(options.name === undefined ? {} : { name: options.name }),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { OnModuleInit } from "@nestjs/common";
|
|
2
|
+
import { DiscoveryService, MetadataScanner } from "@nestjs/core";
|
|
3
|
+
import { RequestSnapshot } from "../interfaces/request-snapshot.interface.js";
|
|
4
|
+
import { ObjectiveOptions } from "./objective.decorator.js";
|
|
5
|
+
/** One handler's objectives, with the route it was seen to serve. */
|
|
6
|
+
export interface ObjectiveDeclaration {
|
|
7
|
+
/** `OrdersController.create`. */
|
|
8
|
+
handler: string;
|
|
9
|
+
operationId: string;
|
|
10
|
+
method?: string;
|
|
11
|
+
objectives: ObjectiveOptions[];
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* What the application declares with `@Objective`, and the moment to say so.
|
|
15
|
+
*
|
|
16
|
+
* The decorators are read at boot, keyed by `Class.method` - the name a
|
|
17
|
+
* request's handler span carries. A route is not known until a request takes
|
|
18
|
+
* it, and taking it is the one way to know the route exactly as the
|
|
19
|
+
* collector will key it, prefix and version included. So each completed
|
|
20
|
+
* request is matched to a declaring handler, and the first match per route is
|
|
21
|
+
* handed to the batch being built.
|
|
22
|
+
*/
|
|
23
|
+
export declare class ObjectivesRegistry implements OnModuleInit {
|
|
24
|
+
private readonly discoveryService;
|
|
25
|
+
private readonly metadataScanner;
|
|
26
|
+
private readonly logger;
|
|
27
|
+
private readonly byHandler;
|
|
28
|
+
private readonly statedAt;
|
|
29
|
+
private readonly refusedRoutes;
|
|
30
|
+
constructor(discoveryService: DiscoveryService, metadataScanner: MetadataScanner);
|
|
31
|
+
onModuleInit(): void;
|
|
32
|
+
/**
|
|
33
|
+
* What of a handler's declarations the collector will take: each checked
|
|
34
|
+
* against its bounds, stripped to the fields it knows, and no more of them
|
|
35
|
+
* than it accepts for one handler. Everything left out is said at boot, once.
|
|
36
|
+
*/
|
|
37
|
+
private acceptedObjectives;
|
|
38
|
+
/**
|
|
39
|
+
* How many routes a handler is mounted on: its controller's paths, times its
|
|
40
|
+
* own, times the versions it answers. A declaration names one route, and
|
|
41
|
+
* the SLO it makes is the handler's, so a handler on several would move
|
|
42
|
+
* that SLO from route to route with every restatement.
|
|
43
|
+
*/
|
|
44
|
+
private routeCount;
|
|
45
|
+
private routedMethod;
|
|
46
|
+
get size(): number;
|
|
47
|
+
/**
|
|
48
|
+
* The declaration a completed request brings due, if any: its handler
|
|
49
|
+
* declares objectives, and this route has not been stated for them within
|
|
50
|
+
* the restatement interval.
|
|
51
|
+
*/
|
|
52
|
+
declarationFor(snapshot: RequestSnapshot, now?: number): ObjectiveDeclaration | undefined;
|
|
53
|
+
/**
|
|
54
|
+
* The declaring handler whose span sits nearest the root: the request's own
|
|
55
|
+
* handler, however many middlewares and interceptors wrap it.
|
|
56
|
+
*/
|
|
57
|
+
private handlerOf;
|
|
58
|
+
}
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
};
|
|
10
|
+
import { Injectable, Logger, RequestMethod, } from "@nestjs/common";
|
|
11
|
+
import { DiscoveryService, MetadataScanner } from "@nestjs/core";
|
|
12
|
+
import { OBJECTIVES_METADATA, objectiveProblems, toDeclaredObjective, unknownObjectiveFields, } from "./objective.decorator.js";
|
|
13
|
+
/**
|
|
14
|
+
* How often a declaration is restated while the process runs. Once per
|
|
15
|
+
* process covers every deploy; the restatement covers a batch that never
|
|
16
|
+
* arrived, so a dropped one costs an hour of the SLO, not a release.
|
|
17
|
+
*/
|
|
18
|
+
const RESTATE_EVERY_MS = 60 * 60 * 1000;
|
|
19
|
+
/**
|
|
20
|
+
* How many spans of a trace are searched for the handler's own. It sits under
|
|
21
|
+
* whatever wraps it - each class middleware, and each interceptor that awaits
|
|
22
|
+
* the handler, nests it one level deeper - but above everything it calls, so
|
|
23
|
+
* a breadth-first search meets it long before this.
|
|
24
|
+
*/
|
|
25
|
+
const MAX_SPANS_SEARCHED = 200;
|
|
26
|
+
/**
|
|
27
|
+
* The collector's bounds on a declaration. It validates a batch whole, so one
|
|
28
|
+
* declaration past any of them would cost every snapshot in the batch - and
|
|
29
|
+
* again at every restatement.
|
|
30
|
+
*/
|
|
31
|
+
const MAX_OBJECTIVES_PER_HANDLER = 10;
|
|
32
|
+
const MAX_HANDLER_LENGTH = 255;
|
|
33
|
+
const MAX_ROUTE_LENGTH = 255;
|
|
34
|
+
/** `@nestjs/common`'s METHOD_METADATA - what `@Get()`, `@Post()` and the rest write. */
|
|
35
|
+
const METHOD_METADATA = "method";
|
|
36
|
+
/** `@nestjs/common`'s PATH_METADATA and VERSION_METADATA, on the controller and the handler. */
|
|
37
|
+
const PATH_METADATA = "path";
|
|
38
|
+
const VERSION_METADATA = "__version__";
|
|
39
|
+
/** How many values a route decorator was given: an array's length, else one. */
|
|
40
|
+
const entries = (value) => Array.isArray(value) ? Math.max(value.length, 1) : 1;
|
|
41
|
+
/**
|
|
42
|
+
* What the application declares with `@Objective`, and the moment to say so.
|
|
43
|
+
*
|
|
44
|
+
* The decorators are read at boot, keyed by `Class.method` - the name a
|
|
45
|
+
* request's handler span carries. A route is not known until a request takes
|
|
46
|
+
* it, and taking it is the one way to know the route exactly as the
|
|
47
|
+
* collector will key it, prefix and version included. So each completed
|
|
48
|
+
* request is matched to a declaring handler, and the first match per route is
|
|
49
|
+
* handed to the batch being built.
|
|
50
|
+
*/
|
|
51
|
+
let ObjectivesRegistry = class ObjectivesRegistry {
|
|
52
|
+
discoveryService;
|
|
53
|
+
metadataScanner;
|
|
54
|
+
logger = new Logger("ObserveObjectives");
|
|
55
|
+
byHandler = new Map();
|
|
56
|
+
statedAt = new Map();
|
|
57
|
+
refusedRoutes = new Set();
|
|
58
|
+
constructor(discoveryService, metadataScanner) {
|
|
59
|
+
this.discoveryService = discoveryService;
|
|
60
|
+
this.metadataScanner = metadataScanner;
|
|
61
|
+
}
|
|
62
|
+
onModuleInit() {
|
|
63
|
+
for (const wrapper of this.discoveryService.getControllers()) {
|
|
64
|
+
const metatype = wrapper.metatype;
|
|
65
|
+
if (!metatype?.prototype) {
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
for (const methodName of this.metadataScanner.getAllMethodNames(metatype.prototype)) {
|
|
69
|
+
const handlerRef = metatype.prototype[methodName];
|
|
70
|
+
const declared = Reflect.getMetadata(OBJECTIVES_METADATA, handlerRef);
|
|
71
|
+
if (!declared?.length) {
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
const handler = `${metatype.name}.${methodName}`;
|
|
75
|
+
const routes = this.routeCount(metatype, handlerRef);
|
|
76
|
+
if (routes > 1) {
|
|
77
|
+
this.logger.warn(`@Objective on ${handler} ignored: it serves ${routes} routes, and an SLO watches one - give each route a handler of its own to declare it.`);
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
const objectives = this.acceptedObjectives(handler, declared);
|
|
81
|
+
if (objectives.length > 0) {
|
|
82
|
+
this.byHandler.set(handler, {
|
|
83
|
+
objectives,
|
|
84
|
+
method: this.routedMethod(handlerRef),
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* What of a handler's declarations the collector will take: each checked
|
|
92
|
+
* against its bounds, stripped to the fields it knows, and no more of them
|
|
93
|
+
* than it accepts for one handler. Everything left out is said at boot, once.
|
|
94
|
+
*/
|
|
95
|
+
acceptedObjectives(handler, declared) {
|
|
96
|
+
if (handler.length > MAX_HANDLER_LENGTH) {
|
|
97
|
+
this.logger.warn(`@Objective on ${handler} ignored: a handler name is at most ${MAX_HANDLER_LENGTH} characters.`);
|
|
98
|
+
return [];
|
|
99
|
+
}
|
|
100
|
+
const accepted = [];
|
|
101
|
+
for (const objective of declared) {
|
|
102
|
+
const problems = objectiveProblems(objective);
|
|
103
|
+
if (problems.length > 0) {
|
|
104
|
+
this.logger.warn(`@Objective on ${handler} ignored: ${problems.join("; ")}.`);
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
const unknown = unknownObjectiveFields(objective);
|
|
108
|
+
if (unknown.length > 0) {
|
|
109
|
+
this.logger.warn(`@Objective on ${handler}: ${unknown.join(", ")} not sent - an objective has availability, latency, windowDays and name.`);
|
|
110
|
+
}
|
|
111
|
+
accepted.push(toDeclaredObjective(objective));
|
|
112
|
+
}
|
|
113
|
+
if (accepted.length > MAX_OBJECTIVES_PER_HANDLER) {
|
|
114
|
+
this.logger.warn(`@Objective on ${handler}: only the first ${MAX_OBJECTIVES_PER_HANDLER} of ${accepted.length} are sent - a handler declares at most ${MAX_OBJECTIVES_PER_HANDLER}.`);
|
|
115
|
+
return accepted.slice(0, MAX_OBJECTIVES_PER_HANDLER);
|
|
116
|
+
}
|
|
117
|
+
return accepted;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* How many routes a handler is mounted on: its controller's paths, times its
|
|
121
|
+
* own, times the versions it answers. A declaration names one route, and
|
|
122
|
+
* the SLO it makes is the handler's, so a handler on several would move
|
|
123
|
+
* that SLO from route to route with every restatement.
|
|
124
|
+
*/
|
|
125
|
+
routeCount(metatype, handlerRef) {
|
|
126
|
+
const versions = Reflect.getMetadata(VERSION_METADATA, handlerRef) ??
|
|
127
|
+
Reflect.getMetadata(VERSION_METADATA, metatype);
|
|
128
|
+
return (entries(Reflect.getMetadata(PATH_METADATA, metatype)) *
|
|
129
|
+
entries(Reflect.getMetadata(PATH_METADATA, handlerRef)) *
|
|
130
|
+
entries(versions));
|
|
131
|
+
}
|
|
132
|
+
routedMethod(handlerRef) {
|
|
133
|
+
const routed = Reflect.getMetadata(METHOD_METADATA, handlerRef);
|
|
134
|
+
if (routed === undefined || routed === RequestMethod.ALL) {
|
|
135
|
+
return undefined;
|
|
136
|
+
}
|
|
137
|
+
return RequestMethod[routed];
|
|
138
|
+
}
|
|
139
|
+
get size() {
|
|
140
|
+
return this.byHandler.size;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* The declaration a completed request brings due, if any: its handler
|
|
144
|
+
* declares objectives, and this route has not been stated for them within
|
|
145
|
+
* the restatement interval.
|
|
146
|
+
*/
|
|
147
|
+
declarationFor(snapshot, now = Date.now()) {
|
|
148
|
+
if (this.byHandler.size === 0 || !snapshot.operationId) {
|
|
149
|
+
return undefined;
|
|
150
|
+
}
|
|
151
|
+
const handler = this.handlerOf(snapshot.traces);
|
|
152
|
+
if (!handler) {
|
|
153
|
+
return undefined;
|
|
154
|
+
}
|
|
155
|
+
const declared = this.byHandler.get(handler);
|
|
156
|
+
// Routed for one method: that one, whatever the request was - a HEAD
|
|
157
|
+
// probe of a GET route is still the GET route.
|
|
158
|
+
const method = declared.method ?? snapshot.attributes?.method;
|
|
159
|
+
const route = `${handler} ${method ?? ""} ${snapshot.operationId}`;
|
|
160
|
+
if (snapshot.operationId.length > MAX_ROUTE_LENGTH) {
|
|
161
|
+
if (!this.refusedRoutes.has(route)) {
|
|
162
|
+
this.refusedRoutes.add(route);
|
|
163
|
+
this.logger.warn(`@Objective on ${handler} not declared for a route longer than ${MAX_ROUTE_LENGTH} characters.`);
|
|
164
|
+
}
|
|
165
|
+
return undefined;
|
|
166
|
+
}
|
|
167
|
+
const stated = this.statedAt.get(route);
|
|
168
|
+
if (stated !== undefined && now - stated < RESTATE_EVERY_MS) {
|
|
169
|
+
return undefined;
|
|
170
|
+
}
|
|
171
|
+
this.statedAt.set(route, now);
|
|
172
|
+
return {
|
|
173
|
+
handler,
|
|
174
|
+
operationId: snapshot.operationId,
|
|
175
|
+
...(method ? { method } : {}),
|
|
176
|
+
objectives: declared.objectives,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* The declaring handler whose span sits nearest the root: the request's own
|
|
181
|
+
* handler, however many middlewares and interceptors wrap it.
|
|
182
|
+
*/
|
|
183
|
+
handlerOf(roots) {
|
|
184
|
+
const queue = [...(roots ?? [])];
|
|
185
|
+
for (let searched = 0; searched < queue.length; searched++) {
|
|
186
|
+
if (searched >= MAX_SPANS_SEARCHED) {
|
|
187
|
+
return undefined;
|
|
188
|
+
}
|
|
189
|
+
const node = queue[searched];
|
|
190
|
+
const key = `${node.className}.${node.methodKey}`;
|
|
191
|
+
if (this.byHandler.has(key)) {
|
|
192
|
+
return key;
|
|
193
|
+
}
|
|
194
|
+
queue.push(...(node.children ?? []));
|
|
195
|
+
}
|
|
196
|
+
return undefined;
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
ObjectivesRegistry = __decorate([
|
|
200
|
+
Injectable(),
|
|
201
|
+
__metadata("design:paramtypes", [DiscoveryService,
|
|
202
|
+
MetadataScanner])
|
|
203
|
+
], ObjectivesRegistry);
|
|
204
|
+
export { ObjectivesRegistry };
|