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 | 'use client'; import { useState, useEffect, useCallback, useRef } from 'react'; import type { TimeRange } from '@/lib/monitoring/percentiles'; import type { TimeSeriesDataPoint } from '@/components/features/admin/monitoring/charts/ResponseTimeChart'; import type { VolumeDataPoint } from '@/components/features/admin/monitoring/charts/RequestVolumeChart'; import type { EndpointDistribution } from '@/components/features/admin/monitoring/charts/EndpointDistributionChart'; import type { StatusCodeData } from '@/components/features/admin/monitoring/charts/StatusCodeChart'; /** * Performance data structure returned by the API */ export interface PerformanceData { summary: { avgResponseTime: number; totalRequests: number; successRate: number; p95ResponseTime: number; p99ResponseTime: number; }; timeSeries: TimeSeriesDataPoint[]; volume: VolumeDataPoint[]; endpoints: EndpointDistribution[]; statusCodes: StatusCodeData[]; slowRequests: Array<{ id: string; name: string; duration: number; timestamp: Date; }>; } /** * Options for the performance polling hook */ export interface UsePerformancePollingOptions { /** Polling interval in milliseconds. Set to null to disable polling. */ interval?: number | null; /** Time range for data fetching */ timeRange?: TimeRange; /** Whether polling is enabled */ enabled?: boolean; /** Callback when data is fetched */ onData?: (data: PerformanceData) => void; /** Callback when an error occurs */ onError?: (error: Error) => void; } /** * Return type for the performance polling hook */ export interface UsePerformancePollingResult { /** Current performance data */ data: PerformanceData | null; /** Loading state for initial fetch */ isLoading: boolean; /** Whether currently refetching */ isRefetching: boolean; /** Error state */ error: Error | null; /** Last updated timestamp */ lastUpdated: Date | null; /** Manually trigger a refetch */ refetch: () => Promise<void>; } const DEFAULT_INTERVAL = 30000; // 30 seconds /** * Hook for polling performance data with auto-refresh * * @example * ```typescript * const { data, isLoading, refetch } = usePerformancePolling({ * interval: 30000, * timeRange: '24h', * enabled: autoRefresh, * }); * ``` */ export function usePerformancePolling( options: UsePerformancePollingOptions = {} ): UsePerformancePollingResult { const { interval = DEFAULT_INTERVAL, timeRange = '24h', enabled = true, onData, onError, } = options; const [data, setData] = useState<PerformanceData | null>(null); const [isLoading, setIsLoading] = useState(true); const [isRefetching, setIsRefetching] = useState(false); const [error, setError] = useState<Error | null>(null); const [lastUpdated, setLastUpdated] = useState<Date | null>(null); // Track if component is mounted const isMountedRef = useRef(true); const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null); // Fetch performance data const fetchData = useCallback(async (isRefetch = false) => { if (isRefetch) { setIsRefetching(true); } else { setIsLoading(true); } try { const response = await fetch( `/api/admin/monitoring/performance?timeRange=${timeRange}`, { credentials: 'include', } ); if (!response.ok) { throw new Error(`Failed to fetch performance data: ${response.statusText}`); } const result = await response.json(); if (isMountedRef.current) { setData(result.data); setError(null); setLastUpdated(new Date()); onData?.(result.data); } } catch (err) { const error = err instanceof Error ? err : new Error('Unknown error'); if (isMountedRef.current) { setError(error); onError?.(error); } } finally { if (isMountedRef.current) { setIsLoading(false); setIsRefetching(false); } } }, [timeRange, onData, onError]); // Manual refetch function const refetch = useCallback(async () => { await fetchData(true); }, [fetchData]); // Initial fetch and polling setup useEffect(() => { isMountedRef.current = true; // Clear any existing interval if (intervalRef.current) { clearInterval(intervalRef.current); intervalRef.current = null; } if (enabled) { // Initial fetch fetchData(false); // Set up polling if interval is specified if (interval !== null && interval > 0) { intervalRef.current = setInterval(() => { fetchData(true); }, interval); } } return () => { isMountedRef.current = false; if (intervalRef.current) { clearInterval(intervalRef.current); intervalRef.current = null; } }; }, [enabled, interval, fetchData]); // Refetch when timeRange changes useEffect(() => { if (enabled && data !== null) { fetchData(true); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [timeRange]); return { data, isLoading, isRefetching, error, lastUpdated, refetch, }; } /** * Format relative time for "last updated" display */ export function formatLastUpdated(date: Date | null): string { if (!date) return 'Never'; const now = new Date(); const diff = Math.floor((now.getTime() - date.getTime()) / 1000); if (diff < 5) return 'Just now'; if (diff < 60) return `${diff}s ago`; if (diff < 3600) return `${Math.floor(diff / 60)}m ago`; return date.toLocaleTimeString(); } |