Skip to content

Commit

Permalink
fix: handle destroyed socket connections
Browse files Browse the repository at this point in the history
  • Loading branch information
dgreif committed Aug 10, 2021
1 parent 65def41 commit 751149f
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions src/my-link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,28 @@ import { createConnection, Socket } from 'net'
import { delay, logDebug, logError } from './util'

class ConnectionManager {
private socket?: Socket
private previousRequestId = 0
private previousRequest: Promise<unknown> = Promise.resolve()

constructor(private host: string, private port: number) {}

private socketPromise?: Promise<Socket>

private openSocket() {
private async openSocket(): Promise<Socket> {
if (this.socketPromise) {
return this.socketPromise
const socketPromise = this.socketPromise,
socket = await this.socketPromise

if (socket.destroyed && socketPromise === this.socketPromise) {
// current socket has been destoryed
this.socketPromise = undefined
return this.openSocket()
} else if (socketPromise !== this.socketPromise) {
// there is a new socket on-deck
return this.openSocket()
}

return socket
}

this.socketPromise = new Promise<Socket>((resolve, reject) => {
Expand All @@ -32,9 +43,12 @@ class ConnectionManager {
})
socket.on('close', () => {
logDebug('Socket Closed')
this.socket = undefined
this.socketPromise = undefined
})
socket.on('end', () => {
logDebug('Socket Ended')
this.socketPromise = undefined
})
this.socket = socket
})

return this.socketPromise
Expand Down

0 comments on commit 751149f

Please sign in to comment.