vendor/github.com/go-rod/rod/lib/utils/sleeper.go

149 lines · 3275 bytes

  1package utils
  2
  3import (
  4	"context"
  5	"fmt"
  6	mr "math/rand"
  7	"sync"
  8	"time"
  9)
 10
 11// Sleep the goroutine for specified seconds, such as 2.3 seconds.
 12func Sleep(seconds float64) {
 13	d := time.Duration(seconds * float64(time.Second))
 14	time.Sleep(d)
 15}
 16
 17// Sleeper sleeps the current goroutine for sometime, returns the reason to wake, if ctx is done release resource.
 18type Sleeper func(context.Context) error
 19
 20// MaxSleepCountError type.
 21type MaxSleepCountError struct {
 22	// Max count
 23	Max int
 24}
 25
 26// Error interface.
 27func (e *MaxSleepCountError) Error() string {
 28	return fmt.Sprintf("max sleep count %d exceeded", e.Max)
 29}
 30
 31// Is interface.
 32func (e *MaxSleepCountError) Is(err error) bool { _, ok := err.(*MaxSleepCountError); return ok }
 33
 34// CountSleeper wakes immediately. When counts to the max returns *ErrMaxSleepCount.
 35func CountSleeper(max int) Sleeper {
 36	l := sync.Mutex{}
 37	count := 0
 38
 39	return func(ctx context.Context) error {
 40		l.Lock()
 41		defer l.Unlock()
 42
 43		if ctx.Err() != nil {
 44			return ctx.Err()
 45		}
 46
 47		if count == max {
 48			return &MaxSleepCountError{max}
 49		}
 50		count++
 51		return nil
 52	}
 53}
 54
 55// DefaultBackoff algorithm: A(n) = A(n-1) * random[1.9, 2.1).
 56func DefaultBackoff(interval time.Duration) time.Duration {
 57	scale := 2 + (mr.Float64()-0.5)*0.2
 58	return time.Duration(float64(interval) * scale)
 59}
 60
 61// BackoffSleeper returns a sleeper that sleeps in a backoff manner every time get called.
 62// The sleep interval of the sleeper will grow from initInterval to maxInterval by the specified algorithm,
 63// then use maxInterval as the interval.
 64// If maxInterval is not greater than 0, the sleeper will wake immediately.
 65// If algorithm is nil, DefaultBackoff will be used.
 66func BackoffSleeper(initInterval, maxInterval time.Duration, algorithm func(time.Duration) time.Duration) Sleeper {
 67	l := sync.Mutex{}
 68
 69	if algorithm == nil {
 70		algorithm = DefaultBackoff
 71	}
 72
 73	return func(ctx context.Context) error {
 74		l.Lock()
 75		defer l.Unlock()
 76
 77		// wake immediately
 78		if maxInterval <= 0 {
 79			return nil
 80		}
 81
 82		var interval time.Duration
 83		if initInterval < maxInterval {
 84			interval = algorithm(initInterval)
 85		} else {
 86			interval = maxInterval
 87		}
 88
 89		t := time.NewTimer(interval)
 90		defer t.Stop()
 91
 92		select {
 93		case <-ctx.Done():
 94			return ctx.Err()
 95		case <-t.C:
 96			initInterval = interval
 97		}
 98
 99		return nil
100	}
101}
102
103// EachSleepers returns a sleeper wakes up when each sleeper is awake.
104// If a sleeper returns error, it will wake up immediately.
105func EachSleepers(list ...Sleeper) Sleeper {
106	return func(ctx context.Context) (err error) {
107		for _, s := range list {
108			err = s(ctx)
109			if err != nil {
110				break
111			}
112		}
113
114		return
115	}
116}
117
118// RaceSleepers returns a sleeper wakes up when one of the sleepers wakes.
119func RaceSleepers(list ...Sleeper) Sleeper {
120	return func(ctx context.Context) error {
121		ctx, cancel := context.WithCancel(ctx)
122		done := make(chan error, len(list))
123
124		sleep := func(s Sleeper) {
125			done <- s(ctx)
126			cancel()
127		}
128
129		for _, s := range list {
130			go sleep(s)
131		}
132
133		return <-done
134	}
135}
136
137// Retry fn and sleeper until fn returns true or s returns error.
138func Retry(ctx context.Context, s Sleeper, fn func() (stop bool, err error)) error {
139	for {
140		stop, err := fn()
141		if stop {
142			return err
143		}
144		err = s(ctx)
145		if err != nil {
146			return err
147		}
148	}
149}