bunker: send responses to relays concurrently.

This commit is contained in:
fiatjaf 2024-02-16 11:08:48 -03:00
parent 5dd5a7c699
commit e008e08105
No known key found for this signature in database
GPG Key ID: BAD43C4BE5C1A3A1

View File

@ -5,6 +5,7 @@ import (
"fmt" "fmt"
"net/url" "net/url"
"os" "os"
"sync"
"github.com/fatih/color" "github.com/fatih/color"
"github.com/nbd-wtf/go-nostr" "github.com/nbd-wtf/go-nostr"
@ -85,10 +86,12 @@ var bunker = &cli.Command{
}) })
signer := nip46.NewStaticKeySigner(sec) signer := nip46.NewStaticKeySigner(sec)
handlerWg := sync.WaitGroup{}
printLock := sync.Mutex{}
for ie := range events { for ie := range events {
req, resp, eventResponse, harmless, err := signer.HandleRequest(ie.Event) req, resp, eventResponse, harmless, err := signer.HandleRequest(ie.Event)
if err != nil { if err != nil {
log("< failed to handle request from %s: %s", ie.Event.PubKey, err.Error()) log("< failed to handle request from %s: %s\n", ie.Event.PubKey, err.Error())
continue continue
} }
@ -98,15 +101,23 @@ var bunker = &cli.Command{
log("~ responding with %s\n", string(jresp)) log("~ responding with %s\n", string(jresp))
if alwaysYes || harmless || askProceed(ie.Event.PubKey) { if alwaysYes || harmless || askProceed(ie.Event.PubKey) {
handlerWg.Add(len(relayURLs))
for _, relayURL := range relayURLs { for _, relayURL := range relayURLs {
go func(relayURL string) {
if relay, _ := pool.EnsureRelay(relayURL); relay != nil { if relay, _ := pool.EnsureRelay(relayURL); relay != nil {
if err := relay.Publish(c.Context, eventResponse); err == nil { err := relay.Publish(c.Context, eventResponse)
printLock.Lock()
if err == nil {
log("* sent response through %s\n", relay.URL) log("* sent response through %s\n", relay.URL)
} else { } else {
log("* failed to send response: %s\n", err) log("* failed to send response: %s\n", err)
} }
printLock.Unlock()
handlerWg.Done()
} }
}(relayURL)
} }
handlerWg.Wait()
} }
} }