forked from flaviostutz/promster
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: Add retry mechanism to Promster with backoff utility
- Loading branch information
Showing
4 changed files
with
180 additions
and
94 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
package util | ||
|
||
import ( | ||
"context" | ||
"github.com/cenkalti/backoff/v5" | ||
"time" | ||
) | ||
|
||
// RetryConfig provides standard retry configurations | ||
type RetryConfig struct { | ||
InitialInterval time.Duration | ||
MaxInterval time.Duration | ||
MaxElapsedTime time.Duration | ||
RandomizationFactor float64 | ||
} | ||
|
||
var ( | ||
// EtcdRetry is configured for etcd operations | ||
EtcdRetry = RetryConfig{ | ||
InitialInterval: 500 * time.Millisecond, | ||
MaxInterval: 10 * time.Second, | ||
RandomizationFactor: 0.1, | ||
} | ||
|
||
// ConfigRetry is configured for Prometheus configuration operations | ||
ConfigRetry = RetryConfig{ | ||
InitialInterval: 1 * time.Second, | ||
MaxInterval: 5 * time.Second, | ||
RandomizationFactor: 0.1, | ||
} | ||
) | ||
|
||
// RetryOperation executes an operation with retry logic | ||
func RetryOperation[T any](operation func() (T, error), config RetryConfig, maxRetries uint) (T, error) { | ||
b := backoff.NewExponentialBackOff() | ||
b.InitialInterval = config.InitialInterval | ||
b.MaxInterval = config.MaxInterval | ||
b.RandomizationFactor = config.RandomizationFactor | ||
|
||
var result T | ||
ctx := context.Background() | ||
|
||
result, err := backoff.Retry( | ||
ctx, | ||
operation, | ||
backoff.WithMaxTries(maxRetries), | ||
backoff.WithBackOff(b), | ||
) | ||
|
||
return result, err | ||
} |