Skip to content

Commit

Permalink
fix: close connection after 1 minute of inactivity
Browse files Browse the repository at this point in the history
  • Loading branch information
dgreif committed Aug 11, 2021
1 parent 721dbb2 commit 92cafed
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/my-link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,34 @@ import { delay, logDebug, logError } from './util'
class ConnectionManager {
private previousRequestId = 0
private previousRequest: Promise<unknown> = Promise.resolve()
private timeout: any

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

private socketPromise?: Promise<Socket>

private async openSocket(): Promise<Socket> {
if (this.timeout) {
clearTimeout(this.timeout)
}
this.timeout = setTimeout(() => {
if (this.socketPromise) {
this.socketPromise.then((socket) => {
if (!socket.destroyed) {
socket.destroy()
}
})
}
}, 60000)

logDebug('Getting Socket')
if (this.socketPromise) {
const socketPromise = this.socketPromise,
socket = await this.socketPromise
logDebug('Have a socket')

if (socket.destroyed && socketPromise === this.socketPromise) {
logDebug('Socket has been destroyed')
// current socket has been destoryed
this.socketPromise = undefined
return this.openSocket()
Expand All @@ -27,12 +44,14 @@ class ConnectionManager {
}

this.socketPromise = new Promise<Socket>((resolve, reject) => {
logDebug('Creating fresh socket')
const socket: Socket = createConnection(
{
host: this.host,
port: this.port,
},
() => {
logDebug('Socket created')
resolve(socket)
}
)
Expand Down

0 comments on commit 92cafed

Please sign in to comment.