@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
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { OutgoingSpanRecorder } from "./outgoing-span.recorder.js";
|
|
2
|
+
interface Mysql2Module {
|
|
3
|
+
Connection?: {
|
|
4
|
+
prototype?: object;
|
|
5
|
+
};
|
|
6
|
+
Pool?: {
|
|
7
|
+
prototype?: object;
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Query spans for `mysql2` - the core connection and pool, which the promise
|
|
12
|
+
* wrappers, TypeORM, MikroORM, Knex, Drizzle and Sequelize all go through.
|
|
13
|
+
*
|
|
14
|
+
* A pool's `query` builds the command itself and hands that object to a
|
|
15
|
+
* connection later, possibly from another request's context, so the span is
|
|
16
|
+
* opened at the pool and the command is marked; the connection-level wrapper
|
|
17
|
+
* sees the mark and stands aside.
|
|
18
|
+
*/
|
|
19
|
+
export declare function patchMysql2(mysql2: Mysql2Module, recorder: OutgoingSpanRecorder): boolean;
|
|
20
|
+
export {};
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { patchMethod } from "./patch-method.util.js";
|
|
2
|
+
import { describeSqlStatement } from "./sql-statement.util.js";
|
|
3
|
+
/** Marks a command that already has a span, however it reaches a connection. */
|
|
4
|
+
const SPANNED = Symbol.for("nestjs.observe.mysql2.spanned");
|
|
5
|
+
/**
|
|
6
|
+
* Query spans for `mysql2` - the core connection and pool, which the promise
|
|
7
|
+
* wrappers, TypeORM, MikroORM, Knex, Drizzle and Sequelize all go through.
|
|
8
|
+
*
|
|
9
|
+
* A pool's `query` builds the command itself and hands that object to a
|
|
10
|
+
* connection later, possibly from another request's context, so the span is
|
|
11
|
+
* opened at the pool and the command is marked; the connection-level wrapper
|
|
12
|
+
* sees the mark and stands aside.
|
|
13
|
+
*/
|
|
14
|
+
export function patchMysql2(mysql2, recorder) {
|
|
15
|
+
const wrap = (original) => function (...args) {
|
|
16
|
+
const first = args[0];
|
|
17
|
+
if (typeof first === "object" && first?.[SPANNED]) {
|
|
18
|
+
return original.apply(this, args);
|
|
19
|
+
}
|
|
20
|
+
const sql = typeof first === "string" ? first : first?.sql;
|
|
21
|
+
if (typeof sql !== "string") {
|
|
22
|
+
return original.apply(this, args);
|
|
23
|
+
}
|
|
24
|
+
const { operation, statement } = describeSqlStatement(sql);
|
|
25
|
+
const span = recorder.open("mysql2", operation, {
|
|
26
|
+
"db.system": "mysql",
|
|
27
|
+
"db.statement": statement,
|
|
28
|
+
});
|
|
29
|
+
if (!span) {
|
|
30
|
+
return original.apply(this, args);
|
|
31
|
+
}
|
|
32
|
+
// The callback is wrapped where it is passed, not only once it has
|
|
33
|
+
// become the command's `onResult`: a pool's `execute` returns no command
|
|
34
|
+
// at all - it builds one later, on the connection it checks out - and a
|
|
35
|
+
// connection's `execute` reports a failed prepare to the callback it
|
|
36
|
+
// was given, whatever `onResult` has been replaced with since.
|
|
37
|
+
let hasCallback = false;
|
|
38
|
+
const last = args.length - 1;
|
|
39
|
+
if (typeof args[last] === "function") {
|
|
40
|
+
const callback = args[last];
|
|
41
|
+
hasCallback = true;
|
|
42
|
+
args[last] = function (error, ...rest) {
|
|
43
|
+
span.end(error);
|
|
44
|
+
return callback.call(this, error, ...rest);
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
let command;
|
|
48
|
+
try {
|
|
49
|
+
// Covered as well as marked. The mark follows a command *object* to
|
|
50
|
+
// the connection, which is how `pool.query` hands its work over; but
|
|
51
|
+
// `pool.execute` passes the connection the SQL string again, with
|
|
52
|
+
// nothing to carry a mark, and the same query would be recorded twice.
|
|
53
|
+
command = recorder.cover(() => original.apply(this, args));
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
span.end(error);
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
if (!command || typeof command !== "object") {
|
|
60
|
+
if (!hasCallback) {
|
|
61
|
+
span.end();
|
|
62
|
+
}
|
|
63
|
+
return command;
|
|
64
|
+
}
|
|
65
|
+
command[SPANNED] = true;
|
|
66
|
+
if (hasCallback) {
|
|
67
|
+
return command;
|
|
68
|
+
}
|
|
69
|
+
if (typeof command.onResult === "function") {
|
|
70
|
+
const onResult = command.onResult;
|
|
71
|
+
command.onResult = function (error, ...rest) {
|
|
72
|
+
span.end(error);
|
|
73
|
+
return onResult.call(this, error, ...rest);
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
// The streaming form. `end` always fires; an `error` listener is not
|
|
78
|
+
// added, because without one mysql2 lets the error surface as an
|
|
79
|
+
// uncaught exception, and an agent must not be what silences that.
|
|
80
|
+
command.once?.("end", () => span.end());
|
|
81
|
+
}
|
|
82
|
+
return command;
|
|
83
|
+
};
|
|
84
|
+
const patched = ["query", "execute"].flatMap((method) => [
|
|
85
|
+
patchMethod(mysql2.Connection?.prototype, method, wrap),
|
|
86
|
+
patchMethod(mysql2.Pool?.prototype, method, wrap),
|
|
87
|
+
]);
|
|
88
|
+
return patched.some(Boolean);
|
|
89
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { OnApplicationShutdown } from "@nestjs/common";
|
|
2
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
3
|
+
import { ObserveModuleOptionsWithDefaults } from "../interfaces/index.js";
|
|
4
|
+
import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
|
|
5
|
+
export declare class OutgoingObserveAgentService implements OnApplicationShutdown {
|
|
6
|
+
private readonly options;
|
|
7
|
+
private readonly logger;
|
|
8
|
+
private unsubscribeHttp?;
|
|
9
|
+
constructor(options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, asyncLocalStorage: AsyncLocalStorage<Map<any, any>>);
|
|
10
|
+
onApplicationShutdown(): void;
|
|
11
|
+
/**
|
|
12
|
+
* Patches every copy of a driver the application can end up running on: the
|
|
13
|
+
* one it resolves itself, and the one each ORM that depends on the driver
|
|
14
|
+
* *directly* resolves - see `DRIVER_DEPENDENTS`.
|
|
15
|
+
*/
|
|
16
|
+
private patchDriver;
|
|
17
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
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 OutgoingObserveAgentService_1;
|
|
14
|
+
import { Inject, Injectable, Logger, } from "@nestjs/common";
|
|
15
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
16
|
+
import { OBSERVE_OPTIONS } from "../observe.constants.js";
|
|
17
|
+
import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
|
|
18
|
+
import { loadAsResolvedBy, loadOptionalPeer, } from "../utils/optional-peer.util.js";
|
|
19
|
+
import { subscribeOutgoingHttp } from "./http.integration.js";
|
|
20
|
+
import { patchMongodb } from "./mongodb.integration.js";
|
|
21
|
+
import { patchMysql2 } from "./mysql2.integration.js";
|
|
22
|
+
import { OutgoingSpanRecorder } from "./outgoing-span.recorder.js";
|
|
23
|
+
import { patchPg } from "./pg.integration.js";
|
|
24
|
+
/**
|
|
25
|
+
* Spans for what leaves the process: database queries and outbound HTTP.
|
|
26
|
+
*
|
|
27
|
+
* The drivers are instrumented, not the ORMs. Every ORM a Nest application is
|
|
28
|
+
* likely to use ends in one of three drivers, so three small patches cover
|
|
29
|
+
* TypeORM, MikroORM, Prisma's driver adapters, Mongoose, Knex, Drizzle and
|
|
30
|
+
* Sequelize alike, and none of them has to be known by name. Each driver is an
|
|
31
|
+
* optional peer nobody is asked to install: it is looked up, and patched only
|
|
32
|
+
* if the application already has it.
|
|
33
|
+
*/
|
|
34
|
+
/**
|
|
35
|
+
* ORMs that list a driver under `dependencies` rather than `peerDependencies`.
|
|
36
|
+
*
|
|
37
|
+
* A peer resolves to the application's own copy, which is the one patched. A
|
|
38
|
+
* direct dependency does too - until the versions disagree, and npm nests a
|
|
39
|
+
* private copy inside the ORM. MikroORM pins its drivers to exact versions,
|
|
40
|
+
* so that happens on a single patch release of difference (its `mysql2`
|
|
41
|
+
* 3.24.3 beside an application's 3.24.4); Mongoose asks for a minor range.
|
|
42
|
+
* Queries through the ORM would then run on a copy nobody patched and simply
|
|
43
|
+
* not appear, with nothing to say why.
|
|
44
|
+
*
|
|
45
|
+
* TypeORM, Drizzle, Knex, Sequelize and Prisma's adapters take their driver
|
|
46
|
+
* as a peer and need no entry.
|
|
47
|
+
*/
|
|
48
|
+
const DRIVER_DEPENDENTS = {
|
|
49
|
+
pg: ["@mikro-orm/postgresql"],
|
|
50
|
+
mysql2: ["@mikro-orm/mysql"],
|
|
51
|
+
mongodb: ["mongoose", "@mikro-orm/mongodb"],
|
|
52
|
+
};
|
|
53
|
+
let OutgoingObserveAgentService = OutgoingObserveAgentService_1 = class OutgoingObserveAgentService {
|
|
54
|
+
options;
|
|
55
|
+
logger = new Logger(OutgoingObserveAgentService_1.name);
|
|
56
|
+
unsubscribeHttp;
|
|
57
|
+
constructor(options, operationTraceRegistry, asyncLocalStorage) {
|
|
58
|
+
this.options = options;
|
|
59
|
+
const outgoing = this.options.outgoing;
|
|
60
|
+
if (outgoing === false) {
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
const recorder = new OutgoingSpanRecorder(operationTraceRegistry, asyncLocalStorage, this.options.traceIdKey);
|
|
64
|
+
if (outgoing?.database !== false) {
|
|
65
|
+
this.patchDriver("pg", "pg", DRIVER_DEPENDENTS.pg, (module) => patchPg(module, recorder));
|
|
66
|
+
this.patchDriver("mysql2", "mysql2", DRIVER_DEPENDENTS.mysql2, (module) => patchMysql2(module, recorder));
|
|
67
|
+
this.patchDriver("mongodb", "mongodb/lib/cmap/connection", DRIVER_DEPENDENTS.mongodb, (module) => patchMongodb(module, recorder));
|
|
68
|
+
}
|
|
69
|
+
if (outgoing?.http !== false) {
|
|
70
|
+
this.unsubscribeHttp = subscribeOutgoingHttp(recorder, () => {
|
|
71
|
+
const traceId = asyncLocalStorage
|
|
72
|
+
.getStore()
|
|
73
|
+
?.get(this.options.traceIdKey);
|
|
74
|
+
return typeof traceId === "string" ? traceId : undefined;
|
|
75
|
+
}, typeof outgoing?.http === "object" ? outgoing.http : {}, () => operationTraceRegistry.getRedactor());
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
onApplicationShutdown() {
|
|
79
|
+
this.unsubscribeHttp?.();
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Patches every copy of a driver the application can end up running on: the
|
|
83
|
+
* one it resolves itself, and the one each ORM that depends on the driver
|
|
84
|
+
* *directly* resolves - see `DRIVER_DEPENDENTS`.
|
|
85
|
+
*/
|
|
86
|
+
patchDriver(packageName, specifier, dependents, patch) {
|
|
87
|
+
const copies = [];
|
|
88
|
+
const own = loadOptionalPeer(packageName, specifier);
|
|
89
|
+
if (own.installed && own.module) {
|
|
90
|
+
copies.push(own.module);
|
|
91
|
+
}
|
|
92
|
+
for (const dependent of dependents) {
|
|
93
|
+
const theirs = loadAsResolvedBy(dependent, specifier);
|
|
94
|
+
if (theirs && !copies.includes(theirs)) {
|
|
95
|
+
copies.push(theirs);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
if (copies.length === 0) {
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
// Never fatal, and quiet unless asked: a driver that moved its internals
|
|
102
|
+
// costs the query spans, and the application did nothing wrong.
|
|
103
|
+
let patched = false;
|
|
104
|
+
for (const copy of copies) {
|
|
105
|
+
try {
|
|
106
|
+
patched = patch(copy) || patched;
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
/* reported below */
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (!patched && this.options.debug) {
|
|
113
|
+
this.logger.debug(`${packageName} is installed but could not be instrumented, so its queries will not appear as spans.`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
OutgoingObserveAgentService = OutgoingObserveAgentService_1 = __decorate([
|
|
118
|
+
Injectable(),
|
|
119
|
+
__param(0, Inject(OBSERVE_OPTIONS)),
|
|
120
|
+
__metadata("design:paramtypes", [Object, OperationTraceRegistry,
|
|
121
|
+
AsyncLocalStorage])
|
|
122
|
+
], OutgoingObserveAgentService);
|
|
123
|
+
export { OutgoingObserveAgentService };
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
2
|
+
import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
|
|
3
|
+
type Tags = Record<string, string | number | boolean>;
|
|
4
|
+
/** A span that has been opened and is waiting to be told how the call went. */
|
|
5
|
+
export interface OpenOutgoingSpan {
|
|
6
|
+
end(error?: unknown): void;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Opens leaf spans for calls that leave the process - a database query, an
|
|
10
|
+
* outbound HTTP request - under whatever span is active when they are made.
|
|
11
|
+
*
|
|
12
|
+
* These calls never pass through the instance decorator: a driver is not a
|
|
13
|
+
* Nest provider, and an ORM's repository is only the last class the
|
|
14
|
+
* application can see before the time disappears. Each driver integration
|
|
15
|
+
* reads its own arguments and then uses this to put the span in the tree the
|
|
16
|
+
* same way the decorator would, so the waterfall shows a query under the
|
|
17
|
+
* repository method that ran it.
|
|
18
|
+
*
|
|
19
|
+
* A plain class shared by the integrations rather than a provider, and
|
|
20
|
+
* deliberately free of anything driver-specific.
|
|
21
|
+
*/
|
|
22
|
+
export declare class OutgoingSpanRecorder {
|
|
23
|
+
private readonly operationTraceRegistry;
|
|
24
|
+
private readonly asyncLocalStorage;
|
|
25
|
+
private readonly traceIdKey;
|
|
26
|
+
/**
|
|
27
|
+
* Set while a higher-level entry point (a pool's `query`) already holds the
|
|
28
|
+
* span for a call, so the lower-level one it delegates to (the client's
|
|
29
|
+
* `query`) does not open a second.
|
|
30
|
+
*/
|
|
31
|
+
private readonly covered;
|
|
32
|
+
constructor(operationTraceRegistry: OperationTraceRegistry, asyncLocalStorage: AsyncLocalStorage<Map<any, any>>, traceIdKey: string);
|
|
33
|
+
/**
|
|
34
|
+
* Opens a span, or returns `undefined` when there is nothing to attach it
|
|
35
|
+
* to: no traced operation in this async context, one that was sampled out,
|
|
36
|
+
* or a call an outer entry point already covers.
|
|
37
|
+
*/
|
|
38
|
+
open(className: string, methodKey: string, tags: Tags): OpenOutgoingSpan | undefined;
|
|
39
|
+
/** Runs `fn` with nested entry points told the call is already covered. */
|
|
40
|
+
cover<T>(fn: () => T): T;
|
|
41
|
+
/**
|
|
42
|
+
* Ends `span` when `result` settles, and hands `result` back untouched - the
|
|
43
|
+
* caller's own chain must see the same value and the same rejection it
|
|
44
|
+
* would have without the span.
|
|
45
|
+
*
|
|
46
|
+
* Anything that is not thenable ends the span on the spot. An open span is
|
|
47
|
+
* not harmless: the registry waits for every span to close before it ships
|
|
48
|
+
* a snapshot, and gives the whole snapshot up when one never does - so an
|
|
49
|
+
* unrecognised return type must cost this span its duration, not the
|
|
50
|
+
* request its trace.
|
|
51
|
+
*/
|
|
52
|
+
endWhenSettled<T>(span: OpenOutgoingSpan, result: T): T;
|
|
53
|
+
}
|
|
54
|
+
export {};
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
2
|
+
import { CALLER_METADATA_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
|
|
3
|
+
/**
|
|
4
|
+
* Opens leaf spans for calls that leave the process - a database query, an
|
|
5
|
+
* outbound HTTP request - under whatever span is active when they are made.
|
|
6
|
+
*
|
|
7
|
+
* These calls never pass through the instance decorator: a driver is not a
|
|
8
|
+
* Nest provider, and an ORM's repository is only the last class the
|
|
9
|
+
* application can see before the time disappears. Each driver integration
|
|
10
|
+
* reads its own arguments and then uses this to put the span in the tree the
|
|
11
|
+
* same way the decorator would, so the waterfall shows a query under the
|
|
12
|
+
* repository method that ran it.
|
|
13
|
+
*
|
|
14
|
+
* A plain class shared by the integrations rather than a provider, and
|
|
15
|
+
* deliberately free of anything driver-specific.
|
|
16
|
+
*/
|
|
17
|
+
export class OutgoingSpanRecorder {
|
|
18
|
+
operationTraceRegistry;
|
|
19
|
+
asyncLocalStorage;
|
|
20
|
+
traceIdKey;
|
|
21
|
+
/**
|
|
22
|
+
* Set while a higher-level entry point (a pool's `query`) already holds the
|
|
23
|
+
* span for a call, so the lower-level one it delegates to (the client's
|
|
24
|
+
* `query`) does not open a second.
|
|
25
|
+
*/
|
|
26
|
+
covered = new AsyncLocalStorage();
|
|
27
|
+
constructor(operationTraceRegistry, asyncLocalStorage, traceIdKey) {
|
|
28
|
+
this.operationTraceRegistry = operationTraceRegistry;
|
|
29
|
+
this.asyncLocalStorage = asyncLocalStorage;
|
|
30
|
+
this.traceIdKey = traceIdKey;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Opens a span, or returns `undefined` when there is nothing to attach it
|
|
34
|
+
* to: no traced operation in this async context, one that was sampled out,
|
|
35
|
+
* or a call an outer entry point already covers.
|
|
36
|
+
*/
|
|
37
|
+
open(className, methodKey, tags) {
|
|
38
|
+
if (this.covered.getStore()) {
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
const store = this.asyncLocalStorage.getStore();
|
|
42
|
+
const registryKey = store?.get(TRACE_REGISTRY_KEY) ?? store?.get(this.traceIdKey);
|
|
43
|
+
if (typeof registryKey !== "string") {
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
const callerId = store?.get(CALLER_METADATA_KEY);
|
|
47
|
+
const spanId = this.operationTraceRegistry.internalStartTraceStep(registryKey, className, methodKey, callerId);
|
|
48
|
+
if (spanId === undefined) {
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
const node = this.operationTraceRegistry.getActiveSpan(registryKey, spanId);
|
|
52
|
+
if (node) {
|
|
53
|
+
node.tags = { ...node.tags, ...tags };
|
|
54
|
+
}
|
|
55
|
+
let ended = false;
|
|
56
|
+
return {
|
|
57
|
+
end: (error) => {
|
|
58
|
+
// A driver may report one call twice - a callback and an `error`
|
|
59
|
+
// event, a settled promise and a late listener. The registry counts
|
|
60
|
+
// closes against opens, so the second would unbalance the snapshot.
|
|
61
|
+
if (ended) {
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
ended = true;
|
|
65
|
+
this.operationTraceRegistry.internalEndTraceStep(registryKey, spanId, className, methodKey, spanId, error === undefined || error === null ? undefined : error);
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
/** Runs `fn` with nested entry points told the call is already covered. */
|
|
70
|
+
cover(fn) {
|
|
71
|
+
return this.covered.run(true, fn);
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Ends `span` when `result` settles, and hands `result` back untouched - the
|
|
75
|
+
* caller's own chain must see the same value and the same rejection it
|
|
76
|
+
* would have without the span.
|
|
77
|
+
*
|
|
78
|
+
* Anything that is not thenable ends the span on the spot. An open span is
|
|
79
|
+
* not harmless: the registry waits for every span to close before it ships
|
|
80
|
+
* a snapshot, and gives the whole snapshot up when one never does - so an
|
|
81
|
+
* unrecognised return type must cost this span its duration, not the
|
|
82
|
+
* request its trace.
|
|
83
|
+
*/
|
|
84
|
+
endWhenSettled(span, result) {
|
|
85
|
+
const then = result?.then;
|
|
86
|
+
if (typeof then === "function") {
|
|
87
|
+
then.call(result, () => span.end(), (error) => span.end(error));
|
|
88
|
+
}
|
|
89
|
+
else {
|
|
90
|
+
span.end();
|
|
91
|
+
}
|
|
92
|
+
return result;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
type AnyFunction = (this: any, ...args: any[]) => any;
|
|
2
|
+
/**
|
|
3
|
+
* Replaces `name` on whichever prototype in the chain actually defines it, and
|
|
4
|
+
* parks the original beside it under a symbol.
|
|
5
|
+
*
|
|
6
|
+
* On the owner, because drivers build their public classes by inheritance
|
|
7
|
+
* (mysql2's `PoolConnection -> Connection -> BaseConnection`): patching a
|
|
8
|
+
* subclass would miss its siblings. Under a symbol, so a second agent in the
|
|
9
|
+
* same process - a second Nest app, a test suite - replaces the wrapper
|
|
10
|
+
* rather than wrapping it again.
|
|
11
|
+
*
|
|
12
|
+
* Returns `false` when no prototype in the chain defines the method.
|
|
13
|
+
*/
|
|
14
|
+
export declare function patchMethod(prototype: object | undefined | null, name: string, wrap: (original: AnyFunction) => AnyFunction): boolean;
|
|
15
|
+
export {};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Replaces `name` on whichever prototype in the chain actually defines it, and
|
|
3
|
+
* parks the original beside it under a symbol.
|
|
4
|
+
*
|
|
5
|
+
* On the owner, because drivers build their public classes by inheritance
|
|
6
|
+
* (mysql2's `PoolConnection -> Connection -> BaseConnection`): patching a
|
|
7
|
+
* subclass would miss its siblings. Under a symbol, so a second agent in the
|
|
8
|
+
* same process - a second Nest app, a test suite - replaces the wrapper
|
|
9
|
+
* rather than wrapping it again.
|
|
10
|
+
*
|
|
11
|
+
* Returns `false` when no prototype in the chain defines the method.
|
|
12
|
+
*/
|
|
13
|
+
export function patchMethod(prototype, name, wrap) {
|
|
14
|
+
let owner = prototype;
|
|
15
|
+
while (owner && !Object.hasOwn(owner, name)) {
|
|
16
|
+
owner = Object.getPrototypeOf(owner);
|
|
17
|
+
}
|
|
18
|
+
if (!owner || owner === Object.prototype) {
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
const key = Symbol.for(`nestjs.observe.original.${name}`);
|
|
22
|
+
const original = owner[key] ?? owner[name];
|
|
23
|
+
if (typeof original !== "function") {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
owner[key] = original;
|
|
27
|
+
owner[name] = wrap(original);
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { OutgoingSpanRecorder } from "./outgoing-span.recorder.js";
|
|
2
|
+
interface PgModule {
|
|
3
|
+
Client?: {
|
|
4
|
+
prototype?: object;
|
|
5
|
+
};
|
|
6
|
+
Pool?: {
|
|
7
|
+
prototype?: object;
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Query spans for `pg` - and so for everything built on it: TypeORM,
|
|
12
|
+
* MikroORM, Knex, Drizzle, Sequelize, and Prisma through its pg adapter.
|
|
13
|
+
*
|
|
14
|
+
* Both entry points are patched. `Client#query` is the one every query ends
|
|
15
|
+
* up in; `Pool#query` is patched as well because it reaches the client from
|
|
16
|
+
* inside the pool's checkout callback, which for a queued checkout runs in
|
|
17
|
+
* whichever request released the connection - the span has to be opened
|
|
18
|
+
* before that hop, in the caller's own context. The pool's span then covers
|
|
19
|
+
* the client call it leads to.
|
|
20
|
+
*/
|
|
21
|
+
export declare function patchPg(pg: PgModule, recorder: OutgoingSpanRecorder): boolean;
|
|
22
|
+
export {};
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { patchMethod } from "./patch-method.util.js";
|
|
2
|
+
import { describeSqlStatement } from "./sql-statement.util.js";
|
|
3
|
+
/**
|
|
4
|
+
* Query spans for `pg` - and so for everything built on it: TypeORM,
|
|
5
|
+
* MikroORM, Knex, Drizzle, Sequelize, and Prisma through its pg adapter.
|
|
6
|
+
*
|
|
7
|
+
* Both entry points are patched. `Client#query` is the one every query ends
|
|
8
|
+
* up in; `Pool#query` is patched as well because it reaches the client from
|
|
9
|
+
* inside the pool's checkout callback, which for a queued checkout runs in
|
|
10
|
+
* whichever request released the connection - the span has to be opened
|
|
11
|
+
* before that hop, in the caller's own context. The pool's span then covers
|
|
12
|
+
* the client call it leads to.
|
|
13
|
+
*/
|
|
14
|
+
export function patchPg(pg, recorder) {
|
|
15
|
+
const wrap = (covers) => (original) => function (...args) {
|
|
16
|
+
const config = args[0];
|
|
17
|
+
const text = typeof config === "string" ? config : config?.text;
|
|
18
|
+
// A submittable - a cursor, a query stream - reports completion
|
|
19
|
+
// through its own events rather than a callback or a promise.
|
|
20
|
+
if (typeof text !== "string" || typeof config?.submit === "function") {
|
|
21
|
+
return original.apply(this, args);
|
|
22
|
+
}
|
|
23
|
+
const { operation, statement } = describeSqlStatement(text);
|
|
24
|
+
const span = recorder.open("pg", operation, {
|
|
25
|
+
"db.system": "postgresql",
|
|
26
|
+
"db.statement": statement,
|
|
27
|
+
});
|
|
28
|
+
if (!span) {
|
|
29
|
+
return original.apply(this, args);
|
|
30
|
+
}
|
|
31
|
+
let hasCallback = false;
|
|
32
|
+
const last = args.length - 1;
|
|
33
|
+
if (typeof args[last] === "function") {
|
|
34
|
+
const callback = args[last];
|
|
35
|
+
hasCallback = true;
|
|
36
|
+
args[last] = function (error, ...rest) {
|
|
37
|
+
span.end(error);
|
|
38
|
+
return callback.call(this, error, ...rest);
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
else if (typeof config?.callback === "function") {
|
|
42
|
+
const callback = config.callback;
|
|
43
|
+
hasCallback = true;
|
|
44
|
+
args[0] = {
|
|
45
|
+
...config,
|
|
46
|
+
callback(error, ...rest) {
|
|
47
|
+
span.end(error);
|
|
48
|
+
return callback.call(this, error, ...rest);
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
try {
|
|
53
|
+
const result = covers
|
|
54
|
+
? recorder.cover(() => original.apply(this, args))
|
|
55
|
+
: original.apply(this, args);
|
|
56
|
+
return hasCallback ? result : recorder.endWhenSettled(span, result);
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
span.end(error);
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
const client = patchMethod(pg.Client?.prototype, "query", wrap(false));
|
|
64
|
+
const pool = patchMethod(pg.Pool?.prototype, "query", wrap(true));
|
|
65
|
+
return client || pool;
|
|
66
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export interface SqlStatementDescription {
|
|
2
|
+
/**
|
|
3
|
+
* A low-cardinality label: the verb and the table, `SELECT users`. It names
|
|
4
|
+
* the span, so it is also what repeated queries collapse under and what the
|
|
5
|
+
* per-method aggregates group by - one row per kind of query, not one per
|
|
6
|
+
* distinct WHERE clause.
|
|
7
|
+
*/
|
|
8
|
+
operation: string;
|
|
9
|
+
/** The statement with every literal replaced, safe to leave the process. */
|
|
10
|
+
statement: string;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Strips a SQL statement of its values.
|
|
14
|
+
*
|
|
15
|
+
* Bound parameters never reach this function - only the text does - but
|
|
16
|
+
* applications interpolate, and an interpolated statement carries its data in
|
|
17
|
+
* its literals. Every string, number and IN-list is replaced, so what is
|
|
18
|
+
* shipped is the statement's shape. Comments go too: ORMs and query taggers
|
|
19
|
+
* put request ids and user ids in them.
|
|
20
|
+
*/
|
|
21
|
+
export declare function describeSqlStatement(sql: string): SqlStatementDescription;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
const MAX_STATEMENT_LENGTH = 2048;
|
|
2
|
+
const MAX_IDENTIFIER_LENGTH = 64;
|
|
3
|
+
/**
|
|
4
|
+
* Where each verb names the table it works on. `WITH` and anything unlisted
|
|
5
|
+
* falls through to the verb alone - a wrong table is worse than none.
|
|
6
|
+
*/
|
|
7
|
+
const TABLE_AFTER = {
|
|
8
|
+
SELECT: /\bFROM\s+([\w."`[\]]+)/i,
|
|
9
|
+
DELETE: /\bFROM\s+([\w."`[\]]+)/i,
|
|
10
|
+
INSERT: /\bINTO\s+([\w."`[\]]+)/i,
|
|
11
|
+
REPLACE: /\bINTO\s+([\w."`[\]]+)/i,
|
|
12
|
+
UPDATE: /^\s*UPDATE\s+(?:ONLY\s+)?([\w."`[\]]+)/i,
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Strips a SQL statement of its values.
|
|
16
|
+
*
|
|
17
|
+
* Bound parameters never reach this function - only the text does - but
|
|
18
|
+
* applications interpolate, and an interpolated statement carries its data in
|
|
19
|
+
* its literals. Every string, number and IN-list is replaced, so what is
|
|
20
|
+
* shipped is the statement's shape. Comments go too: ORMs and query taggers
|
|
21
|
+
* put request ids and user ids in them.
|
|
22
|
+
*/
|
|
23
|
+
export function describeSqlStatement(sql) {
|
|
24
|
+
const statement = sql
|
|
25
|
+
.slice(0, MAX_STATEMENT_LENGTH * 4)
|
|
26
|
+
.replace(/\/\*[\s\S]*?\*\//g, " ")
|
|
27
|
+
.replace(/--[^\n]*/g, " ")
|
|
28
|
+
// Dollar-quoted (Postgres), then single-quoted with doubled-quote and
|
|
29
|
+
// backslash escapes. Double quotes and backticks are identifiers - kept.
|
|
30
|
+
.replace(/\$([A-Za-z_]*)\$[\s\S]*?\$\1\$/g, "?")
|
|
31
|
+
.replace(/'(?:[^'\\]|\\.|'')*'/g, "?")
|
|
32
|
+
// A number that is not part of an identifier or a `$1` placeholder.
|
|
33
|
+
.replace(/(?<![\w$])-?\d+(?:\.\d+)?(?:e[+-]?\d+)?(?![\w])/gi, "?")
|
|
34
|
+
.replace(/\(\s*\?(?:\s*,\s*\?)+\s*\)/g, "(?)")
|
|
35
|
+
.replace(/\(\s*\$\d+(?:\s*,\s*\$\d+)+\s*\)/g, "($n)")
|
|
36
|
+
.replace(/\s+/g, " ")
|
|
37
|
+
.trim()
|
|
38
|
+
.slice(0, MAX_STATEMENT_LENGTH);
|
|
39
|
+
const verb = /^[\s(]*([A-Za-z]+)/.exec(statement)?.[1]?.toUpperCase();
|
|
40
|
+
if (!verb) {
|
|
41
|
+
return { operation: "QUERY", statement };
|
|
42
|
+
}
|
|
43
|
+
const table = TABLE_AFTER[verb]
|
|
44
|
+
?.exec(statement)?.[1]
|
|
45
|
+
?.replace(/["`[\]]/g, "")
|
|
46
|
+
.slice(0, MAX_IDENTIFIER_LENGTH);
|
|
47
|
+
return { operation: table ? `${verb} ${table}` : verb, statement };
|
|
48
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
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 { KeyOf } from "../types/key-of.type.js";
|
|
6
|
+
/**
|
|
7
|
+
* Job tracing for the original Bull, which `@nestjs/bull` wraps - the same
|
|
8
|
+
* snapshots `@nestjs/bullmq` produces, from a driver a large share of Nest
|
|
9
|
+
* applications still run.
|
|
10
|
+
*
|
|
11
|
+
* Bull itself is patched rather than the Nest explorer: every processor, named
|
|
12
|
+
* or not, request-scoped or not, reaches the queue through `setHandler`, so
|
|
13
|
+
* one patch covers them all without depending on the explorer's internals.
|
|
14
|
+
*/
|
|
15
|
+
export declare class BullObserveAgentService<Store extends Record<string, unknown>> {
|
|
16
|
+
private readonly logger;
|
|
17
|
+
private readonly runner;
|
|
18
|
+
constructor(observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>);
|
|
19
|
+
private loadQueuePrototype;
|
|
20
|
+
private readQueueMetadata;
|
|
21
|
+
private patchBull;
|
|
22
|
+
/**
|
|
23
|
+
* Bull decides between a promise and a callback handler by arity, after
|
|
24
|
+
* binding it to the queue - so each wrapper declares the parameters of the
|
|
25
|
+
* kind it stands in for, and leaves `this` to that bind.
|
|
26
|
+
*/
|
|
27
|
+
private instrument;
|
|
28
|
+
}
|