Files
trivy/pkg/rpc/retry.go
Teppei Fukuda 94d6e8ced6 refactor: replace zap with slog (#6466)
Signed-off-by: knqyf263 <knqyf263@gmail.com>
Co-authored-by: Nikita Pivkin <nikita.pivkin@smartforce.io>
Co-authored-by: simar7 <1254783+simar7@users.noreply.github.com>
2024-04-11 18:59:09 +00:00

43 lines
819 B
Go

package rpc
import (
"time"
"github.com/cenkalti/backoff"
"github.com/twitchtv/twirp"
"github.com/aquasecurity/trivy/pkg/log"
)
const (
maxRetries = 10
)
// Retry executes the function again using backoff until maxRetries or success
func Retry(f func() error) error {
operation := func() error {
err := f()
if err != nil {
twerr, ok := err.(twirp.Error)
if !ok {
return backoff.Permanent(err)
}
if twerr.Code() == twirp.Unavailable {
return err
}
return backoff.Permanent(err)
}
return nil
}
b := backoff.WithMaxRetries(backoff.NewExponentialBackOff(), maxRetries)
err := backoff.RetryNotify(operation, b, func(err error, _ time.Duration) {
log.Warn("HTTP error", log.Err(err))
log.Info("Retrying HTTP request...")
})
if err != nil {
return err
}
return nil
}