Skip to content

Commit

Permalink
feat: reconnect immediately on first retry (#338)
Browse files Browse the repository at this point in the history
* feat: reconnect immediately on first retry

* chore: use waitToReconnectSeconds

* chore: code cleanup, add exponential backoff for relay connection

---------

Co-authored-by: Roland Bewick <[email protected]>
  • Loading branch information
im-adithya and rolznz committed Aug 2, 2024
1 parent 41d814a commit 0327150
Showing 1 changed file with 20 additions and 7 deletions.
27 changes: 20 additions & 7 deletions service/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,35 +46,48 @@ func (svc *service) startNostr(ctx context.Context, encryptionKey string) error
defer svc.wg.Done()
//Start infinite loop which will be only broken by canceling ctx (SIGINT)
var relay *nostr.Relay
waitToReconnectSeconds := 0

for i := 0; ; i++ {
// wait for a delay before retrying except on first iteration
if i > 0 {
sleepDuration := 10

// wait for a delay if any before retrying
if waitToReconnectSeconds > 0 {
contextCancelled := false
logger.Logger.Infof("[Iteration %d] Retrying in %d seconds...", i, sleepDuration)

select {
case <-ctx.Done(): //context cancelled
logger.Logger.Info("service context cancelled while waiting for retry")
contextCancelled = true
case <-time.After(time.Duration(sleepDuration) * time.Second): //timeout
case <-time.After(time.Duration(waitToReconnectSeconds) * time.Second): //timeout
}
if contextCancelled {
break
}
}

closeRelay(relay)

//connect to the relay
logger.Logger.Infof("Connecting to the relay: %s", relayUrl)
logger.Logger.WithFields(logrus.Fields{
"relay_url": relayUrl,
"iteration": i,
}).Info("Connecting to the relay")

relay, err = nostr.RelayConnect(ctx, relayUrl, nostr.WithNoticeHandler(svc.noticeHandler))
if err != nil {
logger.Logger.WithError(err).Error("Failed to connect to relay")
// exponential backoff from 2 - 60 seconds
waitToReconnectSeconds = max(waitToReconnectSeconds, 1)
waitToReconnectSeconds *= 2
waitToReconnectSeconds = min(waitToReconnectSeconds, 60)
logger.Logger.WithFields(logrus.Fields{
"iteration": i,
"retry_seconds": waitToReconnectSeconds,
}).WithError(err).Error("Failed to connect to relay")
continue
}

waitToReconnectSeconds = 0

//publish event with NIP-47 info
err = svc.nip47Service.PublishNip47Info(ctx, relay, svc.lnClient)
if err != nil {
Expand Down

0 comments on commit 0327150

Please sign in to comment.