From 38af05edb8cb03ec4eb504f5a014d55c1681fc96 Mon Sep 17 00:00:00 2001 From: kieran Date: Thu, 25 Apr 2024 13:50:24 +0100 Subject: [PATCH] fix: connection race --- packages/system/src/connection-pool.ts | 9 ++++----- packages/system/src/connection.ts | 11 ++++++++++- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/packages/system/src/connection-pool.ts b/packages/system/src/connection-pool.ts index 81c5b6cf..476e69cc 100644 --- a/packages/system/src/connection-pool.ts +++ b/packages/system/src/connection-pool.ts @@ -21,7 +21,7 @@ export interface ConnectionTypeEvents { unknownMessage: (obj: Array) => void; } -export interface ConnectionSubscription {} +export interface ConnectionSubscription { } /** * Basic relay connection @@ -93,15 +93,14 @@ export type ConnectionBuilder = ( address: string, options: RelaySettings, ephemeral: boolean, -) => Promise; +) => Promise | T; /** * Simple connection pool containing connections to multiple nostr relays */ export class DefaultConnectionPool extends EventEmitter - implements ConnectionPool -{ + implements ConnectionPool { #system: SystemInterface; #log = debug("ConnectionPool"); @@ -122,7 +121,7 @@ export class DefaultConnectionPool this.#connectionBuilder = builder; } else { this.#connectionBuilder = (addr, options, ephemeral) => { - return Promise.resolve(new Connection(addr, options, ephemeral) as unknown as T); + return new Connection(addr, options, ephemeral) as unknown as T; }; } } diff --git a/packages/system/src/connection.ts b/packages/system/src/connection.ts index 2fda8686..93570609 100644 --- a/packages/system/src/connection.ts +++ b/packages/system/src/connection.ts @@ -43,6 +43,7 @@ export class Connection extends EventEmitter implements Co #closing = false; #downCount = 0; #activeRequests = new Set(); + #connectStarted = false; id: string; readonly address: string; @@ -85,6 +86,10 @@ export class Connection extends EventEmitter implements Co return this.Socket?.readyState === WebSocket.OPEN; } + get isConnecting() { + return this.Socket?.readyState === WebSocket.CONNECTING; + } + get isDown() { return this.#downCount > 0; } @@ -95,9 +100,12 @@ export class Connection extends EventEmitter implements Co async connect() { // already connected - if (this.isOpen) return; + if (this.isOpen || this.isConnecting) return; // wait for re-connect timer if (this.ReconnectTimer) return; + // prevent race condition + if (this.#connectStarted) return; + this.#connectStarted = true; try { if (this.info === undefined) { @@ -138,6 +146,7 @@ export class Connection extends EventEmitter implements Co this.Socket.onmessage = e => this.#onMessage(e); this.Socket.onerror = e => this.#onError(e); this.Socket.onclose = e => this.#onClose(e); + this.#connectStarted = false; } close() {