GCoordinator/src/client/ts/ws-client.ts

113 lines
3.5 KiB
TypeScript

import type { ClientWsFrame, ServerWsFrame } from '../../shared/ws-protocol.js';
export type WsConnectionStatus = 'online' | 'reconnecting' | 'offline';
export class MultiplexWsClient {
private ws: WebSocket | null = null;
private reconnectAttempt = 0;
private reconnectTimer: number | null = null;
private pingTimer: number | null = null;
private shouldRun = false;
private channels = new Set<string>(['config', 'alerts', 'metrics', 'workflows']);
private readonly frameListeners = new Set<(frame: ServerWsFrame) => void>();
private readonly statusListeners = new Set<(status: WsConnectionStatus) => void>();
onFrame(listener: (frame: ServerWsFrame) => void): () => void {
this.frameListeners.add(listener);
return () => this.frameListeners.delete(listener);
}
onStatus(listener: (status: WsConnectionStatus) => void): () => void {
this.statusListeners.add(listener);
return () => this.statusListeners.delete(listener);
}
connect(): void {
this.shouldRun = true;
this.openSocket();
}
disconnect(): void {
this.shouldRun = false;
if (this.reconnectTimer !== null) {
window.clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
if (this.pingTimer !== null) {
window.clearInterval(this.pingTimer);
this.pingTimer = null;
}
if (this.ws) {
this.ws.close(1000, 'Client disconnect');
this.ws = null;
}
this.emitStatus('offline');
}
send(frame: ClientWsFrame): void {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(frame));
}
}
subscribe(channels: string[]): void {
for (const ch of channels) this.channels.add(ch);
this.send({ type: 'sub', channels });
}
private openSocket(): void {
if (!this.shouldRun) return;
if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) {
return;
}
const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const socket = new WebSocket(`${proto}//${window.location.host}/ws`);
this.ws = socket;
socket.addEventListener('open', () => {
this.reconnectAttempt = 0;
this.emitStatus('online');
if (this.channels.size > 0) {
this.send({ type: 'sub', channels: [...this.channels] });
}
if (this.pingTimer !== null) window.clearInterval(this.pingTimer);
this.pingTimer = window.setInterval(() => {
this.send({ type: 'ping', ts: Date.now() });
}, 20_000);
});
socket.addEventListener('message', (ev) => {
try {
const frame = JSON.parse(String(ev.data)) as ServerWsFrame;
for (const listener of this.frameListeners) {
listener(frame);
}
} catch {
// Ignore malformed server frame
}
});
socket.addEventListener('close', (ev) => {
if (this.pingTimer !== null) {
window.clearInterval(this.pingTimer);
this.pingTimer = null;
}
this.ws = null;
if (!this.shouldRun || ev.code === 4001) {
this.emitStatus('offline');
return;
}
this.emitStatus('reconnecting');
const delay = Math.min(10_000, 500 * 2 ** this.reconnectAttempt);
this.reconnectAttempt = Math.min(this.reconnectAttempt + 1, 6);
this.reconnectTimer = window.setTimeout(() => this.openSocket(), delay);
});
}
private emitStatus(status: WsConnectionStatus): void {
for (const listener of this.statusListeners) {
listener(status);
}
}
}