@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
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
<a href="https://observe.nestjs.com" target="_blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="NestJS Logo" /></a>
|
|
3
3
|
</p>
|
|
4
4
|
|
|
5
|
-
<p align="center">Auto-instrumented observability for <a href="https://nestjs.com" target="_blank">NestJS</a> applications — traces, errors, logs, jobs and
|
|
5
|
+
<p align="center">Auto-instrumented observability for <a href="https://nestjs.com" target="_blank">NestJS</a> applications — traces, errors, logs, jobs and runtime metrics, with no manual span wiring.</p>
|
|
6
6
|
|
|
7
7
|
<p align="center">
|
|
8
8
|
<a href="https://www.npmjs.com/package/@nestjs/observe"><img src="https://img.shields.io/npm/v/@nestjs/observe.svg" alt="NPM Version" /></a>
|
|
@@ -32,8 +32,11 @@ Install it, set two environment variables, and the application starts reporting:
|
|
|
32
32
|
- **Distributed traces** with per-span self time, correlated across services.
|
|
33
33
|
- **Errors**, grouped by fingerprint, with the source frame and the trace that
|
|
34
34
|
produced them.
|
|
35
|
-
- **Logs**, correlated to the request that wrote them
|
|
36
|
-
|
|
35
|
+
- **Logs**, correlated to the request that wrote them, once `forwardLogs` is
|
|
36
|
+
on.
|
|
37
|
+
- **Runtime metrics**, and the
|
|
38
|
+
[custom metrics](https://www.observe.nestjs.com/documentation/sdk#custom-metrics)
|
|
39
|
+
your code reports through `TracerService`.
|
|
37
40
|
|
|
38
41
|
Telemetry is serialised on a detached worker thread and shipped from there, so
|
|
39
42
|
the request path is untouched by the reporting.
|
|
@@ -243,9 +246,10 @@ Once the module and the instrument are in place, the agent reports, with no furt
|
|
|
243
246
|
|
|
244
247
|
- **Requests, GraphQL operations, RPC messages, WebSocket gateway messages, queue jobs and scheduled jobs**, each with its tree of provider method calls.
|
|
245
248
|
- **Database queries**, as a span under the method that ran them, for `pg`, `mysql2` and `mongodb`. Anything built on those drivers is covered without being known by name: TypeORM, Drizzle, MikroORM and Mongoose are tested in this repository, and others (Knex, Sequelize) go through the same driver calls. The statement is recorded with every value removed (`SELECT "o"."id" FROM "orders" "o" WHERE "o"."customer_id" = $1`). Prisma's Rust query engine does not go through these drivers and is not covered yet.
|
|
246
|
-
- **Outbound HTTP calls** made with `fetch`/`undici` or `node:http`/`https` (so Axios too), as `POST api.stripe.com`. The current trace id is forwarded as `x-request-id
|
|
249
|
+
- **Outbound HTTP calls** made with `fetch`/`undici` or `node:http`/`https` (so Axios too), as `POST api.stripe.com`. The current trace id is forwarded as `x-request-id` - by `fetch` on every supported Node version, by `node:http`/`https` from Node 22.12, the first to let a request's headers still be set at that point - so a service that also runs the agent continues the same trace; a header you set yourself is never overwritten.
|
|
247
250
|
- **Trace ids across queues**: a BullMQ (Pro included) or Bull job enqueued while handling a request carries that request's trace id, so the request and its job show up as one trace. Repeatable (cron) jobs start their own.
|
|
248
|
-
- **The
|
|
251
|
+
- **The code around an error's throw site**: for each in-app frame of a captured error, a few lines of source either side, read from the running process, so the dashboard shows the failing code next to the stack. This sends fragments of your application's source to Observe, stored with the error. Frames in `node_modules` and Node internals are never read. `createObserveModule({ sourceContext: false })` turns it off; the [documentation](https://www.observe.nestjs.com/documentation/sdk#error-source-context) covers tuning it instead.
|
|
252
|
+
- **The release it is running**, so Releases, regressions and fix verification work without a version threaded through the build: `OBSERVE_SERVICE_VERSION` if the environment sets it, else the commit a platform or CI job exposes (Vercel, Render, Railway, Heroku, GitHub Actions, GitLab CI and others), else the commit checked out where the process runs, else a Cloud Run or Azure Container Apps revision. A container image usually carries none of these, so hand it the commit at build time - `ARG GIT_SHA` then `ENV OBSERVE_SERVICE_VERSION=$GIT_SHA`. `serviceVersion` names the release yourself, in at most 50 characters - a longer one is cut to fit, with a warning at startup; `serviceVersion: false` reports none.
|
|
249
253
|
|
|
250
254
|
Query and outbound-HTTP spans are not billed as events. Turn them off with `outgoing: false`, or one side with `outgoing: { database: false }` / `outgoing: { http: false }`.
|
|
251
255
|
|
|
@@ -274,6 +278,78 @@ ObserveModule.forRoot({
|
|
|
274
278
|
|
|
275
279
|
A failed request is always captured (headers only, unless `body` is on); `capture: false` turns the feature off. Everything captured goes through the same redaction as error messages and logs before it leaves the process - sensitive keys by name, secrets by pattern - so naming `authorization` in `headers` records `[REDACTED]`.
|
|
276
280
|
|
|
281
|
+
## Declaring objectives in code
|
|
282
|
+
|
|
283
|
+
`@Objective()` states what a route promises, next to the handler that has to keep it, and Observe turns each promise into an [SLO](https://www.observe.nestjs.com/documentation/slos). The objective is written, reviewed and versioned with the route it covers:
|
|
284
|
+
|
|
285
|
+
```ts
|
|
286
|
+
import { Objective } from "@nestjs/observe";
|
|
287
|
+
|
|
288
|
+
@Controller("orders")
|
|
289
|
+
export class OrdersController {
|
|
290
|
+
@Post()
|
|
291
|
+
@Objective({ availability: 99.9, latency: { underMs: 300, target: 99 } })
|
|
292
|
+
create(@Body() dto: CreateOrderDto) {
|
|
293
|
+
return this.ordersService.create(dto);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
- `availability` - the percentage of requests that don't fail with an unhandled error: `99.9` for three nines.
|
|
299
|
+
- `latency` - `{ underMs, target }`: `target` percent of requests finish in under `underMs` milliseconds.
|
|
300
|
+
- `windowDays` - the rolling window it is judged over: 7, 14, 28 (the default) or 30 days.
|
|
301
|
+
- `name` - what the dashboard calls it, instead of the route and the promise.
|
|
302
|
+
|
|
303
|
+
Each promise becomes its own SLO, scoped to the application and the route: `POST /orders availability` and `POST /orders under 300ms` above. The route is read from the first request the handler serves, so a global prefix, URI versioning and `RouterModule` paths come out right, and the SLO appears once the route has had traffic. From then on:
|
|
304
|
+
|
|
305
|
+
- **The code owns it.** Change a target, a window or a name and deploy, and the same SLO follows. The dashboard marks it **in code**, names the handler and the release that last declared it, and doesn't edit it. A new latency threshold is a new promise, so it becomes a new SLO.
|
|
306
|
+
- **A delete in the dashboard doesn't last** while the decorator is there: the agent restates each route's objectives hourly, and a missing SLO is made again. To retire one, remove the decorator, then delete the SLO.
|
|
307
|
+
|
|
308
|
+
Declarations are checked when the application starts, and whatever fails is logged rather than sent. Targets run from 90 to 99.999, `underMs` is whole milliseconds up to 600000, and a handler carries at most ten objectives; a field other than these four is left out. A handler mounted on several routes - `@Get(["catalog", "products"])`, or a controller answering two versions - isn't declared at all, because an SLO watches one route: give each route a handler of its own.
|
|
309
|
+
|
|
310
|
+
SLOs need a plan that has them - Scale or Enterprise. On any other plan, declarations are sent and ignored. The [documentation](https://www.observe.nestjs.com/documentation/sdk#declaring-objectives-in-code) has the rest.
|
|
311
|
+
|
|
312
|
+
## Configuration
|
|
313
|
+
|
|
314
|
+
Every option, with its default. The [documentation](https://www.observe.nestjs.com/documentation/sdk) covers each in more depth.
|
|
315
|
+
|
|
316
|
+
`ObserveModule.forRoot()`, and the factory behind `forRootAsync()`, take:
|
|
317
|
+
|
|
318
|
+
| Option | Default | What it does |
|
|
319
|
+
| ------------------------ | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
320
|
+
| `appKey`, `appSecret` | required | The credentials the dashboard issues - see [Getting credentials](#getting-credentials). |
|
|
321
|
+
| `serviceId` | required | Names the service in the dashboard, in at most 100 characters - a longer one is cut to fit, with a warning at startup. |
|
|
322
|
+
| `serviceVersion` | inferred | The release the process runs, at most 50 characters - see [What it records without any code](#what-it-records-without-any-code). `false` reports none. |
|
|
323
|
+
| `endpoint` | `https://observe-api.nestjs.com` | The collector's base URL. `OBSERVE_ENDPOINT` in the environment changes the default without touching the config. |
|
|
324
|
+
| `flushInterval` | `5000` | Milliseconds between sends of buffered telemetry; at least `1000`. |
|
|
325
|
+
| `maxTracesPerBatch` | `1000` | The most traces one send carries. |
|
|
326
|
+
| `tracesSampleRate` | `1.0` | The share of traces kept, or a function `(protocol, attributes) => boolean` deciding per trace. `0` counts as unset and keeps every trace; `() => false` keeps none. |
|
|
327
|
+
| `spanCollapse` | `{ threshold: 20, keepSlowest: 3 }` | See [Repeated spans](#repeated-spans). `false` ships every span. |
|
|
328
|
+
| `skipSpans` | none | See [Skipping spans for expected outcomes](#skipping-spans-for-expected-outcomes). |
|
|
329
|
+
| `runtimeMetrics` | `true` | Samples memory, CPU, garbage collection and the event loop for the dashboard's [Profiler](https://www.observe.nestjs.com/documentation/profiler). |
|
|
330
|
+
| `runtimeMetricsInterval` | `60000` | Milliseconds between runtime samples; at least `30000`. |
|
|
331
|
+
| `forwardLogs` | `false` | Sends the application's log lines, each correlated to the trace it was written in - see [Logs](https://www.observe.nestjs.com/documentation/sdk#logs). |
|
|
332
|
+
| `redaction` | on | How log lines, error messages and captured requests are scrubbed before they leave the process: `enabled`, `useDefaultPatterns`, `patterns`, `keys` and `replacement`. |
|
|
333
|
+
| `outgoing` | on | Query and outbound-HTTP spans. `false` turns both off; `{ database: false }` or `{ http: false }` one of them. |
|
|
334
|
+
| `http` | | `ignore`, `tags`, `setAttributes`, `getUserId` and `queryParamsObfuscateRegex` for HTTP requests, and `capture` - see [Capturing failed and slow requests](#capturing-failed-and-slow-requests). |
|
|
335
|
+
| `rpc`, `grpc` | | `ignore`, `tags`, `setAttributes` and `getUserId` for microservice and gRPC handlers. |
|
|
336
|
+
| `graphql` | | The same four, once per GraphQL operation. |
|
|
337
|
+
| `ws` | | The same four, once per gateway message. |
|
|
338
|
+
| `jobs` | | `ignore`, `tags` and `setAttributes` for queue jobs and scheduled handlers. |
|
|
339
|
+
| `debug` | `false` | Logs the SDK's own diagnostics. |
|
|
340
|
+
|
|
341
|
+
`forRootAsync()` also takes `extraProviders`, and `global`, which defaults to `true` - `forRoot()` always registers the module globally.
|
|
342
|
+
|
|
343
|
+
`createObserveModule()` takes the options the instrumentation needs before any module exists:
|
|
344
|
+
|
|
345
|
+
| Option | Default | What it does |
|
|
346
|
+
| --------------------- | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
347
|
+
| `sourceContext` | `true` | Attaches the source around each in-app frame of a captured error - see [What it records without any code](#what-it-records-without-any-code). `{ linesOfContext, maxFrames, sourceMaps }` tunes it. |
|
|
348
|
+
| `traceIdGenerator` | the `x-request-id` header, else a UUIDv7 | Gives each request its trace id. |
|
|
349
|
+
| `traceIdKey` | `'traceId'` | The key the trace id is stored under in the request context. |
|
|
350
|
+
| `attachTraceIdToLogs` | `true` | Adds the trace id to the `ConsoleLogger`'s own output, on Nest 11.2 and later. Sending lines to the dashboard is `forwardLogs`. |
|
|
351
|
+
| `skipInstrumentation` | `() => false` | Returns `true` for a provider instance that must not be instrumented. |
|
|
352
|
+
|
|
277
353
|
## Optional peer dependencies
|
|
278
354
|
|
|
279
355
|
Protocol integrations are only loaded when you use them, and their packages are optional peers:
|
|
@@ -289,13 +365,30 @@ Protocol integrations are only loaded when you use them, and their packages are
|
|
|
289
365
|
## Test
|
|
290
366
|
|
|
291
367
|
```bash
|
|
368
|
+
# the lockfile is written with legacy-peer-deps on, and has to be read that way
|
|
369
|
+
$ npm ci --legacy-peer-deps
|
|
370
|
+
|
|
292
371
|
# unit tests
|
|
293
372
|
$ npm test
|
|
294
373
|
|
|
374
|
+
# type-check the sources and the specs
|
|
375
|
+
$ npm run typecheck
|
|
376
|
+
|
|
295
377
|
# integration tests (boot real Nest apps on real ports)
|
|
296
378
|
$ npm run test:int
|
|
297
379
|
```
|
|
298
380
|
|
|
381
|
+
The queue suites need a Redis, and the query-span suites a PostgreSQL, MySQL and MongoDB. Each suite skips itself when its server does not answer, so without them `test:int` passes having tested less. CI starts them with these ports and credentials, which the suites default to:
|
|
382
|
+
|
|
383
|
+
```bash
|
|
384
|
+
$ docker run -d -p 6379:6379 redis:7-alpine
|
|
385
|
+
$ docker run -d -p 54321:5432 -e POSTGRES_PASSWORD=postgres-whisprr postgres:16-alpine
|
|
386
|
+
$ docker run -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=test mysql:8
|
|
387
|
+
$ docker run -d -p 27027:27017 mongo:8
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
To point them elsewhere, set `REDIS_HOST`/`REDIS_PORT`, `PGHOST`/`PGPORT`/`PGUSER`/`PGPASSWORD`/`PGDATABASE`, `MYSQL_HOST`/`MYSQL_PORT`/`MYSQL_USER`/`MYSQL_PASSWORD`/`MYSQL_DATABASE` or `MONGO_HOST`/`MONGO_PORT`.
|
|
391
|
+
|
|
299
392
|
## Module format
|
|
300
393
|
|
|
301
394
|
The package ships as ESM only. CommonJS consumers can still `require()` it
|
|
@@ -253,15 +253,19 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
253
253
|
if (metric instanceof Counter || metric instanceof Summary) {
|
|
254
254
|
this._awaitingFlushAck.add(metric);
|
|
255
255
|
}
|
|
256
|
-
|
|
256
|
+
// Matched on the name as sent, which the encoder cuts to what the
|
|
257
|
+
// collector accepts. Matched on the metric's own, a metric whose name is
|
|
258
|
+
// cut would be buffered again on every change.
|
|
259
|
+
const encoded = CustomMetricsEncoder.encode(metric);
|
|
260
|
+
const existingMetricIndex = this._mainThreadBuffer.custom.findIndex((m) => m.n === encoded.n && m.t === encoded.t);
|
|
257
261
|
if (existingMetricIndex !== -1) {
|
|
258
262
|
this._mainThreadBuffer.custom[existingMetricIndex] = {
|
|
259
263
|
...this._mainThreadBuffer.custom[existingMetricIndex],
|
|
260
|
-
...
|
|
264
|
+
...encoded,
|
|
261
265
|
};
|
|
262
266
|
}
|
|
263
267
|
else {
|
|
264
|
-
this._mainThreadBuffer.custom.push(
|
|
268
|
+
this._mainThreadBuffer.custom.push(encoded);
|
|
265
269
|
}
|
|
266
270
|
}
|
|
267
271
|
/**
|
|
@@ -80,6 +80,14 @@ const JOB_SNAPSHOT = {
|
|
|
80
80
|
e: { type: "object" },
|
|
81
81
|
t: { type: "object", array: true, shape: TRACE_NODE },
|
|
82
82
|
};
|
|
83
|
+
/**
|
|
84
|
+
* One kind of collection in a runtime window. The encoder shortens the kind's
|
|
85
|
+
* key (`m`, `j`, `i`) but not these.
|
|
86
|
+
*/
|
|
87
|
+
const GC_COLLECTIONS = {
|
|
88
|
+
count: { type: "number" },
|
|
89
|
+
duration: { type: "number" },
|
|
90
|
+
};
|
|
83
91
|
const RUNTIME_METRICS = {
|
|
84
92
|
c: {
|
|
85
93
|
type: "object",
|
|
@@ -108,9 +116,9 @@ const RUNTIME_METRICS = {
|
|
|
108
116
|
b: {
|
|
109
117
|
type: "object",
|
|
110
118
|
shape: {
|
|
111
|
-
m: { type: "
|
|
112
|
-
j: { type: "
|
|
113
|
-
i: { type: "
|
|
119
|
+
m: { type: "object", shape: GC_COLLECTIONS },
|
|
120
|
+
j: { type: "object", shape: GC_COLLECTIONS },
|
|
121
|
+
i: { type: "object", shape: GC_COLLECTIONS },
|
|
114
122
|
},
|
|
115
123
|
},
|
|
116
124
|
},
|
|
@@ -123,22 +131,32 @@ const RUNTIME_METRICS = {
|
|
|
123
131
|
},
|
|
124
132
|
},
|
|
125
133
|
};
|
|
134
|
+
/**
|
|
135
|
+
* Every reading - `v`, `iv` and a summary's six distribution fields - is a map
|
|
136
|
+
* from label to number, keyed by whatever labels the application chose, so the
|
|
137
|
+
* contract declares the map rather than its entries. `l` is the label names.
|
|
138
|
+
*
|
|
139
|
+
* The collector also bounds each map - finite numbers, at most 1000 keys of at
|
|
140
|
+
* most 255 characters - and refuses the whole batch over one that is not. The
|
|
141
|
+
* metric classes keep within those bounds at the source, where a bad reading
|
|
142
|
+
* can still be dropped on its own.
|
|
143
|
+
*/
|
|
126
144
|
const CUSTOM_METRIC = {
|
|
127
145
|
n: { type: "string", required: true },
|
|
128
146
|
t: { type: "string" },
|
|
129
|
-
v: { type: "
|
|
147
|
+
v: { type: "object" },
|
|
130
148
|
tg: { type: "object" },
|
|
131
149
|
d: { type: "string" },
|
|
132
|
-
l: { type: "
|
|
150
|
+
l: { type: "string", array: true },
|
|
133
151
|
lu: { type: "number" },
|
|
134
152
|
k: { type: "string" },
|
|
135
|
-
iv: { type: "
|
|
136
|
-
q50: { type: "
|
|
137
|
-
q95: { type: "
|
|
138
|
-
q99: { type: "
|
|
139
|
-
ct: { type: "
|
|
140
|
-
sm: { type: "
|
|
141
|
-
mx: { type: "
|
|
153
|
+
iv: { type: "object" },
|
|
154
|
+
q50: { type: "object" },
|
|
155
|
+
q95: { type: "object" },
|
|
156
|
+
q99: { type: "object" },
|
|
157
|
+
ct: { type: "object" },
|
|
158
|
+
sm: { type: "object" },
|
|
159
|
+
mx: { type: "object" },
|
|
142
160
|
};
|
|
143
161
|
const LOG_ENTRY = {
|
|
144
162
|
timestamp: { type: "number", required: true },
|
|
@@ -22,16 +22,18 @@ export declare function stringifyLabel(label: Record<string, string | number>):
|
|
|
22
22
|
*/
|
|
23
23
|
export declare const MAX_SERIES_PER_METRIC = 1000;
|
|
24
24
|
/**
|
|
25
|
-
* Whether a metric may record under `key
|
|
25
|
+
* Whether a metric may record under `key`: a series it already has, or a new
|
|
26
|
+
* one that is within the cap and short enough for the collector.
|
|
26
27
|
*
|
|
27
28
|
* Refuses rather than throws. This runs inside a customer's own code path -
|
|
28
29
|
* `counter.increment({ userId })` in the middle of their request handler - and
|
|
29
30
|
* an agent that crashes the application it is measuring is worse than one that
|
|
30
|
-
* drops a series. The first refusal is logged, once per metric,
|
|
31
|
-
* silent cap is indistinguishable from a metric that does not work.
|
|
31
|
+
* drops a series. The first refusal of each kind is logged, once per metric,
|
|
32
|
+
* because a silent cap is indistinguishable from a metric that does not work.
|
|
32
33
|
*/
|
|
33
34
|
export declare function admitsSeries(metricName: string, values: Record<string, unknown>, key: string, state: {
|
|
34
35
|
warned: boolean;
|
|
36
|
+
longKeyWarned?: boolean;
|
|
35
37
|
}): boolean;
|
|
36
38
|
export declare class Counter<TLabel extends string = typeof DEFAULT_LABEL> implements CustomMetric<TLabel> {
|
|
37
39
|
/**
|
|
@@ -40,6 +42,8 @@ export declare class Counter<TLabel extends string = typeof DEFAULT_LABEL> imple
|
|
|
40
42
|
* assignable to the structural type such a helper can name.
|
|
41
43
|
*/
|
|
42
44
|
private readonly seriesLimit;
|
|
45
|
+
/** Whether a non-finite value has already been reported, likewise. */
|
|
46
|
+
private readonly nonFinite;
|
|
43
47
|
/**
|
|
44
48
|
* The name of the counter.
|
|
45
49
|
* This should be a descriptive name that identifies the counter.
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { admitsFinite } from "./finite-value.util.js";
|
|
1
2
|
const DEFAULT_LABEL = "default";
|
|
2
3
|
/**
|
|
3
4
|
* Serialises a label object into the map key that identifies its series.
|
|
@@ -27,18 +28,34 @@ export function stringifyLabel(label) {
|
|
|
27
28
|
*/
|
|
28
29
|
export const MAX_SERIES_PER_METRIC = 1_000;
|
|
29
30
|
/**
|
|
30
|
-
*
|
|
31
|
+
* The longest series key - the serialised label combination - the collector
|
|
32
|
+
* accepts. A longer one is not truncated there: the whole batch it rides in is
|
|
33
|
+
* refused, logs and spans included.
|
|
34
|
+
*/
|
|
35
|
+
const MAX_SERIES_KEY_LENGTH = 255;
|
|
36
|
+
/**
|
|
37
|
+
* Whether a metric may record under `key`: a series it already has, or a new
|
|
38
|
+
* one that is within the cap and short enough for the collector.
|
|
31
39
|
*
|
|
32
40
|
* Refuses rather than throws. This runs inside a customer's own code path -
|
|
33
41
|
* `counter.increment({ userId })` in the middle of their request handler - and
|
|
34
42
|
* an agent that crashes the application it is measuring is worse than one that
|
|
35
|
-
* drops a series. The first refusal is logged, once per metric,
|
|
36
|
-
* silent cap is indistinguishable from a metric that does not work.
|
|
43
|
+
* drops a series. The first refusal of each kind is logged, once per metric,
|
|
44
|
+
* because a silent cap is indistinguishable from a metric that does not work.
|
|
37
45
|
*/
|
|
38
46
|
export function admitsSeries(metricName, values, key, state) {
|
|
39
47
|
if (key in values) {
|
|
40
48
|
return true;
|
|
41
49
|
}
|
|
50
|
+
if (key.length > MAX_SERIES_KEY_LENGTH) {
|
|
51
|
+
if (!state.longKeyWarned) {
|
|
52
|
+
state.longKeyWarned = true;
|
|
53
|
+
console.warn(`[observe] Metric "${metricName}" ignored a label combination of ${key.length} characters; ` +
|
|
54
|
+
`the collector accepts at most ${MAX_SERIES_KEY_LENGTH} and refuses the whole batch over a longer one. ` +
|
|
55
|
+
`Shorter label values - an id rather than a URL, say - keep recording.`);
|
|
56
|
+
}
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
42
59
|
// `warned` doubles as a "cap reached" latch: series are never removed, so
|
|
43
60
|
// once the cap has been observed it cannot un-reach. Counting keys is O(n),
|
|
44
61
|
// and without the latch every rejected call would pay it - and the rejected
|
|
@@ -61,6 +78,8 @@ export class Counter {
|
|
|
61
78
|
* assignable to the structural type such a helper can name.
|
|
62
79
|
*/
|
|
63
80
|
seriesLimit = { warned: false };
|
|
81
|
+
/** Whether a non-finite value has already been reported, likewise. */
|
|
82
|
+
nonFinite = { warned: false };
|
|
64
83
|
/**
|
|
65
84
|
* The name of the counter.
|
|
66
85
|
* This should be a descriptive name that identifies the counter.
|
|
@@ -151,8 +170,12 @@ export class Counter {
|
|
|
151
170
|
this.name = name;
|
|
152
171
|
this.description = description;
|
|
153
172
|
this.type = "counter";
|
|
154
|
-
|
|
155
|
-
|
|
173
|
+
const initialValue = typeof labelsOrInitialValue === "number" ? labelsOrInitialValue : 0;
|
|
174
|
+
// Every series starts from this, so a non-finite one is replaced rather
|
|
175
|
+
// than poisoning all of them.
|
|
176
|
+
this._initialValue = admitsFinite(name, initialValue, this.nonFinite)
|
|
177
|
+
? initialValue
|
|
178
|
+
: 0;
|
|
156
179
|
if (Array.isArray(labelsOrInitialValue)) {
|
|
157
180
|
this.labels = labelsOrInitialValue;
|
|
158
181
|
this.value = {};
|
|
@@ -192,15 +215,19 @@ export class Counter {
|
|
|
192
215
|
if (typeof labelOrValue === "object") {
|
|
193
216
|
this.validateLabels(labelOrValue);
|
|
194
217
|
const stringifiedLabel = stringifyLabel(labelOrValue);
|
|
195
|
-
|
|
218
|
+
const incrementValue = value ?? 1;
|
|
219
|
+
if (!admitsFinite(this.name, incrementValue, this.nonFinite) ||
|
|
220
|
+
!admitsSeries(this.name, this.value, stringifiedLabel, this.seriesLimit)) {
|
|
196
221
|
return;
|
|
197
222
|
}
|
|
198
|
-
const incrementValue = value ?? 1;
|
|
199
223
|
this.value[stringifiedLabel] =
|
|
200
224
|
(this.value[stringifiedLabel] ?? this._initialValue) + incrementValue;
|
|
201
225
|
}
|
|
202
226
|
else {
|
|
203
227
|
const incrementValue = labelOrValue ?? 1;
|
|
228
|
+
if (!admitsFinite(this.name, incrementValue, this.nonFinite)) {
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
204
231
|
this.value[DEFAULT_LABEL] =
|
|
205
232
|
(this.value[DEFAULT_LABEL] ?? this._initialValue) + incrementValue;
|
|
206
233
|
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether a metric may record `value`, once any default has been applied.
|
|
3
|
+
*
|
|
4
|
+
* Refuses rather than throws, for the reason `admitsSeries` gives: a metric
|
|
5
|
+
* call runs inside the application's own code path. A NaN or an Infinity is
|
|
6
|
+
* nearly always computed from the application's own data - a division by a
|
|
7
|
+
* total that was zero, a value that failed to parse - so it turns up on
|
|
8
|
+
* unlucky input in production rather than on every run. Recorded, it would
|
|
9
|
+
* reach the collector as null, and a counter would stay NaN for the rest of
|
|
10
|
+
* the process. The first refusal is logged, once per metric.
|
|
11
|
+
*
|
|
12
|
+
* Callers check it after their own argument checks, so a mistake in the
|
|
13
|
+
* calling code - a missing label - still throws, on every run.
|
|
14
|
+
*
|
|
15
|
+
* Kept out of `counter.ts`, unlike `admitsSeries`: everything that module
|
|
16
|
+
* exports is re-exported from the package root.
|
|
17
|
+
*/
|
|
18
|
+
export declare function admitsFinite(metricName: string, value: number, state: {
|
|
19
|
+
warned: boolean;
|
|
20
|
+
}): boolean;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether a metric may record `value`, once any default has been applied.
|
|
3
|
+
*
|
|
4
|
+
* Refuses rather than throws, for the reason `admitsSeries` gives: a metric
|
|
5
|
+
* call runs inside the application's own code path. A NaN or an Infinity is
|
|
6
|
+
* nearly always computed from the application's own data - a division by a
|
|
7
|
+
* total that was zero, a value that failed to parse - so it turns up on
|
|
8
|
+
* unlucky input in production rather than on every run. Recorded, it would
|
|
9
|
+
* reach the collector as null, and a counter would stay NaN for the rest of
|
|
10
|
+
* the process. The first refusal is logged, once per metric.
|
|
11
|
+
*
|
|
12
|
+
* Callers check it after their own argument checks, so a mistake in the
|
|
13
|
+
* calling code - a missing label - still throws, on every run.
|
|
14
|
+
*
|
|
15
|
+
* Kept out of `counter.ts`, unlike `admitsSeries`: everything that module
|
|
16
|
+
* exports is re-exported from the package root.
|
|
17
|
+
*/
|
|
18
|
+
export function admitsFinite(metricName, value, state) {
|
|
19
|
+
if (Number.isFinite(value)) {
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
if (!state.warned) {
|
|
23
|
+
state.warned = true;
|
|
24
|
+
console.warn(`[observe] Metric "${metricName}" ignored ${value}, which is not a finite number. ` +
|
|
25
|
+
`Further ones are ignored without another warning. This usually means the value is ` +
|
|
26
|
+
`computed from something that can be zero or missing (a division by a zero total, a failed parse).`);
|
|
27
|
+
}
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
@@ -14,6 +14,8 @@ export declare class Gauge<TLabel extends string = typeof DEFAULT_LABEL> impleme
|
|
|
14
14
|
* assignable to the structural type such a helper can name.
|
|
15
15
|
*/
|
|
16
16
|
private readonly seriesLimit;
|
|
17
|
+
/** Whether a non-finite value has already been reported, likewise. */
|
|
18
|
+
private readonly nonFinite;
|
|
17
19
|
/**
|
|
18
20
|
* The name of the gauge.
|
|
19
21
|
* This should be a descriptive name that identifies the gauge.
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { admitsSeries, stringifyLabel } from "./counter.js";
|
|
2
|
+
import { admitsFinite } from "./finite-value.util.js";
|
|
2
3
|
const DEFAULT_LABEL = "default";
|
|
3
4
|
export class Gauge {
|
|
4
5
|
/**
|
|
@@ -7,6 +8,8 @@ export class Gauge {
|
|
|
7
8
|
* assignable to the structural type such a helper can name.
|
|
8
9
|
*/
|
|
9
10
|
seriesLimit = { warned: false };
|
|
11
|
+
/** Whether a non-finite value has already been reported, likewise. */
|
|
12
|
+
nonFinite = { warned: false };
|
|
10
13
|
/**
|
|
11
14
|
* The name of the gauge.
|
|
12
15
|
* This should be a descriptive name that identifies the gauge.
|
|
@@ -75,7 +78,12 @@ export class Gauge {
|
|
|
75
78
|
this.description = attributes?.description;
|
|
76
79
|
this.kind = attributes?.kind;
|
|
77
80
|
this.type = "gauge";
|
|
78
|
-
|
|
81
|
+
const initialValue = attributes?.initialValue ?? 0;
|
|
82
|
+
// Every series starts from this, so a non-finite one is replaced rather
|
|
83
|
+
// than poisoning all of them.
|
|
84
|
+
this._initialValue = admitsFinite(name, initialValue, this.nonFinite)
|
|
85
|
+
? initialValue
|
|
86
|
+
: 0;
|
|
79
87
|
// Optional, like every other read of `attributes`. Without this the
|
|
80
88
|
// single-argument overload the class advertises - `new Gauge("name")` -
|
|
81
89
|
// threw "Cannot read properties of undefined".
|
|
@@ -110,15 +118,19 @@ export class Gauge {
|
|
|
110
118
|
if (typeof labelOrValue === "object") {
|
|
111
119
|
this.validateLabels(labelOrValue);
|
|
112
120
|
const stringifiedLabel = stringifyLabel(labelOrValue);
|
|
113
|
-
|
|
121
|
+
const incrementValue = value ?? 1;
|
|
122
|
+
if (!admitsFinite(this.name, incrementValue, this.nonFinite) ||
|
|
123
|
+
!admitsSeries(this.name, this.value, stringifiedLabel, this.seriesLimit)) {
|
|
114
124
|
return;
|
|
115
125
|
}
|
|
116
|
-
const incrementValue = value ?? 1;
|
|
117
126
|
this.value[stringifiedLabel] =
|
|
118
127
|
(this.value[stringifiedLabel] ?? this._initialValue) + incrementValue;
|
|
119
128
|
}
|
|
120
129
|
else {
|
|
121
130
|
const incrementValue = labelOrValue ?? 1;
|
|
131
|
+
if (!admitsFinite(this.name, incrementValue, this.nonFinite)) {
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
122
134
|
this.value[DEFAULT_LABEL] =
|
|
123
135
|
(this.value[DEFAULT_LABEL] ?? this._initialValue) + incrementValue;
|
|
124
136
|
}
|
|
@@ -134,15 +146,19 @@ export class Gauge {
|
|
|
134
146
|
else if (typeof labelOrValue === "object") {
|
|
135
147
|
this.validateLabels(labelOrValue);
|
|
136
148
|
const stringifiedLabel = stringifyLabel(labelOrValue);
|
|
137
|
-
|
|
149
|
+
const decrementValue = value ?? 1;
|
|
150
|
+
if (!admitsFinite(this.name, decrementValue, this.nonFinite) ||
|
|
151
|
+
!admitsSeries(this.name, this.value, stringifiedLabel, this.seriesLimit)) {
|
|
138
152
|
return;
|
|
139
153
|
}
|
|
140
|
-
const decrementValue = value ?? 1;
|
|
141
154
|
this.value[stringifiedLabel] =
|
|
142
155
|
(this.value[stringifiedLabel] ?? this._initialValue) - decrementValue;
|
|
143
156
|
}
|
|
144
157
|
else {
|
|
145
158
|
const decrementValue = labelOrValue ?? 1;
|
|
159
|
+
if (!admitsFinite(this.name, decrementValue, this.nonFinite)) {
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
146
162
|
this.value[DEFAULT_LABEL] =
|
|
147
163
|
(this.value[DEFAULT_LABEL] ?? this._initialValue) - decrementValue;
|
|
148
164
|
}
|
|
@@ -161,7 +177,11 @@ export class Gauge {
|
|
|
161
177
|
if (!(stringifiedLabel in this.value)) {
|
|
162
178
|
throw new Error(`Label "${stringifiedLabel}" does not exist in the gauge. Available labels: ${Object.keys(this.value).join(", ")}.`);
|
|
163
179
|
}
|
|
164
|
-
|
|
180
|
+
const newValue = value ?? this._initialValue;
|
|
181
|
+
if (!admitsFinite(this.name, newValue, this.nonFinite)) {
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
this.value[stringifiedLabel] = newValue;
|
|
165
185
|
}
|
|
166
186
|
else {
|
|
167
187
|
// A gauge starts at 0 by default, so the truthiness check here rejected
|
|
@@ -170,7 +190,11 @@ export class Gauge {
|
|
|
170
190
|
if (!(DEFAULT_LABEL in this.value)) {
|
|
171
191
|
throw new Error(`Default label "${DEFAULT_LABEL}" does not exist in the gauge. Available labels: ${Object.keys(this.value).join(", ")}.`);
|
|
172
192
|
}
|
|
173
|
-
|
|
193
|
+
const newValue = labelOrValue ?? this._initialValue;
|
|
194
|
+
if (!admitsFinite(this.name, newValue, this.nonFinite)) {
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
this.value[DEFAULT_LABEL] = newValue;
|
|
174
198
|
}
|
|
175
199
|
this._lastUpdated = Date.now();
|
|
176
200
|
if (this._onChange) {
|
|
@@ -12,6 +12,11 @@ declare const DEFAULT_LABEL: "default";
|
|
|
12
12
|
* stay truthful across any number of reporters.
|
|
13
13
|
*/
|
|
14
14
|
export declare class Summary<TLabel extends string = typeof DEFAULT_LABEL> implements CustomMetric<TLabel> {
|
|
15
|
+
/**
|
|
16
|
+
* Whether a non-finite observation has already been reported. An object so
|
|
17
|
+
* `admitsFinite` can set it, as with the counter's and gauge's latches.
|
|
18
|
+
*/
|
|
19
|
+
private readonly nonFinite;
|
|
15
20
|
/**
|
|
16
21
|
* The name of the summary.
|
|
17
22
|
* This should be a descriptive name that identifies the distribution.
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { admitsFinite } from "./finite-value.util.js";
|
|
1
2
|
const DEFAULT_LABEL = "default";
|
|
2
3
|
/**
|
|
3
4
|
* How many observations per label are kept to compute quantiles from.
|
|
@@ -19,6 +20,11 @@ const DEFAULT_SAMPLE_SIZE = 2048;
|
|
|
19
20
|
* stay truthful across any number of reporters.
|
|
20
21
|
*/
|
|
21
22
|
export class Summary {
|
|
23
|
+
/**
|
|
24
|
+
* Whether a non-finite observation has already been reported. An object so
|
|
25
|
+
* `admitsFinite` can set it, as with the counter's and gauge's latches.
|
|
26
|
+
*/
|
|
27
|
+
nonFinite = { warned: false };
|
|
22
28
|
/**
|
|
23
29
|
* The name of the summary.
|
|
24
30
|
* This should be a descriptive name that identifies the distribution.
|
|
@@ -136,15 +142,16 @@ export class Summary {
|
|
|
136
142
|
this._sampleSize = attributes?.sampleSize ?? DEFAULT_SAMPLE_SIZE;
|
|
137
143
|
}
|
|
138
144
|
observe(value, label) {
|
|
139
|
-
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
140
|
-
throw new Error(`Cannot observe a non-finite value on summary "${this.name}".`);
|
|
141
|
-
}
|
|
142
145
|
if (this.labels && !label) {
|
|
143
146
|
throw new Error(`Cannot observe on a summary with labels without specifying one. For example, use \`summary.observe(12, "${this.labels[0]}")\`.`);
|
|
144
147
|
}
|
|
145
148
|
if (label && this.labels && !this.labels.includes(label)) {
|
|
146
149
|
throw new Error(`Label "${label}" is not defined in the summary. Available labels: ${this.labels.join(", ")}.`);
|
|
147
150
|
}
|
|
151
|
+
// A NaN would poison every quantile read off the sample, and the total.
|
|
152
|
+
if (!admitsFinite(this.name, value, this.nonFinite)) {
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
148
155
|
const key = label ?? DEFAULT_LABEL;
|
|
149
156
|
const count = (this._count[key] ?? 0) + 1;
|
|
150
157
|
this._count[key] = count;
|