Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { Atom } from "effect/unstable/reactivity";
3
4import { appAtomRegistry } from "./atomRegistry";
5
6export type WsConnectionUiState = "connected" | "connecting" | "error" | "offline" | "reconnecting";
7export type WsReconnectPhase = "attempting" | "exhausted" | "idle" | "waiting";
8
9export const WS_RECONNECT_INITIAL_DELAY_MS = 1_000;
10export const WS_RECONNECT_BACKOFF_FACTOR = 2;
11export const WS_RECONNECT_MAX_DELAY_MS = 64_000;
12export const WS_RECONNECT_MAX_RETRIES = 7;
13export const WS_RECONNECT_MAX_ATTEMPTS = WS_RECONNECT_MAX_RETRIES + 1;
14
15export interface WsConnectionStatus {
16 readonly attemptCount: number;
17 readonly closeCode: number | null;
18 readonly closeReason: string | null;
19 readonly connectedAt: string | null;
20 readonly disconnectedAt: string | null;
21 readonly hasConnected: boolean;
22 readonly lastError: string | null;
23 readonly lastErrorAt: string | null;
24 readonly nextRetryAt: string | null;
25 readonly online: boolean;
26 readonly phase: "idle" | "connecting" | "connected" | "disconnected";
27 readonly reconnectAttemptCount: number;
28 readonly reconnectMaxAttempts: number;
29 readonly reconnectPhase: WsReconnectPhase;
30 readonly socketUrl: string | null;
31}
32
33const INITIAL_WS_CONNECTION_STATUS = Object.freeze<WsConnectionStatus>({
34 attemptCount: 0,
35 closeCode: null,
36 closeReason: null,
37 connectedAt: null,
38 disconnectedAt: null,
39 hasConnected: false,
40 lastError: null,
41 lastErrorAt: null,
42 nextRetryAt: null,
43 online: typeof navigator === "undefined" ? true : navigator.onLine !== false,
44 phase: "idle",
45 reconnectAttemptCount: 0,
46 reconnectMaxAttempts: WS_RECONNECT_MAX_ATTEMPTS,
47 reconnectPhase: "idle",
48 socketUrl: null,
49});
50
51export const wsConnectionStatusAtom = Atom.make(INITIAL_WS_CONNECTION_STATUS).pipe(
52 Atom.keepAlive,
53 Atom.withLabel("ws-connection-status"),
54);
55
56function isoNow() {
57 return new Date().toISOString();
58}
59
60function updateWsConnectionStatus(
61 updater: (current: WsConnectionStatus) => WsConnectionStatus,
62): WsConnectionStatus {
63 const nextStatus = updater(getWsConnectionStatus());
64 appAtomRegistry.set(wsConnectionStatusAtom, nextStatus);
65 return nextStatus;
66}
67
68export function getWsConnectionStatus(): WsConnectionStatus {
69 return appAtomRegistry.get(wsConnectionStatusAtom);
70}
71
72export function getWsConnectionUiState(status: WsConnectionStatus): WsConnectionUiState {
73 if (status.phase === "connected") {
74 return "connected";
75 }
76
77 if (!status.online && (status.disconnectedAt !== null || status.phase === "disconnected")) {
78 return "offline";
79 }
80
81 if (!status.hasConnected) {
82 return status.phase === "disconnected" ? "error" : "connecting";
83 }
84
85 return "reconnecting";
86}
87
88export function recordWsConnectionAttempt(socketUrl: string): WsConnectionStatus {
89 return updateWsConnectionStatus((current) => ({
90 ...current,
91 attemptCount: current.attemptCount + 1,
92 nextRetryAt: null,
93 phase: "connecting",
94 reconnectAttemptCount: current.phase === "connected" ? 1 : current.reconnectAttemptCount + 1,
95 reconnectPhase: "attempting",
96 socketUrl,
97 }));
98}
99
100export function recordWsConnectionOpened(): WsConnectionStatus {
101 return updateWsConnectionStatus((current) => ({
102 ...current,
103 closeCode: null,
104 closeReason: null,
105 connectedAt: isoNow(),
106 disconnectedAt: null,
107 hasConnected: true,
108 nextRetryAt: null,
109 phase: "connected",
110 reconnectAttemptCount: 0,
111 reconnectPhase: "idle",
112 }));
113}
114
115export function recordWsConnectionErrored(message?: string | null): WsConnectionStatus {
116 return updateWsConnectionStatus((current) =>
117 applyDisconnectState(current, {
118 lastError: message?.trim() ? message : current.lastError,
119 lastErrorAt: isoNow(),
120 }),
121 );
122}
123
124export function recordWsConnectionClosed(details?: {
125 readonly code?: number;
126 readonly reason?: string;
127}): WsConnectionStatus {
128 return updateWsConnectionStatus((current) =>
129 applyDisconnectState(current, {
130 closeCode: details?.code ?? current.closeCode,
131 closeReason: details?.reason?.trim() ? details.reason : current.closeReason,
132 }),
133 );
134}
135
136export function setBrowserOnlineStatus(online: boolean): WsConnectionStatus {
137 return updateWsConnectionStatus((current) => ({
138 ...current,
139 online,
140 }));
141}
142
143export function resetWsReconnectBackoff(): WsConnectionStatus {
144 return updateWsConnectionStatus((current) => ({
145 ...current,
146 nextRetryAt: null,
147 reconnectAttemptCount: 0,
148 reconnectPhase: "idle",
149 }));
150}
151
152export function resetWsConnectionStateForTests(): void {
153 appAtomRegistry.set(wsConnectionStatusAtom, INITIAL_WS_CONNECTION_STATUS);
154}
155
156export function useWsConnectionStatus(): WsConnectionStatus {
157 return useAtomValue(wsConnectionStatusAtom);
158}
159
160export function getWsReconnectDelayMsForRetry(retryIndex: number): number | null {
161 if (!Number.isInteger(retryIndex) || retryIndex < 0 || retryIndex >= WS_RECONNECT_MAX_RETRIES) {
162 return null;
163 }
164
165 return Math.min(
166 Math.round(WS_RECONNECT_INITIAL_DELAY_MS * WS_RECONNECT_BACKOFF_FACTOR ** retryIndex),
167 WS_RECONNECT_MAX_DELAY_MS,
168 );
169}
170
171function applyDisconnectState(
172 current: WsConnectionStatus,
173 updates: Partial<
174 Pick<WsConnectionStatus, "closeCode" | "closeReason" | "lastError" | "lastErrorAt">
175 >,
176): WsConnectionStatus {
177 const disconnectedAt = current.disconnectedAt ?? isoNow();
178 const nextRetryDelayMs =
179 current.nextRetryAt !== null || current.reconnectPhase === "exhausted"
180 ? null
181 : getWsReconnectDelayMsForRetry(Math.max(0, current.reconnectAttemptCount - 1));
182
183 return {
184 ...current,
185 ...updates,
186 disconnectedAt,
187 nextRetryAt:
188 nextRetryDelayMs === null
189 ? current.nextRetryAt
190 : new Date(Date.now() + nextRetryDelayMs).toISOString(),
191 phase: "disconnected",
192 reconnectPhase:
193 current.reconnectPhase === "waiting" || current.reconnectPhase === "exhausted"
194 ? current.reconnectPhase
195 : nextRetryDelayMs === null
196 ? "exhausted"
197 : "waiting",
198 };
199}