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

wsConnectionState.ts

238 lines7.5 KB

1import { useAtomValue } from "@effect/atom-react";
2import { DEFAULT_RECONNECT_BACKOFF, getReconnectDelayMs } from "@t3tools/client-runtime";
3import { Atom } from "effect/unstable/reactivity";
4​
5import { appAtomRegistry } from "./atomRegistry";
6​
7export type WsConnectionUiState = "connected" | "connecting" | "error" | "offline" | "reconnecting";
8export type WsReconnectPhase = "attempting" | "exhausted" | "idle" | "waiting";
9​
10export const WS_RECONNECT_INITIAL_DELAY_MS = DEFAULT_RECONNECT_BACKOFF.initialDelayMs;
11export const WS_RECONNECT_BACKOFF_FACTOR = DEFAULT_RECONNECT_BACKOFF.backoffFactor;
12export const WS_RECONNECT_MAX_DELAY_MS = DEFAULT_RECONNECT_BACKOFF.maxDelayMs;
13export const WS_RECONNECT_MAX_RETRIES = DEFAULT_RECONNECT_BACKOFF.maxRetries!;
14export const WS_RECONNECT_MAX_ATTEMPTS = WS_RECONNECT_MAX_RETRIES + 1;
15​
16export interface WsConnectionStatus {
17 readonly attemptCount: number;
18 readonly closeCode: number | null;
19 readonly closeReason: string | null;
20 readonly connectionLabel: string | null;
21 readonly connectedAt: string | null;
22 readonly disconnectedAt: string | null;
23 readonly hasConnected: boolean;
24 readonly lastError: string | null;
25 readonly lastErrorAt: string | null;
26 readonly nextRetryAt: string | null;
27 readonly online: boolean;
28 readonly phase: "idle" | "connecting" | "connected" | "disconnected";
29 readonly reconnectAttemptCount: number;
30 readonly reconnectMaxAttempts: number;
31 readonly reconnectPhase: WsReconnectPhase;
32 readonly socketUrl: string | null;
34​
35const INITIAL_WS_CONNECTION_STATUS = Object.freeze<WsConnectionStatus>({
36 attemptCount: 0,
37 closeCode: null,
38 closeReason: null,
39 connectionLabel: null,
40 connectedAt: null,
41 disconnectedAt: null,
42 hasConnected: false,
43 lastError: null,
44 lastErrorAt: null,
45 nextRetryAt: null,
46 online: typeof navigator === "undefined" ? true : navigator.onLine !== false,
47 phase: "idle",
48 reconnectAttemptCount: 0,
49 reconnectMaxAttempts: WS_RECONNECT_MAX_ATTEMPTS,
50 reconnectPhase: "idle",
51 socketUrl: null,
52});
53​
54export const wsConnectionStatusAtom = Atom.make(INITIAL_WS_CONNECTION_STATUS).pipe(
55 Atom.keepAlive,
56 Atom.withLabel("ws-connection-status"),
57);
58​
59function isoNow() {
60 return new Date().toISOString();
62​
63function updateWsConnectionStatus(
64 updater: (current: WsConnectionStatus) => WsConnectionStatus,
65): WsConnectionStatus {
66 const nextStatus = updater(getWsConnectionStatus());
67 appAtomRegistry.set(wsConnectionStatusAtom, nextStatus);
68 return nextStatus;
70​
71export interface WsConnectionMetadata {
72 readonly connectionLabel?: string | null;
73 readonly versionMismatchHint?: string | null;
75​
76function normalizeConnectionLabel(label: string | null | undefined): string | null {
77 const normalized = label?.trim();
78 return normalized ? normalized : null;
80​
81export function getWsConnectionStatus(): WsConnectionStatus {
82 return appAtomRegistry.get(wsConnectionStatusAtom);
84​
85export function getWsConnectionUiState(status: WsConnectionStatus): WsConnectionUiState {
86 if (status.phase === "connected") {
87 return "connected";
88 }
89​
90 if (!status.online && (status.disconnectedAt !== null || status.phase === "disconnected")) {
91 return "offline";
92 }
93​
94 if (!status.hasConnected) {
95 return status.phase === "disconnected" ? "error" : "connecting";
96 }
97​
98 return "reconnecting";
100​
101export function recordWsConnectionAttempt(
102 socketUrl: string,
103 metadata?: WsConnectionMetadata,
104): WsConnectionStatus {
105 const connectionLabel = normalizeConnectionLabel(metadata?.connectionLabel);
106 return updateWsConnectionStatus((current) => ({
107 ...current,
108 attemptCount: current.attemptCount + 1,
109 connectionLabel: connectionLabel ?? current.connectionLabel,
110 nextRetryAt: null,
111 phase: "connecting",
112 reconnectAttemptCount: current.phase === "connected" ? 1 : current.reconnectAttemptCount + 1,
113 reconnectPhase: "attempting",
114 socketUrl,
115 }));
117​
118export function recordWsConnectionOpened(metadata?: WsConnectionMetadata): WsConnectionStatus {
119 const connectionLabel = normalizeConnectionLabel(metadata?.connectionLabel);
120 return updateWsConnectionStatus((current) => ({
121 ...current,
122 closeCode: null,
123 closeReason: null,
124 connectionLabel: connectionLabel ?? current.connectionLabel,
125 connectedAt: isoNow(),
126 disconnectedAt: null,
127 hasConnected: true,
128 nextRetryAt: null,
129 phase: "connected",
130 reconnectAttemptCount: 0,
131 reconnectPhase: "idle",
132 }));
134​
135function appendHint(message: string | null | undefined, hint: string | null | undefined) {
136 const normalizedMessage = message?.trim();
137 const normalizedHint = hint?.trim();
138 if (!normalizedMessage) {
139 return normalizedHint ? `Hint: ${normalizedHint}` : null;
140 }
141 return normalizedHint ? `${normalizedMessage} Hint: ${normalizedHint}` : normalizedMessage;
143​
144export function recordWsConnectionErrored(
145 message?: string | null,
146 metadata?: WsConnectionMetadata,
147): WsConnectionStatus {
148 return updateWsConnectionStatus((current) =>
149 applyDisconnectState(current, {
150 lastError:
151 appendHint(message, metadata?.versionMismatchHint) ??
152 appendHint(current.lastError, metadata?.versionMismatchHint),
153 lastErrorAt: isoNow(),
154 }),
155 );
157​
158export function recordWsConnectionClosed(
159 details?: {
160 readonly code?: number;
161 readonly reason?: string;
162 },
163 metadata?: WsConnectionMetadata,
164): WsConnectionStatus {
165 const connectionLabel = normalizeConnectionLabel(metadata?.connectionLabel);
166 return updateWsConnectionStatus((current) =>
167 applyDisconnectState(
168 current,
169 {
170 closeCode: details?.code ?? current.closeCode,
171 closeReason:
172 appendHint(details?.reason, metadata?.versionMismatchHint) ??
173 appendHint(current.closeReason, metadata?.versionMismatchHint),
174 },
175 connectionLabel === null ? undefined : { connectionLabel },
176 ),
177 );
179​
180export function setBrowserOnlineStatus(online: boolean): WsConnectionStatus {
181 return updateWsConnectionStatus((current) => ({
182 ...current,
183 online,
184 }));
186​
187export function resetWsReconnectBackoff(): WsConnectionStatus {
188 return updateWsConnectionStatus((current) => ({
189 ...current,
190 nextRetryAt: null,
191 reconnectAttemptCount: 0,
192 reconnectPhase: "idle",
193 }));
195​
196export function resetWsConnectionStateForTests(): void {
197 appAtomRegistry.set(wsConnectionStatusAtom, INITIAL_WS_CONNECTION_STATUS);
199​
200export function useWsConnectionStatus(): WsConnectionStatus {
201 return useAtomValue(wsConnectionStatusAtom);
203​
204export function getWsReconnectDelayMsForRetry(retryIndex: number): number | null {
205 return getReconnectDelayMs(retryIndex);
207​
208function applyDisconnectState(
209 current: WsConnectionStatus,
210 updates: Partial<
211 Pick<WsConnectionStatus, "closeCode" | "closeReason" | "lastError" | "lastErrorAt">
212 >,
213 metadata?: WsConnectionMetadata,
214): WsConnectionStatus {
215 const disconnectedAt = current.disconnectedAt ?? isoNow();
216 const nextRetryDelayMs =
217 current.nextRetryAt !== null || current.reconnectPhase === "exhausted"
218 ? null
219 : getWsReconnectDelayMsForRetry(Math.max(0, current.reconnectAttemptCount - 1));
220​
221 return {
222 ...current,
223 ...updates,
224 connectionLabel: normalizeConnectionLabel(metadata?.connectionLabel) ?? current.connectionLabel,
225 disconnectedAt,
226 nextRetryAt:
227 nextRetryDelayMs === null
228 ? current.nextRetryAt
229 : new Date(Date.now() + nextRetryDelayMs).toISOString(),
230 phase: "disconnected",
231 reconnectPhase:
232 current.reconnectPhase === "waiting" || current.reconnectPhase === "exhausted"
233 ? current.reconnectPhase
234 : nextRetryDelayMs === null
235 ? "exhausted"
236 : "waiting",
237 };