@iii-dev/observability 0.16.1 → 0.16.2-next.1

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/index.mjs CHANGED
@@ -1,1062 +1,8 @@
1
- import { SeverityNumber, SeverityNumber as SeverityNumber$1 } from "@opentelemetry/api-logs";
2
- import { Resource } from "@opentelemetry/resources";
3
- import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
4
- import { randomUUID } from "node:crypto";
5
- import { SpanKind, SpanKind as SpanKind$1, SpanStatusCode, SpanStatusCode as SpanStatusCode$1, context, metrics, propagation, trace } from "@opentelemetry/api";
6
- import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-base";
7
- import { MeterProvider, PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
8
- import { CompositePropagator, ExportResultCode, W3CBaggagePropagator, W3CTraceContextPropagator } from "@opentelemetry/core";
9
- import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
10
- import { registerInstrumentations } from "@opentelemetry/instrumentation";
11
- import { BatchLogRecordProcessor, LoggerProvider } from "@opentelemetry/sdk-logs";
12
- import { WebSocket } from "ws";
13
- import { JsonLogsSerializer, JsonMetricsSerializer, JsonTraceSerializer } from "@opentelemetry/otlp-transformer";
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, j as DEFAULT_ALLOWLIST, 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-B84W8JWm.mjs";
2
+ import { SeverityNumber as SeverityNumber$1 } from "@opentelemetry/api-logs";
3
+ import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
14
4
  import { monitorEventLoopDelay, performance } from "node:perf_hooks";
15
5
 
16
- //#region src/telemetry-system/baggage-span-processor.ts
17
- /** DEFAULT_ALLOWLIST drift across languages would break worker chains;
18
- * lockstep tests in each SDK pin this constant at CI time. */
19
- const DEFAULT_ALLOWLIST = [
20
- "iii.session.id",
21
- "iii.message.id",
22
- "iii.function.id"
23
- ];
24
- var BaggageSpanProcessor = class {
25
- allowlist;
26
- constructor(allowlist = DEFAULT_ALLOWLIST) {
27
- this.allowlist = allowlist;
28
- }
29
- onStart(span, parentContext) {
30
- if (!span.isRecording()) return;
31
- const baggage = propagation.getBaggage(parentContext);
32
- if (!baggage) return;
33
- for (const key of this.allowlist) {
34
- const entry = baggage.getEntry(key);
35
- if (entry) span.setAttribute(key, entry.value);
36
- }
37
- }
38
- onEnd(_span) {}
39
- async shutdown() {}
40
- async forceFlush() {}
41
- };
42
-
43
- //#endregion
44
- //#region src/telemetry-system/types.ts
45
- const ATTR_SERVICE_VERSION = "service.version";
46
- const ATTR_SERVICE_NAMESPACE = "service.namespace";
47
- const ATTR_SERVICE_INSTANCE_ID = "service.instance.id";
48
- /** Magic prefixes for binary frames over WebSocket */
49
- const PREFIX_TRACES = "OTLP";
50
- const PREFIX_METRICS = "MTRC";
51
- const PREFIX_LOGS = "LOGS";
52
- /** Default reconnection configuration */
53
- const DEFAULT_RECONNECTION_CONFIG = {
54
- initialDelayMs: 1e3,
55
- maxDelayMs: 3e4,
56
- backoffMultiplier: 2,
57
- jitterFactor: .3,
58
- maxRetries: -1
59
- };
60
- /** Default configuration values for OpenTelemetry initialization. */
61
- const DEFAULT_OTEL_CONFIG = {
62
- enabled: true,
63
- serviceName: "iii-node",
64
- serviceVersion: "unknown",
65
- engineWsUrl: "ws://localhost:49134",
66
- metricsEnabled: true,
67
- metricsExportIntervalMs: 6e4,
68
- logsFlushIntervalMs: 100,
69
- logsBatchSize: 1,
70
- fetchInstrumentationEnabled: true
71
- };
72
- /** Parse a boolean environment variable, recognizing 'false', '0', 'no', 'off' as false. */
73
- function parseBoolEnv(value, defaultValue) {
74
- if (value === void 0) return defaultValue;
75
- const lower = value.toLowerCase();
76
- return lower !== "false" && lower !== "0" && lower !== "no" && lower !== "off";
77
- }
78
-
79
- //#endregion
80
- //#region src/telemetry-system/connection.ts
81
- /**
82
- * Shared WebSocket connection for OpenTelemetry exporters.
83
- */
84
- /**
85
- * Shared WebSocket connection for all OTEL exporters (traces, metrics, logs).
86
- * Uses a single connection with message prefixes to identify signal type.
87
- */
88
- var SharedEngineConnection = class SharedEngineConnection {
89
- static MAX_PENDING_MESSAGES = 1e3;
90
- ws = null;
91
- wsUrl;
92
- connecting = false;
93
- shuttingDown = false;
94
- pendingMessages = [];
95
- reconnectAttempt = 0;
96
- reconnectTimeout = null;
97
- config;
98
- state = "disconnected";
99
- onConnectedCallbacks = [];
100
- onFailedCallbacks = [];
101
- constructor(wsUrl, config = {}) {
102
- this.wsUrl = wsUrl;
103
- this.config = {
104
- ...DEFAULT_RECONNECTION_CONFIG,
105
- ...config
106
- };
107
- this.connect();
108
- }
109
- connect() {
110
- if (this.connecting || this.ws && this.ws.readyState === WebSocket.OPEN) return;
111
- this.connecting = true;
112
- this.state = "connecting";
113
- try {
114
- this.ws = new WebSocket(this.wsUrl);
115
- this.ws.on("open", () => {
116
- this.connecting = false;
117
- this.state = "connected";
118
- console.log(`[OTel] Connected to engine at ${this.wsUrl}`);
119
- if (this.reconnectAttempt > 0) console.log("[OTel] Successfully reconnected");
120
- this.reconnectAttempt = 0;
121
- if (this.reconnectTimeout) {
122
- clearTimeout(this.reconnectTimeout);
123
- this.reconnectTimeout = null;
124
- }
125
- const pending = this.pendingMessages.splice(0, this.pendingMessages.length);
126
- for (const { frame, callback } of pending) this.ws?.send(frame, (err) => callback?.(err));
127
- for (const cb of this.onConnectedCallbacks) cb();
128
- });
129
- this.ws.on("close", () => {
130
- this.connecting = false;
131
- this.ws = null;
132
- if (this.shuttingDown) {
133
- this.state = "disconnected";
134
- console.log("[OTel] Connection closed during shutdown");
135
- return;
136
- }
137
- this.state = "disconnected";
138
- console.log("[OTel] Disconnected from engine, will reconnect...");
139
- this.scheduleReconnect();
140
- });
141
- this.ws.on("error", (err) => {
142
- this.connecting = false;
143
- if (this.shuttingDown) return;
144
- console.error("[OTel] WebSocket error:", err.message);
145
- });
146
- } catch (err) {
147
- this.connecting = false;
148
- console.error("[OTel] Connection failed:", err);
149
- this.scheduleReconnect();
150
- }
151
- }
152
- scheduleReconnect() {
153
- if (this.config.maxRetries !== -1 && this.reconnectAttempt >= this.config.maxRetries) {
154
- this.state = "failed";
155
- console.error(`[OTel] Max retries (${this.config.maxRetries}) reached, giving up`);
156
- const pending = this.pendingMessages.splice(0, this.pendingMessages.length);
157
- const failedError = /* @__PURE__ */ new Error("Connection failed after max retries");
158
- for (const { callback } of pending) callback?.(failedError);
159
- for (const cb of this.onFailedCallbacks) try {
160
- cb();
161
- } catch (err) {
162
- console.error("[OTel] onFailed callback threw:", err);
163
- }
164
- return;
165
- }
166
- if (this.reconnectTimeout) return;
167
- const exponentialDelay = this.config.initialDelayMs * this.config.backoffMultiplier ** this.reconnectAttempt;
168
- const cappedDelay = Math.min(exponentialDelay, this.config.maxDelayMs);
169
- const jitter = cappedDelay * this.config.jitterFactor * (2 * Math.random() - 1);
170
- const delay = Math.max(0, Math.floor(cappedDelay + jitter));
171
- this.state = "reconnecting";
172
- console.log(`[OTel] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempt + 1})...`);
173
- this.reconnectTimeout = setTimeout(() => {
174
- this.reconnectTimeout = null;
175
- this.reconnectAttempt++;
176
- this.connect();
177
- }, delay);
178
- }
179
- /**
180
- * Send a message with a signal prefix.
181
- */
182
- send(prefix, data, callback) {
183
- const prefixBytes = Buffer.from(prefix, "utf-8");
184
- const frame = Buffer.concat([prefixBytes, Buffer.from(data)]);
185
- if (this.ws && this.ws.readyState === WebSocket.OPEN) this.ws.send(frame, callback);
186
- else {
187
- if (this.pendingMessages.length >= SharedEngineConnection.MAX_PENDING_MESSAGES) {
188
- console.warn("[OTel] Pending message queue full, dropping oldest message");
189
- this.pendingMessages.shift()?.callback?.(/* @__PURE__ */ new Error("Message dropped due to queue overflow"));
190
- }
191
- this.pendingMessages.push({
192
- frame,
193
- callback
194
- });
195
- this.connect();
196
- }
197
- }
198
- /**
199
- * Register a callback to be called when connected.
200
- */
201
- onConnected(callback) {
202
- this.onConnectedCallbacks.push(callback);
203
- if (this.state === "connected") callback();
204
- }
205
- /**
206
- * Register a callback to be called when the connection enters the failed
207
- * terminal state (max retries reached). Exporters use this to drain their
208
- * own pending queues so in-flight forceFlush() calls do not hang.
209
- */
210
- onFailed(callback) {
211
- this.onFailedCallbacks.push(callback);
212
- if (this.state === "failed") try {
213
- callback();
214
- } catch (err) {
215
- console.error("[OTel] onFailed callback threw:", err);
216
- }
217
- }
218
- /**
219
- * Get the current connection state.
220
- */
221
- getState() {
222
- return this.state;
223
- }
224
- /**
225
- * Shutdown the connection.
226
- */
227
- async shutdown() {
228
- this.shuttingDown = true;
229
- if (this.reconnectTimeout) {
230
- clearTimeout(this.reconnectTimeout);
231
- this.reconnectTimeout = null;
232
- }
233
- if (this.ws) {
234
- this.ws.close();
235
- this.ws = null;
236
- }
237
- const pending = this.pendingMessages.splice(0, this.pendingMessages.length);
238
- const shutdownError = /* @__PURE__ */ new Error("Connection shutdown before message could be sent");
239
- for (const { callback } of pending) callback?.(shutdownError);
240
- this.onConnectedCallbacks = [];
241
- this.onFailedCallbacks = [];
242
- this.state = "disconnected";
243
- }
244
- };
245
-
246
- //#endregion
247
- //#region src/telemetry-system/span-exporter.ts
248
- /**
249
- * Span exporter for the III Engine.
250
- */
251
- /**
252
- * Span exporter using the shared WebSocket connection.
253
- */
254
- var EngineSpanExporter = class EngineSpanExporter {
255
- static MAX_PENDING_EXPORTS = 100;
256
- connection;
257
- pendingExports = [];
258
- constructor(connection) {
259
- this.connection = connection;
260
- this.connection.onConnected(() => this.flushPending());
261
- this.connection.onFailed(() => this.failPending());
262
- }
263
- flushPending() {
264
- const pending = this.pendingExports.splice(0, this.pendingExports.length);
265
- for (const { spans, resultCallback } of pending) this.sendExport(spans, resultCallback);
266
- }
267
- failPending() {
268
- const pending = this.pendingExports.splice(0, this.pendingExports.length);
269
- const error = /* @__PURE__ */ new Error("Connection failed: dropping queued spans");
270
- for (const { resultCallback } of pending) resultCallback?.({
271
- code: ExportResultCode.FAILED,
272
- error
273
- });
274
- }
275
- sendExport(spans, resultCallback) {
276
- try {
277
- const serialized = JsonTraceSerializer.serializeRequest(spans);
278
- if (!serialized) {
279
- resultCallback?.({ code: ExportResultCode.SUCCESS });
280
- return;
281
- }
282
- this.connection.send(PREFIX_TRACES, serialized, (err) => {
283
- if (err) {
284
- console.error("[OTel] Failed to send spans:", err.message);
285
- resultCallback?.({
286
- code: ExportResultCode.FAILED,
287
- error: err
288
- });
289
- } else resultCallback?.({ code: ExportResultCode.SUCCESS });
290
- });
291
- } catch (err) {
292
- console.error("[OTel] Error exporting spans:", err);
293
- resultCallback?.({
294
- code: ExportResultCode.FAILED,
295
- error: err
296
- });
297
- }
298
- }
299
- doExport(spans, resultCallback) {
300
- const state = this.connection.getState();
301
- if (state === "failed") {
302
- resultCallback({
303
- code: ExportResultCode.FAILED,
304
- error: /* @__PURE__ */ new Error("Connection failed: dropping spans")
305
- });
306
- return;
307
- }
308
- if (state !== "connected") {
309
- if (this.pendingExports.length >= EngineSpanExporter.MAX_PENDING_EXPORTS) {
310
- this.pendingExports.shift()?.resultCallback?.({
311
- code: ExportResultCode.FAILED,
312
- error: /* @__PURE__ */ new Error("Queue overflow")
313
- });
314
- console.warn("[OTel] Spans export queue full, dropped oldest entry");
315
- }
316
- this.pendingExports.push({
317
- spans,
318
- resultCallback
319
- });
320
- return;
321
- }
322
- this.sendExport(spans, resultCallback);
323
- }
324
- export(spans, resultCallback) {
325
- this.doExport(spans, resultCallback);
326
- }
327
- async shutdown() {
328
- const pending = this.pendingExports.splice(0, this.pendingExports.length);
329
- const shutdownError = /* @__PURE__ */ new Error("Exporter shutdown before export completed");
330
- for (const { resultCallback } of pending) resultCallback?.({
331
- code: ExportResultCode.FAILED,
332
- error: shutdownError
333
- });
334
- }
335
- async forceFlush() {}
336
- };
337
-
338
- //#endregion
339
- //#region src/telemetry-system/metrics-exporter.ts
340
- /**
341
- * Metrics exporter for the III Engine.
342
- */
343
- /**
344
- * Metrics exporter using the shared WebSocket connection.
345
- */
346
- var EngineMetricsExporter = class EngineMetricsExporter {
347
- static MAX_PENDING_EXPORTS = 100;
348
- connection;
349
- pendingExports = [];
350
- constructor(connection) {
351
- this.connection = connection;
352
- this.connection.onConnected(() => this.flushPending());
353
- this.connection.onFailed(() => this.failPending());
354
- }
355
- flushPending() {
356
- const pending = this.pendingExports.splice(0, this.pendingExports.length);
357
- for (const { metrics, resultCallback } of pending) this.sendExport(metrics, resultCallback);
358
- }
359
- failPending() {
360
- const pending = this.pendingExports.splice(0, this.pendingExports.length);
361
- const error = /* @__PURE__ */ new Error("Connection failed: dropping queued metrics");
362
- for (const { resultCallback } of pending) resultCallback?.({
363
- code: ExportResultCode.FAILED,
364
- error
365
- });
366
- }
367
- sendExport(metricsData, resultCallback) {
368
- try {
369
- const serialized = JsonMetricsSerializer.serializeRequest(metricsData);
370
- if (!serialized) {
371
- resultCallback?.({ code: ExportResultCode.SUCCESS });
372
- return;
373
- }
374
- this.connection.send(PREFIX_METRICS, serialized, (err) => {
375
- if (err) {
376
- console.error("[OTel] Failed to send metrics:", err.message);
377
- resultCallback?.({
378
- code: ExportResultCode.FAILED,
379
- error: err
380
- });
381
- } else resultCallback?.({ code: ExportResultCode.SUCCESS });
382
- });
383
- } catch (err) {
384
- console.error("[OTel] Error exporting metrics:", err);
385
- resultCallback?.({
386
- code: ExportResultCode.FAILED,
387
- error: err
388
- });
389
- }
390
- }
391
- doExport(metricsData, resultCallback) {
392
- const state = this.connection.getState();
393
- if (state === "failed") {
394
- resultCallback({
395
- code: ExportResultCode.FAILED,
396
- error: /* @__PURE__ */ new Error("Connection failed: dropping metrics")
397
- });
398
- return;
399
- }
400
- if (state !== "connected") {
401
- if (this.pendingExports.length >= EngineMetricsExporter.MAX_PENDING_EXPORTS) {
402
- this.pendingExports.shift()?.resultCallback?.({
403
- code: ExportResultCode.FAILED,
404
- error: /* @__PURE__ */ new Error("Queue overflow")
405
- });
406
- console.warn("[OTel] Metrics export queue full, dropped oldest entry");
407
- }
408
- this.pendingExports.push({
409
- metrics: metricsData,
410
- resultCallback
411
- });
412
- return;
413
- }
414
- this.sendExport(metricsData, resultCallback);
415
- }
416
- export(metrics, resultCallback) {
417
- this.doExport(metrics, resultCallback);
418
- }
419
- async shutdown() {
420
- const pending = this.pendingExports.splice(0, this.pendingExports.length);
421
- const shutdownError = /* @__PURE__ */ new Error("Exporter shutdown before export completed");
422
- for (const { resultCallback } of pending) resultCallback?.({
423
- code: ExportResultCode.FAILED,
424
- error: shutdownError
425
- });
426
- }
427
- async forceFlush() {}
428
- };
429
-
430
- //#endregion
431
- //#region src/telemetry-system/log-exporter.ts
432
- /**
433
- * Log exporter for the III Engine.
434
- */
435
- /**
436
- * Log exporter using the shared WebSocket connection.
437
- */
438
- var EngineLogExporter = class EngineLogExporter {
439
- static MAX_PENDING_EXPORTS = 100;
440
- connection;
441
- pendingExports = [];
442
- constructor(connection) {
443
- this.connection = connection;
444
- this.connection.onConnected(() => this.flushPending());
445
- this.connection.onFailed(() => this.failPending());
446
- }
447
- flushPending() {
448
- const pending = this.pendingExports.splice(0, this.pendingExports.length);
449
- for (const { logs, callback } of pending) this.doExport(logs, callback);
450
- }
451
- failPending() {
452
- const pending = this.pendingExports.splice(0, this.pendingExports.length);
453
- const error = /* @__PURE__ */ new Error("Connection failed: dropping queued logs");
454
- for (const { callback } of pending) callback({
455
- code: ExportResultCode.FAILED,
456
- error
457
- });
458
- }
459
- doExport(logs, resultCallback) {
460
- const state = this.connection.getState();
461
- if (state === "failed") {
462
- resultCallback({
463
- code: ExportResultCode.FAILED,
464
- error: /* @__PURE__ */ new Error("Connection failed: dropping logs")
465
- });
466
- return;
467
- }
468
- if (state !== "connected") {
469
- if (this.pendingExports.length >= EngineLogExporter.MAX_PENDING_EXPORTS) {
470
- this.pendingExports.shift()?.callback({
471
- code: ExportResultCode.FAILED,
472
- error: /* @__PURE__ */ new Error("Logs export queue full")
473
- });
474
- console.warn("[OTel] Logs export queue full, dropped oldest entry");
475
- }
476
- this.pendingExports.push({
477
- logs,
478
- callback: resultCallback
479
- });
480
- return;
481
- }
482
- try {
483
- const serialized = JsonLogsSerializer.serializeRequest(logs);
484
- if (!serialized) {
485
- resultCallback({ code: ExportResultCode.SUCCESS });
486
- return;
487
- }
488
- this.connection.send(PREFIX_LOGS, serialized, (err) => {
489
- if (err) {
490
- console.error("[OTel] Failed to send logs:", err.message);
491
- resultCallback({
492
- code: ExportResultCode.FAILED,
493
- error: err
494
- });
495
- } else resultCallback({ code: ExportResultCode.SUCCESS });
496
- });
497
- } catch (err) {
498
- console.error("[OTel] Error exporting logs:", err);
499
- resultCallback({
500
- code: ExportResultCode.FAILED,
501
- error: err
502
- });
503
- }
504
- }
505
- export(logs, resultCallback) {
506
- this.doExport(logs, resultCallback);
507
- }
508
- async forceFlush() {}
509
- async shutdown() {
510
- for (const { callback } of this.pendingExports) callback({
511
- code: ExportResultCode.FAILED,
512
- error: /* @__PURE__ */ new Error("Exporter shutdown")
513
- });
514
- this.pendingExports = [];
515
- }
516
- };
517
-
518
- //#endregion
519
- //#region src/telemetry-system/context.ts
520
- /**
521
- * Trace context and baggage propagation utilities.
522
- */
523
- /**
524
- * Extract the current trace ID from the active span context.
525
- */
526
- function currentTraceId() {
527
- const span = trace.getActiveSpan();
528
- if (span) {
529
- const spanContext = span.spanContext();
530
- if (spanContext.traceId && spanContext.traceId !== "00000000000000000000000000000000") return spanContext.traceId;
531
- }
532
- }
533
- /**
534
- * Extract the current span ID from the active span context.
535
- */
536
- function currentSpanId() {
537
- const span = trace.getActiveSpan();
538
- if (span) {
539
- const spanContext = span.spanContext();
540
- if (spanContext.spanId && spanContext.spanId !== "0000000000000000") return spanContext.spanId;
541
- }
542
- }
543
- /**
544
- * Inject the current trace context into a W3C traceparent header string.
545
- */
546
- function injectTraceparent() {
547
- const carrier = {};
548
- propagation.inject(context.active(), carrier);
549
- return carrier.traceparent;
550
- }
551
- /**
552
- * Extract a trace context from a W3C traceparent header string.
553
- */
554
- function extractTraceparent(traceparent) {
555
- const carrier = { traceparent };
556
- return propagation.extract(context.active(), carrier);
557
- }
558
- /**
559
- * Inject the current baggage into a W3C baggage header string.
560
- */
561
- function injectBaggage() {
562
- const carrier = {};
563
- propagation.inject(context.active(), carrier);
564
- return carrier.baggage;
565
- }
566
- /**
567
- * Extract baggage from a W3C baggage header string.
568
- */
569
- function extractBaggage(baggage) {
570
- const carrier = { baggage };
571
- return propagation.extract(context.active(), carrier);
572
- }
573
- /**
574
- * Extract both trace context and baggage from their respective headers.
575
- */
576
- function extractContext(traceparent, baggage) {
577
- const carrier = {};
578
- if (traceparent) carrier.traceparent = traceparent;
579
- if (baggage) carrier.baggage = baggage;
580
- return propagation.extract(context.active(), carrier);
581
- }
582
- /**
583
- * Get a baggage entry from the current context.
584
- */
585
- function getBaggageEntry(key) {
586
- return propagation.getBaggage(context.active())?.getEntry(key)?.value;
587
- }
588
- /**
589
- * Set a baggage entry in the current context.
590
- */
591
- function setBaggageEntry(key, value) {
592
- let bag = propagation.getBaggage(context.active()) ?? propagation.createBaggage();
593
- bag = bag.setEntry(key, { value });
594
- return propagation.setBaggage(context.active(), bag);
595
- }
596
- /**
597
- * Remove a baggage entry from the current context.
598
- */
599
- function removeBaggageEntry(key) {
600
- const bag = propagation.getBaggage(context.active());
601
- if (!bag) return context.active();
602
- const newBag = bag.removeEntry(key);
603
- return propagation.setBaggage(context.active(), newBag);
604
- }
605
- /**
606
- * Get all baggage entries from the current context.
607
- */
608
- function getAllBaggage() {
609
- const bag = propagation.getBaggage(context.active());
610
- if (!bag) return {};
611
- const entries = {};
612
- for (const [key, entry] of bag.getAllEntries()) entries[key] = entry.value;
613
- return entries;
614
- }
615
-
616
- //#endregion
617
- //#region src/telemetry-system/fetch-instrumentation.ts
618
- /**
619
- * Global fetch auto-instrumentation for the III Node SDK.
620
- *
621
- * Patches globalThis.fetch to create OTel CLIENT spans for every HTTP request.
622
- * Works on all runtimes (Bun, Node.js, Deno) unlike UndiciInstrumentation
623
- * which only works when fetch is backed by Node.js's undici.
624
- */
625
- const textEncoder = new TextEncoder();
626
- function getBodyByteSize(body) {
627
- if (body == null) return void 0;
628
- if (typeof body === "string") return textEncoder.encode(body).byteLength;
629
- if (body instanceof ArrayBuffer) return body.byteLength;
630
- if (ArrayBuffer.isView(body)) return body.byteLength;
631
- if (body instanceof Blob) return body.size;
632
- if (body instanceof URLSearchParams) return new TextEncoder().encode(body.toString()).byteLength;
633
- }
634
- const SAFE_REQUEST_HEADERS$1 = ["content-type", "accept"];
635
- const SAFE_RESPONSE_HEADERS$1 = ["content-type"];
636
- let originalFetch = null;
637
- /**
638
- * Patch globalThis.fetch to create OTel CLIENT spans for every HTTP request.
639
- */
640
- function patchGlobalFetch(tracer) {
641
- if (originalFetch) return;
642
- originalFetch = globalThis.fetch;
643
- const capturedFetch = originalFetch;
644
- globalThis.fetch = async (input, init) => {
645
- const url = input instanceof Request ? input.url : String(input);
646
- const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
647
- let host;
648
- let scheme;
649
- let path;
650
- let port;
651
- let query;
652
- try {
653
- const parsed = new URL(url);
654
- host = parsed.hostname;
655
- scheme = parsed.protocol.replace(":", "");
656
- path = parsed.pathname;
657
- port = parsed.port ? parseInt(parsed.port, 10) : void 0;
658
- query = parsed.search ? parsed.search.slice(1) : void 0;
659
- } catch {}
660
- const spanAttributes = {
661
- "http.request.method": method,
662
- "url.full": url
663
- };
664
- if (host) spanAttributes["server.address"] = host;
665
- if (scheme) {
666
- spanAttributes["url.scheme"] = scheme;
667
- spanAttributes["network.protocol.name"] = "http";
668
- }
669
- if (path) spanAttributes["url.path"] = path;
670
- if (port) spanAttributes["server.port"] = port;
671
- if (query) spanAttributes["url.query"] = query;
672
- const spanName = path ? `${method} ${path}` : method;
673
- return tracer.startActiveSpan(spanName, {
674
- kind: SpanKind$1.CLIENT,
675
- attributes: spanAttributes
676
- }, context.active(), async (span) => {
677
- try {
678
- const carrier = {};
679
- propagation.inject(context.active(), carrier);
680
- const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : void 0));
681
- for (const [key, value] of Object.entries(carrier)) headers.set(key, value);
682
- for (const name of SAFE_REQUEST_HEADERS$1) {
683
- const value = headers.get(name);
684
- if (value !== null) span.setAttribute(`http.request.header.${name}`, value);
685
- }
686
- const requestBodySize = getBodyByteSize(init?.body ?? (input instanceof Request ? input.body : void 0));
687
- if (requestBodySize !== void 0) span.setAttribute("http.request.body.size", requestBodySize);
688
- const response = await capturedFetch(input, {
689
- ...init,
690
- headers
691
- });
692
- span.setAttribute("http.response.status_code", response.status);
693
- const contentLength = response.headers.get("content-length");
694
- if (contentLength !== null) {
695
- const size = parseInt(contentLength, 10);
696
- if (!Number.isNaN(size)) span.setAttribute("http.response.body.size", size);
697
- }
698
- for (const name of SAFE_RESPONSE_HEADERS$1) {
699
- const value = response.headers.get(name);
700
- if (value !== null) span.setAttribute(`http.response.header.${name}`, value);
701
- }
702
- if (response.status >= 400) {
703
- span.setAttribute("error.type", String(response.status));
704
- span.setStatus({ code: SpanStatusCode.ERROR });
705
- } else span.setStatus({ code: SpanStatusCode.OK });
706
- return response;
707
- } catch (error) {
708
- span.setAttribute("error.type", error.name ?? "Error");
709
- span.setStatus({
710
- code: SpanStatusCode.ERROR,
711
- message: error.message
712
- });
713
- span.recordException(error);
714
- throw error;
715
- } finally {
716
- span.end();
717
- }
718
- });
719
- };
720
- }
721
- /**
722
- * Restore globalThis.fetch to its original implementation.
723
- */
724
- function unpatchGlobalFetch() {
725
- if (originalFetch) {
726
- globalThis.fetch = originalFetch;
727
- originalFetch = null;
728
- }
729
- }
730
-
731
- //#endregion
732
- //#region src/telemetry-system/utils.ts
733
- /**
734
- * Parse a numeric environment variable with optional minimum bound.
735
- */
736
- function parseNumberEnv(value, minimum = 0) {
737
- if (value === void 0) return void 0;
738
- const parsed = Number(value);
739
- if (!Number.isFinite(parsed) || parsed < minimum) return void 0;
740
- return parsed;
741
- }
742
- /**
743
- * Parse an integer environment variable with optional minimum bound.
744
- */
745
- function parseIntegerEnv(value, minimum = 0) {
746
- const parsed = parseNumberEnv(value, minimum);
747
- if (parsed === void 0 || !Number.isInteger(parsed)) return void 0;
748
- return parsed;
749
- }
750
-
751
- //#endregion
752
- //#region src/telemetry-system/span-ops.ts
753
- /** High-level span operations so consumers don't need `@opentelemetry/api`. */
754
- /** Returns `false` when there is no active span or the sampler dropped it. */
755
- function currentSpanIsRecording() {
756
- const span = trace.getActiveSpan();
757
- return span ? span.isRecording() : false;
758
- }
759
- /** No-op when the current span is not recording. */
760
- function setCurrentSpanAttribute(key, value) {
761
- const span = trace.getActiveSpan();
762
- if (!span || !span.isRecording()) return;
763
- span.setAttribute(key, value);
764
- }
765
- /** No-op when there is no active span. */
766
- function setCurrentSpanError(message) {
767
- const span = trace.getActiveSpan();
768
- if (!span) return;
769
- span.setStatus({
770
- code: SpanStatusCode.ERROR,
771
- message
772
- });
773
- }
774
- /** No-op when the current span is not recording. */
775
- function recordSpanEvent(name, attrs) {
776
- const span = trace.getActiveSpan();
777
- if (!span || !span.isRecording()) return;
778
- span.addEvent(name, attrs);
779
- }
780
-
781
- //#endregion
782
- //#region src/telemetry-system/payload.ts
783
- /** Payload redaction + truncation for invocation event capture. */
784
- const REDACTED_PLACEHOLDER = "[REDACTED]";
785
- const TRUNCATION_MARKER = "...\"[TRUNCATED]\"";
786
- function resolveMaxBytesFromEnv() {
787
- const raw = process.env.III_TRACE_PAYLOAD_MAX_BYTES;
788
- if (raw === void 0) return null;
789
- const trimmed = raw.trim();
790
- if (trimmed === "" || trimmed.toLowerCase() === "unlimited") return null;
791
- if (!/^\d+$/.test(trimmed)) return null;
792
- const parsed = Number(trimmed);
793
- if (parsed <= 0) return null;
794
- return parsed;
795
- }
796
- const SENSITIVE_FRAGMENTS = [
797
- "api_key",
798
- "apikey",
799
- "api-key",
800
- "password",
801
- "secret",
802
- "credential",
803
- "authorization",
804
- "auth_token",
805
- "access_token",
806
- "refresh_token",
807
- "bearer",
808
- "private_key",
809
- "client_secret"
810
- ];
811
- function isSensitiveKey(key) {
812
- const lower = key.toLowerCase();
813
- if (SENSITIVE_FRAGMENTS.some((fragment) => lower.includes(fragment))) return true;
814
- return lower === "token" || lower.endsWith("_token") || lower.endsWith("-token");
815
- }
816
- /** Recursively redact values of sensitive keys. Returns a new value. */
817
- function redact(value) {
818
- if (value === null || value === void 0) return value;
819
- if (Array.isArray(value)) return value.map(redact);
820
- if (typeof value === "object") {
821
- const out = {};
822
- for (const [k, v] of Object.entries(value)) out[k] = isSensitiveKey(k) ? REDACTED_PLACEHOLDER : redact(v);
823
- return out;
824
- }
825
- return value;
826
- }
827
- /** Redact then serialize to JSON, optionally capped at `maxBytes`. */
828
- function redactAndTruncate(value, maxBytes = null) {
829
- const redacted = redact(value);
830
- let serialized;
831
- try {
832
- serialized = JSON.stringify(redacted) ?? "null";
833
- } catch {
834
- serialized = "null";
835
- }
836
- if (maxBytes === null || maxBytes === void 0 || maxBytes <= 0) return {
837
- json: serialized,
838
- truncated: false
839
- };
840
- if (Buffer.byteLength(serialized, "utf8") <= maxBytes) return {
841
- json: serialized,
842
- truncated: false
843
- };
844
- const markerLen = Buffer.byteLength(TRUNCATION_MARKER, "utf8");
845
- if (maxBytes <= markerLen) return {
846
- json: TRUNCATION_MARKER.slice(0, maxBytes),
847
- truncated: true
848
- };
849
- const cap = maxBytes - markerLen;
850
- const buf = Buffer.from(serialized, "utf8");
851
- let cut = Math.min(cap, buf.length);
852
- while (cut > 0 && (buf[cut] & 192) === 128) cut -= 1;
853
- return {
854
- json: buf.subarray(0, cut).toString("utf8") + TRUNCATION_MARKER,
855
- truncated: true
856
- };
857
- }
858
-
859
- //#endregion
860
- //#region src/telemetry-system/index.ts
861
- /**
862
- * OpenTelemetry initialization for the III Node SDK.
863
- *
864
- * This module provides trace, metrics, and log export to the III Engine
865
- * via a shared WebSocket connection using OTLP JSON format.
866
- */
867
- /**
868
- * Normalize an engine WebSocket URL into the dedicated OTEL endpoint.
869
- * The engine exposes `/otel` for telemetry-only WS connections; routing
870
- * there keeps this socket out of the worker registry (otherwise it shows
871
- * up as a ghost null-metadata worker).
872
- */
873
- function appendOtelPath(base) {
874
- const url = new URL(base);
875
- const path = url.pathname.replace(/\/+$/, "");
876
- url.pathname = path.endsWith("/otel") ? path : `${path}/otel`;
877
- return url.toString();
878
- }
879
- let sharedConnection = null;
880
- let tracerProvider = null;
881
- let meterProvider = null;
882
- let loggerProvider = null;
883
- let tracer = null;
884
- let meter = null;
885
- let logger = null;
886
- let serviceName = "iii-node-iii";
887
- /**
888
- * Initialize OpenTelemetry with the given configuration.
889
- * This should be called once at application startup.
890
- */
891
- function initOtel(config = {}) {
892
- if (!(config.enabled ?? parseBoolEnv(process.env.OTEL_ENABLED, DEFAULT_OTEL_CONFIG.enabled))) {
893
- console.debug("[OTel] OpenTelemetry is disabled. To enable, remove OTEL_ENABLED=false or set enabled: true in config.");
894
- return;
895
- }
896
- serviceName = config.serviceName ?? process.env.OTEL_SERVICE_NAME ?? DEFAULT_OTEL_CONFIG.serviceName;
897
- const serviceVersion = config.serviceVersion ?? process.env.SERVICE_VERSION ?? DEFAULT_OTEL_CONFIG.serviceVersion;
898
- const serviceNamespace = config.serviceNamespace ?? process.env.SERVICE_NAMESPACE;
899
- const serviceInstanceId = config.serviceInstanceId ?? process.env.SERVICE_INSTANCE_ID ?? randomUUID();
900
- const engineWsUrl = config.engineWsUrl ?? process.env.III_URL ?? DEFAULT_OTEL_CONFIG.engineWsUrl;
901
- const resourceAttributes = {
902
- [ATTR_SERVICE_NAME]: serviceName,
903
- [ATTR_SERVICE_VERSION]: serviceVersion,
904
- [ATTR_SERVICE_INSTANCE_ID]: serviceInstanceId
905
- };
906
- if (serviceNamespace) resourceAttributes[ATTR_SERVICE_NAMESPACE] = serviceNamespace;
907
- const resource = new Resource(resourceAttributes);
908
- sharedConnection = new SharedEngineConnection(appendOtelPath(engineWsUrl), config.reconnectionConfig);
909
- const spanExporter = new EngineSpanExporter(sharedConnection);
910
- tracerProvider = new NodeTracerProvider({
911
- resource,
912
- spanProcessors: [new BaggageSpanProcessor(), new BatchSpanProcessor(spanExporter)]
913
- });
914
- propagation.setGlobalPropagator(new CompositePropagator({ propagators: [new W3CTraceContextPropagator(), new W3CBaggagePropagator()] }));
915
- tracerProvider.register();
916
- tracer = trace.getTracer(serviceName);
917
- console.debug(`[OTel] Traces initialized: engine=${engineWsUrl}, service=${serviceName}`);
918
- if (config.metricsEnabled ?? parseBoolEnv(process.env.OTEL_METRICS_ENABLED, DEFAULT_OTEL_CONFIG.metricsEnabled)) {
919
- const metricsExporter = new EngineMetricsExporter(sharedConnection);
920
- const exportIntervalMs = config.metricsExportIntervalMs ?? DEFAULT_OTEL_CONFIG.metricsExportIntervalMs;
921
- meterProvider = new MeterProvider({
922
- resource,
923
- readers: [new PeriodicExportingMetricReader({
924
- exporter: metricsExporter,
925
- exportIntervalMillis: exportIntervalMs
926
- })]
927
- });
928
- metrics.setGlobalMeterProvider(meterProvider);
929
- meter = meterProvider.getMeter(serviceName);
930
- console.debug(`[OTel] Metrics initialized: interval=${exportIntervalMs}ms`);
931
- }
932
- const instrumentations = [...config.instrumentations ?? []];
933
- if (instrumentations.length > 0) {
934
- registerInstrumentations({
935
- instrumentations,
936
- tracerProvider,
937
- meterProvider: meterProvider ?? void 0
938
- });
939
- console.debug(`[OTel] Instrumentations registered: ${instrumentations.length} total`);
940
- }
941
- if (config.fetchInstrumentationEnabled ?? DEFAULT_OTEL_CONFIG.fetchInstrumentationEnabled) {
942
- patchGlobalFetch(tracer);
943
- console.debug("[OTel] Global fetch instrumentation enabled");
944
- }
945
- const logExporter = new EngineLogExporter(sharedConnection);
946
- const logsScheduledDelayMillis = config.logsFlushIntervalMs ?? parseNumberEnv(process.env.OTEL_LOGS_FLUSH_INTERVAL_MS, 0) ?? DEFAULT_OTEL_CONFIG.logsFlushIntervalMs;
947
- const logsMaxExportBatchSize = config.logsBatchSize ?? parseIntegerEnv(process.env.OTEL_LOGS_BATCH_SIZE, 1) ?? DEFAULT_OTEL_CONFIG.logsBatchSize;
948
- loggerProvider = new LoggerProvider({ resource });
949
- loggerProvider.addLogRecordProcessor(new BatchLogRecordProcessor(logExporter, {
950
- scheduledDelayMillis: logsScheduledDelayMillis,
951
- maxExportBatchSize: logsMaxExportBatchSize
952
- }));
953
- logger = loggerProvider.getLogger(serviceName);
954
- console.debug(`[OTel] Logs initialized: delay=${logsScheduledDelayMillis}ms, batch=${logsMaxExportBatchSize}`);
955
- }
956
- /**
957
- * Shutdown OpenTelemetry, flushing any pending data.
958
- */
959
- async function shutdownOtel() {
960
- if (tracerProvider) {
961
- await tracerProvider.forceFlush();
962
- await tracerProvider.shutdown();
963
- tracerProvider = null;
964
- }
965
- if (meterProvider) {
966
- await meterProvider.forceFlush();
967
- await meterProvider.shutdown();
968
- meterProvider = null;
969
- }
970
- if (loggerProvider) {
971
- await loggerProvider.forceFlush();
972
- await loggerProvider.shutdown();
973
- loggerProvider = null;
974
- }
975
- if (sharedConnection) {
976
- await sharedConnection.shutdown();
977
- sharedConnection = null;
978
- }
979
- unpatchGlobalFetch();
980
- tracer = null;
981
- meter = null;
982
- logger = null;
983
- }
984
- /**
985
- * Force-flush all OTel providers without tearing them down.
986
- *
987
- * Counterpart to {@link shutdownOtel}. Use before short-lived process exits
988
- * where you want pending spans/metrics/logs delivered but plan to keep using
989
- * OTel afterwards.
990
- */
991
- async function flushOtel() {
992
- await Promise.all([
993
- tracerProvider?.forceFlush(),
994
- meterProvider?.forceFlush(),
995
- loggerProvider?.forceFlush()
996
- ].filter(Boolean));
997
- }
998
- /**
999
- * Get the OpenTelemetry tracer instance.
1000
- */
1001
- function getTracer() {
1002
- return tracer;
1003
- }
1004
- /**
1005
- * Get the OpenTelemetry meter instance.
1006
- */
1007
- function getMeter() {
1008
- return meter;
1009
- }
1010
- /**
1011
- * Get the OpenTelemetry logger instance.
1012
- */
1013
- function getLogger() {
1014
- return logger;
1015
- }
1016
- /**
1017
- * Start a new span with the given name and run the callback within it.
1018
- */
1019
- async function withSpan(name, options, fn) {
1020
- if (!tracer) {
1021
- const noopSpan = {
1022
- spanContext: () => ({
1023
- traceId: "",
1024
- spanId: "",
1025
- traceFlags: 0
1026
- }),
1027
- setAttribute: () => noopSpan,
1028
- setAttributes: () => noopSpan,
1029
- addEvent: () => noopSpan,
1030
- addLink: () => noopSpan,
1031
- setStatus: () => noopSpan,
1032
- updateName: () => noopSpan,
1033
- end: () => {},
1034
- isRecording: () => false,
1035
- recordException: () => {},
1036
- addLinks: () => noopSpan
1037
- };
1038
- return fn(noopSpan);
1039
- }
1040
- const parentContext = options.traceparent ? extractTraceparent(options.traceparent) : context.active();
1041
- return tracer.startActiveSpan(name, { kind: options.kind ?? SpanKind.INTERNAL }, parentContext, async (span) => {
1042
- try {
1043
- const result = await fn(span);
1044
- span.setStatus({ code: SpanStatusCode$1.OK });
1045
- return result;
1046
- } catch (error) {
1047
- span.setStatus({
1048
- code: SpanStatusCode$1.ERROR,
1049
- message: error.message
1050
- });
1051
- span.recordException(error);
1052
- throw error;
1053
- } finally {
1054
- span.end();
1055
- }
1056
- });
1057
- }
1058
-
1059
- //#endregion
1060
6
  //#region src/logger.ts
1061
7
  /**
1062
8
  * Structured logger that emits logs as OpenTelemetry LogRecords.
@@ -1213,7 +159,7 @@ async function executeTracedRequest(input, init) {
1213
159
  const method = (init?.method ?? (typeof input === "object" && "method" in input ? input.method : "GET") ?? "GET").toUpperCase();
1214
160
  const name = url?.pathname ? `${method} ${url.pathname}` : method;
1215
161
  return tracer.startActiveSpan(name, {
1216
- kind: SpanKind$1.CLIENT,
162
+ kind: SpanKind.CLIENT,
1217
163
  attributes: {
1218
164
  "http.request.method": method,
1219
165
  "url.full": url?.toString() ?? rawUrl,
@@ -1505,5 +451,5 @@ function safeStringify(value) {
1505
451
  }
1506
452
 
1507
453
  //#endregion
1508
- export { BaggageSpanProcessor, DEFAULT_ALLOWLIST, Logger, REDACTED_PLACEHOLDER, SeverityNumber, SpanKind, WorkerMetricsCollector, currentSpanId, currentSpanIsRecording, currentTraceId, executeTracedRequest, extractBaggage, extractContext, extractTraceparent, flushOtel, getAllBaggage, getBaggageEntry, getLogger, getMeter, getTracer, initOtel, injectBaggage, injectTraceparent, patchGlobalFetch, recordSpanEvent, redact, redactAndTruncate, registerWorkerGauges, removeBaggageEntry, resolveMaxBytesFromEnv, safeStringify, setBaggageEntry, setCurrentSpanAttribute, setCurrentSpanError, shutdownOtel, stopWorkerGauges, unpatchGlobalFetch, withSpan };
454
+ export { BaggageSpanProcessor, DEFAULT_ALLOWLIST, Logger, REDACTED_PLACEHOLDER, SeverityNumber, WorkerMetricsCollector, currentSpanId, currentSpanIsRecording, currentTraceId, executeTracedRequest, extractBaggage, extractContext, extractTraceparent, flushOtel, getAllBaggage, getBaggageEntry, getLogger, initOtel, injectBaggage, injectTraceparent, patchGlobalFetch, recordSpanEvent, redact, redactAndTruncate, registerWorkerGauges, removeBaggageEntry, resolveMaxBytesFromEnv, safeStringify, setBaggageEntry, setCurrentSpanAttribute, setCurrentSpanError, shutdownOtel, stopWorkerGauges, unpatchGlobalFetch, withSpan };
1509
455
  //# sourceMappingURL=index.mjs.map