-
Notifications
You must be signed in to change notification settings - Fork 5
/
checkerr.go
45 lines (37 loc) · 867 Bytes
/
checkerr.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package util
import (
"regexp"
"time"
"cloud.google.com/go/datastore"
"go.uber.org/zap"
"github.com/nyaxt/otaru/logger"
)
var shouldRetryErrorRegexp = regexp.MustCompile(`status code: (429|5\d\d)`)
func IsShouldRetryError(e error) bool {
if e == nil {
return false
}
if e == datastore.ErrConcurrentTransaction {
return true
}
estr := e.Error()
return shouldRetryErrorRegexp.MatchString(estr)
}
func RetryIfNeeded(f func() error, mylog logger.Logger) (err error) {
const numRetries = 3
for i := 0; i < numRetries; i++ {
start := time.Now()
err = f()
if err == nil {
return
}
if !IsShouldRetryError(err) {
return
}
if i < numRetries {
zap.S().Infof("A Google Cloud API operation has failed after %s. Retrying %d / %d...", time.Since(start), i+1, numRetries)
time.Sleep(time.Duration(i) * time.Second)
}
}
return
}