package notification import ( "math/rand/v2" "time" ) // jitterShare is the share of a retry delay that jitter may add: up to a fifth, // so deliveries refused together do not all return in the same second, and // the wait never exceeds a fifth over the schedule. const jitterShare = 5 // RetryPolicy schedules the next attempt of a delivery whose last attempt the // provider refused for a reason that a later attempt may overcome // (temporary or rate_limited), and of a delivery on which the sending worker // itself failed. It is the minimum that the delivery state machine needs, // because a pending delivery must say when it is due; the attempt limit, the // unknown outcome policy, and manual retries are part of the planned delivery retry policy. // // There is no limit on provider refusals on purpose: service mail carries a // token that expires, and the sending worker cancels the delivery with the // reason token_expired once it does, so those retries end by themselves. type RetryPolicy struct { // Initial is the wait after the first refused attempt; every further // refusal doubles it. Initial time.Duration // Max caps the doubling. A longer wait that the provider itself asked // for (Retry-After) is honored as it is. Max time.Duration // Jitter returns a value in [0, limit] that is added to the scheduled // delay, bounded by a fifth of it. Nil means none, which tests use to // get exact times; RandomJitter is the production source. Jitter func(limit time.Duration) time.Duration } // RandomJitter is a uniformly random jitter source. 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. } // NextAttemptAt returns when the delivery is due again after attempt number // attempt (counted from 1) that ended at at. retryAfter is the provider's own // hint, zero when it gave none; the wait is never shorter than it. func (policy RetryPolicy) NextAttemptAt(at time.Time, attempt int32, retryAfter time.Duration) time.Time { delay := policy.Initial for step := int32(1); step < attempt && delay < policy.Max; step++ { delay = min(delay*2, policy.Max) } delay = min(delay, policy.Max) if policy.Jitter != nil { limit := delay / jitterShare delay += min(max(policy.Jitter(limit), 0), limit) } return at.Add(max(delay, retryAfter)) }