@nestjs/observe 0.3.11 → 0.3.13

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 (39) hide show
  1. package/README.md +71 -2
  2. package/dist/agent/degraded-ingest.protocol.d.ts +87 -16
  3. package/dist/agent/degraded-ingest.protocol.js +62 -17
  4. package/dist/agent/detached-observe-worker.assembly.d.ts +1 -0
  5. package/dist/agent/detached-observe-worker.assembly.js +1 -0
  6. package/dist/agent/detached-observe-worker.d.ts +5 -0
  7. package/dist/agent/detached-observe-worker.js +129 -63
  8. package/dist/agent/observe-agent.shared-buffer.d.ts +54 -1
  9. package/dist/agent/observe-agent.shared-buffer.js +127 -22
  10. package/dist/agent/observe-agent.worker.d.ts +38 -1
  11. package/dist/agent/observe-agent.worker.js +134 -23
  12. package/dist/agent/telemetry-wire-contract.js +11 -1
  13. package/dist/encoders/request-snapshot.encoder.d.ts +1 -0
  14. package/dist/encoders/request-snapshot.encoder.js +1 -0
  15. package/dist/interfaces/observe-options.interface.d.ts +17 -2
  16. package/dist/interfaces/request-snapshot.interface.d.ts +13 -0
  17. package/dist/objectives/objectives.registry.d.ts +1 -0
  18. package/dist/objectives/objectives.registry.js +12 -0
  19. package/dist/outgoing/mssql.integration.d.ts +12 -0
  20. package/dist/outgoing/mssql.integration.js +248 -0
  21. package/dist/outgoing/mysql2.integration.js +1 -1
  22. package/dist/outgoing/outgoing-observe-agent.service.js +46 -8
  23. package/dist/outgoing/outgoing-span.recorder.d.ts +7 -0
  24. package/dist/outgoing/outgoing-span.recorder.js +15 -0
  25. package/dist/outgoing/pg.integration.js +1 -1
  26. package/dist/outgoing/sql-statement.util.d.ts +5 -1
  27. package/dist/outgoing/sql-statement.util.js +83 -10
  28. package/dist/protocols/http-observe-agent.service.js +9 -2
  29. package/dist/protocols/job-trace-runner.js +5 -0
  30. package/dist/services/node-runtime-metrics.service.js +1 -1
  31. package/dist/services/operation-trace.registry.d.ts +11 -0
  32. package/dist/services/operation-trace.registry.js +37 -1
  33. package/dist/services/stdout-forwarder.service.js +1 -1
  34. package/dist/services/trace-sampler.service.js +5 -0
  35. package/dist/services/tracer.service.d.ts +19 -0
  36. package/dist/services/tracer.service.js +61 -3
  37. package/dist/utils/ingest-refusal.util.d.ts +8 -3
  38. package/dist/utils/ingest-refusal.util.js +24 -3
  39. package/package.json +9 -4
@@ -21,16 +21,21 @@ import { ProfileUploader } from "../profiling/profile-uploader.js";
21
21
  import { setActiveSliceRecorder, SpanSliceRecorder, } from "../profiling/span-slice-recorder.js";
22
22
  import { NodeRuntimeMetricsService } from "../services/node-runtime-metrics.service.js";
23
23
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
24
- import { parseDegradedMessage, parsePausedMessage, } from "./degraded-ingest.protocol.js";
24
+ import { parseDegradedMessage, parseOveragePauseReason, parsePausedMessage, } from "./degraded-ingest.protocol.js";
25
25
  import { detachedWorkerData, detachedWorkerSource, } from "./detached-observe-worker.assembly.js";
26
26
  import { ObserveAgentSharedBuffer } from "./observe-agent.shared-buffer.js";
27
27
  const DEFAULT_RUNTIME_METRICS_INTERVAL = 60000; // 60 seconds
28
28
  const MIN_RUNTIME_METRICS_INTERVAL = 30000; // 30 seconds
29
29
  const DEFAULT_FLUSH_INTERVAL = 5000; // 5 seconds
30
+ /**
31
+ * The hosted collector. Unlike a collector in placeholder mode, it accepts
32
+ * nothing without credentials.
33
+ */
34
+ const HOSTED_COLLECTOR_ENDPOINT = "https://observe-api.nestjs.com";
30
35
  /**
31
36
  * Where signals are posted when `endpoint` is not configured.
32
37
  */
33
- const DEFAULT_COLLECTOR_ENDPOINT = process.env.OBSERVE_ENDPOINT ?? "https://observe-api.nestjs.com";
38
+ const DEFAULT_COLLECTOR_ENDPOINT = process.env.OBSERVE_ENDPOINT ?? HOSTED_COLLECTOR_ENDPOINT;
34
39
  const MIN_FLUSH_INTERVAL = 1000; // 1 second
35
40
  /**
36
41
  * How long shutdown waits for buffered telemetry to reach the collector before
@@ -100,7 +105,8 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
100
105
  shutdownPromise = null;
101
106
  /**
102
107
  * Until when the worker has said it will send nothing (epoch ms) - after a
103
- * 429, or for good after rejected credentials. Read by the final flush only.
108
+ * 429 or rejected credentials, until that pause lapses. Read by the final
109
+ * flush only.
104
110
  */
105
111
  sendsPausedUntil = 0;
106
112
  constructor(observeAgentSharedBuffer, options, nodeRuntimeMetricsService, operationTraceRegistry) {
@@ -110,16 +116,8 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
110
116
  this.operationTraceRegistry = operationTraceRegistry;
111
117
  }
112
118
  onModuleInit() {
113
- if (this.hasScaffoldCredentials) {
114
- // Nothing is sent, so there is no worker to start. The flush timer below
115
- // still runs and empties the buffer, which the instrumentation keeps
116
- // writing into either way.
117
- this.logger.log(`Observe is installed but not connected yet: appKey and appSecret are still the placeholders from nest new, so no telemetry is sent. ` +
118
- `See what this app will look like: ${DEMO_URL} - then create a free account at ${SIGN_UP_URL} for your own key and secret.`);
119
- }
120
- else {
121
- this.initializeWorker();
122
- }
119
+ // Settled before the worker starts, which backs off from this interval
120
+ // after rejected credentials - as does a worker restarted later on.
123
121
  let flushIntervalTime = this.options.flushInterval ?? DEFAULT_FLUSH_INTERVAL;
124
122
  if (flushIntervalTime < MIN_FLUSH_INTERVAL) {
125
123
  this.logger.warn(`Flush interval is too short (${flushIntervalTime}ms). Setting to minimum of ${MIN_FLUSH_INTERVAL}ms.`);
@@ -129,8 +127,34 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
129
127
  flushIntervalTime = MIN_FLUSH_INTERVAL;
130
128
  this.options.flushInterval = MIN_FLUSH_INTERVAL;
131
129
  }
130
+ if (this.isDisabled) {
131
+ // Ahead of the credential checks: an agent switched off on purpose
132
+ // needs no key or secret, so a missing one is not worth a warning.
133
+ this.logger.log("Observe is disabled (enabled: false): nothing is recorded or sent.");
134
+ }
135
+ else if (this.hasScaffoldCredentials) {
136
+ // Nothing is sent, so there is no worker to start. The flush timer below
137
+ // still runs and empties the buffer, which the instrumentation keeps
138
+ // writing into either way.
139
+ this.logger.log(`Observe is installed but not connected yet: appKey and appSecret are still the placeholders from nest new, so no telemetry is sent. ` +
140
+ `See what this app will look like: ${DEMO_URL} - then create a free account at ${SIGN_UP_URL} for your own key and secret.`);
141
+ }
142
+ else if (this.lacksHostedCredentials) {
143
+ // The same arrangement, said as a warning: this is a deployment missing
144
+ // its configuration, not a project fresh from the generator.
145
+ const unset = !this.options.appKey && !this.options.appSecret
146
+ ? "appKey and appSecret are"
147
+ : !this.options.appKey
148
+ ? "appKey is"
149
+ : "appSecret is";
150
+ this.logger.warn(`Observe is installed but sends nothing: ${unset} not set, and the hosted collector accepts no telemetry without a key and a secret. ` +
151
+ `If they come from the environment, check that both variables reach this process, then restart it. Create a key and secret at ${SIGN_UP_URL}.`);
152
+ }
153
+ else {
154
+ this.initializeWorker();
155
+ }
132
156
  this.flushInterval = setInterval(() => this.flush(), flushIntervalTime);
133
- if (!this.hasScaffoldCredentials) {
157
+ if (!this.sendsNothing) {
134
158
  this.startRuntimeMetrics();
135
159
  }
136
160
  // Continuous profiling is shelved: a flame graph asks more of a reader than
@@ -262,8 +286,9 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
262
286
  await this.cpuProfiler.stop();
263
287
  this.cpuProfiler = null;
264
288
  }
265
- // No worker - scaffold credentials, or never started - means nothing was
266
- // ever going to be sent, so there is nothing to flush either.
289
+ // No worker - placeholder or missing credentials, or never started -
290
+ // means nothing was ever going to be sent, so there is nothing to flush
291
+ // either.
267
292
  const worker = this.worker;
268
293
  if (!worker) {
269
294
  return;
@@ -420,6 +445,49 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
420
445
  return (this.options.appKey === SCAFFOLD_APP_KEY &&
421
446
  this.options.appSecret === SCAFFOLD_APP_SECRET);
422
447
  }
448
+ /**
449
+ * Whether credentials are missing and the collector is the hosted one,
450
+ * which answers every batch without them with a 401.
451
+ *
452
+ * The worker leaves both headers off when either half is unset, which a
453
+ * collector in placeholder mode accepts, so a collector of the user's own
454
+ * still gets those batches. The hosted collector refuses them for as long
455
+ * as the process runs: on 2026-10-15 that was 42% of the 1.87M batches it
456
+ * refused, from processes deployed without their environment variables,
457
+ * some of them posting every five seconds for weeks.
458
+ */
459
+ get lacksHostedCredentials() {
460
+ return ((!this.options.appKey || !this.options.appSecret) &&
461
+ this.isHostedCollector);
462
+ }
463
+ /**
464
+ * Whether `endpoint` - set, from `OBSERVE_ENDPOINT`, or the default - is the
465
+ * hosted collector. Compared by host, so a trailing slash or a capital
466
+ * letter cannot pass it off as a collector of the user's own.
467
+ */
468
+ get isHostedCollector() {
469
+ try {
470
+ return (new URL(this.endpoint).hostname ===
471
+ new URL(HOSTED_COLLECTOR_ENDPOINT).hostname);
472
+ }
473
+ catch {
474
+ // Not a URL at all; the worker says so when it tries to send.
475
+ return false;
476
+ }
477
+ }
478
+ /**
479
+ * Whether `enabled: false` switched the agent off - whatever the
480
+ * credentials, and whichever collector `endpoint` names.
481
+ */
482
+ get isDisabled() {
483
+ return this.options.enabled === false;
484
+ }
485
+ /** Whether nothing will be sent, so there is no worker to feed. */
486
+ get sendsNothing() {
487
+ return (this.isDisabled ||
488
+ this.hasScaffoldCredentials ||
489
+ this.lacksHostedCredentials);
490
+ }
423
491
  get endpoint() {
424
492
  return this.options.endpoint ?? DEFAULT_COLLECTOR_ENDPOINT;
425
493
  }
@@ -465,6 +533,8 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
465
533
  endpoint: this.endpoint,
466
534
  appKey: this.options.appKey,
467
535
  appSecret: this.options.appSecret,
536
+ // Clamped by `onModuleInit` before the first worker starts.
537
+ flushInterval: this.options.flushInterval ?? DEFAULT_FLUSH_INTERVAL,
468
538
  }),
469
539
  });
470
540
  this.watchWorker(this.worker);
@@ -496,7 +566,7 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
496
566
  }
497
567
  const mode = parseDegradedMessage(msg);
498
568
  if (mode !== null) {
499
- this.applyIngestMode(mode);
569
+ this.applyIngestMode(mode, parseOveragePauseReason(msg));
500
570
  return;
501
571
  }
502
572
  if (msg.includes("Error:")) {
@@ -515,6 +585,13 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
515
585
  * per flush would bury the one thing worth reading.
516
586
  */
517
587
  reportedMode = "full";
588
+ /**
589
+ * Why the account's overage is paused, when the last reply was errors-only
590
+ * and gave a reason this agent can word; null otherwise. Kept beside
591
+ * `reportedMode` for the same reason, and a pause whose reason changes -
592
+ * spike protection's, then a spent budget's - is said again.
593
+ */
594
+ reportedPauseReason = null;
518
595
  /**
519
596
  * Stops sending trace trees the collector has told us it is throwing away,
520
597
  * and says so once - and again only when the reason changes.
@@ -524,14 +601,36 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
524
601
  * that out by opening a trace and seeing nothing has been let down by an
525
602
  * agent that knew. Each line says what is still kept, because the traces
526
603
  * worth opening - server errors, slow requests, failed jobs - still are.
604
+ *
605
+ * Except while the account's overage is paused, when next to nothing is
606
+ * kept and nothing comes back on its own before the month ends: that line
607
+ * says so, and who can change it.
527
608
  */
528
- applyIngestMode(mode) {
529
- // Reduced and trimmed withhold the same trees; only the notice differs.
530
- this.observeAgentSharedBuffer.setDegraded(mode !== "full");
531
- if (mode === this.reportedMode) {
609
+ applyIngestMode(mode, pauseReason = null) {
610
+ // Reduced, trimmed and paced withhold the same trees, and errors-only
611
+ // everything but server errors; the buffer tells them apart.
612
+ this.observeAgentSharedBuffer.setIngestMode(mode);
613
+ if (mode === this.reportedMode &&
614
+ pauseReason === this.reportedPauseReason) {
532
615
  return;
533
616
  }
534
- if (mode === "reduced") {
617
+ if (mode === "errors-only") {
618
+ // Not "most traces arrive without their spans": requests, jobs and
619
+ // logs stop too, and the operator may have to ask whoever holds the
620
+ // account to resume them.
621
+ const why = pauseReason === "spike"
622
+ ? "spike protection paused this account's overage"
623
+ : pauseReason === "budget"
624
+ ? "this account's monthly overage budget is spent, so its overage is paused"
625
+ : "this account's overage is paused";
626
+ const resume = pauseReason === "budget"
627
+ ? "resumes it or raises the budget"
628
+ : "resumes it";
629
+ this.logger.warn(`Observe: ${why}. Only server errors and failed jobs are sent now, without their spans; ` +
630
+ "every other request and job, and every log line, is held back. Runtime and custom metrics are still recorded. " +
631
+ `Full collection returns when someone ${resume} at /dashboard/billing/usage, or at 00:00 UTC on the 1st.`);
632
+ }
633
+ else if (mode === "reduced") {
535
634
  this.logger.warn("Observe: this account has used its monthly allowance, so most traces now arrive without their spans. " +
536
635
  "Requests, jobs and errors are still recorded, and server errors, slow requests and failed jobs keep their full traces. " +
537
636
  "See /dashboard/billing/usage.");
@@ -541,10 +640,22 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
541
640
  "Requests, jobs and errors are still recorded, and server errors, slow requests and failed jobs keep their full traces. " +
542
641
  'To keep every trace, turn on "Keep full traces" at /dashboard/billing/usage.');
543
642
  }
643
+ else if (mode === "paced") {
644
+ // Not the reduced line: the allowance is not spent, and the spans come
645
+ // back at midnight UTC without the operator doing anything.
646
+ this.logger.warn("Observe: this account's day passed the Free plan's daily limit, so most traces arrive without their spans until 00:00 UTC. " +
647
+ "Requests, jobs and errors are still recorded, and server errors, slow requests and failed jobs keep their full traces. " +
648
+ "See /dashboard/billing/usage.");
649
+ }
650
+ else if (this.reportedMode === "errors-only") {
651
+ // Not only the spans: every request, job and log line is back.
652
+ this.logger.log("Observe: this account's overage is no longer paused, so everything is recorded again.");
653
+ }
544
654
  else {
545
655
  this.logger.log("Observe: spans are being recorded again.");
546
656
  }
547
657
  this.reportedMode = mode;
658
+ this.reportedPauseReason = pauseReason;
548
659
  }
549
660
  handleError(error) {
550
661
  this.logger.error(error);
@@ -555,7 +666,7 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
555
666
  // gone quiet, and an empty buffer would otherwise return here and strand
556
667
  // them until shutdown.
557
668
  this.observeAgentSharedBuffer.drainPendingLogs();
558
- if (this.hasScaffoldCredentials) {
669
+ if (this.sendsNothing) {
559
670
  this.observeAgentSharedBuffer.resetMainThreadBuffer();
560
671
  return;
561
672
  }
@@ -58,10 +58,16 @@ const TRACE_NODE = {
58
58
  so: { type: "number" },
59
59
  ch: { type: "object", array: true, recursive: true },
60
60
  };
61
+ /**
62
+ * The API takes the attributes as one object and checks none of its keys,
63
+ * so these are not refused there. They are declared all the same: a repair
64
+ * removes what is undeclared, and `dop` is what marks a request as renamed.
65
+ */
61
66
  const REQUEST_ATTRIBUTES = {
62
67
  m: { type: "string" },
63
68
  sc: { type: "number" },
64
69
  ou: { type: "string" },
70
+ dop: { type: "string" },
65
71
  };
66
72
  /**
67
73
  * An operation's spans. Required - the API refuses an operation without the
@@ -83,7 +89,11 @@ const REQUEST_SNAPSHOT = {
83
89
  ti: { type: "string", required: true, maxLength: 255 },
84
90
  d: { type: "number" },
85
91
  p: { type: "string" },
86
- op: { type: "string" },
92
+ // Required as the API requires it. The application can set it now
93
+ // (`TracerService.setOperationId`), so an unusable one can reach a batch, and
94
+ // a repair that only stripped it would re-send an entry the API refuses
95
+ // again - costing the whole batch rather than the one operation.
96
+ op: { type: "string", required: true },
87
97
  u: { type: "string" },
88
98
  tg: { type: "object" },
89
99
  e: { type: "object" },
@@ -4,6 +4,7 @@ declare const ATTRIBUTES_KEY_MAP: {
4
4
  readonly method: "m";
5
5
  readonly statusCode: "sc";
6
6
  readonly originalUrl: "ou";
7
+ readonly defaultOperationId: "dop";
7
8
  };
8
9
  declare const SNAPSHOT_KEY_MAP: {
9
10
  readonly calledAt: "ct";
@@ -4,6 +4,7 @@ const ATTRIBUTES_KEY_MAP = {
4
4
  method: "m",
5
5
  statusCode: "sc",
6
6
  originalUrl: "ou",
7
+ defaultOperationId: "dop",
7
8
  };
8
9
  const SNAPSHOT_KEY_MAP = {
9
10
  calledAt: "ct",
@@ -134,6 +134,18 @@ export interface CreateObserveModuleOptions {
134
134
  };
135
135
  }
136
136
  export interface ObserveOptions {
137
+ /**
138
+ * Whether the agent runs at all. `false` keeps the module in place - its
139
+ * providers, `TracerService` among them, still resolve - but records and
140
+ * sends nothing: no traces, runtime metrics or forwarded logs, no worker
141
+ * thread, and no request to any collector. It logs one line at startup
142
+ * saying so, and no warning about credentials, which it does not need.
143
+ *
144
+ * For environments that should not report, such as local development:
145
+ * `enabled: process.env.NODE_ENV === "production"`.
146
+ * @default true
147
+ */
148
+ enabled?: boolean;
137
149
  /**
138
150
  * Application key identifying this service to the collector.
139
151
  *
@@ -142,7 +154,10 @@ export interface ObserveOptions {
142
154
  *
143
155
  * Sent as `x-api-key` on every ingest request, alongside `appSecret`.
144
156
  * Without valid credentials the collector answers 401 and the batch is
145
- * dropped.
157
+ * dropped; the agent then backs off, to one attempt an hour, until a
158
+ * restart picks up fixed credentials. With this or `appSecret` unset,
159
+ * nothing is sent to the hosted collector at all - a warning at startup
160
+ * says so - while a collector of your own still receives the batches.
146
161
  */
147
162
  appKey: string;
148
163
  /**
@@ -567,7 +582,7 @@ export interface ObserveOptions {
567
582
  getUserId?: (call: any) => string;
568
583
  };
569
584
  /**
570
- * Spans for what leaves the process: database queries (`pg`, `mysql2`,
585
+ * Spans for what leaves the process: database queries (`pg`, `mysql2`, `mssql`,
571
586
  * `mongodb` - and so every ORM built on them) and outbound HTTP requests
572
587
  * (`fetch`/undici and `node:http`, so axios too). On by default; `false`
573
588
  * switches all of it off.
@@ -89,5 +89,18 @@ export interface RequestSnapshot {
89
89
  * operation id but not a document.
90
90
  */
91
91
  originalUrl?: string;
92
+ /**
93
+ * The operation id a request had before `TracerService.setOperationId`
94
+ * renamed it: its route, its GraphQL root field, its message pattern.
95
+ * Present only on a renamed request. It tells the collector that the
96
+ * operation id is the application's own name, and what the request is
97
+ * grouped under without it.
98
+ *
99
+ * An attribute rather than a field of its own because the collector
100
+ * refuses a snapshot key it does not know but takes the attributes
101
+ * whole, so an agent sending it still reaches a collector that predates
102
+ * it.
103
+ */
104
+ defaultOperationId?: string;
92
105
  };
93
106
  }
@@ -27,6 +27,7 @@ export declare class ObjectivesRegistry implements OnModuleInit {
27
27
  private readonly byHandler;
28
28
  private readonly statedAt;
29
29
  private readonly refusedRoutes;
30
+ private readonly refusedRenamedHandlers;
30
31
  constructor(discoveryService: DiscoveryService, metadataScanner: MetadataScanner);
31
32
  onModuleInit(): void;
32
33
  /**
@@ -55,6 +55,7 @@ let ObjectivesRegistry = class ObjectivesRegistry {
55
55
  byHandler = new Map();
56
56
  statedAt = new Map();
57
57
  refusedRoutes = new Set();
58
+ refusedRenamedHandlers = new Set();
58
59
  constructor(discoveryService, metadataScanner) {
59
60
  this.discoveryService = discoveryService;
60
61
  this.metadataScanner = metadataScanner;
@@ -152,6 +153,17 @@ let ObjectivesRegistry = class ObjectivesRegistry {
152
153
  if (!handler) {
153
154
  return undefined;
154
155
  }
156
+ // A renamed request reports under the application's own name, and the
157
+ // collector keeps one SLO per handler: declared from requests named per
158
+ // call, that SLO would move to each new name in turn - the reason a
159
+ // handler mounted on several routes is refused at boot.
160
+ if (snapshot.attributes?.defaultOperationId !== undefined) {
161
+ if (!this.refusedRenamedHandlers.has(handler)) {
162
+ this.refusedRenamedHandlers.add(handler);
163
+ this.logger.warn(`@Objective on ${handler} not declared for requests renamed with setOperationId: an SLO watches one route, and each name is a route of its own.`);
164
+ }
165
+ return undefined;
166
+ }
155
167
  const declared = this.byHandler.get(handler);
156
168
  // Routed for one method: that one, whatever the request was - a HEAD
157
169
  // probe of a GET route is still the GET route.
@@ -0,0 +1,12 @@
1
+ import { OutgoingSpanRecorder } from "./outgoing-span.recorder.js";
2
+ interface MssqlModule {
3
+ Request?: {
4
+ prototype?: object;
5
+ };
6
+ }
7
+ /**
8
+ * These internal boundaries follow template expansion and precede pool
9
+ * checkout. The tedious driver's `_batch` delegates to `_query`.
10
+ */
11
+ export declare function patchMssql(mssql: MssqlModule, recorder: OutgoingSpanRecorder): boolean;
12
+ export {};
@@ -0,0 +1,248 @@
1
+ import { errorMonitor } from "node:events";
2
+ import { patchMethod } from "./patch-method.util.js";
3
+ import { describeSanitizedSqlStatement, } from "./sql-statement.util.js";
4
+ /**
5
+ * The procedures a `PreparedStatement` calls on requests of its own: the
6
+ * driver parents those requests to the statement and executes these by name.
7
+ */
8
+ const PREPARED_STATEMENT_PROCEDURES = new Set([
9
+ "sp_prepare",
10
+ "sp_execute",
11
+ "sp_unprepare",
12
+ ]);
13
+ function describeMssqlStatement(sql, enableQuotedIdentifier, redactExecArgs = true) {
14
+ const input = sql.slice(0, 8192);
15
+ const truncated = sql.length > input.length;
16
+ let text = "";
17
+ // T-SQL escapes quotes by doubling them, not with backslashes. Tokenizing
18
+ // first keeps comment markers inside strings and identifiers inert.
19
+ // Double quotes follow connection options; SQL SET overrides are not tracked.
20
+ // Binary literals may continue across lines after a backslash.
21
+ const tokenPattern = /(?<comment>--[^\r\n]*)|\[(?:[^\]]|\]\])*(?:\]|$)|(?<quoted>"(?:[^"]|"")*(?:"|$))|(?<literal>N?'(?:[^']|'')*(?:'|$)|(?<![\w@])\$\s*[+-]?(?:\d+(?:\.\d*)?|\.\d+)|\b0x[\da-f]*(?:\\(?:\r\n|\r|\n)[\da-f]*)*|(?<![\w$@])-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?(?![\w]))|[^]/giy;
22
+ for (let index = 0; index < input.length;) {
23
+ if (input.startsWith("/*", index)) {
24
+ let depth = 1;
25
+ index += 2;
26
+ while (index < input.length && depth) {
27
+ if (input.startsWith("/*", index)) {
28
+ depth++;
29
+ index += 2;
30
+ }
31
+ else if (input.startsWith("*/", index)) {
32
+ depth--;
33
+ index += 2;
34
+ }
35
+ else {
36
+ index++;
37
+ }
38
+ }
39
+ text += " ";
40
+ continue;
41
+ }
42
+ tokenPattern.lastIndex = index;
43
+ const token = tokenPattern.exec(input);
44
+ index = tokenPattern.lastIndex;
45
+ if (token.groups?.comment !== undefined) {
46
+ text += " ";
47
+ }
48
+ else if (token.groups?.literal !== undefined ||
49
+ (!enableQuotedIdentifier && token.groups?.quoted !== undefined)) {
50
+ text += "?";
51
+ }
52
+ else {
53
+ text += token[0];
54
+ }
55
+ }
56
+ if (truncated) {
57
+ // Anchored at the run's start. Unanchored, the engine tried every position
58
+ // inside each run of word characters and backtracked the run each time:
59
+ // quadratic, 0.1 s of a blocked event loop for one 8 KB name. The sign is
60
+ // a number cut between its exponent's sign and digits, `987654e+`, which
61
+ // the tokenizer could not read as a number and left as text.
62
+ text = text.replace(/(^|[^\p{L}\p{M}\p{N}_$@#])[\p{L}\p{M}\p{N}_$@#]+[+-]?$/u, "$1?");
63
+ }
64
+ // `;WITH` is how T-SQL is often written, to end whatever came before.
65
+ text = text.replace(/^[\s;]+/, "");
66
+ if (!CAPTURED_STATEMENT.test(text)) {
67
+ const verb = /^[\s(]*([A-Za-z]+)/.exec(text)?.[1]?.toUpperCase();
68
+ return { operation: verb ?? "QUERY" };
69
+ }
70
+ return nameProcedureCall(describeSanitizedSqlStatement(redactExecArgs ? redactExecArguments(text) : text));
71
+ }
72
+ /**
73
+ * Names a procedure call after its procedure, `EXEC dbo.GetOrders`, with
74
+ * quotes and brackets dropped as from a table name - the same row whether it
75
+ * came through `execute()` or an `EXEC` batch, and a row per procedure rather
76
+ * than one `EXEC` for all of them.
77
+ */
78
+ function nameProcedureCall(description) {
79
+ const exec = /^EXEC(?:UTE)?(?=\s|$)/i.exec(description.statement);
80
+ if (!exec) {
81
+ return description;
82
+ }
83
+ const name = EXEC_TARGET.exec(description.statement.slice(exec[0].length))?.[1]
84
+ .replace(/\s*\.\s*/g, ".")
85
+ .replace(/["[\]]/g, "");
86
+ return {
87
+ ...description,
88
+ operation: (name ? `EXEC ${name}` : "EXEC").slice(0, 64),
89
+ };
90
+ }
91
+ /**
92
+ * A batch may open with a procedure call without EXEC, and its unquoted
93
+ * arguments look like keywords. Statement text is kept only for batches
94
+ * opening with a reserved word that starts a statement: a reserved word cannot
95
+ * name a procedure unquoted, so such a batch is never a call in disguise.
96
+ * Non-reserved statement words (`THROW`, `RECEIVE`, `SEND`) can, and are left
97
+ * out.
98
+ */
99
+ const CAPTURED_STATEMENT = /^[\s(]*(?:SELECT|INSERT|UPDATE|DELETE|MERGE|WITH|EXEC|EXECUTE|SET|DECLARE|IF|WHILE|BEGIN|COMMIT|ROLLBACK|SAVE|TRUNCATE|CREATE|ALTER|DROP|USE|PRINT|RAISERROR|WAITFOR|GRANT|REVOKE|DENY|RETURN|OPEN|CLOSE|FETCH|DEALLOCATE|BREAK|CONTINUE|GOTO|KILL|DBCC|BACKUP|RESTORE|CHECKPOINT|RECONFIGURE|BULK|SETUSER|REVERT|SHUTDOWN|READTEXT|WRITETEXT|UPDATETEXT)(?![\p{L}\p{M}\p{N}\p{Pc}@$#])/iu;
100
+ /**
101
+ * What follows `EXEC`: an optional `@status =`, then the procedure's dotted
102
+ * name, each part bracketed, double-quoted or bare.
103
+ */
104
+ const EXEC_TARGET = /^\s+(?:@[\p{L}_][\p{L}\p{M}\p{N}\p{Pc}@$#]*\s*=\s*)?((?:\[(?:[^\]]|\]\])*\]|"(?:[^"]|"")*"|[\p{L}_@#][\p{L}\p{M}\p{N}\p{Pc}@$#]*)(?:\s*\.\s*(?:\[(?:[^\]]|\]\])*\]|"(?:[^"]|"")*"|[\p{L}_@#][\p{L}\p{M}\p{N}\p{Pc}@$#]*))*)/u;
105
+ function findExec(source, start) {
106
+ for (let index = start; index < source.length;) {
107
+ if (source[index] === "[" || source[index] === '"') {
108
+ const opening = source[index];
109
+ const closing = opening === "[" ? "]" : '"';
110
+ index++;
111
+ while (index < source.length) {
112
+ if (source[index] === closing) {
113
+ if (source[index + 1] === closing) {
114
+ index += 2;
115
+ continue;
116
+ }
117
+ index++;
118
+ break;
119
+ }
120
+ index++;
121
+ }
122
+ continue;
123
+ }
124
+ const match = /^EXEC(?:UTE)?\b/i.exec(source.slice(index));
125
+ if (match &&
126
+ (index === 0 || !/[\w@$#]/.test(source[index - 1])) &&
127
+ !/[\w@$#]/.test(source[index + match[0].length] ?? "")) {
128
+ return { index, length: match[0].length };
129
+ }
130
+ index++;
131
+ }
132
+ return undefined;
133
+ }
134
+ function redactExecArguments(sql) {
135
+ let text = sql;
136
+ let searchFrom = 0;
137
+ while (searchFrom < text.length) {
138
+ const exec = findExec(text, searchFrom);
139
+ if (!exec) {
140
+ break;
141
+ }
142
+ let end = exec.index + exec.length;
143
+ let inBracket = false;
144
+ let inQuotedIdentifier = false;
145
+ while (end < text.length) {
146
+ if (inBracket) {
147
+ if (text[end] === "]" && text[end + 1] === "]") {
148
+ end += 2;
149
+ continue;
150
+ }
151
+ if (text[end] === "]")
152
+ inBracket = false;
153
+ }
154
+ else if (inQuotedIdentifier) {
155
+ if (text[end] === '"' && text[end + 1] === '"') {
156
+ end += 2;
157
+ continue;
158
+ }
159
+ if (text[end] === '"')
160
+ inQuotedIdentifier = false;
161
+ }
162
+ else if (text[end] === "[") {
163
+ inBracket = true;
164
+ }
165
+ else if (text[end] === '"') {
166
+ inQuotedIdentifier = true;
167
+ }
168
+ else if (text[end] === ";") {
169
+ break;
170
+ }
171
+ end++;
172
+ }
173
+ const tail = text.slice(exec.index + exec.length, end);
174
+ const procedure = EXEC_TARGET.exec(tail)?.[0] ?? "";
175
+ // Only what follows the procedure is an argument: `EXEC dbo.Refresh`
176
+ // has none to replace.
177
+ if (tail.slice(procedure.length).trim()) {
178
+ const prefix = text.slice(exec.index, exec.index + exec.length + procedure.length);
179
+ text = `${text.slice(0, exec.index)}${prefix} ?${text.slice(end)}`;
180
+ searchFrom = exec.index + prefix.length + 2;
181
+ }
182
+ else {
183
+ searchFrom = end + 1;
184
+ }
185
+ }
186
+ return text;
187
+ }
188
+ /**
189
+ * These internal boundaries follow template expansion and precede pool
190
+ * checkout. The tedious driver's `_batch` delegates to `_query`.
191
+ */
192
+ export function patchMssql(mssql, recorder) {
193
+ const wrap = (method) => (original) => function (...args) {
194
+ const [command, callback] = args;
195
+ // Asked first: describing a statement means tokenizing it, which an
196
+ // untraced or sampled-out call should not pay for.
197
+ if (typeof command !== "string" ||
198
+ typeof callback !== "function" ||
199
+ !recorder.isRecording()) {
200
+ return original.apply(this, args);
201
+ }
202
+ let sql = command;
203
+ let procedure = method === "_execute";
204
+ if (procedure &&
205
+ typeof this.parent?.unprepare === "function" &&
206
+ PREPARED_STATEMENT_PROCEDURES.has(command)) {
207
+ // Preparing and unpreparing are the statement's bookkeeping, and
208
+ // `sp_execute` would name every prepared statement alike: the span is
209
+ // the statement it executes, described like any other query.
210
+ const prepared = this.parent.statement;
211
+ if (command !== "sp_execute" || typeof prepared !== "string") {
212
+ return original.apply(this, args);
213
+ }
214
+ sql = prepared;
215
+ procedure = false;
216
+ }
217
+ const { operation, statement } = describeMssqlStatement(procedure ? `EXEC ${sql}` : sql, this.parent?.config?.options?.enableQuotedIdentifier !== false, !procedure);
218
+ const span = recorder.open("mssql", operation, statement === undefined
219
+ ? { "db.system": "mssql" }
220
+ : { "db.system": "mssql", "db.statement": statement });
221
+ if (!span) {
222
+ return original.apply(this, args);
223
+ }
224
+ let streamError;
225
+ const onError = (error) => {
226
+ streamError ??= error;
227
+ };
228
+ // Observe streaming errors without swallowing unhandled error events.
229
+ this.on(errorMonitor, onError);
230
+ const finish = (error) => {
231
+ this.removeListener(errorMonitor, onError);
232
+ span.end(error ?? streamError);
233
+ };
234
+ args[1] = function (error, ...rest) {
235
+ finish(error);
236
+ return callback.call(this, error, ...rest);
237
+ };
238
+ try {
239
+ return original.apply(this, args);
240
+ }
241
+ catch (error) {
242
+ finish(error);
243
+ throw error;
244
+ }
245
+ };
246
+ const patched = ["_query", "_execute"].map((method) => patchMethod(mssql.Request?.prototype, method, wrap(method)));
247
+ return patched.some(Boolean);
248
+ }
@@ -21,7 +21,7 @@ export function patchMysql2(mysql2, recorder) {
21
21
  if (typeof sql !== "string") {
22
22
  return original.apply(this, args);
23
23
  }
24
- const { operation, statement } = describeSqlStatement(sql);
24
+ const { operation, statement } = describeSqlStatement(sql, "mysql");
25
25
  const span = recorder.open("mysql2", operation, {
26
26
  "db.system": "mysql",
27
27
  "db.statement": statement,