@nestjs/observe 0.3.2 → 0.3.4

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.
@@ -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
- __metadata("design:paramtypes", [Object])
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";
@@ -169,13 +169,17 @@ export interface ObserveOptions {
169
169
  */
170
170
  serviceId: string;
171
171
  /**
172
- * Version of the service.
173
- * This can be used to track changes in the service over time.
174
- * It is optional and can be used to differentiate between different versions of the service.
175
- * For example, it could be a semantic version like "1.0.0"
176
- * or a commit hash like "abc123".
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.
177
181
  */
178
- serviceVersion?: string;
182
+ serviceVersion?: string | false;
179
183
  /**
180
184
  * Interval in milliseconds at which the tracer submits traces to the Agent.
181
185
  * The default value is 5000 milliseconds (5 seconds).
@@ -270,6 +274,40 @@ export interface ObserveOptions {
270
274
  */
271
275
  keepSlowest?: number;
272
276
  };
277
+ /**
278
+ * Reports an operation without its spans when it ends with one of these
279
+ * status codes - or, given a function, whenever that function returns true.
280
+ *
281
+ * Meant for outcomes that are part of an application's ordinary control
282
+ * flow: a `NotFoundException` for a record that does not exist, a 401 for an
283
+ * expired token, a 400 from a `ValidationPipe`. Every span is a metered
284
+ * event, and the waterfall behind a request that was turned away on purpose
285
+ * is rarely one anybody opens.
286
+ *
287
+ * The operation itself is still reported - its route, status code, duration,
288
+ * user and error - so it stays in every chart and on the Errors page, stack
289
+ * included. What is left behind is the span tree underneath it, manual spans
290
+ * too: the waterfall shows the operation with nothing inside it, and the
291
+ * calls it made are missing from the per-method numbers. That tree is the
292
+ * saving - each of its nodes is an event, so a skipped operation costs its
293
+ * own event (plus its error's, when it failed with one) and nothing more.
294
+ *
295
+ * The status code is the one the operation is reported with. Transports
296
+ * without one of their own - microservices, gRPC, WebSocket gateways -
297
+ * carry a status only when the handler threw: a Nest exception's own 4xx,
298
+ * 500 for anything else. So `[404]` also skips the spans of a message
299
+ * handler that threw `NotFoundException`. Jobs always keep their spans.
300
+ *
301
+ * Decided once the operation has finished, since the outcome is not known
302
+ * before: spans are still recorded while it runs, and dropped before
303
+ * anything is serialized or sent. A function that throws is reported once
304
+ * and read as "keep the spans".
305
+ *
306
+ * @example [400, 401, 403, 404]
307
+ * @example ({ statusCode, duration }) => statusCode === 404 && duration < 1000
308
+ * @default undefined - every operation ships its spans
309
+ */
310
+ skipSpans?: number[] | ((operation: SkipSpansContext) => boolean);
273
311
  /**
274
312
  * Whether to forward logs to the Observe APM.
275
313
  * If true, logs will be forwarded to the Agent for correlation with traces.
@@ -611,6 +649,34 @@ export interface JobContext {
611
649
  */
612
650
  id: string | undefined;
613
651
  }
652
+ /** What a `skipSpans` function is told about the operation that finished. */
653
+ export interface SkipSpansContext {
654
+ /**
655
+ * The transport, as reported: `http` or `https`, `graphql` for an operation
656
+ * that arrived without an HTTP request, `ws` for a gateway message, or the
657
+ * microservice transport's name (`TCP`, `GRPC`, ...).
658
+ */
659
+ protocol: string;
660
+ /**
661
+ * The route, message pattern, gateway pattern or GraphQL root field.
662
+ * Absent when none was resolved.
663
+ */
664
+ operationId: string | undefined;
665
+ /** The HTTP method. Absent off HTTP. */
666
+ method: string | undefined;
667
+ /**
668
+ * The status the operation is reported with. See `skipSpans` for where it
669
+ * comes from on transports that have none of their own.
670
+ */
671
+ statusCode: number | undefined;
672
+ /** How long the operation took, in milliseconds. */
673
+ duration: number;
674
+ /**
675
+ * Class name of the exception the operation failed with, e.g.
676
+ * `NotFoundException`. Absent when it did not fail with one.
677
+ */
678
+ errorClass: string | undefined;
679
+ }
614
680
  /** What a `ws` option hook is told about the message being handled. */
615
681
  export interface WsMessageContext {
616
682
  /** Class name of the gateway handling the message. */
@@ -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
+ }