@iii-dev/observability 0.13.0-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.
@@ -0,0 +1,409 @@
1
+ import { Logger as Logger$1, SeverityNumber } from "@opentelemetry/api-logs";
2
+ import { AttributeValue, Attributes, Context, Meter, Meter as Meter$1, Span, SpanKind, Tracer, Tracer as Tracer$1 } from "@opentelemetry/api";
3
+ import { ReadableSpan, Span as Span$1, SpanProcessor } from "@opentelemetry/sdk-trace-base";
4
+ import { Instrumentation } from "@opentelemetry/instrumentation";
5
+
6
+ //#region src/logger.d.ts
7
+ /**
8
+ * Structured logger that emits logs as OpenTelemetry LogRecords.
9
+ *
10
+ * Every log call automatically captures the active trace and span context,
11
+ * correlating your logs with distributed traces without any manual wiring.
12
+ * When OTel is not initialized, Logger gracefully falls back to `console.*`.
13
+ *
14
+ * Pass structured data as the second argument to any log method. Using an
15
+ * object of key-value pairs (instead of string interpolation) lets you
16
+ * filter, aggregate, and build dashboards in your observability backend.
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * import { Logger } from 'iii-sdk'
21
+ *
22
+ * const logger = new Logger()
23
+ *
24
+ * // Basic logging — trace context is injected automatically
25
+ * logger.info('Worker connected')
26
+ *
27
+ * // Structured context for dashboards and alerting
28
+ * logger.info('Order processed', { orderId: 'ord_123', amount: 49.99, currency: 'USD' })
29
+ * logger.warn('Retry attempt', { attempt: 3, maxRetries: 5, endpoint: '/api/charge' })
30
+ * logger.error('Payment failed', { orderId: 'ord_123', gateway: 'stripe', errorCode: 'card_declined' })
31
+ * ```
32
+ */
33
+ declare class Logger {
34
+ private readonly traceId?;
35
+ private readonly serviceName?;
36
+ private readonly spanId?;
37
+ private _otelLogger;
38
+ private get otelLogger();
39
+ constructor(traceId?: string | undefined, serviceName?: string | undefined, spanId?: string | undefined);
40
+ private emit;
41
+ /**
42
+ * Log an info-level message.
43
+ *
44
+ * @param message - Human-readable log message.
45
+ * @param data - Structured context attached as OTel log attributes.
46
+ * Use key-value objects to enable filtering and aggregation in your
47
+ * observability backend (e.g. Grafana, Datadog, New Relic).
48
+ *
49
+ * @example
50
+ * ```typescript
51
+ * logger.info('Order processed', { orderId: 'ord_123', status: 'completed' })
52
+ * ```
53
+ */
54
+ info(message: string, data?: unknown): void;
55
+ /**
56
+ * Log a warning-level message.
57
+ *
58
+ * @param message - Human-readable log message.
59
+ * @param data - Structured context attached as OTel log attributes.
60
+ * Use key-value objects to enable filtering and aggregation in your
61
+ * observability backend (e.g. Grafana, Datadog, New Relic).
62
+ *
63
+ * @example
64
+ * ```typescript
65
+ * logger.warn('Retry attempt', { attempt: 3, maxRetries: 5, endpoint: '/api/charge' })
66
+ * ```
67
+ */
68
+ warn(message: string, data?: unknown): void;
69
+ /**
70
+ * Log an error-level message.
71
+ *
72
+ * @param message - Human-readable log message.
73
+ * @param data - Structured context attached as OTel log attributes.
74
+ * Use key-value objects to enable filtering and aggregation in your
75
+ * observability backend (e.g. Grafana, Datadog, New Relic).
76
+ *
77
+ * @example
78
+ * ```typescript
79
+ * logger.error('Payment failed', { orderId: 'ord_123', gateway: 'stripe', errorCode: 'card_declined' })
80
+ * ```
81
+ */
82
+ error(message: string, data?: unknown): void;
83
+ /**
84
+ * Log a debug-level message.
85
+ *
86
+ * @param message - Human-readable log message.
87
+ * @param data - Structured context attached as OTel log attributes.
88
+ * Use key-value objects to enable filtering and aggregation in your
89
+ * observability backend (e.g. Grafana, Datadog, New Relic).
90
+ *
91
+ * @example
92
+ * ```typescript
93
+ * logger.debug('Cache lookup', { key: 'user:42', hit: false })
94
+ * ```
95
+ */
96
+ debug(message: string, data?: unknown): void;
97
+ }
98
+ //#endregion
99
+ //#region src/http-instrumentation.d.ts
100
+ interface TracedFetchInit extends RequestInit {
101
+ tracer?: Tracer;
102
+ }
103
+ /**
104
+ * Execute a fetch request inside an OTel CLIENT span.
105
+ *
106
+ * Mirrors the Rust execute_traced_request shape: injects W3C traceparent into
107
+ * outgoing headers, records HTTP semantic-convention attributes, and sets
108
+ * ERROR span status for HTTP responses with status >= 400 or network errors.
109
+ */
110
+ declare function executeTracedRequest(input: RequestInfo | URL, init?: TracedFetchInit): Promise<Response>;
111
+ //#endregion
112
+ //#region src/telemetry-system/types.d.ts
113
+ /** Configuration for WebSocket reconnection behavior */
114
+ interface ReconnectionConfig {
115
+ /** Starting delay in milliseconds (default: 1000ms) */
116
+ initialDelayMs: number;
117
+ /** Maximum delay cap in milliseconds (default: 30000ms) */
118
+ maxDelayMs: number;
119
+ /** Exponential backoff multiplier (default: 2) */
120
+ backoffMultiplier: number;
121
+ /** Random jitter factor 0-1 (default: 0.3) */
122
+ jitterFactor: number;
123
+ /** Maximum retry attempts, -1 for infinite (default: -1) */
124
+ maxRetries: number;
125
+ }
126
+ /** Configuration for OpenTelemetry initialization. */
127
+ interface OtelConfig {
128
+ /** Whether OpenTelemetry export is enabled. Defaults to true. Set to false or OTEL_ENABLED=false/0/no/off to disable. */
129
+ enabled?: boolean;
130
+ /** The service name to report. Defaults to OTEL_SERVICE_NAME or "iii-node". */
131
+ serviceName?: string;
132
+ /** The service version to report. Defaults to SERVICE_VERSION env var or "unknown". */
133
+ serviceVersion?: string;
134
+ /** The service namespace to report. Defaults to SERVICE_NAMESPACE env var. */
135
+ serviceNamespace?: string;
136
+ /** The service instance ID to report. Defaults to SERVICE_INSTANCE_ID env var or auto-generated UUID. */
137
+ serviceInstanceId?: string;
138
+ /** III Engine WebSocket URL. Defaults to III_URL or "ws://localhost:49134". */
139
+ engineWsUrl?: string;
140
+ /** OpenTelemetry instrumentations to register (e.g., PrismaInstrumentation). */
141
+ instrumentations?: Instrumentation[];
142
+ /** Whether OpenTelemetry metrics export is enabled. Defaults to true. Set to false or OTEL_METRICS_ENABLED=false/0/no/off to disable. */
143
+ metricsEnabled?: boolean;
144
+ /** Metrics export interval in milliseconds. Defaults to 60000 (60 seconds). */
145
+ metricsExportIntervalMs?: number;
146
+ /** Log processor flush delay in milliseconds. Defaults to 100ms. */
147
+ logsFlushIntervalMs?: number;
148
+ /** Maximum number of log records exported per batch. Defaults to 1. */
149
+ logsBatchSize?: number;
150
+ /** Whether to auto-instrument globalThis.fetch calls. Defaults to true. Works on Node.js, Bun, and Deno. Set to false to disable. */
151
+ fetchInstrumentationEnabled?: boolean;
152
+ /** Optional reconnection configuration for the WebSocket connection. */
153
+ reconnectionConfig?: Partial<ReconnectionConfig>;
154
+ }
155
+ //#endregion
156
+ //#region src/telemetry-system/context.d.ts
157
+ /**
158
+ * Extract the current trace ID from the active span context.
159
+ */
160
+ declare function currentTraceId(): string | undefined;
161
+ /**
162
+ * Extract the current span ID from the active span context.
163
+ */
164
+ declare function currentSpanId(): string | undefined;
165
+ /**
166
+ * Inject the current trace context into a W3C traceparent header string.
167
+ */
168
+ declare function injectTraceparent(): string | undefined;
169
+ /**
170
+ * Extract a trace context from a W3C traceparent header string.
171
+ */
172
+ declare function extractTraceparent(traceparent: string): Context;
173
+ /**
174
+ * Inject the current baggage into a W3C baggage header string.
175
+ */
176
+ declare function injectBaggage(): string | undefined;
177
+ /**
178
+ * Extract baggage from a W3C baggage header string.
179
+ */
180
+ declare function extractBaggage(baggage: string): Context;
181
+ /**
182
+ * Extract both trace context and baggage from their respective headers.
183
+ */
184
+ declare function extractContext(traceparent?: string, baggage?: string): Context;
185
+ /**
186
+ * Get a baggage entry from the current context.
187
+ */
188
+ declare function getBaggageEntry(key: string): string | undefined;
189
+ /**
190
+ * Set a baggage entry in the current context.
191
+ */
192
+ declare function setBaggageEntry(key: string, value: string): Context;
193
+ /**
194
+ * Remove a baggage entry from the current context.
195
+ */
196
+ declare function removeBaggageEntry(key: string): Context;
197
+ /**
198
+ * Get all baggage entries from the current context.
199
+ */
200
+ declare function getAllBaggage(): Record<string, string>;
201
+ //#endregion
202
+ //#region src/telemetry-system/baggage-span-processor.d.ts
203
+ /** DEFAULT_ALLOWLIST drift across languages would break worker chains;
204
+ * lockstep tests in each SDK pin this constant at CI time. */
205
+ declare const DEFAULT_ALLOWLIST: readonly string[];
206
+ declare class BaggageSpanProcessor implements SpanProcessor {
207
+ private readonly allowlist;
208
+ constructor(allowlist?: readonly string[]);
209
+ onStart(span: Span$1, parentContext: Context): void;
210
+ onEnd(_span: ReadableSpan): void;
211
+ shutdown(): Promise<void>;
212
+ forceFlush(): Promise<void>;
213
+ }
214
+ //#endregion
215
+ //#region src/telemetry-system/span-ops.d.ts
216
+ /** Returns `false` when there is no active span or the sampler dropped it. */
217
+ declare function currentSpanIsRecording(): boolean;
218
+ /** No-op when the current span is not recording. */
219
+ declare function setCurrentSpanAttribute(key: string, value: AttributeValue): void;
220
+ /** No-op when there is no active span. */
221
+ declare function setCurrentSpanError(message: string): void;
222
+ /** No-op when the current span is not recording. */
223
+ declare function recordSpanEvent(name: string, attrs?: Attributes): void;
224
+ //#endregion
225
+ //#region src/telemetry-system/payload.d.ts
226
+ /** Payload redaction + truncation for invocation event capture. */
227
+ declare const REDACTED_PLACEHOLDER = "[REDACTED]";
228
+ declare function resolveMaxBytesFromEnv(): number | null;
229
+ /** Recursively redact values of sensitive keys. Returns a new value. */
230
+ declare function redact(value: unknown): unknown;
231
+ /** Redact then serialize to JSON, optionally capped at `maxBytes`. */
232
+ declare function redactAndTruncate(value: unknown, maxBytes?: number | null): {
233
+ json: string;
234
+ truncated: boolean;
235
+ };
236
+ //#endregion
237
+ //#region src/telemetry-system/index.d.ts
238
+ /**
239
+ * Initialize OpenTelemetry with the given configuration.
240
+ * This should be called once at application startup.
241
+ */
242
+ declare function initOtel(config?: OtelConfig): void;
243
+ /**
244
+ * Shutdown OpenTelemetry, flushing any pending data.
245
+ */
246
+ declare function shutdownOtel(): Promise<void>;
247
+ /**
248
+ * Force-flush all OTel providers without tearing them down.
249
+ *
250
+ * Counterpart to {@link shutdownOtel}. Use before short-lived process exits
251
+ * where you want pending spans/metrics/logs delivered but plan to keep using
252
+ * OTel afterwards.
253
+ */
254
+ declare function flushOtel(): Promise<void>;
255
+ /**
256
+ * Get the OpenTelemetry tracer instance.
257
+ */
258
+ declare function getTracer(): Tracer$1 | null;
259
+ /**
260
+ * Get the OpenTelemetry meter instance.
261
+ */
262
+ declare function getMeter(): Meter | null;
263
+ /**
264
+ * Get the OpenTelemetry logger instance.
265
+ */
266
+ declare function getLogger(): Logger$1 | null;
267
+ /**
268
+ * Start a new span with the given name and run the callback within it.
269
+ */
270
+ declare function withSpan<T>(name: string, options: {
271
+ kind?: SpanKind;
272
+ traceparent?: string;
273
+ }, fn: (span: Span) => Promise<T>): Promise<T>;
274
+ //#endregion
275
+ //#region src/telemetry-system/fetch-instrumentation.d.ts
276
+ /**
277
+ * Patch globalThis.fetch to create OTel CLIENT spans for every HTTP request.
278
+ */
279
+ declare function patchGlobalFetch(tracer: Tracer): void;
280
+ /**
281
+ * Restore globalThis.fetch to its original implementation.
282
+ */
283
+ declare function unpatchGlobalFetch(): void;
284
+ //#endregion
285
+ //#region src/otel-worker-gauges.d.ts
286
+ interface WorkerGaugesOptions {
287
+ workerId: string;
288
+ workerName?: string;
289
+ }
290
+ declare function registerWorkerGauges(meter: Meter$1, options: WorkerGaugesOptions): void;
291
+ declare function stopWorkerGauges(): void;
292
+ //#endregion
293
+ //#region src/worker-metrics.d.ts
294
+ /**
295
+ * Worker metrics collection for the III Node SDK.
296
+ *
297
+ * Collects CPU, memory, and event loop metrics for worker health monitoring.
298
+ * Uses the Node.js built-in `monitorEventLoopDelay` API for accurate
299
+ * event loop lag measurements.
300
+ */
301
+ /**
302
+ * Worker metrics data structure used internally for OTEL metric collection.
303
+ */
304
+ type WorkerMetrics = {
305
+ memory_heap_used?: number;
306
+ memory_heap_total?: number;
307
+ memory_rss?: number;
308
+ memory_external?: number;
309
+ cpu_user_micros?: number;
310
+ cpu_system_micros?: number;
311
+ cpu_percent?: number;
312
+ event_loop_lag_ms?: number;
313
+ uptime_seconds?: number;
314
+ timestamp_ms: number;
315
+ runtime: string;
316
+ };
317
+ /**
318
+ * Configuration options for the WorkerMetricsCollector.
319
+ */
320
+ interface WorkerMetricsCollectorOptions {
321
+ /**
322
+ * Event loop delay histogram resolution in milliseconds.
323
+ * Lower values provide more accurate measurements but use more resources.
324
+ * @default 20
325
+ */
326
+ eventLoopResolutionMs?: number;
327
+ }
328
+ /**
329
+ * Collects worker resource metrics including CPU, memory, and event loop lag.
330
+ *
331
+ * Uses the Node.js `monitorEventLoopDelay` API for high-precision event loop
332
+ * delay measurements instead of manual `setImmediate` timing.
333
+ *
334
+ * @example
335
+ * ```typescript
336
+ * const collector = new WorkerMetricsCollector()
337
+ *
338
+ * // Collect metrics periodically
339
+ * setInterval(() => {
340
+ * const metrics = collector.collect()
341
+ * console.log('CPU:', metrics.cpu_percent, '%')
342
+ * console.log('Event Loop Lag:', metrics.event_loop_lag_ms, 'ms')
343
+ * }, 5000)
344
+ *
345
+ * // Clean up when done
346
+ * collector.stopMonitoring()
347
+ * ```
348
+ */
349
+ declare class WorkerMetricsCollector {
350
+ private readonly startTime;
351
+ private lastCpuUsage;
352
+ private lastCpuTime;
353
+ private eventLoopHistogram;
354
+ /**
355
+ * Creates a new WorkerMetricsCollector instance.
356
+ *
357
+ * @param options - Configuration options
358
+ */
359
+ constructor(options?: WorkerMetricsCollectorOptions);
360
+ /**
361
+ * Starts the event loop delay histogram monitoring.
362
+ *
363
+ * @param resolutionMs - Histogram resolution in milliseconds
364
+ */
365
+ private startEventLoopMonitoring;
366
+ /**
367
+ * Stops the event loop monitoring and releases resources.
368
+ * Should be called when the collector is no longer needed.
369
+ */
370
+ stopMonitoring(): void;
371
+ /**
372
+ * Collects current worker metrics.
373
+ *
374
+ * This method calculates CPU usage since the last collection,
375
+ * reads memory usage, and gets event loop delay statistics.
376
+ * The event loop histogram is reset after each collection for
377
+ * accurate per-interval measurements.
378
+ *
379
+ * @returns Current worker metrics snapshot
380
+ */
381
+ collect(): WorkerMetrics;
382
+ }
383
+ //#endregion
384
+ //#region src/types.d.ts
385
+ /** OTEL Log Event from the engine */
386
+ type OtelLogEvent = {
387
+ /** Timestamp in Unix nanoseconds */timestamp_unix_nano: number; /** Observed timestamp in Unix nanoseconds */
388
+ observed_timestamp_unix_nano: number; /** OTEL severity number (1-24): TRACE=1-4, DEBUG=5-8, INFO=9-12, WARN=13-16, ERROR=17-20, FATAL=21-24 */
389
+ severity_number: number; /** Severity text (e.g., "INFO", "WARN", "ERROR") */
390
+ severity_text: string; /** Log message body */
391
+ body: string; /** Structured attributes */
392
+ attributes: Record<string, unknown>; /** Trace ID for correlation (if available) */
393
+ trace_id?: string; /** Span ID for correlation (if available) */
394
+ span_id?: string; /** Resource attributes from the emitting service */
395
+ resource: Record<string, string>; /** Service name that emitted the log */
396
+ service_name: string; /** Instrumentation scope name (if available) */
397
+ instrumentation_scope_name?: string; /** Instrumentation scope version (if available) */
398
+ instrumentation_scope_version?: string;
399
+ };
400
+ //#endregion
401
+ //#region src/utils.d.ts
402
+ /**
403
+ * Safely stringify a value, handling circular references, BigInt, and other edge cases.
404
+ * Returns "[unserializable]" if serialization fails for any reason.
405
+ */
406
+ declare function safeStringify(value: unknown): string;
407
+ //#endregion
408
+ export { BaggageSpanProcessor, DEFAULT_ALLOWLIST, Logger, type Meter, type OtelConfig, type OtelLogEvent, type Logger$1 as OtelLogger, REDACTED_PLACEHOLDER, type ReconnectionConfig, SeverityNumber, type Span, SpanKind, type TracedFetchInit, type WorkerGaugesOptions, type WorkerMetrics, WorkerMetricsCollector, type WorkerMetricsCollectorOptions, 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 };
409
+ //# sourceMappingURL=index.d.mts.map