@bymax-one/nest-telemetry 1.0.1 → 1.0.3
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.
- package/CHANGELOG.md +113 -0
- package/README.md +96 -62
- package/dist/nest/index.cjs +48 -0
- package/dist/nest/index.d.cts +35 -6
- package/dist/nest/index.d.ts +35 -6
- package/dist/nest/index.mjs +48 -2
- package/dist/register/index.mjs +106 -15
- package/dist/sdk/index.cjs +108 -16
- package/dist/sdk/index.d.cts +13 -2
- package/dist/sdk/index.d.ts +13 -2
- package/dist/sdk/index.mjs +108 -16
- package/package.json +4 -1
package/dist/nest/index.d.ts
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
|
-
import { OnApplicationShutdown } from '@nestjs/common';
|
|
1
|
+
import { OnApplicationShutdown, OnModuleInit } from '@nestjs/common';
|
|
2
2
|
|
|
3
3
|
/** Log key of the entry a failed flush leaves, stable so an alert can match it. */
|
|
4
4
|
declare const TELEMETRY_FLUSH_FAILED_KEY = "TRACING_FLUSH_FAILED";
|
|
5
|
+
/** Log key of the entry a shutdown that hit its deadline leaves, stable so an alert can match it. */
|
|
6
|
+
declare const TELEMETRY_SHUTDOWN_TIMEOUT_KEY = "TRACING_SHUTDOWN_TIMEOUT";
|
|
7
|
+
/** Log key of the entry a failed span export leaves, stable so an alert can match it. */
|
|
8
|
+
declare const TELEMETRY_EXPORT_FAILED_KEY = "TRACING_EXPORT_FAILED";
|
|
5
9
|
/** Injection token of the optional structured logger a failed flush is reported through. */
|
|
6
10
|
declare const TELEMETRY_LOGGER: unique symbol;
|
|
7
11
|
/** The one call the hook makes on a structured logger. */
|
|
@@ -13,6 +17,16 @@ interface ITelemetryErrorLogger {
|
|
|
13
17
|
* @param error - The failure.
|
|
14
18
|
*/
|
|
15
19
|
errorStructured(logKey: string, error: Error): void;
|
|
20
|
+
/**
|
|
21
|
+
* Writes a warning entry under a log key, for a failed span export. Optional: a logger without
|
|
22
|
+
* it gets that warning as a process warning.
|
|
23
|
+
*
|
|
24
|
+
* @param logKey - The entry's log key.
|
|
25
|
+
* @param message - The library's own text, never anything from the exporter.
|
|
26
|
+
* @param userId - Always `undefined`.
|
|
27
|
+
* @param metadata - The exporter kind and a short error code.
|
|
28
|
+
*/
|
|
29
|
+
warnStructured?(logKey: string, message: string, userId?: string, metadata?: Record<string, unknown>): void;
|
|
16
30
|
}
|
|
17
31
|
/** What the hook needs of Nest's module reference: to look a provider up anywhere in the application. */
|
|
18
32
|
interface IProviderLookup {
|
|
@@ -27,12 +41,19 @@ interface IProviderLookup {
|
|
|
27
41
|
}): unknown;
|
|
28
42
|
}
|
|
29
43
|
/** Awaits the SDK flush as part of the application's own graceful shutdown. */
|
|
30
|
-
declare class TelemetryShutdownHook implements OnApplicationShutdown {
|
|
44
|
+
declare class TelemetryShutdownHook implements OnApplicationShutdown, OnModuleInit {
|
|
31
45
|
private readonly moduleRef;
|
|
46
|
+
/** Removes this hook's warning sink, when it registered one. */
|
|
47
|
+
private releaseSink;
|
|
32
48
|
/**
|
|
33
49
|
* @param moduleRef - Resolves the optional structured logger when a flush fails.
|
|
34
50
|
*/
|
|
35
51
|
constructor(moduleRef: IProviderLookup);
|
|
52
|
+
/**
|
|
53
|
+
* Routes the library's two runtime warnings to the structured logger the application bound, when
|
|
54
|
+
* there is one. Without it they stay process warnings.
|
|
55
|
+
*/
|
|
56
|
+
onModuleInit(): void;
|
|
36
57
|
/**
|
|
37
58
|
* Flushes and stops the SDK, if one was started.
|
|
38
59
|
*
|
|
@@ -45,6 +66,14 @@ declare class TelemetryShutdownHook implements OnApplicationShutdown {
|
|
|
45
66
|
* has been reported. Never rejects.
|
|
46
67
|
*/
|
|
47
68
|
onApplicationShutdown(): Promise<void>;
|
|
69
|
+
/**
|
|
70
|
+
* Writes a warning to the structured logger under its key.
|
|
71
|
+
*
|
|
72
|
+
* @param warning - The warning.
|
|
73
|
+
* @returns Whether the logger took it; a warning with no key or no method on the logger is left
|
|
74
|
+
* to the process warning.
|
|
75
|
+
*/
|
|
76
|
+
private route;
|
|
48
77
|
/**
|
|
49
78
|
* Reports a failed flush: through the structured logger when the application provides a usable
|
|
50
79
|
* one, else through the Nest logger with the key in the message. Reporting is itself guarded at
|
|
@@ -65,12 +94,12 @@ declare class TelemetryShutdownHook implements OnApplicationShutdown {
|
|
|
65
94
|
}
|
|
66
95
|
|
|
67
96
|
/**
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
97
|
+
* List it first in the imports of the application module, before any module that is global or
|
|
98
|
+
* imports a global module. Nest then awaits the SDK flush while closing the application, so
|
|
99
|
+
* buffered spans are exported before the process exits.
|
|
71
100
|
*/
|
|
72
101
|
declare class TelemetryModule {
|
|
73
102
|
}
|
|
74
103
|
|
|
75
|
-
export { TELEMETRY_FLUSH_FAILED_KEY, TELEMETRY_LOGGER, TelemetryModule, TelemetryShutdownHook };
|
|
104
|
+
export { TELEMETRY_EXPORT_FAILED_KEY, TELEMETRY_FLUSH_FAILED_KEY, TELEMETRY_LOGGER, TELEMETRY_SHUTDOWN_TIMEOUT_KEY, TelemetryModule, TelemetryShutdownHook };
|
|
76
105
|
export type { ITelemetryErrorLogger };
|
package/dist/nest/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Injectable, Inject, Module, Logger } from '@nestjs/common';
|
|
1
|
+
import { Injectable, Inject, Global, Module, Logger } from '@nestjs/common';
|
|
2
2
|
import { ModuleRef } from '@nestjs/core';
|
|
3
3
|
|
|
4
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -11,6 +11,17 @@ var __decorateClass = (decorators, target, key, kind) => {
|
|
|
11
11
|
};
|
|
12
12
|
var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
|
|
13
13
|
|
|
14
|
+
// src/sdk/warning-sink.ts
|
|
15
|
+
var SINK_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/warning-sink");
|
|
16
|
+
function registerWarningSink(sink) {
|
|
17
|
+
Reflect.set(globalThis, SINK_KEY, sink);
|
|
18
|
+
return () => {
|
|
19
|
+
if (Reflect.get(globalThis, SINK_KEY) === sink) {
|
|
20
|
+
Reflect.deleteProperty(globalThis, SINK_KEY);
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
14
25
|
// src/sdk/handle.ts
|
|
15
26
|
var HANDLE_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/handle");
|
|
16
27
|
var PENDING_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/pending-start");
|
|
@@ -28,6 +39,8 @@ async function shutdownTelemetry() {
|
|
|
28
39
|
|
|
29
40
|
// src/nest/telemetry-shutdown.hook.ts
|
|
30
41
|
var TELEMETRY_FLUSH_FAILED_KEY = "TRACING_FLUSH_FAILED";
|
|
42
|
+
var TELEMETRY_SHUTDOWN_TIMEOUT_KEY = "TRACING_SHUTDOWN_TIMEOUT";
|
|
43
|
+
var TELEMETRY_EXPORT_FAILED_KEY = "TRACING_EXPORT_FAILED";
|
|
31
44
|
var TELEMETRY_LOGGER = /* @__PURE__ */ Symbol("TELEMETRY_LOGGER");
|
|
32
45
|
var TelemetryShutdownHook = class {
|
|
33
46
|
/**
|
|
@@ -36,6 +49,15 @@ var TelemetryShutdownHook = class {
|
|
|
36
49
|
constructor(moduleRef) {
|
|
37
50
|
this.moduleRef = moduleRef;
|
|
38
51
|
}
|
|
52
|
+
/**
|
|
53
|
+
* Routes the library's two runtime warnings to the structured logger the application bound, when
|
|
54
|
+
* there is one. Without it they stay process warnings.
|
|
55
|
+
*/
|
|
56
|
+
onModuleInit() {
|
|
57
|
+
if (this.structuredLogger() !== void 0) {
|
|
58
|
+
this.releaseSink = registerWarningSink((warning) => this.route(warning));
|
|
59
|
+
}
|
|
60
|
+
}
|
|
39
61
|
/**
|
|
40
62
|
* Flushes and stops the SDK, if one was started.
|
|
41
63
|
*
|
|
@@ -52,7 +74,30 @@ var TelemetryShutdownHook = class {
|
|
|
52
74
|
await shutdownTelemetry();
|
|
53
75
|
} catch (error) {
|
|
54
76
|
this.report(error);
|
|
77
|
+
} finally {
|
|
78
|
+
this.releaseSink?.();
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Writes a warning to the structured logger under its key.
|
|
83
|
+
*
|
|
84
|
+
* @param warning - The warning.
|
|
85
|
+
* @returns Whether the logger took it; a warning with no key or no method on the logger is left
|
|
86
|
+
* to the process warning.
|
|
87
|
+
*/
|
|
88
|
+
route(warning) {
|
|
89
|
+
const logger = this.structuredLogger();
|
|
90
|
+
if (warning.code === "BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT" && typeof logger?.errorStructured === "function") {
|
|
91
|
+
logger.errorStructured(TELEMETRY_SHUTDOWN_TIMEOUT_KEY, new Error(warning.text));
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
if (warning.code === "BYMAX_TELEMETRY_EXPORT_FAILED" && typeof logger?.warnStructured === "function") {
|
|
95
|
+
logger.warnStructured(TELEMETRY_EXPORT_FAILED_KEY, warning.text, void 0, {
|
|
96
|
+
...warning.fields
|
|
97
|
+
});
|
|
98
|
+
return true;
|
|
55
99
|
}
|
|
100
|
+
return false;
|
|
56
101
|
}
|
|
57
102
|
/**
|
|
58
103
|
* Reports a failed flush: through the structured logger when the application provides a usable
|
|
@@ -102,7 +147,8 @@ TelemetryShutdownHook = __decorateClass([
|
|
|
102
147
|
var TelemetryModule = class {
|
|
103
148
|
};
|
|
104
149
|
TelemetryModule = __decorateClass([
|
|
150
|
+
Global(),
|
|
105
151
|
Module({ providers: [TelemetryShutdownHook] })
|
|
106
152
|
], TelemetryModule);
|
|
107
153
|
|
|
108
|
-
export { TELEMETRY_FLUSH_FAILED_KEY, TELEMETRY_LOGGER, TelemetryModule, TelemetryShutdownHook };
|
|
154
|
+
export { TELEMETRY_EXPORT_FAILED_KEY, TELEMETRY_FLUSH_FAILED_KEY, TELEMETRY_LOGGER, TELEMETRY_SHUTDOWN_TIMEOUT_KEY, TelemetryModule, TelemetryShutdownHook };
|
package/dist/register/index.mjs
CHANGED
|
@@ -23,7 +23,7 @@ function readTelemetryEnvironment(source = process.env) {
|
|
|
23
23
|
const serviceName = source["OTEL_SERVICE_NAME"]?.trim();
|
|
24
24
|
const detectors = source["OTEL_NODE_RESOURCE_DETECTORS"];
|
|
25
25
|
return {
|
|
26
|
-
sdkDisabled: source["OTEL_SDK_DISABLED"]?.toLowerCase() === "true",
|
|
26
|
+
sdkDisabled: source["OTEL_SDK_DISABLED"]?.trim().toLowerCase() === "true",
|
|
27
27
|
serviceName: serviceName === "" ? void 0 : serviceName,
|
|
28
28
|
metricsExporters: readExporterList(source["OTEL_METRICS_EXPORTER"]),
|
|
29
29
|
logsExporters: readExporterList(source["OTEL_LOGS_EXPORTER"]),
|
|
@@ -91,6 +91,7 @@ function serializeRedisCommandName(commandName) {
|
|
|
91
91
|
var FS_INSTRUMENTATION = "@opentelemetry/instrumentation-fs";
|
|
92
92
|
var HTTP_INSTRUMENTATION = "@opentelemetry/instrumentation-http";
|
|
93
93
|
var IOREDIS_INSTRUMENTATION = "@opentelemetry/instrumentation-ioredis";
|
|
94
|
+
var REDIS_INSTRUMENTATION = "@opentelemetry/instrumentation-redis";
|
|
94
95
|
var PINO_INSTRUMENTATION = "@opentelemetry/instrumentation-pino";
|
|
95
96
|
var LOG_EXPORTERS = /* @__PURE__ */ new Set(["otlp", "console"]);
|
|
96
97
|
var UNKNOWN_SERVICE_NAME = "unknown_service:node";
|
|
@@ -98,6 +99,7 @@ var WARNING_OPTIONS = {
|
|
|
98
99
|
type: "SecurityWarning",
|
|
99
100
|
code: "BYMAX_TELEMETRY_UNSAFE_REDACTION_DISABLED"
|
|
100
101
|
};
|
|
102
|
+
var IGNORED_WARNING = { type: "Warning", code: "BYMAX_TELEMETRY_OPTIONS_IGNORED" };
|
|
101
103
|
function planSignals(env) {
|
|
102
104
|
const overrides = {};
|
|
103
105
|
if (env.metricsExporters.length === 0) overrides.metricReaders = [];
|
|
@@ -147,10 +149,9 @@ function buildInstrumentationConfig(options, signals) {
|
|
|
147
149
|
merged[HTTP_INSTRUMENTATION]["ignoreIncomingRequestHook"] = options.ignoreIncomingRequest;
|
|
148
150
|
}
|
|
149
151
|
if (redactRedis) {
|
|
150
|
-
|
|
151
|
-
...merged[
|
|
152
|
-
|
|
153
|
-
};
|
|
152
|
+
for (const name of [IOREDIS_INSTRUMENTATION, REDIS_INSTRUMENTATION]) {
|
|
153
|
+
merged[name] = { ...merged[name], dbStatementSerializer: serializeRedisCommandName };
|
|
154
|
+
}
|
|
154
155
|
}
|
|
155
156
|
return merged;
|
|
156
157
|
}
|
|
@@ -182,10 +183,64 @@ function warnAboutUnsafeOptions(options) {
|
|
|
182
183
|
);
|
|
183
184
|
}
|
|
184
185
|
}
|
|
186
|
+
function warnAboutIgnoredOptions(options) {
|
|
187
|
+
const stop = options.enabled === false;
|
|
188
|
+
if (stop || Object.values(options).some((v) => v !== void 0)) {
|
|
189
|
+
process.emitWarning(
|
|
190
|
+
stop ? "startTelemetry({ enabled: false }) was called while telemetry is already running. It does not stop the running SDK: call shutdownTelemetry() for that." : "startTelemetry was called while telemetry is already running, so the options of this call were ignored. Pass them to the first call.",
|
|
191
|
+
IGNORED_WARNING
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// src/sdk/warning-sink.ts
|
|
197
|
+
var SINK_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/warning-sink");
|
|
198
|
+
function reportWarning(warning) {
|
|
199
|
+
try {
|
|
200
|
+
const sink = Reflect.get(globalThis, SINK_KEY);
|
|
201
|
+
if (sink?.(warning) === true) {
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
} catch {
|
|
205
|
+
}
|
|
206
|
+
process.emitWarning(warning.text, { type: "Warning", code: warning.code });
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// src/sdk/export-failure.ts
|
|
210
|
+
var WINDOW_MS = 6e4;
|
|
211
|
+
var SUCCESS = 0;
|
|
212
|
+
var CODE_TOKEN = /^[A-Z0-9_]{1,40}$/;
|
|
213
|
+
function codeOf(error) {
|
|
214
|
+
const code = String(Reflect.get(Object(error), "code"));
|
|
215
|
+
return CODE_TOKEN.test(code) ? code : "UNKNOWN";
|
|
216
|
+
}
|
|
217
|
+
function warnOnExportFailure(exporter, kind, clock = () => performance.now()) {
|
|
218
|
+
const original = exporter.export.bind(exporter);
|
|
219
|
+
let lastWarning = Number.NEGATIVE_INFINITY;
|
|
220
|
+
exporter.export = (spans, done) => {
|
|
221
|
+
original(spans, (result) => {
|
|
222
|
+
if (result.code !== SUCCESS && clock() - lastWarning >= WINDOW_MS) {
|
|
223
|
+
lastWarning = clock();
|
|
224
|
+
try {
|
|
225
|
+
const code = codeOf(result.error);
|
|
226
|
+
reportWarning({
|
|
227
|
+
code: "BYMAX_TELEMETRY_EXPORT_FAILED",
|
|
228
|
+
text: `Exporting spans failed (${kind}, code ${code}), so the batch was dropped. This warning repeats at most once a minute. Check that the collector is reachable.`,
|
|
229
|
+
fields: { kind, code }
|
|
230
|
+
});
|
|
231
|
+
} catch {
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
done(result);
|
|
235
|
+
});
|
|
236
|
+
};
|
|
237
|
+
return exporter;
|
|
238
|
+
}
|
|
185
239
|
|
|
186
240
|
// src/sdk/handle.ts
|
|
187
241
|
var HANDLE_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/handle");
|
|
188
242
|
var PENDING_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/pending-start");
|
|
243
|
+
var STOPPED_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/stopped");
|
|
189
244
|
var store = globalThis;
|
|
190
245
|
function registerHandle(handle) {
|
|
191
246
|
store[HANDLE_KEY] = handle;
|
|
@@ -193,8 +248,8 @@ function registerHandle(handle) {
|
|
|
193
248
|
function currentHandle() {
|
|
194
249
|
return store[HANDLE_KEY];
|
|
195
250
|
}
|
|
196
|
-
function
|
|
197
|
-
|
|
251
|
+
function hasStopped() {
|
|
252
|
+
return Reflect.get(globalThis, STOPPED_KEY) === true;
|
|
198
253
|
}
|
|
199
254
|
function pendingStart() {
|
|
200
255
|
return store[PENDING_KEY];
|
|
@@ -205,7 +260,12 @@ function setPendingStart(start) {
|
|
|
205
260
|
function clearPendingStart() {
|
|
206
261
|
delete store[PENDING_KEY];
|
|
207
262
|
}
|
|
208
|
-
|
|
263
|
+
var DEFAULT_SHUTDOWN_TIMEOUT_MS = 5e3;
|
|
264
|
+
var MAX_SHUTDOWN_TIMEOUT_MS = 12e4;
|
|
265
|
+
function shutdownDeadline(requested) {
|
|
266
|
+
return requested !== void 0 && Number.isFinite(requested) && requested > 0 && requested <= MAX_SHUTDOWN_TIMEOUT_MS ? requested : DEFAULT_SHUTDOWN_TIMEOUT_MS;
|
|
267
|
+
}
|
|
268
|
+
function createHandle(stopSdk, shutdownTimeoutMs) {
|
|
209
269
|
let flush;
|
|
210
270
|
let finished = false;
|
|
211
271
|
const handle = {
|
|
@@ -217,11 +277,31 @@ function createHandle(stopSdk) {
|
|
|
217
277
|
if (finished) {
|
|
218
278
|
return Promise.resolve();
|
|
219
279
|
}
|
|
220
|
-
flush ??=
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
280
|
+
flush ??= new Promise((resolve, reject) => {
|
|
281
|
+
const deadline = shutdownDeadline(shutdownTimeoutMs);
|
|
282
|
+
const finish = () => {
|
|
283
|
+
finished = true;
|
|
284
|
+
Reflect.set(globalThis, STOPPED_KEY, true);
|
|
285
|
+
if (currentHandle() === handle) {
|
|
286
|
+
Reflect.deleteProperty(globalThis, HANDLE_KEY);
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
const timer = setTimeout(() => {
|
|
290
|
+
reportWarning({
|
|
291
|
+
code: "BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT",
|
|
292
|
+
text: `The telemetry flush did not finish within ${deadline} ms, so shutdown stopped waiting for it. Spans still queued may be lost. Raise shutdownTimeoutMs or check that the collector answers.`,
|
|
293
|
+
fields: { timeoutMs: deadline }
|
|
294
|
+
});
|
|
295
|
+
finish();
|
|
296
|
+
resolve();
|
|
297
|
+
}, deadline);
|
|
298
|
+
timer.unref();
|
|
299
|
+
new Promise((started) => {
|
|
300
|
+
started(stopSdk());
|
|
301
|
+
}).finally(() => {
|
|
302
|
+
clearTimeout(timer);
|
|
303
|
+
finish();
|
|
304
|
+
}).then(resolve, reject);
|
|
225
305
|
});
|
|
226
306
|
return flush;
|
|
227
307
|
}
|
|
@@ -277,6 +357,7 @@ function selectResourceDetectors(selection, detectors, keepCommandLine) {
|
|
|
277
357
|
}
|
|
278
358
|
|
|
279
359
|
// src/sdk/start.ts
|
|
360
|
+
var RESTART_MESSAGE = "Telemetry cannot start again after it was shut down in the same process: the modules the first start instrumented stay patched against its tracer provider, so a second SDK would export nothing for them. Start telemetry once per process; in a test suite, start it once in a global setup.";
|
|
280
361
|
var DISABLED_HANDLE = {
|
|
281
362
|
enabled: false,
|
|
282
363
|
shutdown: () => Promise.resolve()
|
|
@@ -284,6 +365,7 @@ var DISABLED_HANDLE = {
|
|
|
284
365
|
async function startTelemetry(options = {}) {
|
|
285
366
|
const env = readTelemetryEnvironment(options.env);
|
|
286
367
|
if (options.enabled === false || env.sdkDisabled) {
|
|
368
|
+
if (currentHandle()?.stopping === false || pendingStart()) warnAboutIgnoredOptions(options);
|
|
287
369
|
return DISABLED_HANDLE;
|
|
288
370
|
}
|
|
289
371
|
let running = currentHandle();
|
|
@@ -292,12 +374,21 @@ async function startTelemetry(options = {}) {
|
|
|
292
374
|
running = currentHandle();
|
|
293
375
|
}
|
|
294
376
|
if (running !== void 0) {
|
|
377
|
+
warnAboutIgnoredOptions(options);
|
|
295
378
|
return running;
|
|
296
379
|
}
|
|
297
380
|
const joined = pendingStart();
|
|
298
381
|
if (joined !== void 0) {
|
|
382
|
+
warnAboutIgnoredOptions(options);
|
|
299
383
|
return joined;
|
|
300
384
|
}
|
|
385
|
+
if (hasStopped()) {
|
|
386
|
+
process.emitWarning(RESTART_MESSAGE, {
|
|
387
|
+
type: "Warning",
|
|
388
|
+
code: "BYMAX_TELEMETRY_RESTART_UNSUPPORTED"
|
|
389
|
+
});
|
|
390
|
+
throw new Error(RESTART_MESSAGE);
|
|
391
|
+
}
|
|
301
392
|
const start = boot(options, env).finally(clearPendingStart);
|
|
302
393
|
setPendingStart(start);
|
|
303
394
|
return start;
|
|
@@ -333,7 +424,7 @@ function buildSdk(packages, options, env) {
|
|
|
333
424
|
// Ordered before the batch processor, so each span is redacted in place before it is exported.
|
|
334
425
|
...options.unsafe?.disableUrlRedaction === true ? [] : [createUrlQueryRedactor()],
|
|
335
426
|
new sdkTrace.BatchSpanProcessor({
|
|
336
|
-
exporter: new exporter.OTLPTraceExporter(),
|
|
427
|
+
exporter: warnOnExportFailure(new exporter.OTLPTraceExporter(), "otlp-http traces"),
|
|
337
428
|
...env.batchSpanProcessor
|
|
338
429
|
})
|
|
339
430
|
],
|
|
@@ -347,7 +438,7 @@ async function boot(options, env) {
|
|
|
347
438
|
warnAboutMissingServiceName(options, env);
|
|
348
439
|
const sdk = buildSdk(await loadPackages(), options, env);
|
|
349
440
|
sdk.start();
|
|
350
|
-
const handle = createHandle(() => sdk.shutdown());
|
|
441
|
+
const handle = createHandle(() => sdk.shutdown(), options.shutdownTimeoutMs);
|
|
351
442
|
registerHandle(handle);
|
|
352
443
|
return handle;
|
|
353
444
|
}
|
package/dist/sdk/index.cjs
CHANGED
|
@@ -56,6 +56,7 @@ function serializeRedisCommandName(commandName) {
|
|
|
56
56
|
}
|
|
57
57
|
|
|
58
58
|
// src/sdk/ignore-paths.ts
|
|
59
|
+
var MAX_PATH_LENGTH = 2048;
|
|
59
60
|
function ignorePaths(patterns) {
|
|
60
61
|
const stateless = patterns.map(
|
|
61
62
|
(pattern) => new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, ""))
|
|
@@ -66,13 +67,27 @@ function ignorePaths(patterns) {
|
|
|
66
67
|
}
|
|
67
68
|
const cut = request.url.indexOf("?");
|
|
68
69
|
const path = cut === -1 ? request.url : request.url.slice(0, cut);
|
|
69
|
-
return stateless.some((pattern) => pattern.test(path));
|
|
70
|
+
return path.length <= MAX_PATH_LENGTH && stateless.some((pattern) => pattern.test(path));
|
|
70
71
|
};
|
|
71
72
|
}
|
|
72
73
|
|
|
74
|
+
// src/sdk/warning-sink.ts
|
|
75
|
+
var SINK_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/warning-sink");
|
|
76
|
+
function reportWarning(warning) {
|
|
77
|
+
try {
|
|
78
|
+
const sink = Reflect.get(globalThis, SINK_KEY);
|
|
79
|
+
if (sink?.(warning) === true) {
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
} catch {
|
|
83
|
+
}
|
|
84
|
+
process.emitWarning(warning.text, { type: "Warning", code: warning.code });
|
|
85
|
+
}
|
|
86
|
+
|
|
73
87
|
// src/sdk/handle.ts
|
|
74
88
|
var HANDLE_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/handle");
|
|
75
89
|
var PENDING_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/pending-start");
|
|
90
|
+
var STOPPED_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/stopped");
|
|
76
91
|
var store = globalThis;
|
|
77
92
|
function registerHandle(handle) {
|
|
78
93
|
store[HANDLE_KEY] = handle;
|
|
@@ -80,8 +95,8 @@ function registerHandle(handle) {
|
|
|
80
95
|
function currentHandle() {
|
|
81
96
|
return store[HANDLE_KEY];
|
|
82
97
|
}
|
|
83
|
-
function
|
|
84
|
-
|
|
98
|
+
function hasStopped() {
|
|
99
|
+
return Reflect.get(globalThis, STOPPED_KEY) === true;
|
|
85
100
|
}
|
|
86
101
|
function pendingStart() {
|
|
87
102
|
return store[PENDING_KEY];
|
|
@@ -92,7 +107,12 @@ function setPendingStart(start) {
|
|
|
92
107
|
function clearPendingStart() {
|
|
93
108
|
delete store[PENDING_KEY];
|
|
94
109
|
}
|
|
95
|
-
|
|
110
|
+
var DEFAULT_SHUTDOWN_TIMEOUT_MS = 5e3;
|
|
111
|
+
var MAX_SHUTDOWN_TIMEOUT_MS = 12e4;
|
|
112
|
+
function shutdownDeadline(requested) {
|
|
113
|
+
return requested !== void 0 && Number.isFinite(requested) && requested > 0 && requested <= MAX_SHUTDOWN_TIMEOUT_MS ? requested : DEFAULT_SHUTDOWN_TIMEOUT_MS;
|
|
114
|
+
}
|
|
115
|
+
function createHandle(stopSdk, shutdownTimeoutMs) {
|
|
96
116
|
let flush;
|
|
97
117
|
let finished = false;
|
|
98
118
|
const handle = {
|
|
@@ -104,11 +124,31 @@ function createHandle(stopSdk) {
|
|
|
104
124
|
if (finished) {
|
|
105
125
|
return Promise.resolve();
|
|
106
126
|
}
|
|
107
|
-
flush ??=
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
127
|
+
flush ??= new Promise((resolve, reject) => {
|
|
128
|
+
const deadline = shutdownDeadline(shutdownTimeoutMs);
|
|
129
|
+
const finish = () => {
|
|
130
|
+
finished = true;
|
|
131
|
+
Reflect.set(globalThis, STOPPED_KEY, true);
|
|
132
|
+
if (currentHandle() === handle) {
|
|
133
|
+
Reflect.deleteProperty(globalThis, HANDLE_KEY);
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
const timer = setTimeout(() => {
|
|
137
|
+
reportWarning({
|
|
138
|
+
code: "BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT",
|
|
139
|
+
text: `The telemetry flush did not finish within ${deadline} ms, so shutdown stopped waiting for it. Spans still queued may be lost. Raise shutdownTimeoutMs or check that the collector answers.`,
|
|
140
|
+
fields: { timeoutMs: deadline }
|
|
141
|
+
});
|
|
142
|
+
finish();
|
|
143
|
+
resolve();
|
|
144
|
+
}, deadline);
|
|
145
|
+
timer.unref();
|
|
146
|
+
new Promise((started) => {
|
|
147
|
+
started(stopSdk());
|
|
148
|
+
}).finally(() => {
|
|
149
|
+
clearTimeout(timer);
|
|
150
|
+
finish();
|
|
151
|
+
}).then(resolve, reject);
|
|
112
152
|
});
|
|
113
153
|
return flush;
|
|
114
154
|
}
|
|
@@ -124,6 +164,7 @@ async function shutdownTelemetry() {
|
|
|
124
164
|
var FS_INSTRUMENTATION = "@opentelemetry/instrumentation-fs";
|
|
125
165
|
var HTTP_INSTRUMENTATION = "@opentelemetry/instrumentation-http";
|
|
126
166
|
var IOREDIS_INSTRUMENTATION = "@opentelemetry/instrumentation-ioredis";
|
|
167
|
+
var REDIS_INSTRUMENTATION = "@opentelemetry/instrumentation-redis";
|
|
127
168
|
var PINO_INSTRUMENTATION = "@opentelemetry/instrumentation-pino";
|
|
128
169
|
var LOG_EXPORTERS = /* @__PURE__ */ new Set(["otlp", "console"]);
|
|
129
170
|
var UNKNOWN_SERVICE_NAME = "unknown_service:node";
|
|
@@ -131,6 +172,7 @@ var WARNING_OPTIONS = {
|
|
|
131
172
|
type: "SecurityWarning",
|
|
132
173
|
code: "BYMAX_TELEMETRY_UNSAFE_REDACTION_DISABLED"
|
|
133
174
|
};
|
|
175
|
+
var IGNORED_WARNING = { type: "Warning", code: "BYMAX_TELEMETRY_OPTIONS_IGNORED" };
|
|
134
176
|
function planSignals(env) {
|
|
135
177
|
const overrides = {};
|
|
136
178
|
if (env.metricsExporters.length === 0) overrides.metricReaders = [];
|
|
@@ -180,10 +222,9 @@ function buildInstrumentationConfig(options, signals) {
|
|
|
180
222
|
merged[HTTP_INSTRUMENTATION]["ignoreIncomingRequestHook"] = options.ignoreIncomingRequest;
|
|
181
223
|
}
|
|
182
224
|
if (redactRedis) {
|
|
183
|
-
|
|
184
|
-
...merged[
|
|
185
|
-
|
|
186
|
-
};
|
|
225
|
+
for (const name of [IOREDIS_INSTRUMENTATION, REDIS_INSTRUMENTATION]) {
|
|
226
|
+
merged[name] = { ...merged[name], dbStatementSerializer: serializeRedisCommandName };
|
|
227
|
+
}
|
|
187
228
|
}
|
|
188
229
|
return merged;
|
|
189
230
|
}
|
|
@@ -215,6 +256,15 @@ function warnAboutUnsafeOptions(options) {
|
|
|
215
256
|
);
|
|
216
257
|
}
|
|
217
258
|
}
|
|
259
|
+
function warnAboutIgnoredOptions(options) {
|
|
260
|
+
const stop = options.enabled === false;
|
|
261
|
+
if (stop || Object.values(options).some((v) => v !== void 0)) {
|
|
262
|
+
process.emitWarning(
|
|
263
|
+
stop ? "startTelemetry({ enabled: false }) was called while telemetry is already running. It does not stop the running SDK: call shutdownTelemetry() for that." : "startTelemetry was called while telemetry is already running, so the options of this call were ignored. Pass them to the first call.",
|
|
264
|
+
IGNORED_WARNING
|
|
265
|
+
);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
218
268
|
|
|
219
269
|
// src/sdk/environment.ts
|
|
220
270
|
function readExporterList(raw) {
|
|
@@ -237,7 +287,7 @@ function readTelemetryEnvironment(source = process.env) {
|
|
|
237
287
|
const serviceName = source["OTEL_SERVICE_NAME"]?.trim();
|
|
238
288
|
const detectors = source["OTEL_NODE_RESOURCE_DETECTORS"];
|
|
239
289
|
return {
|
|
240
|
-
sdkDisabled: source["OTEL_SDK_DISABLED"]?.toLowerCase() === "true",
|
|
290
|
+
sdkDisabled: source["OTEL_SDK_DISABLED"]?.trim().toLowerCase() === "true",
|
|
241
291
|
serviceName: serviceName === "" ? void 0 : serviceName,
|
|
242
292
|
metricsExporters: readExporterList(source["OTEL_METRICS_EXPORTER"]),
|
|
243
293
|
logsExporters: readExporterList(source["OTEL_LOGS_EXPORTER"]),
|
|
@@ -246,6 +296,37 @@ function readTelemetryEnvironment(source = process.env) {
|
|
|
246
296
|
};
|
|
247
297
|
}
|
|
248
298
|
|
|
299
|
+
// src/sdk/export-failure.ts
|
|
300
|
+
var WINDOW_MS = 6e4;
|
|
301
|
+
var SUCCESS = 0;
|
|
302
|
+
var CODE_TOKEN = /^[A-Z0-9_]{1,40}$/;
|
|
303
|
+
function codeOf(error) {
|
|
304
|
+
const code = String(Reflect.get(Object(error), "code"));
|
|
305
|
+
return CODE_TOKEN.test(code) ? code : "UNKNOWN";
|
|
306
|
+
}
|
|
307
|
+
function warnOnExportFailure(exporter, kind, clock = () => performance.now()) {
|
|
308
|
+
const original = exporter.export.bind(exporter);
|
|
309
|
+
let lastWarning = Number.NEGATIVE_INFINITY;
|
|
310
|
+
exporter.export = (spans, done) => {
|
|
311
|
+
original(spans, (result) => {
|
|
312
|
+
if (result.code !== SUCCESS && clock() - lastWarning >= WINDOW_MS) {
|
|
313
|
+
lastWarning = clock();
|
|
314
|
+
try {
|
|
315
|
+
const code = codeOf(result.error);
|
|
316
|
+
reportWarning({
|
|
317
|
+
code: "BYMAX_TELEMETRY_EXPORT_FAILED",
|
|
318
|
+
text: `Exporting spans failed (${kind}, code ${code}), so the batch was dropped. This warning repeats at most once a minute. Check that the collector is reachable.`,
|
|
319
|
+
fields: { kind, code }
|
|
320
|
+
});
|
|
321
|
+
} catch {
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
done(result);
|
|
325
|
+
});
|
|
326
|
+
};
|
|
327
|
+
return exporter;
|
|
328
|
+
}
|
|
329
|
+
|
|
249
330
|
// src/sdk/resource-detectors.ts
|
|
250
331
|
var COMMAND_LINE_ATTRIBUTES = ["process.command_args", "process.command_line"];
|
|
251
332
|
var NAMED = /* @__PURE__ */ new Map([
|
|
@@ -294,6 +375,7 @@ function selectResourceDetectors(selection, detectors, keepCommandLine) {
|
|
|
294
375
|
}
|
|
295
376
|
|
|
296
377
|
// src/sdk/start.ts
|
|
378
|
+
var RESTART_MESSAGE = "Telemetry cannot start again after it was shut down in the same process: the modules the first start instrumented stay patched against its tracer provider, so a second SDK would export nothing for them. Start telemetry once per process; in a test suite, start it once in a global setup.";
|
|
297
379
|
var DISABLED_HANDLE = {
|
|
298
380
|
enabled: false,
|
|
299
381
|
shutdown: () => Promise.resolve()
|
|
@@ -301,6 +383,7 @@ var DISABLED_HANDLE = {
|
|
|
301
383
|
async function startTelemetry(options = {}) {
|
|
302
384
|
const env = readTelemetryEnvironment(options.env);
|
|
303
385
|
if (options.enabled === false || env.sdkDisabled) {
|
|
386
|
+
if (currentHandle()?.stopping === false || pendingStart()) warnAboutIgnoredOptions(options);
|
|
304
387
|
return DISABLED_HANDLE;
|
|
305
388
|
}
|
|
306
389
|
let running = currentHandle();
|
|
@@ -309,12 +392,21 @@ async function startTelemetry(options = {}) {
|
|
|
309
392
|
running = currentHandle();
|
|
310
393
|
}
|
|
311
394
|
if (running !== void 0) {
|
|
395
|
+
warnAboutIgnoredOptions(options);
|
|
312
396
|
return running;
|
|
313
397
|
}
|
|
314
398
|
const joined = pendingStart();
|
|
315
399
|
if (joined !== void 0) {
|
|
400
|
+
warnAboutIgnoredOptions(options);
|
|
316
401
|
return joined;
|
|
317
402
|
}
|
|
403
|
+
if (hasStopped()) {
|
|
404
|
+
process.emitWarning(RESTART_MESSAGE, {
|
|
405
|
+
type: "Warning",
|
|
406
|
+
code: "BYMAX_TELEMETRY_RESTART_UNSUPPORTED"
|
|
407
|
+
});
|
|
408
|
+
throw new Error(RESTART_MESSAGE);
|
|
409
|
+
}
|
|
318
410
|
const start = boot(options, env).finally(clearPendingStart);
|
|
319
411
|
setPendingStart(start);
|
|
320
412
|
return start;
|
|
@@ -350,7 +442,7 @@ function buildSdk(packages, options, env) {
|
|
|
350
442
|
// Ordered before the batch processor, so each span is redacted in place before it is exported.
|
|
351
443
|
...options.unsafe?.disableUrlRedaction === true ? [] : [createUrlQueryRedactor()],
|
|
352
444
|
new sdkTrace.BatchSpanProcessor({
|
|
353
|
-
exporter: new exporter.OTLPTraceExporter(),
|
|
445
|
+
exporter: warnOnExportFailure(new exporter.OTLPTraceExporter(), "otlp-http traces"),
|
|
354
446
|
...env.batchSpanProcessor
|
|
355
447
|
})
|
|
356
448
|
],
|
|
@@ -364,7 +456,7 @@ async function boot(options, env) {
|
|
|
364
456
|
warnAboutMissingServiceName(options, env);
|
|
365
457
|
const sdk = buildSdk(await loadPackages(), options, env);
|
|
366
458
|
sdk.start();
|
|
367
|
-
const handle = createHandle(() => sdk.shutdown());
|
|
459
|
+
const handle = createHandle(() => sdk.shutdown(), options.shutdownTimeoutMs);
|
|
368
460
|
registerHandle(handle);
|
|
369
461
|
return handle;
|
|
370
462
|
}
|
package/dist/sdk/index.d.cts
CHANGED
|
@@ -85,6 +85,13 @@ interface TelemetryOptions {
|
|
|
85
85
|
readonly extraRedactedQueryParams?: readonly string[];
|
|
86
86
|
/** Explicit opt-outs from redaction. */
|
|
87
87
|
readonly unsafe?: UnsafeOptions;
|
|
88
|
+
/**
|
|
89
|
+
* The longest `shutdown` waits for the final flush, in milliseconds. A collector that accepts a
|
|
90
|
+
* connection and never answers cannot hold the process past it: shutdown warns with
|
|
91
|
+
* `BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT` and resolves, and spans still queued may be lost. Defaults
|
|
92
|
+
* to 5000; a value that is not a finite number above zero, or is above 120000, means the default.
|
|
93
|
+
*/
|
|
94
|
+
readonly shutdownTimeoutMs?: number;
|
|
88
95
|
/**
|
|
89
96
|
* The environment the library reads, which defaults to the process environment. The OTel SDK
|
|
90
97
|
* reads `OTEL_EXPORTER_OTLP_*` and the sampler variables from the process environment itself.
|
|
@@ -110,8 +117,12 @@ interface TelemetryHandle {
|
|
|
110
117
|
* Only the path is compared: the query string is cut first, so an exclusion cannot be switched off
|
|
111
118
|
* by appending a parameter, and a probe path hidden in a query cannot trigger one. A request with no
|
|
112
119
|
* target is not matched: failing open costs a span nobody wanted, where the opposite silently drops
|
|
113
|
-
* the traffic least likely to be well formed.
|
|
114
|
-
*
|
|
120
|
+
* the traffic least likely to be well formed. A path longer than 2,048 characters is never ignored
|
|
121
|
+
* and the patterns are not run against it, which bounds the work a long path can cause. Anchor
|
|
122
|
+
* the patterns at both ends and give them no nested quantifiers such as `(a+)+`: an unanchored
|
|
123
|
+
* pattern also matches routes that merely contain the word, and the cap does not bound a nested
|
|
124
|
+
* quantifier on a short path: `/^\/(a+)+$/` took 2.5 s and 5.5 s in two runs on 28 characters,
|
|
125
|
+
* and the time grows exponentially with the length.
|
|
115
126
|
*
|
|
116
127
|
* @param patterns - Patterns tested against the path alone.
|
|
117
128
|
* @returns A predicate for `TelemetryOptions.ignoreIncomingRequest`.
|