@nestjs/observe 0.3.12 → 0.3.14

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 (36) hide show
  1. package/README.md +65 -2
  2. package/dist/agent/degraded-ingest.protocol.d.ts +82 -26
  3. package/dist/agent/degraded-ingest.protocol.js +60 -19
  4. package/dist/agent/detached-observe-worker.js +31 -16
  5. package/dist/agent/observe-agent.shared-buffer.d.ts +54 -1
  6. package/dist/agent/observe-agent.shared-buffer.js +127 -22
  7. package/dist/agent/observe-agent.worker.d.ts +29 -0
  8. package/dist/agent/observe-agent.worker.js +80 -10
  9. package/dist/agent/telemetry-wire-contract.js +11 -1
  10. package/dist/encoders/request-snapshot.encoder.d.ts +1 -0
  11. package/dist/encoders/request-snapshot.encoder.js +1 -0
  12. package/dist/interfaces/observe-options.interface.d.ts +13 -1
  13. package/dist/interfaces/request-snapshot.interface.d.ts +13 -0
  14. package/dist/objectives/objectives.registry.d.ts +1 -0
  15. package/dist/objectives/objectives.registry.js +12 -0
  16. package/dist/outgoing/mssql.integration.d.ts +12 -0
  17. package/dist/outgoing/mssql.integration.js +248 -0
  18. package/dist/outgoing/mysql2.integration.js +1 -1
  19. package/dist/outgoing/outgoing-observe-agent.service.js +46 -8
  20. package/dist/outgoing/outgoing-span.recorder.d.ts +7 -0
  21. package/dist/outgoing/outgoing-span.recorder.js +15 -0
  22. package/dist/outgoing/pg.integration.js +1 -1
  23. package/dist/outgoing/sql-statement.util.d.ts +5 -1
  24. package/dist/outgoing/sql-statement.util.js +83 -10
  25. package/dist/protocols/http-observe-agent.service.js +9 -2
  26. package/dist/protocols/job-trace-runner.js +5 -0
  27. package/dist/services/node-runtime-metrics.service.js +1 -1
  28. package/dist/services/operation-trace.registry.d.ts +11 -0
  29. package/dist/services/operation-trace.registry.js +37 -1
  30. package/dist/services/stdout-forwarder.service.js +1 -1
  31. package/dist/services/trace-sampler.service.js +5 -0
  32. package/dist/services/tracer.service.d.ts +19 -0
  33. package/dist/services/tracer.service.js +61 -3
  34. package/dist/utils/ingest-refusal.util.d.ts +7 -5
  35. package/dist/utils/ingest-refusal.util.js +17 -5
  36. package/package.json +9 -4
@@ -0,0 +1,248 @@
1
+ import { errorMonitor } from "node:events";
2
+ import { patchMethod } from "./patch-method.util.js";
3
+ import { describeSanitizedSqlStatement, } from "./sql-statement.util.js";
4
+ /**
5
+ * The procedures a `PreparedStatement` calls on requests of its own: the
6
+ * driver parents those requests to the statement and executes these by name.
7
+ */
8
+ const PREPARED_STATEMENT_PROCEDURES = new Set([
9
+ "sp_prepare",
10
+ "sp_execute",
11
+ "sp_unprepare",
12
+ ]);
13
+ function describeMssqlStatement(sql, enableQuotedIdentifier, redactExecArgs = true) {
14
+ const input = sql.slice(0, 8192);
15
+ const truncated = sql.length > input.length;
16
+ let text = "";
17
+ // T-SQL escapes quotes by doubling them, not with backslashes. Tokenizing
18
+ // first keeps comment markers inside strings and identifiers inert.
19
+ // Double quotes follow connection options; SQL SET overrides are not tracked.
20
+ // Binary literals may continue across lines after a backslash.
21
+ const tokenPattern = /(?<comment>--[^\r\n]*)|\[(?:[^\]]|\]\])*(?:\]|$)|(?<quoted>"(?:[^"]|"")*(?:"|$))|(?<literal>N?'(?:[^']|'')*(?:'|$)|(?<![\w@])\$\s*[+-]?(?:\d+(?:\.\d*)?|\.\d+)|\b0x[\da-f]*(?:\\(?:\r\n|\r|\n)[\da-f]*)*|(?<![\w$@])-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?(?![\w]))|[^]/giy;
22
+ for (let index = 0; index < input.length;) {
23
+ if (input.startsWith("/*", index)) {
24
+ let depth = 1;
25
+ index += 2;
26
+ while (index < input.length && depth) {
27
+ if (input.startsWith("/*", index)) {
28
+ depth++;
29
+ index += 2;
30
+ }
31
+ else if (input.startsWith("*/", index)) {
32
+ depth--;
33
+ index += 2;
34
+ }
35
+ else {
36
+ index++;
37
+ }
38
+ }
39
+ text += " ";
40
+ continue;
41
+ }
42
+ tokenPattern.lastIndex = index;
43
+ const token = tokenPattern.exec(input);
44
+ index = tokenPattern.lastIndex;
45
+ if (token.groups?.comment !== undefined) {
46
+ text += " ";
47
+ }
48
+ else if (token.groups?.literal !== undefined ||
49
+ (!enableQuotedIdentifier && token.groups?.quoted !== undefined)) {
50
+ text += "?";
51
+ }
52
+ else {
53
+ text += token[0];
54
+ }
55
+ }
56
+ if (truncated) {
57
+ // Anchored at the run's start. Unanchored, the engine tried every position
58
+ // inside each run of word characters and backtracked the run each time:
59
+ // quadratic, 0.1 s of a blocked event loop for one 8 KB name. The sign is
60
+ // a number cut between its exponent's sign and digits, `987654e+`, which
61
+ // the tokenizer could not read as a number and left as text.
62
+ text = text.replace(/(^|[^\p{L}\p{M}\p{N}_$@#])[\p{L}\p{M}\p{N}_$@#]+[+-]?$/u, "$1?");
63
+ }
64
+ // `;WITH` is how T-SQL is often written, to end whatever came before.
65
+ text = text.replace(/^[\s;]+/, "");
66
+ if (!CAPTURED_STATEMENT.test(text)) {
67
+ const verb = /^[\s(]*([A-Za-z]+)/.exec(text)?.[1]?.toUpperCase();
68
+ return { operation: verb ?? "QUERY" };
69
+ }
70
+ return nameProcedureCall(describeSanitizedSqlStatement(redactExecArgs ? redactExecArguments(text) : text));
71
+ }
72
+ /**
73
+ * Names a procedure call after its procedure, `EXEC dbo.GetOrders`, with
74
+ * quotes and brackets dropped as from a table name - the same row whether it
75
+ * came through `execute()` or an `EXEC` batch, and a row per procedure rather
76
+ * than one `EXEC` for all of them.
77
+ */
78
+ function nameProcedureCall(description) {
79
+ const exec = /^EXEC(?:UTE)?(?=\s|$)/i.exec(description.statement);
80
+ if (!exec) {
81
+ return description;
82
+ }
83
+ const name = EXEC_TARGET.exec(description.statement.slice(exec[0].length))?.[1]
84
+ .replace(/\s*\.\s*/g, ".")
85
+ .replace(/["[\]]/g, "");
86
+ return {
87
+ ...description,
88
+ operation: (name ? `EXEC ${name}` : "EXEC").slice(0, 64),
89
+ };
90
+ }
91
+ /**
92
+ * A batch may open with a procedure call without EXEC, and its unquoted
93
+ * arguments look like keywords. Statement text is kept only for batches
94
+ * opening with a reserved word that starts a statement: a reserved word cannot
95
+ * name a procedure unquoted, so such a batch is never a call in disguise.
96
+ * Non-reserved statement words (`THROW`, `RECEIVE`, `SEND`) can, and are left
97
+ * out.
98
+ */
99
+ const CAPTURED_STATEMENT = /^[\s(]*(?:SELECT|INSERT|UPDATE|DELETE|MERGE|WITH|EXEC|EXECUTE|SET|DECLARE|IF|WHILE|BEGIN|COMMIT|ROLLBACK|SAVE|TRUNCATE|CREATE|ALTER|DROP|USE|PRINT|RAISERROR|WAITFOR|GRANT|REVOKE|DENY|RETURN|OPEN|CLOSE|FETCH|DEALLOCATE|BREAK|CONTINUE|GOTO|KILL|DBCC|BACKUP|RESTORE|CHECKPOINT|RECONFIGURE|BULK|SETUSER|REVERT|SHUTDOWN|READTEXT|WRITETEXT|UPDATETEXT)(?![\p{L}\p{M}\p{N}\p{Pc}@$#])/iu;
100
+ /**
101
+ * What follows `EXEC`: an optional `@status =`, then the procedure's dotted
102
+ * name, each part bracketed, double-quoted or bare.
103
+ */
104
+ const EXEC_TARGET = /^\s+(?:@[\p{L}_][\p{L}\p{M}\p{N}\p{Pc}@$#]*\s*=\s*)?((?:\[(?:[^\]]|\]\])*\]|"(?:[^"]|"")*"|[\p{L}_@#][\p{L}\p{M}\p{N}\p{Pc}@$#]*)(?:\s*\.\s*(?:\[(?:[^\]]|\]\])*\]|"(?:[^"]|"")*"|[\p{L}_@#][\p{L}\p{M}\p{N}\p{Pc}@$#]*))*)/u;
105
+ function findExec(source, start) {
106
+ for (let index = start; index < source.length;) {
107
+ if (source[index] === "[" || source[index] === '"') {
108
+ const opening = source[index];
109
+ const closing = opening === "[" ? "]" : '"';
110
+ index++;
111
+ while (index < source.length) {
112
+ if (source[index] === closing) {
113
+ if (source[index + 1] === closing) {
114
+ index += 2;
115
+ continue;
116
+ }
117
+ index++;
118
+ break;
119
+ }
120
+ index++;
121
+ }
122
+ continue;
123
+ }
124
+ const match = /^EXEC(?:UTE)?\b/i.exec(source.slice(index));
125
+ if (match &&
126
+ (index === 0 || !/[\w@$#]/.test(source[index - 1])) &&
127
+ !/[\w@$#]/.test(source[index + match[0].length] ?? "")) {
128
+ return { index, length: match[0].length };
129
+ }
130
+ index++;
131
+ }
132
+ return undefined;
133
+ }
134
+ function redactExecArguments(sql) {
135
+ let text = sql;
136
+ let searchFrom = 0;
137
+ while (searchFrom < text.length) {
138
+ const exec = findExec(text, searchFrom);
139
+ if (!exec) {
140
+ break;
141
+ }
142
+ let end = exec.index + exec.length;
143
+ let inBracket = false;
144
+ let inQuotedIdentifier = false;
145
+ while (end < text.length) {
146
+ if (inBracket) {
147
+ if (text[end] === "]" && text[end + 1] === "]") {
148
+ end += 2;
149
+ continue;
150
+ }
151
+ if (text[end] === "]")
152
+ inBracket = false;
153
+ }
154
+ else if (inQuotedIdentifier) {
155
+ if (text[end] === '"' && text[end + 1] === '"') {
156
+ end += 2;
157
+ continue;
158
+ }
159
+ if (text[end] === '"')
160
+ inQuotedIdentifier = false;
161
+ }
162
+ else if (text[end] === "[") {
163
+ inBracket = true;
164
+ }
165
+ else if (text[end] === '"') {
166
+ inQuotedIdentifier = true;
167
+ }
168
+ else if (text[end] === ";") {
169
+ break;
170
+ }
171
+ end++;
172
+ }
173
+ const tail = text.slice(exec.index + exec.length, end);
174
+ const procedure = EXEC_TARGET.exec(tail)?.[0] ?? "";
175
+ // Only what follows the procedure is an argument: `EXEC dbo.Refresh`
176
+ // has none to replace.
177
+ if (tail.slice(procedure.length).trim()) {
178
+ const prefix = text.slice(exec.index, exec.index + exec.length + procedure.length);
179
+ text = `${text.slice(0, exec.index)}${prefix} ?${text.slice(end)}`;
180
+ searchFrom = exec.index + prefix.length + 2;
181
+ }
182
+ else {
183
+ searchFrom = end + 1;
184
+ }
185
+ }
186
+ return text;
187
+ }
188
+ /**
189
+ * These internal boundaries follow template expansion and precede pool
190
+ * checkout. The tedious driver's `_batch` delegates to `_query`.
191
+ */
192
+ export function patchMssql(mssql, recorder) {
193
+ const wrap = (method) => (original) => function (...args) {
194
+ const [command, callback] = args;
195
+ // Asked first: describing a statement means tokenizing it, which an
196
+ // untraced or sampled-out call should not pay for.
197
+ if (typeof command !== "string" ||
198
+ typeof callback !== "function" ||
199
+ !recorder.isRecording()) {
200
+ return original.apply(this, args);
201
+ }
202
+ let sql = command;
203
+ let procedure = method === "_execute";
204
+ if (procedure &&
205
+ typeof this.parent?.unprepare === "function" &&
206
+ PREPARED_STATEMENT_PROCEDURES.has(command)) {
207
+ // Preparing and unpreparing are the statement's bookkeeping, and
208
+ // `sp_execute` would name every prepared statement alike: the span is
209
+ // the statement it executes, described like any other query.
210
+ const prepared = this.parent.statement;
211
+ if (command !== "sp_execute" || typeof prepared !== "string") {
212
+ return original.apply(this, args);
213
+ }
214
+ sql = prepared;
215
+ procedure = false;
216
+ }
217
+ const { operation, statement } = describeMssqlStatement(procedure ? `EXEC ${sql}` : sql, this.parent?.config?.options?.enableQuotedIdentifier !== false, !procedure);
218
+ const span = recorder.open("mssql", operation, statement === undefined
219
+ ? { "db.system": "mssql" }
220
+ : { "db.system": "mssql", "db.statement": statement });
221
+ if (!span) {
222
+ return original.apply(this, args);
223
+ }
224
+ let streamError;
225
+ const onError = (error) => {
226
+ streamError ??= error;
227
+ };
228
+ // Observe streaming errors without swallowing unhandled error events.
229
+ this.on(errorMonitor, onError);
230
+ const finish = (error) => {
231
+ this.removeListener(errorMonitor, onError);
232
+ span.end(error ?? streamError);
233
+ };
234
+ args[1] = function (error, ...rest) {
235
+ finish(error);
236
+ return callback.call(this, error, ...rest);
237
+ };
238
+ try {
239
+ return original.apply(this, args);
240
+ }
241
+ catch (error) {
242
+ finish(error);
243
+ throw error;
244
+ }
245
+ };
246
+ const patched = ["_query", "_execute"].map((method) => patchMethod(mssql.Request?.prototype, method, wrap(method)));
247
+ return patched.some(Boolean);
248
+ }
@@ -21,7 +21,7 @@ export function patchMysql2(mysql2, recorder) {
21
21
  if (typeof sql !== "string") {
22
22
  return original.apply(this, args);
23
23
  }
24
- const { operation, statement } = describeSqlStatement(sql);
24
+ const { operation, statement } = describeSqlStatement(sql, "mysql");
25
25
  const span = recorder.open("mysql2", operation, {
26
26
  "db.system": "mysql",
27
27
  "db.statement": statement,
@@ -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
  }