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

wsConnectionState.ts

244 lines7.5 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 connectionLabel: string | null;
20 readonly connectedAt: string | null;
21 readonly disconnectedAt: string | null;
22 readonly hasConnected: boolean;
23 readonly lastError: string | null;
24 readonly lastErrorAt: string | null;
25 readonly nextRetryAt: string | null;
26 readonly online: boolean;
27 readonly phase: "idle" | "connecting" | "connected" | "disconnected";
28 readonly reconnectAttemptCount: number;
29 readonly reconnectMaxAttempts: number;
30 readonly reconnectPhase: WsReconnectPhase;
31 readonly socketUrl: string | null;
33​
34const INITIAL_WS_CONNECTION_STATUS = Object.freeze<WsConnectionStatus>({
35 attemptCount: 0,
36 closeCode: null,
37 closeReason: null,
38 connectionLabel: null,
39 connectedAt: null,
40 disconnectedAt: null,
41 hasConnected: false,
42 lastError: null,
43 lastErrorAt: null,
44 nextRetryAt: null,
45 online: typeof navigator === "undefined" ? true : navigator.onLine !== false,
46 phase: "idle",
47 reconnectAttemptCount: 0,
48 reconnectMaxAttempts: WS_RECONNECT_MAX_ATTEMPTS,
49 reconnectPhase: "idle",
50 socketUrl: null,
51});
52​
53export const wsConnectionStatusAtom = Atom.make(INITIAL_WS_CONNECTION_STATUS).pipe(
54 Atom.keepAlive,
55 Atom.withLabel("ws-connection-status"),
56);
57​
58function isoNow() {
59 return new Date().toISOString();
61​
62function updateWsConnectionStatus(
63 updater: (current: WsConnectionStatus) => WsConnectionStatus,
64): WsConnectionStatus {
65 const nextStatus = updater(getWsConnectionStatus());
66 appAtomRegistry.set(wsConnectionStatusAtom, nextStatus);
67 return nextStatus;
69​
70export interface WsConnectionMetadata {
71 readonly connectionLabel?: string | null;
72 readonly versionMismatchHint?: string | null;
74​
75function normalizeConnectionLabel(label: string | null | undefined): string | null {
76 const normalized = label?.trim();
77 return normalized ? normalized : null;
79​
80export function getWsConnectionStatus(): WsConnectionStatus {
81 return appAtomRegistry.get(wsConnectionStatusAtom);
83​
84export function getWsConnectionUiState(status: WsConnectionStatus): WsConnectionUiState {
85 if (status.phase === "connected") {
86 return "connected";
87 }
88​
89 if (!status.online && (status.disconnectedAt !== null || status.phase === "disconnected")) {
90 return "offline";
91 }
92​
93 if (!status.hasConnected) {
94 return status.phase === "disconnected" ? "error" : "connecting";
95 }
96​
97 return "reconnecting";
99​
100export function recordWsConnectionAttempt(
101 socketUrl: string,
102 metadata?: WsConnectionMetadata,
103): WsConnectionStatus {
104 const connectionLabel = normalizeConnectionLabel(metadata?.connectionLabel);
105 return updateWsConnectionStatus((current) => ({
106 ...current,
107 attemptCount: current.attemptCount + 1,
108 connectionLabel: connectionLabel ?? current.connectionLabel,
109 nextRetryAt: null,
110 phase: "connecting",
111 reconnectAttemptCount: current.phase === "connected" ? 1 : current.reconnectAttemptCount + 1,
112 reconnectPhase: "attempting",
113 socketUrl,
114 }));
116​
117export function recordWsConnectionOpened(metadata?: WsConnectionMetadata): WsConnectionStatus {
118 const connectionLabel = normalizeConnectionLabel(metadata?.connectionLabel);
119 return updateWsConnectionStatus((current) => ({
120 ...current,
121 closeCode: null,
122 closeReason: null,
123 connectionLabel: connectionLabel ?? current.connectionLabel,
124 connectedAt: isoNow(),
125 disconnectedAt: null,
126 hasConnected: true,
127 nextRetryAt: null,
128 phase: "connected",
129 reconnectAttemptCount: 0,
130 reconnectPhase: "idle",
131 }));
133​
134function appendHint(message: string | null | undefined, hint: string | null | undefined) {
135 const normalizedMessage = message?.trim();
136 const normalizedHint = hint?.trim();
137 if (!normalizedMessage) {
138 return normalizedHint ? `Hint: ${normalizedHint}` : null;
139 }
140 return normalizedHint ? `${normalizedMessage} Hint: ${normalizedHint}` : normalizedMessage;
142​
143export function recordWsConnectionErrored(
144 message?: string | null,
145 metadata?: WsConnectionMetadata,
146): WsConnectionStatus {
147 return updateWsConnectionStatus((current) =>
148 applyDisconnectState(current, {
149 lastError:
150 appendHint(message, metadata?.versionMismatchHint) ??
151 appendHint(current.lastError, metadata?.versionMismatchHint),
152 lastErrorAt: isoNow(),
153 }),
154 );
156​
157export function recordWsConnectionClosed(
158 details?: {
159 readonly code?: number;
160 readonly reason?: string;
161 },
162 metadata?: WsConnectionMetadata,
163): WsConnectionStatus {
164 const connectionLabel = normalizeConnectionLabel(metadata?.connectionLabel);
165 return updateWsConnectionStatus((current) =>
166 applyDisconnectState(
167 current,
168 {
169 closeCode: details?.code ?? current.closeCode,
170 closeReason:
171 appendHint(details?.reason, metadata?.versionMismatchHint) ??
172 appendHint(current.closeReason, metadata?.versionMismatchHint),
173 },
174 connectionLabel === null ? undefined : { connectionLabel },
175 ),
176 );
178​
179export function setBrowserOnlineStatus(online: boolean): WsConnectionStatus {
180 return updateWsConnectionStatus((current) => ({
181 ...current,
182 online,
183 }));
185​
186export function resetWsReconnectBackoff(): WsConnectionStatus {
187 return updateWsConnectionStatus((current) => ({
188 ...current,
189 nextRetryAt: null,
190 reconnectAttemptCount: 0,
191 reconnectPhase: "idle",
192 }));
194​
195export function resetWsConnectionStateForTests(): void {
196 appAtomRegistry.set(wsConnectionStatusAtom, INITIAL_WS_CONNECTION_STATUS);
198​
199export function useWsConnectionStatus(): WsConnectionStatus {
200 return useAtomValue(wsConnectionStatusAtom);
202​
203export function getWsReconnectDelayMsForRetry(retryIndex: number): number | null {
204 if (!Number.isInteger(retryIndex) || retryIndex < 0 || retryIndex >= WS_RECONNECT_MAX_RETRIES) {
205 return null;
206 }
207​
208 return Math.min(
209 Math.round(WS_RECONNECT_INITIAL_DELAY_MS * WS_RECONNECT_BACKOFF_FACTOR ** retryIndex),
210 WS_RECONNECT_MAX_DELAY_MS,
211 );
213​
214function applyDisconnectState(
215 current: WsConnectionStatus,
216 updates: Partial<
217 Pick<WsConnectionStatus, "closeCode" | "closeReason" | "lastError" | "lastErrorAt">
218 >,
219 metadata?: WsConnectionMetadata,
220): WsConnectionStatus {
221 const disconnectedAt = current.disconnectedAt ?? isoNow();
222 const nextRetryDelayMs =
223 current.nextRetryAt !== null || current.reconnectPhase === "exhausted"
224 ? null
225 : getWsReconnectDelayMsForRetry(Math.max(0, current.reconnectAttemptCount - 1));
226​
227 return {
228 ...current,
229 ...updates,
230 connectionLabel: normalizeConnectionLabel(metadata?.connectionLabel) ?? current.connectionLabel,
231 disconnectedAt,
232 nextRetryAt:
233 nextRetryDelayMs === null
234 ? current.nextRetryAt
235 : new Date(Date.now() + nextRetryDelayMs).toISOString(),
236 phase: "disconnected",
237 reconnectPhase:
238 current.reconnectPhase === "waiting" || current.reconnectPhase === "exhausted"
239 ? current.reconnectPhase
240 : nextRetryDelayMs === null
241 ? "exhausted"
242 : "waiting",
243 };