import { webSocket, WebSocketSubject } from "rxjs/webSocket" import { of, EMPTY, merge, timer } from "rxjs" import { catchError, mergeMap, exhaustMap, tap, ignoreElements, filter, switchMap, retry, take } from "rxjs/operators" import { CONNECTED, CONNECTING, VALKEY, RETRY_CONFIG, retryDelay } from "@common/src/constants.ts" import { action$ } from "../middleware/rxjsMiddleware/rxjsMiddleware" import type { PayloadAction, Store } from "@reduxjs/toolkit" import { connectionBroken } from "@/state/valkey-features/connection/connectionSlice" import { connectFulfilled, connectPending, connectRejected, reconnectAttempt, reconnectExhausted, selectRetriesPaused } from "@/state/wsconnection/wsConnectionSlice" let socket$: WebSocketSubject | null = null const getWebsocketURL = () => { // If it's an Electron deployment if (window.location.protocol === "file:") { const token = window.valkeyAdminRuntime?.wsToken return token ? `ws://localhost:8080?token=${encodeURIComponent(token)}` : "ws://localhost:8080" } const protocol = window.location.protocol === "https:" ? "wss" : "ws" return `${protocol}://${window.location.host}${window.location.pathname}` } const url = import.meta.env.VITE_VALKEY_ADMIN_WS_URL || getWebsocketURL() const connect = (store: Store) => action$.pipe( filter((action) => action.type === connectPending.type), // Exhaust map so only one websocket is created exhaustMap(() => { if (socket$) { return EMPTY } const createSocket = () => { socket$ = webSocket({ url, deserializer: (message) => JSON.parse(message.data), serializer: (message) => JSON.stringify(message), openObserver: { next: () => { console.log("Socket Connection opened") store.dispatch(connectFulfilled()) }, }, closeObserver: { next: (event) => { console.log("Socket Connection closed", event) const state = store.getState() const connections = state[VALKEY.CONNECTION.name]?.connections || {} // Reset both CONNECTED and CONNECTING states on socket close. // CONNECTING entries can get stuck if the socket dies mid-handshake // (e.g., laptop sleep/wake), leaving the UI unable to retry. Object.keys(connections).forEach((connectionId) => { if (connections[connectionId].status === CONNECTED || connections[connectionId].status === CONNECTING) { console.log(`Dispatching connectionBroken for ${connectionId}`) store.dispatch(connectionBroken({ connectionId })) } }) socket$ = null }, }, }) return socket$ } return of(null).pipe( mergeMap(() => { const socket = createSocket() return socket.pipe(ignoreElements()) }), retry({ count: RETRY_CONFIG.MAX_RETRIES, delay: (error, retryCount) => { console.error(`WebSocket error (attempt ${retryCount}):`, error) const delay = retryDelay(retryCount - 1) store.dispatch(reconnectAttempt({ attempt: retryCount, maxRetries: RETRY_CONFIG.MAX_RETRIES, nextRetryDelay: delay, })) return action$.pipe( filter((action) => !selectRetriesPaused()(store.getState()) || action.type === "websocket/resumeRetries", ), take(1), switchMap(() => timer(delay)), ) }, resetOnSuccess: true, }), catchError((err) => { console.error("WebSocket connection error:", err) store.dispatch(reconnectExhausted()) store.dispatch(connectRejected(err)) return EMPTY }), ) }), ) const emitActions = (store: Store) => action$.pipe( filter((action) => action.type === connectFulfilled.type), switchMap(() => { if (!socket$) { console.warn("Tried to subscribe to socket messages, but socket is null") return EMPTY } return socket$.pipe( tap((message) => { console.log("[WebSocket] Incoming message:", message) store.dispatch(message) }), catchError((err) => { console.error("WebSocket error in message stream:", err) const state = store.getState() const connections = state[VALKEY.CONNECTION.name]?.connections || {} Object.keys(connections).forEach((connectionId) => { if (connections[connectionId].status === CONNECTED) { store.dispatch(connectionBroken({ connectionId })) } }) // trigger reconnection store.dispatch(connectPending()) return EMPTY }), ignoreElements(), ) }), ) export function getSocket(): WebSocketSubject { if (!socket$) { throw new Error("WebSocket is not connected") } return socket$ } export const wsConnectionEpic = (store: Store) => merge( connect(store), emitActions(store), )