@nestjs/observe 0.3.5 → 0.3.7
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 +66 -4
- package/dist/agent/observe-agent.shared-buffer.js +7 -3
- package/dist/agent/observe-agent.worker.d.ts +1 -0
- package/dist/agent/observe-agent.worker.js +32 -2
- 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/interfaces/custom-metric.interface.d.ts +5 -0
- package/dist/interfaces/observe-options.interface.d.ts +23 -14
- package/dist/observe.module.js +25 -6
- 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.js +2 -8
- package/dist/utils/fit-to-length.util.d.ts +10 -0
- package/dist/utils/fit-to-length.util.js +44 -0
- 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,8 +246,9 @@ 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.
|
|
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.
|
|
248
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 }`.
|
|
@@ -305,6 +309,47 @@ Declarations are checked when the application starts, and whatever fails is logg
|
|
|
305
309
|
|
|
306
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.
|
|
307
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
|
+
|
|
308
353
|
## Optional peer dependencies
|
|
309
354
|
|
|
310
355
|
Protocol integrations are only loaded when you use them, and their packages are optional peers:
|
|
@@ -320,13 +365,30 @@ Protocol integrations are only loaded when you use them, and their packages are
|
|
|
320
365
|
## Test
|
|
321
366
|
|
|
322
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
|
+
|
|
323
371
|
# unit tests
|
|
324
372
|
$ npm test
|
|
325
373
|
|
|
374
|
+
# type-check the sources and the specs
|
|
375
|
+
$ npm run typecheck
|
|
376
|
+
|
|
326
377
|
# integration tests (boot real Nest apps on real ports)
|
|
327
378
|
$ npm run test:int
|
|
328
379
|
```
|
|
329
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
|
+
|
|
330
392
|
## Module format
|
|
331
393
|
|
|
332
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
|
/**
|
|
@@ -44,6 +44,7 @@ export declare class ObserveAgentWorker implements OnModuleInit, OnApplicationSh
|
|
|
44
44
|
*/
|
|
45
45
|
private startContinuousProfiling;
|
|
46
46
|
onApplicationShutdown(): Promise<void>;
|
|
47
|
+
private get hasScaffoldCredentials();
|
|
47
48
|
private get endpoint();
|
|
48
49
|
/**
|
|
49
50
|
* Says out loud when credentials are about to cross the network unencrypted.
|
|
@@ -30,6 +30,17 @@ const DEFAULT_FLUSH_INTERVAL = 5000; // 5 seconds
|
|
|
30
30
|
*/
|
|
31
31
|
const DEFAULT_COLLECTOR_ENDPOINT = process.env.OBSERVE_ENDPOINT ?? "https://observe-api.nestjs.com";
|
|
32
32
|
const MIN_FLUSH_INTERVAL = 1000; // 1 second
|
|
33
|
+
/**
|
|
34
|
+
* The credentials `nest new --observe` writes into `AppModule`.
|
|
35
|
+
*
|
|
36
|
+
* A project fresh from the generator has these until someone signs up, so
|
|
37
|
+
* they mean "not connected yet", not "wrong": sending them only buys a 401
|
|
38
|
+
* and an `Error:` line on the very first `npm run start`.
|
|
39
|
+
*/
|
|
40
|
+
const SCAFFOLD_APP_KEY = "YOUR_APP_KEY";
|
|
41
|
+
const SCAFFOLD_APP_SECRET = "YOUR_APP_SECRET";
|
|
42
|
+
const DEMO_URL = "https://www.observe-demo.nestjs.com/dashboard";
|
|
43
|
+
const SIGN_UP_URL = "https://observe.nestjs.com";
|
|
33
44
|
let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
34
45
|
observeAgentSharedBuffer;
|
|
35
46
|
options;
|
|
@@ -57,7 +68,16 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
57
68
|
this.nodeRuntimeMetricsService = nodeRuntimeMetricsService;
|
|
58
69
|
}
|
|
59
70
|
onModuleInit() {
|
|
60
|
-
this.
|
|
71
|
+
if (this.hasScaffoldCredentials) {
|
|
72
|
+
// Nothing is sent, so there is no worker to start. The flush timer below
|
|
73
|
+
// still runs and empties the buffer, which the instrumentation keeps
|
|
74
|
+
// writing into either way.
|
|
75
|
+
this.logger.log(`Observe is installed but not connected yet: appKey and appSecret are still the placeholders from nest new, so no telemetry is sent. ` +
|
|
76
|
+
`See what this app will look like: ${DEMO_URL} - then create a free account at ${SIGN_UP_URL} for your own key and secret.`);
|
|
77
|
+
}
|
|
78
|
+
else {
|
|
79
|
+
this.initializeWorker();
|
|
80
|
+
}
|
|
61
81
|
let flushIntervalTime = this.options.flushInterval ?? DEFAULT_FLUSH_INTERVAL;
|
|
62
82
|
if (flushIntervalTime < MIN_FLUSH_INTERVAL) {
|
|
63
83
|
this.logger.warn(`Flush interval is too short (${flushIntervalTime}ms). Setting to minimum of ${MIN_FLUSH_INTERVAL}ms.`);
|
|
@@ -68,7 +88,9 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
68
88
|
this.options.flushInterval = MIN_FLUSH_INTERVAL;
|
|
69
89
|
}
|
|
70
90
|
this.flushInterval = setInterval(() => this.flush(), flushIntervalTime);
|
|
71
|
-
this.
|
|
91
|
+
if (!this.hasScaffoldCredentials) {
|
|
92
|
+
this.startRuntimeMetrics();
|
|
93
|
+
}
|
|
72
94
|
// Continuous profiling is shelved: a flame graph asks more of a reader than
|
|
73
95
|
// most services' owners want to give it, and the signal is not worth the
|
|
74
96
|
// sampling cost until there is a UI that makes it legible. The
|
|
@@ -170,6 +192,10 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
170
192
|
}
|
|
171
193
|
this.worker = null;
|
|
172
194
|
}
|
|
195
|
+
get hasScaffoldCredentials() {
|
|
196
|
+
return (this.options.appKey === SCAFFOLD_APP_KEY &&
|
|
197
|
+
this.options.appSecret === SCAFFOLD_APP_SECRET);
|
|
198
|
+
}
|
|
173
199
|
get endpoint() {
|
|
174
200
|
return this.options.endpoint ?? DEFAULT_COLLECTOR_ENDPOINT;
|
|
175
201
|
}
|
|
@@ -286,6 +312,10 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
286
312
|
// gone quiet, and an empty buffer would otherwise return here and strand
|
|
287
313
|
// them until shutdown.
|
|
288
314
|
this.observeAgentSharedBuffer.drainPendingLogs();
|
|
315
|
+
if (this.hasScaffoldCredentials) {
|
|
316
|
+
this.observeAgentSharedBuffer.resetMainThreadBuffer();
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
289
319
|
if (this.observeAgentSharedBuffer.isBufferEmpty()) {
|
|
290
320
|
return;
|
|
291
321
|
}
|
|
@@ -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;
|