*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
This commit is contained in:
Derrick Hammer 2022-08-13 20:04:35 -04:00
parent 0120b67c59
commit f6bcc8ecdb
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
1 changed files with 8 additions and 0 deletions

View File

@ -107,6 +107,9 @@ export default class DHT {
} }
async connect(pubkey: string, options = {}): Promise<DhtNode> { async connect(pubkey: string, options = {}): Promise<DhtNode> {
if (this._activeRelays.size === 0) {
await this.fillConnections();
}
if (this._activeRelays.size === 0) { if (this._activeRelays.size === 0) {
throw new Error("Failed to find an available relay"); throw new Error("Failed to find an available relay");
} }
@ -147,6 +150,7 @@ export default class DHT {
relayIndex = await randomNumber(0, available.length - 1); relayIndex = await randomNumber(0, available.length - 1);
} }
const pubkey = available[relayIndex];
const connection = this._relays.get(available[relayIndex]) as string; const connection = this._relays.get(available[relayIndex]) as string;
if (!(await this.isServerAvailable(connection))) { if (!(await this.isServerAvailable(connection))) {
@ -163,6 +167,10 @@ export default class DHT {
updateAvailable(); updateAvailable();
relayPromises.push(node.ready()); relayPromises.push(node.ready());
node._protocol._stream.on("close", () => {
this._activeRelays.delete(pubkey);
});
} }
return Promise.allSettled(relayPromises); return Promise.allSettled(relayPromises);