| 1 | /** Close codes that should not trigger auto-reconnect (auth / intentional server kicks). */ |
| 2 | export const NO_AUTO_RECONNECT_CODES = new Set([ |
| 3 | 1000, // normal closure (also used by intentional close()) |
| 4 | 1001, // going away / server restart |
| 5 | 4000, // logged in elsewhere |
| 6 | 4401, // authentication required |
| 7 | 1011 // authentication / session setup failed |
| 8 | ]); |
| 9 | |
| 10 | /** |
| 11 | * Exponential backoff delay for reconnect attempts. |
| 12 | * @param {number} attempt zero-based attempt index |
| 13 | * @param {{ baseMs?: number, maxMs?: number }} [options] |
| 14 | */ |
| 15 | export function nextReconnectDelayMs (attempt, { baseMs = 750, maxMs = 20_000 } = {}) |
| 16 | { |
| 17 | const n = Math.max(0, attempt | 0); |
| 18 | return Math.min(maxMs, baseMs * (2 ** n)); |
| 19 | } |
| 20 | |
| 21 | /** |
| 22 | * @param {number} code WebSocket close code |
| 23 | * @param {{ intentional?: boolean, autoReconnect?: boolean }} [options] |
| 24 | */ |
| 25 | export function shouldAutoReconnect (code, { intentional = false, autoReconnect = false } = {}) |
| 26 | { |
| 27 | if (!autoReconnect || intentional) |
| 28 | { return false; } |
| 29 | return !NO_AUTO_RECONNECT_CODES.has(code | 0); |
| 30 | } |
| 31 | |
| 32 | export class GameSocket |
| 33 | { |
| 34 | /** |
| 35 | * @param {string} url |
| 36 | * @param {(message: object) => void} onMessage |
| 37 | * @param {{ |
| 38 | * onClose?: (event: CloseEvent) => void, |
| 39 | * onError?: (event: Event) => void, |
| 40 | * onOpen?: (event: Event) => void, |
| 41 | * onReconnecting?: (info: { attempt: number, delayMs: number, code: number }) => void, |
| 42 | * autoReconnect?: boolean, |
| 43 | * reconnectBaseMs?: number, |
| 44 | * reconnectMaxMs?: number |
| 45 | * }} [options] |
| 46 | */ |
| 47 | constructor (url, onMessage, { |
| 48 | onClose, |
| 49 | onError, |
| 50 | onOpen, |
| 51 | onReconnecting, |
| 52 | autoReconnect = false, |
| 53 | reconnectBaseMs = 750, |
| 54 | reconnectMaxMs = 20_000 |
| 55 | } = {}) |
| 56 | { |
| 57 | this.url = url; |
| 58 | this.onMessage = onMessage; |
| 59 | this.onClose = onClose; |
| 60 | this.onError = onError; |
| 61 | this.onOpen = onOpen; |
| 62 | this.onReconnecting = onReconnecting; |
| 63 | this.autoReconnect = !!autoReconnect; |
| 64 | this.reconnectBaseMs = reconnectBaseMs; |
| 65 | this.reconnectMaxMs = reconnectMaxMs; |
| 66 | this.socket = null; |
| 67 | this._intentionalClose = false; |
| 68 | this._reconnectAttempt = 0; |
| 69 | this._reconnectTimer = null; |
| 70 | this._boundMessage = (event) => |
| 71 | { |
| 72 | this.onMessage(JSON.parse(event.data)); |
| 73 | }; |
| 74 | this._boundClose = (event) => |
| 75 | { |
| 76 | this._handleClose(event); |
| 77 | }; |
| 78 | this._boundError = (event) => |
| 79 | { |
| 80 | this.onError?.(event); |
| 81 | }; |
| 82 | this._boundOpen = (event) => |
| 83 | { |
| 84 | this.onOpen?.(event); |
| 85 | }; |
| 86 | } |
| 87 | |
| 88 | connect () |
| 89 | { |
| 90 | this._intentionalClose = false; |
| 91 | return this._openSocket(); |
| 92 | } |
| 93 | |
| 94 | /** Graceful client-initiated close — does not auto-reconnect. */ |
| 95 | close (code = 1000, reason = "Client closed") |
| 96 | { |
| 97 | this._intentionalClose = true; |
| 98 | this._clearReconnectTimer(); |
| 99 | this._reconnectAttempt = 0; |
| 100 | const socket = this.socket; |
| 101 | this._detach(socket); |
| 102 | if (socket && (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING)) |
| 103 | { |
| 104 | try |
| 105 | { socket.close(code, reason); } |
| 106 | catch |
| 107 | { /* ignore */ } |
| 108 | } |
| 109 | this.socket = null; |
| 110 | } |
| 111 | |
| 112 | /** Call when an application SESSION (or equivalent) is established so backoff resets. */ |
| 113 | notifySessionEstablished () |
| 114 | { |
| 115 | this._reconnectAttempt = 0; |
| 116 | this._clearReconnectTimer(); |
| 117 | } |
| 118 | |
| 119 | send (payload) |
| 120 | { |
| 121 | if (!this.socket || this.socket.readyState !== WebSocket.OPEN) |
| 122 | { throw new Error("WebSocket is not connected."); } |
| 123 | this.socket.send(JSON.stringify(payload)); |
| 124 | } |
| 125 | |
| 126 | get reconnecting () |
| 127 | { |
| 128 | return this._reconnectTimer != null; |
| 129 | } |
| 130 | |
| 131 | _openSocket () |
| 132 | { |
| 133 | this._clearReconnectTimer(); |
| 134 | this._detach(this.socket); |
| 135 | const socket = new WebSocket(this.url); |
| 136 | this.socket = socket; |
| 137 | socket.addEventListener("message", this._boundMessage); |
| 138 | socket.addEventListener("close", this._boundClose); |
| 139 | socket.addEventListener("error", this._boundError); |
| 140 | socket.addEventListener("open", this._boundOpen); |
| 141 | |
| 142 | return new Promise((resolve, reject) => |
| 143 | { |
| 144 | const onOpen = () => |
| 145 | { |
| 146 | cleanup(); |
| 147 | resolve(); |
| 148 | }; |
| 149 | const onError = () => |
| 150 | { |
| 151 | cleanup(); |
| 152 | reject(new Error("WebSocket failed")); |
| 153 | }; |
| 154 | const cleanup = () => |
| 155 | { |
| 156 | socket.removeEventListener("open", onOpen); |
| 157 | socket.removeEventListener("error", onError); |
| 158 | }; |
| 159 | socket.addEventListener("open", onOpen, { once: true }); |
| 160 | socket.addEventListener("error", onError, { once: true }); |
| 161 | }); |
| 162 | } |
| 163 | |
| 164 | _detach (socket) |
| 165 | { |
| 166 | if (!socket) |
| 167 | { return; } |
| 168 | socket.removeEventListener("message", this._boundMessage); |
| 169 | socket.removeEventListener("close", this._boundClose); |
| 170 | socket.removeEventListener("error", this._boundError); |
| 171 | socket.removeEventListener("open", this._boundOpen); |
| 172 | } |
| 173 | |
| 174 | _clearReconnectTimer () |
| 175 | { |
| 176 | if (this._reconnectTimer != null) |
| 177 | { |
| 178 | clearTimeout(this._reconnectTimer); |
| 179 | this._reconnectTimer = null; |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | _scheduleReconnect (code) |
| 184 | { |
| 185 | const attempt = this._reconnectAttempt; |
| 186 | const delayMs = nextReconnectDelayMs(attempt, { |
| 187 | baseMs: this.reconnectBaseMs, |
| 188 | maxMs: this.reconnectMaxMs |
| 189 | }); |
| 190 | this._reconnectAttempt = attempt + 1; |
| 191 | this.onReconnecting?.({ attempt: this._reconnectAttempt, delayMs, code: code | 0 }); |
| 192 | this._reconnectTimer = setTimeout(() => |
| 193 | { |
| 194 | this._reconnectTimer = null; |
| 195 | void this._openSocket().catch(() => |
| 196 | { |
| 197 | // open/error path usually also emits close; if not, retry from here |
| 198 | if (this._intentionalClose || !this.autoReconnect || this.socket) |
| 199 | { return; } |
| 200 | this._scheduleReconnect(code); |
| 201 | }); |
| 202 | }, delayMs); |
| 203 | } |
| 204 | |
| 205 | _handleClose (event) |
| 206 | { |
| 207 | this._detach(event?.target ?? this.socket); |
| 208 | if (this.socket === event?.target) |
| 209 | { this.socket = null; } |
| 210 | |
| 211 | this.onClose?.(event); |
| 212 | |
| 213 | const code = event?.code | 0; |
| 214 | if (!shouldAutoReconnect(code, { |
| 215 | intentional: this._intentionalClose, |
| 216 | autoReconnect: this.autoReconnect |
| 217 | })) |
| 218 | { |
| 219 | this._intentionalClose = false; |
| 220 | return; |
| 221 | } |
| 222 | |
| 223 | this._scheduleReconnect(code); |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | export function defaultSocketUrl () |
| 228 | { |
| 229 | const protocol = location.protocol === "https:" ? "wss:" : "ws:"; |
| 230 | return `${protocol}//${location.host}/ws`; |
| 231 | } |