| 1 | package utils |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "time" |
| 7 | |
| 8 | "github.com/sirupsen/logrus" |
| 9 | ) |
| 10 | |
| 11 | const maxRetries = 60 |
| 12 | const initialBackoff = 100 * time.Millisecond |
| 13 | |
| 14 | func Retry[T comparable](ctx context.Context, retryFunc func() (T, error), retryMsg string) (T, error) { |
| 15 | var ( |
| 16 | returnVal T |
| 17 | err error |
| 18 | ) |
| 19 | |
| 20 | backoff := initialBackoff |
| 21 | |
| 22 | loop: |
| 23 | for i := 0; i < maxRetries; i++ { |
| 24 | select { |
| 25 | case <-ctx.Done(): |
| 26 | break loop |
| 27 | default: |
| 28 | |
| 29 | } |
| 30 | |
| 31 | returnVal, err = retryFunc() |
| 32 | if err == nil { |
| 33 | return returnVal, nil |
| 34 | } |
| 35 | logrus.Debugf("%s (%s)", retryMsg, backoff) |
| 36 | Sleep(ctx, backoff) |
| 37 | backoff = backOff(backoff) |
| 38 | } |
| 39 | return returnVal, fmt.Errorf("timeout: %w", err) |
| 40 | } |
| 41 | |
| 42 | func backOff(delay time.Duration) time.Duration { |
| 43 | if delay == 0 { |
| 44 | delay = 5 * time.Millisecond |
| 45 | } else { |
| 46 | delay *= 2 |
| 47 | } |
| 48 | if delay > time.Second { |
| 49 | delay = time.Second |
| 50 | } |
| 51 | return delay |
| 52 | } |
| 53 | |
| 54 | func Sleep(ctx context.Context, wait time.Duration) bool { |
| 55 | select { |
| 56 | case <-ctx.Done(): |
| 57 | return false |
| 58 | case <-time.After(wait): |
| 59 | return true |
| 60 | } |
| 61 | } |