-
Notifications
You must be signed in to change notification settings - Fork 520
Expand file tree
/
Copy pathwebsocket-client.ts
More file actions
258 lines (234 loc) · 7.37 KB
/
websocket-client.ts
File metadata and controls
258 lines (234 loc) · 7.37 KB
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
import { WebSocket } from 'ws'
import type { ClientAction, ServerAction } from '../actions'
import type {
ClientMessage,
ClientMessageType,
ServerMessage,
} from './websocket-schema'
// mqp: useful for debugging
const VERBOSE_LOGGING = false
// Timeout for websocket messages waiting for acknowledgment (2 minutes)
const TIMEOUT_MS = 120_000
const RECONNECT_WAIT_MS = 5_000
type ConnectingState = typeof WebSocket.CONNECTING
type OpenState = typeof WebSocket.OPEN
type ClosingState = typeof WebSocket.CLOSING
type ClosedState = typeof WebSocket.CLOSED
export type ReadyState =
| OpenState
| ConnectingState
| ClosedState
| ClosingState
export function formatState(state: ReadyState) {
switch (state) {
case WebSocket.CONNECTING:
return 'connecting'
case WebSocket.OPEN:
return 'open'
case WebSocket.CLOSING:
return 'closing'
case WebSocket.CLOSED:
return 'closed'
default:
throw new Error('Invalid websocket state.')
}
}
type OutstandingTxn = {
resolve: () => void
reject: (err: Error) => void
timeout?: any
}
/** Client for the API websocket realtime server. Automatically manages reconnection
* and resubscription on disconnect, and allows subscribers to get a callback
* when something is broadcasted. */
export class APIRealtimeClient {
ws!: WebSocket
url: string
// Callbacks subscribed to individual actions.
subscribers: Map<ServerAction['type'], ((action: ServerAction) => void)[]>
txid: number
// all txns that are in flight, with no ack/error/timeout
txns: Map<number, OutstandingTxn>
connectTimeout?: any
heartbeat?: any
hadError = false
onError: (event: WebSocket.ErrorEvent) => void
onReconnect: () => void
constructor(
url: string,
onError: (event: WebSocket.ErrorEvent) => void,
onReconnect: () => void,
) {
this.url = url
this.txid = 0
this.txns = new Map()
this.subscribers = new Map()
this.onError = onError
this.onReconnect = onReconnect
}
get state() {
return this.ws.readyState as ReadyState
}
close() {
this.ws.close(1000, 'Closed manually.')
clearTimeout(this.connectTimeout)
}
connect() {
// you may wish to refer to https://websockets.spec.whatwg.org/
// in order to check the semantics of events etc.
this.ws = new WebSocket(this.url)
this.ws.onmessage = (ev) => {
if (this.hadError) {
this.hadError = false
this.onReconnect()
}
this.receiveMessage(JSON.parse(ev.data as any))
}
this.ws.onerror = (ev) => {
if (!this.hadError) {
this.onError(ev)
this.hadError = true
}
// this can fire without an onclose if this is the first time we ever try
// to connect, so we need to turn on our reconnect in that case
this.waitAndReconnect()
}
this.ws.onclose = (ev) => {
// note that if the connection closes due to an error, onerror fires and then this
if (VERBOSE_LOGGING) {
console.info(`API websocket closed with code=${ev.code}: ${ev.reason}`)
}
clearInterval(this.heartbeat)
// mqp: we might need to change how the txn stuff works if we ever want to
// implement "wait until i am subscribed, and then do something" in a component.
// right now it cannot be reliably used to detect that in the presence of reconnects
for (const txn of Array.from(this.txns.values())) {
clearTimeout(txn.timeout)
// NOTE (James): Don't throw an error when the websocket is closed...
// This seems to be happening, but the client can recover.
txn.resolve()
// txn.reject(new Error('Websocket was closed.'))
}
this.txns.clear()
// 1000 is RFC code for normal on-purpose closure
if (ev.code !== 1000) {
this.waitAndReconnect()
}
}
return new Promise<void>((resolve) => {
this.ws.onopen = (_ev) => {
if (VERBOSE_LOGGING) {
console.info('API websocket opened.')
}
this.heartbeat = setInterval(
async () => this.sendMessage('ping', {}).catch(() => {}),
30000,
)
resolve()
}
})
}
waitAndReconnect() {
if (this.connectTimeout == null) {
this.connectTimeout = setTimeout(() => {
this.connectTimeout = undefined
this.connect()
}, RECONNECT_WAIT_MS)
}
}
forceReconnect() {
// Close the current connection if it's open
if (this.ws && this.state !== WebSocket.CLOSED) {
this.ws.close(1000, 'Forced reconnection due to server shutdown notice')
}
// Immediately attempt to reconnect
this.connect().catch((err) => {
if (VERBOSE_LOGGING) {
console.error('Failed to reconnect after server shutdown notice:', err)
}
// Still set up delayed reconnect as fallback
this.waitAndReconnect()
})
}
receiveMessage(msg: ServerMessage) {
if (VERBOSE_LOGGING) {
console.info('< Incoming API websocket message: ', msg)
}
switch (msg.type) {
case 'action': {
const action = msg.data
const subscribers = this.subscribers.get(action.type) ?? []
for (const callback of subscribers) {
callback(action)
}
return
}
case 'ack': {
if (msg.txid != null) {
const txn = this.txns.get(msg.txid)
if (txn == null) {
// mqp: only reason this should happen is getting an ack after timeout
if (VERBOSE_LOGGING) {
console.warn(`Websocket message with old txid=${msg.txid}.`)
}
} else {
clearTimeout(txn.timeout)
if (msg.error != null) {
txn.reject(new Error(msg.error))
} else {
txn.resolve()
}
this.txns.delete(msg.txid)
}
}
return
}
default:
if (VERBOSE_LOGGING) {
console.warn(`Unknown API websocket message type received: ${msg}`)
}
}
}
async sendMessage<T extends ClientMessageType>(
type: T,
data: Omit<ClientMessage<T>, 'type' | 'txid'>,
) {
if (VERBOSE_LOGGING) {
console.info(`> Outgoing API websocket ${type} message: `, data)
}
if (this.state === WebSocket.OPEN) {
return new Promise<void>((resolve, reject) => {
const txid = this.txid++
const timeout = setTimeout(() => {
this.txns.delete(txid)
reject(new Error(`Websocket message with txid ${txid} timed out.`))
}, TIMEOUT_MS)
this.txns.set(txid, { resolve, reject, timeout })
this.ws.send(JSON.stringify({ type, txid, ...data }))
})
} else {
// expected if components in the code try to subscribe or unsubscribe
// while the socket is closed -- in this case we expect to get the state
// fixed up in the websocket onopen handler when we reconnect
}
}
async sendAction(action: ClientAction) {
return await this.sendMessage('action', {
data: action,
})
}
subscribe<T extends ServerAction['type']>(
action: T,
callback: (action: ServerAction<T>) => void,
) {
const currSubscribers = this.subscribers.get(action) ?? []
this.subscribers.set(action, [
...currSubscribers,
callback as (action: ServerAction) => void,
])
return () => {
const newSubscribers = currSubscribers.filter((cb) => cb !== callback)
this.subscribers.set(action, newSubscribers)
}
}
}