File: waiter.go

package info (click to toggle)
golang-github-aws-smithy-go 1.20.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,116 kB
  • sloc: java: 19,678; xml: 166; sh: 131; makefile: 70
file content (66 lines) | stat: -rw-r--r-- 1,910 bytes parent folder | download | duplicates (5)
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 waiter

import (
	"fmt"
	"math"
	"time"

	"github.com/aws/smithy-go/rand"
)

// ComputeDelay computes delay between waiter attempts. The function takes in a current attempt count,
// minimum delay, maximum delay, and remaining wait time for waiter as input. The inputs minDelay and maxDelay
// must always be greater than 0, along with minDelay lesser than or equal to maxDelay.
//
// Returns the computed delay and if next attempt count is possible within the given input time constraints.
// Note that the zeroth attempt results in no delay.
func ComputeDelay(attempt int64, minDelay, maxDelay, remainingTime time.Duration) (delay time.Duration, err error) {
	// zeroth attempt, no delay
	if attempt <= 0 {
		return 0, nil
	}

	// remainingTime is zero or less, no delay
	if remainingTime <= 0 {
		return 0, nil
	}

	// validate min delay is greater than 0
	if minDelay == 0 {
		return 0, fmt.Errorf("minDelay must be greater than zero when computing Delay")
	}

	// validate max delay is greater than 0
	if maxDelay == 0 {
		return 0, fmt.Errorf("maxDelay must be greater than zero when computing Delay")
	}

	// Get attempt ceiling to prevent integer overflow.
	attemptCeiling := (math.Log(float64(maxDelay/minDelay)) / math.Log(2)) + 1

	if attempt > int64(attemptCeiling) {
		delay = maxDelay
	} else {
		// Compute exponential delay based on attempt.
		ri := 1 << uint64(attempt-1)
		// compute delay
		delay = minDelay * time.Duration(ri)
	}

	if delay != minDelay {
		// randomize to get jitter between min delay and delay value
		d, err := rand.CryptoRandInt63n(int64(delay - minDelay))
		if err != nil {
			return 0, fmt.Errorf("error computing retry jitter, %w", err)
		}

		delay = time.Duration(d) + minDelay
	}

	// check if this is the last attempt possible and compute delay accordingly
	if remainingTime-delay <= minDelay {
		delay = remainingTime - minDelay
	}

	return delay, nil
}