All files / src/lib/observability tracing.ts

43.07% Statements 112/260
50% Branches 2/4
16.66% Functions 2/12
43.07% Lines 112/260

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 260 2611x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                     1x 1x 1x 1x 1x                           1x 1x 1x 1x 1x                                 1x 1x 1x 1x 1x 1x                   1x 1x 1x 1x 1x 1x                   1x 1x 1x 1x 1x 1x 636x 636x 636x 636x 1x 1x 1x 1x 636x 636x 636x 636x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x             1x 1x 1x 1x 1x 1x                   1x 1x 1x 1x                     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                     1x 1x 1x 1x 1x 1x                  
/**
 * Tracing Utilities
 *
 * Helper functions for creating and managing spans in OpenTelemetry.
 * Use these utilities to instrument your application code.
 */
 
import {
  trace,
  SpanStatusCode,
  Span,
  context,
  propagation,
  SpanKind,
  Attributes,
} from '@opentelemetry/api';
import type { NextRequest } from 'next/server';
 
// Get the tracer for this service
const tracer = trace.getTracer('elite-events');
 
/**
 * Create and execute a span for tracing an operation
 *
 * @example
 * ```typescript
 * const result = await createSpan('process-order', async (span) => {
 *   span.setAttribute('order.id', orderId);
 *   return await processOrder(orderId);
 * });
 * ```
 */
export async function createSpan<T>(
  name: string,
  fn: (span: Span) => Promise<T>,
  options?: {
    attributes?: Attributes;
    kind?: SpanKind;
  }
): Promise<T> {
  return tracer.startActiveSpan(
    name,
    { kind: options?.kind ?? SpanKind.INTERNAL },
    async (span) => {
      try {
        // Set initial attributes if provided
        if (options?.attributes) {
          span.setAttributes(options.attributes);
        }

        // Execute the function
        const result = await fn(span);

        // Mark as successful
        span.setStatus({ code: SpanStatusCode.OK });

        return result;
      } catch (error) {
        // Mark as error and record the exception
        span.setStatus({
          code: SpanStatusCode.ERROR,
          message: error instanceof Error ? error.message : 'Unknown error',
        });

        if (error instanceof Error) {
          span.recordException(error);
        }

        throw error;
      } finally {
        span.end();
      }
    }
  );
}
 
/**
 * Create a span for a database operation
 */
export async function createDbSpan<T>(
  operation: string,
  table: string,
  fn: (span: Span) => Promise<T>
): Promise<T> {
  return createSpan(`db.${operation}`, fn, {
    kind: SpanKind.CLIENT,
    attributes: {
      'db.system': 'mysql',
      'db.operation': operation,
      'db.sql.table': table,
    },
  });
}
 
/**
 * Create a span for an external HTTP call
 */
export async function createHttpSpan<T>(
  method: string,
  url: string,
  fn: (span: Span) => Promise<T>
): Promise<T> {
  const parsedUrl = new URL(url);

  return createSpan(`HTTP ${method} ${parsedUrl.pathname}`, fn, {
    kind: SpanKind.CLIENT,
    attributes: {
      'http.method': method,
      'http.url': url,
      'http.host': parsedUrl.host,
      'http.scheme': parsedUrl.protocol.replace(':', ''),
    },
  });
}
 
/**
 * Extract trace context from incoming request headers
 *
 * Use this in API routes to continue a trace from an incoming request.
 */
export function extractTraceContext(request: NextRequest | Request) {
  const carrier: Record<string, string> = {};

  request.headers.forEach((value, key) => {
    carrier[key.toLowerCase()] = value;
  });

  return propagation.extract(context.active(), carrier);
}
 
/**
 * Inject trace context into outgoing request headers
 *
 * Use this when making HTTP requests to propagate the trace.
 */
export function injectTraceContext(headers: Headers): void {
  const carrier: Record<string, string> = {};

  propagation.inject(context.active(), carrier);

  Object.entries(carrier).forEach(([key, value]) => {
    headers.set(key, value);
  });
}
 
/**
 * Get the current trace ID
 *
 * Useful for logging correlation.
 */
export function getCurrentTraceId(): string | undefined {
  const span = trace.getActiveSpan();
  return span?.spanContext().traceId;
}
 
/**
 * Get the current span ID
 */
export function getCurrentSpanId(): string | undefined {
  const span = trace.getActiveSpan();
  return span?.spanContext().spanId;
}
 
/**
 * Add attributes to the current active span
 *
 * @example
 * ```typescript
 * addSpanAttributes({
 *   'user.id': userId,
 *   'order.total': orderTotal,
 * });
 * ```
 */
export function addSpanAttributes(attributes: Attributes): void {
  const span = trace.getActiveSpan();
  if (span) {
    span.setAttributes(attributes);
  }
}
 
/**
 * Add an event to the current active span
 *
 * Events are used to mark points of interest within a span.
 */
export function addSpanEvent(
  name: string,
  attributes?: Attributes
): void {
  const span = trace.getActiveSpan();
  if (span) {
    span.addEvent(name, attributes);
  }
}
 
/**
 * Record an exception on the current active span
 */
export function recordException(error: Error): void {
  const span = trace.getActiveSpan();
  if (span) {
    span.recordException(error);
    span.setStatus({
      code: SpanStatusCode.ERROR,
      message: error.message,
    });
  }
}
 
/**
 * Create a wrapper for API route handlers that adds tracing
 *
 * @example
 * ```typescript
 * export const GET = withTracing('GET /api/products', async (request) => {
 *   // Handler code
 * });
 * ```
 */
export function withTracing<T>(
  operationName: string,
  handler: (request: NextRequest | Request, span: Span) => Promise<T>
): (request: NextRequest | Request) => Promise<T> {
  return async (request: NextRequest | Request) => {
    // Extract context from incoming request
    const ctx = extractTraceContext(request);

    return context.with(ctx, async () => {
      return createSpan(
        operationName,
        async (span) => {
          // Add request attributes
          span.setAttributes({
            'http.method': request.method,
            'http.url': request.url,
            'http.user_agent': request.headers.get('user-agent') || 'unknown',
          });

          return handler(request, span);
        },
        { kind: SpanKind.SERVER }
      );
    });
  };
}
 
/**
 * Get trace context as a string for logging
 *
 * Returns a string like "trace_id=abc123 span_id=def456"
 */
export function getTraceContextString(): string {
  const traceId = getCurrentTraceId();
  const spanId = getCurrentSpanId();

  if (!traceId) return '';

  return `trace_id=${traceId}${spanId ? ` span_id=${spanId}` : ''}`;
}