Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

wsConnectionState.ts

219 lines6.4 KB

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;
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();
59​
60function updateWsConnectionStatus(
61 updater: (current: WsConnectionStatus) => WsConnectionStatus,
62): WsConnectionStatus {
63 const nextStatus = updater(getWsConnectionStatus());
64 appAtomRegistry.set(wsConnectionStatusAtom, nextStatus);
65 return nextStatus;
67​
68export function getWsConnectionStatus(): WsConnectionStatus {
69 return appAtomRegistry.get(wsConnectionStatusAtom);
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";
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 }));
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 }));
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 );
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 );
135​
136export function setBrowserOnlineStatus(online: boolean): WsConnectionStatus {
137 return updateWsConnectionStatus((current) => ({
138 ...current,
139 online,
140 }));
142​
143export function resetWsReconnectBackoff(): WsConnectionStatus {
144 return updateWsConnectionStatus((current) => ({
145 ...current,
146 nextRetryAt: null,
147 reconnectAttemptCount: 0,
148 reconnectPhase: "idle",
149 }));
151​
152export function exhaustWsReconnectIfStillWaiting(expectedNextRetryAt: string): WsConnectionStatus {
153 return updateWsConnectionStatus((current) => {
154 if (
155 current.reconnectPhase !== "waiting" ||
156 current.nextRetryAt !== expectedNextRetryAt ||
157 !current.online ||
158 !current.hasConnected
159 ) {
160 return current;
161 }
162​
163 return {
164 ...current,
165 nextRetryAt: null,
166 reconnectAttemptCount: current.reconnectMaxAttempts,
167 reconnectPhase: "exhausted",
168 };
169 });
171​
172export function resetWsConnectionStateForTests(): void {
173 appAtomRegistry.set(wsConnectionStatusAtom, INITIAL_WS_CONNECTION_STATUS);
175​
176export function useWsConnectionStatus(): WsConnectionStatus {
177 return useAtomValue(wsConnectionStatusAtom);
179​
180export function getWsReconnectDelayMsForRetry(retryIndex: number): number | null {
181 if (!Number.isInteger(retryIndex) || retryIndex < 0 || retryIndex >= WS_RECONNECT_MAX_RETRIES) {
182 return null;
183 }
184​
185 return Math.min(
186 Math.round(WS_RECONNECT_INITIAL_DELAY_MS * WS_RECONNECT_BACKOFF_FACTOR ** retryIndex),
187 WS_RECONNECT_MAX_DELAY_MS,
188 );
190​
191function applyDisconnectState(
192 current: WsConnectionStatus,
193 updates: Partial<
194 Pick<WsConnectionStatus, "closeCode" | "closeReason" | "lastError" | "lastErrorAt">
195 >,
196): WsConnectionStatus {
197 const disconnectedAt = current.disconnectedAt ?? isoNow();
198 const nextRetryDelayMs =
199 current.nextRetryAt !== null || current.reconnectPhase === "exhausted"
200 ? null
201 : getWsReconnectDelayMsForRetry(Math.max(0, current.reconnectAttemptCount - 1));
202​
203 return {
204 ...current,
205 ...updates,
206 disconnectedAt,
207 nextRetryAt:
208 nextRetryDelayMs === null
209 ? current.nextRetryAt
210 : new Date(Date.now() + nextRetryDelayMs).toISOString(),
211 phase: "disconnected",
212 reconnectPhase:
213 current.reconnectPhase === "waiting" || current.reconnectPhase === "exhausted"
214 ? current.reconnectPhase
215 : nextRetryDelayMs === null
216 ? "exhausted"
217 : "waiting",
218 };