import { type Histogram, metrics, type UpDownCounter } from '@opentelemetry/api' import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http' import { resourceFromAttributes } from '@opentelemetry/resources' import { AggregationTemporality, AggregationType, MeterProvider, PeriodicExportingMetricReader, } from '@opentelemetry/sdk-metrics' import { getOpenObserveConfig, SERVICE_NAME } from '@/lib/openobserve' const DEFAULT_EXPORT_INTERVAL_MS = 15_000 /** Bucket bounds (seconds) of the request duration histogram: 5 ms … 10 s. */ const DURATION_BUCKETS = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10] let provider: MeterProvider | null = null /** * Starts exporting metrics to OpenObserve (`/api//v1/metrics`) every * `METRICS_EXPORT_INTERVAL_MS` (15 s by default). Without `OPENOBSERVE_URL` the * global meter stays a no-op, so instruments cost nothing in tests or locally. */ export function configureMetrics(): boolean { const config = getOpenObserveConfig() if (!config) return false const exporter = new OTLPMetricExporter({ url: `${config.otlpBaseUrl}/v1/metrics`, headers: { Authorization: config.authorization }, // Cumulative is what OpenObserve's PromQL (rate, histogram_quantile) expects. temporalityPreference: AggregationTemporality.CUMULATIVE, }) provider = new MeterProvider({ resource: resourceFromAttributes({ 'service.name': SERVICE_NAME }), views: [ { instrumentName: 'http.server.request.duration', aggregation: { type: AggregationType.EXPLICIT_BUCKET_HISTOGRAM, options: { boundaries: DURATION_BUCKETS }, }, }, ], readers: [ new PeriodicExportingMetricReader({ exporter, exportIntervalMillis: Number(process.env.METRICS_EXPORT_INTERVAL_MS) || DEFAULT_EXPORT_INTERVAL_MS, }), ], }) metrics.setGlobalMeterProvider(provider) return true } /** Flushes the last batch and stops the exporter (call on shutdown). */ export async function shutdownMetrics(): Promise { await provider?.shutdown() } type HttpInstruments = { duration: Histogram activeRequests: UpDownCounter } let http: HttpInstruments | null = null /** * HTTP server instruments, following the OpenTelemetry semantic conventions. * Created lazily so they bind to the provider set by `configureMetrics()`. */ export function httpMetrics(): HttpInstruments { if (!http) { const meter = metrics.getMeter(SERVICE_NAME) http = { duration: meter.createHistogram('http.server.request.duration', { description: 'Duration of HTTP server requests.', unit: 's', }), activeRequests: meter.createUpDownCounter('http.server.active_requests', { description: 'Number of HTTP server requests in flight.', unit: '{request}', }), } } return http }