1package gsclient
2
3import (
4	"context"
5	"errors"
6	"fmt"
7	"time"
8
9	"github.com/google/uuid"
10)
11
12type emptyStruct struct {
13}
14
15//retryableFunc defines a function that can be retried
16type retryableFunc func() (bool, error)
17
18//isValidUUID validates the uuid
19func isValidUUID(u string) bool {
20	_, err := uuid.Parse(u)
21	return err == nil
22}
23
24//retryWithContext reruns a function until the context is done
25func retryWithContext(ctx context.Context, targetFunc retryableFunc, delay time.Duration) error {
26	for {
27		select {
28		case <-ctx.Done():
29			return ctx.Err()
30		default:
31			time.Sleep(delay) //delay between retries
32			continueRetrying, err := targetFunc()
33			if !continueRetrying {
34				return err
35			}
36		}
37	}
38}
39
40//retryWithLimitedNumOfRetries reruns a function within a number of retries
41func retryWithLimitedNumOfRetries(targetFunc retryableFunc, numOfRetries int, delay time.Duration) error {
42	retryNo := 0
43	var err error
44	var continueRetrying bool
45	for retryNo <= numOfRetries {
46		retryNo++
47		time.Sleep(delay * time.Duration(retryNo)) //delay between retries
48		continueRetrying, err = targetFunc()
49		if !continueRetrying {
50			return err
51		}
52
53	}
54	if err != nil {
55		return fmt.Errorf("Maximum number of trials has been exhausted with error: %v", err)
56	}
57	return errors.New("Maximum number of trials has been exhausted")
58}
59