Skip to content

Commit

Permalink
Add pong timeout and close handling (#51)
Browse files Browse the repository at this point in the history
  • Loading branch information
lnbc1QWFyb24 authored Nov 26, 2023
1 parent e6dd08f commit 6c9dde3
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "lnmessage",
"version": "0.2.6",
"version": "0.2.7",
"description": "Talk to Lightning nodes from your browser",
"main": "dist/index.js",
"type": "module",
Expand Down
19 changes: 17 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ class LnMessage {
private _processingBuffer: boolean
private _l: number | null
private _pingTimeout: NodeJS.Timeout | null
private _pongTimeout: NodeJS.Timeout | null

constructor(options: LnWebSocketOptions) {
validateInit(options)
Expand Down Expand Up @@ -138,6 +139,7 @@ class LnMessage {
this._processingBuffer = false
this._l = null
this._pingTimeout = null
this._pongTimeout = null

this.decryptedMsgs$.subscribe((msg) => {
this.handleDecryptedMessage(msg)
Expand Down Expand Up @@ -196,6 +198,7 @@ class LnMessage {
this.socket.onclose = async () => {
this._log('error', 'WebSocket is closed at ' + new Date().toISOString())
this._pingTimeout && clearTimeout(this._pingTimeout)
this._pongTimeout && clearTimeout(this._pongTimeout)

this.connectionStatus$.next('disconnected')
this.connected$.next(false)
Expand Down Expand Up @@ -235,9 +238,18 @@ class LnMessage {
if (this.socket) {
this._log('info', 'Sending a Ping message')
this.socket.send(ping)

// wait 5 seconds for a reply and close if no reply
this._pongTimeout = setTimeout(() => this._close(), 5 * 1000)
}
}

private _close() {
this._log('error', 'Closing connection')

this.socket?.close()
}

private queueMessage(event: { data: ArrayBuffer }) {
const { data } = event
const message = Buffer.from(data)
Expand Down Expand Up @@ -265,7 +277,9 @@ class LnMessage {
})

this._attemptReconnect = false
this.socket && this.socket.close()
this._pingTimeout && clearTimeout(this._pingTimeout)
this._pongTimeout && clearTimeout(this._pongTimeout)
this._close()
}

private async _processBuffer() {
Expand Down Expand Up @@ -405,7 +419,8 @@ class LnMessage {
}

async handleDecryptedMessage(decrypted: Buffer) {
// reset ping timeout
// reset ping and pong timeout
this._pongTimeout && clearTimeout(this._pongTimeout)
this._pingTimeout && clearTimeout(this._pingTimeout)
this._pingTimeout = setTimeout(this._sendPingMessage.bind(this), 40 * 1000)

Expand Down

0 comments on commit 6c9dde3

Please sign in to comment.