@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.
- 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 +390 -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/mysql2.integration.js +3 -1
- package/dist/outgoing/outgoing-observe-agent.service.js +5 -1
- package/dist/outgoing/pg.integration.js +5 -0
- 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 +4 -3
|
@@ -16,10 +16,12 @@ import { AsyncLocalStorage } from "async_hooks";
|
|
|
16
16
|
import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
|
|
17
17
|
import { Gauge, Summary } from "../custom-metrics/index.js";
|
|
18
18
|
import { Counter } from "../custom-metrics/counter.js";
|
|
19
|
+
import { admitsFinite } from "../custom-metrics/finite-value.util.js";
|
|
19
20
|
import { TraceSpanDelegate } from "../trace-span.delegate.js";
|
|
20
21
|
import { CALLER_METADATA_KEY, OBSERVE_OPTIONS, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
|
|
21
22
|
import { OperationTraceRegistry } from "./operation-trace.registry.js";
|
|
22
23
|
import { liveTraceId } from "../utils/operation-state.util.js";
|
|
24
|
+
import { getThroughCopies, setThroughCopies, } from "../utils/store-copy.util.js";
|
|
23
25
|
/**
|
|
24
26
|
* Longest operation id the collector stores, counted by code point as it
|
|
25
27
|
* counts. A longer one is cut there anyway; cut here, a name built from a
|
|
@@ -62,11 +64,20 @@ let TracerService = TracerService_1 = class TracerService {
|
|
|
62
64
|
/**
|
|
63
65
|
* Creates a new trace span with the given name and executes the provided callback within that span.
|
|
64
66
|
* The callback can be synchronous or asynchronous.
|
|
67
|
+
* Outside any operation the agent traces, the callback still runs, with a
|
|
68
|
+
* detached delegate whose tags go nowhere, as in an operation that is not
|
|
69
|
+
* recorded.
|
|
65
70
|
*/
|
|
66
71
|
async createSpan(name, callback) {
|
|
67
72
|
const store = this.als.getStore();
|
|
68
73
|
if (!store) {
|
|
69
|
-
|
|
74
|
+
// No operation of the agent's is in flight: a transport it has no hook
|
|
75
|
+
// on - a GraphQL operation sent over the subscriptions socket -, a
|
|
76
|
+
// lifecycle hook, a timer armed at bootstrap, or an agent switched off.
|
|
77
|
+
// Which of these a handler runs in is often the client's choice, and
|
|
78
|
+
// there being nowhere to record the span is no reason for the work in
|
|
79
|
+
// it not to happen.
|
|
80
|
+
return callback(new TraceSpanDelegate("", name, {}));
|
|
70
81
|
}
|
|
71
82
|
const traceId = this.requireTraceId(store, "createSpan");
|
|
72
83
|
const callerId = store.get(CALLER_METADATA_KEY);
|
|
@@ -74,29 +85,31 @@ let TracerService = TracerService_1 = class TracerService {
|
|
|
74
85
|
}
|
|
75
86
|
/**
|
|
76
87
|
* Retrieves the active span for the current request.
|
|
77
|
-
*
|
|
78
|
-
*
|
|
79
|
-
* operation
|
|
80
|
-
*
|
|
88
|
+
* Where there is none - the operation is not being recorded (ignored or
|
|
89
|
+
* sampled out), nothing opened a span around the caller, or the call is
|
|
90
|
+
* outside any operation the agent traces - the delegate is a detached one
|
|
91
|
+
* whose tags go nowhere, as `createSpan`'s is then.
|
|
81
92
|
* @returns {Promise<TraceSpanDelegate>} A promise that resolves to the active span delegate.
|
|
82
93
|
*/
|
|
83
94
|
async activeSpan() {
|
|
84
95
|
const store = this.als.getStore();
|
|
85
96
|
if (!store) {
|
|
86
|
-
|
|
97
|
+
// Outside any operation: see `createSpan`.
|
|
98
|
+
return new TraceSpanDelegate("", undefined, {});
|
|
87
99
|
}
|
|
88
100
|
const traceId = this.requireTraceId(store, "activeSpan");
|
|
89
101
|
const callerId = store.get(CALLER_METADATA_KEY);
|
|
90
102
|
const activeOngoingEvent = this.operationTraceRegistry.getActiveSpan(traceId, callerId);
|
|
91
|
-
if (!activeOngoingEvent && !this.operationTraceRegistry.hasTrace(traceId)) {
|
|
92
|
-
// The store carries the id for log correlation, but no trace was opened
|
|
93
|
-
// under it: `http.ignore`, `jobs.ignore`, or the sampler said no. Which
|
|
94
|
-
// operations get recorded is configuration; a handler tagging its span
|
|
95
|
-
// must not start failing because someone changed it.
|
|
96
|
-
return new TraceSpanDelegate("", undefined, {});
|
|
97
|
-
}
|
|
98
103
|
if (!activeOngoingEvent) {
|
|
99
|
-
|
|
104
|
+
// Either the store carries the id for log correlation and no trace was
|
|
105
|
+
// opened under it - `http.ignore`, `jobs.ignore`, or the sampler said
|
|
106
|
+
// no - or one was, and nothing opened a span around the caller: the
|
|
107
|
+
// resolvers of a GraphQL document the agent cannot label, one that
|
|
108
|
+
// opens with a fragment or is sent as a persisted-query hash alone.
|
|
109
|
+
// Which operations get recorded is configuration, and how a document
|
|
110
|
+
// is spelled is the client's choice; a handler tagging its span must
|
|
111
|
+
// not start failing over either.
|
|
112
|
+
return new TraceSpanDelegate("", undefined, {});
|
|
100
113
|
}
|
|
101
114
|
let tags = activeOngoingEvent.tags;
|
|
102
115
|
if (!tags) {
|
|
@@ -114,9 +127,10 @@ let TracerService = TracerService_1 = class TracerService {
|
|
|
114
127
|
* Captures an error and associates it with the current trace.
|
|
115
128
|
* This method should be called within an async context where the AsyncLocalStorage is active.
|
|
116
129
|
*
|
|
117
|
-
* The details of at most 20 errors are recorded per trace
|
|
118
|
-
*
|
|
119
|
-
* still
|
|
130
|
+
* The details of at most 20 errors are recorded per trace, counting the
|
|
131
|
+
* root spans that fail as well as captured errors; the span an error is
|
|
132
|
+
* captured on after that is marked as failed, and its tags are still
|
|
133
|
+
* recorded.
|
|
120
134
|
*
|
|
121
135
|
* Called outside any async context, it records nothing and says so once.
|
|
122
136
|
*/
|
|
@@ -189,10 +203,12 @@ let TracerService = TracerService_1 = class TracerService {
|
|
|
189
203
|
overridableRef.labels = attributes.labels;
|
|
190
204
|
}
|
|
191
205
|
// `value` holds one reading per label, so the seed goes to the default
|
|
192
|
-
// one; a labelled metric has no unlabelled reading to seed.
|
|
206
|
+
// one; a labelled metric has no unlabelled reading to seed. A seed that
|
|
207
|
+
// is not a finite number is ignored, as the constructor ignores one.
|
|
193
208
|
if (attributes?.initialValue !== undefined &&
|
|
194
209
|
!existingRef.labels &&
|
|
195
|
-
existingRef.getValue() === 0
|
|
210
|
+
existingRef.getValue() === 0 &&
|
|
211
|
+
admitsFinite(name, attributes.initialValue, overridableRef.nonFinite)) {
|
|
196
212
|
overridableRef.value.default = attributes.initialValue;
|
|
197
213
|
}
|
|
198
214
|
return existingRef;
|
|
@@ -216,10 +232,12 @@ let TracerService = TracerService_1 = class TracerService {
|
|
|
216
232
|
overridableRef.labels = attributes.labels;
|
|
217
233
|
}
|
|
218
234
|
// `value` holds one reading per label, so the seed goes to the default
|
|
219
|
-
// one; a labelled metric has no unlabelled reading to seed.
|
|
235
|
+
// one; a labelled metric has no unlabelled reading to seed. A seed that
|
|
236
|
+
// is not a finite number is ignored, as the constructor ignores one.
|
|
220
237
|
if (attributes?.initialValue !== undefined &&
|
|
221
238
|
!existingRef.labels &&
|
|
222
|
-
existingRef.getValue() === 0
|
|
239
|
+
existingRef.getValue() === 0 &&
|
|
240
|
+
admitsFinite(name, attributes.initialValue, overridableRef.nonFinite)) {
|
|
223
241
|
overridableRef.value.default = attributes.initialValue;
|
|
224
242
|
}
|
|
225
243
|
if (attributes?.kind) {
|
|
@@ -258,7 +276,7 @@ let TracerService = TracerService_1 = class TracerService {
|
|
|
258
276
|
/**
|
|
259
277
|
* The id of the trace currently in flight, or `null` outside one.
|
|
260
278
|
*
|
|
261
|
-
*
|
|
279
|
+
* Like the rest of this service, this does not throw when there is no
|
|
262
280
|
* active store - reading the trace id to forward it downstream (an outgoing
|
|
263
281
|
* HTTP header, gRPC metadata, a queued job payload) is exactly the kind of
|
|
264
282
|
* call that may legitimately happen outside a traced context, and a thrown
|
|
@@ -317,35 +335,40 @@ let TracerService = TracerService_1 = class TracerService {
|
|
|
317
335
|
/**
|
|
318
336
|
* Sets an attribute on the current trace.
|
|
319
337
|
* For example, you can use this to add metadata to the current request trace for later use and retrieval.
|
|
320
|
-
*
|
|
338
|
+
* Does nothing outside any operation the agent traces, where there is no
|
|
339
|
+
* request context to keep the attribute in.
|
|
321
340
|
* @param key The attribute key.
|
|
322
341
|
* @param value The attribute value.
|
|
323
342
|
*/
|
|
324
343
|
setAttribute(key, value) {
|
|
325
344
|
const store = this.als.getStore();
|
|
326
345
|
if (!store) {
|
|
327
|
-
|
|
346
|
+
return;
|
|
328
347
|
}
|
|
329
|
-
store
|
|
348
|
+
// The store may be a span's own copy, gone once the span returns, so the
|
|
349
|
+
// stores it was copied from get the attribute too - see `copyStore`.
|
|
350
|
+
setThroughCopies(store, key, value);
|
|
330
351
|
}
|
|
331
352
|
/**
|
|
332
353
|
* Retrieves an attribute from the current trace (request context).
|
|
333
354
|
* This allows you to access metadata that was set earlier in the request lifecycle.
|
|
334
|
-
* This method should be called within an async context where the AsyncLocalStorage is active.
|
|
335
355
|
* @param key The attribute key.
|
|
336
|
-
* @returns The attribute value or undefined if not found
|
|
356
|
+
* @returns The attribute value, or undefined if not found or when called
|
|
357
|
+
* outside any operation the agent traces.
|
|
337
358
|
*/
|
|
338
359
|
getAttribute(key) {
|
|
339
360
|
const store = this.als.getStore();
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
return store
|
|
361
|
+
// The store first, so what the application wrote into it directly wins;
|
|
362
|
+
// then the stores it was copied from, for an attribute set by a span
|
|
363
|
+
// running beside this one.
|
|
364
|
+
return store
|
|
365
|
+
? getThroughCopies(store, key)
|
|
366
|
+
: undefined;
|
|
344
367
|
}
|
|
345
368
|
/**
|
|
346
|
-
* Reads the trace id the request was opened under.
|
|
347
|
-
* is
|
|
348
|
-
*
|
|
369
|
+
* Reads the trace id the request was opened under. A store that carries none
|
|
370
|
+
* is reported as a mistake. No store at all is not one - it is code running
|
|
371
|
+
* outside any operation - and never gets here.
|
|
349
372
|
*/
|
|
350
373
|
requireTraceId(store, method) {
|
|
351
374
|
const traceId = store.get(TRACE_REGISTRY_KEY) ?? store.get(this.options.traceIdKey);
|
|
@@ -119,7 +119,7 @@ function serializeBody(body, redactor, maxBytes) {
|
|
|
119
119
|
}
|
|
120
120
|
body = parsed;
|
|
121
121
|
}
|
|
122
|
-
if (
|
|
122
|
+
if (!isParsed(body)) {
|
|
123
123
|
// A raw buffer is a file or an unparsed stream - nothing readable to show.
|
|
124
124
|
return undefined;
|
|
125
125
|
}
|
|
@@ -150,6 +150,36 @@ function parseJsonDocument(body) {
|
|
|
150
150
|
}
|
|
151
151
|
/** Deeper than the redactor descends, so nothing it would read is cut off. */
|
|
152
152
|
const MAX_BOUNDED_DEPTH = 10;
|
|
153
|
+
/**
|
|
154
|
+
* Whether a value is what a body parser makes - an array, or an object that
|
|
155
|
+
* is only its fields: JSON, urlencoded and multer bodies all are. Some with
|
|
156
|
+
* no prototype at all, and Fastify's form parser (`fast-querystring`) with
|
|
157
|
+
* one that is itself empty and has none, which is as bare.
|
|
158
|
+
*
|
|
159
|
+
* Anything else is not a parsed body but something left where one would be:
|
|
160
|
+
* Fastify's raw request stream, a Buffer, a typed array, an instance of a
|
|
161
|
+
* class. Walked as fields, a stream's are its internals - its buffered
|
|
162
|
+
* chunks, the request's headers, cookies and API keys included, written out
|
|
163
|
+
* as numbers that no rule reads as a secret - and a Buffer's `toJSON` turns
|
|
164
|
+
* it into the same. So none of these is recorded, at any depth.
|
|
165
|
+
*/
|
|
166
|
+
function isParsed(value) {
|
|
167
|
+
if (Array.isArray(value)) {
|
|
168
|
+
return true;
|
|
169
|
+
}
|
|
170
|
+
if (typeof value !== "object" || value === null) {
|
|
171
|
+
return false;
|
|
172
|
+
}
|
|
173
|
+
let prototype = Object.getPrototypeOf(value);
|
|
174
|
+
while (prototype !== null && prototype !== Object.prototype) {
|
|
175
|
+
// A class's prototype has a `constructor` at least.
|
|
176
|
+
if (Reflect.ownKeys(prototype).length > 0) {
|
|
177
|
+
return false;
|
|
178
|
+
}
|
|
179
|
+
prototype = Object.getPrototypeOf(prototype);
|
|
180
|
+
}
|
|
181
|
+
return true;
|
|
182
|
+
}
|
|
153
183
|
/**
|
|
154
184
|
* A copy of the body holding only the nodes that can still show up in the
|
|
155
185
|
* first `maxBytes` of its JSON, in the order JSON writes them. Every value
|
|
@@ -161,16 +191,14 @@ function boundToCap(value, budget,
|
|
|
161
191
|
/** The objects above this one, to refuse a cycle as JSON.stringify would. */
|
|
162
192
|
ancestors) {
|
|
163
193
|
budget.nodes -= 1;
|
|
164
|
-
// What JSON.stringify would write for it: a Date its ISO string, and so on.
|
|
165
|
-
const toJSON = value !== null && typeof value === "object"
|
|
166
|
-
? value.toJSON
|
|
167
|
-
: undefined;
|
|
168
|
-
if (typeof toJSON === "function") {
|
|
169
|
-
value = toJSON.call(value);
|
|
170
|
-
}
|
|
171
194
|
if (value === null || typeof value !== "object") {
|
|
172
195
|
return value;
|
|
173
196
|
}
|
|
197
|
+
if (!isParsed(value)) {
|
|
198
|
+
// Left out, as JSON.stringify leaves out a function: no field, and
|
|
199
|
+
// `null` in an array.
|
|
200
|
+
return undefined;
|
|
201
|
+
}
|
|
174
202
|
if (ancestors.has(value)) {
|
|
175
203
|
throw new TypeError("Converting circular structure to JSON");
|
|
176
204
|
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a microservice context's accessor - `getMetadata()`, `getPattern()` -
|
|
3
|
+
* answers, or `undefined` for a context without one.
|
|
4
|
+
*
|
|
5
|
+
* The accessor is found by name, since a custom transporter delivers a
|
|
6
|
+
* context class of its own, and there it may be anything - asynchronous,
|
|
7
|
+
* too. What it promises cannot be read here: the callers answer before it
|
|
8
|
+
* settles, so it counts as no answer. But the promise is one this call made
|
|
9
|
+
* and nothing else holds, so its rejection is handled here: unhandled, it
|
|
10
|
+
* ended the process. The handler's own call makes a promise of its own,
|
|
11
|
+
* which stays the application's to await.
|
|
12
|
+
*
|
|
13
|
+
* Kept out of `default-trace-id-generator.util.ts`, one of its callers:
|
|
14
|
+
* everything that module exports is re-exported from the package root.
|
|
15
|
+
*/
|
|
16
|
+
export declare function readContextAccessor(context: unknown, name: "getMetadata" | "getPattern"): unknown;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { types } from "util";
|
|
2
|
+
/**
|
|
3
|
+
* What a microservice context's accessor - `getMetadata()`, `getPattern()` -
|
|
4
|
+
* answers, or `undefined` for a context without one.
|
|
5
|
+
*
|
|
6
|
+
* The accessor is found by name, since a custom transporter delivers a
|
|
7
|
+
* context class of its own, and there it may be anything - asynchronous,
|
|
8
|
+
* too. What it promises cannot be read here: the callers answer before it
|
|
9
|
+
* settles, so it counts as no answer. But the promise is one this call made
|
|
10
|
+
* and nothing else holds, so its rejection is handled here: unhandled, it
|
|
11
|
+
* ended the process. The handler's own call makes a promise of its own,
|
|
12
|
+
* which stays the application's to await.
|
|
13
|
+
*
|
|
14
|
+
* Kept out of `default-trace-id-generator.util.ts`, one of its callers:
|
|
15
|
+
* everything that module exports is re-exported from the package root.
|
|
16
|
+
*/
|
|
17
|
+
export function readContextAccessor(context, name) {
|
|
18
|
+
const accessor = context?.[name];
|
|
19
|
+
if (typeof accessor !== "function") {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
const value = accessor.call(context);
|
|
23
|
+
if (types.isPromise(value)) {
|
|
24
|
+
value.then(undefined, () => undefined);
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { readContextAccessor } from "./context-accessor.util.js";
|
|
1
2
|
import { inboundTraceId, w3cTraceIdOf } from "./trace-context.util.js";
|
|
2
3
|
import { uuidv7 } from "./uuid-v7.util.js";
|
|
3
4
|
/**
|
|
@@ -26,13 +27,10 @@ export function defaultTraceIdGenerator(req) {
|
|
|
26
27
|
// which gave their contexts - and the context gRPC hands the processing
|
|
27
28
|
// hooks - the same `getMetadata()`. Held to the same shape as the header - a
|
|
28
29
|
// packet is no more trustworthy than a request.
|
|
29
|
-
const
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
if (typeof requestId === "string" && REQUEST_ID_PATTERN.test(requestId)) {
|
|
34
|
-
return requestId;
|
|
35
|
-
}
|
|
30
|
+
const metadata = readContextAccessor(req, "getMetadata");
|
|
31
|
+
const requestId = metadata?.["x-request-id"];
|
|
32
|
+
if (typeof requestId === "string" && REQUEST_ID_PATTERN.test(requestId)) {
|
|
33
|
+
return requestId;
|
|
36
34
|
}
|
|
37
35
|
// Minted here, so it can carry its time - see uuidv7.
|
|
38
36
|
return uuidv7();
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An error's stack as it reads now, for the agent's own use: its first line
|
|
3
|
+
* is still the application's to change.
|
|
4
|
+
*/
|
|
5
|
+
export declare function readStack(err: Error): unknown;
|
|
6
|
+
/**
|
|
7
|
+
* Rewrites the frames of an error's stack, likewise.
|
|
8
|
+
*
|
|
9
|
+
* `rewrite` is given the frames alone where the agent keeps them, and the
|
|
10
|
+
* whole text where the stack is a plain string - so it must only match what
|
|
11
|
+
* follows a line break.
|
|
12
|
+
*/
|
|
13
|
+
export declare function rewriteStackFrames(err: Error, rewrite: (stack: string) => string): void;
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { types } from "node:util";
|
|
2
|
+
/**
|
|
3
|
+
* Every error the agent has looked at, with the frames it keeps for it - or
|
|
4
|
+
* nothing, for a stack it left as it was. Decided once, on first contact.
|
|
5
|
+
*/
|
|
6
|
+
const heldStacks = new WeakMap();
|
|
7
|
+
/**
|
|
8
|
+
* Stands in for the message while the stack is written. Made of characters no
|
|
9
|
+
* message an error is given by accident contains, so it is found where it is.
|
|
10
|
+
*/
|
|
11
|
+
const MESSAGE_MARKER = "\u0000nestjs-observe:message\u0000";
|
|
12
|
+
/**
|
|
13
|
+
* Whether the message can be set aside for the marker and put back exactly:
|
|
14
|
+
* an own data property that is writable, or none at all - `new Error()` - on
|
|
15
|
+
* an error that can take one. A message behind an accessor (`DOMException`)
|
|
16
|
+
* runs code to set, and is not touched.
|
|
17
|
+
*/
|
|
18
|
+
function messageIsReplaceable(err) {
|
|
19
|
+
for (let holder = err; holder !== null; holder = Object.getPrototypeOf(holder)) {
|
|
20
|
+
const descriptor = Reflect.getOwnPropertyDescriptor(holder, "message");
|
|
21
|
+
if (descriptor !== undefined) {
|
|
22
|
+
return ("value" in descriptor &&
|
|
23
|
+
descriptor.writable === true &&
|
|
24
|
+
(holder === err || Object.isExtensible(err)));
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return Object.isExtensible(err);
|
|
28
|
+
}
|
|
29
|
+
function holdStack(err) {
|
|
30
|
+
// Sealing makes `stack` non-configurable, and so the accessor impossible:
|
|
31
|
+
// the stack is read as it is. Asked before anything else, since asking for
|
|
32
|
+
// the descriptor of a stack not written yet writes it on Node 20.
|
|
33
|
+
if (types.isProxy(err) ||
|
|
34
|
+
Object.isSealed(err) ||
|
|
35
|
+
!messageIsReplaceable(err)) {
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
const ownMessage = Object.hasOwn(err, "message");
|
|
39
|
+
const message = err.message;
|
|
40
|
+
let written;
|
|
41
|
+
let markedFirstLine;
|
|
42
|
+
try {
|
|
43
|
+
err.message = MESSAGE_MARKER;
|
|
44
|
+
written = err.stack;
|
|
45
|
+
markedFirstLine = Error.prototype.toString.call(err);
|
|
46
|
+
}
|
|
47
|
+
finally {
|
|
48
|
+
if (ownMessage) {
|
|
49
|
+
err.message = message;
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
delete err.message;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (typeof written !== "string") {
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
58
|
+
const at = written.indexOf(MESSAGE_MARKER);
|
|
59
|
+
if (at === -1) {
|
|
60
|
+
// Written before the agent saw it: left as it is.
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
const before = written.slice(0, at);
|
|
64
|
+
const after = written.slice(at + MESSAGE_MARKER.length);
|
|
65
|
+
const lineEnd = after.indexOf("\n");
|
|
66
|
+
const restOfLine = lineEnd === -1 ? after : after.slice(0, lineEnd);
|
|
67
|
+
const frames = lineEnd === -1 ? "" : after.slice(lineEnd);
|
|
68
|
+
// The first line as V8 writes it - `name: message`, or the name alone for
|
|
69
|
+
// an empty message - is written again the same way; any other shape (Node's
|
|
70
|
+
// `TypeError [ERR_X]: message`) keeps what surrounds the message.
|
|
71
|
+
const firstLine = `${before}${MESSAGE_MARKER}${restOfLine}` === markedFirstLine
|
|
72
|
+
? () => Error.prototype.toString.call(err)
|
|
73
|
+
: () => `${before}${err.message}${restOfLine}`;
|
|
74
|
+
const own = Reflect.getOwnPropertyDescriptor(err, "stack");
|
|
75
|
+
const enumerable = own?.enumerable ?? false;
|
|
76
|
+
const settle = (value) => Reflect.defineProperty(err, "stack", {
|
|
77
|
+
value,
|
|
78
|
+
writable: true,
|
|
79
|
+
enumerable,
|
|
80
|
+
configurable: true,
|
|
81
|
+
});
|
|
82
|
+
if (own?.configurable !== true || frames.includes(MESSAGE_MARKER)) {
|
|
83
|
+
// Written with the marker, and no way to keep it from the application:
|
|
84
|
+
// write it out now, as it would have been written at this read.
|
|
85
|
+
settle(firstLine() + frames.split(MESSAGE_MARKER).join(String(message)));
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
const held = {
|
|
89
|
+
frames,
|
|
90
|
+
firstLine,
|
|
91
|
+
get: () => {
|
|
92
|
+
// The application's read: the one that fixes the first line.
|
|
93
|
+
const text = held.firstLine() + held.frames;
|
|
94
|
+
settle(text);
|
|
95
|
+
return text;
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
const installed = Reflect.defineProperty(err, "stack", {
|
|
99
|
+
get: held.get,
|
|
100
|
+
set: settle,
|
|
101
|
+
enumerable,
|
|
102
|
+
configurable: true,
|
|
103
|
+
});
|
|
104
|
+
if (!installed) {
|
|
105
|
+
settle(firstLine() + frames);
|
|
106
|
+
return undefined;
|
|
107
|
+
}
|
|
108
|
+
return held;
|
|
109
|
+
}
|
|
110
|
+
/** The frames the agent keeps for an error, if it still does. */
|
|
111
|
+
function heldStackOf(err) {
|
|
112
|
+
if (!heldStacks.has(err)) {
|
|
113
|
+
let held;
|
|
114
|
+
try {
|
|
115
|
+
held = holdStack(err);
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
// A name, message or stack that throws on being read or set: such an
|
|
119
|
+
// error is read as it is, which throws without the agent too.
|
|
120
|
+
held = undefined;
|
|
121
|
+
}
|
|
122
|
+
heldStacks.set(err, held);
|
|
123
|
+
}
|
|
124
|
+
const held = heldStacks.get(err);
|
|
125
|
+
return held !== undefined &&
|
|
126
|
+
Object.getOwnPropertyDescriptor(err, "stack")?.get === held.get
|
|
127
|
+
? held
|
|
128
|
+
: undefined;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* An error's stack as it reads now, for the agent's own use: its first line
|
|
132
|
+
* is still the application's to change.
|
|
133
|
+
*/
|
|
134
|
+
export function readStack(err) {
|
|
135
|
+
const held = heldStackOf(err);
|
|
136
|
+
return held === undefined ? err.stack : held.firstLine() + held.frames;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Rewrites the frames of an error's stack, likewise.
|
|
140
|
+
*
|
|
141
|
+
* `rewrite` is given the frames alone where the agent keeps them, and the
|
|
142
|
+
* whole text where the stack is a plain string - so it must only match what
|
|
143
|
+
* follows a line break.
|
|
144
|
+
*/
|
|
145
|
+
export function rewriteStackFrames(err, rewrite) {
|
|
146
|
+
const held = heldStackOf(err);
|
|
147
|
+
if (held !== undefined) {
|
|
148
|
+
held.frames = rewrite(held.frames);
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
const stack = err.stack;
|
|
152
|
+
if (typeof stack !== "string") {
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
const rewritten = rewrite(stack);
|
|
156
|
+
if (rewritten === stack) {
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
try {
|
|
160
|
+
err.stack = rewritten;
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
// Some errors ship a read-only `stack`; what the agent rewrites there is
|
|
164
|
+
// cosmetic, so leaving it as it is beats masking the original failure.
|
|
165
|
+
}
|
|
166
|
+
}
|
|
@@ -25,6 +25,14 @@ export interface ParsedLogLine {
|
|
|
25
25
|
*/
|
|
26
26
|
unsplit?: string;
|
|
27
27
|
traceId?: string;
|
|
28
|
+
/**
|
|
29
|
+
* On a text line whose `traceId` was read off its end: that end as it was
|
|
30
|
+
* written, marker and all, which `message` no longer has. The parser cannot
|
|
31
|
+
* tell the logger's suffix from a message that happens to end the same
|
|
32
|
+
* way - in a secret, say - so whoever redacts the message needs it to see
|
|
33
|
+
* the line whole.
|
|
34
|
+
*/
|
|
35
|
+
traceIdSuffix?: string;
|
|
28
36
|
attributes?: Record<string, unknown>;
|
|
29
37
|
/**
|
|
30
38
|
* What the line was read as: a record of a JSON logger, a line carrying
|
|
@@ -13,12 +13,20 @@
|
|
|
13
13
|
* understand is still the log the user is looking for.
|
|
14
14
|
*/
|
|
15
15
|
/**
|
|
16
|
-
* CSI escape sequences - colour codes and cursor
|
|
17
|
-
* general-purpose ANSI stripper on
|
|
18
|
-
* loggers emit, and a tight
|
|
16
|
+
* CSI escape sequences - colour codes, and the cursor and erase moves a
|
|
17
|
+
* progress bar writes. Narrower than a general-purpose ANSI stripper on
|
|
18
|
+
* purpose: this only has to undo what console loggers emit, and a tight
|
|
19
|
+
* pattern cannot eat real log content.
|
|
20
|
+
*
|
|
21
|
+
* Only well-formed ones, ending in one of those few letters. The pattern this
|
|
22
|
+
* replaced took any run of digits and `;` and any letter behind `ESC [`, and
|
|
23
|
+
* the escape may come from a client: a value ending in `ESC [;` in front of
|
|
24
|
+
* the application's own `Password=x` took the `P` with it, and what was left
|
|
25
|
+
* - `assword=x` - names no credential. It runs before redaction, on error
|
|
26
|
+
* messages and stacks as well as on forwarded lines.
|
|
19
27
|
*/
|
|
20
28
|
// eslint-disable-next-line no-control-regex
|
|
21
|
-
const ANSI_PATTERN = /\x1B\[
|
|
29
|
+
const ANSI_PATTERN = /\x1B\[(?:\d{1,3}(?:;\d{1,3})*)?[GHJKm]/g;
|
|
22
30
|
/**
|
|
23
31
|
* Nest's default ConsoleLogger line:
|
|
24
32
|
* [Nest] 1234 - 07/29/2026, 10:42:18 AM LOG [AppController] message
|
|
@@ -129,6 +137,7 @@ function parseNestText(line) {
|
|
|
129
137
|
level: toLogLevel(level),
|
|
130
138
|
context: context || undefined,
|
|
131
139
|
traceId,
|
|
140
|
+
traceIdSuffix: traceId === undefined ? undefined : rest.slice(message.length),
|
|
132
141
|
message,
|
|
133
142
|
unsplit: bracket === undefined ? undefined : bracket + message,
|
|
134
143
|
format: "nest",
|