All files / src/components/features/admin/monitoring/ObservabilityDashboard index.tsx

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

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 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
'use client';

import React, { useEffect, useState, useCallback } from 'react';
import Link from 'next/link';
import { useRealtimeMetrics, type Alert } from '@/hooks/useRealtimeMetrics';
import { getSLOStatusColor, getSLOStatusText, formatWindow, type SLOResult, type SLOTrendPoint } from '@/lib/observability/slo-utils';
import { SLOCard, type TrendIndicator } from '@/components/features/admin/monitoring/SLOCard';
import { MetricsSummary } from '@/components/features/admin/monitoring/MetricsSummary';
import { LiveIndicator } from '@/components/features/admin/monitoring/LiveIndicator';
import { RecentRumEvents } from '@/components/features/admin/monitoring/RecentRumEvents';
import { WebVitalsCard } from '@/components/features/admin/monitoring/WebVitalsCard';
import type { WebVitalName, WebVitalStats, PageWebVitals } from '@/lib/observability/web-vitals';

/**
 * SLO with trend data
 */
export type SLOWithTrend = SLOResult & {
  trend: SLOTrendPoint[];
  trendIndicator: TrendIndicator | null;
};

/**
 * Web Vitals data structure
 */
export interface WebVitalsData {
  vitals: Record<WebVitalName, WebVitalStats>;
  byPage: PageWebVitals[];
  totalMeasurements: number;
}

/**
 * Error log entry
 */
export interface ErrorLogEntry {
  id: number | string;
  category: string;
  message: string;
  createdAt: Date | string;
}

/**
 * RUM event summary
 */
export interface RumEventSummary {
  type: string;
  _count: number;
}

/**
 * SLO Alert from database
 */
export interface SLOAlertEntry {
  id: string;
  sloName: string;
  status: string;
  current: number;
  target: number;
  budgetConsumed: number;
  createdAt: Date | string;
  resolvedAt: Date | string | null;
}

/**
 * SLO Alert stats
 */
export interface SLOAlertStats {
  total: number;
  active: number;
  byStatus: Record<string, number>;
  bySLO: Array<{ sloName: string; count: number }>;
}

/**
 * SLO Alerts data
 */
export interface SLOAlertsData {
  active: SLOAlertEntry[];
  recent: SLOAlertEntry[];
  stats: SLOAlertStats;
}

/**
 * Initial data passed from server
 */
export interface ObservabilityInitialData {
  slos: SLOWithTrend[];
  metrics: {
    totalRequests: number;
    successRate: number;
    avgDuration: number;
    errorCount: number;
  };
  rumSummary: RumEventSummary[];
  recentErrors: ErrorLogEntry[];
  webVitals: WebVitalsData;
  sloAlerts?: SLOAlertsData;
}

export interface ObservabilityDashboardProps {
  /** Initial data from server */
  initialData: ObservabilityInitialData;
  /** Enable real-time updates */
  enableRealtime?: boolean;
  /** Enable incident mode for faster updates */
  incidentMode?: boolean;
}

/**
 * ObservabilityDashboard Component
 *
 * Real-time observability dashboard with SSE streaming updates.
 * Falls back to polling if SSE is not available.
 */
export function ObservabilityDashboard({
  initialData,
  enableRealtime = true,
  incidentMode = false,
}: ObservabilityDashboardProps) {
  // Local state for data (initialized from server, updated from SSE)
  const [slos, setSlos] = useState<SLOWithTrend[]>(initialData.slos);
  const [metrics, setMetrics] = useState(initialData.metrics);
  const [recentErrors, setRecentErrors] = useState(initialData.recentErrors);
  const [activeAlerts, setActiveAlerts] = useState<Alert[]>([]);

  // Handle alerts
  const handleAlert = useCallback((alerts: Alert[]) => {
    setActiveAlerts(alerts);

    // Request notification permission and show desktop notification for critical alerts
    if (alerts.some((a) => a.status === 'critical') && typeof Notification !== 'undefined') {
      if (Notification.permission === 'granted') {
        const criticalAlerts = alerts.filter((a) => a.status === 'critical');
        new Notification('Critical SLO Alert', {
          body: `${criticalAlerts.length} SLO(s) in critical state: ${criticalAlerts.map((a) => a.sloName).join(', ')}`,
          icon: '/favicon.ico',
          tag: 'slo-alert',
        });
      } else if (Notification.permission !== 'denied') {
        Notification.requestPermission();
      }
    }
  }, []);

  // Real-time metrics hook (only active when enableRealtime is true)
  const {
    slos: realtimeSlos,
    metrics: realtimeMetrics,
    recentErrors: realtimeErrors,
    status,
    lastUpdate,
    isPolling,
    reconnect,
  } = useRealtimeMetrics({
    incidentMode,
    onAlert: handleAlert,
  });

  // Update local state when real-time data arrives
  useEffect(() => {
    if (!enableRealtime) return;

    if (realtimeSlos.length > 0) {
      // Merge realtime SLO data with trend info from initial data
      const mergedSlos = realtimeSlos.map((rtSlo) => {
        const initialSlo = initialData.slos.find((s) => s.name === rtSlo.name);
        return {
          ...rtSlo,
          trend: initialSlo?.trend || [],
          trendIndicator: initialSlo?.trendIndicator || null,
        } as SLOWithTrend;
      });
      // Use queueMicrotask to avoid synchronous setState in effect body
      queueMicrotask(() => setSlos(mergedSlos));
    }
  }, [enableRealtime, realtimeSlos, initialData.slos]);

  useEffect(() => {
    if (!enableRealtime) return;
    if (realtimeMetrics) {
      // Use queueMicrotask to avoid synchronous setState in effect body
      queueMicrotask(() => setMetrics(realtimeMetrics));
    }
  }, [enableRealtime, realtimeMetrics]);

  useEffect(() => {
    if (!enableRealtime) return;
    if (realtimeErrors.length > 0) {
      // Use queueMicrotask to avoid synchronous setState in effect body
      queueMicrotask(() => setRecentErrors(realtimeErrors as ErrorLogEntry[]));
    }
  }, [enableRealtime, realtimeErrors]);

  // Group SLOs by category
  const slosByCategory = slos.reduce(
    (acc, slo) => {
      if (!acc[slo.category]) {
        acc[slo.category] = [];
      }
      acc[slo.category].push(slo);
      return acc;
    },
    {} as Record<string, SLOWithTrend[]>
  );

  const categoryOrder = ['overall', 'api', 'checkout', 'search'];

  return (
    <div className="p-6 min-h-screen bg-gray-50 dark:bg-gray-900">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="flex items-start justify-between mb-6">
          <div>
            <div className="flex items-center gap-3">
              <h1 className="text-2xl font-bold text-gray-900 dark:text-white">
                Observability Dashboard
              </h1>
              {enableRealtime && (
                <LiveIndicator
                  status={status}
                  lastUpdate={lastUpdate}
                  isPolling={isPolling}
                  onReconnect={reconnect}
                  compact
                />
              )}
            </div>
            <p className="text-gray-600 dark:text-gray-400 mt-1">
              Monitor system health, SLOs, and user experience metrics
            </p>
          </div>

          {/* Quick Links */}
          <div className="flex gap-2">
            <Link
              href="/admin/monitoring/traces"
              className="px-4 py-2 text-sm font-medium rounded-md bg-blue-600 text-white hover:bg-blue-700 transition-colors flex items-center gap-2"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
              </svg>
              Trace Explorer
            </Link>
            <Link
              href="/admin/monitoring/slo"
              className="px-4 py-2 text-sm font-medium rounded-md bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors flex items-center gap-2"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
              </svg>
              SLO Trends
            </Link>
            <Link
              href="/admin/monitoring/performance"
              className="px-4 py-2 text-sm font-medium rounded-md bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors flex items-center gap-2"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6" />
              </svg>
              Performance
            </Link>
          </div>
        </div>

        {/* Active Alerts Banner */}
        {(activeAlerts.length > 0 || (initialData.sloAlerts?.active.length ?? 0) > 0) && (
          <div className="mb-6 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <svg className="w-5 h-5 text-red-600 dark:text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                </svg>
                <span className="font-medium text-red-800 dark:text-red-200">
                  Active Alerts: {
                    activeAlerts.length > 0
                      ? activeAlerts.map((a) => a.sloName).join(', ')
                      : initialData.sloAlerts?.active.map((a) => a.sloName).join(', ')
                  }
                </span>
              </div>
              {initialData.sloAlerts && initialData.sloAlerts.stats.total > 0 && (
                <span className="text-sm text-red-600 dark:text-red-400">
                  {initialData.sloAlerts.stats.total} alerts in last 7 days
                </span>
              )}
            </div>
          </div>
        )}

        {/* Metrics Summary */}
        <MetricsSummary
          totalRequests={metrics.totalRequests}
          successRate={metrics.successRate}
          avgDuration={metrics.avgDuration}
          errorCount={metrics.errorCount}
          animated={enableRealtime}
        />

        {/* SLO Status */}
        <div className="mb-8">
          <h2 className="text-lg font-semibold mb-4 text-gray-900 dark:text-white">
            Service Level Objectives
          </h2>
          {categoryOrder.map((category) => {
            const categorySlos = slosByCategory[category];
            if (!categorySlos || categorySlos.length === 0) return null;

            return (
              <div key={category} className="mb-6">
                <h3 className="text-sm font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-3">
                  {category === 'overall' ? 'Overall' : category.charAt(0).toUpperCase() + category.slice(1)}
                </h3>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                  {categorySlos.map((slo) => (
                    <SLOCard
                      key={slo.name}
                      name={slo.name}
                      current={slo.current}
                      target={slo.target}
                      budgetConsumed={slo.budgetConsumed}
                      status={slo.status}
                      window={formatWindow(slo.window)}
                      statusColor={getSLOStatusColor(slo.status)}
                      statusText={getSLOStatusText(slo.status)}
                      sparklineData={slo.trend.length > 0 ? slo.trend.map((t) => t.value) : undefined}
                      trendIndicator={slo.trendIndicator}
                      historyLink={`/admin/monitoring/slo/${encodeURIComponent(slo.name)}`}
                    />
                  ))}
                </div>
              </div>
            );
          })}
        </div>

        {/* Core Web Vitals */}
        <div className="mb-8">
          <WebVitalsCard
            vitals={initialData.webVitals.vitals}
            problemPages={initialData.webVitals.byPage}
            periodLabel="Last 24 Hours"
            totalMeasurements={initialData.webVitals.totalMeasurements}
          />
        </div>

        {/* RUM Events Summary */}
        <RecentRumEvents events={initialData.rumSummary} />

        {/* Recent SLO Alerts */}
        {initialData.sloAlerts && initialData.sloAlerts.recent.length > 0 && (
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                <svg className="w-5 h-5 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
                </svg>
                SLO Alerts (24h)
              </h2>
              <div className="flex items-center gap-4 text-sm">
                <span className="px-2 py-1 rounded bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300">
                  {initialData.sloAlerts.stats.byStatus['critical'] || 0} Critical
                </span>
                <span className="px-2 py-1 rounded bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300">
                  {initialData.sloAlerts.stats.byStatus['warning'] || 0} Warning
                </span>
              </div>
            </div>
            <div className="space-y-3">
              {initialData.sloAlerts.recent.slice(0, 5).map((alert) => (
                <div
                  key={alert.id}
                  className={`p-3 rounded border-l-4 ${
                    alert.status === 'critical'
                      ? 'bg-red-50 dark:bg-red-900/20 border-red-500'
                      : 'bg-amber-50 dark:bg-amber-900/20 border-amber-500'
                  }`}
                >
                  <div className="flex justify-between items-start">
                    <div>
                      <span className={`inline-block px-2 py-0.5 text-xs font-medium rounded mr-2 ${
                        alert.status === 'critical'
                          ? 'bg-red-100 dark:bg-red-800 text-red-800 dark:text-red-200'
                          : 'bg-amber-100 dark:bg-amber-800 text-amber-800 dark:text-amber-200'
                      }`}>
                        {alert.status.toUpperCase()}
                      </span>
                      <span className="text-sm font-medium text-gray-900 dark:text-gray-100">
                        {alert.sloName}
                      </span>
                      <span className="text-sm text-gray-500 dark:text-gray-400 ml-2">
                        {alert.current.toFixed(2)}% (target: {alert.target}%)
                      </span>
                    </div>
                    <div className="flex items-center gap-2">
                      {alert.resolvedAt ? (
                        <span className="text-xs px-2 py-0.5 rounded bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300">
                          Resolved
                        </span>
                      ) : (
                        <span className="text-xs px-2 py-0.5 rounded bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300">
                          Active
                        </span>
                      )}
                      <span className="text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap">
                        {new Date(alert.createdAt).toLocaleString()}
                      </span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Recent Errors */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <h2 className="text-lg font-semibold mb-4 text-gray-900 dark:text-white">
            Recent Errors (24h)
          </h2>
          {recentErrors.length > 0 ? (
            <div className="space-y-3">
              {recentErrors.map((error) => (
                <div
                  key={error.id}
                  className="p-3 bg-red-50 dark:bg-red-900/20 rounded border-l-4 border-red-500"
                >
                  <div className="flex justify-between items-start">
                    <div>
                      <span className="inline-block px-2 py-0.5 text-xs font-medium rounded bg-red-100 dark:bg-red-800 text-red-800 dark:text-red-200 mr-2">
                        {error.category}
                      </span>
                      <span className="text-sm text-gray-900 dark:text-gray-100">
                        {error.message.slice(0, 100)}
                        {error.message.length > 100 ? '...' : ''}
                      </span>
                    </div>
                    <span className="text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap ml-4">
                      {new Date(error.createdAt).toLocaleString()}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <p className="text-gray-500 dark:text-gray-400 text-center py-8">
              No errors recorded in the last 24 hours
            </p>
          )}
        </div>
      </div>
    </div>
  );
}

export default ObservabilityDashboard;