Shinway Deploy factory-droid[bot] commited on
Commit
ff74951
·
1 Parent(s): bb95c14

feat(dashboard): add SSE live updates and enhanced Gateway Overview UI

Browse files

- Add /api/dashboard/stream/stats SSE endpoint for real-time streaming
- Create useLiveStats hook with EventSource for instant updates
- Redesign Gateway Overview with dark theme and glassmorphism
- Add live connection status indicator (Connected/Disconnected)
- Display uptime, requests, tokens, error rate in hero section
- Add latency progress bar with P50/P95/P99 percentiles
- Animated gradient backgrounds and hover effects

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>

dashboard/src/app/page.tsx CHANGED
@@ -6,42 +6,184 @@ import { StatsCards } from '@/components/dashboard/StatsCards';
6
  import { RequestsChart } from '@/components/charts/RequestsChart';
7
  import { LatencyChart } from '@/components/charts/LatencyChart';
8
  import { TokenUsageChart } from '@/components/charts/TokenUsageChart';
9
- import { useStats, useMetrics } from '@/hooks/useMetrics';
10
- import { ArrowRight, Sparkles } from 'lucide-react';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
  export default function DashboardPage() {
13
- const { data: stats, isLoading: statsLoading } = useStats();
14
  const { data: metrics } = useMetrics();
 
 
 
 
15
 
16
  return (
17
  <div className="space-y-8 animate-fade-in">
18
- {/* Hero Section */}
19
- <div className="group relative overflow-hidden rounded-2xl bg-gradient-to-r from-primary/10 via-chart-5/10 to-chart-2/10 p-8 shadow-xl hover:shadow-2xl transition-all duration-500 glow">
20
- {/* Animated background pattern */}
21
- <div className="absolute inset-0 bg-grid-white/5" />
22
- <div className="absolute inset-0 bg-gradient-to-br from-primary/5 via-transparent to-chart-5/5 opacity-0 group-hover:opacity-100 transition-opacity duration-700" />
23
-
24
- {/* Floating orbs */}
25
- <div className="absolute top-0 right-0 w-64 h-64 bg-primary/10 rounded-full blur-3xl animate-pulse" />
26
- <div className="absolute bottom-0 left-0 w-48 h-48 bg-chart-5/10 rounded-full blur-3xl animate-pulse" style={{ animationDelay: '1s' }} />
27
-
28
- <div className="relative">
29
- <div className="flex items-center gap-2 animate-slide-up">
30
- <Sparkles className="h-5 w-5 text-primary animate-pulse" />
31
- <Badge variant="outline" className="bg-primary/10 text-primary border-primary/20 font-semibold shadow-lg">
32
- <span className="relative flex h-2 w-2 mr-2">
33
- <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-primary opacity-75"></span>
34
- <span className="relative inline-flex rounded-full h-2 w-2 bg-primary"></span>
35
- </span>
36
- Live Monitoring
37
- </Badge>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  </div>
39
- <h2 className="mt-4 text-3xl font-bold tracking-tight bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text text-transparent animate-slide-up" style={{ animationDelay: '100ms' }}>
40
- Gateway Overview
41
- </h2>
42
- <p className="mt-2 max-w-2xl text-muted-foreground leading-relaxed animate-slide-up" style={{ animationDelay: '200ms' }}>
43
- Real-time insights into your Kiro Gateway performance, token usage, and system health.
44
- </p>
45
  </div>
46
  </div>
47
 
 
6
  import { RequestsChart } from '@/components/charts/RequestsChart';
7
  import { LatencyChart } from '@/components/charts/LatencyChart';
8
  import { TokenUsageChart } from '@/components/charts/TokenUsageChart';
9
+ import { useLiveStats, useMetrics, useHealth } from '@/hooks/useMetrics';
10
+ import { ArrowRight, Sparkles, Activity, Zap, Shield, Clock, Server, Wifi, WifiOff } from 'lucide-react';
11
+
12
+ function formatUptime(seconds: number): string {
13
+ const days = Math.floor(seconds / 86400);
14
+ const hours = Math.floor((seconds % 86400) / 3600);
15
+ const mins = Math.floor((seconds % 3600) / 60);
16
+ const secs = Math.floor(seconds % 60);
17
+
18
+ if (days > 0) return `${days}d ${hours}h ${mins}m`;
19
+ if (hours > 0) return `${hours}h ${mins}m ${secs}s`;
20
+ if (mins > 0) return `${mins}m ${secs}s`;
21
+ return `${secs}s`;
22
+ }
23
+
24
+ function formatNumber(num: number): string {
25
+ if (num >= 1_000_000) return `${(num / 1_000_000).toFixed(1)}M`;
26
+ if (num >= 1_000) return `${(num / 1_000).toFixed(1)}K`;
27
+ return num.toLocaleString();
28
+ }
29
 
30
  export default function DashboardPage() {
31
+ const { data: stats, isLoading: statsLoading } = useLiveStats();
32
  const { data: metrics } = useMetrics();
33
+ const { data: health } = useHealth();
34
+
35
+ const isConnected = health?.status === 'healthy';
36
+ const totalTokens = (stats?.total_input_tokens ?? 0) + (stats?.total_output_tokens ?? 0);
37
 
38
  return (
39
  <div className="space-y-8 animate-fade-in">
40
+ {/* Hero Section - Enhanced Gateway Overview */}
41
+ <div className="group relative overflow-hidden rounded-3xl bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 p-8 shadow-2xl border border-white/10">
42
+ {/* Animated grid background */}
43
+ <div className="absolute inset-0 bg-[linear-gradient(to_right,#1f2937_1px,transparent_1px),linear-gradient(to_bottom,#1f2937_1px,transparent_1px)] bg-[size:4rem_4rem] [mask-image:radial-gradient(ellipse_60%_50%_at_50%_0%,#000_70%,transparent_110%)]" />
44
+
45
+ {/* Animated gradient orbs */}
46
+ <div className="absolute top-0 right-0 w-96 h-96 bg-gradient-to-br from-blue-500/30 to-purple-500/30 rounded-full blur-3xl animate-pulse" />
47
+ <div className="absolute bottom-0 left-0 w-80 h-80 bg-gradient-to-tr from-emerald-500/20 to-cyan-500/20 rounded-full blur-3xl animate-pulse" style={{ animationDelay: '1s' }} />
48
+ <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-64 h-64 bg-gradient-to-r from-pink-500/10 to-orange-500/10 rounded-full blur-3xl animate-pulse" style={{ animationDelay: '2s' }} />
49
+
50
+ {/* Content */}
51
+ <div className="relative z-10">
52
+ {/* Top row - Status and Live indicator */}
53
+ <div className="flex items-center justify-between mb-6">
54
+ <div className="flex items-center gap-3">
55
+ <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-gradient-to-br from-blue-500 to-purple-600 shadow-lg shadow-blue-500/25">
56
+ <Server className="h-6 w-6 text-white" />
57
+ </div>
58
+ <div>
59
+ <h1 className="text-2xl font-bold text-white tracking-tight">Gateway Overview</h1>
60
+ <p className="text-sm text-slate-400">Real-time monitoring dashboard</p>
61
+ </div>
62
+ </div>
63
+
64
+ <div className="flex items-center gap-3">
65
+ {/* Connection Status */}
66
+ <div className={`flex items-center gap-2 px-4 py-2 rounded-full ${isConnected ? 'bg-emerald-500/10 border border-emerald-500/20' : 'bg-red-500/10 border border-red-500/20'}`}>
67
+ {isConnected ? (
68
+ <>
69
+ <Wifi className="h-4 w-4 text-emerald-400" />
70
+ <span className="text-sm font-medium text-emerald-400">Connected</span>
71
+ </>
72
+ ) : (
73
+ <>
74
+ <WifiOff className="h-4 w-4 text-red-400" />
75
+ <span className="text-sm font-medium text-red-400">Disconnected</span>
76
+ </>
77
+ )}
78
+ </div>
79
+
80
+ {/* Live indicator */}
81
+ <Badge className="bg-gradient-to-r from-blue-500 to-purple-500 border-0 text-white font-semibold px-4 py-2 shadow-lg shadow-blue-500/25">
82
+ <span className="relative flex h-2 w-2 mr-2">
83
+ <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-white opacity-75"></span>
84
+ <span className="relative inline-flex rounded-full h-2 w-2 bg-white"></span>
85
+ </span>
86
+ LIVE
87
+ </Badge>
88
+ </div>
89
+ </div>
90
+
91
+ {/* Main Stats Grid */}
92
+ <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
93
+ {/* Uptime */}
94
+ <div className="group/card relative overflow-hidden rounded-2xl bg-white/5 backdrop-blur-sm border border-white/10 p-4 hover:bg-white/10 transition-all duration-300">
95
+ <div className="flex items-center gap-3 mb-2">
96
+ <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-emerald-500/20">
97
+ <Clock className="h-5 w-5 text-emerald-400" />
98
+ </div>
99
+ <span className="text-xs font-medium text-slate-400 uppercase tracking-wider">Uptime</span>
100
+ </div>
101
+ <div className="text-2xl font-bold text-white font-mono">
102
+ {statsLoading ? (
103
+ <div className="h-8 w-24 bg-white/10 rounded animate-pulse" />
104
+ ) : (
105
+ formatUptime(stats?.uptime_seconds ?? 0)
106
+ )}
107
+ </div>
108
+ </div>
109
+
110
+ {/* Requests */}
111
+ <div className="group/card relative overflow-hidden rounded-2xl bg-white/5 backdrop-blur-sm border border-white/10 p-4 hover:bg-white/10 transition-all duration-300">
112
+ <div className="flex items-center gap-3 mb-2">
113
+ <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-blue-500/20">
114
+ <Activity className="h-5 w-5 text-blue-400" />
115
+ </div>
116
+ <span className="text-xs font-medium text-slate-400 uppercase tracking-wider">Requests</span>
117
+ </div>
118
+ <div className="text-2xl font-bold text-white font-mono">
119
+ {statsLoading ? (
120
+ <div className="h-8 w-20 bg-white/10 rounded animate-pulse" />
121
+ ) : (
122
+ formatNumber(stats?.total_requests ?? 0)
123
+ )}
124
+ </div>
125
+ {stats?.active_requests ? (
126
+ <div className="mt-1 text-xs text-blue-400">{stats.active_requests} active</div>
127
+ ) : null}
128
+ </div>
129
+
130
+ {/* Tokens */}
131
+ <div className="group/card relative overflow-hidden rounded-2xl bg-white/5 backdrop-blur-sm border border-white/10 p-4 hover:bg-white/10 transition-all duration-300">
132
+ <div className="flex items-center gap-3 mb-2">
133
+ <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-amber-500/20">
134
+ <Zap className="h-5 w-5 text-amber-400" />
135
+ </div>
136
+ <span className="text-xs font-medium text-slate-400 uppercase tracking-wider">Tokens</span>
137
+ </div>
138
+ <div className="text-2xl font-bold text-white font-mono">
139
+ {statsLoading ? (
140
+ <div className="h-8 w-20 bg-white/10 rounded animate-pulse" />
141
+ ) : (
142
+ formatNumber(totalTokens)
143
+ )}
144
+ </div>
145
+ <div className="mt-1 text-xs text-slate-500">
146
+ {formatNumber(stats?.total_input_tokens ?? 0)} in / {formatNumber(stats?.total_output_tokens ?? 0)} out
147
+ </div>
148
+ </div>
149
+
150
+ {/* Error Rate */}
151
+ <div className="group/card relative overflow-hidden rounded-2xl bg-white/5 backdrop-blur-sm border border-white/10 p-4 hover:bg-white/10 transition-all duration-300">
152
+ <div className="flex items-center gap-3 mb-2">
153
+ <div className={`flex h-10 w-10 items-center justify-center rounded-xl ${(stats?.error_rate ?? 0) > 0.05 ? 'bg-red-500/20' : 'bg-emerald-500/20'}`}>
154
+ <Shield className={`h-5 w-5 ${(stats?.error_rate ?? 0) > 0.05 ? 'text-red-400' : 'text-emerald-400'}`} />
155
+ </div>
156
+ <span className="text-xs font-medium text-slate-400 uppercase tracking-wider">Error Rate</span>
157
+ </div>
158
+ <div className={`text-2xl font-bold font-mono ${(stats?.error_rate ?? 0) > 0.05 ? 'text-red-400' : 'text-emerald-400'}`}>
159
+ {statsLoading ? (
160
+ <div className="h-8 w-16 bg-white/10 rounded animate-pulse" />
161
+ ) : (
162
+ `${((stats?.error_rate ?? 0) * 100).toFixed(2)}%`
163
+ )}
164
+ </div>
165
+ <div className="mt-1 text-xs text-slate-500">{stats?.total_errors ?? 0} errors</div>
166
+ </div>
167
+ </div>
168
+
169
+ {/* Latency Bar */}
170
+ <div className="rounded-2xl bg-white/5 backdrop-blur-sm border border-white/10 p-4">
171
+ <div className="flex items-center justify-between mb-3">
172
+ <span className="text-sm font-medium text-slate-400">Response Latency</span>
173
+ <div className="flex items-center gap-4 text-xs">
174
+ <span className="text-slate-500">AVG: <span className="text-white font-mono">{(stats?.avg_latency_ms ?? 0).toFixed(0)}ms</span></span>
175
+ <span className="text-slate-500">P50: <span className="text-white font-mono">{(stats?.p50_latency_ms ?? 0).toFixed(0)}ms</span></span>
176
+ <span className="text-slate-500">P95: <span className="text-amber-400 font-mono">{(stats?.p95_latency_ms ?? 0).toFixed(0)}ms</span></span>
177
+ <span className="text-slate-500">P99: <span className="text-red-400 font-mono">{(stats?.p99_latency_ms ?? 0).toFixed(0)}ms</span></span>
178
+ </div>
179
+ </div>
180
+ <div className="h-2 w-full rounded-full bg-white/10 overflow-hidden">
181
+ <div
182
+ className="h-full bg-gradient-to-r from-emerald-500 via-amber-500 to-red-500 rounded-full transition-all duration-500"
183
+ style={{ width: `${Math.min(100, ((stats?.avg_latency_ms ?? 0) / 5000) * 100)}%` }}
184
+ />
185
+ </div>
186
  </div>
 
 
 
 
 
 
187
  </div>
188
  </div>
189
 
dashboard/src/hooks/useMetrics.ts CHANGED
@@ -1,7 +1,9 @@
1
  'use client';
2
 
3
- import { useQuery } from '@tanstack/react-query';
 
4
  import api from '@/lib/api';
 
5
 
6
  const LIVE_QUERY_OPTIONS = {
7
  refetchOnReconnect: true,
@@ -9,6 +11,11 @@ const LIVE_QUERY_OPTIONS = {
9
  refetchIntervalInBackground: true,
10
  } as const;
11
 
 
 
 
 
 
12
  export function useStats() {
13
  return useQuery({
14
  queryKey: ['stats'],
@@ -18,6 +25,69 @@ export function useStats() {
18
  });
19
  }
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  export function useMetrics(params?: { start_time?: string; end_time?: string; model?: string }) {
22
  return useQuery({
23
  queryKey: ['metrics', params],
 
1
  'use client';
2
 
3
+ import { useQuery, useQueryClient } from '@tanstack/react-query';
4
+ import { useEffect, useCallback, useRef } from 'react';
5
  import api from '@/lib/api';
6
+ import type { DashboardStats } from '@/types/metrics';
7
 
8
  const LIVE_QUERY_OPTIONS = {
9
  refetchOnReconnect: true,
 
11
  refetchIntervalInBackground: true,
12
  } as const;
13
 
14
+ // Get API key from env
15
+ const API_KEY = typeof window !== 'undefined'
16
+ ? (process.env.NEXT_PUBLIC_DASHBOARD_API_KEY || '')
17
+ : '';
18
+
19
  export function useStats() {
20
  return useQuery({
21
  queryKey: ['stats'],
 
25
  });
26
  }
27
 
28
+ export function useLiveStats() {
29
+ const queryClient = useQueryClient();
30
+ const eventSourceRef = useRef<EventSource | null>(null);
31
+ const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
32
+
33
+ const connect = useCallback(() => {
34
+ // Clean up existing connection
35
+ if (eventSourceRef.current) {
36
+ eventSourceRef.current.close();
37
+ }
38
+
39
+ const baseUrl = process.env.NEXT_PUBLIC_API_URL || '';
40
+ const url = `${baseUrl}/api/dashboard/stream/stats?key=${encodeURIComponent(API_KEY)}`;
41
+
42
+ const eventSource = new EventSource(url);
43
+ eventSourceRef.current = eventSource;
44
+
45
+ eventSource.onmessage = (event) => {
46
+ try {
47
+ const data: DashboardStats = JSON.parse(event.data);
48
+ // Update the query cache directly for instant updates
49
+ queryClient.setQueryData(['stats'], data);
50
+ } catch (e) {
51
+ console.error('Failed to parse SSE data:', e);
52
+ }
53
+ };
54
+
55
+ eventSource.onerror = () => {
56
+ eventSource.close();
57
+ // Reconnect after 3 seconds
58
+ reconnectTimeoutRef.current = setTimeout(() => {
59
+ connect();
60
+ }, 3000);
61
+ };
62
+ }, [queryClient]);
63
+
64
+ useEffect(() => {
65
+ // Only connect if we have an API key
66
+ if (API_KEY) {
67
+ connect();
68
+ }
69
+
70
+ return () => {
71
+ if (eventSourceRef.current) {
72
+ eventSourceRef.current.close();
73
+ }
74
+ if (reconnectTimeoutRef.current) {
75
+ clearTimeout(reconnectTimeoutRef.current);
76
+ }
77
+ };
78
+ }, [connect]);
79
+
80
+ // Return the query with SSE updates
81
+ return useQuery({
82
+ queryKey: ['stats'],
83
+ queryFn: api.getStats,
84
+ // Disable polling when SSE is active
85
+ refetchInterval: API_KEY ? false : 5000,
86
+ staleTime: API_KEY ? Infinity : 0,
87
+ ...LIVE_QUERY_OPTIONS,
88
+ });
89
+ }
90
+
91
  export function useMetrics(params?: { start_time?: string; end_time?: string; model?: string }) {
92
  return useQuery({
93
  queryKey: ['metrics', params],
kiro/dashboard_api/routes.py CHANGED
@@ -5,10 +5,13 @@ Dashboard API routes.
5
  Provides REST endpoints for the admin dashboard.
6
  """
7
 
 
 
8
  from datetime import datetime, timezone
9
- from typing import List, Optional
10
 
11
  from fastapi import APIRouter, Depends, HTTPException, Request, Query
 
12
  from fastapi.security import APIKeyHeader
13
  from loguru import logger
14
 
@@ -414,3 +417,100 @@ async def detailed_health(request: Request) -> HealthResponse:
414
  metrics_enabled=METRICS_ENABLED and METRICS_AVAILABLE,
415
  prometheus_ready=METRICS_AVAILABLE,
416
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  Provides REST endpoints for the admin dashboard.
6
  """
7
 
8
+ import asyncio
9
+ import json
10
  from datetime import datetime, timezone
11
+ from typing import List, Optional, AsyncGenerator
12
 
13
  from fastapi import APIRouter, Depends, HTTPException, Request, Query
14
+ from fastapi.responses import StreamingResponse
15
  from fastapi.security import APIKeyHeader
16
  from loguru import logger
17
 
 
417
  metrics_enabled=METRICS_ENABLED and METRICS_AVAILABLE,
418
  prometheus_ready=METRICS_AVAILABLE,
419
  )
420
+
421
+
422
+ async def _generate_stats_stream(request: Request) -> AsyncGenerator[str, None]:
423
+ """Generate SSE stream with live stats updates."""
424
+ while True:
425
+ try:
426
+ # Check if client disconnected
427
+ if await request.is_disconnected():
428
+ break
429
+
430
+ now = datetime.now(timezone.utc)
431
+ uptime = (now - _startup_time).total_seconds()
432
+
433
+ # Build stats data
434
+ stats_data = {
435
+ "uptime_seconds": uptime,
436
+ "total_requests": 0,
437
+ "total_errors": 0,
438
+ "error_rate": 0.0,
439
+ "active_requests": 0,
440
+ "total_input_tokens": 0,
441
+ "total_output_tokens": 0,
442
+ "requests_by_model": {},
443
+ "tokens_by_model": {},
444
+ "avg_latency_ms": 0.0,
445
+ "p50_latency_ms": 0.0,
446
+ "p95_latency_ms": 0.0,
447
+ "p99_latency_ms": 0.0,
448
+ "accounts_total": 0,
449
+ "accounts_healthy": 0,
450
+ "accounts_unhealthy": 0,
451
+ }
452
+
453
+ if METRICS_AVAILABLE and get_aggregator:
454
+ aggregator = get_aggregator()
455
+ metrics_stats = aggregator.get_stats()
456
+ stats_data.update({
457
+ "uptime_seconds": metrics_stats.get("uptime_seconds", uptime),
458
+ "total_requests": metrics_stats.get("total_requests", 0),
459
+ "total_errors": metrics_stats.get("total_errors", 0),
460
+ "error_rate": metrics_stats.get("error_rate", 0.0),
461
+ "active_requests": metrics_stats.get("active_requests", 0),
462
+ "total_input_tokens": metrics_stats.get("total_input_tokens", 0),
463
+ "total_output_tokens": metrics_stats.get("total_output_tokens", 0),
464
+ "requests_by_model": metrics_stats.get("requests_by_model", {}),
465
+ "tokens_by_model": metrics_stats.get("tokens_by_model", {}),
466
+ "avg_latency_ms": metrics_stats.get("avg_latency_ms", 0.0),
467
+ "p50_latency_ms": metrics_stats.get("p50_latency_ms", 0.0),
468
+ "p95_latency_ms": metrics_stats.get("p95_latency_ms", 0.0),
469
+ "p99_latency_ms": metrics_stats.get("p99_latency_ms", 0.0),
470
+ })
471
+
472
+ # Get account stats
473
+ account_pool = getattr(request.app.state, 'account_pool', None)
474
+ if account_pool:
475
+ account_stats = account_pool.get_account_stats()
476
+ stats_data["accounts_total"] = len(account_stats)
477
+ for acc in account_stats:
478
+ if acc.get('health_status') in ('healthy', 'unknown'):
479
+ stats_data["accounts_healthy"] += 1
480
+ else:
481
+ stats_data["accounts_unhealthy"] += 1
482
+
483
+ # Send SSE event
484
+ yield f"data: {json.dumps(stats_data)}\n\n"
485
+
486
+ # Wait before next update (1 second for real-time feel)
487
+ await asyncio.sleep(1)
488
+
489
+ except asyncio.CancelledError:
490
+ break
491
+ except Exception as e:
492
+ logger.error(f"SSE stream error: {e}")
493
+ break
494
+
495
+
496
+ @router.get("/stream/stats")
497
+ async def stream_stats(request: Request, api_key: str = Query(None, alias="key")):
498
+ """
499
+ Server-Sent Events (SSE) endpoint for real-time stats.
500
+
501
+ Streams live dashboard statistics every second.
502
+ Connect with EventSource: /api/dashboard/stream/stats?key=YOUR_API_KEY
503
+ """
504
+ # Verify API key from query param (SSE doesn't support headers easily)
505
+ if not api_key or api_key != PROXY_API_KEY:
506
+ raise HTTPException(status_code=401, detail="Invalid API key")
507
+
508
+ return StreamingResponse(
509
+ _generate_stats_stream(request),
510
+ media_type="text/event-stream",
511
+ headers={
512
+ "Cache-Control": "no-cache",
513
+ "Connection": "keep-alive",
514
+ "X-Accel-Buffering": "no", # Disable nginx buffering
515
+ },
516
+ )