@nestjs/observe 0.3.25 → 0.3.27

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.
Files changed (109) hide show
  1. package/README.md +55 -2
  2. package/dist/agent/detached-observe-worker.js +50 -6
  3. package/dist/agent/observe-agent.shared-buffer.d.ts +44 -0
  4. package/dist/agent/observe-agent.shared-buffer.js +201 -19
  5. package/dist/agent/observe-agent.worker.d.ts +22 -2
  6. package/dist/agent/observe-agent.worker.js +43 -7
  7. package/dist/agent/telemetry-wire-contract.js +10 -4
  8. package/dist/cli/agent-notes.js +16 -4
  9. package/dist/cli/link.js +51 -4
  10. package/dist/cli/observe-cli.js +1 -19
  11. package/dist/cli/open-url.d.ts +27 -0
  12. package/dist/cli/open-url.js +63 -0
  13. package/dist/cli/package-manager.d.ts +6 -0
  14. package/dist/cli/package-manager.js +60 -3
  15. package/dist/cli/project-files.d.ts +62 -1
  16. package/dist/cli/project-files.js +229 -7
  17. package/dist/cli/project-setup.d.ts +6 -0
  18. package/dist/cli/project-setup.js +14 -1
  19. package/dist/cli/wire-application.js +6 -0
  20. package/dist/custom-metrics/counter.d.ts +13 -2
  21. package/dist/custom-metrics/counter.js +33 -16
  22. package/dist/custom-metrics/finite-value.util.d.ts +14 -0
  23. package/dist/custom-metrics/finite-value.util.js +33 -1
  24. package/dist/custom-metrics/gauge.d.ts +2 -0
  25. package/dist/custom-metrics/gauge.js +41 -17
  26. package/dist/custom-metrics/label-values.util.d.ts +37 -0
  27. package/dist/custom-metrics/label-values.util.js +51 -0
  28. package/dist/custom-metrics/summary.d.ts +23 -0
  29. package/dist/custom-metrics/summary.js +90 -12
  30. package/dist/instrument/create-instance-decorator.instrument.js +504 -116
  31. package/dist/instrument/raw-receiver.d.ts +6 -0
  32. package/dist/instrument/raw-receiver.js +32 -0
  33. package/dist/interfaces/observe-options.interface.d.ts +17 -6
  34. package/dist/objectives/objectives.registry.js +12 -0
  35. package/dist/observe.module.js +119 -3
  36. package/dist/otlp/otlp-encoders.js +22 -5
  37. package/dist/otlp/otlp-span.mapper.d.ts +2 -0
  38. package/dist/otlp/otlp-span.mapper.js +26 -4
  39. package/dist/otlp/otlp-trace-exporter.service.d.ts +63 -9
  40. package/dist/otlp/otlp-trace-exporter.service.js +295 -43
  41. package/dist/outgoing/http.integration.d.ts +8 -4
  42. package/dist/outgoing/http.integration.js +49 -17
  43. package/dist/outgoing/llm/llm-fetch.integration.js +62 -1
  44. package/dist/outgoing/llm/llm-providers.d.ts +16 -4
  45. package/dist/outgoing/llm/llm-providers.js +72 -22
  46. package/dist/outgoing/llm/llm-usage.d.ts +11 -6
  47. package/dist/outgoing/llm/llm-usage.js +72 -25
  48. package/dist/outgoing/mongodb.integration.d.ts +3 -1
  49. package/dist/outgoing/mongodb.integration.js +93 -18
  50. package/dist/outgoing/mssql.integration.js +25 -6
  51. package/dist/outgoing/mysql2.integration.js +17 -1
  52. package/dist/outgoing/outgoing-observe-agent.service.js +20 -4
  53. package/dist/outgoing/outgoing-span.recorder.js +17 -3
  54. package/dist/outgoing/pg.integration.d.ts +3 -2
  55. package/dist/outgoing/pg.integration.js +39 -11
  56. package/dist/outgoing/sql-statement.util.js +139 -21
  57. package/dist/outgoing/undici.integration.d.ts +13 -0
  58. package/dist/outgoing/undici.integration.js +68 -0
  59. package/dist/protocols/bull-observe-agent.service.js +23 -12
  60. package/dist/protocols/deferred-trace-completion.d.ts +17 -3
  61. package/dist/protocols/deferred-trace-completion.js +76 -9
  62. package/dist/protocols/graphql-observe-agent.service.d.ts +97 -6
  63. package/dist/protocols/graphql-observe-agent.service.js +354 -19
  64. package/dist/protocols/graphql-operation-parser.js +111 -26
  65. package/dist/protocols/http-observe-agent.service.d.ts +50 -9
  66. package/dist/protocols/http-observe-agent.service.js +220 -59
  67. package/dist/protocols/job-trace-runner.d.ts +42 -3
  68. package/dist/protocols/job-trace-runner.js +197 -36
  69. package/dist/protocols/queue-observe-agent.service.js +44 -20
  70. package/dist/protocols/rpc-observe-agent.service.d.ts +111 -8
  71. package/dist/protocols/rpc-observe-agent.service.js +332 -56
  72. package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
  73. package/dist/protocols/ws-observe-agent.service.js +227 -21
  74. package/dist/services/index.d.ts +1 -1
  75. package/dist/services/index.js +1 -1
  76. package/dist/services/logger-patcher.service.js +16 -7
  77. package/dist/services/operation-trace.registry.d.ts +58 -1
  78. package/dist/services/operation-trace.registry.js +576 -63
  79. package/dist/services/stdout-forwarder.service.d.ts +69 -0
  80. package/dist/services/stdout-forwarder.service.js +308 -51
  81. package/dist/services/tracer.service.d.ts +39 -11
  82. package/dist/services/tracer.service.js +145 -36
  83. package/dist/utils/capture-request.util.d.ts +3 -1
  84. package/dist/utils/capture-request.util.js +128 -12
  85. package/dist/utils/context-accessor.util.d.ts +16 -0
  86. package/dist/utils/context-accessor.util.js +28 -0
  87. package/dist/utils/default-trace-id-generator.util.js +5 -7
  88. package/dist/utils/error-stack.util.d.ts +13 -0
  89. package/dist/utils/error-stack.util.js +166 -0
  90. package/dist/utils/fit-to-length.util.js +33 -10
  91. package/dist/utils/log-line.parser.d.ts +22 -0
  92. package/dist/utils/log-line.parser.js +20 -7
  93. package/dist/utils/log-redactor.d.ts +14 -0
  94. package/dist/utils/log-redactor.js +690 -65
  95. package/dist/utils/operation-state.util.d.ts +39 -0
  96. package/dist/utils/operation-state.util.js +50 -0
  97. package/dist/utils/redact-url-query.d.ts +37 -4
  98. package/dist/utils/redact-url-query.js +197 -32
  99. package/dist/utils/sensitive-keys.d.ts +4 -1
  100. package/dist/utils/sensitive-keys.js +48 -10
  101. package/dist/utils/shared-hook-slot.util.d.ts +48 -0
  102. package/dist/utils/shared-hook-slot.util.js +103 -0
  103. package/dist/utils/source-context.util.d.ts +14 -0
  104. package/dist/utils/source-context.util.js +142 -43
  105. package/dist/utils/source-map-resolver.util.js +33 -6
  106. package/dist/utils/store-copy.util.d.ts +10 -0
  107. package/dist/utils/store-copy.util.js +43 -0
  108. package/dist/utils/trace-context.util.js +21 -6
  109. package/package.json +2 -2
@@ -1,5 +1,44 @@
1
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
- import { join } from "node:path";
1
+ import { spawnSync } from "node:child_process";
2
+ import { accessSync, constants, existsSync, lstatSync, readFileSync, realpathSync, writeFileSync, } from "node:fs";
3
+ import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
4
+ /** The files `link` writes in every project, whatever else it does. */
5
+ export const LINK_FILES = [".env", ".gitignore", "package.json"];
6
+ /**
7
+ * Whether `path`, relative to `cwd`, is a file of the project's own once
8
+ * links are followed - where `link` may write.
9
+ *
10
+ * A checkout's files can be links to anywhere the person can write, and a
11
+ * project's own paths can climb out with `../`: written through, the key
12
+ * pair, the notes or the wiring would land in someone else's file, reported
13
+ * under an in-project name. A file still to be created is the project's when
14
+ * its directory is; a link that leads nowhere is not, because writing to it
15
+ * would create the file it points at.
16
+ */
17
+ export function isProjectFile(cwd, path) {
18
+ let root;
19
+ try {
20
+ root = realpathSync.native(cwd);
21
+ }
22
+ catch {
23
+ return false;
24
+ }
25
+ const file = join(cwd, path);
26
+ let real;
27
+ try {
28
+ real = realpathSync.native(file);
29
+ }
30
+ catch {
31
+ if (lstatSync(file, { throwIfNoEntry: false }) !== undefined) {
32
+ return false;
33
+ }
34
+ const parent = dirname(path);
35
+ return parent === path ? false : isProjectFile(cwd, parent);
36
+ }
37
+ const fromRoot = relative(root, real);
38
+ return (fromRoot !== ".." &&
39
+ !fromRoot.startsWith(`..${sep}`) &&
40
+ !isAbsolute(fromRoot));
41
+ }
3
42
  /** The variables `ObserveModule` falls back to for its key pair. */
4
43
  export const KEY_VARIABLE = "OBSERVE_APP_KEY";
5
44
  export const SECRET_VARIABLE = "OBSERVE_APP_SECRET";
@@ -9,6 +48,26 @@ export const SECRET_VARIABLE = "OBSERVE_APP_SECRET";
9
48
  * load `.env` instead.
10
49
  */
11
50
  const CONVENTIONAL_START_SCRIPTS = new Set(["start", "start:dev"]);
51
+ /**
52
+ * Printable ASCII without whitespace, a single quote or a backslash: what
53
+ * stands between single quotes in `.env` and reads the same to every loader.
54
+ * Key and secret are drawn from letters, digits and `!$%^&`, well inside it.
55
+ */
56
+ const ENV_FILE_VALUE = /^[\x21-\x26\x28-\x5b\x5d-\x7e]+$/;
57
+ /**
58
+ * Whether `value` can be written into `.env` as `writeEnvFile` writes it.
59
+ *
60
+ * The pair comes from the link service's reply, and `.env` is loaded into
61
+ * the app on every start: a quote and a line break would end the value and
62
+ * add a line of the reply's choosing - `NODE_OPTIONS=--import ...`, or a
63
+ * `DATABASE_URL` that wins over the project's own. Refused rather than
64
+ * escaped: no escape for a quote or a line break reads the same in Node's
65
+ * `--env-file`, `dotenv` and a shell, and `dotenv` reads `\'` as an escaped
66
+ * quote where Node ends the value.
67
+ */
68
+ export function isEnvFileValue(value) {
69
+ return typeof value === "string" && ENV_FILE_VALUE.test(value);
70
+ }
12
71
  /**
13
72
  * Writes the key pair into `<cwd>/.env`, replacing an earlier pair and keeping
14
73
  * every other line as it was. Created owner-only when it does not exist.
@@ -18,9 +77,13 @@ const CONVENTIONAL_START_SCRIPTS = new Set(["start", "start:dev"]);
18
77
  * variables (`dotenv-expand`, `ConfigModule` with `expandVariables`) rewrites
19
78
  * everything after a `$`, and a shell sourcing the file stops at the `&`.
20
79
  * Node's own `--env-file` reads either form literally. Single quotes are
21
- * literal in all of them, and the alphabet has no quote in it to escape.
80
+ * literal in all of them, and a value with a quote - or anything else
81
+ * `isEnvFileValue` refuses - is not written at all.
22
82
  */
23
83
  export function writeEnvFile(cwd, appKey, appSecret) {
84
+ if (!isEnvFileValue(appKey) || !isEnvFileValue(appSecret)) {
85
+ throw new TypeError("The key pair can hold only printable ASCII without whitespace, quotes or backslashes.");
86
+ }
24
87
  const path = join(cwd, ".env");
25
88
  const existing = existsSync(path) ? readFileSync(path, "utf8") : "";
26
89
  const kept = existing
@@ -39,6 +102,132 @@ export function writeEnvFile(cwd, appKey, appSecret) {
39
102
  writeFileSync(path, lines.join("\n"), existing ? undefined : { mode: 0o600 });
40
103
  return path;
41
104
  }
105
+ /**
106
+ * `.env` as a path relative to `cwd` when git already tracks the file it is -
107
+ * itself, or what it links to - or undefined: not tracked, not in a
108
+ * repository, or no git to ask.
109
+ *
110
+ * An ignore rule does not apply to a file in the index, so the secret written
111
+ * into a tracked `.env` would be in the next `git commit -a` whatever
112
+ * `.gitignore` says. Git is asked as `askGit` asks it, with nothing of the
113
+ * project's that could run a program.
114
+ */
115
+ export function trackedEnvFile(cwd) {
116
+ const env = envFileOf(cwd);
117
+ if (!env) {
118
+ return undefined;
119
+ }
120
+ const status = askGit(dirname(env.path), [
121
+ "--literal-pathspecs",
122
+ "ls-files",
123
+ "--error-unmatch",
124
+ "--",
125
+ basename(env.path),
126
+ ]);
127
+ return status === 0 ? relative(env.root, env.path) || ".env" : undefined;
128
+ }
129
+ /**
130
+ * Whether git ignores the file the key pair is written into - `.env`, or
131
+ * what it links to: true or false as git answers, undefined when there is
132
+ * no repository or no git to ask.
133
+ *
134
+ * Asked of git itself, after `ensureEnvIgnored`, rather than read off
135
+ * `.gitignore`: git decides with every ignore file there is, and a rule
136
+ * `ensureEnvIgnored` saw does not ignore a file `.env` links to under
137
+ * another name. Asked the way `trackedEnvFile` asks.
138
+ */
139
+ export function envFileIgnored(cwd) {
140
+ const env = envFileOf(cwd);
141
+ if (!env) {
142
+ return undefined;
143
+ }
144
+ // `check-ignore` takes no `--literal-pathspecs`; a name after `./` is a
145
+ // name, whatever it starts with.
146
+ const status = askGit(dirname(env.path), [
147
+ "check-ignore",
148
+ "-q",
149
+ "--",
150
+ `./${basename(env.path)}`,
151
+ ]);
152
+ return status === 0 ? true : status === 1 ? false : undefined;
153
+ }
154
+ /**
155
+ * The project's real directory, and the real path of its `.env` - what it
156
+ * links to, or where it would be created.
157
+ */
158
+ function envFileOf(cwd) {
159
+ let root;
160
+ try {
161
+ root = realpathSync(cwd);
162
+ }
163
+ catch {
164
+ return undefined;
165
+ }
166
+ let path = join(root, ".env");
167
+ try {
168
+ path = realpathSync(path);
169
+ }
170
+ catch {
171
+ // Not there yet, though it may still be in the index.
172
+ }
173
+ return { root, path };
174
+ }
175
+ /**
176
+ * Runs git with `args` in `dir` and returns its exit status, null when it
177
+ * could not run. Its arguments are fixed, it starts from Node's own
178
+ * directory and is pointed at the project with `-C`, and the two settings
179
+ * a project's own `.git/config` could use to run a program are turned off:
180
+ * `core.fsmonitor`, which reading the index starts, and the discovery of
181
+ * a bare repository that only sits in the checkout.
182
+ */
183
+ function askGit(dir, args) {
184
+ return spawnSync("git", [
185
+ "-c",
186
+ "core.fsmonitor=false",
187
+ "-c",
188
+ "safe.bareRepository=explicit",
189
+ "-C",
190
+ dir,
191
+ ...args,
192
+ ], { cwd: dirname(process.execPath), stdio: "ignore", timeout: 10_000 }).status;
193
+ }
194
+ /**
195
+ * Why `ensureEnvIgnored` could not add `.env` to `<cwd>/.gitignore`, or
196
+ * undefined when it can: the file is there, a regular file that can be read
197
+ * and written, or it is not and the directory can take it. Asked before a
198
+ * code is, so no pair is issued for a project it could not be kept out of
199
+ * git in.
200
+ *
201
+ * A link is refused even when it stays in the project: git reads no
202
+ * `.gitignore` that is a symbolic link (2.32 and later), so a rule written
203
+ * through it would keep nothing out of git, however it read.
204
+ */
205
+ export function gitignoreProblem(cwd) {
206
+ const path = join(cwd, ".gitignore");
207
+ const stats = lstatSync(path, { throwIfNoEntry: false });
208
+ if (stats === undefined) {
209
+ try {
210
+ accessSync(cwd, constants.W_OK);
211
+ return undefined;
212
+ }
213
+ catch {
214
+ return `There is no .gitignore in ${cwd} and the directory cannot be written to, so link could not keep .env out of git.`;
215
+ }
216
+ }
217
+ if (stats.isSymbolicLink()) {
218
+ return ".gitignore is a symbolic link, and git does not read one, so a rule in it would not keep .env out of git. Put the file itself in its place and link again.";
219
+ }
220
+ if (!stats.isFile()) {
221
+ return ".gitignore is not a file, so link could not keep .env out of git.";
222
+ }
223
+ try {
224
+ accessSync(path, constants.R_OK | constants.W_OK);
225
+ return undefined;
226
+ }
227
+ catch {
228
+ return ".gitignore cannot be read and written, so link could not keep .env out of git.";
229
+ }
230
+ }
42
231
  /**
43
232
  * Makes sure `.env` is git-ignored, so the secret cannot be committed by
44
233
  * accident. `nest new` already ignores it; a project from elsewhere may not.
@@ -47,10 +236,20 @@ export function writeEnvFile(cwd, appKey, appSecret) {
47
236
  export function ensureEnvIgnored(cwd) {
48
237
  const path = join(cwd, ".gitignore");
49
238
  const existing = existsSync(path) ? readFileSync(path, "utf8") : "";
50
- const ignored = existing
51
- .split(/\r?\n/)
52
- .map((line) => line.trim())
53
- .some((line) => line === ".env" || line === "/.env" || line === ".env*");
239
+ // Read the way git reads it. The last rule that matches decides, so a
240
+ // `!.env` further down takes `.env` back out. Only trailing spaces are
241
+ // dropped from a rule: an indented ` .env` names a file that starts with
242
+ // a space, and `.env` followed by a tab one that ends with a tab.
243
+ let ignored = false;
244
+ for (const line of existing.replace(/^\uFEFF/, "").split(/\r?\n/)) {
245
+ const rule = line.replace(/ +$/, "");
246
+ if (rule === ".env" || rule === "/.env" || rule === ".env*") {
247
+ ignored = true;
248
+ }
249
+ else if (rule.startsWith("!") && mayMatchEnv(rule.slice(1))) {
250
+ ignored = false;
251
+ }
252
+ }
54
253
  if (ignored) {
55
254
  return false;
56
255
  }
@@ -58,6 +257,29 @@ export function ensureEnvIgnored(cwd) {
58
257
  writeFileSync(path, `${existing}${separator}\n# NestJS Observe key pair\n.env\n`);
59
258
  return true;
60
259
  }
260
+ /**
261
+ * Whether a `.gitignore` pattern can match `<cwd>/.env`. Asked only of rules
262
+ * that take files back out, where a wrong yes costs one more `.env` line at
263
+ * the end of the file and a wrong no costs the secret - so whatever is not
264
+ * read exactly counts as a match: a `[class]`, a `\` escape, and a name in
265
+ * another case, for a checkout on a case-insensitive file system.
266
+ */
267
+ function mayMatchEnv(pattern) {
268
+ if (/[[\\]/.test(pattern)) {
269
+ return true;
270
+ }
271
+ // `/` in front anchors it to this directory, where `.env` is anyway; one
272
+ // at the end means directories only, and `.env` is a file.
273
+ const name = pattern.replace(/^\//, "").replace(/^(\*\*\/)+/, "");
274
+ if (!name || name.includes("/")) {
275
+ return false;
276
+ }
277
+ const glob = name
278
+ .replace(/[.+^${}()|]/g, "\\$&")
279
+ .replace(/\*/g, "[^/]*")
280
+ .replace(/\?/g, "[^/]");
281
+ return new RegExp(`^${glob}$`, "i").test(".env");
282
+ }
61
283
  /**
62
284
  * Adds `--env-file .env` to every script that runs `nest start` - `start`,
63
285
  * `start:dev` and `start:debug` in a `nest new` project, and any of a
@@ -26,6 +26,12 @@ export declare function inspectProject(cwd: string, version: string, ts: TypeScr
26
26
  * The project's own TypeScript, which the code is edited with - parsed by the
27
27
  * compiler that will build it, so whatever syntax the project uses, it reads.
28
28
  * Undefined without one; the CLI does not bring a compiler of its own.
29
+ *
30
+ * Found in the `node_modules` directories the project resolves from, and
31
+ * loaded by its absolute path from the CLI's own module. Not asked of the
32
+ * project as `require("typescript")`: Node answers that with package
33
+ * self-reference first, and in a project named `typescript` with `exports`
34
+ * it would load and run the project's own file instead, on every link.
29
35
  */
30
36
  export declare function loadTypeScript(cwd: string): TypeScript | undefined;
31
37
  /**
@@ -53,10 +53,23 @@ export function inspectProject(cwd, version, ts) {
53
53
  * The project's own TypeScript, which the code is edited with - parsed by the
54
54
  * compiler that will build it, so whatever syntax the project uses, it reads.
55
55
  * Undefined without one; the CLI does not bring a compiler of its own.
56
+ *
57
+ * Found in the `node_modules` directories the project resolves from, and
58
+ * loaded by its absolute path from the CLI's own module. Not asked of the
59
+ * project as `require("typescript")`: Node answers that with package
60
+ * self-reference first, and in a project named `typescript` with `exports`
61
+ * it would load and run the project's own file instead, on every link.
56
62
  */
57
63
  export function loadTypeScript(cwd) {
58
64
  try {
59
- const ts = createRequire(join(cwd, "package.json"))("typescript");
65
+ const installed = createRequire(join(cwd, "package.json"))
66
+ .resolve.paths("typescript")
67
+ ?.map((dir) => join(dir, "typescript"))
68
+ .find((dir) => existsSync(join(dir, "package.json")));
69
+ if (installed === undefined) {
70
+ return undefined;
71
+ }
72
+ const ts = createRequire(import.meta.url)(installed);
60
73
  return typeof ts.createSourceFile === "function" ? ts : undefined;
61
74
  }
62
75
  catch {
@@ -1,5 +1,6 @@
1
1
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { join, posix } from "node:path";
3
+ import { isProjectFile } from "./project-files.js";
3
4
  import { SDK_PACKAGE } from "./project-setup.js";
4
5
  /** What a step could not do, as the reason the CLI prints. */
5
6
  class ManualStep {
@@ -26,6 +27,11 @@ export function wireApplication(ts, cwd, mainPath, serviceId) {
26
27
  try {
27
28
  const files = planWiring(ts, cwd, mainPath, serviceId);
28
29
  for (const file of files) {
30
+ // A link out of the tree, or a `../` path: some other application's
31
+ // file, which nobody asked to have rewritten.
32
+ if (!isProjectFile(cwd, file.path)) {
33
+ return manual(`${file.path} leads out of the project`);
34
+ }
29
35
  if (syntaxErrors(ts, file.path, file.text) >
30
36
  syntaxErrors(ts, file.path, file.original)) {
31
37
  return manual(`editing ${file.path} would not have left it valid TypeScript`);
@@ -15,8 +15,10 @@ export declare function stringifyLabel(label: Record<string, string | number>):
15
15
  * flushed for the life of the process. That is correct for a counter and fatal
16
16
  * for one labelled with something unbounded - a user id, a request id, a raw
17
17
  * URL - which grows this object forever inside the *host application's* memory
18
- * and adds a row per series to every flush. Summaries need no such cap; their
19
- * windows are cleared on each flush.
18
+ * and adds a row per series to every flush. A summary's labels go when its
19
+ * window does, on each flush written - but a flush that is never written, by
20
+ * an agent switched off or without credentials, never clears one, so a
21
+ * summary that declared no labels is held to the same number per window.
20
22
  *
21
23
  * A thousand is far above a sensible label set and far below a leak.
22
24
  */
@@ -44,6 +46,8 @@ export declare class Counter<TLabel extends string = typeof DEFAULT_LABEL> imple
44
46
  private readonly seriesLimit;
45
47
  /** Whether a non-finite value has already been reported, likewise. */
46
48
  private readonly nonFinite;
49
+ /** Whether a label value no key can be made from has been reported. */
50
+ private readonly labelValues;
47
51
  /**
48
52
  * The name of the counter.
49
53
  * This should be a descriptive name that identifies the counter.
@@ -162,6 +166,13 @@ export declare class Counter<TLabel extends string = typeof DEFAULT_LABEL> imple
162
166
  * @param value Value to increment the counter by.
163
167
  */
164
168
  increment(label: Record<TLabel, string | number>, value: number): void;
169
+ /**
170
+ * Whether `key` may move to `reading`. The reading and its increase since
171
+ * the last flush both go on the wire, and the increase can leave the
172
+ * doubles while the reading stays in them: a counter taken down to -1e308,
173
+ * flushed, then brought back up to 1e308 is 2e308 above its baseline.
174
+ */
175
+ private admitsNewReading;
165
176
  private validateLabels;
166
177
  }
167
178
  export {};
@@ -1,4 +1,5 @@
1
- import { admitsFinite } from "./finite-value.util.js";
1
+ import { admitsFinite, admitsReading } from "./finite-value.util.js";
2
+ import { admitsLabelValues, isLabelSet, MAX_SERIES_KEY_LENGTH, } from "./label-values.util.js";
2
3
  const DEFAULT_LABEL = "default";
3
4
  /**
4
5
  * Serialises a label object into the map key that identifies its series.
@@ -21,18 +22,14 @@ export function stringifyLabel(label) {
21
22
  * flushed for the life of the process. That is correct for a counter and fatal
22
23
  * for one labelled with something unbounded - a user id, a request id, a raw
23
24
  * URL - which grows this object forever inside the *host application's* memory
24
- * and adds a row per series to every flush. Summaries need no such cap; their
25
- * windows are cleared on each flush.
25
+ * and adds a row per series to every flush. A summary's labels go when its
26
+ * window does, on each flush written - but a flush that is never written, by
27
+ * an agent switched off or without credentials, never clears one, so a
28
+ * summary that declared no labels is held to the same number per window.
26
29
  *
27
30
  * A thousand is far above a sensible label set and far below a leak.
28
31
  */
29
32
  export const MAX_SERIES_PER_METRIC = 1_000;
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
33
  /**
37
34
  * Whether a metric may record under `key`: a series it already has, or a new
38
35
  * one that is within the cap and short enough for the collector.
@@ -80,6 +77,8 @@ export class Counter {
80
77
  seriesLimit = { warned: false };
81
78
  /** Whether a non-finite value has already been reported, likewise. */
82
79
  nonFinite = { warned: false };
80
+ /** Whether a label value no key can be made from has been reported. */
81
+ labelValues = { warned: false };
83
82
  /**
84
83
  * The name of the counter.
85
84
  * This should be a descriptive name that identifies the counter.
@@ -209,33 +208,51 @@ export class Counter {
209
208
  }
210
209
  }
211
210
  increment(labelOrValue, value) {
212
- if (this.labels && typeof labelOrValue !== "object") {
211
+ if (this.labels && !isLabelSet(labelOrValue)) {
213
212
  throw new Error("Cannot increment a counter with labels without specifying a label. For example, use `counter.increment({ route: '/login' })`.");
214
213
  }
215
- if (typeof labelOrValue === "object") {
214
+ if (isLabelSet(labelOrValue)) {
216
215
  this.validateLabels(labelOrValue);
216
+ if (!admitsLabelValues(this.name, labelOrValue, this.labelValues)) {
217
+ return;
218
+ }
217
219
  const stringifiedLabel = stringifyLabel(labelOrValue);
218
220
  const incrementValue = value ?? 1;
219
- if (!admitsFinite(this.name, incrementValue, this.nonFinite) ||
221
+ if (!admitsFinite(this.name, incrementValue, this.nonFinite)) {
222
+ return;
223
+ }
224
+ const reading = (this.value[stringifiedLabel] ?? this._initialValue) + incrementValue;
225
+ if (!this.admitsNewReading(stringifiedLabel, reading) ||
220
226
  !admitsSeries(this.name, this.value, stringifiedLabel, this.seriesLimit)) {
221
227
  return;
222
228
  }
223
- this.value[stringifiedLabel] =
224
- (this.value[stringifiedLabel] ?? this._initialValue) + incrementValue;
229
+ this.value[stringifiedLabel] = reading;
225
230
  }
226
231
  else {
227
232
  const incrementValue = labelOrValue ?? 1;
228
233
  if (!admitsFinite(this.name, incrementValue, this.nonFinite)) {
229
234
  return;
230
235
  }
231
- this.value[DEFAULT_LABEL] =
232
- (this.value[DEFAULT_LABEL] ?? this._initialValue) + incrementValue;
236
+ const reading = (this.value[DEFAULT_LABEL] ?? this._initialValue) + incrementValue;
237
+ if (!this.admitsNewReading(DEFAULT_LABEL, reading)) {
238
+ return;
239
+ }
240
+ this.value[DEFAULT_LABEL] = reading;
233
241
  }
234
242
  this._lastUpdated = Date.now();
235
243
  if (this._onChange) {
236
244
  this._onChange(this);
237
245
  }
238
246
  }
247
+ /**
248
+ * Whether `key` may move to `reading`. The reading and its increase since
249
+ * the last flush both go on the wire, and the increase can leave the
250
+ * doubles while the reading stays in them: a counter taken down to -1e308,
251
+ * flushed, then brought back up to 1e308 is 2e308 above its baseline.
252
+ */
253
+ admitsNewReading(key, reading) {
254
+ return admitsReading(this.name, reading, this.nonFinite, this._lastFlushedValue[key] ?? 0);
255
+ }
239
256
  validateLabels(labeledValue) {
240
257
  const keys = Object.keys(labeledValue);
241
258
  const declared = this.labels;
@@ -18,3 +18,17 @@
18
18
  export declare function admitsFinite(metricName: string, value: number, state: {
19
19
  warned: boolean;
20
20
  }): boolean;
21
+ /**
22
+ * Whether a metric may move to `reading`, which an admitted value takes it to,
23
+ * when what goes on the wire is its difference from `baseline` - a counter's
24
+ * increase since the last flush - or the reading itself.
25
+ *
26
+ * Asked after `admitsFinite`, about the result rather than the argument: two
27
+ * finite numbers can add up to an Infinity (`1e308 + 1e308`), which is sent
28
+ * as null just the same, and which nothing added later would bring back. The
29
+ * step is ignored and the reading kept, under the same once-per-metric
30
+ * warning as a non-finite argument.
31
+ */
32
+ export declare function admitsReading(metricName: string, reading: number, state: {
33
+ warned: boolean;
34
+ }, baseline?: number): boolean;
@@ -21,9 +21,41 @@ export function admitsFinite(metricName, value, state) {
21
21
  }
22
22
  if (!state.warned) {
23
23
  state.warned = true;
24
- console.warn(`[observe] Metric "${metricName}" ignored ${value}, which is not a finite number. ` +
24
+ // Only what the warning is about - a NaN, an Infinity, a missing value -
25
+ // is printed. Anything else got past the type at run time, a field of a
26
+ // request body say, and need not convert to a string at all: `{"toString":
27
+ // 1}` throws a TypeError and a deeply nested array a RangeError, out of
28
+ // the call this function exists not to fail. Nor is a string any
29
+ // particular length, or free of line breaks.
30
+ const refused = value;
31
+ const given = typeof refused === "number" || refused === undefined || refused === null
32
+ ? String(refused)
33
+ : `a value of type ${typeof refused}`;
34
+ console.warn(`[observe] Metric "${metricName}" ignored ${given}, which is not a finite number. ` +
25
35
  `Further ones are ignored without another warning. This usually means the value is ` +
26
36
  `computed from something that can be zero or missing (a division by a zero total, a failed parse).`);
27
37
  }
28
38
  return false;
29
39
  }
40
+ /**
41
+ * Whether a metric may move to `reading`, which an admitted value takes it to,
42
+ * when what goes on the wire is its difference from `baseline` - a counter's
43
+ * increase since the last flush - or the reading itself.
44
+ *
45
+ * Asked after `admitsFinite`, about the result rather than the argument: two
46
+ * finite numbers can add up to an Infinity (`1e308 + 1e308`), which is sent
47
+ * as null just the same, and which nothing added later would bring back. The
48
+ * step is ignored and the reading kept, under the same once-per-metric
49
+ * warning as a non-finite argument.
50
+ */
51
+ export function admitsReading(metricName, reading, state, baseline = 0) {
52
+ if (Number.isFinite(reading - baseline)) {
53
+ return true;
54
+ }
55
+ if (!state.warned) {
56
+ state.warned = true;
57
+ console.warn(`[observe] Metric "${metricName}" ignored a value that would take it past the largest number it can report ` +
58
+ `(${Number.MAX_VALUE}). Further ones, and non-finite values, are ignored without another warning.`);
59
+ }
60
+ return false;
61
+ }
@@ -16,6 +16,8 @@ export declare class Gauge<TLabel extends string = typeof DEFAULT_LABEL> impleme
16
16
  private readonly seriesLimit;
17
17
  /** Whether a non-finite value has already been reported, likewise. */
18
18
  private readonly nonFinite;
19
+ /** Whether a label value no key can be made from has been reported. */
20
+ private readonly labelValues;
19
21
  /**
20
22
  * The name of the gauge.
21
23
  * This should be a descriptive name that identifies the gauge.
@@ -1,5 +1,6 @@
1
1
  import { admitsSeries, stringifyLabel } from "./counter.js";
2
- import { admitsFinite } from "./finite-value.util.js";
2
+ import { admitsFinite, admitsReading } from "./finite-value.util.js";
3
+ import { admitsLabelValues, isLabelSet } from "./label-values.util.js";
3
4
  const DEFAULT_LABEL = "default";
4
5
  export class Gauge {
5
6
  /**
@@ -10,6 +11,8 @@ export class Gauge {
10
11
  seriesLimit = { warned: false };
11
12
  /** Whether a non-finite value has already been reported, likewise. */
12
13
  nonFinite = { warned: false };
14
+ /** Whether a label value no key can be made from has been reported. */
15
+ labelValues = { warned: false };
13
16
  /**
14
17
  * The name of the gauge.
15
18
  * This should be a descriptive name that identifies the gauge.
@@ -112,27 +115,36 @@ export class Gauge {
112
115
  }
113
116
  }
114
117
  increment(labelOrValue, value) {
115
- if (this.labels && typeof labelOrValue !== "object") {
118
+ if (this.labels && !isLabelSet(labelOrValue)) {
116
119
  throw new Error("Cannot increment a gauge with labels without specifying a label. For example, use `gauge.increment({ route: '/login' })`.");
117
120
  }
118
- if (typeof labelOrValue === "object") {
121
+ if (isLabelSet(labelOrValue)) {
119
122
  this.validateLabels(labelOrValue);
123
+ if (!admitsLabelValues(this.name, labelOrValue, this.labelValues)) {
124
+ return;
125
+ }
120
126
  const stringifiedLabel = stringifyLabel(labelOrValue);
121
127
  const incrementValue = value ?? 1;
122
- if (!admitsFinite(this.name, incrementValue, this.nonFinite) ||
128
+ if (!admitsFinite(this.name, incrementValue, this.nonFinite)) {
129
+ return;
130
+ }
131
+ const reading = (this.value[stringifiedLabel] ?? this._initialValue) + incrementValue;
132
+ if (!admitsReading(this.name, reading, this.nonFinite) ||
123
133
  !admitsSeries(this.name, this.value, stringifiedLabel, this.seriesLimit)) {
124
134
  return;
125
135
  }
126
- this.value[stringifiedLabel] =
127
- (this.value[stringifiedLabel] ?? this._initialValue) + incrementValue;
136
+ this.value[stringifiedLabel] = reading;
128
137
  }
129
138
  else {
130
139
  const incrementValue = labelOrValue ?? 1;
131
140
  if (!admitsFinite(this.name, incrementValue, this.nonFinite)) {
132
141
  return;
133
142
  }
134
- this.value[DEFAULT_LABEL] =
135
- (this.value[DEFAULT_LABEL] ?? this._initialValue) + incrementValue;
143
+ const reading = (this.value[DEFAULT_LABEL] ?? this._initialValue) + incrementValue;
144
+ if (!admitsReading(this.name, reading, this.nonFinite)) {
145
+ return;
146
+ }
147
+ this.value[DEFAULT_LABEL] = reading;
136
148
  }
137
149
  this._lastUpdated = Date.now();
138
150
  if (this._onChange) {
@@ -140,27 +152,36 @@ export class Gauge {
140
152
  }
141
153
  }
142
154
  decrement(labelOrValue, value) {
143
- if (this.labels && typeof labelOrValue !== "object") {
155
+ if (this.labels && !isLabelSet(labelOrValue)) {
144
156
  throw new Error("Cannot decrement a gauge with labels without specifying a label. For example, use `gauge.decrement({ route: '/login' })`.");
145
157
  }
146
- else if (typeof labelOrValue === "object") {
158
+ else if (isLabelSet(labelOrValue)) {
147
159
  this.validateLabels(labelOrValue);
160
+ if (!admitsLabelValues(this.name, labelOrValue, this.labelValues)) {
161
+ return;
162
+ }
148
163
  const stringifiedLabel = stringifyLabel(labelOrValue);
149
164
  const decrementValue = value ?? 1;
150
- if (!admitsFinite(this.name, decrementValue, this.nonFinite) ||
165
+ if (!admitsFinite(this.name, decrementValue, this.nonFinite)) {
166
+ return;
167
+ }
168
+ const reading = (this.value[stringifiedLabel] ?? this._initialValue) - decrementValue;
169
+ if (!admitsReading(this.name, reading, this.nonFinite) ||
151
170
  !admitsSeries(this.name, this.value, stringifiedLabel, this.seriesLimit)) {
152
171
  return;
153
172
  }
154
- this.value[stringifiedLabel] =
155
- (this.value[stringifiedLabel] ?? this._initialValue) - decrementValue;
173
+ this.value[stringifiedLabel] = reading;
156
174
  }
157
175
  else {
158
176
  const decrementValue = labelOrValue ?? 1;
159
177
  if (!admitsFinite(this.name, decrementValue, this.nonFinite)) {
160
178
  return;
161
179
  }
162
- this.value[DEFAULT_LABEL] =
163
- (this.value[DEFAULT_LABEL] ?? this._initialValue) - decrementValue;
180
+ const reading = (this.value[DEFAULT_LABEL] ?? this._initialValue) - decrementValue;
181
+ if (!admitsReading(this.name, reading, this.nonFinite)) {
182
+ return;
183
+ }
184
+ this.value[DEFAULT_LABEL] = reading;
164
185
  }
165
186
  this._lastUpdated = Date.now();
166
187
  if (this._onChange) {
@@ -168,11 +189,14 @@ export class Gauge {
168
189
  }
169
190
  }
170
191
  setValue(labelOrValue, value) {
171
- if (this.labels && typeof labelOrValue !== "object") {
192
+ if (this.labels && !isLabelSet(labelOrValue)) {
172
193
  throw new Error("Cannot set value of a gauge with labels without specifying a label. For example, use `gauge.setValue({ route: '/login' }, 42)`.");
173
194
  }
174
- else if (typeof labelOrValue === "object") {
195
+ else if (isLabelSet(labelOrValue)) {
175
196
  this.validateLabels(labelOrValue);
197
+ if (!admitsLabelValues(this.name, labelOrValue, this.labelValues)) {
198
+ return;
199
+ }
176
200
  const stringifiedLabel = stringifyLabel(labelOrValue);
177
201
  const newValue = value ?? this._initialValue;
178
202
  if (!admitsFinite(this.name, newValue, this.nonFinite) ||