// Package retry holds the waiting rules that the background workers share: // a capped exponential backoff with jitter and a context-aware sleep. package retry import ( "context" "math/rand/v2" "time" ) // Backoff is a capped exponential delay with equal jitter: the ceiling starts // at Initial, doubles with every consecutive failure, and stops at Max; the // delay is half the ceiling plus a random share of the other half. The fixed // half keeps retries from hammering a recovering dependency, and the random // half spreads several workers apart. type Backoff struct { Initial time.Duration Max time.Duration // jitter returns a value in [0, limit]. Tests replace it. jitter func(limit time.Duration) time.Duration } // Delay returns the wait before the next attempt after failures consecutive // failures. failures below 1 count as 1. func (backoff Backoff) Delay(failures int) time.Duration { ceiling := min(backoff.Initial, backoff.Max) for attempt := 1; attempt < failures && ceiling < backoff.Max; attempt++ { ceiling = min(ceiling*2, backoff.Max) } half := ceiling / 2 jitter := backoff.jitter if jitter == nil { jitter = randomJitter } return half + jitter(ceiling-half) } func randomJitter(limit time.Duration) time.Duration { if limit <= 0 { return 0 } return rand.N(limit + 1) //nolint:gosec // Retry jitter needs no cryptographic randomness. } // Wait sleeps for delay and reports false when ctx ends first. A zero delay // still reports a canceled context. func Wait(ctx context.Context, delay time.Duration) bool { if delay <= 0 { return ctx.Err() == nil } timer := time.NewTimer(delay) defer timer.Stop() select { case <-ctx.Done(): return false case <-timer.C: return true } }