sync-pk-sp/WebsocketClient.js

77 lines
2.7 KiB
JavaScript
Raw Normal View History

2022-03-01 19:14:15 -08:00
const WebSocket = require('ws')
const timestamp = () => new Date().toISOString().replace('T', ' ').substr(0, 19)
function WebSocketClient(url) {
2022-03-01 19:14:15 -08:00
let client
let timeout
let connecting = false
let backoff = 250
const init = () => {
if (!process.env.silence_connections) console.error(`::SimplyWS:: [${timestamp()}] connecting`)
2022-03-01 19:14:15 -08:00
connecting = false
if (client !== undefined) {
2022-03-01 19:14:15 -08:00
client.removeAllListeners()
}
2022-03-01 19:14:15 -08:00
client = new WebSocket(url)
const heartbeat = () => {
if (timeout !== undefined) {
2022-03-01 19:14:15 -08:00
clearTimeout(timeout)
timeout = undefined
}
2022-03-01 19:59:20 -08:00
timeout = setTimeout(() => client.terminate(), process.env.heartbeat || 350000)
2022-03-01 19:14:15 -08:00
}
client.on('ping', () => {
if (!process.env.silence_connections) console.log(`::SimplyWS:: [${timestamp()}] pinged`)
2022-03-01 19:14:15 -08:00
heartbeat()
})
client.on('open', (e) => {
if (typeof this.onOpen === 'function') {
2022-03-01 19:14:15 -08:00
this.onOpen()
} else {
if (!process.env.silence_connections) console.log(`::SimplyWS:: [${timestamp()}] opened`)
2022-03-01 19:14:15 -08:00
console.log(e)
}
2022-03-01 19:14:15 -08:00
heartbeat()
})
client.on('message', (e) => {
if (typeof this.onMessage === 'function') {
2022-03-01 19:14:15 -08:00
this.onMessage(e)
} else {
if (!process.env.silence_connections) console.log(`::SimplyWS:: [${timestamp()}] messaged`)
}
2022-03-01 19:14:15 -08:00
heartbeat()
})
client.on('close', (e) => {
if (e.code !== 1000) {
if (connecting === false) { // abnormal closure
2022-03-01 19:14:15 -08:00
backoff = backoff === 8000 ? 250 : backoff * 2
setTimeout(() => init(), backoff)
connecting = true
}
} else if (typeof this.onClose === 'function') {
2022-03-01 19:14:15 -08:00
this.onClose()
} else {
2022-03-01 19:14:15 -08:00
console.error(`::SimplyWS:: [${timestamp()}] closed`)
console.error(e)
}
2022-03-01 19:14:15 -08:00
})
client.on('error', (e) => {
if (e.code === 'ECONREFUSED') {
if (connecting === false) { // abnormal closure
2022-03-01 19:14:15 -08:00
backoff = backoff === 8000 ? 250 : backoff * 2
setTimeout(() => init(), backoff)
connecting = true
}
} else if (typeof this.onError === 'function') {
2022-03-01 19:14:15 -08:00
this.onError(e)
} else {
2022-03-01 19:14:15 -08:00
console.error(`::SimplyWS:: [${timestamp()}] errored`)
console.error(e)
}
2022-03-01 19:14:15 -08:00
})
this.send = client.send.bind(client)
}
init()
}
2022-03-01 19:14:15 -08:00
module.exports = WebSocketClient