@bymax-one/nest-telemetry 1.0.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.
@@ -0,0 +1,108 @@
1
+ import { Injectable, Inject, Module, Logger } from '@nestjs/common';
2
+ import { ModuleRef } from '@nestjs/core';
3
+
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __decorateClass = (decorators, target, key, kind) => {
6
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
7
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
8
+ if (decorator = decorators[i])
9
+ result = (decorator(result)) || result;
10
+ return result;
11
+ };
12
+ var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
13
+
14
+ // src/sdk/handle.ts
15
+ var HANDLE_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/handle");
16
+ var PENDING_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/pending-start");
17
+ var store = globalThis;
18
+ function currentHandle() {
19
+ return store[HANDLE_KEY];
20
+ }
21
+ function pendingStart() {
22
+ return store[PENDING_KEY];
23
+ }
24
+ async function shutdownTelemetry() {
25
+ await Promise.allSettled([pendingStart()]);
26
+ await currentHandle()?.shutdown();
27
+ }
28
+
29
+ // src/nest/telemetry-shutdown.hook.ts
30
+ var TELEMETRY_FLUSH_FAILED_KEY = "TRACING_FLUSH_FAILED";
31
+ var TELEMETRY_LOGGER = /* @__PURE__ */ Symbol("TELEMETRY_LOGGER");
32
+ var TelemetryShutdownHook = class {
33
+ /**
34
+ * @param moduleRef - Resolves the optional structured logger when a flush fails.
35
+ */
36
+ constructor(moduleRef) {
37
+ this.moduleRef = moduleRef;
38
+ }
39
+ /**
40
+ * Flushes and stops the SDK, if one was started.
41
+ *
42
+ * Nest awaits this while closing the application, so awaiting the flush here guarantees buffered
43
+ * spans are exported before the process exits. A flush the collector refuses, or one the batch
44
+ * processor abandons after its export timeout, is reported and ends there: an orchestrator reads
45
+ * the exit code, and a collector outage is not a crashed instance.
46
+ *
47
+ * @returns A promise that resolves once buffered spans are exported, or once a failed export
48
+ * has been reported. Never rejects.
49
+ */
50
+ async onApplicationShutdown() {
51
+ try {
52
+ await shutdownTelemetry();
53
+ } catch (error) {
54
+ this.report(error);
55
+ }
56
+ }
57
+ /**
58
+ * Reports a failed flush: through the structured logger when the application provides a usable
59
+ * one, else through the Nest logger with the key in the message. Reporting is itself guarded at
60
+ * every step, because the hook's one job is to keep shutdown from failing: a logger the
61
+ * application bound to the token that is the wrong value, or that throws, falls through to the
62
+ * Nest logger, and a Nest logger that throws ends the report.
63
+ *
64
+ * @param error - The rejection. A value that is not an `Error` is not stringified, since its
65
+ * `toString` could throw here.
66
+ */
67
+ report(error) {
68
+ const failure = error instanceof Error ? error : new Error("The telemetry SDK failed to shut down.");
69
+ try {
70
+ const logger = this.structuredLogger();
71
+ if (typeof logger?.errorStructured === "function") {
72
+ logger.errorStructured(TELEMETRY_FLUSH_FAILED_KEY, failure);
73
+ return;
74
+ }
75
+ } catch {
76
+ }
77
+ try {
78
+ new Logger("Telemetry").error(
79
+ `${TELEMETRY_FLUSH_FAILED_KEY}: ${failure.message}`,
80
+ failure.stack
81
+ );
82
+ } catch {
83
+ }
84
+ }
85
+ /**
86
+ * Looks the structured logger up.
87
+ *
88
+ * @returns The logger, or `undefined` when the application provides none.
89
+ */
90
+ structuredLogger() {
91
+ try {
92
+ return this.moduleRef.get(TELEMETRY_LOGGER, { strict: false });
93
+ } catch {
94
+ return void 0;
95
+ }
96
+ }
97
+ };
98
+ TelemetryShutdownHook = __decorateClass([
99
+ Injectable(),
100
+ __decorateParam(0, Inject(ModuleRef))
101
+ ], TelemetryShutdownHook);
102
+ var TelemetryModule = class {
103
+ };
104
+ TelemetryModule = __decorateClass([
105
+ Module({ providers: [TelemetryShutdownHook] })
106
+ ], TelemetryModule);
107
+
108
+ export { TELEMETRY_FLUSH_FAILED_KEY, TELEMETRY_LOGGER, TelemetryModule, TelemetryShutdownHook };
@@ -0,0 +1,6 @@
1
+ 'use strict';
2
+
3
+ // src/register/require-stub.ts
4
+ throw new Error(
5
+ "@bymax-one/nest-telemetry/register is a preload for `node --import`, and cannot be required: starting the SDK is asynchronous, so a `--require` preload would let the application load first."
6
+ );
@@ -0,0 +1,2 @@
1
+
2
+ export { };
@@ -0,0 +1,2 @@
1
+
2
+ export { };
@@ -0,0 +1,400 @@
1
+ import { register } from 'module';
2
+
3
+ // src/register/boot.ts
4
+
5
+ // src/sdk/environment.ts
6
+ function readExporterList(raw) {
7
+ return (raw ?? "").split(",").map((name) => name.trim()).filter((name) => name !== "");
8
+ }
9
+ function readPositiveNumber(raw) {
10
+ const value = Number(raw);
11
+ return Number.isFinite(value) && value > 0 ? value : void 0;
12
+ }
13
+ function readTelemetryEnvironment(source = process.env) {
14
+ const tuning = {};
15
+ const maxQueueSize = readPositiveNumber(source["OTEL_BSP_MAX_QUEUE_SIZE"]);
16
+ if (maxQueueSize !== void 0) tuning.maxQueueSize = maxQueueSize;
17
+ const scheduledDelayMillis = readPositiveNumber(source["OTEL_BSP_SCHEDULE_DELAY"]);
18
+ if (scheduledDelayMillis !== void 0) tuning.scheduledDelayMillis = scheduledDelayMillis;
19
+ const exportTimeoutMillis = readPositiveNumber(source["OTEL_BSP_EXPORT_TIMEOUT"]);
20
+ if (exportTimeoutMillis !== void 0) tuning.exportTimeoutMillis = exportTimeoutMillis;
21
+ const maxExportBatchSize = readPositiveNumber(source["OTEL_BSP_MAX_EXPORT_BATCH_SIZE"]);
22
+ if (maxExportBatchSize !== void 0) tuning.maxExportBatchSize = maxExportBatchSize;
23
+ const serviceName = source["OTEL_SERVICE_NAME"]?.trim();
24
+ const detectors = source["OTEL_NODE_RESOURCE_DETECTORS"];
25
+ return {
26
+ sdkDisabled: source["OTEL_SDK_DISABLED"]?.toLowerCase() === "true",
27
+ serviceName: serviceName === "" ? void 0 : serviceName,
28
+ metricsExporters: readExporterList(source["OTEL_METRICS_EXPORTER"]),
29
+ logsExporters: readExporterList(source["OTEL_LOGS_EXPORTER"]),
30
+ batchSpanProcessor: tuning,
31
+ resourceDetectors: detectors === void 0 || detectors.trim() === "" ? void 0 : readExporterList(detectors)
32
+ };
33
+ }
34
+
35
+ // src/sdk/redaction.ts
36
+ var REDACTED_QUERY_VALUE = "[redacted]";
37
+ var URL_QUERY_ATTRIBUTE = "url.query";
38
+ var TARGET_ATTRIBUTES = ["url.full", "http.url", "http.target"];
39
+ var DEFAULT_REDACTED_QUERY_PARAMS = [
40
+ "sig",
41
+ "Signature",
42
+ "AWSAccessKeyId",
43
+ "X-Goog-Signature",
44
+ "X-Amz-Signature",
45
+ "X-Amz-Credential",
46
+ "X-Amz-Security-Token",
47
+ "token",
48
+ "code",
49
+ "access_token",
50
+ "refresh_token",
51
+ "id_token",
52
+ "secret",
53
+ "password",
54
+ "api_key",
55
+ "apikey",
56
+ "key",
57
+ "signature",
58
+ "sas",
59
+ "auth"
60
+ ];
61
+ function buildRedactedQueryParams(extra) {
62
+ return [.../* @__PURE__ */ new Set([...DEFAULT_REDACTED_QUERY_PARAMS, ...extra])];
63
+ }
64
+ function redactSpanUrlQuery(span) {
65
+ if (URL_QUERY_ATTRIBUTE in span.attributes) {
66
+ span.setAttribute(URL_QUERY_ATTRIBUTE, REDACTED_QUERY_VALUE);
67
+ }
68
+ for (const key of TARGET_ATTRIBUTES) {
69
+ const target = span.attributes[key];
70
+ if (typeof target === "string" && target.includes("?")) {
71
+ span.setAttribute(key, target.slice(0, target.indexOf("?")));
72
+ }
73
+ }
74
+ }
75
+ function createUrlQueryRedactor() {
76
+ return {
77
+ onStart: () => void 0,
78
+ onEnding: (span) => {
79
+ redactSpanUrlQuery(span);
80
+ },
81
+ onEnd: () => void 0,
82
+ shutdown: () => Promise.resolve(),
83
+ forceFlush: () => Promise.resolve()
84
+ };
85
+ }
86
+ function serializeRedisCommandName(commandName) {
87
+ return commandName;
88
+ }
89
+
90
+ // src/sdk/assembly.ts
91
+ var FS_INSTRUMENTATION = "@opentelemetry/instrumentation-fs";
92
+ var HTTP_INSTRUMENTATION = "@opentelemetry/instrumentation-http";
93
+ var IOREDIS_INSTRUMENTATION = "@opentelemetry/instrumentation-ioredis";
94
+ var PINO_INSTRUMENTATION = "@opentelemetry/instrumentation-pino";
95
+ var LOG_EXPORTERS = /* @__PURE__ */ new Set(["otlp", "console"]);
96
+ var UNKNOWN_SERVICE_NAME = "unknown_service:node";
97
+ var WARNING_OPTIONS = {
98
+ type: "SecurityWarning",
99
+ code: "BYMAX_TELEMETRY_UNSAFE_REDACTION_DISABLED"
100
+ };
101
+ function planSignals(env) {
102
+ const overrides = {};
103
+ if (env.metricsExporters.length === 0) overrides.metricReaders = [];
104
+ if (env.logsExporters.length === 0) overrides.logRecordProcessors = [];
105
+ return {
106
+ overrides,
107
+ sendLogs: !env.logsExporters.includes("none") && env.logsExporters.some((name) => LOG_EXPORTERS.has(name))
108
+ };
109
+ }
110
+ function nonBlank(value) {
111
+ const trimmed = value?.trim();
112
+ return trimmed === "" ? void 0 : trimmed;
113
+ }
114
+ function buildResourceAttributes(options, env) {
115
+ const attributes = {};
116
+ const name = env.serviceName ?? nonBlank(options.serviceName);
117
+ attributes["service.name"] = name ?? UNKNOWN_SERVICE_NAME;
118
+ const version = nonBlank(options.serviceVersion);
119
+ if (version !== void 0) attributes["service.version"] = version;
120
+ return attributes;
121
+ }
122
+ function buildInstrumentationConfig(options, signals) {
123
+ const instrumentations = options.instrumentations ?? {};
124
+ const overrides = {};
125
+ for (const [name, config] of Object.entries(instrumentations.overrides ?? {})) {
126
+ if (config !== void 0) overrides[name] = { ...config };
127
+ }
128
+ const redactRedis = options.unsafe?.disableRedisArgumentRedaction !== true;
129
+ const library = {
130
+ [FS_INSTRUMENTATION]: { enabled: instrumentations.fs === true },
131
+ [HTTP_INSTRUMENTATION]: {},
132
+ [PINO_INSTRUMENTATION]: { disableLogSending: !(instrumentations.sendLogs ?? signals.sendLogs) }
133
+ };
134
+ const merged = {};
135
+ for (const name of /* @__PURE__ */ new Set([...Object.keys(library), ...Object.keys(overrides)])) {
136
+ merged[name] = { ...library[name], ...overrides[name] };
137
+ }
138
+ const hostParams = merged[HTTP_INSTRUMENTATION]?.["redactedQueryParams"];
139
+ merged[HTTP_INSTRUMENTATION] = {
140
+ ...merged[HTTP_INSTRUMENTATION],
141
+ redactedQueryParams: buildRedactedQueryParams([
142
+ ...Array.isArray(hostParams) ? hostParams : [],
143
+ ...options.extraRedactedQueryParams ?? []
144
+ ])
145
+ };
146
+ if (options.ignoreIncomingRequest !== void 0) {
147
+ merged[HTTP_INSTRUMENTATION]["ignoreIncomingRequestHook"] = options.ignoreIncomingRequest;
148
+ }
149
+ if (redactRedis) {
150
+ merged[IOREDIS_INSTRUMENTATION] = {
151
+ ...merged[IOREDIS_INSTRUMENTATION],
152
+ dbStatementSerializer: serializeRedisCommandName
153
+ };
154
+ }
155
+ return merged;
156
+ }
157
+ function warnAboutMissingServiceName(options, env) {
158
+ if (env.serviceName === void 0 && nonBlank(options.serviceName) === void 0) {
159
+ process.emitWarning(
160
+ "No service name is set, so spans are exported as unknown_service:node. Set OTEL_SERVICE_NAME or the serviceName option.",
161
+ { type: "Warning", code: "BYMAX_TELEMETRY_SERVICE_NAME_MISSING" }
162
+ );
163
+ }
164
+ }
165
+ function warnAboutUnsafeOptions(options) {
166
+ if (options.unsafe?.disableUrlRedaction === true) {
167
+ process.emitWarning(
168
+ "URL redaction is disabled: url.query, url.full, http.url and http.target are exported as recorded.",
169
+ WARNING_OPTIONS
170
+ );
171
+ }
172
+ if (options.unsafe?.exportProcessCommandArgs === true) {
173
+ process.emitWarning(
174
+ "Process command-line redaction is disabled: process.command_args and process.command_line are exported in the resource, and command-line arguments can carry secrets.",
175
+ WARNING_OPTIONS
176
+ );
177
+ }
178
+ if (options.unsafe?.disableRedisArgumentRedaction === true) {
179
+ process.emitWarning(
180
+ "Redis argument redaction is disabled: command arguments, EVAL and EVALSHA payloads included, are exported in db.query.text.",
181
+ WARNING_OPTIONS
182
+ );
183
+ }
184
+ }
185
+
186
+ // src/sdk/handle.ts
187
+ var HANDLE_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/handle");
188
+ var PENDING_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/pending-start");
189
+ var store = globalThis;
190
+ function registerHandle(handle) {
191
+ store[HANDLE_KEY] = handle;
192
+ }
193
+ function currentHandle() {
194
+ return store[HANDLE_KEY];
195
+ }
196
+ function clearHandle() {
197
+ delete store[HANDLE_KEY];
198
+ }
199
+ function pendingStart() {
200
+ return store[PENDING_KEY];
201
+ }
202
+ function setPendingStart(start) {
203
+ store[PENDING_KEY] = start;
204
+ }
205
+ function clearPendingStart() {
206
+ delete store[PENDING_KEY];
207
+ }
208
+ function createHandle(stopSdk) {
209
+ let flush;
210
+ let finished = false;
211
+ const handle = {
212
+ enabled: true,
213
+ get stopping() {
214
+ return flush !== void 0 && !finished;
215
+ },
216
+ shutdown: () => {
217
+ if (finished) {
218
+ return Promise.resolve();
219
+ }
220
+ flush ??= stopSdk().finally(() => {
221
+ finished = true;
222
+ if (currentHandle() === handle) {
223
+ clearHandle();
224
+ }
225
+ });
226
+ return flush;
227
+ }
228
+ };
229
+ return handle;
230
+ }
231
+
232
+ // src/sdk/resource-detectors.ts
233
+ var COMMAND_LINE_ATTRIBUTES = ["process.command_args", "process.command_line"];
234
+ var NAMED = /* @__PURE__ */ new Map([
235
+ ["process", ["process"]],
236
+ ["host", ["host", "os"]],
237
+ ["os", ["os"]],
238
+ ["service", ["serviceinstance", "env"]],
239
+ ["serviceinstance", ["serviceinstance"]],
240
+ ["env", ["env"]]
241
+ ]);
242
+ var DEFAULT_DETECTORS = [
243
+ "serviceinstance",
244
+ "process",
245
+ "host",
246
+ "os",
247
+ "env"
248
+ ];
249
+ var ALL_DETECTORS = ["host", "os", "serviceinstance", "process", "env"];
250
+ function withoutAttributes(detector, names) {
251
+ return {
252
+ detect: (config) => {
253
+ const detected = detector.detect(config);
254
+ return {
255
+ ...detected,
256
+ // Spreading an absent attribute map yields an empty one, so a detector that found nothing
257
+ // needs no case of its own.
258
+ attributes: Object.fromEntries(
259
+ Object.entries({ ...detected.attributes }).filter(([name]) => !names.includes(name))
260
+ )
261
+ };
262
+ }
263
+ };
264
+ }
265
+ function selectResourceDetectors(selection, detectors, keepCommandLine) {
266
+ const available = keepCommandLine ? detectors : { ...detectors, process: withoutAttributes(detectors.process, COMMAND_LINE_ATTRIBUTES) };
267
+ if (selection?.includes("none") === true && !selection.includes("all")) {
268
+ return [];
269
+ }
270
+ let chosen = DEFAULT_DETECTORS;
271
+ if (selection?.includes("all") === true) {
272
+ chosen = ALL_DETECTORS;
273
+ } else if (selection !== void 0) {
274
+ chosen = selection.flatMap((name) => NAMED.get(name) ?? []);
275
+ }
276
+ return [...new Set(chosen)].map((name) => available[name]);
277
+ }
278
+
279
+ // src/sdk/start.ts
280
+ var DISABLED_HANDLE = {
281
+ enabled: false,
282
+ shutdown: () => Promise.resolve()
283
+ };
284
+ async function startTelemetry(options = {}) {
285
+ const env = readTelemetryEnvironment(options.env);
286
+ if (options.enabled === false || env.sdkDisabled) {
287
+ return DISABLED_HANDLE;
288
+ }
289
+ let running = currentHandle();
290
+ if (running?.stopping === true) {
291
+ await Promise.allSettled([running.shutdown()]);
292
+ running = currentHandle();
293
+ }
294
+ if (running !== void 0) {
295
+ return running;
296
+ }
297
+ const joined = pendingStart();
298
+ if (joined !== void 0) {
299
+ return joined;
300
+ }
301
+ const start = boot(options, env).finally(clearPendingStart);
302
+ setPendingStart(start);
303
+ return start;
304
+ }
305
+ async function loadPackages() {
306
+ const [sdkNode, sdkTrace, autoInstrumentations, exporter, resources] = await Promise.all([
307
+ import('@opentelemetry/sdk-node'),
308
+ import('@opentelemetry/sdk-trace'),
309
+ import('@opentelemetry/auto-instrumentations-node'),
310
+ import('@opentelemetry/exporter-trace-otlp-http'),
311
+ import('@opentelemetry/resources')
312
+ ]);
313
+ return { sdkNode, sdkTrace, autoInstrumentations, exporter, resources };
314
+ }
315
+ function buildSdk(packages, options, env) {
316
+ const { sdkNode, sdkTrace, autoInstrumentations, exporter, resources } = packages;
317
+ const signals = planSignals(env);
318
+ return new sdkNode.NodeSDK({
319
+ ...signals.overrides,
320
+ resource: resources.resourceFromAttributes(buildResourceAttributes(options, env)),
321
+ resourceDetectors: selectResourceDetectors(
322
+ env.resourceDetectors,
323
+ {
324
+ env: resources.envDetector,
325
+ host: resources.hostDetector,
326
+ os: resources.osDetector,
327
+ process: resources.processDetector,
328
+ serviceinstance: resources.serviceInstanceIdDetector
329
+ },
330
+ options.unsafe?.exportProcessCommandArgs === true
331
+ ),
332
+ spanProcessors: [
333
+ // Ordered before the batch processor, so each span is redacted in place before it is exported.
334
+ ...options.unsafe?.disableUrlRedaction === true ? [] : [createUrlQueryRedactor()],
335
+ new sdkTrace.BatchSpanProcessor({
336
+ exporter: new exporter.OTLPTraceExporter(),
337
+ ...env.batchSpanProcessor
338
+ })
339
+ ],
340
+ instrumentations: [
341
+ autoInstrumentations.getNodeAutoInstrumentations(buildInstrumentationConfig(options, signals))
342
+ ]
343
+ });
344
+ }
345
+ async function boot(options, env) {
346
+ warnAboutUnsafeOptions(options);
347
+ warnAboutMissingServiceName(options, env);
348
+ const sdk = buildSdk(await loadPackages(), options, env);
349
+ sdk.start();
350
+ const handle = createHandle(() => sdk.shutdown());
351
+ registerHandle(handle);
352
+ return handle;
353
+ }
354
+
355
+ // src/register/boot.ts
356
+ var ESM_HOOK_SPECIFIER = "@opentelemetry/instrumentation/hook.mjs";
357
+ var HOOK_WARNING_CODE = "BYMAX_TELEMETRY_ESM_HOOK_UNAVAILABLE";
358
+ async function bootFromEnvironment(parentUrl, dependencies = {}) {
359
+ const env = readTelemetryEnvironment(dependencies.env);
360
+ if (!env.sdkDisabled) {
361
+ registerLoaderHook(dependencies.registerHook ?? registerModuleHook, parentUrl);
362
+ }
363
+ const handle = await startOrWarn(
364
+ dependencies.start ?? startTelemetry,
365
+ dependencies.env === void 0 ? {} : { env: dependencies.env }
366
+ );
367
+ if (handle.enabled) {
368
+ process.once("beforeExit", () => {
369
+ void Promise.allSettled([handle.shutdown()]);
370
+ });
371
+ }
372
+ return handle;
373
+ }
374
+ async function startOrWarn(start, options) {
375
+ try {
376
+ return await start(options);
377
+ } catch (error) {
378
+ process.emitWarning(
379
+ `Telemetry could not be started (${String(error)}), so the application continues without it.`,
380
+ { type: "Warning", code: "BYMAX_TELEMETRY_START_FAILED" }
381
+ );
382
+ return { enabled: false, shutdown: () => Promise.resolve() };
383
+ }
384
+ }
385
+ function registerLoaderHook(register2, parentUrl) {
386
+ try {
387
+ register2(ESM_HOOK_SPECIFIER, parentUrl);
388
+ } catch (error) {
389
+ process.emitWarning(
390
+ `The OpenTelemetry loader hook could not be registered (${String(error)}), so native ES modules are not instrumented. Install @opentelemetry/instrumentation to instrument them; CommonJS code is unaffected.`,
391
+ { type: "Warning", code: HOOK_WARNING_CODE }
392
+ );
393
+ }
394
+ }
395
+ function registerModuleHook(specifier, parentUrl) {
396
+ register(specifier, parentUrl);
397
+ }
398
+
399
+ // src/register/preload.mjs
400
+ await bootFromEnvironment(import.meta.url);