@nestjs/observe 0.3.3 → 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.
@@ -15,6 +15,7 @@ import { DiscoveryModule, DiscoveryService, HttpAdapterHost, MetadataScanner, Mo
15
15
  import { AsyncLocalStorage } from "async_hooks";
16
16
  import { ObserveAgentSharedBuffer } from "./agent/observe-agent.shared-buffer.js";
17
17
  import { ObserveAgentWorker } from "./agent/observe-agent.worker.js";
18
+ import { ObjectivesRegistry } from "./objectives/objectives.registry.js";
18
19
  import { createInstanceDecorator } from "./instrument/create-instance-decorator.instrument.js";
19
20
  import { CALLER_METADATA_KEY, OBSERVE_OPTIONS } from "./observe.constants.js";
20
21
  import { GraphQLObserveAgentService } from "./protocols/graphql-observe-agent.service.js";
@@ -35,6 +36,7 @@ import { TraceSamplerService } from "./services/trace-sampler.service.js";
35
36
  import { TracerService } from "./services/tracer.service.js";
36
37
  import { assertModuleOptions } from "./utils/assert-module-options.util.js";
37
38
  import { defaultTraceIdGenerator } from "./utils/default-trace-id-generator.util.js";
39
+ import { inferServiceVersion } from "./utils/infer-service-version.util.js";
38
40
  import { LogRedactor } from "./utils/log-redactor.js";
39
41
  /**
40
42
  * All three async providers are optional on the options type, but one of them
@@ -42,6 +44,24 @@ import { LogRedactor } from "./utils/log-redactor.js";
42
44
  * otherwise try to resolve, which fails much later with no mention of why.
43
45
  */
44
46
  const MISSING_ASYNC_OPTIONS_PROVIDER = 'ObserveModule.forRootAsync() requires one of "useFactory", "useClass" or "useExisting".';
47
+ /**
48
+ * Names the release when the application did not, so Releases, regressions
49
+ * and fix verification work without anyone threading a version through the
50
+ * build. Resolved once, with the rest of the options: the answer cannot change
51
+ * while the process runs. `serviceVersion: false` opts out.
52
+ */
53
+ function withServiceVersion(options) {
54
+ if (options.serviceVersion || options.serviceVersion === false) {
55
+ return options;
56
+ }
57
+ const inferred = inferServiceVersion();
58
+ if (options.debug) {
59
+ new Logger("ObserveModule").debug(inferred
60
+ ? `serviceVersion "${inferred.version}" inferred from ${inferred.source}.`
61
+ : "serviceVersion is not set and none could be inferred, so telemetry will carry no release.");
62
+ }
63
+ return inferred ? { ...options, serviceVersion: inferred.version } : options;
64
+ }
45
65
  export function createObserveModule(options = {}) {
46
66
  var ObserveModule_1;
47
67
  options.traceIdKey ??= "traceId";
@@ -67,10 +87,10 @@ export function createObserveModule(options = {}) {
67
87
  providers: [
68
88
  {
69
89
  provide: OBSERVE_OPTIONS,
70
- useValue: {
90
+ useValue: withServiceVersion({
71
91
  ...options,
72
92
  ...observeOpts,
73
- },
93
+ }),
74
94
  },
75
95
  ],
76
96
  };
@@ -109,10 +129,10 @@ export function createObserveModule(options = {}) {
109
129
  provide: OBSERVE_OPTIONS,
110
130
  useFactory: async (...args) => {
111
131
  const opts = await useFactory(...args);
112
- return {
132
+ return withServiceVersion({
113
133
  ...options,
114
134
  ...opts,
115
- };
135
+ });
116
136
  },
117
137
  inject: asyncOptions.inject || [],
118
138
  };
@@ -123,7 +143,7 @@ export function createObserveModule(options = {}) {
123
143
  }
124
144
  return {
125
145
  provide: OBSERVE_OPTIONS,
126
- useFactory: async (optionsFactory) => ({
146
+ useFactory: async (optionsFactory) => withServiceVersion({
127
147
  ...options,
128
148
  ...(await optionsFactory.createObserveOptions()),
129
149
  }),
@@ -171,6 +191,9 @@ export function createObserveModule(options = {}) {
171
191
  GraphQLObserveAgentService,
172
192
  ObserveAgentWorker,
173
193
  ObserveAgentSharedBuffer,
194
+ // Reads `@Objective` off the controllers at boot, for the buffer to
195
+ // pair with the routes their handlers serve.
196
+ ObjectivesRegistry,
174
197
  TraceSamplerService,
175
198
  NodeRuntimeMetricsService,
176
199
  // Registered unconditionally; the service itself is a no-op unless
@@ -203,6 +226,9 @@ export function createObserveModule(options = {}) {
203
226
  instance instanceof TraceSamplerService ||
204
227
  instance instanceof TracerService ||
205
228
  instance instanceof ObserveAgentSharedBuffer ||
229
+ // Consulted as each request's snapshot is buffered: agent bookkeeping,
230
+ // not application code.
231
+ instance instanceof ObjectivesRegistry ||
206
232
  // Its methods run *inside* the traces it opens, so instrumenting it
207
233
  // would put a span for the agent itself at the root of every GraphQL
208
234
  // operation it records.
@@ -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.3",
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",