@nestjs/observe 0.3.26 → 0.3.28

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 (61) hide show
  1. package/README.md +38 -2
  2. package/dist/agent/observe-agent.shared-buffer.js +5 -0
  3. package/dist/agent/telemetry-wire-contract.js +3 -3
  4. package/dist/cli/link.js +24 -2
  5. package/dist/cli/package-manager.d.ts +6 -0
  6. package/dist/cli/package-manager.js +60 -3
  7. package/dist/cli/project-files.d.ts +25 -5
  8. package/dist/cli/project-files.js +98 -15
  9. package/dist/custom-metrics/summary.js +17 -10
  10. package/dist/instrument/create-instance-decorator.instrument.js +390 -38
  11. package/dist/instrument/raw-receiver.d.ts +6 -0
  12. package/dist/instrument/raw-receiver.js +32 -0
  13. package/dist/interfaces/observe-options.interface.d.ts +14 -5
  14. package/dist/otlp/otlp-span.mapper.d.ts +2 -0
  15. package/dist/otlp/otlp-span.mapper.js +19 -1
  16. package/dist/otlp/otlp-trace-exporter.service.d.ts +63 -9
  17. package/dist/otlp/otlp-trace-exporter.service.js +232 -38
  18. package/dist/outgoing/http.integration.js +36 -11
  19. package/dist/outgoing/mongodb.integration.d.ts +3 -1
  20. package/dist/outgoing/mongodb.integration.js +93 -18
  21. package/dist/outgoing/mssql.integration.js +9 -4
  22. package/dist/outgoing/mysql2.integration.js +3 -1
  23. package/dist/outgoing/outgoing-observe-agent.service.js +5 -1
  24. package/dist/outgoing/pg.integration.js +5 -0
  25. package/dist/outgoing/sql-statement.util.js +36 -10
  26. package/dist/protocols/bull-observe-agent.service.js +21 -0
  27. package/dist/protocols/deferred-trace-completion.d.ts +8 -2
  28. package/dist/protocols/deferred-trace-completion.js +40 -3
  29. package/dist/protocols/graphql-observe-agent.service.d.ts +62 -2
  30. package/dist/protocols/graphql-observe-agent.service.js +188 -14
  31. package/dist/protocols/graphql-operation-parser.js +45 -14
  32. package/dist/protocols/http-observe-agent.service.d.ts +14 -7
  33. package/dist/protocols/http-observe-agent.service.js +57 -14
  34. package/dist/protocols/job-trace-runner.d.ts +7 -0
  35. package/dist/protocols/job-trace-runner.js +72 -8
  36. package/dist/protocols/rpc-observe-agent.service.d.ts +61 -0
  37. package/dist/protocols/rpc-observe-agent.service.js +146 -10
  38. package/dist/protocols/ws-observe-agent.service.js +1 -1
  39. package/dist/services/logger-patcher.service.js +13 -3
  40. package/dist/services/operation-trace.registry.d.ts +13 -0
  41. package/dist/services/operation-trace.registry.js +195 -65
  42. package/dist/services/stdout-forwarder.service.js +22 -2
  43. package/dist/services/tracer.service.d.ts +19 -14
  44. package/dist/services/tracer.service.js +57 -34
  45. package/dist/utils/capture-request.util.js +36 -8
  46. package/dist/utils/context-accessor.util.d.ts +16 -0
  47. package/dist/utils/context-accessor.util.js +28 -0
  48. package/dist/utils/default-trace-id-generator.util.js +5 -7
  49. package/dist/utils/error-stack.util.d.ts +13 -0
  50. package/dist/utils/error-stack.util.js +166 -0
  51. package/dist/utils/log-line.parser.d.ts +8 -0
  52. package/dist/utils/log-line.parser.js +13 -4
  53. package/dist/utils/log-redactor.js +184 -10
  54. package/dist/utils/redact-url-query.d.ts +16 -5
  55. package/dist/utils/redact-url-query.js +20 -7
  56. package/dist/utils/source-context.util.d.ts +6 -0
  57. package/dist/utils/source-context.util.js +68 -33
  58. package/dist/utils/source-map-resolver.util.js +25 -4
  59. package/dist/utils/store-copy.util.d.ts +10 -0
  60. package/dist/utils/store-copy.util.js +43 -0
  61. package/package.json +4 -3
@@ -1,3 +1,4 @@
1
+ import { AsyncLocalStorage } from "async_hooks";
1
2
  import { subscribe, unsubscribe } from "diagnostics_channel";
2
3
  import { openTelemetryWritesTraceparent } from "../utils/opentelemetry.util.js";
3
4
  import { redactUrlQuery } from "../utils/redact-url-query.js";
@@ -41,6 +42,11 @@ obfuscateUrl) {
41
42
  * `traceparent` has to be written, for the span `start` opens later.
42
43
  */
43
44
  const presetSpanIds = new WeakMap();
45
+ /**
46
+ * The async context a `node:http` request was created in, for `start` to
47
+ * open its span in - see `http.client.request.start`.
48
+ */
49
+ const createdIn = new WeakMap();
44
50
  const subscriptions = [];
45
51
  const on = (channel, handler) => {
46
52
  const guarded = (message) => {
@@ -129,6 +135,9 @@ obfuscateUrl) {
129
135
  // runtimes there is simply no propagation for this client; `start` below
130
136
  // fires after the header block is already on its way.
131
137
  on("http.client.request.created", ({ request }) => {
138
+ // Taken for every request, in a trace or not: whichever context
139
+ // `start` fires in is no more this request's when it has none.
140
+ createdIn.set(request, AsyncLocalStorage.snapshot());
132
141
  const { url } = describeNodeRequest(request);
133
142
  const trace = currentTrace();
134
143
  if (!trace || options.ignore?.(url) || !shouldPropagate(url)) {
@@ -152,19 +161,35 @@ obfuscateUrl) {
152
161
  }
153
162
  }
154
163
  });
164
+ // `start` fires once the request is ended, which is not always in the call
165
+ // that made it: a body piped in ends it from the source's `end` event, in
166
+ // the context of whoever opened the source's socket - another request's,
167
+ // for a pooled connection an earlier one opened. So the span opens in the
168
+ // context the request was created in, where `created` fired; on runtimes
169
+ // without that event, where `start` fired.
155
170
  on("http.client.request.start", ({ request }) => {
156
- const { host, url, method } = describeNodeRequest(request);
157
- const presetSpanId = presetSpanIds.get(request);
158
- presetSpanIds.delete(request);
159
- if (!open(request, method, url, host, presetSpanId)) {
160
- return;
171
+ const runInCreated = createdIn.get(request);
172
+ createdIn.delete(request);
173
+ const begin = () => {
174
+ const { host, url, method } = describeNodeRequest(request);
175
+ const presetSpanId = presetSpanIds.get(request);
176
+ presetSpanIds.delete(request);
177
+ if (!open(request, method, url, host, presetSpanId)) {
178
+ return;
179
+ }
180
+ // `close` always fires, with or without a response. An `error`
181
+ // listener would tell more, but adding one changes what an otherwise
182
+ // unhandled request error does to the process.
183
+ request.once?.("close", () => close(request, request.res
184
+ ? undefined
185
+ : new Error("Request closed with no response")));
186
+ };
187
+ if (runInCreated) {
188
+ runInCreated(begin);
189
+ }
190
+ else {
191
+ begin();
161
192
  }
162
- // `close` always fires, with or without a response. An `error` listener
163
- // would tell more, but adding one changes what an otherwise unhandled
164
- // request error does to the process.
165
- request.once?.("close", () => close(request, request.res
166
- ? undefined
167
- : new Error("Request closed with no response")));
168
193
  });
169
194
  on("http.client.request.error", ({ request, error }) => close(request, error));
170
195
  on("http.client.response.finish", ({ request }) => close(request));
@@ -6,7 +6,9 @@ interface MongoConnectionModule {
6
6
  }
7
7
  /**
8
8
  * A command with its values removed: field names and operators stay, since
9
- * they are the query's shape, and every primitive becomes `?`.
9
+ * they are the query's shape, and every primitive becomes `?`. The one value
10
+ * kept is the collection a command names, which is to a command what the
11
+ * table is to a SQL statement.
10
12
  *
11
13
  * Arrays come in two kinds and are told apart by what they hold. A list of
12
14
  * values keeps one element - `$in: [1, 2, 3]` and `$in: [4]` are the same
@@ -24,9 +24,49 @@ const DRIVER_HOUSEKEEPING = new Set([
24
24
  "endSessions",
25
25
  "killCursors",
26
26
  ]);
27
+ /**
28
+ * Commands whose first value is the collection, or the namespace, they act
29
+ * on: what the driver builds for a collection's own methods, and the
30
+ * collection commands an application sends through `db.command()`. Only these
31
+ * keep that value. Anywhere else it is data like any other - the user of
32
+ * `createUser`, `dropUser` and `usersInfo`, the role of `createRole`, the free
33
+ * text of `logApplicationMessage`. A command missing from the list loses its
34
+ * collection from the span, and nothing else.
35
+ */
36
+ const NAMES_A_COLLECTION = new Set([
37
+ "find",
38
+ "insert",
39
+ "update",
40
+ "delete",
41
+ "aggregate",
42
+ "count",
43
+ "distinct",
44
+ "findAndModify",
45
+ "findandmodify",
46
+ "mapReduce",
47
+ "mapreduce",
48
+ "create",
49
+ "drop",
50
+ "renameCollection",
51
+ "collMod",
52
+ "collStats",
53
+ "validate",
54
+ "compact",
55
+ "reIndex",
56
+ "convertToCapped",
57
+ "cloneCollectionAsCapped",
58
+ "createIndexes",
59
+ "dropIndexes",
60
+ "listIndexes",
61
+ "createSearchIndexes",
62
+ "updateSearchIndex",
63
+ "dropSearchIndex",
64
+ ]);
27
65
  /**
28
66
  * A command with its values removed: field names and operators stay, since
29
- * they are the query's shape, and every primitive becomes `?`.
67
+ * they are the query's shape, and every primitive becomes `?`. The one value
68
+ * kept is the collection a command names, which is to a command what the
69
+ * table is to a SQL statement.
30
70
  *
31
71
  * Arrays come in two kinds and are told apart by what they hold. A list of
32
72
  * values keeps one element - `$in: [1, 2, 3]` and `$in: [4]` are the same
@@ -36,13 +76,33 @@ const DRIVER_HOUSEKEEPING = new Set([
36
76
  */
37
77
  export function describeMongoCommand(command) {
38
78
  const [name] = Object.keys(command);
39
- const target = name === undefined ? undefined : command[name];
79
+ const target = name !== undefined && NAMES_A_COLLECTION.has(name)
80
+ ? command[name]
81
+ : undefined;
40
82
  const operation = name === undefined
41
83
  ? "command"
42
84
  : typeof target === "string"
43
85
  ? `${name} ${target}`
44
86
  : name;
87
+ // What is left of the statement to write. A command is the application's
88
+ // data, and often its client's: a document that refers to one sub-document
89
+ // from many fields - a GraphQL variable used many times over, a YAML alias -
90
+ // is small to hold and has no end when copied out as a tree, and the
91
+ // command is described before the driver's size limit can refuse it. Every
92
+ // value is charged one character and every field its name, never more than
93
+ // they take up once written, so by the time the budget is spent the walk is
94
+ // past the cut below and the statement is what it would have been.
95
+ let budget = MAX_STATEMENT_LENGTH;
96
+ // Telling a list of values from a list of documents means looking at every
97
+ // element, which the budget cannot charge for: a list of values is one `?`
98
+ // however long it is. So each array is looked through once, and the fields
99
+ // that refer to it again are answered from here.
100
+ const documentsOf = new Map();
45
101
  const scrub = (value, depth) => {
102
+ budget -= 1;
103
+ if (budget <= 0) {
104
+ return "?";
105
+ }
46
106
  if (value === null || typeof value !== "object") {
47
107
  return "?";
48
108
  }
@@ -50,7 +110,11 @@ export function describeMongoCommand(command) {
50
110
  return "?";
51
111
  }
52
112
  if (Array.isArray(value)) {
53
- const documents = value.filter((item) => item !== null && typeof item === "object");
113
+ let documents = documentsOf.get(value);
114
+ if (documents === undefined) {
115
+ documents = value.filter((item) => item !== null && typeof item === "object");
116
+ documentsOf.set(value, documents);
117
+ }
54
118
  if (documents.length === 0) {
55
119
  return value.length === 0 ? [] : ["?"];
56
120
  }
@@ -63,21 +127,10 @@ export function describeMongoCommand(command) {
63
127
  if (proto !== Object.prototype && proto !== null) {
64
128
  return "?";
65
129
  }
66
- const out = {};
67
- for (const [key, item] of Object.entries(value)) {
68
- out[key] = scrub(item, depth + 1);
69
- }
70
- return out;
130
+ return fields(Object.entries(value), (item) => scrub(item, depth + 1));
71
131
  };
72
- const shape = {};
73
- for (const [key, value] of Object.entries(command)) {
74
- // Session, cluster time and read preference: driver bookkeeping.
75
- if (key === "lsid" || key.startsWith("$")) {
76
- continue;
77
- }
78
- shape[key] =
79
- key === name && typeof value === "string" ? value : scrub(value, 0);
80
- }
132
+ // Session, cluster time and read preference: driver bookkeeping.
133
+ const shape = fields(Object.entries(command).filter(([key]) => key !== "lsid" && !key.startsWith("$")), (value, key) => key === name && typeof target === "string" ? target : scrub(value, 0));
81
134
  let statement;
82
135
  try {
83
136
  statement = JSON.stringify(shape).slice(0, MAX_STATEMENT_LENGTH);
@@ -86,6 +139,24 @@ export function describeMongoCommand(command) {
86
139
  statement = operation;
87
140
  }
88
141
  return { operation, statement };
142
+ /**
143
+ * The fields of a document, described one by one until the budget is spent.
144
+ * Defined, not assigned: the names are the application's data, and
145
+ * assigning one called `__proto__` or `constructor` reaches
146
+ * `Object.prototype` instead of making a field - an accessor that throws
147
+ * under `--disable-proto=throw`, a read-only property once it is frozen.
148
+ */
149
+ function fields(entries, describe) {
150
+ const described = [];
151
+ for (const [key, value] of entries) {
152
+ if (budget <= 0) {
153
+ break;
154
+ }
155
+ budget -= key.length;
156
+ described.push([key, describe(value, key)]);
157
+ }
158
+ return Object.fromEntries(described);
159
+ }
89
160
  }
90
161
  /**
91
162
  * Command spans for the `mongodb` driver, and so for Mongoose and the Mongo
@@ -110,7 +181,11 @@ export function patchMongodb(connectionModule, recorder) {
110
181
  return original.apply(this, args);
111
182
  }
112
183
  const [commandName] = Object.keys(command);
113
- if (commandName === undefined || DRIVER_HOUSEKEEPING.has(commandName)) {
184
+ // Asked before the command is described: an untraced or sampled-out
185
+ // call should not pay for a description nobody will read.
186
+ if (commandName === undefined ||
187
+ DRIVER_HOUSEKEEPING.has(commandName) ||
188
+ !recorder.isRecording()) {
114
189
  return original.apply(this, args);
115
190
  }
116
191
  const { operation, statement } = describeMongoCommand(command);
@@ -18,7 +18,11 @@ function describeMssqlStatement(sql, enableQuotedIdentifier, redactExecArgs = tr
18
18
  // first keeps comment markers inside strings and identifiers inert.
19
19
  // Double quotes follow connection options; SQL SET overrides are not tracked.
20
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;
21
+ // No name starts with a digit, and T-SQL needs no space after a number:
22
+ // `42ORDER BY` is a number and a keyword, so the word that follows does not
23
+ // decide whether it is one. A digit after `#` is part of a name, `#2fa`,
24
+ // and `-0x1F` is a minus and a binary literal, not `-0` and a word.
25
+ const tokenPattern = /(?<comment>--[^\r\n]*)|\[(?:[^\]]|\]\])*(?:\]|$)|(?<quoted>"(?:[^"]|"")*(?:"|$))|(?<literal>N?'(?:[^']|'')*(?:'|$)|(?<![\w@])\$\s*[+-]?(?:\d+(?:\.\d*)?|\.\d+)|\b0x[\da-f]*(?:\\(?:\r\n|\r|\n)[\da-f]*)*|(?<![\w$@#])-?(?!0x)(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?)|[^]/giy;
22
26
  for (let index = 0; index < input.length;) {
23
27
  if (input.startsWith("/*", index)) {
24
28
  let depth = 1;
@@ -57,9 +61,10 @@ function describeMssqlStatement(sql, enableQuotedIdentifier, redactExecArgs = tr
57
61
  // Anchored at the run's start. Unanchored, the engine tried every position
58
62
  // inside each run of word characters and backtracked the run each time:
59
63
  // 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?");
64
+ // a number cut between its exponent's sign and digits, `987654e+`: the
65
+ // tokenizer read its digits as a number and left `e+` as text, so the `?`
66
+ // of the digits goes with the word.
67
+ text = text.replace(/(^|[^\p{L}\p{M}\p{N}_$@#])\??[\p{L}\p{M}\p{N}_$@#]+[+-]?$/u, "$1?");
63
68
  }
64
69
  // `;WITH` is how T-SQL is often written, to end whatever came before.
65
70
  text = text.replace(/^[\s;]+/, "");
@@ -26,7 +26,9 @@ export function patchMysql2(mysql2, recorder) {
26
26
  args[last] = AsyncResource.bind(args[last]);
27
27
  }
28
28
  const sql = typeof first === "string" ? first : first?.sql;
29
- if (typeof sql !== "string") {
29
+ // Asked before the statement is described: an untraced or sampled-out
30
+ // call should not pay for tokenizing it.
31
+ if (typeof sql !== "string" || !recorder.isRecording()) {
30
32
  return original.apply(this, args);
31
33
  }
32
34
  const { operation, statement } = describeSqlStatement(sql, "mysql");
@@ -115,7 +115,11 @@ let OutgoingObserveAgentService = OutgoingObserveAgentService_1 = class Outgoing
115
115
  this.patchDriver("pg", "pg", DRIVER_DEPENDENTS.pg, (module) => patchPg(module, recorder));
116
116
  this.patchDriver("mysql2", "mysql2", DRIVER_DEPENDENTS.mysql2, (module) => patchMysql2(module, recorder));
117
117
  this.patchDriver("mongodb", "mongodb/lib/cmap/connection", DRIVER_DEPENDENTS.mongodb, (module) => patchMongodb(module, recorder));
118
- this.patchDriver("mssql", "mssql", DRIVER_DEPENDENTS.mssql, (module) => patchMssql(module, recorder));
118
+ // The class that is patched, not `mssql` itself: loading that entry
119
+ // makes tedious the driver of every request mssql creates on its own
120
+ // behalf, which breaks an application that runs on
121
+ // `mssql/msnodesqlv8`.
122
+ this.patchDriver("mssql", "mssql/lib/tedious/request", DRIVER_DEPENDENTS.mssql, (Request) => patchMssql({ Request }, recorder));
119
123
  }
120
124
  if (outgoing?.http !== false) {
121
125
  // undici creates a request, and publishes the channel read below, in
@@ -29,6 +29,11 @@ export function patchPg(pg, recorder) {
29
29
  if (typeof text !== "string" || typeof config?.submit === "function") {
30
30
  return original.apply(this, args);
31
31
  }
32
+ // Asked before the statement is described: an untraced or sampled-out
33
+ // call should not pay for tokenizing it.
34
+ if (!recorder.isRecording()) {
35
+ return original.apply(this, args);
36
+ }
32
37
  const { operation, statement } = describeSqlStatement(text, "postgresql");
33
38
  const span = recorder.open("pg", operation, {
34
39
  "db.system": "postgresql",
@@ -99,21 +99,49 @@ function withoutFunctionArguments(statement) {
99
99
  * where a token can start - Postgres reads `a$b$` as one name - and its tag
100
100
  * is empty, or a letter, `_` or non-ASCII character followed by any of those
101
101
  * or digits, so `$q1$` opens one and `$1` stays a placeholder. Block
102
- * comments nest, so `/*` is matched alone and its end found by hand.
102
+ * comments nest, so `/*` is matched alone and its end found by hand. A `--`
103
+ * comment ends at a carriage return as well as a line feed: Postgres reads
104
+ * either as the end of the line, and a comment run on past a lone `\r` would
105
+ * have the SQL after it, quotes and all, read as part of it.
103
106
  *
104
107
  * MySQL quotes strings in `"` as well as `'`, as its default sql_mode does
105
108
  * (under ANSI_QUOTES a `"` name goes too), with backslash escapes in both,
106
109
  * and `#` starts a comment. `--` does
107
110
  * only before whitespace or a control character, as MySQL reads it:
108
111
  * `credit--5` is `credit - -5`, and the rest of its line is still SQL, quotes
109
- * and all. Its block comments do not nest.
112
+ * and all. Its comments end at a line feed alone, as MySQL ends them, and
113
+ * its block comments do not nest.
110
114
  */
111
115
  const TOKEN = {
112
- postgresql: /(?<nested>\/\*)|(?<comment>--[^\n]*)|(?<name>"(?:[^"]|"")*(?:"|$))|(?<![\w$])(?<escape>[eE])'(?:[^'\\]|\\[\s\S]?|'')*(?:'|$)|(?<plain>'(?:[^']|'')*(?:'|$))|(?<!\w)\$(?<tag>(?:[A-Za-z_\u0080-\uffff][\w\u0080-\uffff]*)?)\$[\s\S]*?(?:\$\k<tag>\$|$)/g,
116
+ postgresql: /(?<nested>\/\*)|(?<comment>--[^\r\n]*)|(?<name>"(?:[^"]|"")*(?:"|$))|(?<![\w$])(?<escape>[eE])'(?:[^'\\]|\\[\s\S]?|'')*(?:'|$)|(?<plain>'(?:[^']|'')*(?:'|$))|(?<!\w)\$(?<tag>(?:[A-Za-z_\u0080-\uffff][\w\u0080-\uffff]*)?)\$[\s\S]*?(?:\$\k<tag>\$|$)/g,
113
117
  mysql:
114
118
  // eslint-disable-next-line no-control-regex -- MySQL's rule for `--`.
115
119
  /(?<comment>\/\*[\s\S]*?(?:\*\/|$)|--(?=[\u0000-\u0020\u007f]|$)[^\n]*|#[^\n]*)|(?<name>`(?:[^`]|``)*(?:`|$))|(?<plain>'(?:[^'\\]|\\[\s\S]?|'')*(?:'|$)|"(?:[^"\\]|\\[\s\S]?|"")*(?:"|$))/g,
116
120
  };
121
+ /**
122
+ * A number that is not part of an identifier or a `$1` placeholder: hex,
123
+ * binary and octal too, digits grouped with `_` (Postgres 16), and a point
124
+ * with no digit after it, `3.e15`, which is one number to both dialects.
125
+ *
126
+ * The server needs no space after a number, so the word that follows does
127
+ * not decide whether it is one: `-0.141588WHERE`, and `219099999AND` before
128
+ * Postgres 15, are a number and a keyword. No Postgres name starts with a
129
+ * digit. A MySQL name can, but only digits without a point or an exponent:
130
+ * `2fa_code` is a name, `1.5AND`, `.5AND` and `1e5OR` are not, and a point
131
+ * after a name is no decimal point, `t.2fa_code`. An integer run into a word
132
+ * is a name to MySQL, `219099999AND`, and is kept as one.
133
+ *
134
+ * Quoted names are matched first, so `"2fa_code"` and `"2022_sales"` stay as
135
+ * they are. Inside one, a number standing on its own goes as it always has -
136
+ * `"order 66"` is `"order ?"`, and `"4815162342"`, more likely a value quoted
137
+ * the wrong way than a column, is `"?"`.
138
+ */
139
+ const NUMBER = {
140
+ postgresql: /(?<name>"(?:[^"]|"")*")|(?<![\w$])-?(?:0x[\da-f_]+|0b[01_]+|0o[0-7_]+|\d[\d_]*(?:\.[\d_]*)?(?:e[+-]?\d[\d_]*)?)/gi,
141
+ mysql: /(?<name>`(?:[^`]|``)*`)|(?<![\w$])(?:(?:0x[\da-f_]+|0b[01_]+|0o[0-7_]+)(?!\w)|-?\d[\d_]*(?:\.[\d_]*(?:e[+-]?\d[\d_]*)?|e[+-]?\d[\d_]*|(?!\w))|(?<=(?<![\w$`])\.)\d[\d_]*)/gi,
142
+ };
143
+ /** A number within a quoted name: one no word character runs on from. */
144
+ const NUMBER_IN_NAME = /(?<![\w$])(?:0x[\da-f_]+|0b[01_]+|0o[0-7_]+|-?\d[\d_]*(?:\.[\d_]*)?(?:e[+-]?\d[\d_]*)?)(?!\w)/gi;
117
145
  /**
118
146
  * An odd run of backslashes before the quote a string opened with. Whether
119
147
  * that quote ends the string is a session setting the statement does not
@@ -181,15 +209,13 @@ function endOfNestedComment(sql, index) {
181
209
  */
182
210
  export function describeSqlStatement(sql, dialect) {
183
211
  const input = sql.slice(0, MAX_STATEMENT_LENGTH * 4);
184
- let sanitized = stripLiteralsAndComments(input, dialect)
185
- // A number that is not part of an identifier or a `$1` placeholder: hex,
186
- // binary and octal too, and digits grouped with `_` (Postgres 16).
187
- .replace(/(?<![\w$])(?:0x[\da-f_]+|0b[01_]+|0o[0-7_]+|-?\d[\d_]*(?:\.[\d_]+)?(?:e[+-]?\d[\d_]*)?)(?![\w])/gi, "?");
212
+ let sanitized = stripLiteralsAndComments(input, dialect).replace(NUMBER[dialect], (_number, name) => name?.replace(NUMBER_IN_NAME, "?") ?? "?");
188
213
  if (sql.length > input.length) {
189
- // The bound may have cut a number short - `987654e+` is no longer one -
190
- // so whatever word it cut goes too. Anchored at the run's start, which
214
+ // The bound may have cut a number short - `987654e+` is no longer one,
215
+ // and its digits are a `?` with `e+` after it - so whatever word it cut
216
+ // goes too, with the `?` before it. Anchored at the run's start, which
191
217
  // keeps it linear on a run 8 KB long.
192
- sanitized = sanitized.replace(/(^|[^\p{L}\p{M}\p{N}_$])[\p{L}\p{M}\p{N}_$]+[+-]?$/u, "$1?");
218
+ sanitized = sanitized.replace(/(^|[^\p{L}\p{M}\p{N}_$])\??[\p{L}\p{M}\p{N}_$]+[+-]?$/u, "$1?");
193
219
  }
194
220
  return describeSanitizedSqlStatement(sanitized);
195
221
  }
@@ -21,6 +21,26 @@ import { JobTraceRunner, readJobTimes } from "./job-trace-runner.js";
21
21
  const ORIGINAL_SET_HANDLER = Symbol.for("nestjs.observe.bull.setHandler");
22
22
  /** Bull names an unnamed job this; reporting it would name every job the same. */
23
23
  const BULL_DEFAULT_JOB_NAME = "__default__";
24
+ /** The longest delay a Node timer keeps; a longer one fires after 1 ms. */
25
+ const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
26
+ /**
27
+ * When Bull fails a run on its own, read off the job's `timeout` option as
28
+ * Bull reads it: it races the handler's promise against a timer of that many
29
+ * ms from the moment the handler returns, and fails the job once the timer
30
+ * wins. A falsy timeout and `Infinity` arm none. Any other value that is not
31
+ * a positive number - `-1`, `"50"` - makes that race throw, which fails the
32
+ * job at once, and one past what a timer can hold fires after 1 ms.
33
+ */
34
+ function readBullTimeout(opts) {
35
+ const timeout = opts?.timeout;
36
+ if (!timeout || timeout === Number.POSITIVE_INFINITY) {
37
+ return undefined;
38
+ }
39
+ if (typeof timeout !== "number" || timeout < 0) {
40
+ return 0;
41
+ }
42
+ return timeout > MAX_TIMER_DELAY_MS ? 1 : timeout;
43
+ }
24
44
  /**
25
45
  * Job tracing for the original Bull, which `@nestjs/bull` wraps - the same
26
46
  * snapshots `@nestjs/bullmq` produces, from a driver a large share of Nest
@@ -96,6 +116,7 @@ let BullObserveAgentService = BullObserveAgentService_1 = class BullObserveAgent
96
116
  id: job.id,
97
117
  opts: job.opts,
98
118
  metadata: this.readQueueMetadata(job),
119
+ timeout: readBullTimeout(job.opts),
99
120
  });
100
121
  const runner = this.runner;
101
122
  if (handler.length > 1) {
@@ -13,8 +13,14 @@ export declare function invokeUserCallbackSafely<TArgs extends unknown[], TResul
13
13
  * traced under a registry key of its own.
14
14
  */
15
15
  export declare function generateTraceIdSafely(generator: (context: unknown) => string, context: unknown, receiver: unknown, logger: Logger): string;
16
- /** Copies an operation's `setAttributes` into its store, unless it throws. */
17
- export declare function setAttributesSafely<TArgs extends unknown[]>(callback: ((...args: TArgs) => Record<string, unknown>) | undefined, args: TArgs, receiver: unknown, store: Map<any, unknown>, logger: Logger, transport: string): void;
16
+ /**
17
+ * Copies an operation's `setAttributes` into its store, unless it throws.
18
+ *
19
+ * An attribute named `traceIdKey`, or like one of `AGENT_STORE_KEYS`, is left
20
+ * out: the store keeps the agent's own entry there. The first such key each
21
+ * callback returns is reported; later ones are not.
22
+ */
23
+ export declare function setAttributesSafely<TArgs extends unknown[]>(callback: ((...args: TArgs) => Record<string, unknown>) | undefined, args: TArgs, receiver: unknown, store: Map<any, unknown>, logger: Logger, transport: string, traceIdKey: string): void;
18
24
  /**
19
25
  * Whether `ignore` excludes an operation. One that throws excludes it as
20
26
  * well: the operation still runs, but recording what a broken predicate may
@@ -1,3 +1,6 @@
1
+ import { CALLER_METADATA_KEY, TRACE_CONTEXT_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
2
+ import { OPERATION_STATE_KEY } from "../utils/operation-state.util.js";
3
+ import { setThroughCopies } from "../utils/store-copy.util.js";
1
4
  import { uuidv7 } from "../utils/uuid-v7.util.js";
2
5
  const reportedCallbacks = new WeakSet();
3
6
  const reportedDeferredFailures = new WeakSet();
@@ -54,8 +57,31 @@ function reportCallbackFailure(callback, logger, name, failure, outcome, error)
54
57
  export function generateTraceIdSafely(generator, context, receiver, logger) {
55
58
  return invokeUserCallbackSafely(generator, [context], receiver, uuidv7, logger, "traceIdGenerator", "using a random trace id");
56
59
  }
57
- /** Copies an operation's `setAttributes` into its store, unless it throws. */
58
- export function setAttributesSafely(callback, args, receiver, store, logger, transport) {
60
+ /**
61
+ * What the agent keeps in an operation's store for itself, beside the trace
62
+ * id under `traceIdKey`. Attributes share that store, and their names can
63
+ * come from a sender - a message's metadata, a query string spread into the
64
+ * result - so one named like any of these is left out rather than written
65
+ * over the agent's own entry. A trace id that arrived that way had been
66
+ * through none of the checks an `x-request-id` goes through, and was sent on
67
+ * to every service called downstream; a registry key or a caller that
68
+ * arrived that way detached the operation from its trace.
69
+ */
70
+ const AGENT_STORE_KEYS = new Set([
71
+ CALLER_METADATA_KEY,
72
+ TRACE_REGISTRY_KEY,
73
+ TRACE_CONTEXT_KEY,
74
+ OPERATION_STATE_KEY,
75
+ ]);
76
+ const reportedReservedKeys = new WeakSet();
77
+ /**
78
+ * Copies an operation's `setAttributes` into its store, unless it throws.
79
+ *
80
+ * An attribute named `traceIdKey`, or like one of `AGENT_STORE_KEYS`, is left
81
+ * out: the store keeps the agent's own entry there. The first such key each
82
+ * callback returns is reported; later ones are not.
83
+ */
84
+ export function setAttributesSafely(callback, args, receiver, store, logger, transport, traceIdKey) {
59
85
  if (!callback) {
60
86
  return;
61
87
  }
@@ -63,8 +89,19 @@ export function setAttributesSafely(callback, args, receiver, store, logger, tra
63
89
  if (!attributes) {
64
90
  return;
65
91
  }
92
+ // Through to the stores this one was copied from, as `setAttribute` writes:
93
+ // an operation started inside a span - GraphQL's, in a request whose
94
+ // middleware set the same key - is the later write, and the one the rest
95
+ // of the request should read.
66
96
  for (const [key, value] of Object.entries(attributes)) {
67
- store.set(key, value);
97
+ if (key === traceIdKey || AGENT_STORE_KEYS.has(key)) {
98
+ if (!reportedReservedKeys.has(callback)) {
99
+ reportedReservedKeys.add(callback);
100
+ warnSafely(logger, `"${transport}.setAttributes" returned an attribute named "${key.slice(0, 100)}", a key the agent keeps for itself; it is left out. Later ones are not reported.`);
101
+ }
102
+ continue;
103
+ }
104
+ setThroughCopies(store, key, value);
68
105
  }
69
106
  }
70
107
  /**
@@ -38,13 +38,19 @@ interface OperationState {
38
38
  spanId: string;
39
39
  className: string;
40
40
  methodKey: string;
41
- /** The caller this operation displaced, restored once it ends. */
41
+ /**
42
+ * The caller this operation displaced - for one of a batch, the caller the
43
+ * first of them displaced - restored once the last one open has ended.
44
+ */
42
45
  previousCallerId: string | undefined;
43
46
  store: Map<string, unknown> | undefined;
44
47
  /** Whether this service opened the trace, and therefore has to ship it. */
45
48
  ownsTrace: boolean;
46
49
  context: unknown;
47
- /** Closed already: refused by the application's start hook. */
50
+ /**
51
+ * Closed already: by the end hook, or refused by the application's start
52
+ * hook. See `openOperationsByStore` too.
53
+ */
48
54
  ended?: boolean;
49
55
  }
50
56
  /**
@@ -97,9 +103,51 @@ export declare class GraphQLObserveAgentService<Store extends Record<string, unk
97
103
  * after the schema is built.
98
104
  */
99
105
  private resolverIndex;
106
+ /**
107
+ * The operations each async store has open, in the order they started.
108
+ *
109
+ * Usually one. A batched HTTP request (Apollo's `allowBatchedHttpRequests`)
110
+ * is the exception: its operations run at once in the one store the
111
+ * request has, so the caller a later one found there was the span of the
112
+ * one before it - a sibling, not a caller - and they end in any order.
113
+ * Nested that way, the trace was as deep as the client made the batch
114
+ * long, and a failure behind the first operation was on no root span, so
115
+ * the request was reported as a success.
116
+ *
117
+ * Beside the store rather than in it: a span's store is a copy of its
118
+ * caller's, and an operation started inside the copy really is a callee.
119
+ * Weakly keyed, so an unmatched start - see `onRequestEnd` - leaves
120
+ * nothing behind once the request's store is gone.
121
+ */
122
+ private readonly openOperationsByStore;
100
123
  constructor(asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, observeAgentSharedBuffer: ObserveAgentSharedBuffer, traceSamplerService: TraceSamplerService, moduleRef: ModuleRef, discoveryService: DiscoveryService, metadataScanner: MetadataScanner);
101
124
  onModuleInit(): Promise<void>;
102
125
  registerRequestHooksIfPossible(): Promise<void>;
126
+ /**
127
+ * Has `@nestjs/graphql` apply a resolver's methods to the instance itself
128
+ * where the instrumentation proxy cannot be their receiver.
129
+ *
130
+ * The explorer reads each `@Query`, `@Mutation`, `@Subscription` and
131
+ * `@ResolveField` method off the class prototype and applies it to the
132
+ * instance the container holds, which is the proxy. For a class with
133
+ * private members (`this.#x`), whose methods only the instance itself can
134
+ * run against, the first such read threw: the proxy only helps the methods
135
+ * read through it. `createContextCallback` is where every one of them is
136
+ * paired with its instance, the field resolvers' fast path included, so
137
+ * that is where the instance behind the proxy is handed over instead -
138
+ * what the explorer would have held without the agent. Only the receiver
139
+ * changes: the method is still the class's own, so `getHandler()`, guards,
140
+ * pipes and interceptors see what they saw before, and no span is added,
141
+ * as none is for any other resolver. A request-scoped resolver reads its
142
+ * method through the instance already, and is left alone.
143
+ *
144
+ * Patched on the prototype from the constructor, which Nest runs before any
145
+ * `onModuleInit`, `GraphQLModule`'s included, where the explorer does its
146
+ * work - synchronously, for the reason given on `loadOptionalPeer`. The
147
+ * original is parked under a symbol, so a second agent replaces the wrapper
148
+ * instead of wrapping it again.
149
+ */
150
+ private patchResolversExplorer;
103
151
  /**
104
152
  * The start hook the host is given: this service's part first, so the span
105
153
  * covers the application's hook, then the application's, whose result is
@@ -182,6 +230,18 @@ export declare class GraphQLObserveAgentService<Store extends Record<string, unk
182
230
  * beside it.
183
231
  */
184
232
  private openSpan;
233
+ /**
234
+ * Takes the operations that have ended off the ones a store has open, and
235
+ * returns the caller the store names from here on.
236
+ *
237
+ * While another operation is open there, that is the one of them that
238
+ * started last, whichever just ended: the work still running in the store
239
+ * belongs to an open operation, and a slot emptied or left naming an ended
240
+ * span put it at the root of the trace, beside the operation, and had
241
+ * `activeSpan()` find nothing. Once the last has ended, it is the caller
242
+ * they displaced.
243
+ */
244
+ private closeOperation;
185
245
  /**
186
246
  * Ends and ships a trace this service opened itself.
187
247
  *