From 2d92c1361388635d38d0eea2dd08fb089c6e1807 Mon Sep 17 00:00:00 2001 From: Jonathan Staab Date: Sat, 21 Jan 2023 14:44:09 -0800 Subject: [PATCH] Fix onEvent when fast relays are combined with slow ones --- README.md | 1 + src/agent/pool.js | 53 +++++++++++++++++++++++++++++++----------- src/routes/Chat.svelte | 2 +- 3 files changed, 42 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 89623f4e..475fee87 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,7 @@ If you like Coracle and want to support its development, you can donate sats via # Bugs +- [ ] Alerts are not showing likes, just generally screwy. Maybe because I threadify before adding to the db? - [ ] Sync mentions box and in-reply mentions - [ ] Add petnames for channels - [ ] Add notifications for chat messages diff --git a/src/agent/pool.js b/src/agent/pool.js index 4016b1f5..e6c52382 100644 --- a/src/agent/pool.js +++ b/src/agent/pool.js @@ -117,6 +117,12 @@ const subscribe = async (relays, filters) => { filters.map(describeFilter).join(':'), ].join('-') + const seen = new Set() + const eose = [] + const events = [] + let onEvent + let onEose + const subs = filter(identity, await Promise.all( relays.map(async relay => { const conn = await connect(relay.url) @@ -128,6 +134,30 @@ const subscribe = async (relays, filters) => { const sub = conn.nostr.sub(filters, {id}) + // Subscribe to events immediately so we don't miss any while we + // wait for slow relays to connect + sub.on('event', e => { + if (!seen.has(e.id)) { + e.seen_on = sub.conn.url + seen.add(e.id) + + if (onEvent) { + onEvent(e) + } else { + events.push(e) + } + } + }) + + // Same thing for eose + sub.on('eose', () => { + if (onEose) { + onEose(conn.url) + } else { + eose.push(conn.url) + } + }) + sub.conn = conn sub.conn.stats.activeCount += 1 @@ -139,7 +169,6 @@ const subscribe = async (relays, filters) => { }) )) - const seen = new Set() return { subs, @@ -153,20 +182,18 @@ const subscribe = async (relays, filters) => { }) }, onEvent: cb => { - subs.forEach(sub => { - sub.on('event', e => { - if (!seen.has(e.id)) { - e.seen_on = sub.conn.url - seen.add(e.id) - cb(e) - } - }) - }) + // Report our buffered events + events.splice(0).forEach(e => cb(e)) + + // Add our listener for future ones + onEvent = cb }, onEose: cb => { - subs.forEach(sub => { - sub.on('eose', () => cb(sub.conn.url)) - }) + // Report our buffered eoses + eose.splice(0).forEach(e => cb(e)) + + // Add our listener for future ones + onEose = cb }, } } diff --git a/src/routes/Chat.svelte b/src/routes/Chat.svelte index 3327b3cc..b52a1289 100644 --- a/src/routes/Chat.svelte +++ b/src/routes/Chat.svelte @@ -1,5 +1,5 @@