@nestjs/observe 0.2.2 → 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.
Files changed (66) hide show
  1. package/README.md +38 -0
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/agent/detached-observe-worker.assembly.d.ts +18 -0
  4. package/dist/agent/detached-observe-worker.assembly.js +29 -0
  5. package/dist/agent/detached-observe-worker.d.ts +21 -0
  6. package/dist/agent/detached-observe-worker.js +74 -24
  7. package/dist/agent/observe-agent.shared-buffer.js +7 -5
  8. package/dist/agent/observe-agent.worker.js +17 -21
  9. package/dist/agent/telemetry-wire-contract.js +1 -0
  10. package/dist/encoders/remap-keys.util.js +6 -0
  11. package/dist/encoders/request-snapshot.encoder.d.ts +1 -0
  12. package/dist/encoders/request-snapshot.encoder.js +1 -0
  13. package/dist/instrument/create-instance-decorator.instrument.js +2 -2
  14. package/dist/interfaces/observe-options.interface.d.ts +97 -9
  15. package/dist/interfaces/request-snapshot.interface.d.ts +8 -0
  16. package/dist/observe.constants.d.ts +16 -0
  17. package/dist/observe.constants.js +16 -0
  18. package/dist/observe.module.js +55 -6
  19. package/dist/outgoing/http.integration.d.ts +36 -0
  20. package/dist/outgoing/http.integration.js +127 -0
  21. package/dist/outgoing/mongodb.integration.d.ts +38 -0
  22. package/dist/outgoing/mongodb.integration.js +141 -0
  23. package/dist/outgoing/mysql2.integration.d.ts +20 -0
  24. package/dist/outgoing/mysql2.integration.js +89 -0
  25. package/dist/outgoing/outgoing-observe-agent.service.d.ts +17 -0
  26. package/dist/outgoing/outgoing-observe-agent.service.js +123 -0
  27. package/dist/outgoing/outgoing-span.recorder.d.ts +54 -0
  28. package/dist/outgoing/outgoing-span.recorder.js +94 -0
  29. package/dist/outgoing/patch-method.util.d.ts +15 -0
  30. package/dist/outgoing/patch-method.util.js +29 -0
  31. package/dist/outgoing/pg.integration.d.ts +22 -0
  32. package/dist/outgoing/pg.integration.js +66 -0
  33. package/dist/outgoing/sql-statement.util.d.ts +21 -0
  34. package/dist/outgoing/sql-statement.util.js +48 -0
  35. package/dist/protocols/bull-observe-agent.service.d.ts +28 -0
  36. package/dist/protocols/bull-observe-agent.service.js +130 -0
  37. package/dist/protocols/graphql-observe-agent.service.js +5 -2
  38. package/dist/protocols/graphql-operation-parser.d.ts +6 -4
  39. package/dist/protocols/graphql-operation-parser.js +61 -6
  40. package/dist/protocols/http-observe-agent.service.js +26 -7
  41. package/dist/protocols/job-trace-runner.d.ts +77 -0
  42. package/dist/protocols/job-trace-runner.js +196 -0
  43. package/dist/protocols/queue-observe-agent.service.d.ts +9 -4
  44. package/dist/protocols/queue-observe-agent.service.js +36 -95
  45. package/dist/protocols/ws-observe-agent.service.d.ts +39 -0
  46. package/dist/protocols/ws-observe-agent.service.js +180 -0
  47. package/dist/services/operation-trace.registry.d.ts +35 -1
  48. package/dist/services/operation-trace.registry.js +68 -5
  49. package/dist/services/trace-sampler.service.d.ts +4 -0
  50. package/dist/services/tracer.service.js +5 -3
  51. package/dist/utils/capture-request.util.d.ts +57 -0
  52. package/dist/utils/capture-request.util.js +116 -0
  53. package/dist/utils/default-trace-id-generator.util.d.ts +12 -0
  54. package/dist/utils/default-trace-id-generator.util.js +12 -1
  55. package/dist/utils/log-redactor.d.ts +20 -1
  56. package/dist/utils/log-redactor.js +54 -38
  57. package/dist/utils/optional-peer.util.d.ts +13 -0
  58. package/dist/utils/optional-peer.util.js +30 -0
  59. package/dist/utils/redact-url-query.d.ts +10 -1
  60. package/dist/utils/redact-url-query.js +16 -37
  61. package/dist/utils/sensitive-keys.d.ts +15 -0
  62. package/dist/utils/sensitive-keys.js +76 -0
  63. package/dist/utils/source-context.util.d.ts +6 -0
  64. package/dist/utils/source-context.util.js +121 -15
  65. package/dist/utils/source-map-resolver.util.js +12 -0
  66. package/package.json +35 -2
@@ -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
+ }
@@ -0,0 +1,130 @@
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 BullObserveAgentService_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 { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
20
+ import { JobTraceRunner } from "./job-trace-runner.js";
21
+ const ORIGINAL_SET_HANDLER = Symbol.for("nestjs.observe.bull.setHandler");
22
+ /** Bull names an unnamed job this; reporting it would name every job the same. */
23
+ const BULL_DEFAULT_JOB_NAME = "__default__";
24
+ /**
25
+ * Job tracing for the original Bull, which `@nestjs/bull` wraps - the same
26
+ * snapshots `@nestjs/bullmq` produces, from a driver a large share of Nest
27
+ * applications still run.
28
+ *
29
+ * Bull itself is patched rather than the Nest explorer: every processor, named
30
+ * or not, request-scoped or not, reaches the queue through `setHandler`, so
31
+ * one patch covers them all without depending on the explorer's internals.
32
+ */
33
+ let BullObserveAgentService = BullObserveAgentService_1 = class BullObserveAgentService {
34
+ logger = new Logger(BullObserveAgentService_1.name);
35
+ runner;
36
+ constructor(observeAgentSharedBuffer, options, operationTraceRegistry, asyncLocalStorage) {
37
+ this.runner = new JobTraceRunner(observeAgentSharedBuffer, options, operationTraceRegistry, asyncLocalStorage, this.logger);
38
+ this.patchBull();
39
+ }
40
+ loadQueuePrototype() {
41
+ const result = loadOptionalPeer("bull");
42
+ if (!result.installed) {
43
+ return undefined;
44
+ }
45
+ if (result.error) {
46
+ this.logger.warn(`bull is installed but could not be loaded, so its jobs will not be instrumented: ${describePeerLoadError(result.error)}`);
47
+ return null;
48
+ }
49
+ return result.module?.prototype ?? null;
50
+ }
51
+ readQueueMetadata(job) {
52
+ const metadata = {};
53
+ if (typeof job.timestamp === "number") {
54
+ metadata.enqueuedAt = new Date(job.timestamp).toISOString();
55
+ const startedAt = typeof job.processedOn === "number" ? job.processedOn : Date.now();
56
+ // As with BullMQ: a delay the caller asked for is a schedule, not a
57
+ // backlog, so the wait is measured from when the job became runnable.
58
+ // `||`, not `??`: the job's own `delay` reads 0 once Bull has promoted
59
+ // it, and only the options still say what was asked for.
60
+ const delay = job.delay || job.opts?.delay || 0;
61
+ metadata.waitDuration = Math.max(0, startedAt - (job.timestamp + delay));
62
+ }
63
+ if (typeof job.attemptsMade === "number") {
64
+ metadata.attemptsMade = job.attemptsMade;
65
+ }
66
+ if (typeof job.opts?.attempts === "number") {
67
+ metadata.maxAttempts = job.opts.attempts;
68
+ }
69
+ return metadata;
70
+ }
71
+ patchBull() {
72
+ const prototype = this.loadQueuePrototype();
73
+ if (prototype === undefined) {
74
+ // An optional peer. No Bull means no processor to wrap.
75
+ return;
76
+ }
77
+ const originalSetHandler = (prototype?.[ORIGINAL_SET_HANDLER] ??
78
+ prototype?.setHandler);
79
+ if (!prototype || typeof originalSetHandler !== "function") {
80
+ this.logger.warn("Bull's Queue.prototype.setHandler is not available, so its jobs will not be instrumented.");
81
+ return;
82
+ }
83
+ prototype[ORIGINAL_SET_HANDLER] = originalSetHandler;
84
+ const instrument = (handler) => this.instrument(handler);
85
+ prototype.setHandler = function (name, handler) {
86
+ // A string is a path to a sandboxed processor. It runs in a child
87
+ // process this agent is not loaded in, so there is nothing to wrap.
88
+ return originalSetHandler.call(this, name, typeof handler === "function"
89
+ ? instrument(handler)
90
+ : handler);
91
+ };
92
+ // add(name?, data, opts)
93
+ this.runner.patchEnqueue(prototype, (args) => typeof args[0] === "string" ? 2 : 1);
94
+ }
95
+ /**
96
+ * Bull decides between a promise and a callback handler by arity, after
97
+ * binding it to the queue - so each wrapper declares the parameters of the
98
+ * kind it stands in for, and leaves `this` to that bind.
99
+ */
100
+ instrument(handler) {
101
+ const describe = (job) => ({
102
+ queueName: job.queue?.name ?? "bull",
103
+ name: job.name && job.name !== BULL_DEFAULT_JOB_NAME
104
+ ? job.name
105
+ : job.queue?.name ?? "bull",
106
+ id: job.id,
107
+ opts: job.opts,
108
+ metadata: this.readQueueMetadata(job),
109
+ });
110
+ const runner = this.runner;
111
+ if (handler.length > 1) {
112
+ return function (job, done) {
113
+ return runner.run(describe(job), (settle) => handler.call(this, job, (error, value) => {
114
+ settle(error ? "failed" : "completed");
115
+ done?.(error, value);
116
+ }), true);
117
+ };
118
+ }
119
+ return function (job) {
120
+ return runner.run(describe(job), () => handler.call(this, job));
121
+ };
122
+ }
123
+ };
124
+ BullObserveAgentService = BullObserveAgentService_1 = __decorate([
125
+ Injectable(),
126
+ __param(1, Inject(OBSERVE_OPTIONS)),
127
+ __metadata("design:paramtypes", [ObserveAgentSharedBuffer, Object, OperationTraceRegistry,
128
+ AsyncLocalStorage])
129
+ ], BullObserveAgentService);
130
+ export { BullObserveAgentService };
@@ -15,7 +15,7 @@ import { Inject, Injectable, Logger } from "@nestjs/common";
15
15
  import { DiscoveryService, MetadataScanner, ModuleRef } from "@nestjs/core";
16
16
  import { AsyncLocalStorage } from "async_hooks";
17
17
  import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
18
- import { CALLER_METADATA_KEY, OBSERVE_OPTIONS } from "../observe.constants.js";
18
+ import { CALLER_METADATA_KEY, OBSERVE_OPTIONS, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
19
19
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
20
20
  import { TraceSamplerService } from "../services/trace-sampler.service.js";
21
21
  import { parseGraphQLOperation, toResolveInfoLike, } from "./graphql-operation-parser.js";
@@ -186,7 +186,10 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
186
186
  originalUrl: parsed.sanitizedDocument,
187
187
  };
188
188
  const store = this.asyncLocalStorage.getStore();
189
- const traceId = store?.get(this.options.traceIdKey);
189
+ // The registry key, where the transport in front gave the request one
190
+ // of its own; the trace id otherwise, which is then the key as well.
191
+ const traceId = store?.get(TRACE_REGISTRY_KEY) ??
192
+ store?.get(this.options.traceIdKey);
190
193
  if (traceId) {
191
194
  return this.startWithinRequest(traceId, operationId, attributes, info, ctx);
192
195
  }