diff --git a/packages/system/src/connection.ts b/packages/system/src/connection.ts index a1e10745..33cb8301 100644 --- a/packages/system/src/connection.ts +++ b/packages/system/src/connection.ts @@ -1,7 +1,7 @@ import { v4 as uuid } from "uuid"; import debug from "debug"; import WebSocket from "isomorphic-ws"; -import { unwrap, ExternalStore, unixNowMs, dedupe } from "@snort/shared"; +import { ExternalStore, unixNowMs, dedupe } from "@snort/shared"; import { DefaultConnectTimeout } from "./const"; import { ConnectionStats } from "./connection-stats"; @@ -51,6 +51,7 @@ export class Connection extends ExternalStore { #ephemeralCheck?: ReturnType; #activity: number = unixNowMs(); #expectAuth = false; + #ephemeral: boolean; Id: string; Address: string; @@ -78,7 +79,6 @@ export class Connection extends ExternalStore { Auth?: AuthHandler; AwaitingAuth: Map; Authed = false; - Ephemeral: boolean; Down = true; constructor(addr: string, options: RelaySettings, auth?: AuthHandler, ephemeral: boolean = false) { @@ -90,10 +90,19 @@ export class Connection extends ExternalStore { this.EventsCallback = new Map(); this.AwaitingAuth = new Map(); this.Auth = auth; - this.Ephemeral = ephemeral; + this.#ephemeral = ephemeral; this.#log = debug("Connection").extend(addr); } + get Ephemeral() { + return this.#ephemeral; + } + + set Ephemeral(v: boolean) { + this.#ephemeral = v; + this.#setupEphemeral(); + } + async Connect() { try { if (this.Info === undefined) { @@ -460,11 +469,11 @@ export class Connection extends ExternalStore { } #setupEphemeral() { + if (this.#ephemeralCheck) { + clearInterval(this.#ephemeralCheck); + this.#ephemeralCheck = undefined; + } if (this.Ephemeral) { - if (this.#ephemeralCheck) { - clearInterval(this.#ephemeralCheck); - this.#ephemeralCheck = undefined; - } this.#ephemeralCheck = setInterval(() => { const lastActivity = unixNowMs() - this.#activity; if (lastActivity > 30_000 && !this.IsClosed) { diff --git a/packages/system/src/nostr-system.ts b/packages/system/src/nostr-system.ts index e4428f8f..83529d40 100644 --- a/packages/system/src/nostr-system.ts +++ b/packages/system/src/nostr-system.ts @@ -147,7 +147,8 @@ export class NostrSystem extends ExternalStore implements System async ConnectToRelay(address: string, options: RelaySettings) { try { const addr = unwrap(sanitizeRelayUrl(address)); - if (!this.#sockets.has(addr)) { + const existing = this.#sockets.get(addr); + if (!existing) { const c = new Connection(addr, options, this.#handleAuth?.bind(this)); this.#sockets.set(addr, c); c.OnEvent = (s, e) => this.#onEvent(s, e); @@ -157,7 +158,8 @@ export class NostrSystem extends ExternalStore implements System await c.Connect(); } else { // update settings if already connected - unwrap(this.#sockets.get(addr)).Settings = options; + existing.Settings = options; + existing.Ephemeral = false; } } catch (e) { console.error(e);