@nestjs/observe 0.3.11 → 0.3.13

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 (39) hide show
  1. package/README.md +71 -2
  2. package/dist/agent/degraded-ingest.protocol.d.ts +87 -16
  3. package/dist/agent/degraded-ingest.protocol.js +62 -17
  4. package/dist/agent/detached-observe-worker.assembly.d.ts +1 -0
  5. package/dist/agent/detached-observe-worker.assembly.js +1 -0
  6. package/dist/agent/detached-observe-worker.d.ts +5 -0
  7. package/dist/agent/detached-observe-worker.js +129 -63
  8. package/dist/agent/observe-agent.shared-buffer.d.ts +54 -1
  9. package/dist/agent/observe-agent.shared-buffer.js +127 -22
  10. package/dist/agent/observe-agent.worker.d.ts +38 -1
  11. package/dist/agent/observe-agent.worker.js +134 -23
  12. package/dist/agent/telemetry-wire-contract.js +11 -1
  13. package/dist/encoders/request-snapshot.encoder.d.ts +1 -0
  14. package/dist/encoders/request-snapshot.encoder.js +1 -0
  15. package/dist/interfaces/observe-options.interface.d.ts +17 -2
  16. package/dist/interfaces/request-snapshot.interface.d.ts +13 -0
  17. package/dist/objectives/objectives.registry.d.ts +1 -0
  18. package/dist/objectives/objectives.registry.js +12 -0
  19. package/dist/outgoing/mssql.integration.d.ts +12 -0
  20. package/dist/outgoing/mssql.integration.js +248 -0
  21. package/dist/outgoing/mysql2.integration.js +1 -1
  22. package/dist/outgoing/outgoing-observe-agent.service.js +46 -8
  23. package/dist/outgoing/outgoing-span.recorder.d.ts +7 -0
  24. package/dist/outgoing/outgoing-span.recorder.js +15 -0
  25. package/dist/outgoing/pg.integration.js +1 -1
  26. package/dist/outgoing/sql-statement.util.d.ts +5 -1
  27. package/dist/outgoing/sql-statement.util.js +83 -10
  28. package/dist/protocols/http-observe-agent.service.js +9 -2
  29. package/dist/protocols/job-trace-runner.js +5 -0
  30. package/dist/services/node-runtime-metrics.service.js +1 -1
  31. package/dist/services/operation-trace.registry.d.ts +11 -0
  32. package/dist/services/operation-trace.registry.js +37 -1
  33. package/dist/services/stdout-forwarder.service.js +1 -1
  34. package/dist/services/trace-sampler.service.js +5 -0
  35. package/dist/services/tracer.service.d.ts +19 -0
  36. package/dist/services/tracer.service.js +61 -3
  37. package/dist/utils/ingest-refusal.util.d.ts +8 -3
  38. package/dist/utils/ingest-refusal.util.js +24 -3
  39. package/package.json +9 -4
@@ -18,6 +18,7 @@ import { OperationTraceRegistry } from "../services/operation-trace.registry.js"
18
18
  import { loadAsResolvedBy, loadOptionalPeer, } from "../utils/optional-peer.util.js";
19
19
  import { subscribeOutgoingHttp } from "./http.integration.js";
20
20
  import { patchMongodb } from "./mongodb.integration.js";
21
+ import { patchMssql } from "./mssql.integration.js";
21
22
  import { patchMysql2 } from "./mysql2.integration.js";
22
23
  import { OutgoingSpanRecorder } from "./outgoing-span.recorder.js";
23
24
  import { patchPg } from "./pg.integration.js";
@@ -25,14 +26,15 @@ import { patchPg } from "./pg.integration.js";
25
26
  * Spans for what leaves the process: database queries and outbound HTTP.
26
27
  *
27
28
  * The drivers are instrumented, not the ORMs. Every ORM a Nest application is
28
- * likely to use ends in one of three drivers, so three small patches cover
29
+ * likely to use ends in a supported driver, so small patches cover
29
30
  * TypeORM, MikroORM, Prisma's driver adapters, Mongoose, Knex, Drizzle and
30
31
  * Sequelize alike, and none of them has to be known by name. Each driver is an
31
32
  * optional peer nobody is asked to install: it is looked up, and patched only
32
33
  * if the application already has it.
33
34
  */
34
35
  /**
35
- * ORMs that list a driver under `dependencies` rather than `peerDependencies`.
36
+ * Packages that list a driver under `dependencies` rather than
37
+ * `peerDependencies`.
36
38
  *
37
39
  * A peer resolves to the application's own copy, which is the one patched. A
38
40
  * direct dependency does too - until the versions disagree, and npm nests a
@@ -40,15 +42,50 @@ import { patchPg } from "./pg.integration.js";
40
42
  * so that happens on a single patch release of difference (its `mysql2`
41
43
  * 3.24.3 beside an application's 3.24.4); Mongoose asks for a minor range.
42
44
  * Queries through the ORM would then run on a copy nobody patched and simply
43
- * not appear, with nothing to say why.
45
+ * not appear, with nothing to say why. Prisma's driver adapters depend on
46
+ * their drivers directly too: the pg adapter has since 6.11 and asks for
47
+ * ^8.16.3, and the SQL Server adapter asks for `mssql` ^12.2, so an
48
+ * application pinned outside those ranges runs Prisma's queries on a nested
49
+ * copy.
44
50
  *
45
- * TypeORM, Drizzle, Knex, Sequelize and Prisma's adapters take their driver
46
- * as a peer and need no entry.
51
+ * The same holds beyond the ORMs, for packages that reach the database on
52
+ * the application's behalf: query libraries, job queues, session stores,
53
+ * Keyv's cache stores and Socket.IO's Postgres adapter. pg-promise and
54
+ * express-mysql-session pin their driver exactly, and @hokify/agenda still
55
+ * asks for `mongodb` 4. What they run inside a request is recorded whenever
56
+ * they share the application's copy, so a nested copy is followed too; a
57
+ * queue's own polling runs outside any trace and records nothing either way.
58
+ *
59
+ * TypeORM, Drizzle, Knex and Sequelize take their driver as a peer and need
60
+ * no entry.
47
61
  */
48
62
  const DRIVER_DEPENDENTS = {
49
- pg: ["@mikro-orm/postgresql"],
50
- mysql2: ["@mikro-orm/mysql"],
51
- mongodb: ["mongoose", "@mikro-orm/mongodb"],
63
+ pg: [
64
+ "@mikro-orm/postgresql",
65
+ "@prisma/adapter-pg",
66
+ "pg-promise",
67
+ "@slonik/pg-driver",
68
+ "@databases/pg",
69
+ "pg-boss",
70
+ "graphile-worker",
71
+ "connect-pg-simple",
72
+ "@keyv/postgres",
73
+ "@socket.io/postgres-adapter",
74
+ ],
75
+ mysql2: [
76
+ "@mikro-orm/mysql",
77
+ "serverless-mysql",
78
+ "express-mysql-session",
79
+ "@keyv/mysql",
80
+ ],
81
+ mongodb: [
82
+ "mongoose",
83
+ "@mikro-orm/mongodb",
84
+ "@hokify/agenda",
85
+ "connect-mongodb-session",
86
+ "@keyv/mongo",
87
+ ],
88
+ mssql: ["@prisma/adapter-mssql"],
52
89
  };
53
90
  let OutgoingObserveAgentService = OutgoingObserveAgentService_1 = class OutgoingObserveAgentService {
54
91
  options;
@@ -65,6 +102,7 @@ let OutgoingObserveAgentService = OutgoingObserveAgentService_1 = class Outgoing
65
102
  this.patchDriver("pg", "pg", DRIVER_DEPENDENTS.pg, (module) => patchPg(module, recorder));
66
103
  this.patchDriver("mysql2", "mysql2", DRIVER_DEPENDENTS.mysql2, (module) => patchMysql2(module, recorder));
67
104
  this.patchDriver("mongodb", "mongodb/lib/cmap/connection", DRIVER_DEPENDENTS.mongodb, (module) => patchMongodb(module, recorder));
105
+ this.patchDriver("mssql", "mssql", DRIVER_DEPENDENTS.mssql, (module) => patchMssql(module, recorder));
68
106
  }
69
107
  if (outgoing?.http !== false) {
70
108
  this.unsubscribeHttp = subscribeOutgoingHttp(recorder, () => {
@@ -36,6 +36,13 @@ export declare class OutgoingSpanRecorder {
36
36
  * or a call an outer entry point already covers.
37
37
  */
38
38
  open(className: string, methodKey: string, tags: Tags): OpenOutgoingSpan | undefined;
39
+ /**
40
+ * Whether `open` would attach a span here - asked first by an integration
41
+ * whose description of a call costs more than the call's own bookkeeping
42
+ * (a statement it has to tokenize), so that untraced and sampled-out calls
43
+ * do not pay for a description nobody will read.
44
+ */
45
+ isRecording(): boolean;
39
46
  /** Runs `fn` with nested entry points told the call is already covered. */
40
47
  cover<T>(fn: () => T): T;
41
48
  /**
@@ -66,6 +66,21 @@ export class OutgoingSpanRecorder {
66
66
  },
67
67
  };
68
68
  }
69
+ /**
70
+ * Whether `open` would attach a span here - asked first by an integration
71
+ * whose description of a call costs more than the call's own bookkeeping
72
+ * (a statement it has to tokenize), so that untraced and sampled-out calls
73
+ * do not pay for a description nobody will read.
74
+ */
75
+ isRecording() {
76
+ if (this.covered.getStore()) {
77
+ return false;
78
+ }
79
+ const store = this.asyncLocalStorage.getStore();
80
+ const registryKey = store?.get(TRACE_REGISTRY_KEY) ?? store?.get(this.traceIdKey);
81
+ return (typeof registryKey === "string" &&
82
+ this.operationTraceRegistry.hasTrace(registryKey));
83
+ }
69
84
  /** Runs `fn` with nested entry points told the call is already covered. */
70
85
  cover(fn) {
71
86
  return this.covered.run(true, fn);
@@ -20,7 +20,7 @@ export function patchPg(pg, recorder) {
20
20
  if (typeof text !== "string" || typeof config?.submit === "function") {
21
21
  return original.apply(this, args);
22
22
  }
23
- const { operation, statement } = describeSqlStatement(text);
23
+ const { operation, statement } = describeSqlStatement(text, "postgresql");
24
24
  const span = recorder.open("pg", operation, {
25
25
  "db.system": "postgresql",
26
26
  "db.statement": statement,
@@ -9,6 +9,8 @@ export interface SqlStatementDescription {
9
9
  /** The statement with every literal replaced, safe to leave the process. */
10
10
  statement: string;
11
11
  }
12
+ /** The SQL a driver speaks, which decides what its quotes and comments mean. */
13
+ export type SqlDialect = "postgresql" | "mysql";
12
14
  /**
13
15
  * Strips a SQL statement of its values.
14
16
  *
@@ -18,4 +20,6 @@ export interface SqlStatementDescription {
18
20
  * shipped is the statement's shape. Comments go too: ORMs and query taggers
19
21
  * put request ids and user ids in them.
20
22
  */
21
- export declare function describeSqlStatement(sql: string): SqlStatementDescription;
23
+ export declare function describeSqlStatement(sql: string, dialect: SqlDialect): SqlStatementDescription;
24
+ /** Names and bounds SQL whose literals and comments have already been removed. */
25
+ export declare function describeSanitizedSqlStatement(sql: string): SqlStatementDescription;
@@ -11,6 +11,73 @@ const TABLE_AFTER = {
11
11
  REPLACE: /\bINTO\s+([\w."`[\]]+)/i,
12
12
  UPDATE: /^\s*UPDATE\s+(?:ONLY\s+)?([\w."`[\]]+)/i,
13
13
  };
14
+ /**
15
+ * Comments, quoted names and literals, found left to right: a comment marker
16
+ * inside a string, or a quote inside a comment or a name, is part of the token
17
+ * it is in. Each runs to the end of the input when nothing closes it. Names
18
+ * are kept, comments become a space and literals `?`.
19
+ *
20
+ * Postgres quotes names in `"`. A plain string takes a backslash as it is and
21
+ * an `E'...'` string as an escape. A dollar quote opens only where a token
22
+ * can start - Postgres reads `a$b$` as one name - and block comments nest, so
23
+ * `/*` is matched alone and its end found by hand.
24
+ *
25
+ * MySQL quotes strings in `"` as well as `'`, as its default sql_mode does
26
+ * (under ANSI_QUOTES a `"` name goes too), with backslash escapes in both -
27
+ * NO_BACKSLASH_ESCAPES is not assumed - and `#` starts a comment. Its block
28
+ * comments do not nest.
29
+ */
30
+ const TOKEN = {
31
+ postgresql: /(?<nested>\/\*)|(?<comment>--[^\n]*)|(?<name>"(?:[^"]|"")*(?:"|$)|`(?:[^`]|``)*(?:`|$))|(?<![\w$])(?<escape>[eE])'(?:[^'\\]|\\[\s\S]?|'')*(?:'|$)|(?<plain>'(?:[^']|'')*(?:'|$))|(?<!\w)\$(?<tag>[A-Za-z_]*)\$[\s\S]*?(?:\$\k<tag>\$|$)/g,
32
+ mysql: /(?<comment>\/\*[\s\S]*?(?:\*\/|$)|--[^\n]*|#[^\n]*)|(?<name>`(?:[^`]|``)*(?:`|$))|'(?:[^'\\]|\\[\s\S]?|'')*(?:'|$)|"(?:[^"\\]|\\[\s\S]?|"")*(?:"|$)/g,
33
+ };
34
+ function stripLiteralsAndComments(sql, dialect) {
35
+ const token = TOKEN[dialect];
36
+ token.lastIndex = 0;
37
+ let text = "";
38
+ let index = 0;
39
+ for (let match; (match = token.exec(sql)); index = token.lastIndex) {
40
+ text += sql.slice(index, match.index);
41
+ const { nested, comment, name, escape, plain } = match.groups;
42
+ if (nested !== undefined) {
43
+ token.lastIndex = endOfNestedComment(sql, token.lastIndex);
44
+ text += " ";
45
+ }
46
+ else if (comment !== undefined) {
47
+ text += " ";
48
+ }
49
+ else if (name !== undefined) {
50
+ text += name;
51
+ }
52
+ else if (plain !== undefined && /(?<!\\)(?:\\\\)*\\'/.test(plain)) {
53
+ // An odd run of backslashes before a quote: with
54
+ // standard_conforming_strings off, the quote does not end the string
55
+ // here, so where it does end is unknown - and so is everything after.
56
+ return `${text}?`;
57
+ }
58
+ else {
59
+ text += `${escape ?? ""}?`;
60
+ }
61
+ }
62
+ return text + sql.slice(index);
63
+ }
64
+ /** Where a Postgres block comment opened before `index` ends. */
65
+ function endOfNestedComment(sql, index) {
66
+ for (let depth = 1; depth && index < sql.length;) {
67
+ if (sql.startsWith("/*", index)) {
68
+ depth++;
69
+ index += 2;
70
+ }
71
+ else if (sql.startsWith("*/", index)) {
72
+ depth--;
73
+ index += 2;
74
+ }
75
+ else {
76
+ index++;
77
+ }
78
+ }
79
+ return index;
80
+ }
14
81
  /**
15
82
  * Strips a SQL statement of its values.
16
83
  *
@@ -20,17 +87,23 @@ const TABLE_AFTER = {
20
87
  * shipped is the statement's shape. Comments go too: ORMs and query taggers
21
88
  * put request ids and user ids in them.
22
89
  */
23
- export function describeSqlStatement(sql) {
90
+ export function describeSqlStatement(sql, dialect) {
91
+ const input = sql.slice(0, MAX_STATEMENT_LENGTH * 4);
92
+ let sanitized = stripLiteralsAndComments(input, dialect)
93
+ // A number that is not part of an identifier or a `$1` placeholder: hex,
94
+ // binary and octal too, and digits grouped with `_` (Postgres 16).
95
+ .replace(/(?<![\w$])(?:0x[\da-f_]+|0b[01_]+|0o[0-7_]+|-?\d[\d_]*(?:\.[\d_]+)?(?:e[+-]?\d[\d_]*)?)(?![\w])/gi, "?");
96
+ if (sql.length > input.length) {
97
+ // The bound may have cut a number short - `987654e+` is no longer one -
98
+ // so whatever word it cut goes too. Anchored at the run's start, which
99
+ // keeps it linear on a run 8 KB long.
100
+ sanitized = sanitized.replace(/(^|[^\p{L}\p{M}\p{N}_$])[\p{L}\p{M}\p{N}_$]+[+-]?$/u, "$1?");
101
+ }
102
+ return describeSanitizedSqlStatement(sanitized);
103
+ }
104
+ /** Names and bounds SQL whose literals and comments have already been removed. */
105
+ export function describeSanitizedSqlStatement(sql) {
24
106
  const statement = sql
25
- .slice(0, MAX_STATEMENT_LENGTH * 4)
26
- .replace(/\/\*[\s\S]*?\*\//g, " ")
27
- .replace(/--[^\n]*/g, " ")
28
- // Dollar-quoted (Postgres), then single-quoted with doubled-quote and
29
- // backslash escapes. Double quotes and backticks are identifiers - kept.
30
- .replace(/\$([A-Za-z_]*)\$[\s\S]*?\$\1\$/g, "?")
31
- .replace(/'(?:[^'\\]|\\.|'')*'/g, "?")
32
- // A number that is not part of an identifier or a `$1` placeholder.
33
- .replace(/(?<![\w$])-?\d+(?:\.\d+)?(?:e[+-]?\d+)?(?![\w])/gi, "?")
34
107
  .replace(/\(\s*\?(?:\s*,\s*\?)+\s*\)/g, "(?)")
35
108
  .replace(/\(\s*\$\d+(?:\s*,\s*\$\d+)+\s*\)/g, "($n)")
36
109
  .replace(/\s+/g, " ")
@@ -113,15 +113,22 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
113
113
  }
114
114
  }
115
115
  }
116
+ // A request that is not recorded still carries its trace id, which an
117
+ // adopted `x-request-id` can share with a recorded request. A registry
118
+ // key of its own, never registered, keeps its lookups off that trace.
119
+ const skip = () => {
120
+ store.set(TRACE_REGISTRY_KEY, uuidv7());
121
+ done();
122
+ };
116
123
  if (this.shouldIgnoreRequest(req) || this.isUntracedPreflight(req)) {
117
- return done();
124
+ return skip();
118
125
  }
119
126
  const shouldCapture = this.traceSamplerService.shouldCapture("http", {
120
127
  url: req.url,
121
128
  method: req.method,
122
129
  });
123
130
  if (!shouldCapture) {
124
- return done();
131
+ return skip();
125
132
  }
126
133
  // Sensitive query parameters are masked whether or not the deployment
127
134
  // configured anything: an opt-in redactor protects only those who
@@ -137,6 +137,11 @@ export class JobTraceRunner {
137
137
  * stop the job itself from running.
138
138
  */
139
139
  isIgnored(context) {
140
+ // Jobs never reach the sampler, which is where every other protocol
141
+ // learns that the agent is disabled.
142
+ if (this.options.enabled === false) {
143
+ return true;
144
+ }
140
145
  try {
141
146
  return Boolean(this.options.jobs?.ignore?.(context));
142
147
  }
@@ -72,7 +72,7 @@ let NodeRuntimeMetricsService = NodeRuntimeMetricsService_1 = class NodeRuntimeM
72
72
  this.options.runtimeMetrics ??= true;
73
73
  }
74
74
  onModuleInit() {
75
- if (!this.options.runtimeMetrics) {
75
+ if (!this.options.runtimeMetrics || this.options.enabled === false) {
76
76
  return;
77
77
  }
78
78
  this.lastCpuUsage = process.cpuUsage();
@@ -143,6 +143,17 @@ export declare class OperationTraceRegistry {
143
143
  */
144
144
  spanId: string | undefined, className: string, methodKey: string, callerId: string | undefined, error?: Error | string | object): void;
145
145
  addRouteMetadataToTrace(requestId: string, requestMethod: RequestMethod, path: string): void;
146
+ setOperationId(traceId: TraceId, operationId: string): void;
147
+ /**
148
+ * Puts the name `setOperationId` chose in place of the transport's, and
149
+ * keeps the one it replaces beside it as `defaultOperationId`. That one
150
+ * tells the collector what the request would otherwise be grouped under,
151
+ * and tells `@Objective` that the request was renamed.
152
+ *
153
+ * Renaming a request to the name it already had changes nothing, so it is
154
+ * not recorded as a rename.
155
+ */
156
+ private applyCustomOperationId;
146
157
  /**
147
158
  * Labels a trace with the GraphQL root field being resolved.
148
159
  *
@@ -3,6 +3,7 @@ import { activeSliceRecorder } from "../profiling/span-slice-recorder.js";
3
3
  import { uuidv7 } from "../utils/uuid-v7.util.js";
4
4
  import { TraceSpanDelegate } from "../trace-span.delegate.js";
5
5
  import { collectCodeFrames } from "../utils/source-context.util.js";
6
+ import { fallbackOperationId } from "../utils/fallback-operation-id.util.js";
6
7
  import { LogRedactor } from "../utils/log-redactor.js";
7
8
  import { CALLER_METADATA_KEY } from "../observe.constants.js";
8
9
  import { collapseRepeatedSpans, DEFAULT_SPAN_COLLAPSE, } from "./collapse-repeated-spans.util.js";
@@ -432,6 +433,34 @@ export class OperationTraceRegistry {
432
433
  }
433
434
  snapshot.operationId = path;
434
435
  }
436
+ setOperationId(traceId, operationId) {
437
+ const snapshot = this.traceSnapshots.get(traceId);
438
+ if (snapshot && "protocol" in snapshot) {
439
+ snapshot.customOperationId = operationId;
440
+ }
441
+ }
442
+ /**
443
+ * Puts the name `setOperationId` chose in place of the transport's, and
444
+ * keeps the one it replaces beside it as `defaultOperationId`. That one
445
+ * tells the collector what the request would otherwise be grouped under,
446
+ * and tells `@Objective` that the request was renamed.
447
+ *
448
+ * Renaming a request to the name it already had changes nothing, so it is
449
+ * not recorded as a rename.
450
+ */
451
+ applyCustomOperationId(snapshot, operationId) {
452
+ // The same fallback the buffer applies to a request no route matched, so
453
+ // the name kept is the one the request would have been reported under.
454
+ const defaultOperationId = snapshot.operationId ??
455
+ fallbackOperationId(snapshot.attributes?.originalUrl);
456
+ if (operationId === defaultOperationId) {
457
+ return;
458
+ }
459
+ snapshot.operationId = operationId;
460
+ if (defaultOperationId !== undefined) {
461
+ snapshot.attributes = { ...snapshot.attributes, defaultOperationId };
462
+ }
463
+ }
435
464
  /**
436
465
  * Labels a trace with the GraphQL root field being resolved.
437
466
  *
@@ -537,12 +566,19 @@ export class OperationTraceRegistry {
537
566
  }
538
567
  }
539
568
  cleanup();
540
- // These three are what distinguish the registry's working copy from the
569
+ // These four are what distinguish the registry's working copy from the
541
570
  // snapshot the API receives, so removing them is the hand-off.
542
571
  const bookkeeping = snapshot;
572
+ const customOperationId = bookkeeping.customOperationId;
543
573
  delete bookkeeping.refsCounter;
544
574
  delete bookkeeping.refsMarkedAsComplete;
545
575
  delete bookkeeping.errorStatusCode;
576
+ delete bookkeeping.customOperationId;
577
+ // Before `skipSpans`, which judges the operation by the name it is
578
+ // reported under.
579
+ if (customOperationId !== undefined && "protocol" in snapshot) {
580
+ this.applyCustomOperationId(snapshot, customOperationId);
581
+ }
546
582
  // Emptied rather than removed: the collector requires the field, and an
547
583
  // empty tree is what it already stores for a trace it sampled out - the
548
584
  // operation keeps its row, its error and every chart it feeds.
@@ -86,7 +86,7 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
86
86
  this.options.redaction?.enabled === false
87
87
  ? null
88
88
  : new LogRedactor(this.options.redaction);
89
- if (this.options.forwardLogs) {
89
+ if (this.options.forwardLogs && this.options.enabled !== false) {
90
90
  this.start();
91
91
  }
92
92
  }
@@ -18,6 +18,11 @@ let TraceSamplerService = class TraceSamplerService {
18
18
  this.options = options;
19
19
  }
20
20
  shouldCapture(protocol, attributes) {
21
+ // Ahead of the sample rate: a disabled agent records nothing, whatever
22
+ // share of traces it was told to keep.
23
+ if (this.options.enabled === false) {
24
+ return false;
25
+ }
21
26
  if (!this.options.tracesSampleRate) {
22
27
  return true; // Always capture if sample rate is not set
23
28
  }
@@ -15,6 +15,8 @@ export declare class TracerService<Store extends Record<string | symbol, unknown
15
15
  private readonly counters;
16
16
  private readonly gauges;
17
17
  private readonly summaries;
18
+ private readonly logger;
19
+ private hasReportedUnusableOperationId;
18
20
  constructor(operationTraceRegistry: OperationTraceRegistry, als: AsyncLocalStorage<Map<KeyOf<Store> | TraceKey, any>>, observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults);
19
21
  /**
20
22
  * Creates a new trace span with the given name and executes the provided callback within that span.
@@ -113,6 +115,23 @@ export declare class TracerService<Store extends Record<string | symbol, unknown
113
115
  * propagate an id that simply isn't there yet.
114
116
  */
115
117
  currentTraceId(): string | null;
118
+ /**
119
+ * Sets the operation id reported for the current request trace, in place of
120
+ * its route path, GraphQL root field or message pattern. Works from anywhere
121
+ * in the request - middleware, guard, interceptor or handler - and a later
122
+ * call replaces an earlier one.
123
+ *
124
+ * Use a stable, bounded name, not a per-request value, so requests aggregate
125
+ * together. The name is trimmed and cut to 255 characters, and anything but
126
+ * a non-blank string is ignored. Does nothing when there is no active trace
127
+ * or the request is not recorded.
128
+ */
129
+ setOperationId(operationId: string): void;
130
+ /**
131
+ * An unusable name comes from the same call site on every request, so it is
132
+ * reported once rather than once per request.
133
+ */
134
+ private reportUnusableOperationId;
116
135
  /**
117
136
  * Sets an attribute on the current trace.
118
137
  * For example, you can use this to add metadata to the current request trace for later use and retrieval.
@@ -10,7 +10,8 @@ var __metadata = (this && this.__metadata) || function (k, v) {
10
10
  var __param = (this && this.__param) || function (paramIndex, decorator) {
11
11
  return function (target, key) { decorator(target, key, paramIndex); }
12
12
  };
13
- import { Inject, Injectable } from "@nestjs/common";
13
+ var TracerService_1;
14
+ import { Inject, Injectable, Logger } from "@nestjs/common";
14
15
  import { AsyncLocalStorage } from "async_hooks";
15
16
  import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
16
17
  import { Gauge, Summary } from "../custom-metrics/index.js";
@@ -18,7 +19,13 @@ import { Counter } from "../custom-metrics/counter.js";
18
19
  import { TraceSpanDelegate } from "../trace-span.delegate.js";
19
20
  import { CALLER_METADATA_KEY, OBSERVE_OPTIONS, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
20
21
  import { OperationTraceRegistry } from "./operation-trace.registry.js";
21
- let TracerService = class TracerService {
22
+ /**
23
+ * Longest operation id the collector stores, counted by code point as it
24
+ * counts. A longer one is cut there anyway; cut here, a name built from a
25
+ * request body cannot grow the batch it rides in without bound.
26
+ */
27
+ const MAX_OPERATION_ID_LENGTH = 255;
28
+ let TracerService = TracerService_1 = class TracerService {
22
29
  operationTraceRegistry;
23
30
  als;
24
31
  observeAgentSharedBuffer;
@@ -29,6 +36,8 @@ let TracerService = class TracerService {
29
36
  counters = new Map();
30
37
  gauges = new Map();
31
38
  summaries = new Map();
39
+ logger = new Logger(TracerService_1.name);
40
+ hasReportedUnusableOperationId = false;
32
41
  constructor(operationTraceRegistry, als, observeAgentSharedBuffer, options) {
33
42
  this.operationTraceRegistry = operationTraceRegistry;
34
43
  this.als = als;
@@ -102,6 +111,11 @@ let TracerService = class TracerService {
102
111
  // in this case anyway, so the outcome is unchanged.
103
112
  return;
104
113
  }
114
+ if (this.options.enabled === false) {
115
+ // A disabled agent opens no traces, and the registry warns about every
116
+ // error it is handed without one.
117
+ return;
118
+ }
105
119
  const callerId = store.get(CALLER_METADATA_KEY);
106
120
  this.operationTraceRegistry.captureError(traceId, callerId, error, tags ?? {});
107
121
  }
@@ -182,6 +196,50 @@ let TracerService = class TracerService {
182
196
  const traceId = store?.get(this.options.traceIdKey);
183
197
  return typeof traceId === "string" ? traceId : null;
184
198
  }
199
+ /**
200
+ * Sets the operation id reported for the current request trace, in place of
201
+ * its route path, GraphQL root field or message pattern. Works from anywhere
202
+ * in the request - middleware, guard, interceptor or handler - and a later
203
+ * call replaces an earlier one.
204
+ *
205
+ * Use a stable, bounded name, not a per-request value, so requests aggregate
206
+ * together. The name is trimmed and cut to 255 characters, and anything but
207
+ * a non-blank string is ignored. Does nothing when there is no active trace
208
+ * or the request is not recorded.
209
+ */
210
+ setOperationId(operationId) {
211
+ // Typed, but often read off a request body, which nothing checks at
212
+ // runtime: a number would have the collector refuse the batch it rides in,
213
+ // and a blank name would have the agent drop the request, error and all.
214
+ const name = typeof operationId === "string" ? operationId.trim() : "";
215
+ if (!name) {
216
+ this.reportUnusableOperationId(operationId);
217
+ return;
218
+ }
219
+ const store = this.als.getStore();
220
+ const traceId = store?.get(TRACE_REGISTRY_KEY) ?? store?.get(this.options.traceIdKey);
221
+ if (typeof traceId === "string") {
222
+ this.operationTraceRegistry.setOperationId(traceId, name.length > MAX_OPERATION_ID_LENGTH
223
+ ? Array.from(name).slice(0, MAX_OPERATION_ID_LENGTH).join("")
224
+ : name);
225
+ }
226
+ }
227
+ /**
228
+ * An unusable name comes from the same call site on every request, so it is
229
+ * reported once rather than once per request.
230
+ */
231
+ reportUnusableOperationId(value) {
232
+ if (this.hasReportedUnusableOperationId) {
233
+ return;
234
+ }
235
+ this.hasReportedUnusableOperationId = true;
236
+ const given = value === null || value === undefined
237
+ ? String(value)
238
+ : typeof value === "string"
239
+ ? "a blank string"
240
+ : `a value of type ${typeof value}`;
241
+ this.logger.warn(`setOperationId ignored ${given}: an operation id is a non-blank string. Later ones are not reported.`);
242
+ }
185
243
  /**
186
244
  * Sets an attribute on the current trace.
187
245
  * For example, you can use this to add metadata to the current request trace for later use and retrieval.
@@ -239,7 +297,7 @@ let TracerService = class TracerService {
239
297
  };
240
298
  }
241
299
  };
242
- TracerService = __decorate([
300
+ TracerService = TracerService_1 = __decorate([
243
301
  Injectable(),
244
302
  __param(3, Inject(OBSERVE_OPTIONS)),
245
303
  __metadata("design:paramtypes", [OperationTraceRegistry,
@@ -1,14 +1,19 @@
1
1
  /**
2
2
  * Explains a 429 from the collector in the operator's terms.
3
3
  *
4
- * The collector refuses ingest for three different reasons, and until this
4
+ * The collector refuses ingest for several different reasons, and until this
5
5
  * existed the agent reported all of them as "the account may be out of
6
6
  * credits or over budget" - which sent an operator whose card had been
7
7
  * declined to the pricing page, and one whose rate cap had engaged to their
8
8
  * invoices. The body tells them apart: a quota refusal carries
9
9
  * `code: "USAGE_LIMIT_REACHED"` with the plan and the counts, and a quota
10
- * refusal caused by a declined payment adds `reason: "payment_failed"`. A
11
- * rate cap, and any older collector, sends neither and gets the old sentence.
10
+ * refusal caused by a declined payment adds `reason: "payment_failed"` - or
11
+ * `reason: "overage_budget"` when the account's own $0 overage budget stopped
12
+ * collection once its included events were spent. Credentials the collector
13
+ * has already rejected carry `code: "CREDENTIALS_REJECTED"` - a 429 rather
14
+ * than another 401, so that agents which pause only on a 429 stop retrying
15
+ * them. A rate cap, and any older collector, sends none of these and gets the
16
+ * old sentence.
12
17
  *
13
18
  * Written self-contained on purpose - no imports, no module-scope constants -
14
19
  * because the telemetry worker is a stringified function and this travels
@@ -1,14 +1,19 @@
1
1
  /**
2
2
  * Explains a 429 from the collector in the operator's terms.
3
3
  *
4
- * The collector refuses ingest for three different reasons, and until this
4
+ * The collector refuses ingest for several different reasons, and until this
5
5
  * existed the agent reported all of them as "the account may be out of
6
6
  * credits or over budget" - which sent an operator whose card had been
7
7
  * declined to the pricing page, and one whose rate cap had engaged to their
8
8
  * invoices. The body tells them apart: a quota refusal carries
9
9
  * `code: "USAGE_LIMIT_REACHED"` with the plan and the counts, and a quota
10
- * refusal caused by a declined payment adds `reason: "payment_failed"`. A
11
- * rate cap, and any older collector, sends neither and gets the old sentence.
10
+ * refusal caused by a declined payment adds `reason: "payment_failed"` - or
11
+ * `reason: "overage_budget"` when the account's own $0 overage budget stopped
12
+ * collection once its included events were spent. Credentials the collector
13
+ * has already rejected carry `code: "CREDENTIALS_REJECTED"` - a 429 rather
14
+ * than another 401, so that agents which pause only on a 429 stop retrying
15
+ * them. A rate cap, and any older collector, sends none of these and gets the
16
+ * old sentence.
12
17
  *
13
18
  * Written self-contained on purpose - no imports, no module-scope constants -
14
19
  * because the telemetry worker is a stringified function and this travels
@@ -22,6 +27,12 @@ export const describeIngestRefusal = (body) => {
22
27
  const detail = body !== null && typeof body === "object"
23
28
  ? body
24
29
  : {};
30
+ if (detail.code === "CREDENTIALS_REJECTED") {
31
+ // Nothing to do with the account's usage: the credentials are wrong and
32
+ // the process reads them once, so the fix is valid ones and a restart.
33
+ // The pause that follows only stops the agent asking in the meantime.
34
+ return "appKey and appSecret were rejected; check that both are valid for this application, then restart the process, which reads them once at start-up";
35
+ }
25
36
  if (detail.code !== "USAGE_LIMIT_REACHED") {
26
37
  return "the account may be out of credits or over budget";
27
38
  }
@@ -39,6 +50,16 @@ export const describeIngestRefusal = (body) => {
39
50
  (counts ? ` (${counts})` : "") +
40
51
  "; update the payment method in the dashboard to resume");
41
52
  }
53
+ if (detail.reason === "overage_budget") {
54
+ // The account asked for nothing past its plan - a $0 overage budget - and
55
+ // the plan's events are spent. Nothing is wrong with the plan or the
56
+ // card, so neither an upgrade nor a payment is the fix: raising the
57
+ // budget is, or the turn of the month, which the operator would otherwise
58
+ // not know is coming.
59
+ return ("the account's overage budget is $0 and its included events for this period are used" +
60
+ (counts ? ` (${counts})` : "") +
61
+ ", so collection is stopped until the 1st (UTC) or until the overage budget is raised on the dashboard's Usage page");
62
+ }
42
63
  return ("the account has used its included events for this period" +
43
64
  (counts ? ` (${counts})` : "") +
44
65
  "; upgrade the plan or wait for the period to reset");