From f1eb9a3bc73cff5ef198e1626abe4ac316bfdc2e Mon Sep 17 00:00:00 2001 From: Steve Perkins Date: Mon, 3 Apr 2023 21:55:40 -0400 Subject: [PATCH] Reuse connectionPromise for relay connect. --- pool.ts | 18 ++++++------------ relay.ts | 8 +++++++- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/pool.ts b/pool.ts index 89a3869..f59100b 100644 --- a/pool.ts +++ b/pool.ts @@ -26,22 +26,16 @@ export class SimplePool { async ensureRelay(url: string): Promise { const nm = normalizeURL(url) - const existing = this._conn[nm] - if (existing && existing.status === 1) return existing - if (existing) { - await existing.connect() - return existing + if (!this._conn[nm]) { + this._conn[nm] = relayInit(nm, { + getTimeout: this.getTimeout * 0.9, + listTimeout: this.getTimeout * 0.9 + }) } - const relay = relayInit(nm, { - getTimeout: this.getTimeout * 0.9, - listTimeout: this.getTimeout * 0.9 - }) - this._conn[nm] = relay - + const relay = this._conn[nm] await relay.connect() - return relay } diff --git a/relay.ts b/relay.ts index 54af8b4..60b9954 100644 --- a/relay.ts +++ b/relay.ts @@ -83,8 +83,10 @@ export function relayInit( } } = {} + var connectionPromise: Promise | undefined async function connectRelay(): Promise { - return new Promise((resolve, reject) => { + if (connectionPromise) return connectionPromise + connectionPromise = new Promise((resolve, reject) => { try { ws = new WebSocket(url) } catch (err) { @@ -96,10 +98,12 @@ export function relayInit( resolve() } ws.onerror = () => { + connectionPromise = undefined listeners.error.forEach(cb => cb()) reject() } ws.onclose = async () => { + connectionPromise = undefined listeners.disconnect.forEach(cb => cb()) } @@ -185,6 +189,8 @@ export function relayInit( } } }) + + return connectionPromise } function connected() {