Tweak connection stuff

This commit is contained in:
Jon Staab
2024-03-01 13:48:49 -08:00
parent e7b604711a
commit 5aeafd6932
2 changed files with 16 additions and 36 deletions
+5 -4
View File
@@ -91,7 +91,7 @@ export class Connection extends Emitter {
ensureConnected = ({shouldReconnect = true}) => {
if (shouldReconnect && !this.socket.isHealthy()) {
this.reset()
this.disconnect()
}
if (this.socket.isPending()) {
@@ -99,14 +99,15 @@ export class Connection extends Emitter {
}
}
reset() {
this.socket.reset()
disconnect() {
this.socket.disconnect()
this.sendQueue.clear()
this.receiveQueue.clear()
this.meta.clearPending()
}
destroy() {
this.socket.disconnect()
this.disconnect()
this.removeAllListeners()
this.sendQueue.stop()
this.receiveQueue.stop()
+11 -32
View File
@@ -22,7 +22,7 @@ export type SocketOpts = {
export class Socket {
url: string
ws?: WebSocket
ready: Deferred<void>
ready: Deferred<boolean>
failedToConnect = false
constructor(url: string, readonly opts: SocketOpts) {
@@ -30,15 +30,6 @@ export class Socket {
this.ready = defer()
}
_close() {
if (!this.ws) {
throw new Error('Socket was closed before it was opened')
}
// Avoid "WebSocket was closed before the connection was established"
this.ready.then(() => this.ws?.close()).catch(() => null)
}
isPending() {
return !this.ws && !this.failedToConnect
}
@@ -64,23 +55,13 @@ export class Socket {
}
onOpen = () => {
this.ready.resolve()
this.ready.resolve(true)
this.opts.onOpen()
}
onClose = () => {
this.ready.reject()
this.opts.onClose()
if (this.ws) {
this._close()
}
}
onError = () => {
this.ready.reject()
this.opts.onError()
this._close()
this.disconnect()
}
onMessage = (event: MessageEvent) => {
@@ -113,24 +94,22 @@ export class Socket {
try {
this.ws = new WebSocket(this.url)
this.ws.onopen = this.onOpen
this.ws.onclose = this.onClose
this.ws.onerror = this.onError
this.ws.onmessage = this.onMessage
this.ws.onclose = this.disconnect
} catch (e) {
this.failedToConnect = true
}
}
disconnect() {
this.onClose()
}
reset() {
disconnect = () => {
if (this.ws) {
this._close()
}
const currentWs = this.ws
this.ws = undefined
this.ready = defer()
this.ready.then(() => currentWs.close())
this.ready.resolve(false)
this.opts.onClose()
this.ws = undefined
}
}
}