From f6bcc8ecdbcf8ecfba2a8e00c905cdea9d81b26d Mon Sep 17 00:00:00 2001 From: Derrick Hammer Date: Sat, 13 Aug 2022 20:04:35 -0400 Subject: [PATCH] *Delete relay from active list when the raw stream/websocket closes *Attempt to refill and reconnect to relays if we have 0 active relays in the pool --- src/index.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/index.ts b/src/index.ts index 21ceac5..040af7b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -107,6 +107,9 @@ export default class DHT { } async connect(pubkey: string, options = {}): Promise { + if (this._activeRelays.size === 0) { + await this.fillConnections(); + } if (this._activeRelays.size === 0) { throw new Error("Failed to find an available relay"); } @@ -147,6 +150,7 @@ export default class DHT { relayIndex = await randomNumber(0, available.length - 1); } + const pubkey = available[relayIndex]; const connection = this._relays.get(available[relayIndex]) as string; if (!(await this.isServerAvailable(connection))) { @@ -163,6 +167,10 @@ export default class DHT { updateAvailable(); relayPromises.push(node.ready()); + + node._protocol._stream.on("close", () => { + this._activeRelays.delete(pubkey); + }); } return Promise.allSettled(relayPromises);