-
Notifications
You must be signed in to change notification settings - Fork 7
/
common.go
66 lines (59 loc) · 1.54 KB
/
common.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package gsclient
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
)
type emptyStruct struct {
}
// retryableFunc defines a function that can be retried.
type retryableFunc func() (bool, error)
// isValidUUID validates the uuid.
func isValidUUID(u string) bool {
_, err := uuid.Parse(u)
return err == nil
}
// retryWithContext reruns a function until the context is done.
func retryWithContext(ctx context.Context, targetFunc retryableFunc, delay time.Duration) error {
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
continueRetrying, err := targetFunc()
if !continueRetrying {
return err
}
time.Sleep(delay) //delay between retries
}
}
}
// retryNTimes reruns a function within a number of retries.
func retryNTimes(targetFunc retryableFunc, numOfRetries int, delay time.Duration) error {
retryNo := 0
var err error
var continueRetrying bool
for retryNo <= numOfRetries {
continueRetrying, err = targetFunc()
if !continueRetrying {
return err
}
//delay between retries.
retryNo++
time.Sleep(delay * time.Duration(retryNo))
}
if err != nil {
reqErr, ok := err.(RequestError)
if ok {
if reqErr.Description == "" {
reqErr.Description = "no error message received from server"
}
reqErr.Description = fmt.Sprintf("Maximum number of re-tries has been exhausted with error: %s", reqErr.Description)
return reqErr
}
return fmt.Errorf("maximum number of tries has been exhausted with error: %v", err)
}
return errors.New("maximum number of tries has been exhausted")
}