|
1 | 1 | package utils |
2 | 2 |
|
3 | 3 | import ( |
4 | | - "strings" |
| 4 | + "fmt" |
5 | 5 | "time" |
6 | 6 |
|
7 | 7 | "github.com/threatwinds/go-sdk/catcher" |
8 | 8 | ) |
9 | 9 |
|
10 | 10 | const ( |
11 | | - wait = 5 * time.Second |
| 11 | + retryInitialBackoff = 5 * time.Second |
| 12 | + retryMaxBackoff = 2 * time.Minute |
| 13 | + retryBackoffMultiplier = 2.0 |
| 14 | + retryLogInterval = 10 |
12 | 15 | ) |
13 | 16 |
|
14 | | -func InfiniteRetryIfXError(f func() error, exceptions ...string) error { |
15 | | - var xErrorWasLogged bool |
| 17 | +func InfiniteRetry(f func() error, operationName string) { |
| 18 | + attempt := 0 |
| 19 | + currentBackoff := retryInitialBackoff |
| 20 | + |
| 21 | + catcher.Info(fmt.Sprintf("Starting %s with infinite retry and exponential backoff", operationName), map[string]any{ |
| 22 | + "initial_backoff": retryInitialBackoff.String(), |
| 23 | + "max_backoff": retryMaxBackoff.String(), |
| 24 | + }) |
16 | 25 |
|
17 | 26 | for { |
| 27 | + attempt++ |
18 | 28 | err := f() |
19 | | - if err != nil && is(err, exceptions...) { |
20 | | - if !xErrorWasLogged { |
21 | | - _ = catcher.Error("An error occurred (%s), will keep retrying indefinitely...", err, nil) |
22 | | - xErrorWasLogged = true |
23 | | - } |
24 | | - time.Sleep(wait) |
25 | | - continue |
26 | | - } |
27 | 29 |
|
28 | | - return err |
29 | | - } |
30 | | -} |
| 30 | + if err == nil { |
| 31 | + catcher.Info(fmt.Sprintf("%s completed successfully", operationName), map[string]any{ |
| 32 | + "attempts": attempt, |
| 33 | + }) |
| 34 | + return |
| 35 | + } |
31 | 36 |
|
32 | | -func is(e error, args ...string) bool { |
33 | | - for _, arg := range args { |
34 | | - if strings.Contains(e.Error(), arg) { |
35 | | - return true |
| 37 | + if attempt == 1 || attempt%retryLogInterval == 0 { |
| 38 | + _ = catcher.Error(fmt.Sprintf("%s failed, will retry indefinitely...", operationName), err, map[string]any{ |
| 39 | + "attempt": attempt, |
| 40 | + "next_retry_in": currentBackoff.String(), |
| 41 | + }) |
36 | 42 | } |
| 43 | + |
| 44 | + time.Sleep(currentBackoff) |
| 45 | + |
| 46 | + currentBackoff = min(time.Duration(float64(currentBackoff)*retryBackoffMultiplier), retryMaxBackoff) |
37 | 47 | } |
38 | | - return false |
39 | 48 | } |
0 commit comments