All files / src/app/api/traces/collect route.ts

0% Statements 0/223
100% Branches 0/0
0% Functions 0/1
0% Lines 0/223

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                                                                                                                                                                                                                                                                                                                                                                                                                                                               
/**
 * Trace Collection API
 *
 * Receives trace data from OpenTelemetry exporters and stores in database.
 * This endpoint allows external services to push traces to our database.
 */

import { NextRequest, NextResponse } from 'next/server';
import { Prisma } from '@prisma/client';
import { prisma } from '@/lib/prisma';
import { z } from 'zod';

// Schema for incoming span data
const SpanSchema = z.object({
  traceId: z.string().length(32),
  spanId: z.string().length(16),
  parentSpanId: z.string().length(16).optional().nullable(),
  name: z.string().max(200),
  kind: z.enum(['server', 'client', 'internal', 'producer', 'consumer']),
  startTimeUnixNano: z.number(),
  endTimeUnixNano: z.number(),
  status: z.object({
    code: z.enum(['unset', 'ok', 'error']),
    message: z.string().optional(),
  }),
  attributes: z.record(z.string(), z.unknown()).optional(),
  events: z.array(z.object({
    name: z.string(),
    timeUnixNano: z.number(),
    attributes: z.record(z.string(), z.unknown()).optional(),
  })).optional(),
});

const TraceDataSchema = z.object({
  serviceName: z.string().max(100),
  spans: z.array(SpanSchema),
});

const RequestSchema = z.object({
  resourceSpans: z.array(z.object({
    resource: z.object({
      attributes: z.array(z.object({
        key: z.string(),
        value: z.object({
          stringValue: z.string().optional(),
          intValue: z.number().optional(),
        }),
      })).optional(),
    }).optional(),
    scopeSpans: z.array(z.object({
      spans: z.array(SpanSchema),
    })),
  })),
});

// Convert nanoseconds to Date
function nanoToDate(nanos: number): Date {
  return new Date(nanos / 1_000_000);
}

// Convert nanoseconds to milliseconds
function nanoToMs(nanos: number): number {
  return Math.round(nanos / 1_000_000);
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();

    // Handle OTLP format
    if (body.resourceSpans) {
      const parsed = RequestSchema.safeParse(body);
      if (!parsed.success) {
        return NextResponse.json(
          { error: 'Invalid OTLP format', details: parsed.error.issues },
          { status: 400 }
        );
      }

      // Process OTLP format
      for (const resourceSpan of parsed.data.resourceSpans) {
        // Extract service name from resource attributes
        let serviceName = 'unknown';
        const attrs = resourceSpan.resource?.attributes || [];
        for (const attr of attrs) {
          if (attr.key === 'service.name' && attr.value.stringValue) {
            serviceName = attr.value.stringValue;
            break;
          }
        }

        for (const scopeSpan of resourceSpan.scopeSpans) {
          await processSpans(serviceName, scopeSpan.spans);
        }
      }

      return NextResponse.json({ status: 'ok' });
    }

    // Handle simple format
    const parsed = TraceDataSchema.safeParse(body);
    if (!parsed.success) {
      return NextResponse.json(
        { error: 'Invalid request format', details: parsed.error.issues },
        { status: 400 }
      );
    }

    await processSpans(parsed.data.serviceName, parsed.data.spans);

    return NextResponse.json({ status: 'ok' });
  } catch (error) {
    console.error('[Trace Collector] Error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

async function processSpans(
  serviceName: string,
  spans: z.infer<typeof SpanSchema>[]
): Promise<void> {
  // Group spans by trace
  const traceMap = new Map<string, z.infer<typeof SpanSchema>[]>();
  for (const span of spans) {
    if (!traceMap.has(span.traceId)) {
      traceMap.set(span.traceId, []);
    }
    traceMap.get(span.traceId)!.push(span);
  }

  // Process each trace
  for (const [traceId, traceSpans] of traceMap) {
    // Find root span
    const rootSpan = traceSpans.find(
      (s) => !s.parentSpanId || !traceSpans.some((other) => other.spanId === s.parentSpanId)
    ) || traceSpans[0];

    // Calculate trace timing
    const startTime = nanoToDate(rootSpan.startTimeUnixNano);
    const endTime = nanoToDate(rootSpan.endTimeUnixNano);
    const duration = nanoToMs(rootSpan.endTimeUnixNano - rootSpan.startTimeUnixNano);

    // Determine trace status
    const hasError = traceSpans.some((s) => s.status.code === 'error');
    const status = hasError ? 'error' : 'ok';

    // Extract context from root span attributes
    const userId = rootSpan.attributes?.['user.id'] as number | undefined;
    const requestId = rootSpan.attributes?.['http.request_id'] as string | undefined;

    // Upsert trace
    await prisma.trace.upsert({
      where: { id: traceId },
      update: {
        name: rootSpan.name,
        endTime,
        duration,
        status,
      },
      create: {
        id: traceId,
        name: rootSpan.name,
        serviceName,
        startTime,
        endTime,
        duration,
        status,
        userId: userId ?? null,
        requestId: requestId ?? null,
      },
    });

    // Upsert spans
    for (const span of traceSpans) {
      const spanStartTime = nanoToDate(span.startTimeUnixNano);
      const spanEndTime = nanoToDate(span.endTimeUnixNano);
      const spanDuration = nanoToMs(span.endTimeUnixNano - span.startTimeUnixNano);

      // Convert events
      const events = span.events?.map((e) => ({
        name: e.name,
        timestamp: nanoToDate(e.timeUnixNano).toISOString(),
        attributes: e.attributes,
      }));

      // Convert to Prisma-compatible JSON values
      const attributesJson = span.attributes
        ? (span.attributes as Prisma.InputJsonValue)
        : Prisma.JsonNull;
      const eventsJson = events
        ? (events as Prisma.InputJsonValue)
        : Prisma.JsonNull;

      await prisma.span.upsert({
        where: { id: span.spanId },
        update: {
          name: span.name,
          endTime: spanEndTime,
          duration: spanDuration,
          status: span.status.code,
          attributes: attributesJson,
          events: eventsJson,
        },
        create: {
          id: span.spanId,
          traceId,
          parentId: span.parentSpanId ?? null,
          name: span.name,
          kind: span.kind,
          startTime: spanStartTime,
          endTime: spanEndTime,
          duration: spanDuration,
          status: span.status.code,
          attributes: attributesJson,
          events: eventsJson,
        },
      });
    }
  }
}