Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions internal/nostr/subscriptions.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,11 +101,25 @@ func sleepCtx(ctx context.Context, d time.Duration) bool {
// resubscribeDelay returns the randomised delay for the given attempt, where
// attempt is 1 for the first retry. The window doubles per attempt up to
// resubscribeMaxDelay; the returned value is uniform within it.
//
// Both bounds are enforced here rather than left to callers. attempt < 1 would
// shift by a negative amount and rand.Int63n requires a positive argument, and
// either one panics rather than degrading. An unrecovered panic in a
// subscription goroutine takes the process down, which drops every
// subscription at once - the synchronised reconnect this backoff exists to
// prevent.
func resubscribeDelay(attempt int) time.Duration {
if attempt < 1 {
attempt = 1
}

window := resubscribeBaseDelay << min(attempt-1, 5)
if window > resubscribeMaxDelay {
window = resubscribeMaxDelay
}
if window <= 0 {
return 0
}

return time.Duration(rand.Int63n(int64(window)))
}
Expand Down
20 changes: 20 additions & 0 deletions internal/nostr/subscriptions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,26 @@ func TestResubscribeDelayStaysWithinWindow(t *testing.T) {
}
}

// attempt values below 1 would shift by a negative amount, which panics at
// runtime rather than returning a bad value. Nothing calls it that way today,
// but the guard against it lives here rather than in the callers.
func TestResubscribeDelayHandlesAttemptsBelowOne(t *testing.T) {
for _, attempt := range []int{0, -1, -1000} {
func() {
defer func() {
if r := recover(); r != nil {
t.Fatalf("resubscribeDelay(%d) panicked: %v", attempt, r)
}
}()

got := resubscribeDelay(attempt)
if got < 0 || got >= resubscribeBaseDelay {
t.Fatalf("resubscribeDelay(%d) = %v, want within [0, %v)", attempt, got, resubscribeBaseDelay)
}
}()
}
}

func TestResubscribeDelayGrowsWithAttempts(t *testing.T) {
// Compare means rather than single draws, which are random by design.
mean := func(attempt int) time.Duration {
Expand Down
Loading