All files / src/lib/monitoring performanceAlerts.ts

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

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
/**
 * Performance Alerts System
 *
 * Monitors performance metrics and triggers alerts when thresholds are exceeded.
 */

import { prisma } from '@/lib/prisma';
import { monitoringLogger } from './logger';

/**
 * Performance threshold configuration
 */
export interface PerformanceThreshold {
  /** Endpoint or query name pattern (supports wildcards) */
  name: string;
  /** Maximum acceptable duration in ms */
  maxDuration: number;
  /** Metric type: api, database, render */
  type: 'api' | 'database' | 'render';
  /** Alert severity level */
  severity: 'warning' | 'critical';
  /** Minimum sample size before alerting */
  minSamples?: number;
}

/**
 * Alert result from threshold check
 */
export interface PerformanceAlert {
  /** Threshold that was exceeded */
  threshold: PerformanceThreshold;
  /** Actual average duration */
  avgDuration: number;
  /** Number of samples in the window */
  sampleCount: number;
  /** Maximum duration in the window */
  maxDuration: number;
  /** When the alert was triggered */
  triggeredAt: Date;
}

/**
 * Default performance thresholds
 */
export const DEFAULT_THRESHOLDS: PerformanceThreshold[] = [
  // API endpoints
  { name: '/api/products', type: 'api', maxDuration: 500, severity: 'warning' },
  { name: '/api/cart', type: 'api', maxDuration: 300, severity: 'warning' },
  { name: '/api/checkout', type: 'api', maxDuration: 2000, severity: 'critical' },
  { name: '/api/auth', type: 'api', maxDuration: 500, severity: 'warning' },
  { name: '/api/orders', type: 'api', maxDuration: 1000, severity: 'warning' },
  { name: '/api/search', type: 'api', maxDuration: 800, severity: 'warning' },

  // Database queries
  { name: 'findMany', type: 'database', maxDuration: 500, severity: 'warning' },
  { name: 'aggregate', type: 'database', maxDuration: 1000, severity: 'warning' },
  { name: 'groupBy', type: 'database', maxDuration: 1000, severity: 'warning' },

  // Render metrics
  { name: '/products', type: 'render', maxDuration: 1000, severity: 'warning' },
  { name: '/checkout', type: 'render', maxDuration: 1500, severity: 'critical' },
];

/**
 * Check all performance thresholds and return alerts
 *
 * @param windowMinutes - Time window in minutes to check (default: 5)
 * @param thresholds - Custom thresholds (default: DEFAULT_THRESHOLDS)
 * @returns Array of triggered alerts
 */
export async function checkPerformanceThresholds(
  windowMinutes: number = 5,
  thresholds: PerformanceThreshold[] = DEFAULT_THRESHOLDS
): Promise<PerformanceAlert[]> {
  const alerts: PerformanceAlert[] = [];
  const since = new Date();
  since.setMinutes(since.getMinutes() - windowMinutes);

  for (const threshold of thresholds) {
    try {
      // Query metrics matching the threshold
      const result = await prisma.performanceMetric.aggregate({
        where: {
          type: threshold.type,
          name: { contains: threshold.name },
          createdAt: { gte: since },
        },
        _avg: { duration: true },
        _max: { duration: true },
        _count: true,
      });

      const avgDuration = result._avg.duration ?? 0;
      const maxDuration = result._max.duration ?? 0;
      const sampleCount = result._count;
      const minSamples = threshold.minSamples ?? 3;

      // Only alert if we have enough samples and threshold is exceeded
      if (sampleCount >= minSamples && avgDuration > threshold.maxDuration) {
        const alert: PerformanceAlert = {
          threshold,
          avgDuration,
          maxDuration,
          sampleCount,
          triggeredAt: new Date(),
        };

        alerts.push(alert);

        // Log the alert
        const alertContext = {
          threshold: threshold.maxDuration,
          avgDuration,
          maxDuration,
          sampleCount,
          severity: threshold.severity,
        };

        if (threshold.severity === 'critical') {
          monitoringLogger.error(
            'PERFORMANCE',
            `Performance threshold exceeded: ${threshold.name}`,
            new Error('Critical threshold exceeded'),
            alertContext
          );
        } else {
          monitoringLogger.warn(
            'PERFORMANCE',
            `Performance threshold exceeded: ${threshold.name}`,
            alertContext
          );
        }
      }
    } catch (error) {
      monitoringLogger.error('PERFORMANCE', `Error checking threshold: ${threshold.name}`, error);
    }
  }

  return alerts;
}

/**
 * Get performance summary for alerting dashboard
 */
export async function getPerformanceAlertSummary(
  hours: number = 24
): Promise<{
  totalAlerts: number;
  criticalCount: number;
  warningCount: number;
  topOffenders: Array<{
    name: string;
    type: string;
    avgDuration: number;
    threshold: number;
    exceedancePercent: number;
  }>;
}> {
  const since = new Date();
  since.setHours(since.getHours() - hours);

  const offenders: Array<{
    name: string;
    type: string;
    avgDuration: number;
    threshold: number;
    exceedancePercent: number;
  }> = [];

  let criticalCount = 0;
  let warningCount = 0;

  for (const threshold of DEFAULT_THRESHOLDS) {
    try {
      const result = await prisma.performanceMetric.aggregate({
        where: {
          type: threshold.type,
          name: { contains: threshold.name },
          createdAt: { gte: since },
        },
        _avg: { duration: true },
        _count: true,
      });

      const avgDuration = result._avg.duration ?? 0;

      if (avgDuration > threshold.maxDuration) {
        const exceedancePercent = ((avgDuration - threshold.maxDuration) / threshold.maxDuration) * 100;

        offenders.push({
          name: threshold.name,
          type: threshold.type,
          avgDuration,
          threshold: threshold.maxDuration,
          exceedancePercent,
        });

        if (threshold.severity === 'critical') {
          criticalCount++;
        } else {
          warningCount++;
        }
      }
    } catch {
      // Skip on error
    }
  }

  // Sort by exceedance percentage (worst first)
  offenders.sort((a, b) => b.exceedancePercent - a.exceedancePercent);

  return {
    totalAlerts: criticalCount + warningCount,
    criticalCount,
    warningCount,
    topOffenders: offenders.slice(0, 10),
  };
}

/**
 * Record a custom performance metric
 *
 * @param type - Metric type
 * @param name - Metric name
 * @param duration - Duration in ms
 * @param metadata - Additional metadata
 */
export async function recordPerformanceMetric(
  type: 'api' | 'database' | 'render',
  name: string,
  duration: number,
  metadata?: {
    method?: string;
    statusCode?: number;
    userId?: number;
    requestId?: string;
    extra?: Record<string, unknown>;
  }
): Promise<void> {
  try {
    await prisma.performanceMetric.create({
      data: {
        type,
        name,
        duration,
        method: metadata?.method,
        statusCode: metadata?.statusCode,
        userId: metadata?.userId,
        requestId: metadata?.requestId,
        metadata: metadata?.extra ? JSON.parse(JSON.stringify(metadata.extra)) : undefined,
      },
    });
  } catch (error) {
    monitoringLogger.error('PERFORMANCE', 'Failed to record performance metric', error, {
      type,
      name,
      duration,
    });
  }
}

/**
 * Clean up old performance metrics
 *
 * @param daysToKeep - Number of days of data to retain
 * @returns Number of deleted records
 */
export async function cleanupOldPerformanceMetrics(daysToKeep: number = 30): Promise<number> {
  const cutoffDate = new Date();
  cutoffDate.setDate(cutoffDate.getDate() - daysToKeep);

  const result = await prisma.performanceMetric.deleteMany({
    where: {
      createdAt: { lt: cutoffDate },
    },
  });

  monitoringLogger.info('PERFORMANCE', `Cleaned up old performance metrics`, {
    deleted: result.count,
    cutoffDate: cutoffDate.toISOString(),
  });

  return result.count;
}