Skip to content

Commit d558858

Browse files
committed
feat(bunker): publish bunker connect responses concurrently
- Introduce goroutines to handle concurrent publishing to target relays. - Use `sync/atomic` for thread-safe success counter tracking - Add `WaitGroup` to ensure all goroutines complete before proceeding.
1 parent 5894b5a commit d558858

1 file changed

Lines changed: 20 additions & 12 deletions

File tree

bunker.go

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313
"slices"
1414
"strings"
1515
"sync"
16+
"sync/atomic"
1617
"time"
1718

1819
"fiatjaf.com/nostr"
@@ -466,6 +467,7 @@ var bunker = &cli.Command{
466467
log("Subscription updated to include new relays\n")
467468
}
468469

470+
// Prepare the response payload
469471
responsePayload := nip46.Response{
470472
ID: secret,
471473
Result: "ack",
@@ -507,30 +509,36 @@ var bunker = &cli.Command{
507509
return
508510
}
509511

510-
// Create a fake Kind 24133 connect request to process through the signer
511512
targetRelays := newRelayURLs
512513
if len(targetRelays) == 0 {
513514
targetRelays = relayURLs
514515
}
515516

516517
log("Sending connect response...\n")
517-
successCount := 0
518+
successCount := atomic.Uint32{}
519+
handlerWg.Add(len(targetRelays))
518520
for _, relayURL := range targetRelays {
519-
if relay, _ := sys.Pool.EnsureRelay(relayURL); relay != nil {
520-
err := relay.Publish(ctx, eventResponse)
521-
if err != nil {
522-
log("Failed to publish to %s: %v\n", relayURL, err)
523-
} else {
524-
log("Published connect response to %s\n", color.GreenString(relayURL))
525-
successCount++
521+
go func(relayURL string) {
522+
if relay, _ := sys.Pool.EnsureRelay(relayURL); relay != nil {
523+
err := relay.Publish(ctx, eventResponse)
524+
printLock.Lock()
525+
if err != nil {
526+
log("Failed to publish to %s: %v\n", relayURL, err)
527+
} else {
528+
log("Published connect response to %s\n", color.GreenString(relayURL))
529+
successCount.Add(1)
530+
}
531+
printLock.Unlock()
532+
handlerWg.Done()
526533
}
527-
}
534+
}(relayURL)
528535
}
536+
handlerWg.Wait()
529537

530-
if successCount == 0 {
538+
if successCount.Load() == 0 {
531539
log("Error: Failed to publish connect response to any relay\n")
532540
} else {
533-
log(color.GreenString("\nConnect response sent successfully to %d relay(s)!\n"), successCount)
541+
log(color.GreenString("\nConnect response sent successfully to %d relay(s)!\n"), successCount.Load())
534542
}
535543
}
536544

0 commit comments

Comments
 (0)