@nestjs/observe 0.2.3 → 0.3.0
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 -0
- package/dist/.tsbuildinfo +1 -1
- package/dist/agent/telemetry-wire-contract.js +1 -0
- package/dist/encoders/request-snapshot.encoder.d.ts +1 -0
- package/dist/encoders/request-snapshot.encoder.js +1 -0
- package/dist/instrument/create-instance-decorator.instrument.js +2 -2
- package/dist/interfaces/observe-options.interface.d.ts +90 -4
- package/dist/interfaces/request-snapshot.interface.d.ts +8 -0
- package/dist/observe.constants.d.ts +16 -0
- package/dist/observe.constants.js +16 -0
- package/dist/observe.module.js +48 -4
- package/dist/outgoing/http.integration.d.ts +36 -0
- package/dist/outgoing/http.integration.js +127 -0
- package/dist/outgoing/mongodb.integration.d.ts +38 -0
- package/dist/outgoing/mongodb.integration.js +141 -0
- package/dist/outgoing/mysql2.integration.d.ts +20 -0
- package/dist/outgoing/mysql2.integration.js +89 -0
- package/dist/outgoing/outgoing-observe-agent.service.d.ts +17 -0
- package/dist/outgoing/outgoing-observe-agent.service.js +123 -0
- package/dist/outgoing/outgoing-span.recorder.d.ts +54 -0
- package/dist/outgoing/outgoing-span.recorder.js +94 -0
- package/dist/outgoing/patch-method.util.d.ts +15 -0
- package/dist/outgoing/patch-method.util.js +29 -0
- package/dist/outgoing/pg.integration.d.ts +22 -0
- package/dist/outgoing/pg.integration.js +66 -0
- package/dist/outgoing/sql-statement.util.d.ts +21 -0
- package/dist/outgoing/sql-statement.util.js +48 -0
- package/dist/protocols/bull-observe-agent.service.d.ts +28 -0
- package/dist/protocols/bull-observe-agent.service.js +130 -0
- package/dist/protocols/graphql-observe-agent.service.js +5 -2
- package/dist/protocols/graphql-operation-parser.d.ts +4 -4
- package/dist/protocols/graphql-operation-parser.js +28 -4
- package/dist/protocols/http-observe-agent.service.js +26 -7
- package/dist/protocols/job-trace-runner.d.ts +77 -0
- package/dist/protocols/job-trace-runner.js +196 -0
- package/dist/protocols/queue-observe-agent.service.d.ts +9 -4
- package/dist/protocols/queue-observe-agent.service.js +36 -95
- package/dist/protocols/ws-observe-agent.service.d.ts +39 -0
- package/dist/protocols/ws-observe-agent.service.js +180 -0
- package/dist/services/operation-trace.registry.d.ts +17 -1
- package/dist/services/operation-trace.registry.js +39 -7
- package/dist/services/trace-sampler.service.d.ts +4 -0
- package/dist/services/tracer.service.js +5 -3
- package/dist/utils/capture-request.util.d.ts +57 -0
- package/dist/utils/capture-request.util.js +116 -0
- package/dist/utils/default-trace-id-generator.util.d.ts +12 -0
- package/dist/utils/default-trace-id-generator.util.js +12 -1
- package/dist/utils/log-redactor.d.ts +20 -1
- package/dist/utils/log-redactor.js +54 -38
- package/dist/utils/optional-peer.util.d.ts +13 -0
- package/dist/utils/optional-peer.util.js +30 -0
- package/dist/utils/redact-url-query.d.ts +10 -1
- package/dist/utils/redact-url-query.js +16 -37
- package/dist/utils/sensitive-keys.d.ts +15 -0
- package/dist/utils/sensitive-keys.js +76 -0
- package/dist/utils/source-context.util.d.ts +6 -0
- package/dist/utils/source-context.util.js +113 -15
- package/dist/utils/source-map-resolver.util.js +12 -0
- package/package.json +35 -2
|
@@ -13,22 +13,16 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
13
13
|
var QueueObserveAgentService_1;
|
|
14
14
|
import { Inject, Injectable, Logger } from "@nestjs/common";
|
|
15
15
|
import { AsyncLocalStorage } from "async_hooks";
|
|
16
|
-
import { uuidv7 } from "../utils/uuid-v7.util.js";
|
|
17
16
|
import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
|
|
18
17
|
import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
|
|
19
18
|
import { OBSERVE_OPTIONS } from "../observe.constants.js";
|
|
19
|
+
import { JobTraceRunner } from "./job-trace-runner.js";
|
|
20
20
|
import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
|
|
21
21
|
let QueueObserveAgentService = QueueObserveAgentService_1 = class QueueObserveAgentService {
|
|
22
|
-
observeAgentSharedBuffer;
|
|
23
|
-
options;
|
|
24
|
-
operationTraceRegistry;
|
|
25
|
-
asyncLocalStorage;
|
|
26
22
|
logger = new Logger(QueueObserveAgentService_1.name);
|
|
23
|
+
runner;
|
|
27
24
|
constructor(observeAgentSharedBuffer, options, operationTraceRegistry, asyncLocalStorage) {
|
|
28
|
-
this.
|
|
29
|
-
this.options = options;
|
|
30
|
-
this.operationTraceRegistry = operationTraceRegistry;
|
|
31
|
-
this.asyncLocalStorage = asyncLocalStorage;
|
|
25
|
+
this.runner = new JobTraceRunner(observeAgentSharedBuffer, options, operationTraceRegistry, asyncLocalStorage, this.logger);
|
|
32
26
|
this.patchDecorate();
|
|
33
27
|
}
|
|
34
28
|
/**
|
|
@@ -50,7 +44,11 @@ let QueueObserveAgentService = QueueObserveAgentService_1 = class QueueObserveAg
|
|
|
50
44
|
// for a delayed job the gap between the two is a schedule the caller asked
|
|
51
45
|
// for - not a queue that fell behind. Counting it would report a job dated
|
|
52
46
|
// a week out as a week of backlog and drag `job_wait_p95` with it.
|
|
53
|
-
|
|
47
|
+
//
|
|
48
|
+
// Read off the options when `job.delay` is zero: BullMQ resets that
|
|
49
|
+
// field as it promotes a delayed job, so by the time a worker holds the
|
|
50
|
+
// job it says 0 whatever was asked for.
|
|
51
|
+
const availableAt = job.timestamp + (job.delay || job.opts?.delay || 0);
|
|
54
52
|
metadata.waitDuration = Math.max(0, startedAt - availableAt);
|
|
55
53
|
}
|
|
56
54
|
if (typeof job.attemptsMade === "number") {
|
|
@@ -96,91 +94,34 @@ let QueueObserveAgentService = QueueObserveAgentService_1 = class QueueObserveAg
|
|
|
96
94
|
return;
|
|
97
95
|
}
|
|
98
96
|
ProcessorDecoratorService.prototype["decorate"] =
|
|
99
|
-
(processor) => (job) => {
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
// setImmediate(() => {
|
|
130
|
-
this.operationTraceRegistry.startTrace(traceId, {
|
|
131
|
-
tags: this.options.jobs?.tags,
|
|
132
|
-
queueName: job.queueName,
|
|
133
|
-
name: job.name,
|
|
134
|
-
id: typeof job.id === "number" ? `${job.id}` : job.id,
|
|
135
|
-
...this.readQueueMetadata(job),
|
|
136
|
-
});
|
|
137
|
-
// });
|
|
138
|
-
const endTrace = (status) => {
|
|
139
|
-
setTimeout(async () => {
|
|
140
|
-
this.operationTraceRegistry.endTrace(traceId, { status });
|
|
141
|
-
const snapshot = (await this.operationTraceRegistry.pluckSnapshot(traceId));
|
|
142
|
-
// `pluckSnapshot` deletes what it returns, so a trace already
|
|
143
|
-
// plucked - a job whose handler resolved and rejected, a retry
|
|
144
|
-
// reusing the id - answers undefined. The `!` here asserted
|
|
145
|
-
// otherwise, and the encoder dereferenced it inside a
|
|
146
|
-
// `setTimeout`, where no try/catch can reach: an unhandled
|
|
147
|
-
// TypeError that took the whole process down. A worker deployment
|
|
148
|
-
// could not finish booting, because draining a queue was enough
|
|
149
|
-
// to trigger it.
|
|
150
|
-
//
|
|
151
|
-
// Dropped rather than reported: there is no snapshot, so there is
|
|
152
|
-
// nothing to send, and losing one job's self-instrumentation is
|
|
153
|
-
// not worth a crash loop.
|
|
154
|
-
if (!snapshot) {
|
|
155
|
-
return;
|
|
156
|
-
}
|
|
157
|
-
this.observeAgentSharedBuffer.insertJobSnapshot(snapshot);
|
|
158
|
-
}, 0);
|
|
159
|
-
};
|
|
160
|
-
try {
|
|
161
|
-
const returnValue = processor(job);
|
|
162
|
-
if (returnValue instanceof Promise) {
|
|
163
|
-
return returnValue
|
|
164
|
-
.then((ret) => {
|
|
165
|
-
endTrace("completed");
|
|
166
|
-
return ret;
|
|
167
|
-
})
|
|
168
|
-
.catch((error) => {
|
|
169
|
-
console.error("ending trace with error:", error);
|
|
170
|
-
endTrace("failed");
|
|
171
|
-
throw error;
|
|
172
|
-
});
|
|
173
|
-
}
|
|
174
|
-
endTrace("completed");
|
|
175
|
-
return returnValue;
|
|
176
|
-
}
|
|
177
|
-
catch (error) {
|
|
178
|
-
console.error("rethrowing again?");
|
|
179
|
-
endTrace("failed");
|
|
180
|
-
throw error;
|
|
181
|
-
}
|
|
182
|
-
});
|
|
183
|
-
};
|
|
97
|
+
(processor) => (job) => this.runner.run({
|
|
98
|
+
queueName: job.queueName,
|
|
99
|
+
name: job.name,
|
|
100
|
+
id: job.id,
|
|
101
|
+
opts: job.opts,
|
|
102
|
+
metadata: this.readQueueMetadata(job),
|
|
103
|
+
}, () => processor(job));
|
|
104
|
+
this.patchQueue();
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* The enqueuing half: without it a worker has no way to learn which
|
|
108
|
+
* operation a job came from, and every run opens an unrelated trace.
|
|
109
|
+
*
|
|
110
|
+
* `bullmq` is loaded the way `@nestjs/bullmq` loads it, so the prototype
|
|
111
|
+
* patched here is the one behind every `@InjectQueue()`.
|
|
112
|
+
*/
|
|
113
|
+
patchQueue() {
|
|
114
|
+
const result = loadOptionalPeer("bullmq");
|
|
115
|
+
if (!result.installed) {
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
const prototype = result.module?.Queue?.prototype;
|
|
119
|
+
if (!prototype) {
|
|
120
|
+
this.logger.warn(`bullmq is installed but its Queue could not be loaded, so jobs will not inherit the trace that enqueued them${result.error ? `: ${describePeerLoadError(result.error)}` : "."}`);
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
// add(name, data, opts)
|
|
124
|
+
this.runner.patchEnqueue(prototype, () => 2);
|
|
184
125
|
}
|
|
185
126
|
};
|
|
186
127
|
QueueObserveAgentService = QueueObserveAgentService_1 = __decorate([
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
2
|
+
import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
|
|
3
|
+
import { ObserveModuleOptionsWithDefaults } from "../interfaces/index.js";
|
|
4
|
+
import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
|
|
5
|
+
import { TraceSamplerService } from "../services/trace-sampler.service.js";
|
|
6
|
+
import { KeyOf } from "../types/key-of.type.js";
|
|
7
|
+
/**
|
|
8
|
+
* Gateway message tracing for `@nestjs/websockets`.
|
|
9
|
+
*
|
|
10
|
+
* Unlike the HTTP adapter and the microservice server, a gateway offers no
|
|
11
|
+
* processing hooks, so the one place every `@SubscribeMessage()` handler
|
|
12
|
+
* passes through is patched instead: `WsContextCreator.create`, which builds
|
|
13
|
+
* the guards-pipes-interceptors-handler chain for a message. Wrapping what it
|
|
14
|
+
* returns puts the whole chain inside the trace, whichever platform adapter -
|
|
15
|
+
* socket.io, ws - delivers the message.
|
|
16
|
+
*/
|
|
17
|
+
export declare class WsObserveAgentService<Store extends Record<string, unknown>> {
|
|
18
|
+
private readonly observeAgentSharedBuffer;
|
|
19
|
+
private readonly options;
|
|
20
|
+
private readonly operationTraceRegistry;
|
|
21
|
+
private readonly traceSamplerService;
|
|
22
|
+
private readonly asyncLocalStorage;
|
|
23
|
+
private readonly logger;
|
|
24
|
+
constructor(observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, traceSamplerService: TraceSamplerService, asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>);
|
|
25
|
+
private loadContextCreator;
|
|
26
|
+
private patchContextCreator;
|
|
27
|
+
/**
|
|
28
|
+
* Nest reads a gateway's handlers off the class prototype and applies them
|
|
29
|
+
* to the instance, which steps around the instrumentation proxy - the one
|
|
30
|
+
* method of the whole chain that would go unrecorded is the handler itself,
|
|
31
|
+
* and a handler that throws before calling anything leaves no span at all.
|
|
32
|
+
*
|
|
33
|
+
* The stand-in calls the same method through the instance instead. Guards,
|
|
34
|
+
* pipes, filters and the message pattern are all looked up as metadata on
|
|
35
|
+
* the callback, so that metadata is carried over.
|
|
36
|
+
*/
|
|
37
|
+
private routeThroughInstance;
|
|
38
|
+
private traceMessage;
|
|
39
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
};
|
|
10
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
11
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
|
+
};
|
|
13
|
+
var WsObserveAgentService_1;
|
|
14
|
+
import { Inject, Injectable, Logger } from "@nestjs/common";
|
|
15
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
16
|
+
import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
|
|
17
|
+
import { OBSERVE_OPTIONS } from "../observe.constants.js";
|
|
18
|
+
import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
|
|
19
|
+
import { TraceSamplerService } from "../services/trace-sampler.service.js";
|
|
20
|
+
import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
|
|
21
|
+
import { uuidv7 } from "../utils/uuid-v7.util.js";
|
|
22
|
+
const ORIGINAL_CREATE = Symbol.for("nestjs.observe.ws.create");
|
|
23
|
+
/** `@nestjs/websockets`' MESSAGE_METADATA - what `@SubscribeMessage()` writes. */
|
|
24
|
+
const MESSAGE_METADATA = "message";
|
|
25
|
+
/**
|
|
26
|
+
* Gateway message tracing for `@nestjs/websockets`.
|
|
27
|
+
*
|
|
28
|
+
* Unlike the HTTP adapter and the microservice server, a gateway offers no
|
|
29
|
+
* processing hooks, so the one place every `@SubscribeMessage()` handler
|
|
30
|
+
* passes through is patched instead: `WsContextCreator.create`, which builds
|
|
31
|
+
* the guards-pipes-interceptors-handler chain for a message. Wrapping what it
|
|
32
|
+
* returns puts the whole chain inside the trace, whichever platform adapter -
|
|
33
|
+
* socket.io, ws - delivers the message.
|
|
34
|
+
*/
|
|
35
|
+
let WsObserveAgentService = WsObserveAgentService_1 = class WsObserveAgentService {
|
|
36
|
+
observeAgentSharedBuffer;
|
|
37
|
+
options;
|
|
38
|
+
operationTraceRegistry;
|
|
39
|
+
traceSamplerService;
|
|
40
|
+
asyncLocalStorage;
|
|
41
|
+
logger = new Logger(WsObserveAgentService_1.name);
|
|
42
|
+
constructor(observeAgentSharedBuffer, options, operationTraceRegistry, traceSamplerService, asyncLocalStorage) {
|
|
43
|
+
this.observeAgentSharedBuffer = observeAgentSharedBuffer;
|
|
44
|
+
this.options = options;
|
|
45
|
+
this.operationTraceRegistry = operationTraceRegistry;
|
|
46
|
+
this.traceSamplerService = traceSamplerService;
|
|
47
|
+
this.asyncLocalStorage = asyncLocalStorage;
|
|
48
|
+
this.patchContextCreator();
|
|
49
|
+
}
|
|
50
|
+
loadContextCreator() {
|
|
51
|
+
const result = loadOptionalPeer("@nestjs/websockets", "@nestjs/websockets/context/ws-context-creator");
|
|
52
|
+
if (!result.installed) {
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
if (result.error) {
|
|
56
|
+
this.logger.warn(`@nestjs/websockets is installed but its context creator could not be loaded, so gateway messages will not be instrumented: ${describePeerLoadError(result.error)}`);
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
return result.module?.WsContextCreator ?? null;
|
|
60
|
+
}
|
|
61
|
+
patchContextCreator() {
|
|
62
|
+
const WsContextCreator = this.loadContextCreator();
|
|
63
|
+
if (WsContextCreator === undefined) {
|
|
64
|
+
// An optional peer. No gateways means nothing to wrap.
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
const prototype = WsContextCreator?.prototype;
|
|
68
|
+
const originalCreate = (prototype?.[ORIGINAL_CREATE] ??
|
|
69
|
+
prototype?.create);
|
|
70
|
+
if (!prototype || typeof originalCreate !== "function") {
|
|
71
|
+
this.logger.warn("WsContextCreator is not available. Please, update to the latest version of @nestjs/websockets. Skipping patching.");
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
// Parked under a symbol so a second agent replaces the wrapper instead of
|
|
75
|
+
// wrapping it again.
|
|
76
|
+
prototype[ORIGINAL_CREATE] = originalCreate;
|
|
77
|
+
const trace = this.traceMessage.bind(this);
|
|
78
|
+
const routeThroughInstance = this.routeThroughInstance.bind(this);
|
|
79
|
+
prototype.create = function (instance, callback, ...rest) {
|
|
80
|
+
const handler = originalCreate.call(this, instance,
|
|
81
|
+
// rest: [moduleKey, methodName, ...]
|
|
82
|
+
routeThroughInstance(instance, callback, rest[1]), ...rest);
|
|
83
|
+
const pattern = Reflect.getMetadata?.(MESSAGE_METADATA, callback);
|
|
84
|
+
const gateway = instance?.constructor?.name || "Gateway";
|
|
85
|
+
return (...args) => trace({ gateway, pattern: String(pattern), client: args[0], data: args[1] }, () => handler(...args));
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Nest reads a gateway's handlers off the class prototype and applies them
|
|
90
|
+
* to the instance, which steps around the instrumentation proxy - the one
|
|
91
|
+
* method of the whole chain that would go unrecorded is the handler itself,
|
|
92
|
+
* and a handler that throws before calling anything leaves no span at all.
|
|
93
|
+
*
|
|
94
|
+
* The stand-in calls the same method through the instance instead. Guards,
|
|
95
|
+
* pipes, filters and the message pattern are all looked up as metadata on
|
|
96
|
+
* the callback, so that metadata is carried over.
|
|
97
|
+
*/
|
|
98
|
+
routeThroughInstance(instance, callback, methodName) {
|
|
99
|
+
if (typeof methodName !== "string" || typeof callback !== "function") {
|
|
100
|
+
return callback;
|
|
101
|
+
}
|
|
102
|
+
const instrumented = instance[methodName];
|
|
103
|
+
if (typeof instrumented !== "function" || instrumented === callback) {
|
|
104
|
+
return callback;
|
|
105
|
+
}
|
|
106
|
+
const routed = function (...args) {
|
|
107
|
+
return instrumented.apply(this, args);
|
|
108
|
+
};
|
|
109
|
+
Object.defineProperty(routed, "name", { value: callback.name });
|
|
110
|
+
for (const key of Reflect.getMetadataKeys?.(callback) ?? []) {
|
|
111
|
+
Reflect.defineMetadata(key, Reflect.getMetadata(key, callback), routed);
|
|
112
|
+
}
|
|
113
|
+
return routed;
|
|
114
|
+
}
|
|
115
|
+
traceMessage(message, invoke) {
|
|
116
|
+
// Always a store of its own: whatever context the socket's events happen
|
|
117
|
+
// to fire in - the upgrade request, a polling request - is not this
|
|
118
|
+
// message's operation.
|
|
119
|
+
const store = new Map();
|
|
120
|
+
return this.asyncLocalStorage.run(store, () => {
|
|
121
|
+
const traceId = uuidv7();
|
|
122
|
+
store.set(this.options.traceIdKey, traceId);
|
|
123
|
+
const attributes = this.options.ws?.setAttributes?.(message);
|
|
124
|
+
if (attributes) {
|
|
125
|
+
for (const [key, value] of Object.entries(attributes)) {
|
|
126
|
+
store.set(key, value);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
if (this.options.ws?.ignore?.(message) ||
|
|
130
|
+
!this.traceSamplerService.shouldCapture("ws", {
|
|
131
|
+
gateway: message.gateway,
|
|
132
|
+
pattern: message.pattern,
|
|
133
|
+
})) {
|
|
134
|
+
return invoke();
|
|
135
|
+
}
|
|
136
|
+
this.operationTraceRegistry.startTrace(traceId, {
|
|
137
|
+
protocol: "ws",
|
|
138
|
+
operationId: `${message.gateway}:${message.pattern}`,
|
|
139
|
+
tags: this.options.ws?.tags,
|
|
140
|
+
});
|
|
141
|
+
const endTrace = () => {
|
|
142
|
+
setTimeout(async () => {
|
|
143
|
+
this.operationTraceRegistry.endTrace(traceId, {
|
|
144
|
+
userId: this.options.ws?.getUserId?.(message),
|
|
145
|
+
});
|
|
146
|
+
const snapshot = await this.operationTraceRegistry.pluckSnapshot(traceId);
|
|
147
|
+
if (!snapshot) {
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
|
|
151
|
+
}, 0);
|
|
152
|
+
};
|
|
153
|
+
// Nest's ws proxy hands a thrown error to the exception filter and
|
|
154
|
+
// resolves, so there is no rejection to read a failure from here - the
|
|
155
|
+
// handler's own span records it, and the registry lifts a failed root
|
|
156
|
+
// span into the snapshot's status.
|
|
157
|
+
let result;
|
|
158
|
+
try {
|
|
159
|
+
result = invoke();
|
|
160
|
+
}
|
|
161
|
+
catch (error) {
|
|
162
|
+
endTrace();
|
|
163
|
+
throw error;
|
|
164
|
+
}
|
|
165
|
+
if (result instanceof Promise) {
|
|
166
|
+
return result.finally(endTrace);
|
|
167
|
+
}
|
|
168
|
+
endTrace();
|
|
169
|
+
return result;
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
WsObserveAgentService = WsObserveAgentService_1 = __decorate([
|
|
174
|
+
Injectable(),
|
|
175
|
+
__param(1, Inject(OBSERVE_OPTIONS)),
|
|
176
|
+
__metadata("design:paramtypes", [ObserveAgentSharedBuffer, Object, OperationTraceRegistry,
|
|
177
|
+
TraceSamplerService,
|
|
178
|
+
AsyncLocalStorage])
|
|
179
|
+
], WsObserveAgentService);
|
|
180
|
+
export { WsObserveAgentService };
|
|
@@ -55,12 +55,28 @@ export declare class OperationTraceRegistry {
|
|
|
55
55
|
* `configureSpanCollapse`, for the same reason.
|
|
56
56
|
*/
|
|
57
57
|
configureRedaction(redactor: LogRedactor | null): void;
|
|
58
|
+
/**
|
|
59
|
+
* The redactor error payloads go through, for a caller adding to one - so
|
|
60
|
+
* what it adds is held to the same rules as the rest of the payload.
|
|
61
|
+
*/
|
|
62
|
+
getRedactor(): LogRedactor | null;
|
|
58
63
|
/**
|
|
59
64
|
* Builds the error payload attached to a span or snapshot, including the source
|
|
60
65
|
* around each in-app frame when source context is enabled.
|
|
61
66
|
*/
|
|
62
67
|
private toErrorPayload;
|
|
63
|
-
|
|
68
|
+
/**
|
|
69
|
+
* Whether a trace is open under this key - for a caller about to open one
|
|
70
|
+
* under an id it adopted rather than minted, which a second operation in
|
|
71
|
+
* this process may already hold.
|
|
72
|
+
*/
|
|
73
|
+
hasTrace(traceId: TraceId): boolean;
|
|
74
|
+
startTrace(traceId: TraceId, data: Omit<RequestSnapshot, "traces" | "startTimestamp" | "calledAt" | "traceId"> | Omit<JobSnapshot, "duration">,
|
|
75
|
+
/**
|
|
76
|
+
* The trace id the snapshot reports under, when it is not the registry
|
|
77
|
+
* key - a job inheriting the id of the operation that enqueued it.
|
|
78
|
+
*/
|
|
79
|
+
reportedTraceId?: string): void;
|
|
64
80
|
endTrace(traceId: string): void;
|
|
65
81
|
endTrace(traceId: string, opts?: {
|
|
66
82
|
statusCode?: number;
|
|
@@ -70,6 +70,13 @@ export class OperationTraceRegistry {
|
|
|
70
70
|
configureRedaction(redactor) {
|
|
71
71
|
this.redactor = redactor;
|
|
72
72
|
}
|
|
73
|
+
/**
|
|
74
|
+
* The redactor error payloads go through, for a caller adding to one - so
|
|
75
|
+
* what it adds is held to the same rules as the rest of the payload.
|
|
76
|
+
*/
|
|
77
|
+
getRedactor() {
|
|
78
|
+
return this.redactor;
|
|
79
|
+
}
|
|
73
80
|
/**
|
|
74
81
|
* Builds the error payload attached to a span or snapshot, including the source
|
|
75
82
|
* around each in-app frame when source context is enabled.
|
|
@@ -78,9 +85,7 @@ export class OperationTraceRegistry {
|
|
|
78
85
|
const raw = error instanceof Error
|
|
79
86
|
? { message: error.message, stack: error.stack }
|
|
80
87
|
: { message: String(error), stack: undefined };
|
|
81
|
-
// Redacted here, at the one point every error payload passes through
|
|
82
|
-
// and before code frames are read: the frames are keyed off the stack's
|
|
83
|
-
// file positions, which the redactor leaves alone.
|
|
88
|
+
// Redacted here, at the one point every error payload passes through.
|
|
84
89
|
const payload = this.redactor
|
|
85
90
|
? {
|
|
86
91
|
message: this.redactor.redactMessage(raw.message),
|
|
@@ -95,14 +100,41 @@ export class OperationTraceRegistry {
|
|
|
95
100
|
}
|
|
96
101
|
if (this.sourceContext !== false) {
|
|
97
102
|
const settings = this.sourceContext === true ? {} : this.sourceContext;
|
|
98
|
-
|
|
103
|
+
// Read off the raw stack with the raw message: the message is what marks
|
|
104
|
+
// where the frames start, and it only matches the stack it came from.
|
|
105
|
+
// Nothing of either is shipped from here - just the file positions.
|
|
106
|
+
const codeFrames = collectCodeFrames(raw.stack, {
|
|
107
|
+
...settings,
|
|
108
|
+
message: raw.message,
|
|
109
|
+
});
|
|
99
110
|
if (codeFrames) {
|
|
100
|
-
|
|
111
|
+
// Source is as likely to hold a literal secret as a message is, and
|
|
112
|
+
// goes to the same place.
|
|
113
|
+
const redactor = this.redactor;
|
|
114
|
+
result.codeFrames = redactor
|
|
115
|
+
? codeFrames.map((frame) => ({
|
|
116
|
+
...frame,
|
|
117
|
+
lines: redactor.redactSource(frame.lines),
|
|
118
|
+
}))
|
|
119
|
+
: codeFrames;
|
|
101
120
|
}
|
|
102
121
|
}
|
|
103
122
|
return result;
|
|
104
123
|
}
|
|
105
|
-
|
|
124
|
+
/**
|
|
125
|
+
* Whether a trace is open under this key - for a caller about to open one
|
|
126
|
+
* under an id it adopted rather than minted, which a second operation in
|
|
127
|
+
* this process may already hold.
|
|
128
|
+
*/
|
|
129
|
+
hasTrace(traceId) {
|
|
130
|
+
return this.traceSnapshots.has(traceId);
|
|
131
|
+
}
|
|
132
|
+
startTrace(traceId, data,
|
|
133
|
+
/**
|
|
134
|
+
* The trace id the snapshot reports under, when it is not the registry
|
|
135
|
+
* key - a job inheriting the id of the operation that enqueued it.
|
|
136
|
+
*/
|
|
137
|
+
reportedTraceId = traceId) {
|
|
106
138
|
if (this.traceSnapshots.has(traceId)) {
|
|
107
139
|
this.logger.warn(`Trace already started for traceId: "${traceId}". Overwriting existing trace.`);
|
|
108
140
|
this.traceSnapshots.delete(traceId);
|
|
@@ -110,7 +142,7 @@ export class OperationTraceRegistry {
|
|
|
110
142
|
}
|
|
111
143
|
const snapshot = {
|
|
112
144
|
...data,
|
|
113
|
-
traceId,
|
|
145
|
+
traceId: reportedTraceId,
|
|
114
146
|
calledAt: new Date().toISOString(),
|
|
115
147
|
startTimestamp: performance.now(),
|
|
116
148
|
traces: [],
|
|
@@ -16,7 +16,7 @@ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.j
|
|
|
16
16
|
import { Gauge, Summary } from "../custom-metrics/index.js";
|
|
17
17
|
import { Counter } from "../custom-metrics/counter.js";
|
|
18
18
|
import { TraceSpanDelegate } from "../trace-span.delegate.js";
|
|
19
|
-
import { CALLER_METADATA_KEY, OBSERVE_OPTIONS } from "../observe.constants.js";
|
|
19
|
+
import { CALLER_METADATA_KEY, OBSERVE_OPTIONS, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
|
|
20
20
|
import { OperationTraceRegistry } from "./operation-trace.registry.js";
|
|
21
21
|
let TracerService = class TracerService {
|
|
22
22
|
operationTraceRegistry;
|
|
@@ -89,7 +89,8 @@ let TracerService = class TracerService {
|
|
|
89
89
|
if (!store) {
|
|
90
90
|
throw new Error('AsyncLocalStorage is not initialized. Ensure that you are using the "captureError" method within an async context.');
|
|
91
91
|
}
|
|
92
|
-
const traceId = store.get(
|
|
92
|
+
const traceId = store.get(TRACE_REGISTRY_KEY) ??
|
|
93
|
+
store.get(this.options.traceIdKey);
|
|
93
94
|
if (typeof traceId !== "string") {
|
|
94
95
|
// Reporting an error must not raise one. The registry warned and gave up
|
|
95
96
|
// in this case anyway, so the outcome is unchanged.
|
|
@@ -209,7 +210,8 @@ let TracerService = class TracerService {
|
|
|
209
210
|
* methods with no async context at all - and is reported the same way.
|
|
210
211
|
*/
|
|
211
212
|
requireTraceId(store, method) {
|
|
212
|
-
const traceId = store.get(
|
|
213
|
+
const traceId = store.get(TRACE_REGISTRY_KEY) ??
|
|
214
|
+
store.get(this.options.traceIdKey);
|
|
213
215
|
if (typeof traceId !== "string") {
|
|
214
216
|
throw new Error(`No trace id found in the current context. Ensure that you are using the "${method}" method within a traced operation.`);
|
|
215
217
|
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { LogRedactor } from "./log-redactor.js";
|
|
2
|
+
/**
|
|
3
|
+
* Headers recorded when the application names none. Chosen for what they are
|
|
4
|
+
* not: nothing here authenticates the caller, identifies a person or carries a
|
|
5
|
+
* session - no `authorization`, `cookie`, `x-forwarded-for` or custom `x-*`.
|
|
6
|
+
*/
|
|
7
|
+
export declare const DEFAULT_CAPTURED_HEADERS: readonly ["accept", "content-length", "content-type", "host", "origin", "referer", "user-agent"];
|
|
8
|
+
export declare const DEFAULT_CAPTURED_BODY_BYTES = 2048;
|
|
9
|
+
export interface HttpCaptureOptions {
|
|
10
|
+
/**
|
|
11
|
+
* Names of the request headers to record with a failed request, or `false`
|
|
12
|
+
* to record none. Matched case-insensitively. Values still pass through
|
|
13
|
+
* redaction, so naming `authorization` here records `[REDACTED]`.
|
|
14
|
+
* @default DEFAULT_CAPTURED_HEADERS
|
|
15
|
+
*/
|
|
16
|
+
headers?: readonly string[] | false;
|
|
17
|
+
/**
|
|
18
|
+
* Record the parsed request body of a failed request. Off by default: a body
|
|
19
|
+
* is the application's own data, and whether it may leave the process is
|
|
20
|
+
* not something an agent can decide. `maxBytes` caps the serialized size
|
|
21
|
+
* (default 2048, at most 16384); what does not fit is cut, and marked so.
|
|
22
|
+
* @default false
|
|
23
|
+
*/
|
|
24
|
+
body?: boolean | {
|
|
25
|
+
maxBytes?: number;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Also capture requests that took at least this long, failed or not - the
|
|
29
|
+
* inputs behind a slow request are as hard to guess as those behind a
|
|
30
|
+
* failing one. Unset, only failed requests are captured.
|
|
31
|
+
* @example 2000
|
|
32
|
+
* @default undefined
|
|
33
|
+
*/
|
|
34
|
+
slowerThanMs?: number;
|
|
35
|
+
}
|
|
36
|
+
export interface CapturedRequest {
|
|
37
|
+
headers?: Record<string, string>;
|
|
38
|
+
body?: string;
|
|
39
|
+
bodyTruncated?: true;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Whether a finished request is one whose inputs are worth keeping: it
|
|
43
|
+
* failed, or it ran past the configured threshold. Never the ordinary
|
|
44
|
+
* request - that keeps both the volume and the exposure to the exceptions
|
|
45
|
+
* rather than the traffic.
|
|
46
|
+
*/
|
|
47
|
+
export declare function shouldCaptureRequest(snapshot: {
|
|
48
|
+
error?: unknown;
|
|
49
|
+
duration?: number;
|
|
50
|
+
}, options: HttpCaptureOptions | false | undefined): boolean;
|
|
51
|
+
/**
|
|
52
|
+
* What to record of a request `shouldCaptureRequest` picked, or `undefined`
|
|
53
|
+
* for nothing. Everything passes through the same redactor as error messages
|
|
54
|
+
* and forwarded logs - sensitive keys by name, secrets by pattern - before it
|
|
55
|
+
* is handed back.
|
|
56
|
+
*/
|
|
57
|
+
export declare function captureRequest(req: unknown, options: HttpCaptureOptions | false | undefined, redactor: LogRedactor | null): CapturedRequest | undefined;
|