All files / frontend/src/store dashboardStore.ts

0% Statements 0/208
0% Branches 0/1
0% Functions 0/1
0% Lines 0/208

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
import { create } from 'zustand';
import type {
    WebSDRConfig,
    WebSDRHealthStatus,
    ModelInfo,
    ServiceHealth
} from '@/services/api/types';
import {
    webSDRService,
    inferenceService,
    systemService,
    analyticsService
} from '@/services/api';
import { WebSocketManager, ConnectionState, createWebSocketManager } from '@/lib/websocket';
 
interface DashboardMetrics {
    activeWebSDRs: number;
    totalWebSDRs: number;
    signalDetections: number;
    systemUptime: number;
    averageAccuracy: number;
}
 
interface DashboardData {
    websdrs: WebSDRConfig[];
    websdrsHealth: Record<number, WebSDRHealthStatus>;
    modelInfo: ModelInfo | null;
    servicesHealth: Record<string, ServiceHealth>;
}
 
interface DashboardStore {
    metrics: DashboardMetrics;
    data: DashboardData;
    isLoading: boolean;
    error: string | null;
    lastUpdate: Date | null;
    retryCount: number;
    retryDelay: number;
    // WebSocket state
    wsManager: WebSocketManager | null;
    wsConnectionState: ConnectionState;
    wsEnabled: boolean;
 
    setMetrics: (metrics: DashboardMetrics) => void;
    setLoading: (loading: boolean) => void;
    setError: (error: string | null) => void;
    resetRetry: () => void;
    incrementRetry: () => void;
 
    fetchDashboardData: () => Promise<void>;
    fetchWebSDRs: () => Promise<void>;
    fetchModelInfo: () => Promise<void>;
    fetchServicesHealth: () => Promise<void>;
 
    refreshAll: () => Promise<void>;
 
    // WebSocket methods
    connectWebSocket: () => Promise<void>;
    disconnectWebSocket: () => void;
    setWebSocketState: (state: ConnectionState) => void;
}
 
export const useDashboardStore = create<DashboardStore>((set, get) => ({
    metrics: {
        activeWebSDRs: 0,
        totalWebSDRs: 0,
        signalDetections: 0,
        systemUptime: 0,
        averageAccuracy: 0,
    },
    data: {
        websdrs: [],
        websdrsHealth: {},
        modelInfo: null,
        servicesHealth: {},
    },
    isLoading: false,
    error: null,
    lastUpdate: null,
    retryCount: 0,
    retryDelay: 1000,
    // WebSocket state
    wsManager: null,
    wsConnectionState: ConnectionState.DISCONNECTED,
    wsEnabled: true, // Enable WebSocket by default, fallback to polling if unavailable
 
    setMetrics: (metrics) => set({ metrics }),
    setLoading: (loading) => set({ isLoading: loading }),
    setError: (error) => set({ error }),
 
    resetRetry: () => set({ retryCount: 0, retryDelay: 1000 }),
 
    incrementRetry: () => set((state) => ({
        retryCount: state.retryCount + 1,
        retryDelay: Math.min(state.retryDelay * 2, 30000), // Max 30 seconds
    })),
 
    fetchWebSDRs: async () => {
        try {
            // Load WebSDRs FAST - don't wait for health check
            const websdrs = await webSDRService.getWebSDRs();
 
            set((state) => ({
                data: {
                    ...state.data,
                    websdrs,
                },
                metrics: {
                    ...state.metrics,
                    totalWebSDRs: websdrs.length,
                    activeWebSDRs: websdrs.filter(w => w.is_active).length,
                },
            }));
 
            // Load health check in background (doesn't block UI)
            webSDRService.checkWebSDRHealth()
                .then(health => {
                    set((state) => ({
                        data: {
                            ...state.data,
                            websdrsHealth: health,
                        },
                    }));
                })
                .catch(error => {
                    console.warn('Health check failed (non-critical):', error);
                });
        } catch (error) {
            console.error('Failed to fetch WebSDRs:', error);
            throw error;
        }
    },
 
    fetchModelInfo: async () => {
        try {
            const modelInfo = await inferenceService.getModelInfo();
 
            set((state) => ({
                data: {
                    ...state.data,
                    modelInfo,
                },
                metrics: {
                    ...state.metrics,
                    averageAccuracy: modelInfo.accuracy ? modelInfo.accuracy * 100 : 0,
                    systemUptime: modelInfo.uptime_seconds,
                },
            }));
        } catch (error) {
            console.error('Failed to fetch model info:', error);
            // Model service might not be available, this is not critical
        }
    },
 
    fetchServicesHealth: async () => {
        try {
            const servicesHealth = await systemService.checkAllServicesHealth();
 
            set((state) => ({
                data: {
                    ...state.data,
                    servicesHealth,
                },
            }));
        } catch (error) {
            console.error('Failed to fetch services health:', error);
            throw error;
        }
    },
 
    fetchDashboardData: async () => {
        set({ isLoading: true, error: null });
 
        try {
            // Fetch all data in parallel
            const [metricsData] = await Promise.allSettled([
                analyticsService.getDashboardMetrics(),
            ]);
 
            // Update metrics from analytics endpoint
            if (metricsData.status === 'fulfilled') {
                set((state) => ({
                    metrics: {
                        ...state.metrics,
                        signalDetections: metricsData.value.signalDetections,
                        systemUptime: metricsData.value.systemUptime,
                        averageAccuracy: metricsData.value.modelAccuracy * 100,
                    },
                }));
            }
 
            // Fetch other data sources
            await Promise.allSettled([
                get().fetchWebSDRs(),
                get().fetchModelInfo(),
                get().fetchServicesHealth(),
            ]);
 
            set({
                lastUpdate: new Date(),
                error: null,
            });
 
            // Reset retry count on success
            get().resetRetry();
        } catch (error) {
            const errorMessage = error instanceof Error ? error.message : 'Failed to fetch dashboard data';
            set({ error: errorMessage });
            console.error('Dashboard data fetch error:', error);
 
            // Increment retry count for exponential backoff
            get().incrementRetry();
        } finally {
            set({ isLoading: false });
        }
    },
 
    refreshAll: async () => {
        await get().fetchDashboardData();
    },
 
    // WebSocket methods
    setWebSocketState: (state: ConnectionState) => {
        set({ wsConnectionState: state });
    },
 
    connectWebSocket: async () => {
        const { wsManager, wsEnabled } = get();
 
        if (!wsEnabled) {
            console.log('[Dashboard] WebSocket disabled, using polling');
            return;
        }
 
        if (wsManager) {
            console.log('[Dashboard] WebSocket already initialized');
            return;
        }
 
        try {
            // Determine WebSocket URL based on current location
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const host = window.location.hostname;
            const port = import.meta.env.VITE_API_PORT || '8000';
            const wsUrl = `${protocol}//${host}:${port}/ws/updates`;
 
            console.log('[Dashboard] Connecting to WebSocket:', wsUrl);
 
            const manager = createWebSocketManager(wsUrl);
 
            // Subscribe to connection state changes
            manager.onStateChange((state) => {
                get().setWebSocketState(state);
            });
 
            // Subscribe to real-time events
            manager.subscribe('services:health', (data) => {
                console.log('[Dashboard] Received services health update:', data);
                set((state) => ({
                    data: {
                        ...state.data,
                        servicesHealth: data,
                    },
                    lastUpdate: new Date(),
                }));
            });
 
            manager.subscribe('websdrs:status', (data) => {
                console.log('[Dashboard] Received WebSDR status update:', data);
                set((state) => ({
                    data: {
                        ...state.data,
                        websdrsHealth: data,
                    },
                    lastUpdate: new Date(),
                }));
            });
 
            manager.subscribe('signals:detected', (data) => {
                console.log('[Dashboard] Received signal detection:', data);
                set((state) => ({
                    metrics: {
                        ...state.metrics,
                        signalDetections: (state.metrics.signalDetections || 0) + 1,
                    },
                    lastUpdate: new Date(),
                }));
            });
 
            manager.subscribe('localizations:updated', (data) => {
                console.log('[Dashboard] Received localization update:', data);
                // Handle localization updates (could update a separate store)
                set({ lastUpdate: new Date() });
            });
 
            // Store manager and attempt connection
            set({ wsManager: manager });
 
            await manager.connect();
            console.log('[Dashboard] WebSocket connected successfully');
        } catch (error) {
            console.error('[Dashboard] WebSocket connection failed:', error);
            // Disable WebSocket and fallback to polling
            set({ wsEnabled: false, wsManager: null });
        }
    },
 
    disconnectWebSocket: () => {
        const { wsManager } = get();
        if (wsManager) {
            console.log('[Dashboard] Disconnecting WebSocket');
            wsManager.disconnect();
            set({ wsManager: null, wsConnectionState: ConnectionState.DISCONNECTED });
        }
    },
}));