retrier.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Package retrier implements the "retriable" resiliency pattern for Go.
  2. package retrier
  3. import (
  4. "math/rand"
  5. "time"
  6. )
  7. // Retrier implements the "retriable" resiliency pattern, abstracting out the process of retrying a failed action
  8. // a certain number of times with an optional back-off between each retry.
  9. type Retrier struct {
  10. backoff []time.Duration
  11. class Classifier
  12. jitter float64
  13. rand *rand.Rand
  14. }
  15. // New constructs a Retrier with the given backoff pattern and classifier. The length of the backoff pattern
  16. // indicates how many times an action will be retried, and the value at each index indicates the amount of time
  17. // waited before each subsequent retry. The classifier is used to determine which errors should be retried and
  18. // which should cause the retrier to fail fast. The DefaultClassifier is used if nil is passed.
  19. func New(backoff []time.Duration, class Classifier) *Retrier {
  20. if class == nil {
  21. class = DefaultClassifier{}
  22. }
  23. return &Retrier{
  24. backoff: backoff,
  25. class: class,
  26. rand: rand.New(rand.NewSource(time.Now().UnixNano())),
  27. }
  28. }
  29. // Run executes the given work function, then classifies its return value based on the classifier used
  30. // to construct the Retrier. If the result is Succeed or Fail, the return value of the work function is
  31. // returned to the caller. If the result is Retry, then Run sleeps according to the its backoff policy
  32. // before retrying. If the total number of retries is exceeded then the return value of the work function
  33. // is returned to the caller regardless.
  34. func (r *Retrier) Run(work func() error) error {
  35. retries := 0
  36. for {
  37. ret := work()
  38. switch r.class.Classify(ret) {
  39. case Succeed, Fail:
  40. return ret
  41. case Retry:
  42. if retries >= len(r.backoff) {
  43. return ret
  44. }
  45. time.Sleep(r.calcSleep(retries))
  46. retries++
  47. }
  48. }
  49. }
  50. func (r *Retrier) calcSleep(i int) time.Duration {
  51. // take a random float in the range (-r.jitter, +r.jitter) and multiply it by the base amount
  52. return r.backoff[i] + time.Duration(((r.rand.Float64()*2)-1)*r.jitter*float64(r.backoff[i]))
  53. }
  54. // SetJitter sets the amount of jitter on each back-off to a factor between 0.0 and 1.0 (values outside this range
  55. // are silently ignored). When a retry occurs, the back-off is adjusted by a random amount up to this value.
  56. func (r *Retrier) SetJitter(jit float64) {
  57. if jit < 0 || jit > 1 {
  58. return
  59. }
  60. r.jitter = jit
  61. }