summaryrefslogtreecommitdiff
path: root/frontend/src/services/ws.ts
blob: 7d10512ba0b398a71a9c7245587ae7a071d39a99 (plain) (blame)
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
// Minimal WS client with auto-reconnect for Rust backend interoperability.
// Point URL to your Rust server: ws://localhost:8080/ws (example)

type Listener = (data: any) => void

export class VNWebSocket {
  private url: string
  private ws: WebSocket | null = null
  private reconnectDelay = 1000
  private maxReconnectDelay = 8000
  private shouldReconnect = true
  private listeners: Record<string, Listener[]> = {}

  constructor(url: string) {
    this.url = url
  }

  on(event: 'open' | 'close' | 'error' | 'message', cb: Listener) {
    if (!this.listeners[event]) this.listeners[event] = []
    this.listeners[event].push(cb)
  }

  private emit(event: string, data?: any) {
    ;(this.listeners[event] || []).forEach(cb => cb(data))
  }

  connect() {
    this.ws = new WebSocket(this.url)

    this.ws.addEventListener('open', () => {
      this.emit('open')
      this.reconnectDelay = 1000
    })

    this.ws.addEventListener('message', (evt) => {
      try {
        const parsed = JSON.parse(evt.data)
        this.emit('message', parsed)
      } catch {
        this.emit('message', evt.data)
      }
    })

    this.ws.addEventListener('close', () => {
      this.emit('close')
      if (this.shouldReconnect) {
        setTimeout(() => this.connect(), this.reconnectDelay)
        this.reconnectDelay = Math.min(this.reconnectDelay * 2, this.maxReconnectDelay)
      }
    })

    this.ws.addEventListener('error', (e) => {
      this.emit('error', e)
      this.ws?.close()
    })
  }

  send(data: any) {
    const payload = typeof data === 'string' ? data : JSON.stringify(data)
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(payload)
    }
  }

  close() {
    this.shouldReconnect = false
    this.ws?.close()
  }
}