@safaricom-mxl/node-sdk 0.0.14 → 0.0.16
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/dist/bin/opentelemetry-instrument.cjs +1 -1
- package/dist/bin/opentelemetry-instrument.mjs.map +1 -1
- package/dist/gcp.cjs +1 -1
- package/dist/gcp.mjs +1 -1
- package/dist/index.cjs +4 -3
- package/dist/index.mjs +4 -3
- package/dist/index.mjs.map +1 -1
- package/dist/{initSDK-CIA2rpa5.cjs → initSDK-C-ft2w7-.cjs} +10 -9
- package/dist/{initSDK-BrnRS8th.mjs → initSDK-CajMs1dG.mjs} +10 -9
- package/dist/{initSDK-BrnRS8th.mjs.map → initSDK-CajMs1dG.mjs.map} +1 -1
- package/dist/initSDK-DSRBxu9o.mjs +776 -0
- package/dist/initSDK-DSRBxu9o.mjs.map +1 -0
- package/dist/initSDK-jl3H9NgJ.cjs +827 -0
- package/dist/{json-B-RLbOrx.cjs → json-DSW-bpAR.cjs} +1 -1
- package/dist/logger/evlog.cjs +9 -6
- package/dist/logger/evlog.mjs +9 -6
- package/dist/logger/evlog.mjs.map +1 -1
- package/dist/logger/nest.cjs +1 -1
- package/dist/logger/nest.mjs +1 -1
- package/dist/logger/pino.cjs +3 -3
- package/dist/logger/pino.mjs +1 -1
- package/dist/logger/winston.cjs +3 -3
- package/dist/logger/winston.mjs +1 -1
- package/dist/{otelLogger-DEU-e5Wd.mjs → otelLogger-66qqKXgj.mjs} +2 -2
- package/dist/{otelLogger-DEU-e5Wd.mjs.map → otelLogger-66qqKXgj.mjs.map} +1 -1
- package/dist/{otelLogger-B5z69GWi.cjs → otelLogger-B3PJIZne.cjs} +1 -1
- package/dist/otelLogger-CITnaM4a.mjs +185 -0
- package/dist/otelLogger-CITnaM4a.mjs.map +1 -0
- package/dist/otelLogger-DyoXEc9Z.cjs +260 -0
- package/dist/{rolldown-runtime-D6vf50IK.cjs → rolldown-runtime-VH7oDXx4.cjs} +1 -1
- package/dist/tracing.cjs +1 -1
- package/dist/tracing.mjs +1 -1
- package/package.json +4 -4
|
@@ -0,0 +1,776 @@
|
|
|
1
|
+
import { a as parseHeaderAttributeMap, c as DEFAULT_METRIC_EXPORT_TIMEOUT_MS, d as DEFAULT_TRACE_TIMEOUT_MS, f as NODE_SDK_NAME, i as getStringFromEnv, n as resolveOtlpExporterUrl, o as parseOtlpHeaders, p as NODE_SDK_VERSION, r as getBooleanFromEnv, s as DEFAULT_METRIC_EXPORT_INTERVAL_MS, t as OTelLogger } from "./otelLogger-CITnaM4a.mjs";
|
|
2
|
+
import { parseWinstonLog } from "./logger/winston.mjs";
|
|
3
|
+
import { t as recordException } from "./recordException-DTepFVfN.mjs";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
import opentelemetry, { ROOT_CONTEXT, diag } from "@opentelemetry/api";
|
|
6
|
+
import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION, ATTR_TELEMETRY_SDK_NAME, ATTR_TELEMETRY_SDK_VERSION } from "@opentelemetry/semantic-conventions";
|
|
7
|
+
import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";
|
|
8
|
+
import { RuntimeNodeInstrumentation } from "@opentelemetry/instrumentation-runtime-node";
|
|
9
|
+
import { NodeSDK } from "@opentelemetry/sdk-node";
|
|
10
|
+
import { InstrumentationBase, InstrumentationNodeModuleDefinition } from "@opentelemetry/instrumentation";
|
|
11
|
+
import isObject from "lodash.isobject";
|
|
12
|
+
import isPlainObject from "lodash.isplainobject";
|
|
13
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
14
|
+
import { EventEmitter } from "node:events";
|
|
15
|
+
import { defaultServiceName, resourceFromAttributes } from "@opentelemetry/resources";
|
|
16
|
+
import * as http from "node:http";
|
|
17
|
+
import { PassThrough } from "node:stream";
|
|
18
|
+
import zlib from "node:zlib";
|
|
19
|
+
import { AlwaysOffSampler, AlwaysOnSampler, BatchSpanProcessor, ParentBasedSampler, TraceIdRatioBasedSampler } from "@opentelemetry/sdk-trace-base";
|
|
20
|
+
import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-grpc";
|
|
21
|
+
import { OTLPMetricExporter as OTLPMetricExporter$1 } from "@opentelemetry/exporter-metrics-otlp-proto";
|
|
22
|
+
import { PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
|
|
23
|
+
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-grpc";
|
|
24
|
+
import { OTLPTraceExporter as OTLPTraceExporter$1 } from "@opentelemetry/exporter-trace-otlp-proto";
|
|
25
|
+
//#region src/context/AbstractAsyncHooksContextManager.ts
|
|
26
|
+
const ADD_LISTENER_METHODS = [
|
|
27
|
+
"addListener",
|
|
28
|
+
"on",
|
|
29
|
+
"once",
|
|
30
|
+
"prependListener",
|
|
31
|
+
"prependOnceListener"
|
|
32
|
+
];
|
|
33
|
+
var AbstractAsyncHooksContextManager = class {
|
|
34
|
+
bind(context, target) {
|
|
35
|
+
if (target instanceof EventEmitter) return this._bindEventEmitter(context, target);
|
|
36
|
+
if (typeof target === "function") return this._bindFunction(context, target);
|
|
37
|
+
return target;
|
|
38
|
+
}
|
|
39
|
+
_bindFunction(context, target) {
|
|
40
|
+
const manager = this;
|
|
41
|
+
const contextWrapper = function(...args) {
|
|
42
|
+
return manager.with(context, () => target.apply(this, args));
|
|
43
|
+
};
|
|
44
|
+
Object.defineProperty(contextWrapper, "length", {
|
|
45
|
+
enumerable: false,
|
|
46
|
+
configurable: true,
|
|
47
|
+
writable: false,
|
|
48
|
+
value: target.length
|
|
49
|
+
});
|
|
50
|
+
return contextWrapper;
|
|
51
|
+
}
|
|
52
|
+
_bindEventEmitter(context, ee) {
|
|
53
|
+
if (this._getPatchMap(ee) !== void 0) return ee;
|
|
54
|
+
this._createPatchMap(ee);
|
|
55
|
+
ADD_LISTENER_METHODS.forEach((methodName) => {
|
|
56
|
+
if (ee[methodName] === void 0) return;
|
|
57
|
+
ee[methodName] = this._patchAddListener(ee, ee[methodName], context);
|
|
58
|
+
});
|
|
59
|
+
if (typeof ee.removeListener === "function") ee.removeListener = this._patchRemoveListener(ee, ee.removeListener);
|
|
60
|
+
if (typeof ee.off === "function") ee.off = this._patchRemoveListener(ee, ee.off);
|
|
61
|
+
if (typeof ee.removeAllListeners === "function") ee.removeAllListeners = this._patchRemoveAllListeners(ee, ee.removeAllListeners);
|
|
62
|
+
return ee;
|
|
63
|
+
}
|
|
64
|
+
_patchRemoveListener(ee, original) {
|
|
65
|
+
const contextManager = this;
|
|
66
|
+
return function(event, listener) {
|
|
67
|
+
const events = contextManager._getPatchMap(ee)?.[event];
|
|
68
|
+
if (events === void 0) return original.call(this, event, listener);
|
|
69
|
+
const patchedListener = events.get(listener);
|
|
70
|
+
return original.call(this, event, patchedListener || listener);
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
_patchRemoveAllListeners(ee, original) {
|
|
74
|
+
const contextManager = this;
|
|
75
|
+
return function(event) {
|
|
76
|
+
const map = contextManager._getPatchMap(ee);
|
|
77
|
+
if (map !== void 0) {
|
|
78
|
+
if (arguments.length === 0) contextManager._createPatchMap(ee);
|
|
79
|
+
else if (map[event] !== void 0) delete map[event];
|
|
80
|
+
}
|
|
81
|
+
return original.apply(this, arguments);
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
_patchAddListener(ee, original, context) {
|
|
85
|
+
const contextManager = this;
|
|
86
|
+
return function(event, listener) {
|
|
87
|
+
if (contextManager._wrapped) return original.call(this, event, listener);
|
|
88
|
+
let map = contextManager._getPatchMap(ee);
|
|
89
|
+
if (map === void 0) map = contextManager._createPatchMap(ee);
|
|
90
|
+
let listeners = map[event];
|
|
91
|
+
if (listeners === void 0) {
|
|
92
|
+
listeners = /* @__PURE__ */ new WeakMap();
|
|
93
|
+
map[event] = listeners;
|
|
94
|
+
}
|
|
95
|
+
const patchedListener = contextManager.bind(context, listener);
|
|
96
|
+
listeners.set(listener, patchedListener);
|
|
97
|
+
contextManager._wrapped = true;
|
|
98
|
+
try {
|
|
99
|
+
return original.call(this, event, patchedListener);
|
|
100
|
+
} finally {
|
|
101
|
+
contextManager._wrapped = false;
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
_createPatchMap(ee) {
|
|
106
|
+
const map = Object.create(null);
|
|
107
|
+
ee[this._kOtListeners] = map;
|
|
108
|
+
return map;
|
|
109
|
+
}
|
|
110
|
+
_getPatchMap(ee) {
|
|
111
|
+
return ee[this._kOtListeners];
|
|
112
|
+
}
|
|
113
|
+
_kOtListeners = Symbol("OtListeners");
|
|
114
|
+
_wrapped = false;
|
|
115
|
+
};
|
|
116
|
+
//#endregion
|
|
117
|
+
//#region src/context/MutableAsyncLocalStorageContextManager.ts
|
|
118
|
+
var MutableAsyncLocalStorageContextManager = class extends AbstractAsyncHooksContextManager {
|
|
119
|
+
asyncLocalStorage;
|
|
120
|
+
constructor() {
|
|
121
|
+
super();
|
|
122
|
+
this.asyncLocalStorage = new AsyncLocalStorage();
|
|
123
|
+
}
|
|
124
|
+
active() {
|
|
125
|
+
return this.asyncLocalStorage.getStore()?.context ?? ROOT_CONTEXT;
|
|
126
|
+
}
|
|
127
|
+
with(context, fn, thisArg, ...args) {
|
|
128
|
+
const mutableContext = this.asyncLocalStorage.getStore()?.mutableContext ?? { traceAttributes: /* @__PURE__ */ new Map() };
|
|
129
|
+
const callback = thisArg == null ? fn : fn.bind(thisArg);
|
|
130
|
+
return this.asyncLocalStorage.run({
|
|
131
|
+
context,
|
|
132
|
+
mutableContext
|
|
133
|
+
}, callback, ...args);
|
|
134
|
+
}
|
|
135
|
+
getMutableContext() {
|
|
136
|
+
return this.asyncLocalStorage.getStore()?.mutableContext;
|
|
137
|
+
}
|
|
138
|
+
enable() {
|
|
139
|
+
return this;
|
|
140
|
+
}
|
|
141
|
+
disable() {
|
|
142
|
+
this.asyncLocalStorage.disable();
|
|
143
|
+
return this;
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
//#endregion
|
|
147
|
+
//#region src/context/contextManager.ts
|
|
148
|
+
let mutableContextManager;
|
|
149
|
+
function setMutableContextManager(manager) {
|
|
150
|
+
mutableContextManager = manager;
|
|
151
|
+
}
|
|
152
|
+
function setTraceAttributes(attributes) {
|
|
153
|
+
const mutableContext = mutableContextManager?.getMutableContext();
|
|
154
|
+
if (!mutableContext) return;
|
|
155
|
+
for (const [key, value] of Object.entries(attributes)) mutableContext.traceAttributes.set(key, value);
|
|
156
|
+
}
|
|
157
|
+
function getTraceAttributes() {
|
|
158
|
+
const mutableContext = mutableContextManager?.getMutableContext();
|
|
159
|
+
if (!mutableContext) return {};
|
|
160
|
+
return Object.fromEntries(mutableContext.traceAttributes);
|
|
161
|
+
}
|
|
162
|
+
//#endregion
|
|
163
|
+
//#region src/instrumentations/console.ts
|
|
164
|
+
const PACKAGE_NAME = "@safaricom-mxl/instrumentation-console";
|
|
165
|
+
const PACKAGE_VERSION = "0.0.4";
|
|
166
|
+
function parseConsoleArgs(args) {
|
|
167
|
+
const stringified = [];
|
|
168
|
+
let firstObject;
|
|
169
|
+
for (const arg of args) {
|
|
170
|
+
if (isObject(arg)) {
|
|
171
|
+
if (!firstObject && isPlainObject(arg)) firstObject = arg;
|
|
172
|
+
try {
|
|
173
|
+
stringified.push(JSON.stringify(arg));
|
|
174
|
+
} catch {}
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
stringified.push(arg);
|
|
178
|
+
}
|
|
179
|
+
return firstObject ? {
|
|
180
|
+
...firstObject,
|
|
181
|
+
...args.length > 1 ? { message: stringified.join(" ") } : {}
|
|
182
|
+
} : stringified.join(" ");
|
|
183
|
+
}
|
|
184
|
+
var ConsoleInstrumentation = class extends InstrumentationBase {
|
|
185
|
+
otelLogger;
|
|
186
|
+
constructor(config) {
|
|
187
|
+
super(PACKAGE_NAME, PACKAGE_VERSION, config);
|
|
188
|
+
this.otelLogger = new OTelLogger({ config: config.config });
|
|
189
|
+
}
|
|
190
|
+
patchConsoleMethod(type, ...args) {
|
|
191
|
+
const level = type === "log" ? "info" : type;
|
|
192
|
+
const parsed = parseWinstonLog({
|
|
193
|
+
message: parseConsoleArgs(args),
|
|
194
|
+
level
|
|
195
|
+
});
|
|
196
|
+
const spanContext = opentelemetry.trace.getActiveSpan()?.spanContext();
|
|
197
|
+
let attributes = {
|
|
198
|
+
...parsed.meta,
|
|
199
|
+
...spanContext ? {
|
|
200
|
+
trace_id: spanContext.traceId,
|
|
201
|
+
span_id: spanContext.spanId,
|
|
202
|
+
trace_flags: spanContext.traceFlags
|
|
203
|
+
} : {}
|
|
204
|
+
};
|
|
205
|
+
if (this.getConfig().config.betaMode) attributes = {
|
|
206
|
+
...attributes,
|
|
207
|
+
...getTraceAttributes()
|
|
208
|
+
};
|
|
209
|
+
this.otelLogger.postMessage(parsed.level, parsed.message, attributes);
|
|
210
|
+
}
|
|
211
|
+
wrapHandler(type, original) {
|
|
212
|
+
return (...args) => {
|
|
213
|
+
this.patchConsoleMethod(type, ...args);
|
|
214
|
+
return original.apply(this, args);
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
onPatch(moduleExports) {
|
|
218
|
+
this._wrap(moduleExports, "debug", (original) => this.wrapHandler("debug", original));
|
|
219
|
+
this._wrap(moduleExports, "log", (original) => this.wrapHandler("log", original));
|
|
220
|
+
this._wrap(moduleExports, "info", (original) => this.wrapHandler("info", original));
|
|
221
|
+
this._wrap(moduleExports, "warn", (original) => this.wrapHandler("warn", original));
|
|
222
|
+
this._wrap(moduleExports, "error", (original) => this.wrapHandler("error", original));
|
|
223
|
+
return moduleExports;
|
|
224
|
+
}
|
|
225
|
+
onUnpatch(moduleExports) {
|
|
226
|
+
this._unwrap(moduleExports, "debug");
|
|
227
|
+
this._unwrap(moduleExports, "log");
|
|
228
|
+
this._unwrap(moduleExports, "info");
|
|
229
|
+
this._unwrap(moduleExports, "warn");
|
|
230
|
+
this._unwrap(moduleExports, "error");
|
|
231
|
+
}
|
|
232
|
+
init() {
|
|
233
|
+
return [new InstrumentationNodeModuleDefinition("console", ["*"], (moduleExports) => this.onPatch(moduleExports), (moduleExports) => {
|
|
234
|
+
this.onUnpatch(moduleExports);
|
|
235
|
+
return moduleExports;
|
|
236
|
+
})];
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
//#endregion
|
|
240
|
+
//#region src/instrumentations/exceptions/ExceptionInstrumentation.ts
|
|
241
|
+
var ExceptionInstrumentation = class extends InstrumentationBase {
|
|
242
|
+
forceFlush;
|
|
243
|
+
uncaughtExceptionListener;
|
|
244
|
+
unhandledRejectionListener;
|
|
245
|
+
constructor(config = {}) {
|
|
246
|
+
super("@safaricom-mxl/instrumentation-exception", "0.0.4", config);
|
|
247
|
+
this.forceFlush = config.forceFlush;
|
|
248
|
+
}
|
|
249
|
+
init() {}
|
|
250
|
+
enable() {
|
|
251
|
+
const config = this.getConfig();
|
|
252
|
+
const rejectionMode = config.unhandledRejectionMode ?? "warn";
|
|
253
|
+
this.uncaughtExceptionListener = (error) => {
|
|
254
|
+
config.captureExceptionHook?.(error);
|
|
255
|
+
recordException(error).finally(() => {
|
|
256
|
+
config.forceFlush?.() ?? this.forceFlush?.();
|
|
257
|
+
});
|
|
258
|
+
if (config.exitEvenIfOtherHandlersAreRegistered) process.exitCode = 1;
|
|
259
|
+
};
|
|
260
|
+
this.unhandledRejectionListener = (reason) => {
|
|
261
|
+
config.captureExceptionHook?.(reason);
|
|
262
|
+
recordException(reason).finally(() => {
|
|
263
|
+
if (rejectionMode === "warn") console.warn("Unhandled promise rejection captured by MXL Node SDK. Set unhandledRejectionMode=strict to terminate the process.");
|
|
264
|
+
if (rejectionMode === "strict") (config.forceFlush?.() ?? this.forceFlush?.()).finally(() => {
|
|
265
|
+
process.exitCode = 1;
|
|
266
|
+
});
|
|
267
|
+
});
|
|
268
|
+
};
|
|
269
|
+
process.on("uncaughtException", this.uncaughtExceptionListener);
|
|
270
|
+
process.on("unhandledRejection", this.unhandledRejectionListener);
|
|
271
|
+
}
|
|
272
|
+
disable() {
|
|
273
|
+
if (this.uncaughtExceptionListener) process.off("uncaughtException", this.uncaughtExceptionListener);
|
|
274
|
+
if (this.unhandledRejectionListener) process.off("unhandledRejection", this.unhandledRejectionListener);
|
|
275
|
+
this.uncaughtExceptionListener = void 0;
|
|
276
|
+
this.unhandledRejectionListener = void 0;
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
//#endregion
|
|
280
|
+
//#region src/instrumentations/exceptions/sentry.ts
|
|
281
|
+
const require = createRequire(import.meta.url);
|
|
282
|
+
function createSentryBridge(enabled) {
|
|
283
|
+
if (!enabled) return;
|
|
284
|
+
try {
|
|
285
|
+
const sentry = require("@sentry/node");
|
|
286
|
+
return { captureException(error) {
|
|
287
|
+
sentry.captureException(error);
|
|
288
|
+
} };
|
|
289
|
+
} catch {
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
//#endregion
|
|
294
|
+
//#region src/instrumentations/http.ts
|
|
295
|
+
const SENSITIVE_DATA_SUBSTITUTE = "[Filtered]";
|
|
296
|
+
const DEFAULT_DENYLIST = [
|
|
297
|
+
"password",
|
|
298
|
+
"passwd",
|
|
299
|
+
"secret",
|
|
300
|
+
"api_key",
|
|
301
|
+
"apikey",
|
|
302
|
+
"auth",
|
|
303
|
+
"credentials",
|
|
304
|
+
"private_key",
|
|
305
|
+
"token",
|
|
306
|
+
"session",
|
|
307
|
+
"cookie",
|
|
308
|
+
"authorization",
|
|
309
|
+
"x_api_key",
|
|
310
|
+
"_csrf",
|
|
311
|
+
"phpsessid",
|
|
312
|
+
"xsrf-token"
|
|
313
|
+
];
|
|
314
|
+
function captureSelectedHeaders(span, prefix, headers, getter) {
|
|
315
|
+
for (const header of headers) {
|
|
316
|
+
const value = getter(header);
|
|
317
|
+
if (Array.isArray(value)) span.setAttribute(`http.${prefix}.header.${header.toLowerCase()}`, value.join(","));
|
|
318
|
+
else if (value != null) span.setAttribute(`http.${prefix}.header.${header.toLowerCase()}`, String(value));
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
function splitCommaSeparatedStrings(headers) {
|
|
322
|
+
return headers?.split(",").map((header) => header.trim()).filter(Boolean);
|
|
323
|
+
}
|
|
324
|
+
function getShouldRecordBody(defaultFilter) {
|
|
325
|
+
return (body) => {
|
|
326
|
+
const lowerCaseBody = body.toLowerCase();
|
|
327
|
+
return !(splitCommaSeparatedStrings(defaultFilter)?.map((item) => item.toLowerCase()) ?? DEFAULT_DENYLIST).some((keyword) => lowerCaseBody.includes(keyword));
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
function interceptReadableStream(stream, passThrough) {
|
|
331
|
+
const originalState = stream.readableFlowing;
|
|
332
|
+
stream.pipe(passThrough);
|
|
333
|
+
stream.readableFlowing = originalState ?? false;
|
|
334
|
+
return stream;
|
|
335
|
+
}
|
|
336
|
+
function captureBodyAttribute({ targetSpan, attributeName, body, shouldRecordBody }) {
|
|
337
|
+
targetSpan.setAttribute(attributeName, shouldRecordBody(body) ? body : SENSITIVE_DATA_SUBSTITUTE);
|
|
338
|
+
}
|
|
339
|
+
function handleOutgoingClientRequest({ request, span, shouldRecordBody, captureHeaders }) {
|
|
340
|
+
try {
|
|
341
|
+
captureSelectedHeaders(span, "request", splitCommaSeparatedStrings(captureHeaders) ?? request.getRawHeaderNames(), (header) => request.getHeader(header));
|
|
342
|
+
} catch (error) {
|
|
343
|
+
diag.debug("Failed to capture outgoing request headers", error);
|
|
344
|
+
}
|
|
345
|
+
const chunks = [];
|
|
346
|
+
const oldWrite = request.write.bind(request);
|
|
347
|
+
request.write = ((data) => {
|
|
348
|
+
chunks.push(Buffer.isBuffer(data) ? data : Buffer.from(String(data)));
|
|
349
|
+
return oldWrite(data);
|
|
350
|
+
});
|
|
351
|
+
const oldEnd = request.end.bind(request);
|
|
352
|
+
request.end = ((data) => {
|
|
353
|
+
if (data != null) chunks.push(Buffer.isBuffer(data) ? data : Buffer.from(String(data)));
|
|
354
|
+
if (chunks.length > 0) captureBodyAttribute({
|
|
355
|
+
targetSpan: span,
|
|
356
|
+
attributeName: "http.request.body",
|
|
357
|
+
body: Buffer.concat(chunks).toString("utf8"),
|
|
358
|
+
shouldRecordBody
|
|
359
|
+
});
|
|
360
|
+
return oldEnd(data);
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
function handleIncomingServerRequest({ request, span, shouldRecordBody, captureHeaders, headerAttributeMap }) {
|
|
364
|
+
try {
|
|
365
|
+
captureSelectedHeaders(span, "request", splitCommaSeparatedStrings(captureHeaders) ?? Object.keys(request.headers), (header) => request.headers[header]);
|
|
366
|
+
} catch (error) {
|
|
367
|
+
diag.debug("Failed to capture incoming request headers", error);
|
|
368
|
+
}
|
|
369
|
+
if (headerAttributeMap) for (const [headerName, attributeName] of Object.entries(headerAttributeMap)) {
|
|
370
|
+
const value = request.headers[headerName];
|
|
371
|
+
if (Array.isArray(value)) span.setAttribute(attributeName, value.join(","));
|
|
372
|
+
else if (value) span.setAttribute(attributeName, value);
|
|
373
|
+
}
|
|
374
|
+
const chunks = [];
|
|
375
|
+
const passThrough = new PassThrough();
|
|
376
|
+
passThrough.on("data", (chunk) => {
|
|
377
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
|
|
378
|
+
});
|
|
379
|
+
passThrough.on("end", () => {
|
|
380
|
+
if (chunks.length === 0) return;
|
|
381
|
+
captureBodyAttribute({
|
|
382
|
+
targetSpan: span,
|
|
383
|
+
attributeName: "http.request.body",
|
|
384
|
+
body: Buffer.concat(chunks).toString("utf8"),
|
|
385
|
+
shouldRecordBody
|
|
386
|
+
});
|
|
387
|
+
});
|
|
388
|
+
interceptReadableStream(request, passThrough);
|
|
389
|
+
}
|
|
390
|
+
function handleIncomingServerResponse({ response, span, shouldRecordBody, captureHeaders }) {
|
|
391
|
+
const chunks = [];
|
|
392
|
+
const oldWrite = response.write.bind(response);
|
|
393
|
+
response.write = ((data) => {
|
|
394
|
+
chunks.push(Buffer.isBuffer(data) ? data : Buffer.from(String(data)));
|
|
395
|
+
return oldWrite(data);
|
|
396
|
+
});
|
|
397
|
+
const oldEnd = response.end.bind(response);
|
|
398
|
+
response.end = ((data) => {
|
|
399
|
+
if (data != null) chunks.push(Buffer.isBuffer(data) ? data : Buffer.from(String(data)));
|
|
400
|
+
if (chunks.length > 0) {
|
|
401
|
+
const payload = Buffer.concat(chunks);
|
|
402
|
+
captureBodyAttribute({
|
|
403
|
+
targetSpan: span,
|
|
404
|
+
attributeName: "http.response.body",
|
|
405
|
+
body: (response.getHeader("content-encoding") === "gzip" ? zlib.gunzipSync(payload) : payload).toString("utf8"),
|
|
406
|
+
shouldRecordBody
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
try {
|
|
410
|
+
captureSelectedHeaders(span, "response", splitCommaSeparatedStrings(captureHeaders) ?? response.getHeaderNames(), (header) => response.getHeader(header));
|
|
411
|
+
} catch (error) {
|
|
412
|
+
diag.debug("Failed to capture incoming response headers", error);
|
|
413
|
+
}
|
|
414
|
+
return oldEnd(data);
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
function handleOutgoingClientResponse({ response, span, shouldRecordBody, captureHeaders }) {
|
|
418
|
+
try {
|
|
419
|
+
captureSelectedHeaders(span, "response", splitCommaSeparatedStrings(captureHeaders) ?? Object.keys(response.headers), (header) => response.headers[header]);
|
|
420
|
+
} catch (error) {
|
|
421
|
+
diag.debug("Failed to capture outgoing response headers", error);
|
|
422
|
+
}
|
|
423
|
+
const chunks = [];
|
|
424
|
+
const passThrough = new PassThrough();
|
|
425
|
+
passThrough.on("data", (chunk) => {
|
|
426
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
|
|
427
|
+
});
|
|
428
|
+
passThrough.on("end", () => {
|
|
429
|
+
if (chunks.length === 0) return;
|
|
430
|
+
const payload = Buffer.concat(chunks);
|
|
431
|
+
captureBodyAttribute({
|
|
432
|
+
targetSpan: span,
|
|
433
|
+
attributeName: "http.response.body",
|
|
434
|
+
body: (response.headers["content-encoding"] === "gzip" ? zlib.gunzipSync(payload) : payload).toString("utf8"),
|
|
435
|
+
shouldRecordBody
|
|
436
|
+
});
|
|
437
|
+
});
|
|
438
|
+
interceptReadableStream(response, passThrough);
|
|
439
|
+
}
|
|
440
|
+
function getAdvancedHttpInstrumentationConfig({ captureBodyKeywordsFilter, captureHeadersClientRequest, captureHeadersClientResponse, captureHeadersServerRequest, captureHeadersServerResponse, headerAttributeMap }) {
|
|
441
|
+
const shouldRecordBody = getShouldRecordBody(captureBodyKeywordsFilter);
|
|
442
|
+
return {
|
|
443
|
+
requestHook(span, request) {
|
|
444
|
+
if (request instanceof http.ClientRequest) handleOutgoingClientRequest({
|
|
445
|
+
request,
|
|
446
|
+
span,
|
|
447
|
+
shouldRecordBody,
|
|
448
|
+
captureHeaders: captureHeadersClientRequest
|
|
449
|
+
});
|
|
450
|
+
else handleIncomingServerRequest({
|
|
451
|
+
request,
|
|
452
|
+
span,
|
|
453
|
+
shouldRecordBody,
|
|
454
|
+
captureHeaders: captureHeadersServerRequest,
|
|
455
|
+
headerAttributeMap
|
|
456
|
+
});
|
|
457
|
+
},
|
|
458
|
+
responseHook(span, response) {
|
|
459
|
+
if (response instanceof http.ServerResponse) handleIncomingServerResponse({
|
|
460
|
+
response,
|
|
461
|
+
span,
|
|
462
|
+
shouldRecordBody,
|
|
463
|
+
captureHeaders: captureHeadersServerResponse
|
|
464
|
+
});
|
|
465
|
+
else handleOutgoingClientResponse({
|
|
466
|
+
response,
|
|
467
|
+
span,
|
|
468
|
+
shouldRecordBody,
|
|
469
|
+
captureHeaders: captureHeadersClientResponse
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
//#endregion
|
|
475
|
+
//#region src/processors/CompositeSpanProcessor.ts
|
|
476
|
+
var CompositeSpanProcessor = class {
|
|
477
|
+
processors;
|
|
478
|
+
constructor(processors) {
|
|
479
|
+
this.processors = processors;
|
|
480
|
+
}
|
|
481
|
+
forceFlush() {
|
|
482
|
+
return Promise.all(this.processors.map((processor) => processor.forceFlush().catch((error) => {
|
|
483
|
+
diag.error("@safaricom-mxl/node-sdk: forceFlush failed", error);
|
|
484
|
+
}))).then(() => void 0);
|
|
485
|
+
}
|
|
486
|
+
shutdown() {
|
|
487
|
+
return Promise.all(this.processors.map((processor) => processor.shutdown().catch((error) => {
|
|
488
|
+
diag.error("@safaricom-mxl/node-sdk: shutdown failed", error);
|
|
489
|
+
}))).then(() => void 0);
|
|
490
|
+
}
|
|
491
|
+
onStart(span, parentContext) {
|
|
492
|
+
for (const processor of this.processors) processor.onStart(span, parentContext);
|
|
493
|
+
}
|
|
494
|
+
onEnd(span) {
|
|
495
|
+
for (const processor of this.processors) processor.onEnd(span);
|
|
496
|
+
}
|
|
497
|
+
};
|
|
498
|
+
//#endregion
|
|
499
|
+
//#region src/processors/FilterWhenDrainedSpanProcessor.ts
|
|
500
|
+
var FilterWhenDrainedSpanProcessor = class {
|
|
501
|
+
delegate;
|
|
502
|
+
drained = false;
|
|
503
|
+
constructor(delegate) {
|
|
504
|
+
this.delegate = delegate;
|
|
505
|
+
}
|
|
506
|
+
drain() {
|
|
507
|
+
this.drained = true;
|
|
508
|
+
}
|
|
509
|
+
onStart(span, parentContext) {
|
|
510
|
+
if (this.drained) return;
|
|
511
|
+
this.delegate.onStart(span, parentContext);
|
|
512
|
+
}
|
|
513
|
+
onEnd(span) {
|
|
514
|
+
if (this.drained) return;
|
|
515
|
+
this.delegate.onEnd(span);
|
|
516
|
+
}
|
|
517
|
+
forceFlush() {
|
|
518
|
+
return this.delegate.forceFlush();
|
|
519
|
+
}
|
|
520
|
+
shutdown() {
|
|
521
|
+
this.drained = true;
|
|
522
|
+
return this.delegate.shutdown();
|
|
523
|
+
}
|
|
524
|
+
};
|
|
525
|
+
//#endregion
|
|
526
|
+
//#region src/processors/NodeSpanProcessor.ts
|
|
527
|
+
var NodeSpanProcessor = class extends BatchSpanProcessor {
|
|
528
|
+
constructor(exporter) {
|
|
529
|
+
super(exporter);
|
|
530
|
+
}
|
|
531
|
+
applyTraceAttributes(span) {
|
|
532
|
+
const attributes = getTraceAttributes();
|
|
533
|
+
for (const [key, value] of Object.entries(attributes)) if (span.attributes[key] == null) span.setAttribute(key, value);
|
|
534
|
+
}
|
|
535
|
+
onStart(span, parentContext) {
|
|
536
|
+
this.applyTraceAttributes(span);
|
|
537
|
+
super.onStart(span, parentContext);
|
|
538
|
+
}
|
|
539
|
+
onEnd(span) {
|
|
540
|
+
span._ended = false;
|
|
541
|
+
this.applyTraceAttributes(span);
|
|
542
|
+
span._ended = true;
|
|
543
|
+
super.onEnd(span);
|
|
544
|
+
}
|
|
545
|
+
};
|
|
546
|
+
//#endregion
|
|
547
|
+
//#region src/resources/nodeSdkResource.ts
|
|
548
|
+
function createNodeSdkResource(config) {
|
|
549
|
+
return resourceFromAttributes({
|
|
550
|
+
[ATTR_SERVICE_NAME]: config.serviceName || defaultServiceName(),
|
|
551
|
+
[ATTR_SERVICE_VERSION]: process.env.VERCEL_DEPLOYMENT_ID ?? process.env.npm_package_version,
|
|
552
|
+
[ATTR_TELEMETRY_SDK_NAME]: NODE_SDK_NAME,
|
|
553
|
+
[ATTR_TELEMETRY_SDK_VERSION]: NODE_SDK_VERSION,
|
|
554
|
+
"telemetry.distro.name": "mxl-node-sdk",
|
|
555
|
+
"telemetry.distro.version": NODE_SDK_VERSION,
|
|
556
|
+
...config.additionalResourceAttributes
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
//#endregion
|
|
560
|
+
//#region src/exporters/metricReader.ts
|
|
561
|
+
function createMetricReader(config) {
|
|
562
|
+
const url = resolveOtlpExporterUrl({
|
|
563
|
+
kind: "metric",
|
|
564
|
+
endpoint: config.otlpEndpoint
|
|
565
|
+
});
|
|
566
|
+
const headers = parseOtlpHeaders(config.otlpHeaders);
|
|
567
|
+
const exporter = config.otlpProtocol === "grpc" ? new OTLPMetricExporter({
|
|
568
|
+
url,
|
|
569
|
+
headers
|
|
570
|
+
}) : new OTLPMetricExporter$1({
|
|
571
|
+
url,
|
|
572
|
+
headers
|
|
573
|
+
});
|
|
574
|
+
return new PeriodicExportingMetricReader({
|
|
575
|
+
exporter,
|
|
576
|
+
exportIntervalMillis: DEFAULT_METRIC_EXPORT_INTERVAL_MS,
|
|
577
|
+
exportTimeoutMillis: DEFAULT_METRIC_EXPORT_TIMEOUT_MS
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
//#endregion
|
|
581
|
+
//#region src/exporters/traceExporter.ts
|
|
582
|
+
function createTraceExporter(config) {
|
|
583
|
+
const url = resolveOtlpExporterUrl({
|
|
584
|
+
kind: "trace",
|
|
585
|
+
endpoint: config.otlpEndpoint,
|
|
586
|
+
explicitUrl: config.traceExporterUrl
|
|
587
|
+
});
|
|
588
|
+
const headers = parseOtlpHeaders(config.otlpHeaders);
|
|
589
|
+
if (config.otlpProtocol === "grpc") return new OTLPTraceExporter({
|
|
590
|
+
url,
|
|
591
|
+
timeoutMillis: DEFAULT_TRACE_TIMEOUT_MS,
|
|
592
|
+
headers
|
|
593
|
+
});
|
|
594
|
+
return new OTLPTraceExporter$1({
|
|
595
|
+
url,
|
|
596
|
+
timeoutMillis: DEFAULT_TRACE_TIMEOUT_MS,
|
|
597
|
+
headers
|
|
598
|
+
});
|
|
599
|
+
}
|
|
600
|
+
//#endregion
|
|
601
|
+
//#region src/sdk/sampler.ts
|
|
602
|
+
const DEFAULT_RATIO = 1;
|
|
603
|
+
function resolveTraceSampler(traceSampler, traceSamplerArg) {
|
|
604
|
+
if (typeof traceSampler !== "string") return traceSampler;
|
|
605
|
+
switch (traceSampler) {
|
|
606
|
+
case "always_on": return new AlwaysOnSampler();
|
|
607
|
+
case "always_off": return new AlwaysOffSampler();
|
|
608
|
+
case "parentbased_always_on": return new ParentBasedSampler({ root: new AlwaysOnSampler() });
|
|
609
|
+
case "parentbased_always_off": return new ParentBasedSampler({ root: new AlwaysOffSampler() });
|
|
610
|
+
case "traceidratio": return new TraceIdRatioBasedSampler(resolveSamplerRatio(traceSamplerArg));
|
|
611
|
+
case "parentbased_traceidratio": return new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(resolveSamplerRatio(traceSamplerArg)) });
|
|
612
|
+
default:
|
|
613
|
+
diag.error(`@safaricom-mxl/node-sdk: unknown sampler "${traceSampler}", defaulting to always_on`);
|
|
614
|
+
return new AlwaysOnSampler();
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
function resolveSamplerRatio(arg) {
|
|
618
|
+
const parsed = Number(arg);
|
|
619
|
+
if (!Number.isFinite(parsed) || parsed < 0 || parsed > 1) return DEFAULT_RATIO;
|
|
620
|
+
return parsed;
|
|
621
|
+
}
|
|
622
|
+
//#endregion
|
|
623
|
+
//#region src/sdk/config.ts
|
|
624
|
+
function resolveSDKConfig(config = {}) {
|
|
625
|
+
return {
|
|
626
|
+
additionalInstrumentations: config.additionalInstrumentations ?? [],
|
|
627
|
+
additionalResourceAttributes: config.additionalResourceAttributes ?? {},
|
|
628
|
+
advancedNetworkCapture: config.advancedNetworkCapture ?? getBooleanFromEnv("MXL_NODE_ADVANCED_NETWORK_CAPTURE") ?? false,
|
|
629
|
+
apiKey: config.apiKey ?? getStringFromEnv("MXL_API_KEY"),
|
|
630
|
+
betaMode: config.betaMode ?? getBooleanFromEnv("MXL_NODE_BETA_MODE") ?? false,
|
|
631
|
+
captureBodyKeywordsFilter: config.captureBodyKeywordsFilter ?? getStringFromEnv("OTEL_INSTRUMENTATION_HTTP_CAPTURE_BODY_KEYWORDS_FILTER") ?? "",
|
|
632
|
+
captureHeadersClientRequest: config.captureHeadersClientRequest ?? getStringFromEnv("OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_CLIENT_REQUEST") ?? "",
|
|
633
|
+
captureHeadersClientResponse: config.captureHeadersClientResponse ?? getStringFromEnv("OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_CLIENT_RESPONSE") ?? "",
|
|
634
|
+
captureHeadersServerRequest: config.captureHeadersServerRequest ?? getStringFromEnv("OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST") ?? "",
|
|
635
|
+
captureHeadersServerResponse: config.captureHeadersServerResponse ?? getStringFromEnv("OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE") ?? "",
|
|
636
|
+
consoleCapture: config.consoleCapture ?? getBooleanFromEnv("MXL_NODE_CONSOLE_CAPTURE") ?? true,
|
|
637
|
+
contextManager: config.contextManager,
|
|
638
|
+
detectResources: config.detectResources ?? true,
|
|
639
|
+
disableLogs: config.disableLogs ?? getStringFromEnv("OTEL_LOGS_EXPORTER") === "none",
|
|
640
|
+
disableMetrics: config.disableMetrics ?? getStringFromEnv("OTEL_METRICS_EXPORTER") === "none",
|
|
641
|
+
disableStartupLogs: config.disableStartupLogs ?? !(getBooleanFromEnv("MXL_STARTUP_LOGS") ?? true),
|
|
642
|
+
disableTracing: config.disableTracing ?? getStringFromEnv("OTEL_TRACES_EXPORTER") === "none",
|
|
643
|
+
exceptionCaptureEnabled: config.exceptionCaptureEnabled ?? getBooleanFromEnv("MXL_NODE_EXPERIMENTAL_EXCEPTION_CAPTURE") ?? true,
|
|
644
|
+
headerAttributeMap: config.headerAttributeMap ?? parseHeaderAttributeMap(getStringFromEnv("MXL_NODE_ROOT_SPAN_HEADER_ATTRIBUTES")),
|
|
645
|
+
instrumentations: config.instrumentations,
|
|
646
|
+
metricReader: config.metricReader,
|
|
647
|
+
otlpEndpoint: config.otlpEndpoint ?? getStringFromEnv("OTEL_EXPORTER_OTLP_ENDPOINT"),
|
|
648
|
+
otlpHeaders: config.otlpHeaders ?? getStringFromEnv("OTEL_EXPORTER_OTLP_HEADERS"),
|
|
649
|
+
otlpProtocol: config.otlpProtocol ?? getStringFromEnv("OTEL_EXPORTER_OTLP_PROTOCOL") ?? "http/protobuf",
|
|
650
|
+
sentryIntegrationEnabled: config.sentryIntegrationEnabled ?? getBooleanFromEnv("MXL_NODE_SENTRY_INTEGRATION_ENABLED") ?? false,
|
|
651
|
+
serviceName: config.serviceName ?? getStringFromEnv("OTEL_SERVICE_NAME") ?? "app",
|
|
652
|
+
spanLimits: config.spanLimits,
|
|
653
|
+
spanProcessors: config.spanProcessors ?? [],
|
|
654
|
+
stopOnTerminationSignals: config.stopOnTerminationSignals ?? getBooleanFromEnv("MXL_NODE_STOP_ON_TERMINATION_SIGNALS") ?? true,
|
|
655
|
+
traceExporterUrl: config.traceExporterUrl ?? getStringFromEnv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"),
|
|
656
|
+
traceSampler: config.traceSampler ?? getStringFromEnv("OTEL_TRACES_SAMPLER") ?? "parentbased_always_on",
|
|
657
|
+
traceSamplerArg: config.traceSamplerArg ?? getStringFromEnv("OTEL_TRACES_SAMPLER_ARG") ?? "1"
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
//#endregion
|
|
661
|
+
//#region src/sdk/state.ts
|
|
662
|
+
let activeConfig;
|
|
663
|
+
function setActiveSDKConfig(config) {
|
|
664
|
+
activeConfig = config;
|
|
665
|
+
}
|
|
666
|
+
function getActiveSDKConfig() {
|
|
667
|
+
return activeConfig;
|
|
668
|
+
}
|
|
669
|
+
//#endregion
|
|
670
|
+
//#region src/sdk/initSDK.ts
|
|
671
|
+
let sdk;
|
|
672
|
+
let logger;
|
|
673
|
+
let contextManager;
|
|
674
|
+
let drainableSpanProcessor;
|
|
675
|
+
let signalHandlersRegistered = false;
|
|
676
|
+
const terminationHandlers = [];
|
|
677
|
+
function initSDK(config = {}) {
|
|
678
|
+
const resolved = resolveSDKConfig(config);
|
|
679
|
+
setActiveSDKConfig(resolved);
|
|
680
|
+
if (sdk) return getControl();
|
|
681
|
+
if (!resolved.disableStartupLogs) diag.info("@safaricom-mxl/node-sdk: initializing");
|
|
682
|
+
contextManager = resolved.contextManager instanceof MutableAsyncLocalStorageContextManager ? resolved.contextManager : new MutableAsyncLocalStorageContextManager();
|
|
683
|
+
setMutableContextManager(contextManager);
|
|
684
|
+
const autoInstrumentationConfig = {
|
|
685
|
+
"@opentelemetry/instrumentation-http": resolved.advancedNetworkCapture ? getAdvancedHttpInstrumentationConfig({
|
|
686
|
+
captureBodyKeywordsFilter: resolved.captureBodyKeywordsFilter,
|
|
687
|
+
captureHeadersClientRequest: resolved.captureHeadersClientRequest,
|
|
688
|
+
captureHeadersClientResponse: resolved.captureHeadersClientResponse,
|
|
689
|
+
captureHeadersServerRequest: resolved.captureHeadersServerRequest,
|
|
690
|
+
captureHeadersServerResponse: resolved.captureHeadersServerResponse,
|
|
691
|
+
headerAttributeMap: resolved.headerAttributeMap
|
|
692
|
+
}) : { enabled: true },
|
|
693
|
+
"@opentelemetry/instrumentation-fs": { enabled: false },
|
|
694
|
+
...resolved.instrumentations ?? {}
|
|
695
|
+
};
|
|
696
|
+
logger = new OTelLogger({ config: resolved });
|
|
697
|
+
const traceProcessor = new NodeSpanProcessor(createTraceExporter(resolved));
|
|
698
|
+
const spanProcessors = resolved.disableTracing ? [] : [drainableSpanProcessor = new FilterWhenDrainedSpanProcessor(new CompositeSpanProcessor([traceProcessor, ...resolved.spanProcessors]))];
|
|
699
|
+
const instrumentations = [
|
|
700
|
+
...getNodeAutoInstrumentations(autoInstrumentationConfig),
|
|
701
|
+
new RuntimeNodeInstrumentation(),
|
|
702
|
+
...resolved.consoleCapture ? [new ConsoleInstrumentation({ config: resolved })] : [],
|
|
703
|
+
...resolved.exceptionCaptureEnabled ? [new ExceptionInstrumentation({
|
|
704
|
+
forceFlush,
|
|
705
|
+
captureExceptionHook: createSentryBridge(resolved.sentryIntegrationEnabled)?.captureException
|
|
706
|
+
})] : [],
|
|
707
|
+
...resolved.additionalInstrumentations
|
|
708
|
+
];
|
|
709
|
+
sdk = new NodeSDK({
|
|
710
|
+
resource: createNodeSdkResource(resolved),
|
|
711
|
+
contextManager,
|
|
712
|
+
instrumentations,
|
|
713
|
+
metricReaders: resolved.disableMetrics ? void 0 : [resolved.metricReader ?? createMetricReader(resolved)],
|
|
714
|
+
logRecordProcessors: resolved.disableLogs ? [] : [logger.getProcessor()],
|
|
715
|
+
spanProcessors,
|
|
716
|
+
sampler: resolveTraceSampler(resolved.traceSampler, resolved.traceSamplerArg),
|
|
717
|
+
spanLimits: resolved.spanLimits
|
|
718
|
+
});
|
|
719
|
+
sdk.start();
|
|
720
|
+
logger.setGlobalProvider();
|
|
721
|
+
if (resolved.stopOnTerminationSignals && !signalHandlersRegistered) registerTerminationHandlers();
|
|
722
|
+
if (!resolved.disableStartupLogs) diag.info("@safaricom-mxl/node-sdk: initialized");
|
|
723
|
+
return getControl();
|
|
724
|
+
}
|
|
725
|
+
function registerTerminationHandlers() {
|
|
726
|
+
const createTerminationHandler = (signal) => {
|
|
727
|
+
return () => {
|
|
728
|
+
diag.debug(`@safaricom-mxl/node-sdk: ${signal} received`);
|
|
729
|
+
shutdown().finally(() => {
|
|
730
|
+
process.exit();
|
|
731
|
+
});
|
|
732
|
+
};
|
|
733
|
+
};
|
|
734
|
+
const sigterm = createTerminationHandler("SIGTERM");
|
|
735
|
+
const sigint = createTerminationHandler("SIGINT");
|
|
736
|
+
terminationHandlers.push(["SIGTERM", sigterm], ["SIGINT", sigint]);
|
|
737
|
+
process.on("SIGTERM", sigterm);
|
|
738
|
+
process.on("SIGINT", sigint);
|
|
739
|
+
signalHandlersRegistered = true;
|
|
740
|
+
}
|
|
741
|
+
async function forceFlush() {
|
|
742
|
+
await Promise.all([
|
|
743
|
+
logger?.forceFlush(),
|
|
744
|
+
sdk?._tracerProvider?.forceFlush?.(),
|
|
745
|
+
sdk?._loggerProvider?.forceFlush?.(),
|
|
746
|
+
sdk?._meterProvider?.forceFlush?.()
|
|
747
|
+
]);
|
|
748
|
+
}
|
|
749
|
+
function getInitializedOTelLogger() {
|
|
750
|
+
return logger;
|
|
751
|
+
}
|
|
752
|
+
async function shutdown() {
|
|
753
|
+
if (signalHandlersRegistered) {
|
|
754
|
+
for (const [signal, handler] of terminationHandlers) process.off(signal, handler);
|
|
755
|
+
terminationHandlers.length = 0;
|
|
756
|
+
signalHandlersRegistered = false;
|
|
757
|
+
}
|
|
758
|
+
drainableSpanProcessor?.drain();
|
|
759
|
+
await Promise.allSettled([logger?.shutdown(), sdk?.shutdown()]);
|
|
760
|
+
sdk = void 0;
|
|
761
|
+
logger = void 0;
|
|
762
|
+
drainableSpanProcessor = void 0;
|
|
763
|
+
setMutableContextManager(void 0);
|
|
764
|
+
setActiveSDKConfig(void 0);
|
|
765
|
+
}
|
|
766
|
+
function getControl() {
|
|
767
|
+
return {
|
|
768
|
+
forceFlush,
|
|
769
|
+
shutdown,
|
|
770
|
+
setTraceAttributes
|
|
771
|
+
};
|
|
772
|
+
}
|
|
773
|
+
//#endregion
|
|
774
|
+
export { getActiveSDKConfig as a, setTraceAttributes as c, shutdown as i, getInitializedOTelLogger as n, resolveSDKConfig as o, initSDK as r, getTraceAttributes as s, forceFlush as t };
|
|
775
|
+
|
|
776
|
+
//# sourceMappingURL=initSDK-DSRBxu9o.mjs.map
|