170 lines
4.8 KiB
TypeScript
170 lines
4.8 KiB
TypeScript
import { readAuth } from '../../../shared/auth/tokenStorage';
|
|
|
|
import type { WsClientMessage, WsServerMessage } from './protocol';
|
|
import { resolveWsBaseUrl } from './protocol';
|
|
|
|
type Listener = (msg: WsServerMessage) => void;
|
|
type Status = 'disconnected' | 'connecting' | 'connected' | 'reconnecting' | 'stale';
|
|
type StatusListener = (status: Status) => void;
|
|
|
|
export class GameSocketClient {
|
|
private socket: WebSocket | null = null;
|
|
private listeners = new Set<Listener>();
|
|
private reconnectAttempt = 0;
|
|
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
|
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
|
|
private staleTimer: ReturnType<typeof setTimeout> | null = null;
|
|
private subscribedInterval: number | null = null;
|
|
private closedByUser = false;
|
|
private lastConnectUrl: string | null = null;
|
|
private status: Status = 'disconnected';
|
|
private statusListeners = new Set<StatusListener>();
|
|
|
|
private static readonly HEARTBEAT_MS = 30_000;
|
|
private static readonly STALE_MS = 45_000;
|
|
|
|
connect(force = false): void {
|
|
const { accessToken } = readAuth();
|
|
const base = resolveWsBaseUrl();
|
|
const url = accessToken ? `${base}?token=${encodeURIComponent(accessToken)}` : base;
|
|
|
|
if (
|
|
!force &&
|
|
this.socket &&
|
|
(this.socket.readyState === WebSocket.OPEN || this.socket.readyState === WebSocket.CONNECTING) &&
|
|
this.lastConnectUrl === url
|
|
) {
|
|
return;
|
|
}
|
|
|
|
this.closedByUser = false;
|
|
this.lastConnectUrl = url;
|
|
this.setStatus(this.reconnectAttempt > 0 ? 'reconnecting' : 'connecting');
|
|
if (this.socket) {
|
|
this.socket.onclose = null;
|
|
this.socket.close();
|
|
this.socket = null;
|
|
}
|
|
|
|
this.socket = new WebSocket(url);
|
|
|
|
this.socket.onopen = () => {
|
|
this.reconnectAttempt = 0;
|
|
this.setStatus('connected');
|
|
this.startHeartbeat();
|
|
this.armStaleTimer();
|
|
if (this.subscribedInterval != null) {
|
|
this.send({ type: 'subscribe', intervalMinutes: this.subscribedInterval });
|
|
}
|
|
};
|
|
|
|
this.socket.onmessage = (ev) => {
|
|
try {
|
|
this.armStaleTimer();
|
|
this.setStatus('connected');
|
|
const msg = JSON.parse(String(ev.data)) as WsServerMessage;
|
|
for (const listener of this.listeners) listener(msg);
|
|
} catch {
|
|
/* ignore malformed */
|
|
}
|
|
};
|
|
|
|
this.socket.onclose = () => {
|
|
this.stopHeartbeat();
|
|
this.clearStaleTimer();
|
|
if (!this.closedByUser) this.scheduleReconnect();
|
|
else this.setStatus('disconnected');
|
|
};
|
|
}
|
|
|
|
reconnect(): void {
|
|
this.connect(true);
|
|
}
|
|
|
|
disconnect(): void {
|
|
this.closedByUser = true;
|
|
this.stopHeartbeat();
|
|
this.clearStaleTimer();
|
|
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
|
this.socket?.close();
|
|
this.socket = null;
|
|
this.setStatus('disconnected');
|
|
}
|
|
|
|
subscribe(intervalMinutes: number): void {
|
|
this.subscribedInterval = intervalMinutes;
|
|
this.send({ type: 'subscribe', intervalMinutes });
|
|
}
|
|
|
|
unsubscribe(intervalMinutes: number): void {
|
|
this.send({ type: 'unsubscribe', intervalMinutes });
|
|
if (this.subscribedInterval === intervalMinutes) {
|
|
this.subscribedInterval = null;
|
|
}
|
|
}
|
|
|
|
onMessage(listener: Listener): () => void {
|
|
this.listeners.add(listener);
|
|
return () => this.listeners.delete(listener);
|
|
}
|
|
|
|
getStatus(): Status {
|
|
return this.status;
|
|
}
|
|
|
|
onStatusChange(listener: StatusListener): () => void {
|
|
this.statusListeners.add(listener);
|
|
listener(this.status);
|
|
return () => this.statusListeners.delete(listener);
|
|
}
|
|
|
|
private send(msg: WsClientMessage): void {
|
|
if (this.socket?.readyState !== WebSocket.OPEN) return;
|
|
this.socket.send(JSON.stringify(msg));
|
|
}
|
|
|
|
private scheduleReconnect(): void {
|
|
const delay = Math.min(30_000, 1000 * 2 ** this.reconnectAttempt);
|
|
this.reconnectAttempt += 1;
|
|
this.setStatus('reconnecting');
|
|
this.reconnectTimer = setTimeout(() => this.connect(), delay);
|
|
}
|
|
|
|
private startHeartbeat(): void {
|
|
this.stopHeartbeat();
|
|
this.heartbeatTimer = setInterval(() => {
|
|
this.send({ type: 'ping', ts: Date.now() });
|
|
}, GameSocketClient.HEARTBEAT_MS);
|
|
}
|
|
|
|
private stopHeartbeat(): void {
|
|
if (this.heartbeatTimer) {
|
|
clearInterval(this.heartbeatTimer);
|
|
this.heartbeatTimer = null;
|
|
}
|
|
}
|
|
|
|
private armStaleTimer(): void {
|
|
this.clearStaleTimer();
|
|
this.staleTimer = setTimeout(() => {
|
|
this.setStatus('stale');
|
|
this.socket?.close();
|
|
}, GameSocketClient.STALE_MS);
|
|
}
|
|
|
|
private clearStaleTimer(): void {
|
|
if (this.staleTimer) {
|
|
clearTimeout(this.staleTimer);
|
|
this.staleTimer = null;
|
|
}
|
|
}
|
|
|
|
private setStatus(status: Status): void {
|
|
if (this.status === status) return;
|
|
this.status = status;
|
|
for (const listener of this.statusListeners) listener(status);
|
|
}
|
|
}
|
|
|
|
export const gameSocketClient = new GameSocketClient();
|