forked from mtusi2026/mtusi2026lab7
на оценку 4
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RetryDelay returns exponential backoff with deterministic per-job jitter in
|
||||
// [0.5, 1.5). Determinism makes retries reproducible while still avoiding a
|
||||
// synchronized retry wave across different jobs.
|
||||
func RetryDelay(jobID string, nextAttempt int, base, maximum time.Duration) time.Duration {
|
||||
if base <= 0 {
|
||||
base = time.Millisecond
|
||||
}
|
||||
if maximum < base {
|
||||
maximum = base
|
||||
}
|
||||
exponent := nextAttempt - 2
|
||||
if exponent < 0 {
|
||||
exponent = 0
|
||||
}
|
||||
delay := base
|
||||
for index := 0; index < exponent && delay < maximum; index++ {
|
||||
if delay > maximum/2 {
|
||||
delay = maximum
|
||||
break
|
||||
}
|
||||
delay *= 2
|
||||
}
|
||||
if delay > maximum {
|
||||
delay = maximum
|
||||
}
|
||||
sum := sha256.Sum256([]byte(jobID + ":" + strconv.Itoa(nextAttempt)))
|
||||
fraction := float64(binary.BigEndian.Uint64(sum[:8])) / float64(^uint64(0))
|
||||
jittered := time.Duration(float64(delay) * (0.5 + fraction))
|
||||
if jittered > maximum {
|
||||
return maximum
|
||||
}
|
||||
if jittered < time.Millisecond {
|
||||
return time.Millisecond
|
||||
}
|
||||
return jittered
|
||||
}
|
||||
Reference in New Issue
Block a user