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 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 | 'use client'; import { useState, useEffect, useCallback } from 'react'; import { Button } from '@/components/ui/Button'; import { Card } from '@/components/ui/Card'; import { Badge } from '@/components/ui/Badge'; import LoadingSpinner from '@/components/ui/LoadingSpinner'; import { Icon, IconName } from '@/components/ui/icons'; import { cn } from '@/lib/core'; import toast from 'react-hot-toast'; import { clientLogger } from '@/lib/logging/clientLogger'; interface CacheStats { stats: { hits: number; misses: number; keys: number; ksize: number; vsize: number; hitRate: number; hitRatePercent: string; }; totalKeys: number; keysByPrefix: Record<string, number>; sampleKeys: string[]; sources?: { nodeCacheKeys: number; coreCacheKeys: number; }; } type InvalidateTarget = | 'all' | 'products' | 'categories' | 'content' | 'support' | 'promotions' | 'admin'; interface CacheDashboardProps { /** Initial stats from server */ initialStats?: CacheStats | null; /** Auto-refresh interval in seconds (0 to disable) */ autoRefreshInterval?: number; } /** * CacheDashboard - Admin dashboard for monitoring and managing cache * * Features: * - Real-time cache statistics * - Hit/miss ratio visualization * - Cache key inspection * - Manual cache invalidation * - Auto-refresh capability */ export function CacheDashboard({ initialStats = null, autoRefreshInterval = 30, }: CacheDashboardProps) { const [stats, setStats] = useState<CacheStats | null>(initialStats); const [loading, setLoading] = useState(!initialStats); const [invalidating, setInvalidating] = useState<string | null>(null); const [autoRefresh, setAutoRefresh] = useState(autoRefreshInterval > 0); const [lastRefresh, setLastRefresh] = useState<Date>(new Date()); const [selectedPrefix, setSelectedPrefix] = useState<string | null>(null); const [patternInput, setPatternInput] = useState(''); const fetchStats = useCallback(async () => { try { const response = await fetch('/api/admin/cache/stats'); if (!response.ok) throw new Error('Failed to fetch cache stats'); const json = await response.json(); // API returns { success: true, data: {...} } - extract the data const data = json.data || json; setStats(data); setLastRefresh(new Date()); } catch (error) { clientLogger.error('Failed to fetch cache stats', error instanceof Error ? error : new Error(String(error))); toast.error('Failed to fetch cache stats'); } finally { setLoading(false); } }, []); // Initial fetch useEffect(() => { if (!initialStats) { fetchStats(); } }, [initialStats, fetchStats]); // Auto-refresh useEffect(() => { if (!autoRefresh || autoRefreshInterval <= 0) return; const interval = setInterval(fetchStats, autoRefreshInterval * 1000); return () => clearInterval(interval); }, [autoRefresh, autoRefreshInterval, fetchStats]); const handleInvalidate = async (target: InvalidateTarget) => { setInvalidating(target); try { const response = await fetch('/api/admin/cache/invalidate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ target }), }); if (!response.ok) throw new Error('Failed to invalidate cache'); const result = await response.json(); toast.success(result.message); await fetchStats(); } catch (error) { clientLogger.error('Failed to invalidate cache', error instanceof Error ? error : new Error(String(error)), { target }); toast.error('Failed to invalidate cache'); } finally { setInvalidating(null); } }; const handlePatternInvalidate = async () => { if (!patternInput.trim()) { toast.error('Please enter a pattern'); return; } setInvalidating('pattern'); try { const response = await fetch('/api/admin/cache/invalidate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ target: 'pattern', pattern: patternInput }), }); if (!response.ok) throw new Error('Failed to invalidate cache'); const result = await response.json(); toast.success(result.message); setPatternInput(''); await fetchStats(); } catch (error) { clientLogger.error('Failed to invalidate cache by pattern', error instanceof Error ? error : new Error(String(error)), { pattern: patternInput }); toast.error('Failed to invalidate cache'); } finally { setInvalidating(null); } }; const filteredKeys = stats?.sampleKeys?.filter((key) => selectedPrefix ? key.startsWith(selectedPrefix) : true ) || []; if (loading) { return ( <div className="flex items-center justify-center p-12"> <LoadingSpinner size="lg" /> </div> ); } return ( <div className="space-y-6"> {/* Header with refresh controls */} <div className="flex items-center justify-between"> <div className="flex items-center gap-4"> <Button variant="outline" size="sm" onClick={fetchStats} disabled={loading} > <Icon name="refresh" className="w-4 h-4 mr-2" /> Refresh </Button> <label className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400"> <input type="checkbox" checked={autoRefresh} onChange={(e) => setAutoRefresh(e.target.checked)} className="rounded border-gray-300 dark:border-gray-600" /> Auto-refresh ({autoRefreshInterval}s) </label> </div> <span className="text-sm text-gray-500 dark:text-gray-400"> Last updated: {lastRefresh.toLocaleTimeString()} </span> </div> {/* Stats Cards */} <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4"> <StatsCard title="Cache Hits" value={stats?.stats.hits.toLocaleString() || '0'} icon="check-circle" color="green" /> <StatsCard title="Cache Misses" value={stats?.stats.misses.toLocaleString() || '0'} icon="x-circle" color="red" /> <StatsCard title="Hit Rate" value={stats?.stats.hitRatePercent || '0%'} icon="trending-up" color="blue" subtitle={getHitRateQuality(stats?.stats.hitRate || 0)} /> <StatsCard title="Cached Keys" value={stats?.totalKeys.toLocaleString() || '0'} icon="database" color="purple" /> </div> {/* Cold Start Notice */} {stats && stats.totalKeys === 0 && stats.stats.hits === 0 && ( <div className="p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg"> <div className="flex items-start gap-3"> <Icon name="info-circle" className="w-5 h-5 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" /> <div> <p className="text-sm text-blue-800 dark:text-blue-200 font-medium"> Cache is empty (cold start) </p> <p className="text-sm text-blue-700 dark:text-blue-300 mt-1"> The in-memory cache clears when the server restarts. Visit some pages (products, categories) to populate the cache, then refresh this dashboard. </p> </div> </div> </div> )} {/* Memory Usage */} <Card className="p-6"> <h3 className="text-lg font-semibold mb-4 text-gray-900 dark:text-white"> Memory Usage </h3> <div className="grid grid-cols-2 gap-4"> <div> <p className="text-sm text-gray-500 dark:text-gray-400">Key Storage</p> <p className="text-2xl font-bold text-gray-900 dark:text-white"> {formatBytes(stats?.stats.ksize || 0)} </p> </div> <div> <p className="text-sm text-gray-500 dark:text-gray-400">Value Storage</p> <p className="text-2xl font-bold text-gray-900 dark:text-white"> {formatBytes(stats?.stats.vsize || 0)} </p> </div> </div> </Card> {/* Keys by Prefix */} <Card className="p-6"> <h3 className="text-lg font-semibold mb-4 text-gray-900 dark:text-white"> Keys by Category </h3> <div className="flex flex-wrap gap-2"> <Badge variant={selectedPrefix === null ? 'primary' : 'default'} className="cursor-pointer" onClick={() => setSelectedPrefix(null)} > All ({stats?.totalKeys || 0}) </Badge> {Object.entries(stats?.keysByPrefix || {}) .sort((a, b) => b[1] - a[1]) .map(([prefix, count]) => ( <Badge key={prefix} variant={selectedPrefix === prefix ? 'primary' : 'default'} className="cursor-pointer" onClick={() => setSelectedPrefix(prefix === selectedPrefix ? null : prefix)} > {prefix} ({count}) </Badge> ))} </div> </Card> {/* Cache Keys Inspector */} <Card className="p-6"> <h3 className="text-lg font-semibold mb-4 text-gray-900 dark:text-white"> Cached Keys {selectedPrefix && `(${selectedPrefix})`} </h3> {filteredKeys.length > 0 ? ( <div className="max-h-64 overflow-y-auto"> <ul className="space-y-1"> {filteredKeys.map((key) => ( <li key={key} className="text-sm font-mono text-gray-600 dark:text-gray-400 py-1 px-2 bg-gray-50 dark:bg-gray-800 rounded" > {key} </li> ))} </ul> {stats && stats.totalKeys > 100 && ( <p className="text-sm text-gray-500 dark:text-gray-400 mt-4"> Showing first 100 of {stats.totalKeys} keys </p> )} </div> ) : ( <p className="text-gray-500 dark:text-gray-400">No cached keys</p> )} </Card> {/* Cache Invalidation Controls */} <Card className="p-6"> <h3 className="text-lg font-semibold mb-4 text-gray-900 dark:text-white"> Cache Invalidation </h3> {/* Quick Actions */} <div className="space-y-4"> <div> <p className="text-sm text-gray-600 dark:text-gray-400 mb-2"> Quick Actions </p> <div className="flex flex-wrap gap-2"> <InvalidateButton label="Products" target="products" onClick={() => handleInvalidate('products')} loading={invalidating === 'products'} disabled={!!invalidating} /> <InvalidateButton label="Categories" target="categories" onClick={() => handleInvalidate('categories')} loading={invalidating === 'categories'} disabled={!!invalidating} /> <InvalidateButton label="Content" target="content" onClick={() => handleInvalidate('content')} loading={invalidating === 'content'} disabled={!!invalidating} /> <InvalidateButton label="Support" target="support" onClick={() => handleInvalidate('support')} loading={invalidating === 'support'} disabled={!!invalidating} /> <InvalidateButton label="Promotions" target="promotions" onClick={() => handleInvalidate('promotions')} loading={invalidating === 'promotions'} disabled={!!invalidating} /> </div> </div> {/* Pattern-based invalidation */} <div> <p className="text-sm text-gray-600 dark:text-gray-400 mb-2"> Pattern-based Invalidation (regex) </p> <div className="flex gap-2"> <input type="text" value={patternInput} onChange={(e) => setPatternInput(e.target.value)} placeholder="e.g., ^products:category:1" className="flex-1 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white text-sm" /> <Button variant="outline" onClick={handlePatternInvalidate} disabled={!!invalidating || !patternInput.trim()} > {invalidating === 'pattern' ? ( <LoadingSpinner size="sm" /> ) : ( 'Invalidate' )} </Button> </div> </div> {/* Flush All */} <div className="pt-4 border-t border-gray-200 dark:border-gray-700"> <Button variant="danger" onClick={() => { if (confirm('Are you sure you want to flush all caches? This cannot be undone.')) { handleInvalidate('all'); } }} disabled={!!invalidating} > {invalidating === 'all' ? ( <span className="mr-2 inline-flex scale-50"><LoadingSpinner size="sm" /></span> ) : ( <Icon name="trash" className="w-4 h-4 mr-2" /> )} Flush All Caches </Button> </div> </div> </Card> </div> ); } // Helper Components interface StatsCardProps { title: string; value: string; icon: IconName; color: 'green' | 'red' | 'blue' | 'purple' | 'yellow'; subtitle?: string; } function StatsCard({ title, value, icon, color, subtitle }: StatsCardProps) { const colorClasses = { green: 'bg-green-100 text-green-600 dark:bg-green-900/30 dark:text-green-400', red: 'bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400', blue: 'bg-blue-100 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400', purple: 'bg-purple-100 text-purple-600 dark:bg-purple-900/30 dark:text-purple-400', yellow: 'bg-yellow-100 text-yellow-600 dark:bg-yellow-900/30 dark:text-yellow-400', }; return ( <Card className="p-6"> <div className="flex items-center justify-between"> <div> <p className="text-sm text-gray-500 dark:text-gray-400">{title}</p> <p className="text-2xl font-bold text-gray-900 dark:text-white">{value}</p> {subtitle && ( <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">{subtitle}</p> )} </div> <div className={cn('p-3 rounded-full', colorClasses[color])}> <Icon name={icon} className="w-6 h-6" /> </div> </div> </Card> ); } interface InvalidateButtonProps { label: string; target: InvalidateTarget; onClick: () => void; loading: boolean; disabled: boolean; } function InvalidateButton({ label, onClick, loading, disabled }: InvalidateButtonProps) { return ( <Button variant="outline" size="sm" onClick={onClick} disabled={disabled} > {loading ? <span className="mr-1 inline-flex scale-50"><LoadingSpinner size="sm" /></span> : null} {label} </Button> ); } // Utility functions function formatBytes(bytes: number): string { if (bytes === 0) return '0 B'; const k = 1024; const sizes = ['B', 'KB', 'MB', 'GB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`; } function getHitRateQuality(hitRate: number): string { if (hitRate >= 0.9) return 'Excellent'; if (hitRate >= 0.7) return 'Good'; if (hitRate >= 0.5) return 'Fair'; if (hitRate > 0) return 'Poor'; return 'No data'; } export default CacheDashboard; |