Initial code commit
This commit is contained in:
53
pkg/utils/retry.go
Normal file
53
pkg/utils/retry.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func RetryWithBackoff(maxAttempts int, initialDelay time.Duration, fn func() error) error {
|
||||
var lastErr error
|
||||
delay := initialDelay
|
||||
|
||||
for attempt := 1; attempt <= maxAttempts; attempt++ {
|
||||
err := fn()
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
lastErr = err
|
||||
|
||||
if attempt < maxAttempts {
|
||||
time.Sleep(delay)
|
||||
delay *= 2
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("max attempts (%d) reached, last error: %w", maxAttempts, lastErr)
|
||||
}
|
||||
|
||||
func RetryWithExponentialBackoff(maxAttempts int, initialDelay, maxDelay time.Duration, fn func() error) error {
|
||||
var lastErr error
|
||||
delay := initialDelay
|
||||
|
||||
for attempt := 1; attempt <= maxAttempts; attempt++ {
|
||||
err := fn()
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
lastErr = err
|
||||
|
||||
if attempt < maxAttempts {
|
||||
time.Sleep(delay)
|
||||
if delay < maxDelay {
|
||||
delay *= 2
|
||||
if delay > maxDelay {
|
||||
delay = maxDelay
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("max attempts (%d) reached, last error: %w", maxAttempts, lastErr)
|
||||
}
|
||||
Reference in New Issue
Block a user