54 lines
985 B
Go
54 lines
985 B
Go
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)
|
|
}
|