From f4ab599bd195b52ca105feb19969f6b7154436a0 Mon Sep 17 00:00:00 2001 From: Andre Staltz Date: Sat, 16 Dec 2023 16:55:45 +0200 Subject: [PATCH] support start() before peers connect --- lib/index.js | 7 ++++++- lib/stream.js | 7 +++++++ test/account-sync.test.js | 9 ++++++--- 3 files changed, 19 insertions(+), 4 deletions(-) diff --git a/lib/index.js b/lib/index.js index 132ed82..d0f16a0 100644 --- a/lib/index.js +++ b/lib/index.js @@ -67,6 +67,7 @@ function initSync(peer, config) { assertSHSEExists(peer) const debug = makeDebug(`ppppp:sync`) const algo = new Algorithm(peer) + let started = false const streams = /** @type {Array} */ ([]) @@ -92,7 +93,8 @@ function initSync(peer, config) { assertSHSEExists(peer) if (rpc.shse.pubkey === peer.shse.pubkey) return // connecting to myself if (!iamClient) return - const local = toPull.duplex(createStream(rpc.shse.pubkey, true)) + const stream = createStream(rpc.shse.pubkey, true) + const local = toPull.duplex(stream) let abort = /** @type {CallableFunction | null} */ (null) const remote = rpc.sync.connect((networkError) => { @@ -108,6 +110,7 @@ function initSync(peer, config) { } }) abort = pull(local, remote, local) + if (started) stream.initiate() } peer.on('rpc:connect', onSyncRPCConnect) @@ -119,6 +122,8 @@ function initSync(peer, config) { } function start() { + if (started) return + started = true for (const stream of streams) { stream.initiate() } diff --git a/lib/stream.js b/lib/stream.js index 81749ad..af4fbee 100644 --- a/lib/stream.js +++ b/lib/stream.js @@ -105,6 +105,13 @@ class SyncStream extends Pipeable { this.#requested.add(goal.id) } this.resume() + + this.#goals.watch((/** @type {any} */ goal) => { + if (!this.#requested.has(goal.id)) { + this.#requested.add(goal.id) + this.resume() + } + }) } #canSend() { diff --git a/test/account-sync.test.js b/test/account-sync.test.js index 384cb96..06c9da7 100644 --- a/test/account-sync.test.js +++ b/test/account-sync.test.js @@ -51,13 +51,16 @@ test('sync an account tangle', async (t) => { "bob doesn't have alice's account tangle" ) - bob.goals.set(aliceID, 'all') - alice.goals.set(aliceID, 'all') + // start() on purpose before connect, to test whether this also works + bob.sync.start() const remoteAlice = await p(bob.connect)(alice.getAddress()) assert('bob connected to alice') - bob.sync.start() + // Set goals on purpose after connect, to test whether this also works + bob.goals.set(aliceID, 'all') + alice.goals.set(aliceID, 'all') + await p(setTimeout)(1000) assert('sync!')