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 | export const dynamic = 'force-dynamic'; import { NextRequest, NextResponse } from 'next/server'; import { prisma } from '@/lib/prisma'; import { withAdmin, withErrorHandling, successResponse, errorResponse, type ApiSuccessResponse, type ApiErrorResponse, type AuthenticatedUser, } from '@/lib/api'; import type { PerformanceAlertConfig, PerformanceAlert, Prisma } from '@prisma/client'; import type { Session } from 'next-auth'; import { getSchedulerStatus } from '@/lib/monitoring/alertScheduler'; /** * Alert config with alerts included */ type AlertConfigWithAlerts = PerformanceAlertConfig & { alerts: PerformanceAlert[]; _count: { alerts: number }; }; /** * Response structure for alert configs list */ interface AlertConfigsResponse { configs: AlertConfigWithAlerts[]; activeAlerts: PerformanceAlert[]; schedulerStatus: Awaited<ReturnType<typeof getSchedulerStatus>>; pagination: { page: number; limit: number; total: number; totalPages: number; }; } /** * Input for creating a new alert config */ interface CreateAlertConfigInput { name: string; description?: string; metricType: string; scope: string; warningThreshold: number; criticalThreshold: number; evaluationWindow?: number; evaluationInterval?: number; minSamples?: number; notifyOnWarning?: boolean; notifyOnCritical?: boolean; notificationChannels?: string[]; cooldownMinutes?: number; enabled?: boolean; } /** * GET /api/admin/monitoring/alerts * * Returns alert configurations and active alerts. * Requires admin authentication. */ async function handleGet( request: NextRequest ): Promise<NextResponse<ApiSuccessResponse<AlertConfigsResponse> | ApiErrorResponse>> { const { searchParams } = new URL(request.url); const page = Math.max(1, parseInt(searchParams.get('page') || '1', 10)); const limit = Math.min(100, Math.max(1, parseInt(searchParams.get('limit') || '20', 10))); const skip = (page - 1) * limit; const enabled = searchParams.get('enabled'); const metricType = searchParams.get('metricType'); // Build where clause const where: Prisma.PerformanceAlertConfigWhereInput = {}; if (enabled !== null) { where.enabled = enabled === 'true'; } if (metricType) { where.metricType = metricType; } // Fetch configs, active alerts, and scheduler status in parallel const [configs, total, activeAlerts, schedulerStatus] = await Promise.all([ prisma.performanceAlertConfig.findMany({ where, include: { alerts: { where: { status: 'active' }, orderBy: { triggeredAt: 'desc' }, take: 5, }, _count: { select: { alerts: true } }, }, orderBy: { createdAt: 'desc' }, skip, take: limit, }), prisma.performanceAlertConfig.count({ where }), prisma.performanceAlert.findMany({ where: { status: 'active' }, include: { config: true }, orderBy: { triggeredAt: 'desc' }, take: 20, }), getSchedulerStatus(), ]); return successResponse({ configs, activeAlerts, schedulerStatus, pagination: { page, limit, total, totalPages: Math.ceil(total / limit), }, }); } /** * POST /api/admin/monitoring/alerts * * Create a new alert configuration. * Requires admin authentication. */ async function handlePost( request: NextRequest, _context: { params?: Promise<Record<string, string>> } | undefined, _session: Session, user: AuthenticatedUser ): Promise<NextResponse<ApiSuccessResponse<{ config: PerformanceAlertConfig }> | ApiErrorResponse>> { const body = (await request.json()) as CreateAlertConfigInput; // Validate required fields if (!body.name || !body.metricType || !body.scope) { return errorResponse('VALIDATION_ERROR', 'name, metricType, and scope are required'); } if (body.warningThreshold === undefined || body.criticalThreshold === undefined) { return errorResponse('VALIDATION_ERROR', 'warningThreshold and criticalThreshold are required'); } // Validate thresholds if (body.warningThreshold >= body.criticalThreshold) { return errorResponse('VALIDATION_ERROR', 'warningThreshold must be less than criticalThreshold'); } // Validate metricType const validMetricTypes = ['response_time', 'error_rate', 'throughput', 'p95_latency']; if (!validMetricTypes.includes(body.metricType)) { return errorResponse('VALIDATION_ERROR', `metricType must be one of: ${validMetricTypes.join(', ')}`); } const config = await prisma.performanceAlertConfig.create({ data: { name: body.name, description: body.description, metricType: body.metricType, scope: body.scope, warningThreshold: body.warningThreshold, criticalThreshold: body.criticalThreshold, evaluationWindow: body.evaluationWindow ?? 300, evaluationInterval: body.evaluationInterval ?? 60, minSamples: body.minSamples ?? 10, notifyOnWarning: body.notifyOnWarning ?? true, notifyOnCritical: body.notifyOnCritical ?? true, notificationChannels: body.notificationChannels ?? ['email'], cooldownMinutes: body.cooldownMinutes ?? 15, enabled: body.enabled ?? true, createdBy: user.id, }, }); return successResponse({ config }, { status: 201 }); } // Export handlers with middleware export const GET = withErrorHandling(withAdmin(handleGet)); export const POST = withErrorHandling(withAdmin(handlePost)); |