github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/go-grpc-middleware/retry/backoff.go (about) 1 // Copyright 2016 Michal Witkowski. All Rights Reserved. 2 // See LICENSE for licensing terms. 3 4 package grpc_retry 5 6 import ( 7 "time" 8 9 "github.com/hxx258456/ccgo/go-grpc-middleware/util/backoffutils" 10 ) 11 12 // BackoffLinear is very simple: it waits for a fixed period of time between calls. 13 func BackoffLinear(waitBetween time.Duration) BackoffFunc { 14 return func(attempt uint) time.Duration { 15 return waitBetween 16 } 17 } 18 19 // BackoffLinearWithJitter waits a set period of time, allowing for jitter (fractional adjustment). 20 // 21 // For example waitBetween=1s and jitter=0.10 can generate waits between 900ms and 1100ms. 22 func BackoffLinearWithJitter(waitBetween time.Duration, jitterFraction float64) BackoffFunc { 23 return func(attempt uint) time.Duration { 24 return backoffutils.JitterUp(waitBetween, jitterFraction) 25 } 26 } 27 28 // BackoffExponential produces increasing intervals for each attempt. 29 // 30 // The scalar is multiplied times 2 raised to the current attempt. So the first 31 // retry with a scalar of 100ms is 100ms, while the 5th attempt would be 3.2s. 32 func BackoffExponential(scalar time.Duration) BackoffFunc { 33 return func(attempt uint) time.Duration { 34 return scalar * time.Duration(backoffutils.ExponentBase2(attempt)) 35 } 36 } 37 38 // BackoffExponentialWithJitter creates an exponential backoff like 39 // BackoffExponential does, but adds jitter. 40 func BackoffExponentialWithJitter(scalar time.Duration, jitterFraction float64) BackoffFunc { 41 return func(attempt uint) time.Duration { 42 return backoffutils.JitterUp(scalar*time.Duration(backoffutils.ExponentBase2(attempt)), jitterFraction) 43 } 44 }