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 | export const dynamic = 'force-dynamic'; import { getAllSLOsWithTrends } from '@/lib/observability/slo-history'; import { getActiveSLOAlerts, getRecentSLOAlerts, getSLOAlertStats } from '@/lib/observability/slo-alerts'; import { prisma } from '@/lib/prisma'; import { ObservabilityDashboard } from '@/components/features/admin/monitoring/ObservabilityDashboard'; import { calculateWebVitalStats, normalizePagePath, getWorstMetric, type WebVitalName, type WebVitalStats, type PageWebVitals, } from '@/lib/observability/web-vitals'; async function getObservabilityData() { const now = new Date(); const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000); const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000); const [slos, httpMetrics, rumEvents, recentErrors, vitalsEvents, activeSloAlerts, recentSloAlerts, sloAlertStats] = await Promise.all([ getAllSLOsWithTrends(), // Get HTTP metrics summary prisma.httpMetric .groupBy({ by: ['statusCode'], where: { timestamp: { gte: oneHourAgo } }, _count: true, _avg: { duration: true }, }) .catch(() => []), // Get recent RUM events count prisma.rumEvent .groupBy({ by: ['type'], where: { timestamp: { gte: oneDayAgo } }, _count: true, }) .catch(() => []), // Get recent errors prisma.errorLog .findMany({ where: { createdAt: { gte: oneDayAgo } }, orderBy: { createdAt: 'desc' }, take: 10, }) .catch(() => []), // Get Web Vitals data prisma.rumEvent .findMany({ where: { type: 'vitals', timestamp: { gte: oneDayAgo }, }, select: { url: true, data: true, }, }) .catch(() => []), // Get SLO alerts getActiveSLOAlerts().catch(() => []), getRecentSLOAlerts(24).catch(() => []), getSLOAlertStats(7).catch(() => ({ total: 0, active: 0, byStatus: {}, bySLO: [] })), ]); // Calculate summary metrics const totalRequests = httpMetrics.reduce((sum, m) => sum + m._count, 0); const successRequests = httpMetrics .filter((m) => m.statusCode < 400) .reduce((sum, m) => sum + m._count, 0); const avgDuration = httpMetrics.length > 0 ? httpMetrics.reduce((sum, m) => sum + (m._avg.duration || 0) * m._count, 0) / totalRequests : 0; // Process Web Vitals data const webVitalsData = processWebVitals(vitalsEvents); return { slos, metrics: { totalRequests, successRate: totalRequests > 0 ? (successRequests / totalRequests) * 100 : 100, avgDuration, errorCount: recentErrors.length, }, rumSummary: rumEvents, recentErrors, webVitals: webVitalsData, sloAlerts: { active: activeSloAlerts, recent: recentSloAlerts, stats: sloAlertStats, }, }; } /** * Process raw vitals events into aggregated statistics */ function processWebVitals( events: { url: string; data: unknown }[] ): { vitals: Record<WebVitalName, WebVitalStats>; byPage: PageWebVitals[]; totalMeasurements: number; } { const metricValues: Record<WebVitalName, number[]> = { LCP: [], CLS: [], FID: [], INP: [], FCP: [], TTFB: [], }; const pageMetrics: Map<string, Record<WebVitalName, number[]>> = new Map(); for (const event of events) { const data = event.data as Record<string, unknown>; const normalizedPath = normalizePagePath(event.url); if (!pageMetrics.has(normalizedPath)) { pageMetrics.set(normalizedPath, { LCP: [], CLS: [], FID: [], INP: [], FCP: [], TTFB: [], }); } const pageData = pageMetrics.get(normalizedPath)!; const metrics: WebVitalName[] = ['LCP', 'CLS', 'FID', 'INP', 'FCP', 'TTFB']; for (const metric of metrics) { const value = data[metric]; if (typeof value === 'number' && !isNaN(value) && value >= 0) { metricValues[metric].push(value); pageData[metric].push(value); } } } const vitals: Record<WebVitalName, WebVitalStats> = { LCP: calculateWebVitalStats('LCP', metricValues.LCP), CLS: calculateWebVitalStats('CLS', metricValues.CLS), FID: calculateWebVitalStats('FID', metricValues.FID), INP: calculateWebVitalStats('INP', metricValues.INP), FCP: calculateWebVitalStats('FCP', metricValues.FCP), TTFB: calculateWebVitalStats('TTFB', metricValues.TTFB), }; const byPage: PageWebVitals[] = []; for (const [url, metrics] of pageMetrics.entries()) { const pageStats: Partial<Record<WebVitalName, WebVitalStats>> = {}; let hasData = false; for (const metric of ['LCP', 'CLS', 'FID', 'INP', 'FCP', 'TTFB'] as WebVitalName[]) { if (metrics[metric].length > 0) { pageStats[metric] = calculateWebVitalStats(metric, metrics[metric]); hasData = true; } } if (hasData) { byPage.push({ url, metrics: pageStats, worstMetric: getWorstMetric(pageStats), }); } } // Sort by worst performing byPage.sort((a, b) => { const aRating = a.worstMetric?.rating || 'good'; const bRating = b.worstMetric?.rating || 'good'; const ratingOrder = { poor: 0, 'needs-improvement': 1, good: 2 }; return ratingOrder[aRating] - ratingOrder[bRating]; }); return { vitals, byPage: byPage.slice(0, 10), totalMeasurements: events.length, }; } export default async function ObservabilityPage() { const data = await getObservabilityData(); return ( <ObservabilityDashboard initialData={data} enableRealtime={true} /> ); } |