prevent blocking waiting times on publish (unless "wait" is set in the pool policy).

This commit is contained in:
fiatjaf
2022-01-12 17:39:24 -03:00
parent e3631ba806
commit 3d6f9a41e0
2 changed files with 34 additions and 21 deletions

View File

@@ -1,6 +1,6 @@
{ {
"name": "nostr-tools", "name": "nostr-tools",
"version": "0.17.0", "version": "0.18.0",
"description": "Tools for making a Nostr client.", "description": "Tools for making a Nostr client.",
"repository": { "repository": {
"type": "git", "type": "git",

21
pool.js
View File

@@ -6,7 +6,11 @@ export function relayPool() {
const poolPolicy = { const poolPolicy = {
// setting this to a number will cause events to be published to a random // setting this to a number will cause events to be published to a random
// set of relays only, instead of publishing to all relays all the time // set of relays only, instead of publishing to all relays all the time
randomChoice: null randomChoice: null,
// setting this to true will cause .publish() calls to wait until the event has
// been published -- or at least attempted to be published -- to all relays
wait: false
} }
const relays = {} const relays = {}
const noticeCallbacks = [] const noticeCallbacks = []
@@ -111,7 +115,7 @@ export function relayPool() {
let index = noticeCallbacks.indexOf(cb) let index = noticeCallbacks.indexOf(cb)
if (index !== -1) noticeCallbacks.splice(index, 1) if (index !== -1) noticeCallbacks.splice(index, 1)
}, },
async publish(event, statusCallback = (status, relayURL) => {}) { async publish(event, statusCallback) {
event.id = getEventHash(event) event.id = getEventHash(event)
if (!event.sig) { if (!event.sig) {
@@ -136,6 +140,7 @@ export function relayPool() {
let successes = 0 let successes = 0
if (poolPolicy.wait) {
for (let i = 0; i < writeable.length; i++) { for (let i = 0; i < writeable.length; i++) {
let {relay} = writeable[i] let {relay} = writeable[i]
@@ -143,11 +148,11 @@ export function relayPool() {
await new Promise(async (resolve, reject) => { await new Promise(async (resolve, reject) => {
try { try {
await relay.publish(event, status => { await relay.publish(event, status => {
statusCallback(status, relay.url) if (statusCallback) statusCallback(status, relay.url)
resolve() resolve()
}) })
} catch (err) { } catch (err) {
statusCallback(-1, relay.url) if (statusCallback) statusCallback(-1, relay.url)
} }
}) })
@@ -159,6 +164,14 @@ export function relayPool() {
/***/ /***/
} }
} }
} else {
writeable.forEach(async ({relay}) => {
let callback = statusCallback
? status => statusCallback(status, relay.url)
: null
relay.publish(event, callback)
})
}
return event return event
} }