@nestjs/observe 0.3.2 → 0.3.4

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.
@@ -79,12 +79,15 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
79
79
  return result.module;
80
80
  }
81
81
  registerRpcHooks(target) {
82
+ // Return `done()`'s promise, as Nest's default hook does. Nest's servers
83
+ // hand it back from their message handlers: kafkajs waits on it to commit
84
+ // the offset or retry the message, and recent Nest versions log its
85
+ // rejection for most other transports.
82
86
  target.setOnProcessingStartHook((transportId, ctx, done) => {
83
87
  if (transportId === this.microservices.Transport.GRPC) {
84
- this.startGrpcRequestTracing(transportId, ctx, done);
85
- return;
88
+ return this.startGrpcRequestTracing(transportId, ctx, done);
86
89
  }
87
- this.startRpcRequestTracing(transportId, ctx, done);
90
+ return this.startRpcRequestTracing(transportId, ctx, done);
88
91
  });
89
92
  target.setOnProcessingEndHook((transportId, ctx) => {
90
93
  this.endRpcRequestTracing(transportId, ctx);
@@ -106,7 +109,7 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
106
109
  // The same map `run` is given, rather than `getStore()` inside the callback:
107
110
  // identical object, one lookup fewer, and it is known to exist.
108
111
  const store = new Map();
109
- this.asyncLocalStorage.run(store, () => {
112
+ return this.asyncLocalStorage.run(store, () => {
110
113
  const traceId = this.options.traceIdGenerator(ctx);
111
114
  store.set(this.options.traceIdKey, traceId);
112
115
  if (this.options.rpc?.setAttributes) {
@@ -133,14 +136,14 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
133
136
  operationId: this.getOperationIdFromContext(ctx),
134
137
  tags: this.options.rpc?.tags,
135
138
  });
136
- done();
139
+ return done();
137
140
  // });
138
141
  });
139
142
  }
140
143
  startGrpcRequestTracing(transportId, call, done) {
141
144
  // As above: the map `run` is given, not looked back up.
142
145
  const store = new Map();
143
- this.asyncLocalStorage.run(store, () => {
146
+ return this.asyncLocalStorage.run(store, () => {
144
147
  const traceId = this.options.traceIdGenerator(call);
145
148
  store.set(this.options.traceIdKey, traceId);
146
149
  if (this.options.grpc?.setAttributes) {
@@ -151,23 +154,25 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
151
154
  }
152
155
  }
153
156
  }
154
- setTimeout(() => {
155
- if (this.options.grpc?.ignore?.(call)) {
156
- return done();
157
- }
158
- const shouldCapture = this.traceSamplerService.shouldCapture("grpc", {
159
- call,
160
- });
161
- if (!shouldCapture) {
162
- return done();
163
- }
164
- this.operationTraceRegistry.startTrace(traceId, {
165
- protocol: this.toProtocolName(transportId),
166
- operationId: call.operationId,
167
- tags: this.options.grpc?.tags,
168
- });
169
- done();
170
- }, 0);
157
+ return new Promise((resolve) => {
158
+ setTimeout(() => {
159
+ if (this.options.grpc?.ignore?.(call)) {
160
+ return resolve(done());
161
+ }
162
+ const shouldCapture = this.traceSamplerService.shouldCapture("grpc", {
163
+ call,
164
+ });
165
+ if (!shouldCapture) {
166
+ return resolve(done());
167
+ }
168
+ this.operationTraceRegistry.startTrace(traceId, {
169
+ protocol: this.toProtocolName(transportId),
170
+ operationId: call.operationId,
171
+ tags: this.options.grpc?.tags,
172
+ });
173
+ resolve(done());
174
+ }, 0);
175
+ });
171
176
  });
172
177
  }
173
178
  endRpcRequestTracing(transportId, ctx) {
@@ -9,6 +9,7 @@ import { KeyOf } from "../types/key-of.type.js";
9
9
  import { LogRedactor } from "../utils/log-redactor.js";
10
10
  import { CALLER_METADATA_KEY } from "../observe.constants.js";
11
11
  import { SpanCollapseSettings } from "./collapse-repeated-spans.util.js";
12
+ import { SkipSpansPredicate } from "./skip-spans.util.js";
12
13
  type TraceId = string;
13
14
  export declare class OperationTraceRegistry {
14
15
  private readonly als;
@@ -28,6 +29,15 @@ export declare class OperationTraceRegistry {
28
29
  * registry the module has not (yet) configured still bounds what it ships.
29
30
  */
30
31
  private spanCollapse;
32
+ /**
33
+ * `skipSpans`, resolved. Undefined - the default - ships every tree.
34
+ */
35
+ private skipSpans;
36
+ /**
37
+ * A `skipSpans` function that throws does so on every request, so the
38
+ * failure is reported once rather than once per request.
39
+ */
40
+ private hasReportedSkipSpansFailure;
31
41
  /**
32
42
  * Scrubs error messages and stacks before they are attached to a span.
33
43
  *
@@ -49,6 +59,12 @@ export declare class OperationTraceRegistry {
49
59
  * before the DI container so the instrumentation hook can hold it.
50
60
  */
51
61
  configureSpanCollapse(settings: SpanCollapseSettings | undefined): void;
62
+ /**
63
+ * Sets which finished operations ship without their spans, or none with
64
+ * `undefined`. Called by the module alongside `configureSpanCollapse`, for
65
+ * the same reason.
66
+ */
67
+ configureSkipSpans(predicate: SkipSpansPredicate | undefined): void;
52
68
  /**
53
69
  * Applies the resolved `redaction` options to error payloads, or switches
54
70
  * redaction off with `null`. Called by the module alongside
@@ -161,6 +177,15 @@ export declare class OperationTraceRegistry {
161
177
  */
162
178
  abandonTrace(traceId: TraceId): void;
163
179
  pluckSnapshot(traceId: string): Promise<RequestSnapshot | JobSnapshot | undefined>;
180
+ /**
181
+ * Whether `skipSpans` claims a finished operation. Only request snapshots
182
+ * are asked: a job has no status to be judged by.
183
+ *
184
+ * Asked once the snapshot is complete, so the rule sees the status and the
185
+ * error the operation is reported with. A rule that throws keeps the spans:
186
+ * a mistake in it must not cost the application its traces.
187
+ */
188
+ private shouldSkipSpans;
164
189
  getActiveSpan(traceId: string, callerId: string | undefined): OngoingTraceEventNode | undefined;
165
190
  createManualSpan(traceId: string, callerId: string | undefined, name: string, spanFunction: (span: TraceSpanDelegate) => any): Promise<any>;
166
191
  }
@@ -38,6 +38,15 @@ export class OperationTraceRegistry {
38
38
  * registry the module has not (yet) configured still bounds what it ships.
39
39
  */
40
40
  spanCollapse = DEFAULT_SPAN_COLLAPSE;
41
+ /**
42
+ * `skipSpans`, resolved. Undefined - the default - ships every tree.
43
+ */
44
+ skipSpans;
45
+ /**
46
+ * A `skipSpans` function that throws does so on every request, so the
47
+ * failure is reported once rather than once per request.
48
+ */
49
+ hasReportedSkipSpansFailure = false;
41
50
  /**
42
51
  * Scrubs error messages and stacks before they are attached to a span.
43
52
  *
@@ -62,6 +71,14 @@ export class OperationTraceRegistry {
62
71
  configureSpanCollapse(settings) {
63
72
  this.spanCollapse = settings;
64
73
  }
74
+ /**
75
+ * Sets which finished operations ship without their spans, or none with
76
+ * `undefined`. Called by the module alongside `configureSpanCollapse`, for
77
+ * the same reason.
78
+ */
79
+ configureSkipSpans(predicate) {
80
+ this.skipSpans = predicate;
81
+ }
65
82
  /**
66
83
  * Applies the resolved `redaction` options to error payloads, or switches
67
84
  * redaction off with `null`. Called by the module alongside
@@ -511,6 +528,13 @@ export class OperationTraceRegistry {
511
528
  delete bookkeeping.refsCounter;
512
529
  delete bookkeeping.refsMarkedAsComplete;
513
530
  delete bookkeeping.errorStatusCode;
531
+ // Emptied rather than removed: the collector requires the field, and an
532
+ // empty tree is what it already stores for a trace it sampled out - the
533
+ // operation keeps its row, its error and every chart it feeds.
534
+ if (this.shouldSkipSpans(snapshot)) {
535
+ snapshot.traces = [];
536
+ return snapshot;
537
+ }
514
538
  // Last, on the finished tree: every span has closed by now, so a group
515
539
  // is judged on its complete membership and durations, and nothing that
516
540
  // reads the tree afterwards - the encoder, the buffer - sees the
@@ -522,6 +546,36 @@ export class OperationTraceRegistry {
522
546
  }
523
547
  return undefined;
524
548
  }
549
+ /**
550
+ * Whether `skipSpans` claims a finished operation. Only request snapshots
551
+ * are asked: a job has no status to be judged by.
552
+ *
553
+ * Asked once the snapshot is complete, so the rule sees the status and the
554
+ * error the operation is reported with. A rule that throws keeps the spans:
555
+ * a mistake in it must not cost the application its traces.
556
+ */
557
+ shouldSkipSpans(snapshot) {
558
+ if (!this.skipSpans || !("protocol" in snapshot)) {
559
+ return false;
560
+ }
561
+ try {
562
+ return this.skipSpans({
563
+ protocol: snapshot.protocol,
564
+ operationId: snapshot.operationId,
565
+ method: snapshot.attributes?.method,
566
+ statusCode: snapshot.attributes?.statusCode,
567
+ duration: snapshot.duration ?? 0,
568
+ errorClass: snapshot.error?.cls,
569
+ });
570
+ }
571
+ catch (error) {
572
+ if (!this.hasReportedSkipSpansFailure) {
573
+ this.hasReportedSkipSpansFailure = true;
574
+ this.logger.warn(`"skipSpans" threw for "${snapshot.operationId ?? snapshot.protocol}"; keeping its spans. Later failures are not reported: ${error instanceof Error ? error.message : String(error)}`);
575
+ }
576
+ return false;
577
+ }
578
+ }
525
579
  getActiveSpan(traceId, callerId) {
526
580
  const refsByCaller = this.callerIdsByTraceId.get(traceId);
527
581
  if (!refsByCaller) {
@@ -0,0 +1,14 @@
1
+ import { ObserveOptions, SkipSpansContext } from "../interfaces/observe-options.interface.js";
2
+ /** Resolved form of `ObserveOptions.skipSpans`. */
3
+ export type SkipSpansPredicate = (operation: SkipSpansContext) => boolean;
4
+ /**
5
+ * Turns the user-facing option into the one predicate the registry asks, or
6
+ * `undefined` when nothing is to be skipped - so an application that never
7
+ * set it pays one falsy check per operation and builds no context object.
8
+ *
9
+ * A list matches on the status code alone, by strict equality: a status never
10
+ * reaches the registry as a string, so `"404"` in the list can only be a
11
+ * mistake, and a list that coerced its way into skipping more than it names
12
+ * would be the worse one to get wrong.
13
+ */
14
+ export declare function resolveSkipSpans(option: ObserveOptions["skipSpans"]): SkipSpansPredicate | undefined;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Turns the user-facing option into the one predicate the registry asks, or
3
+ * `undefined` when nothing is to be skipped - so an application that never
4
+ * set it pays one falsy check per operation and builds no context object.
5
+ *
6
+ * A list matches on the status code alone, by strict equality: a status never
7
+ * reaches the registry as a string, so `"404"` in the list can only be a
8
+ * mistake, and a list that coerced its way into skipping more than it names
9
+ * would be the worse one to get wrong.
10
+ */
11
+ export function resolveSkipSpans(option) {
12
+ if (typeof option === "function") {
13
+ return option;
14
+ }
15
+ if (!Array.isArray(option) || option.length === 0) {
16
+ return undefined;
17
+ }
18
+ const statusCodes = new Set(option);
19
+ return ({ statusCode }) => statusCode !== undefined && statusCodes.has(statusCode);
20
+ }
@@ -0,0 +1,15 @@
1
+ /** A release found without the application naming one. */
2
+ export interface InferredServiceVersion {
3
+ version: string;
4
+ /** The environment variable it was read from, or the git directory. */
5
+ source: string;
6
+ }
7
+ /**
8
+ * The release this process is running, for an application that did not set
9
+ * `serviceVersion`: from the environment first, then from the git checkout
10
+ * the process runs in, then from a container platform's revision name.
11
+ *
12
+ * Never throws - an unreadable file is a release that could not be inferred,
13
+ * not a reason to keep the application from booting.
14
+ */
15
+ export declare function inferServiceVersion(env?: NodeJS.ProcessEnv, searchFrom?: (string | undefined)[]): InferredServiceVersion | undefined;
@@ -0,0 +1,185 @@
1
+ import { readFileSync, statSync } from "fs";
2
+ import { dirname, join, resolve } from "path";
3
+ /**
4
+ * Environment variables that name the running release, in the order they are
5
+ * trusted.
6
+ *
7
+ * `OBSERVE_SERVICE_VERSION` first: the SDK's own name for it, for a deploy
8
+ * that wants to be explicit without touching code - a container image built
9
+ * with `ENV OBSERVE_SERVICE_VERSION=$GIT_SHA`, say. Then the commit that
10
+ * platforms deploying from git expose at runtime, then the one CI providers
11
+ * set for the length of a job, which is how an application booted by an e2e
12
+ * run reports the commit under test. Last, the names teams tend to pick when
13
+ * they set one themselves.
14
+ */
15
+ const VERSION_ENV_VARS = [
16
+ "OBSERVE_SERVICE_VERSION",
17
+ // Platforms, at runtime.
18
+ "VERCEL_GIT_COMMIT_SHA",
19
+ "RENDER_GIT_COMMIT",
20
+ "RAILWAY_GIT_COMMIT_SHA",
21
+ "HEROKU_BUILD_COMMIT",
22
+ "HEROKU_SLUG_COMMIT",
23
+ "SOURCE_COMMIT", // Coolify
24
+ "GIT_REV", // Dokku
25
+ // CI, for the length of a job.
26
+ "GITHUB_SHA",
27
+ "CI_COMMIT_SHA", // GitLab
28
+ "BITBUCKET_COMMIT",
29
+ "CIRCLE_SHA1",
30
+ "BUILDKITE_COMMIT",
31
+ "BUILD_SOURCEVERSION", // Azure Pipelines
32
+ "CODEBUILD_RESOLVED_SOURCE_VERSION",
33
+ // Conventions.
34
+ "GIT_COMMIT_SHA",
35
+ "GIT_COMMIT", // Jenkins, among others
36
+ "GIT_SHA",
37
+ "COMMIT_SHA",
38
+ "SOURCE_VERSION",
39
+ ];
40
+ /**
41
+ * What container platforms call each deploy. Not commits - nothing in the
42
+ * code maps back to one - but each changes on every deploy and is shared by
43
+ * all of that deploy's replicas, which is all a release boundary needs. Only
44
+ * consulted once no commit turned up anywhere.
45
+ */
46
+ const REVISION_ENV_VARS = [
47
+ "K_REVISION", // Cloud Run
48
+ "CONTAINER_APP_REVISION", // Azure Container Apps
49
+ ];
50
+ /**
51
+ * The longest version the collector accepts. A longer one is not truncated
52
+ * there - the whole batch it rides in is refused - so an inferred version is
53
+ * cut to fit before it is ever sent: from the end for a commit, whose head is
54
+ * what identifies it, and from the start for a revision, whose head is the
55
+ * service's name that every revision shares.
56
+ */
57
+ const MAX_VERSION_LENGTH = 50;
58
+ /** A full commit id: SHA-1, or SHA-256 in a repository created with it. */
59
+ const COMMIT_ID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
60
+ /**
61
+ * The release this process is running, for an application that did not set
62
+ * `serviceVersion`: from the environment first, then from the git checkout
63
+ * the process runs in, then from a container platform's revision name.
64
+ *
65
+ * Never throws - an unreadable file is a release that could not be inferred,
66
+ * not a reason to keep the application from booting.
67
+ */
68
+ export function inferServiceVersion(env = process.env, searchFrom = defaultSearchDirectories()) {
69
+ for (const name of VERSION_ENV_VARS) {
70
+ const value = env[name]?.trim();
71
+ if (value) {
72
+ return { version: value.slice(0, MAX_VERSION_LENGTH), source: name };
73
+ }
74
+ }
75
+ for (const directory of searchFrom) {
76
+ const checkout = directory && readCheckoutHead(directory);
77
+ if (checkout) {
78
+ return checkout;
79
+ }
80
+ }
81
+ for (const name of REVISION_ENV_VARS) {
82
+ const value = env[name]?.trim();
83
+ if (value) {
84
+ return { version: value.slice(-MAX_VERSION_LENGTH), source: name };
85
+ }
86
+ }
87
+ return undefined;
88
+ }
89
+ /**
90
+ * The working directory, then the entry script's directory: a process
91
+ * started by a supervisor can have a working directory nowhere near its code.
92
+ */
93
+ function defaultSearchDirectories() {
94
+ const entry = process.argv[1];
95
+ return [process.cwd(), entry ? dirname(entry) : undefined];
96
+ }
97
+ /**
98
+ * The commit checked out in the repository `start` sits in, found by walking
99
+ * up the way git itself does. Read from the files rather than by running git,
100
+ * which a production image rarely has.
101
+ *
102
+ * The first `.git` found settles it: a repository whose HEAD cannot be read -
103
+ * one with no commits yet - does not hand the question to a repository that
104
+ * happens to enclose it.
105
+ */
106
+ function readCheckoutHead(start) {
107
+ let directory = resolve(start);
108
+ for (;;) {
109
+ const gitDir = resolveGitDir(join(directory, ".git"));
110
+ if (gitDir) {
111
+ const commit = readHeadCommit(gitDir);
112
+ return commit
113
+ ? { version: commit.slice(0, MAX_VERSION_LENGTH), source: gitDir }
114
+ : undefined;
115
+ }
116
+ const parent = dirname(directory);
117
+ if (parent === directory) {
118
+ return undefined;
119
+ }
120
+ directory = parent;
121
+ }
122
+ }
123
+ /**
124
+ * `.git` is a directory in an ordinary clone, and a file holding
125
+ * `gitdir: <path>` in a worktree or a submodule.
126
+ */
127
+ function resolveGitDir(dotGit) {
128
+ try {
129
+ const stats = statSync(dotGit, { throwIfNoEntry: false });
130
+ if (!stats) {
131
+ return undefined;
132
+ }
133
+ if (stats.isDirectory()) {
134
+ return dotGit;
135
+ }
136
+ const pointer = /^gitdir:\s*(.+)$/m.exec(readFileSync(dotGit, "utf8"));
137
+ return pointer ? resolve(dirname(dotGit), pointer[1].trim()) : undefined;
138
+ }
139
+ catch {
140
+ return undefined;
141
+ }
142
+ }
143
+ function readHeadCommit(gitDir) {
144
+ const head = readText(join(gitDir, "HEAD"));
145
+ if (!head) {
146
+ return undefined;
147
+ }
148
+ // Detached: HEAD is the commit itself.
149
+ if (COMMIT_ID.test(head)) {
150
+ return head;
151
+ }
152
+ const ref = /^ref:\s*(\S+)$/.exec(head)?.[1];
153
+ if (!ref) {
154
+ return undefined;
155
+ }
156
+ // A worktree keeps its own HEAD but shares branches with the repository
157
+ // `commondir` points at.
158
+ const commonDir = readText(join(gitDir, "commondir"));
159
+ const refDirs = commonDir ? [gitDir, resolve(gitDir, commonDir)] : [gitDir];
160
+ for (const refDir of refDirs) {
161
+ const loose = readText(join(refDir, ref));
162
+ if (loose && COMMIT_ID.test(loose)) {
163
+ return loose;
164
+ }
165
+ }
166
+ // A branch untouched since the last `git gc` exists only in packed-refs.
167
+ for (const refDir of refDirs) {
168
+ const packed = readText(join(refDir, "packed-refs"));
169
+ for (const line of packed?.split(/\r?\n/) ?? []) {
170
+ const [commit, name] = line.split(" ");
171
+ if (name === ref && COMMIT_ID.test(commit)) {
172
+ return commit;
173
+ }
174
+ }
175
+ }
176
+ return undefined;
177
+ }
178
+ function readText(file) {
179
+ try {
180
+ return readFileSync(file, "utf8").trim();
181
+ }
182
+ catch {
183
+ return undefined;
184
+ }
185
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nestjs/observe",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
4
4
  "description": "Observability and APM agent for NestJS - traces, runtime metrics, custom metrics and CPU profiles",
5
5
  "author": "Kamil Mysliwiec",
6
6
  "homepage": "https://observe.nestjs.com",
@@ -78,6 +78,7 @@
78
78
  "@nestjs/microservices": "^11.0.0 || ^12.0.0",
79
79
  "@nestjs/schedule": "^4.0.0 || ^5.0.0 || ^6.0.0 || ^12.0.0",
80
80
  "@nestjs/websockets": "^11.0.0 || ^12.0.0",
81
+ "@taskforcesh/bullmq-pro": "^7.0.0",
81
82
  "bull": "^3.3.0 || ^4.0.0",
82
83
  "bullmq": "^5.0.0 || ^6.0.0",
83
84
  "reflect-metadata": "^0.1.12 || ^0.2.0",
@@ -102,6 +103,9 @@
102
103
  "@nestjs/websockets": {
103
104
  "optional": true
104
105
  },
106
+ "@taskforcesh/bullmq-pro": {
107
+ "optional": true
108
+ },
105
109
  "bull": {
106
110
  "optional": true
107
111
  },