import { type Attributes, SpanStatusCode, trace } from "@opentelemetry/api"; import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node"; import { FastifyInstrumentation } from "@opentelemetry/instrumentation-fastify"; import { NodeSDK } from "@opentelemetry/sdk-node"; // Instrumentation hooks must be registered before fastify/http/undici are // loaded, so this module self-initializes and must be the first import in // main.ts. Standard OTEL_* env vars configure the endpoint and service name. // Disabled when no endpoint is set so local dev doesn't report to localhost. if (process.env.OTEL_EXPORTER_OTLP_ENDPOINT) { const sdk = new NodeSDK({ instrumentations: [getNodeAutoInstrumentations(), new FastifyInstrumentation()], // Traces only — logs are collected from the docker process by alloy, and // nothing here emits metrics. logRecordProcessors: [], metricReaders: [], }); sdk.start(); const shutdown = () => void sdk.shutdown(); process.on("SIGTERM", shutdown); process.on("SIGINT", shutdown); } const tracer = trace.getTracer("devict-bot"); export async function withSpan( name: string, attributes: Attributes, fn: () => Promise, ): Promise { return tracer.startActiveSpan(name, { attributes }, async (span) => { try { const result = await fn(); span.setStatus({ code: SpanStatusCode.OK }); return result; } catch (err) { span.recordException(err as Error); span.setStatus({ code: SpanStatusCode.ERROR, message: (err as Error).message }); throw err; } finally { span.end(); } }); }