mirror of
https://github.com/netbirdio/netbird.git
synced 2024-12-12 18:00:49 +01:00
d1a323fa9d
* Add gocritic linter `gocritic` provides diagnostics that check for bugs, performance, and style issues We disable the following checks: - commentFormatting - captLocal - deprecatedComment This PR contains many `//nolint:gocritic` to disable `appendAssign`.
33 lines
643 B
Go
33 lines
643 B
Go
package util
|
|
|
|
import (
|
|
"math/rand"
|
|
"time"
|
|
)
|
|
|
|
// Retry retries a given toExec function calling onError on failed attempts
|
|
// onError shouldn be a lightweight function and shouldn't be blocking
|
|
func Retry(attempts int, sleep time.Duration, toExec func() error, onError func(e error)) error {
|
|
if err := toExec(); err != nil {
|
|
if s, ok := err.(stop); ok {
|
|
return s.error
|
|
}
|
|
|
|
if attempts--; attempts > 0 {
|
|
jitter := time.Duration(rand.Int63n(int64(sleep)))
|
|
sleep += jitter / 2
|
|
|
|
onError(err)
|
|
time.Sleep(sleep)
|
|
return Retry(attempts, 2*sleep, toExec, onError)
|
|
}
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
type stop struct {
|
|
error
|
|
}
|