forked from dmonad/lib0
-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket.js
145 lines (137 loc) · 4 KB
/
websocket.js
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
/* eslint-env browser */
import { Observable } from './observable.js'
import * as time from './time.js'
import * as math from './math.js'
const reconnectTimeoutBase = 1200
const maxReconnectTimeout = 2500
// @todo - this should depend on awareness.outdatedTime
const messageReconnectTimeout = 30000
/**
* @param {WebsocketClient} wsclient
*/
const setupWS = (wsclient) => {
if (wsclient.shouldConnect && wsclient.ws === null) {
const websocket = new WebSocket(wsclient.url)
const binaryType = wsclient.binaryType
/**
* @type {any}
*/
let pingTimeout = null
if (binaryType) {
websocket.binaryType = binaryType
}
wsclient.ws = websocket
wsclient.connecting = true
wsclient.connected = false
websocket.onmessage = event => {
wsclient.lastMessageReceived = time.getUnixTime()
const data = event.data
const message = typeof data === 'string' ? JSON.parse(data) : data
if (message && message.type === 'pong') {
clearTimeout(pingTimeout)
pingTimeout = setTimeout(sendPing, messageReconnectTimeout / 2)
}
wsclient.emit('message', [message, wsclient])
}
/**
* @param {any} error
*/
const onclose = error => {
if (wsclient.ws !== null) {
wsclient.ws = null
wsclient.connecting = false
if (wsclient.connected) {
wsclient.connected = false
wsclient.emit('disconnect', [{ type: 'disconnect', error }, wsclient])
} else {
wsclient.unsuccessfulReconnects++
}
// Start with no reconnect timeout and increase timeout by
// log10(wsUnsuccessfulReconnects).
// The idea is to increase reconnect timeout slowly and have no reconnect
// timeout at the beginning (log(1) = 0)
setTimeout(setupWS, math.min(math.log10(wsclient.unsuccessfulReconnects + 1) * reconnectTimeoutBase, maxReconnectTimeout), wsclient)
}
clearTimeout(pingTimeout)
}
const sendPing = () => {
if (wsclient.ws === websocket) {
wsclient.send({
type: 'ping'
})
}
}
websocket.onclose = () => onclose(null)
websocket.onerror = error => onclose(error)
websocket.onopen = () => {
wsclient.lastMessageReceived = time.getUnixTime()
wsclient.connecting = false
wsclient.connected = true
wsclient.unsuccessfulReconnects = 0
wsclient.emit('connect', [{ type: 'connect' }, wsclient])
// set ping
pingTimeout = setTimeout(sendPing, messageReconnectTimeout / 2)
}
}
}
/**
* @extends Observable<string>
*/
export class WebsocketClient extends Observable {
/**
* @param {string} url
* @param {object} [opts]
* @param {'arraybuffer' | 'blob' | null} [opts.binaryType] Set `ws.binaryType`
*/
constructor (url, { binaryType } = {}) {
super()
this.url = url
/**
* @type {WebSocket?}
*/
this.ws = null
this.binaryType = binaryType || null
this.connected = false
this.connecting = false
this.unsuccessfulReconnects = 0
this.lastMessageReceived = 0
/**
* Whether to connect to other peers or not
* @type {boolean}
*/
this.shouldConnect = true
this._checkInterval = setInterval(() => {
if (this.connected && messageReconnectTimeout < time.getUnixTime() - this.lastMessageReceived) {
// no message received in a long time - not even your own awareness
// updates (which are updated every 15 seconds)
/** @type {WebSocket} */ (this.ws).close()
}
}, messageReconnectTimeout / 2)
setupWS(this)
}
/**
* @param {any} message
*/
send (message) {
if (this.ws) {
this.ws.send(JSON.stringify(message))
}
}
destroy () {
clearInterval(this._checkInterval)
this.disconnect()
super.destroy()
}
disconnect () {
this.shouldConnect = false
if (this.ws !== null) {
this.ws.close()
}
}
connect () {
this.shouldConnect = true
if (!this.connected && this.ws === null) {
setupWS(this)
}
}
}