Matthias Nott
2026-03-07 8cdf33e27c633ac30e8851c4617f6063c141660d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import { AppState, AppStateStatus } from "react-native";
import { WsOutgoing } from "../types";
type WebSocketMessage = Record<string, unknown>;
type MessageCallback = (data: WebSocketMessage) => void;
type StatusCallback = () => void;
type ErrorCallback = (error: Event) => void;
interface WebSocketClientOptions {
  onMessage?: MessageCallback;
  onOpen?: StatusCallback;
  onClose?: StatusCallback;
  onError?: ErrorCallback;
}
const INITIAL_RECONNECT_DELAY = 1000;
const MAX_RECONNECT_DELAY = 30000;
const RECONNECT_MULTIPLIER = 2;
const LOCAL_TIMEOUT = 2500;
const HEARTBEAT_INTERVAL = 20000; // 20s ping to detect zombie sockets
export class WebSocketClient {
  private ws: WebSocket | null = null;
  private urls: string[] = [];
  private urlIndex: number = 0;
  private reconnectDelay: number = INITIAL_RECONNECT_DELAY;
  private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
  private localTimer: ReturnType<typeof setTimeout> | null = null;
  private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
  private pongReceived: boolean = true;
  private shouldReconnect: boolean = false;
  private connected: boolean = false;
  private callbacks: WebSocketClientOptions = {};
  constructor() {
    // When app comes back to foreground, check if socket is still alive
    AppState.addEventListener("change", (state: AppStateStatus) => {
      if (state === "active" && this.shouldReconnect) {
        if (!this.connected || !this.ws || this.ws.readyState !== WebSocket.OPEN) {
          // Socket is dead — force immediate reconnect
          this.reconnectDelay = INITIAL_RECONNECT_DELAY;
          this.urlIndex = 0;
          this.tryUrl();
        } else {
          // Socket looks open but might be zombie — send a ping to verify
          this.sendPing();
        }
      }
    });
  }
  setCallbacks(callbacks: WebSocketClientOptions) {
    this.callbacks = callbacks;
  }
  connect(urls: string[]) {
    this.urls = urls.filter(Boolean);
    if (this.urls.length === 0) return;
    this.shouldReconnect = true;
    this.reconnectDelay = INITIAL_RECONNECT_DELAY;
    this.urlIndex = 0;
    this.connected = false;
    this.tryUrl();
  }
  private cleanup() {
    if (this.localTimer) { clearTimeout(this.localTimer); this.localTimer = null; }
    if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; }
    this.stopHeartbeat();
    if (this.ws) {
      const old = this.ws;
      this.ws = null;
      old.onopen = null;
      old.onclose = null;
      old.onerror = null;
      old.onmessage = null;
      try { old.close(); } catch { /* ignore */ }
    }
  }
  private startHeartbeat() {
    this.stopHeartbeat();
    this.pongReceived = true;
    this.heartbeatTimer = setInterval(() => {
      if (!this.pongReceived) {
        // No pong since last ping — socket is zombie, force reconnect
        this.connected = false;
        this.callbacks.onClose?.();
        this.reconnectDelay = INITIAL_RECONNECT_DELAY;
        this.urlIndex = 0;
        this.tryUrl();
        return;
      }
      this.sendPing();
    }, HEARTBEAT_INTERVAL);
  }
  private stopHeartbeat() {
    if (this.heartbeatTimer) { clearInterval(this.heartbeatTimer); this.heartbeatTimer = null; }
  }
  private sendPing() {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.pongReceived = false;
      try {
        this.ws.send(JSON.stringify({ type: "ping" }));
      } catch {
        // Send failed — socket is dead
        this.connected = false;
        this.callbacks.onClose?.();
        this.reconnectDelay = INITIAL_RECONNECT_DELAY;
        this.urlIndex = 0;
        this.tryUrl();
      }
    }
  }
  private tryUrl() {
    this.cleanup();
    const url = this.urls[this.urlIndex];
    if (!url) return;
    const ws = new WebSocket(url);
    this.ws = ws;
    // If trying local (index 0) and we have a remote fallback,
    // give local 2.5s before switching to remote
    if (this.urlIndex === 0 && this.urls.length > 1) {
      this.localTimer = setTimeout(() => {
        this.localTimer = null;
        if (this.connected) return; // already connected, ignore
        // Local didn't connect in time — try remote
        this.urlIndex = 1;
        this.tryUrl();
      }, LOCAL_TIMEOUT);
    }
    ws.onopen = () => {
      if (ws !== this.ws) return; // stale
      this.connected = true;
      if (this.localTimer) { clearTimeout(this.localTimer); this.localTimer = null; }
      this.reconnectDelay = INITIAL_RECONNECT_DELAY;
      this.startHeartbeat();
      this.callbacks.onOpen?.();
    };
    ws.onmessage = (event) => {
      if (ws !== this.ws) return; // stale
      try {
        const data = JSON.parse(event.data) as WebSocketMessage;
        // Handle pong responses from heartbeat
        if (data.type === "pong") {
          this.pongReceived = true;
          return;
        }
        this.callbacks.onMessage?.(data);
      } catch {
        this.callbacks.onMessage?.({ type: "text", content: String(event.data) });
      }
    };
    ws.onclose = () => {
      if (ws !== this.ws) return; // stale
      this.connected = false;
      this.callbacks.onClose?.();
      if (this.shouldReconnect) {
        this.scheduleReconnect();
      }
    };
    ws.onerror = () => {
      if (ws !== this.ws) return; // stale
      // Don't do anything here — onclose always fires after onerror
      // and handles reconnect. Just swallow the error event.
    };
  }
  private scheduleReconnect() {
    if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
    this.reconnectTimer = setTimeout(() => {
      this.reconnectTimer = null;
      this.reconnectDelay = Math.min(
        this.reconnectDelay * RECONNECT_MULTIPLIER,
        MAX_RECONNECT_DELAY
      );
      // Alternate between URLs on each reconnect attempt
      if (this.urls.length > 1) {
        this.urlIndex = this.urlIndex === 0 ? 1 : 0;
      }
      this.tryUrl();
    }, this.reconnectDelay);
  }
  disconnect() {
    this.shouldReconnect = false;
    this.connected = false;
    this.cleanup();
  }
  send(message: WsOutgoing) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify(message));
      return true;
    }
    return false;
  }
  get readyState(): number {
    return this.ws?.readyState ?? WebSocket.CLOSED;
  }
  get isConnected(): boolean {
    return this.connected;
  }
  get currentUrl(): string {
    return this.urls[this.urlIndex] ?? "";
  }
}
export const wsClient = new WebSocketClient();