@iii-dev/helpers 0.21.5 → 0.21.6-alpha.2
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/http/index.cjs.map +1 -1
- package/dist/http/index.d.cts +9 -10
- package/dist/http/index.d.mts +9 -10
- package/dist/http/index.mjs.map +1 -1
- package/dist/{index-BrvCdiQj.d.cts → index-CFP8erFF.d.cts} +59 -7
- package/dist/{index-DnQ__58E.d.mts → index-DObZ7kdy.d.mts} +59 -7
- package/dist/observability/index.cjs +13 -1
- package/dist/observability/index.cjs.map +1 -1
- package/dist/observability/index.d.cts +19 -1
- package/dist/observability/index.d.mts +19 -1
- package/dist/observability/index.mjs +13 -1
- package/dist/observability/index.mjs.map +1 -1
- package/dist/observability/internal.cjs +1 -1
- package/dist/observability/internal.d.cts +1 -1
- package/dist/observability/internal.d.mts +1 -1
- package/dist/observability/internal.mjs +1 -1
- package/dist/{telemetry-system-p24MCQGC.cjs → telemetry-system-BH119njX.cjs} +62 -8
- package/dist/telemetry-system-BH119njX.cjs.map +1 -0
- package/dist/{telemetry-system-xdaGTiJZ.mjs → telemetry-system-Pyz9irBj.mjs} +62 -8
- package/dist/telemetry-system-Pyz9irBj.mjs.map +1 -0
- package/dist/worker-connection-manager/index.d.cts +3 -3
- package/dist/worker-connection-manager/index.d.mts +3 -3
- package/package.json +1 -1
- package/dist/telemetry-system-p24MCQGC.cjs.map +0 -1
- package/dist/telemetry-system-xdaGTiJZ.mjs.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as removeBaggageEntry, C as extractBaggage, D as getBaggageEntry, E as getAllBaggage, M as OtelConfig, N as ReconnectionConfig, O as injectBaggage, S as currentTraceId, T as extractTraceparent, _ as recordSpanEvent, a as flushOtel, b as BaggageSpanProcessor, d as withSpan, f as REDACTED_PLACEHOLDER, g as currentSpanIsRecording, h as resolveMaxBytesFromEnv, i as Span, j as setBaggageEntry, k as injectTraceparent, l as initOtel, m as redactAndTruncate, n as Meter, o as getLogger, p as redact, r as SeverityNumber, t as Logger$1, u as shutdownOtel, v as setCurrentSpanAttribute, w as extractContext, x as currentSpanId, y as setCurrentSpanError } from "../index-
|
|
1
|
+
import { A as removeBaggageEntry, C as extractBaggage, D as getBaggageEntry, E as getAllBaggage, M as OtelConfig, N as ReconnectionConfig, O as injectBaggage, S as currentTraceId, T as extractTraceparent, _ as recordSpanEvent, a as flushOtel, b as BaggageSpanProcessor, d as withSpan, f as REDACTED_PLACEHOLDER, g as currentSpanIsRecording, h as resolveMaxBytesFromEnv, i as Span, j as setBaggageEntry, k as injectTraceparent, l as initOtel, m as redactAndTruncate, n as Meter, o as getLogger, p as redact, r as SeverityNumber, t as Logger$1, u as shutdownOtel, v as setCurrentSpanAttribute, w as extractContext, x as currentSpanId, y as setCurrentSpanError } from "../index-CFP8erFF.cjs";
|
|
2
2
|
import { Meter as Meter$1, Tracer } from "@opentelemetry/api";
|
|
3
3
|
|
|
4
4
|
//#region src/observability/logger.d.ts
|
|
@@ -96,6 +96,7 @@ declare class Logger {
|
|
|
96
96
|
//#endregion
|
|
97
97
|
//#region src/observability/http-instrumentation.d.ts
|
|
98
98
|
interface TracedFetchInit extends RequestInit {
|
|
99
|
+
/** Tracer used to create the client span for the outgoing request. */
|
|
99
100
|
tracer?: Tracer;
|
|
100
101
|
}
|
|
101
102
|
/**
|
|
@@ -104,12 +105,17 @@ interface TracedFetchInit extends RequestInit {
|
|
|
104
105
|
* Mirrors the Rust execute_traced_request shape: injects W3C traceparent into
|
|
105
106
|
* outgoing headers, records HTTP semantic-convention attributes, and sets
|
|
106
107
|
* ERROR span status for HTTP responses with status >= 400 or network errors.
|
|
108
|
+
*
|
|
109
|
+
* @param input - The resource to fetch: a URL string, `URL`, or `Request`.
|
|
110
|
+
* @param init - Fetch options, plus an optional `tracer` to create the span.
|
|
107
111
|
*/
|
|
108
112
|
declare function executeTracedRequest(input: RequestInfo | URL, init?: TracedFetchInit): Promise<Response>;
|
|
109
113
|
//#endregion
|
|
110
114
|
//#region src/observability/telemetry-system/fetch-instrumentation.d.ts
|
|
111
115
|
/**
|
|
112
116
|
* Patch globalThis.fetch to create OTel CLIENT spans for every HTTP request.
|
|
117
|
+
*
|
|
118
|
+
* @param tracer - Tracer used to create the client span for each request.
|
|
113
119
|
*/
|
|
114
120
|
declare function patchGlobalFetch(tracer: Tracer): void;
|
|
115
121
|
/**
|
|
@@ -119,10 +125,19 @@ declare function unpatchGlobalFetch(): void;
|
|
|
119
125
|
//#endregion
|
|
120
126
|
//#region src/observability/otel-worker-gauges.d.ts
|
|
121
127
|
interface WorkerGaugesOptions {
|
|
128
|
+
/** Stable identifier of the worker the gauges are reported for. */
|
|
122
129
|
workerId: string;
|
|
130
|
+
/** Human-readable name of the worker. */
|
|
123
131
|
workerName?: string;
|
|
124
132
|
}
|
|
133
|
+
/**
|
|
134
|
+
* Register OpenTelemetry observable gauges that report worker resource metrics
|
|
135
|
+
* (CPU, memory, event-loop) on each collection cycle.
|
|
136
|
+
*/
|
|
125
137
|
declare function registerWorkerGauges(meter: Meter$1, options: WorkerGaugesOptions): void;
|
|
138
|
+
/**
|
|
139
|
+
* Stop and unregister the worker resource gauges.
|
|
140
|
+
*/
|
|
126
141
|
declare function stopWorkerGauges(): void;
|
|
127
142
|
//#endregion
|
|
128
143
|
//#region src/observability/worker-metrics.d.ts
|
|
@@ -135,6 +150,7 @@ declare function stopWorkerGauges(): void;
|
|
|
135
150
|
*/
|
|
136
151
|
/**
|
|
137
152
|
* Worker metrics data structure used internally for OTEL metric collection.
|
|
153
|
+
* <!-- docs:internal -->
|
|
138
154
|
*/
|
|
139
155
|
type WorkerMetrics = {
|
|
140
156
|
memory_heap_used?: number;
|
|
@@ -237,6 +253,8 @@ type OtelLogEvent = {
|
|
|
237
253
|
/**
|
|
238
254
|
* Safely stringify a value, handling circular references, BigInt, and other edge cases.
|
|
239
255
|
* Returns "[unserializable]" if serialization fails for any reason.
|
|
256
|
+
*
|
|
257
|
+
* @param value - The value to serialize to JSON.
|
|
240
258
|
*/
|
|
241
259
|
declare function safeStringify(value: unknown): string;
|
|
242
260
|
//#endregion
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as removeBaggageEntry, C as extractBaggage, D as getBaggageEntry, E as getAllBaggage, M as OtelConfig, N as ReconnectionConfig, O as injectBaggage, S as currentTraceId, T as extractTraceparent, _ as recordSpanEvent, a as flushOtel, b as BaggageSpanProcessor, d as withSpan, f as REDACTED_PLACEHOLDER, g as currentSpanIsRecording, h as resolveMaxBytesFromEnv, i as Span, j as setBaggageEntry, k as injectTraceparent, l as initOtel, m as redactAndTruncate, n as Meter, o as getLogger, p as redact, r as SeverityNumber, t as Logger$1, u as shutdownOtel, v as setCurrentSpanAttribute, w as extractContext, x as currentSpanId, y as setCurrentSpanError } from "../index-
|
|
1
|
+
import { A as removeBaggageEntry, C as extractBaggage, D as getBaggageEntry, E as getAllBaggage, M as OtelConfig, N as ReconnectionConfig, O as injectBaggage, S as currentTraceId, T as extractTraceparent, _ as recordSpanEvent, a as flushOtel, b as BaggageSpanProcessor, d as withSpan, f as REDACTED_PLACEHOLDER, g as currentSpanIsRecording, h as resolveMaxBytesFromEnv, i as Span, j as setBaggageEntry, k as injectTraceparent, l as initOtel, m as redactAndTruncate, n as Meter, o as getLogger, p as redact, r as SeverityNumber, t as Logger$1, u as shutdownOtel, v as setCurrentSpanAttribute, w as extractContext, x as currentSpanId, y as setCurrentSpanError } from "../index-DObZ7kdy.mjs";
|
|
2
2
|
import { Meter as Meter$1, Tracer } from "@opentelemetry/api";
|
|
3
3
|
|
|
4
4
|
//#region src/observability/logger.d.ts
|
|
@@ -96,6 +96,7 @@ declare class Logger {
|
|
|
96
96
|
//#endregion
|
|
97
97
|
//#region src/observability/http-instrumentation.d.ts
|
|
98
98
|
interface TracedFetchInit extends RequestInit {
|
|
99
|
+
/** Tracer used to create the client span for the outgoing request. */
|
|
99
100
|
tracer?: Tracer;
|
|
100
101
|
}
|
|
101
102
|
/**
|
|
@@ -104,12 +105,17 @@ interface TracedFetchInit extends RequestInit {
|
|
|
104
105
|
* Mirrors the Rust execute_traced_request shape: injects W3C traceparent into
|
|
105
106
|
* outgoing headers, records HTTP semantic-convention attributes, and sets
|
|
106
107
|
* ERROR span status for HTTP responses with status >= 400 or network errors.
|
|
108
|
+
*
|
|
109
|
+
* @param input - The resource to fetch: a URL string, `URL`, or `Request`.
|
|
110
|
+
* @param init - Fetch options, plus an optional `tracer` to create the span.
|
|
107
111
|
*/
|
|
108
112
|
declare function executeTracedRequest(input: RequestInfo | URL, init?: TracedFetchInit): Promise<Response>;
|
|
109
113
|
//#endregion
|
|
110
114
|
//#region src/observability/telemetry-system/fetch-instrumentation.d.ts
|
|
111
115
|
/**
|
|
112
116
|
* Patch globalThis.fetch to create OTel CLIENT spans for every HTTP request.
|
|
117
|
+
*
|
|
118
|
+
* @param tracer - Tracer used to create the client span for each request.
|
|
113
119
|
*/
|
|
114
120
|
declare function patchGlobalFetch(tracer: Tracer): void;
|
|
115
121
|
/**
|
|
@@ -119,10 +125,19 @@ declare function unpatchGlobalFetch(): void;
|
|
|
119
125
|
//#endregion
|
|
120
126
|
//#region src/observability/otel-worker-gauges.d.ts
|
|
121
127
|
interface WorkerGaugesOptions {
|
|
128
|
+
/** Stable identifier of the worker the gauges are reported for. */
|
|
122
129
|
workerId: string;
|
|
130
|
+
/** Human-readable name of the worker. */
|
|
123
131
|
workerName?: string;
|
|
124
132
|
}
|
|
133
|
+
/**
|
|
134
|
+
* Register OpenTelemetry observable gauges that report worker resource metrics
|
|
135
|
+
* (CPU, memory, event-loop) on each collection cycle.
|
|
136
|
+
*/
|
|
125
137
|
declare function registerWorkerGauges(meter: Meter$1, options: WorkerGaugesOptions): void;
|
|
138
|
+
/**
|
|
139
|
+
* Stop and unregister the worker resource gauges.
|
|
140
|
+
*/
|
|
126
141
|
declare function stopWorkerGauges(): void;
|
|
127
142
|
//#endregion
|
|
128
143
|
//#region src/observability/worker-metrics.d.ts
|
|
@@ -135,6 +150,7 @@ declare function stopWorkerGauges(): void;
|
|
|
135
150
|
*/
|
|
136
151
|
/**
|
|
137
152
|
* Worker metrics data structure used internally for OTEL metric collection.
|
|
153
|
+
* <!-- docs:internal -->
|
|
138
154
|
*/
|
|
139
155
|
type WorkerMetrics = {
|
|
140
156
|
memory_heap_used?: number;
|
|
@@ -237,6 +253,8 @@ type OtelLogEvent = {
|
|
|
237
253
|
/**
|
|
238
254
|
* Safely stringify a value, handling circular references, BigInt, and other edge cases.
|
|
239
255
|
* Returns "[unserializable]" if serialization fails for any reason.
|
|
256
|
+
*
|
|
257
|
+
* @param value - The value to serialize to JSON.
|
|
240
258
|
*/
|
|
241
259
|
declare function safeStringify(value: unknown): string;
|
|
242
260
|
//#endregion
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as BaggageSpanProcessor, C as extractTraceparent, D as injectTraceparent, E as injectBaggage, O as removeBaggageEntry, S as extractContext, T as getBaggageEntry, _ as patchGlobalFetch, b as currentTraceId, c as withSpan, d as redactAndTruncate, f as resolveMaxBytesFromEnv, g as setCurrentSpanError, h as setCurrentSpanAttribute, k as setBaggageEntry, l as REDACTED_PLACEHOLDER, m as recordSpanEvent, n as flushOtel, o as initOtel, p as currentSpanIsRecording, r as getLogger, s as shutdownOtel, t as SeverityNumber, u as redact, v as unpatchGlobalFetch, w as getAllBaggage, x as extractBaggage, y as currentSpanId } from "../telemetry-system-
|
|
1
|
+
import { A as BaggageSpanProcessor, C as extractTraceparent, D as injectTraceparent, E as injectBaggage, O as removeBaggageEntry, S as extractContext, T as getBaggageEntry, _ as patchGlobalFetch, b as currentTraceId, c as withSpan, d as redactAndTruncate, f as resolveMaxBytesFromEnv, g as setCurrentSpanError, h as setCurrentSpanAttribute, k as setBaggageEntry, l as REDACTED_PLACEHOLDER, m as recordSpanEvent, n as flushOtel, o as initOtel, p as currentSpanIsRecording, r as getLogger, s as shutdownOtel, t as SeverityNumber, u as redact, v as unpatchGlobalFetch, w as getAllBaggage, x as extractBaggage, y as currentSpanId } from "../telemetry-system-Pyz9irBj.mjs";
|
|
2
2
|
import { SeverityNumber as SeverityNumber$1 } from "@opentelemetry/api-logs";
|
|
3
3
|
import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
|
|
4
4
|
import { monitorEventLoopDelay, performance } from "node:perf_hooks";
|
|
@@ -146,6 +146,9 @@ const SAFE_RESPONSE_HEADERS = ["content-type"];
|
|
|
146
146
|
* Mirrors the Rust execute_traced_request shape: injects W3C traceparent into
|
|
147
147
|
* outgoing headers, records HTTP semantic-convention attributes, and sets
|
|
148
148
|
* ERROR span status for HTTP responses with status >= 400 or network errors.
|
|
149
|
+
*
|
|
150
|
+
* @param input - The resource to fetch: a URL string, `URL`, or `Request`.
|
|
151
|
+
* @param init - Fetch options, plus an optional `tracer` to create the span.
|
|
149
152
|
*/
|
|
150
153
|
async function executeTracedRequest(input, init) {
|
|
151
154
|
const tracer = init?.tracer ?? trace.getTracer("iii-node-sdk");
|
|
@@ -333,6 +336,10 @@ let metricsCollector = null;
|
|
|
333
336
|
let registeredMeter = null;
|
|
334
337
|
let registeredBatchCallback = null;
|
|
335
338
|
let registeredObservables = [];
|
|
339
|
+
/**
|
|
340
|
+
* Register OpenTelemetry observable gauges that report worker resource metrics
|
|
341
|
+
* (CPU, memory, event-loop) on each collection cycle.
|
|
342
|
+
*/
|
|
336
343
|
function registerWorkerGauges(meter, options) {
|
|
337
344
|
if (registeredGauges) return;
|
|
338
345
|
const { workerId, workerName } = options;
|
|
@@ -416,6 +423,9 @@ function registerWorkerGauges(meter, options) {
|
|
|
416
423
|
];
|
|
417
424
|
registeredGauges = true;
|
|
418
425
|
}
|
|
426
|
+
/**
|
|
427
|
+
* Stop and unregister the worker resource gauges.
|
|
428
|
+
*/
|
|
419
429
|
function stopWorkerGauges() {
|
|
420
430
|
if (registeredMeter && registeredBatchCallback) registeredMeter.removeBatchObservableCallback(registeredBatchCallback, registeredObservables);
|
|
421
431
|
if (metricsCollector) {
|
|
@@ -433,6 +443,8 @@ function stopWorkerGauges() {
|
|
|
433
443
|
/**
|
|
434
444
|
* Safely stringify a value, handling circular references, BigInt, and other edge cases.
|
|
435
445
|
* Returns "[unserializable]" if serialization fails for any reason.
|
|
446
|
+
*
|
|
447
|
+
* @param value - The value to serialize to JSON.
|
|
436
448
|
*/
|
|
437
449
|
function safeStringify(value) {
|
|
438
450
|
const seen = /* @__PURE__ */ new WeakSet();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["getOtelLogger","SeverityNumber","otelContext"],"sources":["../../src/observability/logger.ts","../../src/observability/http-instrumentation.ts","../../src/observability/worker-metrics.ts","../../src/observability/otel-worker-gauges.ts","../../src/observability/utils.ts"],"sourcesContent":["import { AnyValue, AnyValueMap, SeverityNumber } from '@opentelemetry/api-logs'\nimport {\n currentSpanId,\n currentTraceId,\n getLogger as getOtelLogger,\n} from './telemetry-system'\n\n/** @internal */\nexport type LoggerParams = {\n message: string\n trace_id?: string\n span_id?: string\n service_name?: string\n data?: unknown\n /** @deprecated Use service_name instead */\n function_name?: string\n}\n\n/**\n * Structured logger that emits logs as OpenTelemetry LogRecords.\n *\n * Every log call automatically captures the active trace and span context,\n * correlating your logs with distributed traces without any manual wiring.\n * When OTel is not initialized, Logger gracefully falls back to `console.*`.\n *\n * Pass structured data as the second argument to any log method. Using an\n * object of key-value pairs (instead of string interpolation) lets you\n * filter, aggregate, and build dashboards in your observability backend.\n *\n * @example\n * ```typescript\n * import { Logger } from 'iii-sdk'\n *\n * const logger = new Logger()\n *\n * // Basic logging, trace context is injected automatically\n * logger.info('Worker connected')\n *\n * // Structured context for dashboards and alerting\n * logger.info('Order processed', { orderId: 'ord_123', amount: 49.99, currency: 'USD' })\n * logger.warn('Retry attempt', { attempt: 3, maxRetries: 5, endpoint: '/api/charge' })\n * logger.error('Payment failed', { orderId: 'ord_123', gateway: 'stripe', errorCode: 'card_declined' })\n * ```\n */\nexport class Logger {\n private _otelLogger: ReturnType<typeof getOtelLogger> | null = null\n\n private get otelLogger() {\n // Lazy initialization: re-fetch logger if not yet available\n if (!this._otelLogger) {\n this._otelLogger = getOtelLogger()\n }\n return this._otelLogger\n }\n\n constructor(\n private readonly traceId?: string,\n private readonly serviceName?: string,\n private readonly spanId?: string,\n ) {}\n\n private emit(message: string, severity: SeverityNumber, data?: unknown): void {\n const attributes: AnyValueMap = {}\n const traceId = this.traceId ?? currentTraceId()\n const spanId = this.spanId ?? currentSpanId()\n\n if (traceId) {\n attributes.trace_id = traceId\n }\n if (spanId) {\n attributes.span_id = spanId\n }\n if (this.serviceName) {\n attributes['service.name'] = this.serviceName\n }\n if (data !== undefined) {\n attributes['log.data'] = data as AnyValue\n }\n\n if (this.otelLogger) {\n this.otelLogger.emit({\n severityNumber: severity,\n body: message,\n attributes: Object.keys(attributes).length > 0 ? attributes : undefined,\n })\n } else {\n // Fallback to console when OTEL is not available\n switch (severity) {\n case SeverityNumber.DEBUG:\n console.debug(message, data)\n break\n case SeverityNumber.INFO:\n console.info(message, data)\n break\n case SeverityNumber.WARN:\n console.warn(message, data)\n break\n case SeverityNumber.ERROR:\n console.error(message, data)\n break\n default:\n console.log(message, data)\n }\n }\n }\n\n /**\n * Log an info-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.info('Order processed', { orderId: 'ord_123', status: 'completed' })\n * ```\n */\n info(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.INFO, data)\n }\n\n /**\n * Log a warning-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.warn('Retry attempt', { attempt: 3, maxRetries: 5, endpoint: '/api/charge' })\n * ```\n */\n warn(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.WARN, data)\n }\n\n /**\n * Log an error-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.error('Payment failed', { orderId: 'ord_123', gateway: 'stripe', errorCode: 'card_declined' })\n * ```\n */\n error(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.ERROR, data)\n }\n\n /**\n * Log a debug-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.debug('Cache lookup', { key: 'user:42', hit: false })\n * ```\n */\n debug(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.DEBUG, data)\n }\n}\n","import { context as otelContext, propagation, SpanKind, SpanStatusCode, trace, type Tracer } from '@opentelemetry/api'\n\nconst SAFE_REQUEST_HEADERS = ['content-type', 'accept'] as const\nconst SAFE_RESPONSE_HEADERS = ['content-type'] as const\n\nexport interface TracedFetchInit extends RequestInit {\n tracer?: Tracer\n}\n\n/**\n * Execute a fetch request inside an OTel CLIENT span.\n *\n * Mirrors the Rust execute_traced_request shape: injects W3C traceparent into\n * outgoing headers, records HTTP semantic-convention attributes, and sets\n * ERROR span status for HTTP responses with status >= 400 or network errors.\n */\nexport async function executeTracedRequest(\n input: RequestInfo | URL,\n init?: TracedFetchInit,\n): Promise<Response> {\n const tracer = init?.tracer ?? trace.getTracer('iii-node-sdk')\n const rawUrl = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url\n let url: URL | null\n try {\n url = new URL(rawUrl)\n } catch {\n url = null\n }\n const method = (init?.method ?? (typeof input === 'object' && 'method' in input ? input.method : 'GET') ?? 'GET').toUpperCase()\n const name = url?.pathname ? `${method} ${url.pathname}` : method\n\n return tracer.startActiveSpan(\n name,\n {\n kind: SpanKind.CLIENT,\n attributes: {\n 'http.request.method': method,\n 'url.full': url?.toString() ?? rawUrl,\n 'network.protocol.name': 'http',\n ...(url\n ? {\n 'server.address': url.hostname,\n 'url.scheme': url.protocol.replace(':', ''),\n 'url.path': url.pathname,\n }\n : {}),\n ...(url?.port ? { 'server.port': Number(url.port) } : {}),\n ...(url?.search ? { 'url.query': url.search.slice(1) } : {}),\n },\n },\n async (span) => {\n try {\n // Seed with the Request's own headers so they survive when caller\n // passes a Request object; init.headers (if any) then overrides.\n const baseHeaders =\n typeof input === 'object' && 'headers' in input ? input.headers : undefined\n const headers = new Headers(baseHeaders)\n if (init?.headers) {\n for (const [k, v] of new Headers(init.headers).entries()) headers.set(k, v)\n }\n const carrier: Record<string, string> = {}\n propagation.inject(otelContext.active(), carrier)\n for (const [k, v] of Object.entries(carrier)) headers.set(k, v)\n\n for (const h of SAFE_REQUEST_HEADERS) {\n const v = headers.get(h)\n if (v) span.setAttribute(`http.request.header.${h}`, v)\n }\n\n const response = await fetch(input, { ...init, headers })\n span.setAttribute('http.response.status_code', response.status)\n const cl = response.headers.get('content-length')\n if (cl) span.setAttribute('http.response.body.size', Number(cl))\n for (const h of SAFE_RESPONSE_HEADERS) {\n const v = response.headers.get(h)\n if (v) span.setAttribute(`http.response.header.${h}`, v)\n }\n\n if (response.status >= 400) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: String(response.status) })\n span.setAttribute('error.type', String(response.status))\n } else {\n span.setStatus({ code: SpanStatusCode.OK })\n }\n return response\n } catch (err) {\n const error = err as Error\n span.recordException(error)\n span.setStatus({ code: SpanStatusCode.ERROR, message: error.message })\n span.setAttribute('error.type', error.name)\n throw err\n } finally {\n span.end()\n }\n },\n )\n}\n","/**\n * Worker metrics collection for the III Node SDK.\n *\n * Collects CPU, memory, and event loop metrics for worker health monitoring.\n * Uses the Node.js built-in `monitorEventLoopDelay` API for accurate\n * event loop lag measurements.\n */\n\nimport { type IntervalHistogram, monitorEventLoopDelay, performance } from 'node:perf_hooks'\n\n/**\n * Worker metrics data structure used internally for OTEL metric collection.\n */\nexport type WorkerMetrics = {\n memory_heap_used?: number\n memory_heap_total?: number\n memory_rss?: number\n memory_external?: number\n cpu_user_micros?: number\n cpu_system_micros?: number\n cpu_percent?: number\n event_loop_lag_ms?: number\n uptime_seconds?: number\n timestamp_ms: number\n runtime: string\n}\n\n/**\n * Configuration options for the WorkerMetricsCollector.\n */\nexport interface WorkerMetricsCollectorOptions {\n /**\n * Event loop delay histogram resolution in milliseconds.\n * Lower values provide more accurate measurements but use more resources.\n * @default 20\n */\n eventLoopResolutionMs?: number\n}\n\n/**\n * Collects worker resource metrics including CPU, memory, and event loop lag.\n *\n * Uses the Node.js `monitorEventLoopDelay` API for high-precision event loop\n * delay measurements instead of manual `setImmediate` timing.\n *\n * @example\n * ```typescript\n * const collector = new WorkerMetricsCollector()\n *\n * // Collect metrics periodically\n * setInterval(() => {\n * const metrics = collector.collect()\n * console.log('CPU:', metrics.cpu_percent, '%')\n * console.log('Event Loop Lag:', metrics.event_loop_lag_ms, 'ms')\n * }, 5000)\n *\n * // Clean up when done\n * collector.stopMonitoring()\n * ```\n */\nexport class WorkerMetricsCollector {\n private readonly startTime: number\n private lastCpuUsage: NodeJS.CpuUsage\n private lastCpuTime: number\n private eventLoopHistogram: IntervalHistogram | null = null\n\n /**\n * Creates a new WorkerMetricsCollector instance.\n *\n * @param options - Configuration options\n */\n constructor(options: WorkerMetricsCollectorOptions = {}) {\n this.startTime = Date.now()\n this.lastCpuUsage = process.cpuUsage()\n this.lastCpuTime = performance.now()\n this.startEventLoopMonitoring(options.eventLoopResolutionMs ?? 20)\n }\n\n /**\n * Starts the event loop delay histogram monitoring.\n *\n * @param resolutionMs - Histogram resolution in milliseconds\n */\n private startEventLoopMonitoring(resolutionMs: number): void {\n // Sanitize resolution: must be a positive finite number, minimum 1ms\n const safeResolutionMs =\n Number.isFinite(resolutionMs) && resolutionMs > 0 ? Math.max(1, Math.floor(resolutionMs)) : 20 // Default fallback\n\n this.eventLoopHistogram = monitorEventLoopDelay({ resolution: safeResolutionMs })\n this.eventLoopHistogram.enable()\n }\n\n /**\n * Stops the event loop monitoring and releases resources.\n * Should be called when the collector is no longer needed.\n */\n public stopMonitoring(): void {\n if (this.eventLoopHistogram) {\n this.eventLoopHistogram.disable()\n this.eventLoopHistogram = null\n }\n }\n\n /**\n * Collects current worker metrics.\n *\n * This method calculates CPU usage since the last collection,\n * reads memory usage, and gets event loop delay statistics.\n * The event loop histogram is reset after each collection for\n * accurate per-interval measurements.\n *\n * @returns Current worker metrics snapshot\n */\n collect(): WorkerMetrics {\n const memoryUsage = process.memoryUsage()\n const cpuUsage = process.cpuUsage()\n const now = performance.now()\n\n // Calculate CPU percentage since last collection\n const cpuDelta = {\n user: cpuUsage.user - this.lastCpuUsage.user,\n system: cpuUsage.system - this.lastCpuUsage.system,\n }\n const timeDelta = (now - this.lastCpuTime) * 1000 // Convert ms to microseconds\n const cpuPercent = timeDelta > 0 ? ((cpuDelta.user + cpuDelta.system) / timeDelta) * 100 : 0\n\n // Update state for next collection\n this.lastCpuUsage = cpuUsage\n this.lastCpuTime = now\n\n // Get event loop lag from histogram (in nanoseconds, convert to ms)\n let eventLoopLagMs = 0\n if (this.eventLoopHistogram) {\n // Mean is in nanoseconds, convert to milliseconds\n eventLoopLagMs = this.eventLoopHistogram.mean / 1_000_000\n // Reset histogram for next collection interval\n this.eventLoopHistogram.reset()\n }\n\n return {\n memory_heap_used: memoryUsage.heapUsed,\n memory_heap_total: memoryUsage.heapTotal,\n memory_rss: memoryUsage.rss,\n memory_external: memoryUsage.external,\n cpu_user_micros: cpuUsage.user,\n cpu_system_micros: cpuUsage.system,\n cpu_percent: Math.min(cpuPercent, 100), // Cap at 100%\n event_loop_lag_ms: eventLoopLagMs,\n uptime_seconds: Math.floor((Date.now() - this.startTime) / 1000),\n timestamp_ms: Date.now(),\n runtime: 'node',\n }\n }\n}\n","import type { Meter, BatchObservableResult, Observable } from '@opentelemetry/api'\nimport { WorkerMetricsCollector } from './worker-metrics'\n\nexport interface WorkerGaugesOptions {\n workerId: string\n workerName?: string\n}\n\nlet registeredGauges = false\nlet metricsCollector: WorkerMetricsCollector | null = null\nlet registeredMeter: Meter | null = null\nlet registeredBatchCallback: ((observableResult: BatchObservableResult) => void) | null = null\nlet registeredObservables: Observable[] = []\n\nexport function registerWorkerGauges(meter: Meter, options: WorkerGaugesOptions): void {\n if (registeredGauges) {\n return\n }\n\n const { workerId, workerName } = options\n const baseAttributes = {\n 'worker.id': workerId,\n ...(workerName && { 'worker.name': workerName }),\n }\n\n metricsCollector = new WorkerMetricsCollector()\n\n const memoryHeapUsed = meter.createObservableGauge('iii.worker.memory.heap_used', {\n description: 'Worker heap memory used in bytes',\n unit: 'bytes',\n })\n\n const memoryHeapTotal = meter.createObservableGauge('iii.worker.memory.heap_total', {\n description: 'Worker total heap memory in bytes',\n unit: 'bytes',\n })\n\n const memoryRss = meter.createObservableGauge('iii.worker.memory.rss', {\n description: 'Worker resident set size in bytes',\n unit: 'bytes',\n })\n\n const memoryExternal = meter.createObservableGauge('iii.worker.memory.external', {\n description: 'Worker external memory in bytes',\n unit: 'bytes',\n })\n\n const cpuPercent = meter.createObservableGauge('iii.worker.cpu.percent', {\n description: 'Worker CPU usage percentage',\n unit: '%',\n })\n\n const cpuUserMicros = meter.createObservableGauge('iii.worker.cpu.user_micros', {\n description: 'Worker CPU user time in microseconds',\n unit: 'us',\n })\n\n const cpuSystemMicros = meter.createObservableGauge('iii.worker.cpu.system_micros', {\n description: 'Worker CPU system time in microseconds',\n unit: 'us',\n })\n\n const eventLoopLag = meter.createObservableGauge('iii.worker.event_loop.lag_ms', {\n description: 'Worker event loop lag in milliseconds',\n unit: 'ms',\n })\n\n const uptimeSeconds = meter.createObservableGauge('iii.worker.uptime_seconds', {\n description: 'Worker uptime in seconds',\n unit: 's',\n })\n\n const batchCallback = (observableResult: BatchObservableResult) => {\n if (!metricsCollector) return\n\n const metrics = metricsCollector.collect()\n\n if (metrics.memory_heap_used !== undefined) {\n observableResult.observe(memoryHeapUsed, metrics.memory_heap_used, baseAttributes)\n }\n if (metrics.memory_heap_total !== undefined) {\n observableResult.observe(memoryHeapTotal, metrics.memory_heap_total, baseAttributes)\n }\n if (metrics.memory_rss !== undefined) {\n observableResult.observe(memoryRss, metrics.memory_rss, baseAttributes)\n }\n if (metrics.memory_external !== undefined) {\n observableResult.observe(memoryExternal, metrics.memory_external, baseAttributes)\n }\n if (metrics.cpu_percent !== undefined) {\n observableResult.observe(cpuPercent, metrics.cpu_percent, baseAttributes)\n }\n if (metrics.cpu_user_micros !== undefined) {\n observableResult.observe(cpuUserMicros, metrics.cpu_user_micros, baseAttributes)\n }\n if (metrics.cpu_system_micros !== undefined) {\n observableResult.observe(cpuSystemMicros, metrics.cpu_system_micros, baseAttributes)\n }\n if (metrics.event_loop_lag_ms !== undefined) {\n observableResult.observe(eventLoopLag, metrics.event_loop_lag_ms, baseAttributes)\n }\n if (metrics.uptime_seconds !== undefined) {\n observableResult.observe(uptimeSeconds, metrics.uptime_seconds, baseAttributes)\n }\n }\n\n meter.addBatchObservableCallback(batchCallback, [\n memoryHeapUsed,\n memoryHeapTotal,\n memoryRss,\n memoryExternal,\n cpuPercent,\n cpuUserMicros,\n cpuSystemMicros,\n eventLoopLag,\n uptimeSeconds,\n ])\n\n registeredMeter = meter\n registeredBatchCallback = batchCallback\n registeredObservables = [\n memoryHeapUsed,\n memoryHeapTotal,\n memoryRss,\n memoryExternal,\n cpuPercent,\n cpuUserMicros,\n cpuSystemMicros,\n eventLoopLag,\n uptimeSeconds,\n ]\n\n registeredGauges = true\n}\n\nexport function stopWorkerGauges(): void {\n // Remove the batch observable callback before stopping\n if (registeredMeter && registeredBatchCallback) {\n registeredMeter.removeBatchObservableCallback(registeredBatchCallback, registeredObservables)\n }\n\n if (metricsCollector) {\n metricsCollector.stopMonitoring()\n metricsCollector = null\n }\n\n registeredMeter = null\n registeredBatchCallback = null\n registeredObservables = []\n registeredGauges = false\n}\n","/**\n * Safely stringify a value, handling circular references, BigInt, and other edge cases.\n * Returns \"[unserializable]\" if serialization fails for any reason.\n */\nexport function safeStringify(value: unknown): string {\n const seen = new WeakSet<object>()\n\n try {\n const result = JSON.stringify(value, (_key, val) => {\n // Handle BigInt\n if (typeof val === 'bigint') {\n return val.toString()\n }\n\n // Handle circular references\n if (val !== null && typeof val === 'object') {\n if (seen.has(val)) {\n return '[Circular]'\n }\n seen.add(val)\n }\n\n return val\n })\n return result ?? '[unserializable]'\n } catch {\n return '[unserializable]'\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,IAAa,SAAb,MAAoB;CAClB,AAAQ,cAAuD;CAE/D,IAAY,aAAa;AAEvB,MAAI,CAAC,KAAK,YACR,MAAK,cAAcA,WAAe;AAEpC,SAAO,KAAK;;CAGd,YACE,AAAiB,SACjB,AAAiB,aACjB,AAAiB,QACjB;EAHiB;EACA;EACA;;CAGnB,AAAQ,KAAK,SAAiB,UAA0B,MAAsB;EAC5E,MAAM,aAA0B,EAAE;EAClC,MAAM,UAAU,KAAK,WAAW,gBAAgB;EAChD,MAAM,SAAS,KAAK,UAAU,eAAe;AAE7C,MAAI,QACF,YAAW,WAAW;AAExB,MAAI,OACF,YAAW,UAAU;AAEvB,MAAI,KAAK,YACP,YAAW,kBAAkB,KAAK;AAEpC,MAAI,SAAS,OACX,YAAW,cAAc;AAG3B,MAAI,KAAK,WACP,MAAK,WAAW,KAAK;GACnB,gBAAgB;GAChB,MAAM;GACN,YAAY,OAAO,KAAK,WAAW,CAAC,SAAS,IAAI,aAAa;GAC/D,CAAC;MAGF,SAAQ,UAAR;GACE,KAAKC,iBAAe;AAClB,YAAQ,MAAM,SAAS,KAAK;AAC5B;GACF,KAAKA,iBAAe;AAClB,YAAQ,KAAK,SAAS,KAAK;AAC3B;GACF,KAAKA,iBAAe;AAClB,YAAQ,KAAK,SAAS,KAAK;AAC3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BAAwB,EAAE;AAC1B,oBAAmB;;;;;;;;;ACjJrB,SAAgB,cAAc,OAAwB;CACpD,MAAM,uBAAO,IAAI,SAAiB;AAElC,KAAI;AAiBF,SAhBe,KAAK,UAAU,QAAQ,MAAM,QAAQ;AAElD,OAAI,OAAO,QAAQ,SACjB,QAAO,IAAI,UAAU;AAIvB,OAAI,QAAQ,QAAQ,OAAO,QAAQ,UAAU;AAC3C,QAAI,KAAK,IAAI,IAAI,CACf,QAAO;AAET,SAAK,IAAI,IAAI;;AAGf,UAAO;IACP,IACe;SACX;AACN,SAAO"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["getOtelLogger","SeverityNumber","otelContext"],"sources":["../../src/observability/logger.ts","../../src/observability/http-instrumentation.ts","../../src/observability/worker-metrics.ts","../../src/observability/otel-worker-gauges.ts","../../src/observability/utils.ts"],"sourcesContent":["import { AnyValue, AnyValueMap, SeverityNumber } from '@opentelemetry/api-logs'\nimport {\n currentSpanId,\n currentTraceId,\n getLogger as getOtelLogger,\n} from './telemetry-system'\n\n/** @internal */\nexport type LoggerParams = {\n message: string\n trace_id?: string\n span_id?: string\n service_name?: string\n data?: unknown\n /** @deprecated Use service_name instead */\n function_name?: string\n}\n\n/**\n * Structured logger that emits logs as OpenTelemetry LogRecords.\n *\n * Every log call automatically captures the active trace and span context,\n * correlating your logs with distributed traces without any manual wiring.\n * When OTel is not initialized, Logger gracefully falls back to `console.*`.\n *\n * Pass structured data as the second argument to any log method. Using an\n * object of key-value pairs (instead of string interpolation) lets you\n * filter, aggregate, and build dashboards in your observability backend.\n *\n * @example\n * ```typescript\n * import { Logger } from 'iii-sdk'\n *\n * const logger = new Logger()\n *\n * // Basic logging, trace context is injected automatically\n * logger.info('Worker connected')\n *\n * // Structured context for dashboards and alerting\n * logger.info('Order processed', { orderId: 'ord_123', amount: 49.99, currency: 'USD' })\n * logger.warn('Retry attempt', { attempt: 3, maxRetries: 5, endpoint: '/api/charge' })\n * logger.error('Payment failed', { orderId: 'ord_123', gateway: 'stripe', errorCode: 'card_declined' })\n * ```\n */\nexport class Logger {\n private _otelLogger: ReturnType<typeof getOtelLogger> | null = null\n\n private get otelLogger() {\n // Lazy initialization: re-fetch logger if not yet available\n if (!this._otelLogger) {\n this._otelLogger = getOtelLogger()\n }\n return this._otelLogger\n }\n\n constructor(\n private readonly traceId?: string,\n private readonly serviceName?: string,\n private readonly spanId?: string,\n ) {}\n\n private emit(message: string, severity: SeverityNumber, data?: unknown): void {\n const attributes: AnyValueMap = {}\n const traceId = this.traceId ?? currentTraceId()\n const spanId = this.spanId ?? currentSpanId()\n\n if (traceId) {\n attributes.trace_id = traceId\n }\n if (spanId) {\n attributes.span_id = spanId\n }\n if (this.serviceName) {\n attributes['service.name'] = this.serviceName\n }\n if (data !== undefined) {\n attributes['log.data'] = data as AnyValue\n }\n\n if (this.otelLogger) {\n this.otelLogger.emit({\n severityNumber: severity,\n body: message,\n attributes: Object.keys(attributes).length > 0 ? attributes : undefined,\n })\n } else {\n // Fallback to console when OTEL is not available\n switch (severity) {\n case SeverityNumber.DEBUG:\n console.debug(message, data)\n break\n case SeverityNumber.INFO:\n console.info(message, data)\n break\n case SeverityNumber.WARN:\n console.warn(message, data)\n break\n case SeverityNumber.ERROR:\n console.error(message, data)\n break\n default:\n console.log(message, data)\n }\n }\n }\n\n /**\n * Log an info-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.info('Order processed', { orderId: 'ord_123', status: 'completed' })\n * ```\n */\n info(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.INFO, data)\n }\n\n /**\n * Log a warning-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.warn('Retry attempt', { attempt: 3, maxRetries: 5, endpoint: '/api/charge' })\n * ```\n */\n warn(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.WARN, data)\n }\n\n /**\n * Log an error-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.error('Payment failed', { orderId: 'ord_123', gateway: 'stripe', errorCode: 'card_declined' })\n * ```\n */\n error(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.ERROR, data)\n }\n\n /**\n * Log a debug-level message.\n *\n * @param message - Human-readable log message.\n * @param data - Structured context attached as OTel log attributes.\n * Use key-value objects to enable filtering and aggregation in your\n * observability backend (e.g. Grafana, Datadog, New Relic).\n *\n * @example\n * ```typescript\n * logger.debug('Cache lookup', { key: 'user:42', hit: false })\n * ```\n */\n debug(message: string, data?: unknown): void {\n this.emit(message, SeverityNumber.DEBUG, data)\n }\n}\n","import { context as otelContext, propagation, SpanKind, SpanStatusCode, trace, type Tracer } from '@opentelemetry/api'\n\nconst SAFE_REQUEST_HEADERS = ['content-type', 'accept'] as const\nconst SAFE_RESPONSE_HEADERS = ['content-type'] as const\n\nexport interface TracedFetchInit extends RequestInit {\n /** Tracer used to create the client span for the outgoing request. */\n tracer?: Tracer\n}\n\n/**\n * Execute a fetch request inside an OTel CLIENT span.\n *\n * Mirrors the Rust execute_traced_request shape: injects W3C traceparent into\n * outgoing headers, records HTTP semantic-convention attributes, and sets\n * ERROR span status for HTTP responses with status >= 400 or network errors.\n *\n * @param input - The resource to fetch: a URL string, `URL`, or `Request`.\n * @param init - Fetch options, plus an optional `tracer` to create the span.\n */\nexport async function executeTracedRequest(\n input: RequestInfo | URL,\n init?: TracedFetchInit,\n): Promise<Response> {\n const tracer = init?.tracer ?? trace.getTracer('iii-node-sdk')\n const rawUrl = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url\n let url: URL | null\n try {\n url = new URL(rawUrl)\n } catch {\n url = null\n }\n const method = (init?.method ?? (typeof input === 'object' && 'method' in input ? input.method : 'GET') ?? 'GET').toUpperCase()\n const name = url?.pathname ? `${method} ${url.pathname}` : method\n\n return tracer.startActiveSpan(\n name,\n {\n kind: SpanKind.CLIENT,\n attributes: {\n 'http.request.method': method,\n 'url.full': url?.toString() ?? rawUrl,\n 'network.protocol.name': 'http',\n ...(url\n ? {\n 'server.address': url.hostname,\n 'url.scheme': url.protocol.replace(':', ''),\n 'url.path': url.pathname,\n }\n : {}),\n ...(url?.port ? { 'server.port': Number(url.port) } : {}),\n ...(url?.search ? { 'url.query': url.search.slice(1) } : {}),\n },\n },\n async (span) => {\n try {\n // Seed with the Request's own headers so they survive when caller\n // passes a Request object; init.headers (if any) then overrides.\n const baseHeaders =\n typeof input === 'object' && 'headers' in input ? input.headers : undefined\n const headers = new Headers(baseHeaders)\n if (init?.headers) {\n for (const [k, v] of new Headers(init.headers).entries()) headers.set(k, v)\n }\n const carrier: Record<string, string> = {}\n propagation.inject(otelContext.active(), carrier)\n for (const [k, v] of Object.entries(carrier)) headers.set(k, v)\n\n for (const h of SAFE_REQUEST_HEADERS) {\n const v = headers.get(h)\n if (v) span.setAttribute(`http.request.header.${h}`, v)\n }\n\n const response = await fetch(input, { ...init, headers })\n span.setAttribute('http.response.status_code', response.status)\n const cl = response.headers.get('content-length')\n if (cl) span.setAttribute('http.response.body.size', Number(cl))\n for (const h of SAFE_RESPONSE_HEADERS) {\n const v = response.headers.get(h)\n if (v) span.setAttribute(`http.response.header.${h}`, v)\n }\n\n if (response.status >= 400) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: String(response.status) })\n span.setAttribute('error.type', String(response.status))\n } else {\n span.setStatus({ code: SpanStatusCode.OK })\n }\n return response\n } catch (err) {\n const error = err as Error\n span.recordException(error)\n span.setStatus({ code: SpanStatusCode.ERROR, message: error.message })\n span.setAttribute('error.type', error.name)\n throw err\n } finally {\n span.end()\n }\n },\n )\n}\n","/**\n * Worker metrics collection for the III Node SDK.\n *\n * Collects CPU, memory, and event loop metrics for worker health monitoring.\n * Uses the Node.js built-in `monitorEventLoopDelay` API for accurate\n * event loop lag measurements.\n */\n\nimport { type IntervalHistogram, monitorEventLoopDelay, performance } from 'node:perf_hooks'\n\n/**\n * Worker metrics data structure used internally for OTEL metric collection.\n * <!-- docs:internal -->\n */\nexport type WorkerMetrics = {\n memory_heap_used?: number\n memory_heap_total?: number\n memory_rss?: number\n memory_external?: number\n cpu_user_micros?: number\n cpu_system_micros?: number\n cpu_percent?: number\n event_loop_lag_ms?: number\n uptime_seconds?: number\n timestamp_ms: number\n runtime: string\n}\n\n/**\n * Configuration options for the WorkerMetricsCollector.\n */\nexport interface WorkerMetricsCollectorOptions {\n /**\n * Event loop delay histogram resolution in milliseconds.\n * Lower values provide more accurate measurements but use more resources.\n * @default 20\n */\n eventLoopResolutionMs?: number\n}\n\n/**\n * Collects worker resource metrics including CPU, memory, and event loop lag.\n *\n * Uses the Node.js `monitorEventLoopDelay` API for high-precision event loop\n * delay measurements instead of manual `setImmediate` timing.\n *\n * @example\n * ```typescript\n * const collector = new WorkerMetricsCollector()\n *\n * // Collect metrics periodically\n * setInterval(() => {\n * const metrics = collector.collect()\n * console.log('CPU:', metrics.cpu_percent, '%')\n * console.log('Event Loop Lag:', metrics.event_loop_lag_ms, 'ms')\n * }, 5000)\n *\n * // Clean up when done\n * collector.stopMonitoring()\n * ```\n */\nexport class WorkerMetricsCollector {\n private readonly startTime: number\n private lastCpuUsage: NodeJS.CpuUsage\n private lastCpuTime: number\n private eventLoopHistogram: IntervalHistogram | null = null\n\n /**\n * Creates a new WorkerMetricsCollector instance.\n *\n * @param options - Configuration options\n */\n constructor(options: WorkerMetricsCollectorOptions = {}) {\n this.startTime = Date.now()\n this.lastCpuUsage = process.cpuUsage()\n this.lastCpuTime = performance.now()\n this.startEventLoopMonitoring(options.eventLoopResolutionMs ?? 20)\n }\n\n /**\n * Starts the event loop delay histogram monitoring.\n *\n * @param resolutionMs - Histogram resolution in milliseconds\n */\n private startEventLoopMonitoring(resolutionMs: number): void {\n // Sanitize resolution: must be a positive finite number, minimum 1ms\n const safeResolutionMs =\n Number.isFinite(resolutionMs) && resolutionMs > 0 ? Math.max(1, Math.floor(resolutionMs)) : 20 // Default fallback\n\n this.eventLoopHistogram = monitorEventLoopDelay({ resolution: safeResolutionMs })\n this.eventLoopHistogram.enable()\n }\n\n /**\n * Stops the event loop monitoring and releases resources.\n * Should be called when the collector is no longer needed.\n */\n public stopMonitoring(): void {\n if (this.eventLoopHistogram) {\n this.eventLoopHistogram.disable()\n this.eventLoopHistogram = null\n }\n }\n\n /**\n * Collects current worker metrics.\n *\n * This method calculates CPU usage since the last collection,\n * reads memory usage, and gets event loop delay statistics.\n * The event loop histogram is reset after each collection for\n * accurate per-interval measurements.\n *\n * @returns Current worker metrics snapshot\n */\n collect(): WorkerMetrics {\n const memoryUsage = process.memoryUsage()\n const cpuUsage = process.cpuUsage()\n const now = performance.now()\n\n // Calculate CPU percentage since last collection\n const cpuDelta = {\n user: cpuUsage.user - this.lastCpuUsage.user,\n system: cpuUsage.system - this.lastCpuUsage.system,\n }\n const timeDelta = (now - this.lastCpuTime) * 1000 // Convert ms to microseconds\n const cpuPercent = timeDelta > 0 ? ((cpuDelta.user + cpuDelta.system) / timeDelta) * 100 : 0\n\n // Update state for next collection\n this.lastCpuUsage = cpuUsage\n this.lastCpuTime = now\n\n // Get event loop lag from histogram (in nanoseconds, convert to ms)\n let eventLoopLagMs = 0\n if (this.eventLoopHistogram) {\n // Mean is in nanoseconds, convert to milliseconds\n eventLoopLagMs = this.eventLoopHistogram.mean / 1_000_000\n // Reset histogram for next collection interval\n this.eventLoopHistogram.reset()\n }\n\n return {\n memory_heap_used: memoryUsage.heapUsed,\n memory_heap_total: memoryUsage.heapTotal,\n memory_rss: memoryUsage.rss,\n memory_external: memoryUsage.external,\n cpu_user_micros: cpuUsage.user,\n cpu_system_micros: cpuUsage.system,\n cpu_percent: Math.min(cpuPercent, 100), // Cap at 100%\n event_loop_lag_ms: eventLoopLagMs,\n uptime_seconds: Math.floor((Date.now() - this.startTime) / 1000),\n timestamp_ms: Date.now(),\n runtime: 'node',\n }\n }\n}\n","import type { Meter, BatchObservableResult, Observable } from '@opentelemetry/api'\nimport { WorkerMetricsCollector } from './worker-metrics'\n\nexport interface WorkerGaugesOptions {\n /** Stable identifier of the worker the gauges are reported for. */\n workerId: string\n /** Human-readable name of the worker. */\n workerName?: string\n}\n\nlet registeredGauges = false\nlet metricsCollector: WorkerMetricsCollector | null = null\nlet registeredMeter: Meter | null = null\nlet registeredBatchCallback: ((observableResult: BatchObservableResult) => void) | null = null\nlet registeredObservables: Observable[] = []\n\n/**\n * Register OpenTelemetry observable gauges that report worker resource metrics\n * (CPU, memory, event-loop) on each collection cycle.\n */\nexport function registerWorkerGauges(meter: Meter, options: WorkerGaugesOptions): void {\n if (registeredGauges) {\n return\n }\n\n const { workerId, workerName } = options\n const baseAttributes = {\n 'worker.id': workerId,\n ...(workerName && { 'worker.name': workerName }),\n }\n\n metricsCollector = new WorkerMetricsCollector()\n\n const memoryHeapUsed = meter.createObservableGauge('iii.worker.memory.heap_used', {\n description: 'Worker heap memory used in bytes',\n unit: 'bytes',\n })\n\n const memoryHeapTotal = meter.createObservableGauge('iii.worker.memory.heap_total', {\n description: 'Worker total heap memory in bytes',\n unit: 'bytes',\n })\n\n const memoryRss = meter.createObservableGauge('iii.worker.memory.rss', {\n description: 'Worker resident set size in bytes',\n unit: 'bytes',\n })\n\n const memoryExternal = meter.createObservableGauge('iii.worker.memory.external', {\n description: 'Worker external memory in bytes',\n unit: 'bytes',\n })\n\n const cpuPercent = meter.createObservableGauge('iii.worker.cpu.percent', {\n description: 'Worker CPU usage percentage',\n unit: '%',\n })\n\n const cpuUserMicros = meter.createObservableGauge('iii.worker.cpu.user_micros', {\n description: 'Worker CPU user time in microseconds',\n unit: 'us',\n })\n\n const cpuSystemMicros = meter.createObservableGauge('iii.worker.cpu.system_micros', {\n description: 'Worker CPU system time in microseconds',\n unit: 'us',\n })\n\n const eventLoopLag = meter.createObservableGauge('iii.worker.event_loop.lag_ms', {\n description: 'Worker event loop lag in milliseconds',\n unit: 'ms',\n })\n\n const uptimeSeconds = meter.createObservableGauge('iii.worker.uptime_seconds', {\n description: 'Worker uptime in seconds',\n unit: 's',\n })\n\n const batchCallback = (observableResult: BatchObservableResult) => {\n if (!metricsCollector) return\n\n const metrics = metricsCollector.collect()\n\n if (metrics.memory_heap_used !== undefined) {\n observableResult.observe(memoryHeapUsed, metrics.memory_heap_used, baseAttributes)\n }\n if (metrics.memory_heap_total !== undefined) {\n observableResult.observe(memoryHeapTotal, metrics.memory_heap_total, baseAttributes)\n }\n if (metrics.memory_rss !== undefined) {\n observableResult.observe(memoryRss, metrics.memory_rss, baseAttributes)\n }\n if (metrics.memory_external !== undefined) {\n observableResult.observe(memoryExternal, metrics.memory_external, baseAttributes)\n }\n if (metrics.cpu_percent !== undefined) {\n observableResult.observe(cpuPercent, metrics.cpu_percent, baseAttributes)\n }\n if (metrics.cpu_user_micros !== undefined) {\n observableResult.observe(cpuUserMicros, metrics.cpu_user_micros, baseAttributes)\n }\n if (metrics.cpu_system_micros !== undefined) {\n observableResult.observe(cpuSystemMicros, metrics.cpu_system_micros, baseAttributes)\n }\n if (metrics.event_loop_lag_ms !== undefined) {\n observableResult.observe(eventLoopLag, metrics.event_loop_lag_ms, baseAttributes)\n }\n if (metrics.uptime_seconds !== undefined) {\n observableResult.observe(uptimeSeconds, metrics.uptime_seconds, baseAttributes)\n }\n }\n\n meter.addBatchObservableCallback(batchCallback, [\n memoryHeapUsed,\n memoryHeapTotal,\n memoryRss,\n memoryExternal,\n cpuPercent,\n cpuUserMicros,\n cpuSystemMicros,\n eventLoopLag,\n uptimeSeconds,\n ])\n\n registeredMeter = meter\n registeredBatchCallback = batchCallback\n registeredObservables = [\n memoryHeapUsed,\n memoryHeapTotal,\n memoryRss,\n memoryExternal,\n cpuPercent,\n cpuUserMicros,\n cpuSystemMicros,\n eventLoopLag,\n uptimeSeconds,\n ]\n\n registeredGauges = true\n}\n\n/**\n * Stop and unregister the worker resource gauges.\n */\nexport function stopWorkerGauges(): void {\n // Remove the batch observable callback before stopping\n if (registeredMeter && registeredBatchCallback) {\n registeredMeter.removeBatchObservableCallback(registeredBatchCallback, registeredObservables)\n }\n\n if (metricsCollector) {\n metricsCollector.stopMonitoring()\n metricsCollector = null\n }\n\n registeredMeter = null\n registeredBatchCallback = null\n registeredObservables = []\n registeredGauges = false\n}\n","/**\n * Safely stringify a value, handling circular references, BigInt, and other edge cases.\n * Returns \"[unserializable]\" if serialization fails for any reason.\n *\n * @param value - The value to serialize to JSON.\n */\nexport function safeStringify(value: unknown): string {\n const seen = new WeakSet<object>()\n\n try {\n const result = JSON.stringify(value, (_key, val) => {\n // Handle BigInt\n if (typeof val === 'bigint') {\n return val.toString()\n }\n\n // Handle circular references\n if (val !== null && typeof val === 'object') {\n if (seen.has(val)) {\n return '[Circular]'\n }\n seen.add(val)\n }\n\n return val\n })\n return result ?? '[unserializable]'\n } catch {\n return '[unserializable]'\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,IAAa,SAAb,MAAoB;CAClB,AAAQ,cAAuD;CAE/D,IAAY,aAAa;AAEvB,MAAI,CAAC,KAAK,YACR,MAAK,cAAcA,WAAe;AAEpC,SAAO,KAAK;;CAGd,YACE,AAAiB,SACjB,AAAiB,aACjB,AAAiB,QACjB;EAHiB;EACA;EACA;;CAGnB,AAAQ,KAAK,SAAiB,UAA0B,MAAsB;EAC5E,MAAM,aAA0B,EAAE;EAClC,MAAM,UAAU,KAAK,WAAW,gBAAgB;EAChD,MAAM,SAAS,KAAK,UAAU,eAAe;AAE7C,MAAI,QACF,YAAW,WAAW;AAExB,MAAI,OACF,YAAW,UAAU;AAEvB,MAAI,KAAK,YACP,YAAW,kBAAkB,KAAK;AAEpC,MAAI,SAAS,OACX,Y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9C;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;AAEF,mBAAkB;AAClB,2BAA0B;AAC1B,yBAAwB;EACtB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD;AAED,oBAAmB;;;;;AAMrB,SAAgB,mBAAyB;AAEvC,KAAI,mBAAmB,wBACrB,iBAAgB,8BAA8B,yBAAyB,sBAAsB;AAG/F,KAAI,kBAAkB;AACpB,mBAAiB,gBAAgB;AACjC,qBAAmB;;AAGrB,mBAAkB;AAClB,2BAA0B;AAC1B,yBAAwB,EAAE;AAC1B,oBAAmB;;;;;;;;;;;ACxJrB,SAAgB,cAAc,OAAwB;CACpD,MAAM,uBAAO,IAAI,SAAiB;AAElC,KAAI;AAiBF,SAhBe,KAAK,UAAU,QAAQ,MAAM,QAAQ;AAElD,OAAI,OAAO,QAAQ,SACjB,QAAO,IAAI,UAAU;AAIvB,OAAI,QAAQ,QAAQ,OAAO,QAAQ,UAAU;AAC3C,QAAI,KAAK,IAAI,IAAI,CACf,QAAO;AAET,SAAK,IAAI,IAAI;;AAGf,UAAO;IACP,IACe;SACX;AACN,SAAO"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_telemetry_system = require('../telemetry-system-
|
|
2
|
+
const require_telemetry_system = require('../telemetry-system-BH119njX.cjs');
|
|
3
3
|
|
|
4
4
|
exports.getMeter = require_telemetry_system.getMeter;
|
|
5
5
|
exports.getTracer = require_telemetry_system.getTracer;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { c as getTracer, s as getMeter } from "../index-
|
|
1
|
+
import { c as getTracer, s as getMeter } from "../index-CFP8erFF.cjs";
|
|
2
2
|
export { getMeter, getTracer };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { c as getTracer, s as getMeter } from "../index-
|
|
1
|
+
import { c as getTracer, s as getMeter } from "../index-DObZ7kdy.mjs";
|
|
2
2
|
export { getMeter, getTracer };
|
|
@@ -13,6 +13,10 @@ let ws = require("ws");
|
|
|
13
13
|
let _opentelemetry_otlp_transformer = require("@opentelemetry/otlp-transformer");
|
|
14
14
|
|
|
15
15
|
//#region src/observability/telemetry-system/baggage-span-processor.ts
|
|
16
|
+
/**
|
|
17
|
+
* OpenTelemetry span processor that copies OTel baggage entries onto each
|
|
18
|
+
* started span as attributes.
|
|
19
|
+
*/
|
|
16
20
|
var BaggageSpanProcessor = class {
|
|
17
21
|
onStart(span, parentContext) {
|
|
18
22
|
if (!span.isRecording()) return;
|
|
@@ -97,7 +101,7 @@ var SharedEngineConnection = class SharedEngineConnection {
|
|
|
97
101
|
this.connecting = true;
|
|
98
102
|
this.state = "connecting";
|
|
99
103
|
try {
|
|
100
|
-
this.ws = new ws.WebSocket(this.wsUrl);
|
|
104
|
+
this.ws = new ws.WebSocket(this.wsUrl, { handshakeTimeout: 1e4 });
|
|
101
105
|
this.ws.on("open", () => {
|
|
102
106
|
this.connecting = false;
|
|
103
107
|
this.state = "connected";
|
|
@@ -570,6 +574,8 @@ function injectTraceparent() {
|
|
|
570
574
|
}
|
|
571
575
|
/**
|
|
572
576
|
* Extract a trace context from a W3C traceparent header string.
|
|
577
|
+
*
|
|
578
|
+
* @param traceparent - W3C `traceparent` header value to parse.
|
|
573
579
|
*/
|
|
574
580
|
function extractTraceparent(traceparent) {
|
|
575
581
|
const carrier = { traceparent };
|
|
@@ -585,6 +591,8 @@ function injectBaggage() {
|
|
|
585
591
|
}
|
|
586
592
|
/**
|
|
587
593
|
* Extract baggage from a W3C baggage header string.
|
|
594
|
+
*
|
|
595
|
+
* @param baggage - W3C `baggage` header value to parse.
|
|
588
596
|
*/
|
|
589
597
|
function extractBaggage(baggage) {
|
|
590
598
|
const carrier = { baggage };
|
|
@@ -592,6 +600,9 @@ function extractBaggage(baggage) {
|
|
|
592
600
|
}
|
|
593
601
|
/**
|
|
594
602
|
* Extract both trace context and baggage from their respective headers.
|
|
603
|
+
*
|
|
604
|
+
* @param traceparent - W3C `traceparent` header value to parse.
|
|
605
|
+
* @param baggage - W3C `baggage` header value to parse.
|
|
595
606
|
*/
|
|
596
607
|
function extractContext(traceparent, baggage) {
|
|
597
608
|
const carrier = {};
|
|
@@ -601,12 +612,17 @@ function extractContext(traceparent, baggage) {
|
|
|
601
612
|
}
|
|
602
613
|
/**
|
|
603
614
|
* Get a baggage entry from the current context.
|
|
615
|
+
*
|
|
616
|
+
* @param key - Baggage entry key to read.
|
|
604
617
|
*/
|
|
605
618
|
function getBaggageEntry(key) {
|
|
606
619
|
return _opentelemetry_api.propagation.getBaggage(_opentelemetry_api.context.active())?.getEntry(key)?.value;
|
|
607
620
|
}
|
|
608
621
|
/**
|
|
609
622
|
* Set a baggage entry in the current context.
|
|
623
|
+
*
|
|
624
|
+
* @param key - Baggage entry key to set.
|
|
625
|
+
* @param value - Baggage entry value to set.
|
|
610
626
|
*/
|
|
611
627
|
function setBaggageEntry(key, value) {
|
|
612
628
|
let bag = _opentelemetry_api.propagation.getBaggage(_opentelemetry_api.context.active()) ?? _opentelemetry_api.propagation.createBaggage();
|
|
@@ -615,6 +631,8 @@ function setBaggageEntry(key, value) {
|
|
|
615
631
|
}
|
|
616
632
|
/**
|
|
617
633
|
* Remove a baggage entry from the current context.
|
|
634
|
+
*
|
|
635
|
+
* @param key - Baggage entry key to remove.
|
|
618
636
|
*/
|
|
619
637
|
function removeBaggageEntry(key) {
|
|
620
638
|
const bag = _opentelemetry_api.propagation.getBaggage(_opentelemetry_api.context.active());
|
|
@@ -666,6 +684,8 @@ function shouldIgnoreFetchUrl(url) {
|
|
|
666
684
|
}
|
|
667
685
|
/**
|
|
668
686
|
* Patch globalThis.fetch to create OTel CLIENT spans for every HTTP request.
|
|
687
|
+
*
|
|
688
|
+
* @param tracer - Tracer used to create the client span for each request.
|
|
669
689
|
*/
|
|
670
690
|
function patchGlobalFetch(tracer) {
|
|
671
691
|
if (originalFetch) return;
|
|
@@ -804,13 +824,22 @@ function currentSpanIsRecording() {
|
|
|
804
824
|
const span = _opentelemetry_api.trace.getActiveSpan();
|
|
805
825
|
return span ? span.isRecording() : false;
|
|
806
826
|
}
|
|
807
|
-
/**
|
|
827
|
+
/**
|
|
828
|
+
* No-op when the current span is not recording.
|
|
829
|
+
*
|
|
830
|
+
* @param key - Attribute key to set on the active span.
|
|
831
|
+
* @param value - Attribute value to set.
|
|
832
|
+
*/
|
|
808
833
|
function setCurrentSpanAttribute(key, value) {
|
|
809
834
|
const span = _opentelemetry_api.trace.getActiveSpan();
|
|
810
835
|
if (!span || !span.isRecording()) return;
|
|
811
836
|
span.setAttribute(key, value);
|
|
812
837
|
}
|
|
813
|
-
/**
|
|
838
|
+
/**
|
|
839
|
+
* No-op when there is no active span.
|
|
840
|
+
*
|
|
841
|
+
* @param message - Error message to set as the span's error status.
|
|
842
|
+
*/
|
|
814
843
|
function setCurrentSpanError(message) {
|
|
815
844
|
const span = _opentelemetry_api.trace.getActiveSpan();
|
|
816
845
|
if (!span) return;
|
|
@@ -819,7 +848,12 @@ function setCurrentSpanError(message) {
|
|
|
819
848
|
message
|
|
820
849
|
});
|
|
821
850
|
}
|
|
822
|
-
/**
|
|
851
|
+
/**
|
|
852
|
+
* No-op when the current span is not recording.
|
|
853
|
+
*
|
|
854
|
+
* @param name - Name of the event to add to the active span.
|
|
855
|
+
* @param attrs - Optional attributes to attach to the event.
|
|
856
|
+
*/
|
|
823
857
|
function recordSpanEvent(name, attrs) {
|
|
824
858
|
const span = _opentelemetry_api.trace.getActiveSpan();
|
|
825
859
|
if (!span || !span.isRecording()) return;
|
|
@@ -831,6 +865,10 @@ function recordSpanEvent(name, attrs) {
|
|
|
831
865
|
/** Payload redaction + truncation for invocation event capture. */
|
|
832
866
|
const REDACTED_PLACEHOLDER = "[REDACTED]";
|
|
833
867
|
const TRUNCATION_MARKER = "...\"[TRUNCATED]\"";
|
|
868
|
+
/**
|
|
869
|
+
* Resolve the payload byte cap from the environment, returning undefined when
|
|
870
|
+
* unset.
|
|
871
|
+
*/
|
|
834
872
|
function resolveMaxBytesFromEnv() {
|
|
835
873
|
const raw = process.env.III_TRACE_PAYLOAD_MAX_BYTES;
|
|
836
874
|
if (raw === void 0) return null;
|
|
@@ -861,7 +899,11 @@ function isSensitiveKey(key) {
|
|
|
861
899
|
if (SENSITIVE_FRAGMENTS.some((fragment) => lower.includes(fragment))) return true;
|
|
862
900
|
return lower === "token" || lower.endsWith("_token") || lower.endsWith("-token");
|
|
863
901
|
}
|
|
864
|
-
/**
|
|
902
|
+
/**
|
|
903
|
+
* Recursively redact values of sensitive keys. Returns a new value.
|
|
904
|
+
*
|
|
905
|
+
* @param value - The value to recursively redact.
|
|
906
|
+
*/
|
|
865
907
|
function redact(value) {
|
|
866
908
|
if (value === null || value === void 0) return value;
|
|
867
909
|
if (Array.isArray(value)) return value.map(redact);
|
|
@@ -872,7 +914,12 @@ function redact(value) {
|
|
|
872
914
|
}
|
|
873
915
|
return value;
|
|
874
916
|
}
|
|
875
|
-
/**
|
|
917
|
+
/**
|
|
918
|
+
* Redact then serialize to JSON, optionally capped at `maxBytes`.
|
|
919
|
+
*
|
|
920
|
+
* @param value - The value to redact and serialize.
|
|
921
|
+
* @param maxBytes - Maximum serialized size in bytes; null leaves it uncapped.
|
|
922
|
+
*/
|
|
876
923
|
function redactAndTruncate(value, maxBytes = null) {
|
|
877
924
|
const redacted = redact(value);
|
|
878
925
|
let serialized;
|
|
@@ -935,6 +982,8 @@ let serviceName = "iii-node-iii";
|
|
|
935
982
|
/**
|
|
936
983
|
* Initialize OpenTelemetry with the given configuration.
|
|
937
984
|
* This should be called once at application startup.
|
|
985
|
+
*
|
|
986
|
+
* @param config - OpenTelemetry configuration; env vars fill in unset fields.
|
|
938
987
|
*/
|
|
939
988
|
function initOtel(config = {}) {
|
|
940
989
|
if (!(config.enabled ?? parseBoolEnv(process.env.OTEL_ENABLED, DEFAULT_OTEL_CONFIG.enabled))) {
|
|
@@ -1003,7 +1052,8 @@ function initOtel(config = {}) {
|
|
|
1003
1052
|
console.debug(`[OTel] Logs initialized: delay=${logsScheduledDelayMillis}ms, batch=${logsMaxExportBatchSize}`);
|
|
1004
1053
|
}
|
|
1005
1054
|
/**
|
|
1006
|
-
*
|
|
1055
|
+
* Shut down OpenTelemetry, best-effort flushing any pending data before
|
|
1056
|
+
* teardown.
|
|
1007
1057
|
*/
|
|
1008
1058
|
async function shutdownOtel() {
|
|
1009
1059
|
sharedConnection?.beginShutdown();
|
|
@@ -1066,6 +1116,10 @@ function getLogger() {
|
|
|
1066
1116
|
}
|
|
1067
1117
|
/**
|
|
1068
1118
|
* Start a new span with the given name and run the callback within it.
|
|
1119
|
+
*
|
|
1120
|
+
* @param name - Name of the span to create.
|
|
1121
|
+
* @param options - Span options: `kind` sets the span kind, `traceparent` sets the parent context from a W3C traceparent header.
|
|
1122
|
+
* @param fn - Callback run inside the active span; its result is returned.
|
|
1069
1123
|
*/
|
|
1070
1124
|
async function withSpan(name, options, fn) {
|
|
1071
1125
|
if (!tracer) {
|
|
@@ -1282,4 +1336,4 @@ Object.defineProperty(exports, 'withSpan', {
|
|
|
1282
1336
|
return withSpan;
|
|
1283
1337
|
}
|
|
1284
1338
|
});
|
|
1285
|
-
//# sourceMappingURL=telemetry-system-
|
|
1339
|
+
//# sourceMappingURL=telemetry-system-BH119njX.cjs.map
|