Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 | /** * Database Span Exporter * * Custom OpenTelemetry exporter that stores spans in the database * for local trace exploration via the admin dashboard. */ import type { SpanExporter, ReadableSpan, } from '@opentelemetry/sdk-trace-base'; import { ExportResultCode, type ExportResult } from '@opentelemetry/core'; import { SpanKind, SpanStatusCode } from '@opentelemetry/api'; import { Prisma } from '@prisma/client'; import { prisma } from '@/lib/prisma'; import { logger } from '@/lib/logging'; // Map OpenTelemetry SpanKind to string function spanKindToString(kind: SpanKind): string { switch (kind) { case SpanKind.SERVER: return 'server'; case SpanKind.CLIENT: return 'client'; case SpanKind.PRODUCER: return 'producer'; case SpanKind.CONSUMER: return 'consumer'; default: return 'internal'; } } // Map SpanStatusCode to string function statusToString(code: SpanStatusCode): string { switch (code) { case SpanStatusCode.ERROR: return 'error'; case SpanStatusCode.OK: return 'ok'; default: return 'unset'; } } // Convert hrtime to milliseconds function hrTimeToMs(hrTime: [number, number]): number { return hrTime[0] * 1000 + hrTime[1] / 1_000_000; } // Convert hrtime to Date function hrTimeToDate(hrTime: [number, number]): Date { return new Date(hrTimeToMs(hrTime)); } // Convert attributes to plain object (Prisma-compatible) function attributesToObject(attributes: ReadableSpan['attributes']): Prisma.InputJsonValue | typeof Prisma.JsonNull { if (!attributes || Object.keys(attributes).length === 0) { return Prisma.JsonNull; } return { ...attributes } as Prisma.InputJsonValue; } // Convert events to array (Prisma-compatible) function eventsToArray(events: ReadableSpan['events']): Prisma.InputJsonValue | typeof Prisma.JsonNull { if (!events || events.length === 0) { return Prisma.JsonNull; } return events.map((event) => ({ name: event.name, timestamp: hrTimeToDate(event.time).toISOString(), attributes: event.attributes ? { ...event.attributes } : undefined, })) as Prisma.InputJsonValue; } export interface DatabaseSpanExporterOptions { /** Service name to use for traces */ serviceName?: string; /** Maximum batch size for database writes */ maxBatchSize?: number; /** Whether to enable the exporter */ enabled?: boolean; } /** * DatabaseSpanExporter stores OpenTelemetry spans in the database * for local exploration via the admin dashboard. */ export class DatabaseSpanExporter implements SpanExporter { private serviceName: string; private maxBatchSize: number; private enabled: boolean; private isShutdown = false; constructor(options: DatabaseSpanExporterOptions = {}) { this.serviceName = options.serviceName || 'elite-events'; this.maxBatchSize = options.maxBatchSize || 100; this.enabled = options.enabled ?? process.env.TRACE_DB_EXPORTER_ENABLED === 'true'; } /** * Export spans to the database */ export( spans: ReadableSpan[], resultCallback: (result: ExportResult) => void ): void { if (this.isShutdown || !this.enabled) { resultCallback({ code: ExportResultCode.SUCCESS }); return; } // Process in background to avoid blocking this.exportSpans(spans) .then(() => { resultCallback({ code: ExportResultCode.SUCCESS }); }) .catch((error) => { logger.error('DatabaseSpanExporter export failed', error instanceof Error ? error : new Error(String(error)), { category: 'SYSTEM' }); resultCallback({ code: ExportResultCode.FAILED, error: error instanceof Error ? error : new Error(String(error)), }); }); } /** * Actual export implementation */ private async exportSpans(spans: ReadableSpan[]): Promise<void> { if (spans.length === 0) return; // Group spans by trace const traceMap = new Map<string, ReadableSpan[]>(); for (const span of spans) { const traceId = span.spanContext().traceId; if (!traceMap.has(traceId)) { traceMap.set(traceId, []); } traceMap.get(traceId)!.push(span); } // Process each trace for (const [traceId, traceSpans] of traceMap) { await this.processTrace(traceId, traceSpans); } } /** * Process a single trace and its spans */ private async processTrace(traceId: string, spans: ReadableSpan[]): Promise<void> { // Find root span (no parent or parent not in this trace) const getParentSpanId = (span: ReadableSpan): string | undefined => span.parentSpanContext?.spanId; const rootSpan = spans.find( (s) => !getParentSpanId(s) || !spans.some((other) => other.spanContext().spanId === getParentSpanId(s)) ) || spans[0]; // Calculate trace timing const startTime = hrTimeToDate(rootSpan.startTime); const endTime = hrTimeToDate(rootSpan.endTime); const duration = Math.round(hrTimeToMs(rootSpan.endTime) - hrTimeToMs(rootSpan.startTime)); // Determine trace status (error if any span has error) const hasError = spans.some((s) => s.status.code === SpanStatusCode.ERROR); const status = hasError ? 'error' : 'ok'; // Extract user ID from root span attributes if present const userId = rootSpan.attributes['user.id'] as number | undefined; const requestId = rootSpan.attributes['http.request_id'] as string | undefined; try { // Upsert trace await prisma.trace.upsert({ where: { id: traceId }, update: { name: rootSpan.name, endTime, duration, status, }, create: { id: traceId, name: rootSpan.name, serviceName: this.serviceName, startTime, endTime, duration, status, userId: userId ?? null, requestId: requestId ?? null, }, }); // Upsert spans for (const span of spans) { const spanId = span.spanContext().spanId; const parentId = getParentSpanId(span); const spanStartTime = hrTimeToDate(span.startTime); const spanEndTime = hrTimeToDate(span.endTime); const spanDuration = Math.round(hrTimeToMs(span.endTime) - hrTimeToMs(span.startTime)); await prisma.span.upsert({ where: { id: spanId }, update: { name: span.name, endTime: spanEndTime, duration: spanDuration, status: statusToString(span.status.code), attributes: attributesToObject(span.attributes), events: eventsToArray(span.events), }, create: { id: spanId, traceId, parentId: parentId || null, name: span.name, kind: spanKindToString(span.kind), startTime: spanStartTime, endTime: spanEndTime, duration: spanDuration, status: statusToString(span.status.code), attributes: attributesToObject(span.attributes), events: eventsToArray(span.events), }, }); } } catch (error) { // Log but don't fail - tracing should not break the application logger.error('DatabaseSpanExporter failed to store trace', error instanceof Error ? error : new Error(String(error)), { category: 'SYSTEM', traceId }); } } /** * Shutdown the exporter */ async shutdown(): Promise<void> { this.isShutdown = true; } /** * Force flush any pending exports */ async forceFlush(): Promise<void> { // No buffering, so nothing to flush } } /** * Create a DatabaseSpanExporter instance */ export function createDatabaseSpanExporter( options?: DatabaseSpanExporterOptions ): DatabaseSpanExporter { return new DatabaseSpanExporter(options); } |