use setInterval() instead of nested setTimeout()s for pingpong.

prevent call stacks from building up
This commit is contained in:
fiatjaf
2025-12-05 21:44:41 -03:00
parent 693b262b7c
commit 0b6543e1a8
3 changed files with 12 additions and 14 deletions

View File

@@ -45,7 +45,7 @@ export class AbstractRelay {
public enableReconnect: boolean
private connectionTimeoutHandle: ReturnType<typeof setTimeout> | undefined
private reconnectTimeoutHandle: ReturnType<typeof setTimeout> | undefined
private pingTimeoutHandle: ReturnType<typeof setTimeout> | undefined
private pingIntervalHandle: ReturnType<typeof setInterval> | undefined
private reconnectAttempts: number = 0
private closedIntentionally: boolean = false
@@ -111,9 +111,9 @@ export class AbstractRelay {
}
private handleHardClose(reason: string) {
if (this.pingTimeoutHandle) {
clearTimeout(this.pingTimeoutHandle)
this.pingTimeoutHandle = undefined
if (this.pingIntervalHandle) {
clearInterval(this.pingIntervalHandle)
this.pingIntervalHandle = undefined
}
this._connected = false
@@ -177,7 +177,7 @@ export class AbstractRelay {
}
if (this.enablePing) {
this.pingpong()
this.pingIntervalHandle = setInterval(() => this.pingpong(), this.pingFrequency)
}
resolve()
}
@@ -247,10 +247,8 @@ export class AbstractRelay {
this.ws && this.ws.ping && (this.ws as any).once ? this.waitForPingPong() : this.waitForDummyReq(),
new Promise(res => setTimeout(() => res(false), this.pingTimeout)),
])
if (result) {
// schedule another pingpong
this.pingTimeoutHandle = setTimeout(() => this.pingpong(), this.pingFrequency)
} else {
if (!result) {
// pingpong closing socket
if (this.ws?.readyState === this._WebSocket.OPEN) {
this.ws?.close()
@@ -458,9 +456,9 @@ export class AbstractRelay {
clearTimeout(this.reconnectTimeoutHandle)
this.reconnectTimeoutHandle = undefined
}
if (this.pingTimeoutHandle) {
clearTimeout(this.pingTimeoutHandle)
this.pingTimeoutHandle = undefined
if (this.pingIntervalHandle) {
clearInterval(this.pingIntervalHandle)
this.pingIntervalHandle = undefined
}
this.closeAllSubscriptions('relay connection closed by us')
this._connected = false

View File

@@ -1,6 +1,6 @@
{
"name": "@nostr/tools",
"version": "2.19.1",
"version": "2.19.2",
"exports": {
".": "./index.ts",
"./core": "./core.ts",

View File

@@ -1,7 +1,7 @@
{
"type": "module",
"name": "nostr-tools",
"version": "2.19.1",
"version": "2.19.2",
"description": "Tools for making a Nostr client.",
"repository": {
"type": "git",