Skip to content

Commit

Permalink
feat: add exponential backoff to subscriptions
Browse files Browse the repository at this point in the history
  • Loading branch information
im-adithya committed Aug 22, 2024
1 parent f73fec3 commit 2e77c88
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions internal/nostr/nostr.go
Original file line number Diff line number Diff line change
Expand Up @@ -699,6 +699,7 @@ func (svc *Service) startSubscription(ctx context.Context, subscription *Subscri
var relay *nostr.Relay
var isCustomRelay bool
var err error
waitToReconnectSeconds := 0

for {
// close relays with connection errors before connecting again
Expand All @@ -707,14 +708,16 @@ func (svc *Service) startSubscription(ctx context.Context, subscription *Subscri
if relay != nil && isCustomRelay {
relay.Close()
}
time.Sleep(time.Duration(waitToReconnectSeconds) * time.Second)
relay, isCustomRelay, err = svc.getRelayConnection(ctx, subscription.RelayUrl)
if err != nil {
// TODO: notify user about relay failure
svc.Logger.WithError(err).WithFields(logrus.Fields{
"subscription_id": subscription.ID,
"relay_url": subscription.RelayUrl,
}).Error("Failed get relay connection, retrying in 5s...")
time.Sleep(5 * time.Second) // sleep for 5 seconds
}).Errorf("Failed to subscribe to relay, retrying in %vs...", waitToReconnectSeconds)
waitToReconnectSeconds = max(waitToReconnectSeconds, 1)
waitToReconnectSeconds = min(waitToReconnectSeconds * 2, 900)
continue
}

Expand All @@ -724,8 +727,9 @@ func (svc *Service) startSubscription(ctx context.Context, subscription *Subscri
svc.Logger.WithError(err).WithFields(logrus.Fields{
"subscription_id": subscription.ID,
"relay_url": subscription.RelayUrl,
}).Error("Failed to subscribe to relay, retrying in 5s...")
time.Sleep(5 * time.Second) // sleep for 5 seconds
}).Errorf("Failed to subscribe to relay, retrying in %vs...", waitToReconnectSeconds)
waitToReconnectSeconds = max(waitToReconnectSeconds, 1)
waitToReconnectSeconds = min(waitToReconnectSeconds * 2, 900)
continue
}

Expand All @@ -745,8 +749,7 @@ func (svc *Service) startSubscription(ctx context.Context, subscription *Subscri
svc.Logger.WithError(err).WithFields(logrus.Fields{
"subscription_id": subscription.ID,
"relay_url": subscription.RelayUrl,
}).Error("Subscription stopped due to relay error, reconnecting in 5s...")
time.Sleep(5 * time.Second) // sleep for 5 seconds
}).Error("Subscription stopped due to relay error, reconnecting...")
continue
} else {
if isCustomRelay {
Expand Down

0 comments on commit 2e77c88

Please sign in to comment.