From 33b11cbde608210bab4bdc216748fd3708bb8fff Mon Sep 17 00:00:00 2001 From: Derrick Hammer Date: Thu, 6 Apr 2023 13:16:46 -0400 Subject: [PATCH] *In getSwarm and swarm init, await on .opened to ensure we are ready, only when we have an active relay *Only set mux.syncState if not previously set *change mux.syncState to emit syncProtomux *ensure the state data are numbers *check for undefined in the state data --- src/index.ts | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/src/index.ts b/src/index.ts index 2769296..0e4660f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -12,6 +12,7 @@ import { logErr } from "libkmodule/dist"; // @ts-ignore import Protomux from "protomux"; import { Mutex } from "async-mutex"; +import defer from "p-defer"; const MAX_PEER_LISTENERS = 20; @@ -225,9 +226,16 @@ async function getSwarm(aq: ActiveQuery): Promise { } if (!swarm) { + if (defaultSwarm.activeRelay && defaultSwarm.ready) { + await defaultSwarm.activeRelay.dht._protocol.opened; + } return defaultSwarm; } + if (swarm.activeRelay && swarm.ready) { + await swarm.activeRelay.dht._protocol.opened; + } + return swarmInstances.get(swarm) as Hyperswarm; } @@ -330,9 +338,11 @@ async function handleReady(aq: ActiveQuery) { if (swarm.activeRelay && swarm.ready) { aq.respond(); + await swarm.activeRelay.dht._protocol.opened; return; } - swarm.once("ready", () => { + swarm.once("ready", async () => { + await swarm.activeRelay.dht._protocol.opened; aq.respond(); }); } @@ -426,9 +436,9 @@ async function handleSyncProtomux(aq: ActiveQuery) { const sync = () => send(mux); - mux.syncState = send.bind(undefined, mux); - - sync(); + if (!mux.syncState) { + mux.syncState = socket.emit.bind(socket, "syncProtomux"); + } socket.on("syncProtomux", sync); @@ -438,12 +448,13 @@ async function handleSyncProtomux(aq: ActiveQuery) { ["remote", "local"].forEach((field) => { const rField = `_${field}`; data[field].forEach((item: any) => { - if (!mux[rField][item]) { + item = parseInt(item); + if (typeof mux[rField][item] === "undefined") { while (item > mux[rField].length) { mux[rField].push(null); } } - if (!mux[rField][item]) { + if (typeof mux[rField][item] === "undefined") { mux[rField][item] = null; } });