-
Notifications
You must be signed in to change notification settings - Fork 7
/
common.go
58 lines (50 loc) · 1.29 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
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:
time.Sleep(delay) //delay between retries
continueRetrying, err := targetFunc()
if !continueRetrying {
return err
}
}
}
}
//retryWithLimitedNumOfRetries reruns a function within a number of retries
func retryWithLimitedNumOfRetries(targetFunc retryableFunc, numOfRetries int, delay time.Duration) error {
retryNo := 0
var err error
var continueRetrying bool
for retryNo <= numOfRetries {
retryNo++
time.Sleep(delay * time.Duration(retryNo)) //delay between retries
continueRetrying, err = targetFunc()
if !continueRetrying {
return err
}
}
if err != nil {
return fmt.Errorf("Maximum number of trials has been exhausted with error: %v", err)
}
return errors.New("Maximum number of trials has been exhausted")
}