Skip to content

Commit

Permalink
fix: pep close handler
Browse files Browse the repository at this point in the history
Await the previous connection to prevent unhandled promise rejection;
Wait before reconnecting to prevent flooding;
Don't reconnect after calling close
  • Loading branch information
ianshade committed Mar 30, 2021
1 parent 12b4252 commit 578d55e
Showing 1 changed file with 21 additions and 5 deletions.
26 changes: 21 additions & 5 deletions src/mse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export class MSERep extends EventEmitter implements MSE {
private connection?: Promise<PepResponse> = undefined

private isAwaitingConnection = false
private reconnectTimeout?: NodeJS.Timeout = undefined

constructor(hostname: string, restPort?: number, wsPort?: number, resthost?: string) {
super()
Expand All @@ -26,14 +27,26 @@ export class MSERep extends EventEmitter implements MSE {
this.wsPort = typeof wsPort === 'number' && wsPort > 0 ? wsPort : 8595
this.resthost = resthost // For ngrok testing only
this.pep = startPepTalk(this.hostname, this.wsPort)
this.pep.on('close', async () => {
if (this.connection && !this.isAwaitingConnection) {
this.connection = this.pep.connect()
}
})
this.pep.on('close', () => this.onPepClose())
this.connection = this.pep.connect()
}

async onPepClose(): Promise<void> {
if (this.connection && !this.isAwaitingConnection) {
try {
await this.connection
} catch (error) {
// nothing we can do about it
}
this.connection = undefined
this.reconnectTimeout = setTimeout(() => {
if (!this.connection) {
this.connection = this.pep.connect()
}
}, 2000)
}
}

async checkConnection(): Promise<void> {
try {
if (this.connection) {
Expand Down Expand Up @@ -284,6 +297,9 @@ export class MSERep extends EventEmitter implements MSE {
}

async close(): Promise<boolean> {
if (this.reconnectTimeout) {
clearTimeout(this.reconnectTimeout)
}
if (this.connection) {
await this.pep.close()
return true
Expand Down

0 comments on commit 578d55e

Please sign in to comment.