@nestjs/observe 0.3.26 → 0.3.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -2
- package/dist/agent/observe-agent.shared-buffer.js +5 -0
- package/dist/agent/telemetry-wire-contract.js +3 -3
- package/dist/cli/link.js +24 -2
- package/dist/cli/package-manager.d.ts +6 -0
- package/dist/cli/package-manager.js +60 -3
- package/dist/cli/project-files.d.ts +25 -5
- package/dist/cli/project-files.js +98 -15
- package/dist/custom-metrics/summary.js +17 -10
- package/dist/instrument/create-instance-decorator.instrument.js +364 -38
- package/dist/instrument/raw-receiver.d.ts +6 -0
- package/dist/instrument/raw-receiver.js +32 -0
- package/dist/interfaces/observe-options.interface.d.ts +14 -5
- package/dist/otlp/otlp-span.mapper.d.ts +2 -0
- package/dist/otlp/otlp-span.mapper.js +19 -1
- package/dist/otlp/otlp-trace-exporter.service.d.ts +63 -9
- package/dist/otlp/otlp-trace-exporter.service.js +232 -38
- package/dist/outgoing/http.integration.js +36 -11
- package/dist/outgoing/mongodb.integration.d.ts +3 -1
- package/dist/outgoing/mongodb.integration.js +93 -18
- package/dist/outgoing/mssql.integration.js +9 -4
- package/dist/outgoing/outgoing-observe-agent.service.js +5 -1
- package/dist/outgoing/sql-statement.util.js +36 -10
- package/dist/protocols/bull-observe-agent.service.js +21 -0
- package/dist/protocols/deferred-trace-completion.d.ts +8 -2
- package/dist/protocols/deferred-trace-completion.js +40 -3
- package/dist/protocols/graphql-observe-agent.service.d.ts +62 -2
- package/dist/protocols/graphql-observe-agent.service.js +188 -14
- package/dist/protocols/graphql-operation-parser.js +45 -14
- package/dist/protocols/http-observe-agent.service.d.ts +14 -7
- package/dist/protocols/http-observe-agent.service.js +57 -14
- package/dist/protocols/job-trace-runner.d.ts +7 -0
- package/dist/protocols/job-trace-runner.js +72 -8
- package/dist/protocols/rpc-observe-agent.service.d.ts +61 -0
- package/dist/protocols/rpc-observe-agent.service.js +146 -10
- package/dist/protocols/ws-observe-agent.service.js +1 -1
- package/dist/services/logger-patcher.service.js +13 -3
- package/dist/services/operation-trace.registry.d.ts +13 -0
- package/dist/services/operation-trace.registry.js +195 -65
- package/dist/services/stdout-forwarder.service.js +22 -2
- package/dist/services/tracer.service.d.ts +19 -14
- package/dist/services/tracer.service.js +57 -34
- package/dist/utils/capture-request.util.js +36 -8
- package/dist/utils/context-accessor.util.d.ts +16 -0
- package/dist/utils/context-accessor.util.js +28 -0
- package/dist/utils/default-trace-id-generator.util.js +5 -7
- package/dist/utils/error-stack.util.d.ts +13 -0
- package/dist/utils/error-stack.util.js +166 -0
- package/dist/utils/log-line.parser.d.ts +8 -0
- package/dist/utils/log-line.parser.js +13 -4
- package/dist/utils/log-redactor.js +184 -10
- package/dist/utils/redact-url-query.d.ts +16 -5
- package/dist/utils/redact-url-query.js +20 -7
- package/dist/utils/source-context.util.d.ts +6 -0
- package/dist/utils/source-context.util.js +68 -33
- package/dist/utils/source-map-resolver.util.js +25 -4
- package/dist/utils/store-copy.util.d.ts +10 -0
- package/dist/utils/store-copy.util.js +43 -0
- package/package.json +1 -1
|
@@ -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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
73
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
61
|
-
//
|
|
62
|
-
|
|
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;]+/, "");
|
|
@@ -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
|
-
|
|
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
|
|
@@ -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
|
|
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
|
-
//
|
|
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
|
-
/**
|
|
17
|
-
|
|
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
|
-
/**
|
|
58
|
-
|
|
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
|
-
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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
|
*
|