/** * Copyright Valkey GLIDE Project Contributors - SPDX Identifier: Apache-2.0 */ import { OpenTelemetryConfig } from "."; /** * Extended OpenTelemetry configuration that includes JS-side options * not representable in the native (NAPI) config. * * Pass this to {@link OpenTelemetry.init} instead of the plain `OpenTelemetryConfig`. */ export interface GlideOpenTelemetryConfig extends OpenTelemetryConfig { /** * Optional callback that returns the active parent span context for each command. * * When a {@link GlideSpanContext} is returned, the GLIDE command span will be created * as a child of that context, enabling end-to-end distributed tracing. * * The callback is invoked synchronously before each sampled command. Keep the * implementation lightweight — avoid I/O, async work, or expensive computation. * * @example * ```typescript * import { trace } from "@opentelemetry/api"; * * OpenTelemetry.init({ * traces: { endpoint: "http://localhost:4318/v1/traces" }, * parentSpanContextProvider: () => { * const span = trace.getActiveSpan(); * if (!span) return undefined; * const ctx = span.spanContext(); * return { * traceId: ctx.traceId, * spanId: ctx.spanId, * traceFlags: ctx.traceFlags, * traceState: ctx.traceState?.toString(), * }; * }, * }); * ``` */ parentSpanContextProvider?: () => GlideSpanContext | undefined; } /** * Represents the trace context of a remote span, used for parent span context propagation. * * When a user's application has an active OTel span (e.g., from an HTTP request handler), * this context allows GLIDE command spans to appear as children of that span in tracing UIs. */ export interface GlideSpanContext { /** The trace ID as a 32-character lowercase hex string. */ traceId: string; /** The span ID as a 16-character lowercase hex string. */ spanId: string; /** Trace flags (e.g., 1 for sampled). */ traceFlags: number; /** Optional W3C trace state (e.g., "vendorname1=opaqueValue1,vendorname2=opaqueValue2"). */ traceState?: string; } /** * ⚠️ OpenTelemetry can only be initialized once per process. Calling `OpenTelemetry.init()` more than once will be ignored. * If you need to change configuration, restart the process with new settings. * ### OpenTelemetry * * - **openTelemetryConfig**: Use {@link GlideOpenTelemetryConfig} to configure OpenTelemetry exporters and options. * - **traces**: (optional) Configure trace exporting. * - **endpoint**: The collector endpoint for traces. Supported protocols: * - `http://` or `https://` for HTTP/HTTPS * - `grpc://` for gRPC * - `file://` for local file export (see below) * - **samplePercentage**: (optional) The percentage of requests to sample and create a span for, used to measure command duration. Must be between 0 and 100. Defaults to 1 if not specified. * Note: There is a tradeoff between sampling percentage and performance. Higher sampling percentages will provide more detailed telemetry data but will impact performance. * It is recommended to keep this number low (1-5%) in production environments unless you have specific needs for higher sampling rates. * - **metrics**: (optional) Configure metrics exporting. * - **endpoint**: The collector endpoint for metrics. Same protocol rules as above. * - **flushIntervalMs**: (optional) Interval in milliseconds for flushing data to the collector. Must be a positive integer. Defaults to 5000ms if not specified. * - **parentSpanContextProvider**: (optional) Callback returning the active parent span context. See {@link GlideOpenTelemetryConfig.parentSpanContextProvider}. * * #### File Exporter Details * - For `file://` endpoints: * - The path must start with `file://` (e.g., `file:///tmp/otel` or `file:///tmp/otel/traces.json`). * - If the path is a directory or lacks a file extension, data is written to `signals.json` in that directory. * - If the path includes a filename with an extension, that file is used as-is. * - The parent directory must already exist; otherwise, initialization will fail with an InvalidInput error. * - If the target file exists, new data is appended (not overwritten). * * #### Validation Rules * - `flushIntervalMs` must be a positive integer. * - `samplePercentage` must be between 0 and 100. * - File exporter paths must start with `file://` and have an existing parent directory. * - Invalid configuration will throw an error synchronously when calling `OpenTelemetry.init()`. */ export declare class OpenTelemetry { private static _instance; private static openTelemetryConfig; private static spanContextFn; private static readonly TRACE_ID_REGEX; private static readonly SPAN_ID_REGEX; /** * Singleton class for managing OpenTelemetry configuration and operations. * This class provides a centralized way to initialize OpenTelemetry and control * sampling behavior at runtime. * * Example usage: * ```typescript * import { OpenTelemetry, GlideOpenTelemetryConfig } from "@valkey/valkey-glide"; * import { trace } from "@opentelemetry/api"; * * const config: GlideOpenTelemetryConfig = { * traces: { * endpoint: "http://localhost:4318/v1/traces", * samplePercentage: 10, * }, * metrics: { * endpoint: "http://localhost:4318/v1/metrics", * }, * flushIntervalMs: 1000, * parentSpanContextProvider: () => { * const span = trace.getActiveSpan(); * if (!span) return undefined; * const ctx = span.spanContext(); * return { traceId: ctx.traceId, spanId: ctx.spanId, traceFlags: ctx.traceFlags }; * }, * }; * OpenTelemetry.init(config); * ``` * * @remarks * OpenTelemetry can only be initialized once per process. Subsequent calls to * init() will be ignored. This is by design, as OpenTelemetry is a global * resource that should be configured once at application startup. * * Initialize the OpenTelemetry instance * @param openTelemetryConfig - The OpenTelemetry configuration */ static init(openTelemetryConfig: GlideOpenTelemetryConfig): void; private static internalInit; /** * Check if the OpenTelemetry instance is initialized * @returns True if the OpenTelemetry instance is initialized, false otherwise */ static isInitialized(): boolean; /** * Get the sample percentage for traces * @returns The sample percentage for traces only if OpenTelemetry is initialized and the traces config is set, otherwise undefined. */ static getSamplePercentage(): number | undefined; /** * Determines if the current request should be sampled for OpenTelemetry tracing. * Uses the configured sample percentage to randomly decide whether to create a span for this request. * @returns true if the request should be sampled, false otherwise */ static shouldSample(): boolean; /** * Set the percentage of requests to be sampled and traced. Must be a value between 0 and 100. * This setting only affects traces, not metrics. * @param percentage - The sample percentage 0-100 * @throws Error if OpenTelemetry is not initialized or traces config is not set * @remarks * This method can be called at runtime to change the sampling percentage without reinitializing OpenTelemetry. */ static setSamplePercentage(percentage: number): void; /** * Register or replace the callback that returns the active parent span context. * * This allows changing the provider at runtime (e.g., switching tracing contexts * in a multi-tenant application). The initial provider can also be set via * {@link GlideOpenTelemetryConfig.parentSpanContextProvider} in `init()`. * * @param fn - A function returning a `GlideSpanContext` or `undefined`, or `null` to clear. * * @example * ```typescript * import { trace } from "@opentelemetry/api"; * * OpenTelemetry.setParentSpanContextProvider(() => { * const span = trace.getActiveSpan(); * if (!span) return undefined; * const ctx = span.spanContext(); * return { * traceId: ctx.traceId, * spanId: ctx.spanId, * traceFlags: ctx.traceFlags, * traceState: ctx.traceState?.toString(), * }; * }); * ``` */ static setParentSpanContextProvider(fn: (() => GlideSpanContext | undefined) | null): void; }