@nestjs/observe 0.3.3 → 0.3.5

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,8 @@ 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 { fitServiceVersion, MAX_SERVICE_VERSION_LENGTH, } from "./utils/fit-service-version.util.js";
40
+ import { inferServiceVersion } from "./utils/infer-service-version.util.js";
38
41
  import { LogRedactor } from "./utils/log-redactor.js";
39
42
  /**
40
43
  * All three async providers are optional on the options type, but one of them
@@ -42,6 +45,33 @@ import { LogRedactor } from "./utils/log-redactor.js";
42
45
  * otherwise try to resolve, which fails much later with no mention of why.
43
46
  */
44
47
  const MISSING_ASYNC_OPTIONS_PROVIDER = 'ObserveModule.forRootAsync() requires one of "useFactory", "useClass" or "useExisting".';
48
+ /**
49
+ * Names the release when the application did not, so Releases, regressions
50
+ * and fix verification work without anyone threading a version through the
51
+ * build. Resolved once, with the rest of the options: the answer cannot change
52
+ * while the process runs. `serviceVersion: false` opts out.
53
+ *
54
+ * A release the application names is cut to what the collector accepts, as
55
+ * an inferred one is - sent whole, it would cost every batch it rides in.
56
+ */
57
+ function withServiceVersion(options) {
58
+ const named = options.serviceVersion;
59
+ if (typeof named === "string" && named.length > MAX_SERVICE_VERSION_LENGTH) {
60
+ const sent = fitServiceVersion(named);
61
+ new Logger("ObserveModule").warn(`serviceVersion "${named}" is sent as "${sent}": the collector takes at most ${MAX_SERVICE_VERSION_LENGTH} characters.`);
62
+ return { ...options, serviceVersion: sent };
63
+ }
64
+ if (named || named === false) {
65
+ return options;
66
+ }
67
+ const inferred = inferServiceVersion();
68
+ if (options.debug) {
69
+ new Logger("ObserveModule").debug(inferred
70
+ ? `serviceVersion "${inferred.version}" inferred from ${inferred.source}.`
71
+ : "serviceVersion is not set and none could be inferred, so telemetry will carry no release.");
72
+ }
73
+ return inferred ? { ...options, serviceVersion: inferred.version } : options;
74
+ }
45
75
  export function createObserveModule(options = {}) {
46
76
  var ObserveModule_1;
47
77
  options.traceIdKey ??= "traceId";
@@ -67,10 +97,10 @@ export function createObserveModule(options = {}) {
67
97
  providers: [
68
98
  {
69
99
  provide: OBSERVE_OPTIONS,
70
- useValue: {
100
+ useValue: withServiceVersion({
71
101
  ...options,
72
102
  ...observeOpts,
73
- },
103
+ }),
74
104
  },
75
105
  ],
76
106
  };
@@ -109,10 +139,10 @@ export function createObserveModule(options = {}) {
109
139
  provide: OBSERVE_OPTIONS,
110
140
  useFactory: async (...args) => {
111
141
  const opts = await useFactory(...args);
112
- return {
142
+ return withServiceVersion({
113
143
  ...options,
114
144
  ...opts,
115
- };
145
+ });
116
146
  },
117
147
  inject: asyncOptions.inject || [],
118
148
  };
@@ -123,7 +153,7 @@ export function createObserveModule(options = {}) {
123
153
  }
124
154
  return {
125
155
  provide: OBSERVE_OPTIONS,
126
- useFactory: async (optionsFactory) => ({
156
+ useFactory: async (optionsFactory) => withServiceVersion({
127
157
  ...options,
128
158
  ...(await optionsFactory.createObserveOptions()),
129
159
  }),
@@ -171,6 +201,9 @@ export function createObserveModule(options = {}) {
171
201
  GraphQLObserveAgentService,
172
202
  ObserveAgentWorker,
173
203
  ObserveAgentSharedBuffer,
204
+ // Reads `@Objective` off the controllers at boot, for the buffer to
205
+ // pair with the routes their handlers serve.
206
+ ObjectivesRegistry,
174
207
  TraceSamplerService,
175
208
  NodeRuntimeMetricsService,
176
209
  // Registered unconditionally; the service itself is a no-op unless
@@ -203,6 +236,9 @@ export function createObserveModule(options = {}) {
203
236
  instance instanceof TraceSamplerService ||
204
237
  instance instanceof TracerService ||
205
238
  instance instanceof ObserveAgentSharedBuffer ||
239
+ // Consulted as each request's snapshot is buffered: agent bookkeeping,
240
+ // not application code.
241
+ instance instanceof ObjectivesRegistry ||
206
242
  // Its methods run *inside* the traces it opens, so instrumenting it
207
243
  // would put a span for the agent itself at the root of every GraphQL
208
244
  // operation it records.
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The longest version the collector accepts. A longer one is not truncated
3
+ * there - the whole batch it rides in is refused - so a version is cut to fit
4
+ * before it is ever sent.
5
+ */
6
+ export declare const MAX_SERVICE_VERSION_LENGTH = 50;
7
+ /**
8
+ * `version`, at most as long as the collector accepts.
9
+ *
10
+ * A commit keeps its head, which is what identifies it - and what git and the
11
+ * dashboard shorten it to. Anything else keeps its head too, but ends in a
12
+ * hash of the whole after a `~`: the part each deploy changes can sit past the
13
+ * cut - the tag at the end of an image reference, say - and cut there, every
14
+ * release would arrive as the same one.
15
+ */
16
+ export declare function fitServiceVersion(version: string): string;
@@ -0,0 +1,32 @@
1
+ import { createHash } from "crypto";
2
+ /**
3
+ * The longest version the collector accepts. A longer one is not truncated
4
+ * there - the whole batch it rides in is refused - so a version is cut to fit
5
+ * before it is ever sent.
6
+ */
7
+ export const MAX_SERVICE_VERSION_LENGTH = 50;
8
+ /** How much of a cut version is a hash of the whole. */
9
+ const HASH_LENGTH = 8;
10
+ const HEX = /^[0-9a-f]+$/i;
11
+ /**
12
+ * `version`, at most as long as the collector accepts.
13
+ *
14
+ * A commit keeps its head, which is what identifies it - and what git and the
15
+ * dashboard shorten it to. Anything else keeps its head too, but ends in a
16
+ * hash of the whole after a `~`: the part each deploy changes can sit past the
17
+ * cut - the tag at the end of an image reference, say - and cut there, every
18
+ * release would arrive as the same one.
19
+ */
20
+ export function fitServiceVersion(version) {
21
+ if (version.length <= MAX_SERVICE_VERSION_LENGTH) {
22
+ return version;
23
+ }
24
+ if (HEX.test(version)) {
25
+ return version.slice(0, MAX_SERVICE_VERSION_LENGTH);
26
+ }
27
+ const hash = createHash("sha256")
28
+ .update(version)
29
+ .digest("hex")
30
+ .slice(0, HASH_LENGTH);
31
+ return `${version.slice(0, MAX_SERVICE_VERSION_LENGTH - HASH_LENGTH - 1)}~${hash}`;
32
+ }
@@ -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,183 @@
1
+ import { readFileSync, statSync } from "fs";
2
+ import { dirname, join, resolve } from "path";
3
+ import { fitServiceVersion, MAX_SERVICE_VERSION_LENGTH, } from "./fit-service-version.util.js";
4
+ /**
5
+ * Environment variables that name the running release, in the order they are
6
+ * trusted.
7
+ *
8
+ * `OBSERVE_SERVICE_VERSION` first: the SDK's own name for it, for a deploy
9
+ * that wants to be explicit without touching code - a container image built
10
+ * with `ENV OBSERVE_SERVICE_VERSION=$GIT_SHA`, say. Then the commit that
11
+ * platforms deploying from git expose at runtime, then the one CI providers
12
+ * set for the length of a job, which is how an application booted by an e2e
13
+ * run reports the commit under test. Last, the names teams tend to pick when
14
+ * they set one themselves.
15
+ */
16
+ const VERSION_ENV_VARS = [
17
+ "OBSERVE_SERVICE_VERSION",
18
+ // Platforms, at runtime.
19
+ "VERCEL_GIT_COMMIT_SHA",
20
+ "RENDER_GIT_COMMIT",
21
+ "RAILWAY_GIT_COMMIT_SHA",
22
+ "HEROKU_BUILD_COMMIT",
23
+ "HEROKU_SLUG_COMMIT",
24
+ "SOURCE_COMMIT", // Coolify
25
+ "GIT_REV", // Dokku
26
+ // CI, for the length of a job.
27
+ "GITHUB_SHA",
28
+ "CI_COMMIT_SHA", // GitLab
29
+ "BITBUCKET_COMMIT",
30
+ "CIRCLE_SHA1",
31
+ "BUILDKITE_COMMIT",
32
+ "BUILD_SOURCEVERSION", // Azure Pipelines
33
+ "CODEBUILD_RESOLVED_SOURCE_VERSION",
34
+ // Conventions.
35
+ "GIT_COMMIT_SHA",
36
+ "GIT_COMMIT", // Jenkins, among others
37
+ "GIT_SHA",
38
+ "COMMIT_SHA",
39
+ "SOURCE_VERSION",
40
+ ];
41
+ /**
42
+ * What container platforms call each deploy. Not commits - nothing in the
43
+ * code maps back to one - but each changes on every deploy and is shared by
44
+ * all of that deploy's replicas, which is all a release boundary needs. Only
45
+ * consulted once no commit turned up anywhere.
46
+ */
47
+ const REVISION_ENV_VARS = [
48
+ "K_REVISION", // Cloud Run
49
+ "CONTAINER_APP_REVISION", // Azure Container Apps
50
+ ];
51
+ /** A full commit id: SHA-1, or SHA-256 in a repository created with it. */
52
+ const COMMIT_ID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
53
+ /**
54
+ * The release this process is running, for an application that did not set
55
+ * `serviceVersion`: from the environment first, then from the git checkout
56
+ * the process runs in, then from a container platform's revision name.
57
+ *
58
+ * Never throws - an unreadable file is a release that could not be inferred,
59
+ * not a reason to keep the application from booting.
60
+ */
61
+ export function inferServiceVersion(env = process.env, searchFrom = defaultSearchDirectories()) {
62
+ for (const name of VERSION_ENV_VARS) {
63
+ const value = env[name]?.trim();
64
+ if (value) {
65
+ return { version: fitServiceVersion(value), source: name };
66
+ }
67
+ }
68
+ for (const directory of searchFrom) {
69
+ const checkout = directory && readCheckoutHead(directory);
70
+ if (checkout) {
71
+ return checkout;
72
+ }
73
+ }
74
+ for (const name of REVISION_ENV_VARS) {
75
+ const value = env[name]?.trim();
76
+ if (value) {
77
+ // Cut from the start: a revision's head is the service's name, which
78
+ // every revision shares, and its end is the part each deploy changes.
79
+ return {
80
+ version: value.slice(-MAX_SERVICE_VERSION_LENGTH),
81
+ source: name,
82
+ };
83
+ }
84
+ }
85
+ return undefined;
86
+ }
87
+ /**
88
+ * The working directory, then the entry script's directory: a process
89
+ * started by a supervisor can have a working directory nowhere near its code.
90
+ */
91
+ function defaultSearchDirectories() {
92
+ const entry = process.argv[1];
93
+ return [process.cwd(), entry ? dirname(entry) : undefined];
94
+ }
95
+ /**
96
+ * The commit checked out in the repository `start` sits in, found by walking
97
+ * up the way git itself does. Read from the files rather than by running git,
98
+ * which a production image rarely has.
99
+ *
100
+ * The first `.git` found settles it: a repository whose HEAD cannot be read -
101
+ * one with no commits yet - does not hand the question to a repository that
102
+ * happens to enclose it.
103
+ */
104
+ function readCheckoutHead(start) {
105
+ let directory = resolve(start);
106
+ for (;;) {
107
+ const gitDir = resolveGitDir(join(directory, ".git"));
108
+ if (gitDir) {
109
+ const commit = readHeadCommit(gitDir);
110
+ return commit
111
+ ? { version: fitServiceVersion(commit), source: gitDir }
112
+ : undefined;
113
+ }
114
+ const parent = dirname(directory);
115
+ if (parent === directory) {
116
+ return undefined;
117
+ }
118
+ directory = parent;
119
+ }
120
+ }
121
+ /**
122
+ * `.git` is a directory in an ordinary clone, and a file holding
123
+ * `gitdir: <path>` in a worktree or a submodule.
124
+ */
125
+ function resolveGitDir(dotGit) {
126
+ try {
127
+ const stats = statSync(dotGit, { throwIfNoEntry: false });
128
+ if (!stats) {
129
+ return undefined;
130
+ }
131
+ if (stats.isDirectory()) {
132
+ return dotGit;
133
+ }
134
+ const pointer = /^gitdir:\s*(.+)$/m.exec(readFileSync(dotGit, "utf8"));
135
+ return pointer ? resolve(dirname(dotGit), pointer[1].trim()) : undefined;
136
+ }
137
+ catch {
138
+ return undefined;
139
+ }
140
+ }
141
+ function readHeadCommit(gitDir) {
142
+ const head = readText(join(gitDir, "HEAD"));
143
+ if (!head) {
144
+ return undefined;
145
+ }
146
+ // Detached: HEAD is the commit itself.
147
+ if (COMMIT_ID.test(head)) {
148
+ return head;
149
+ }
150
+ const ref = /^ref:\s*(\S+)$/.exec(head)?.[1];
151
+ if (!ref) {
152
+ return undefined;
153
+ }
154
+ // A worktree keeps its own HEAD but shares branches with the repository
155
+ // `commondir` points at.
156
+ const commonDir = readText(join(gitDir, "commondir"));
157
+ const refDirs = commonDir ? [gitDir, resolve(gitDir, commonDir)] : [gitDir];
158
+ for (const refDir of refDirs) {
159
+ const loose = readText(join(refDir, ref));
160
+ if (loose && COMMIT_ID.test(loose)) {
161
+ return loose;
162
+ }
163
+ }
164
+ // A branch untouched since the last `git gc` exists only in packed-refs.
165
+ for (const refDir of refDirs) {
166
+ const packed = readText(join(refDir, "packed-refs"));
167
+ for (const line of packed?.split(/\r?\n/) ?? []) {
168
+ const [commit, name] = line.split(" ");
169
+ if (name === ref && COMMIT_ID.test(commit)) {
170
+ return commit;
171
+ }
172
+ }
173
+ }
174
+ return undefined;
175
+ }
176
+ function readText(file) {
177
+ try {
178
+ return readFileSync(file, "utf8").trim();
179
+ }
180
+ catch {
181
+ return undefined;
182
+ }
183
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nestjs/observe",
3
- "version": "0.3.3",
3
+ "version": "0.3.5",
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",