All files / src/app/api/admin/monitoring/performance route.ts

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

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 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
/**
 * Performance Metrics API
 *
 * GET /api/admin/monitoring/performance
 *
 * Returns aggregated performance metrics with time series data for visualization.
 */

export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { logger } from '@/lib/logging';
import {
  calculatePercentile,
  getStartDateForRange,
  getGranularityForRange,
  type TimeRange,
} from '@/lib/monitoring/percentiles';
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  errorResponse,
  type ApiSuccessResponse,
  type ApiErrorResponse,
} from '@/lib/api';

/**
 * Performance API response type
 */
interface PerformanceResponse {
  summary: {
    avgResponseTime: number;
    totalRequests: number;
    successRate: number;
    p95ResponseTime: number;
    p99ResponseTime: number;
  };
  timeSeries: Array<{
    timestamp: string;
    avgDuration: number;
    p95Duration: number;
    p99Duration: number;
    maxDuration: number;
  }>;
  volume: Array<{
    timestamp: string;
    total: number;
    successful: number;
    clientErrors: number;
    serverErrors: number;
  }>;
  endpoints: Array<{
    path: string;
    count: number;
    percentage: number;
  }>;
  statusCodes: Array<{
    statusCode: number;
    count: number;
  }>;
  slowRequests: Array<{
    id: string;
    name: string;
    duration: number;
    timestamp: string;
  }>;
}

/**
 * GET handler for performance metrics
 */
async function handleGet(
  request: NextRequest
): Promise<NextResponse<ApiSuccessResponse<PerformanceResponse> | ApiErrorResponse>> {
  // Parse query parameters
  const { searchParams } = new URL(request.url);
  const timeRangeParam = searchParams.get('timeRange') as TimeRange | null;
  const timeRange: TimeRange = timeRangeParam || '24h';

  // Validate time range
  const validRanges = ['1h', '6h', '24h', '7d', '30d'];
  if (!validRanges.includes(timeRange)) {
    return errorResponse(
      'INVALID_PARAM',
      'Invalid timeRange. Must be one of: 1h, 6h, 24h, 7d, 30d',
      { status: 400 }
    );
  }

  const startTime = getStartDateForRange(timeRange);
  const endTime = new Date();
  const granularity = getGranularityForRange(timeRange);

  try {
    // Fetch all metrics for the time range
    const [allMetrics, aggregateData, endpointStats, statusCodeStats, slowRequests] =
      await Promise.all([
        // Get all metrics for percentile calculation
        prisma.httpMetric.findMany({
          where: {
            timestamp: { gte: startTime, lte: endTime },
          },
          select: {
            duration: true,
            statusCode: true,
            timestamp: true,
          },
        }),

        // Get aggregate data
        prisma.httpMetric.aggregate({
          where: {
            timestamp: { gte: startTime, lte: endTime },
          },
          _avg: { duration: true },
          _count: true,
        }),

        // Get endpoint distribution
        prisma.httpMetric.groupBy({
          by: ['path'],
          where: {
            timestamp: { gte: startTime, lte: endTime },
          },
          _count: true,
          orderBy: { _count: { path: 'desc' } },
          take: 20,
        }),

        // Get status code distribution
        prisma.httpMetric.groupBy({
          by: ['statusCode'],
          where: {
            timestamp: { gte: startTime, lte: endTime },
          },
          _count: true,
        }),

        // Get slow requests
        prisma.httpMetric.findMany({
          where: {
            timestamp: { gte: startTime, lte: endTime },
            duration: { gt: 500 },
          },
          orderBy: { duration: 'desc' },
          take: 20,
        }),
      ]);

    // Calculate percentiles
    const durations = allMetrics.map((m) => m.duration);
    const p95ResponseTime = calculatePercentile(durations, 95);
    const p99ResponseTime = calculatePercentile(durations, 99);

    // Calculate success rate
    const successCount = allMetrics.filter(
      (m) => m.statusCode >= 200 && m.statusCode < 400
    ).length;
    const successRate =
      allMetrics.length > 0 ? (successCount / allMetrics.length) * 100 : 100;

    // Generate time series data
    const timeSeries = generateTimeSeries(allMetrics, startTime, endTime, granularity);

    // Generate volume data
    const volume = generateVolumeData(allMetrics, startTime, endTime, granularity);

    // Calculate total for percentage
    const totalRequests = aggregateData._count;

    // Format endpoints with percentage
    const endpoints = endpointStats.map((e) => ({
      path: e.path,
      count: e._count,
      percentage: totalRequests > 0 ? (e._count / totalRequests) * 100 : 0,
    }));

    // Format status codes
    const statusCodes = statusCodeStats
      .map((s) => ({
        statusCode: s.statusCode,
        count: s._count,
      }))
      .sort((a, b) => a.statusCode - b.statusCode);

    // Format slow requests
    const formattedSlowRequests = slowRequests.map((r) => ({
      id: r.id,
      name: `${r.method} ${r.path} (${r.statusCode})`,
      duration: r.duration,
      timestamp: r.timestamp.toISOString(),
    }));

    return successResponse({
      summary: {
        avgResponseTime: aggregateData._avg.duration || 0,
        totalRequests,
        successRate,
        p95ResponseTime,
        p99ResponseTime,
      },
      timeSeries,
      volume,
      endpoints,
      statusCodes,
      slowRequests: formattedSlowRequests,
    });
  } catch (error) {
    logger.error('Error fetching performance metrics', error instanceof Error ? error : new Error(String(error)), { category: 'API' });
    return errorResponse('INTERNAL_ERROR', 'Failed to fetch performance metrics', {
      status: 500,
    });
  }
}

/**
 * Generate time series data points
 */
function generateTimeSeries(
  metrics: Array<{ duration: number; timestamp: Date }>,
  startTime: Date,
  endTime: Date,
  granularity: 'minute' | 'hour' | 'day'
): Array<{
  timestamp: string;
  avgDuration: number;
  p95Duration: number;
  p99Duration: number;
  maxDuration: number;
}> {
  const buckets = new Map<
    string,
    { durations: number[]; timestamp: Date }
  >();

  // Determine bucket size in milliseconds
  const bucketSize =
    granularity === 'minute'
      ? 60 * 1000
      : granularity === 'hour'
        ? 60 * 60 * 1000
        : 24 * 60 * 60 * 1000;

  // Create buckets for the entire range
  let currentBucket = new Date(startTime);
  while (currentBucket <= endTime) {
    const key = currentBucket.toISOString();
    buckets.set(key, { durations: [], timestamp: new Date(currentBucket) });
    currentBucket = new Date(currentBucket.getTime() + bucketSize);
  }

  // Assign metrics to buckets
  for (const metric of metrics) {
    const bucketTime = new Date(
      Math.floor(metric.timestamp.getTime() / bucketSize) * bucketSize
    );
    const key = bucketTime.toISOString();

    if (buckets.has(key)) {
      buckets.get(key)!.durations.push(metric.duration);
    }
  }

  // Calculate stats for each bucket
  const result: Array<{
    timestamp: string;
    avgDuration: number;
    p95Duration: number;
    p99Duration: number;
    maxDuration: number;
  }> = [];

  for (const [, bucket] of buckets) {
    const durations = bucket.durations;
    if (durations.length === 0) {
      result.push({
        timestamp: bucket.timestamp.toISOString(),
        avgDuration: 0,
        p95Duration: 0,
        p99Duration: 0,
        maxDuration: 0,
      });
    } else {
      const avg = durations.reduce((a, b) => a + b, 0) / durations.length;
      const sorted = [...durations].sort((a, b) => a - b);

      result.push({
        timestamp: bucket.timestamp.toISOString(),
        avgDuration: avg,
        p95Duration: calculatePercentile(durations, 95),
        p99Duration: calculatePercentile(durations, 99),
        maxDuration: sorted[sorted.length - 1],
      });
    }
  }

  return result.sort(
    (a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
  );
}

/**
 * Generate volume data points
 */
function generateVolumeData(
  metrics: Array<{ duration: number; statusCode: number; timestamp: Date }>,
  startTime: Date,
  endTime: Date,
  granularity: 'minute' | 'hour' | 'day'
): Array<{
  timestamp: string;
  total: number;
  successful: number;
  clientErrors: number;
  serverErrors: number;
}> {
  const buckets = new Map<
    string,
    {
      timestamp: Date;
      total: number;
      successful: number;
      clientErrors: number;
      serverErrors: number;
    }
  >();

  // Determine bucket size in milliseconds
  const bucketSize =
    granularity === 'minute'
      ? 60 * 1000
      : granularity === 'hour'
        ? 60 * 60 * 1000
        : 24 * 60 * 60 * 1000;

  // Create buckets for the entire range
  let currentBucket = new Date(startTime);
  while (currentBucket <= endTime) {
    const key = currentBucket.toISOString();
    buckets.set(key, {
      timestamp: new Date(currentBucket),
      total: 0,
      successful: 0,
      clientErrors: 0,
      serverErrors: 0,
    });
    currentBucket = new Date(currentBucket.getTime() + bucketSize);
  }

  // Assign metrics to buckets
  for (const metric of metrics) {
    const bucketTime = new Date(
      Math.floor(metric.timestamp.getTime() / bucketSize) * bucketSize
    );
    const key = bucketTime.toISOString();

    if (buckets.has(key)) {
      const bucket = buckets.get(key)!;
      bucket.total++;

      if (metric.statusCode >= 200 && metric.statusCode < 400) {
        bucket.successful++;
      } else if (metric.statusCode >= 400 && metric.statusCode < 500) {
        bucket.clientErrors++;
      } else if (metric.statusCode >= 500) {
        bucket.serverErrors++;
      }
    }
  }

  // Convert to array
  const result = Array.from(buckets.values()).map((bucket) => ({
    timestamp: bucket.timestamp.toISOString(),
    total: bucket.total,
    successful: bucket.successful,
    clientErrors: bucket.clientErrors,
    serverErrors: bucket.serverErrors,
  }));

  return result.sort(
    (a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
  );
}

export const GET = withErrorHandling(withAdmin(handleGet));