fix async race condition that caused pool.publish() callbacks to not be called.

fixes https://github.com/nbd-wtf/nostr-tools/issues/169
This commit is contained in:
fiatjaf 2023-04-04 10:23:26 -03:00
parent f1eb9a3bc7
commit 9ee58bd6c7
No known key found for this signature in database
GPG Key ID: BAD43C4BE5C1A3A1
1 changed files with 22 additions and 8 deletions

30
pool.ts
View File

@ -159,22 +159,36 @@ export class SimplePool {
}
publish(relays: string[], event: Event): Pub {
const pubs: Pub[] = []
relays.forEach(async relay => {
const pubPromises: Promise<Pub>[] = relays.map(async relay => {
let r
try {
r = await this.ensureRelay(relay)
pubs.push(r.publish(event))
} catch (_) {}
return r.publish(event)
} catch (_) {
return {on() {}, off() {}}
}
})
const callbackMap = new Map()
return {
on(type, cb) {
pubs.forEach((pub, i) => {
pub.on(type, () => cb(relays[i]))
relays.forEach(async (relay, i) => {
let pub = await pubPromises[i]
let callback = () => cb(relay)
callbackMap.set(cb, callback)
pub.on(type, callback)
})
},
off() {
// do nothing here, FIXME
off(type, cb) {
relays.forEach(async (_, i) => {
let callback = callbackMap.get(cb)
if (callback) {
let pub = await pubPromises[i]
pub.off(type, callback)
}
})
}
}
}