go.temporal.io/server/common/backoff/retry.go

207 LOC · 94 covered · 113 uncovered · 43 ranges · 2242 concepts · 35 introducers · 1071 tests

File neighbourhood

The centred file is linked to every concept that introduces one of its ranges, every test that runs code from the file, and the gray connector concepts standing between those tests and the file's own introducer concepts. Undirected links join concepts to every file where they introduce source and concepts to the tests they introduce; arrows show specialization between the displayed concepts and bridge only concepts omitted from this view. Concept colors match the source ranges below; connector concepts have no source color and are shown in gray.

Focused file, its introducer and connector concepts, their introduced files, and tests that run code from the file

In the embedded map, ordinary wheel input scrolls the page; use the visible controls to zoom and drag to pan. Open the full-screen map for canvas navigation: wheel pans, Ctrl/Command plus wheel zooms, and arrow keys pan when this region is focused. On touch screens, open the full-screen map to pan or pinch. If JavaScript or WebGL is unavailable, use the related-file, concept, and source links on this page.

Graph controls are ready.

Interactive rendering requires JavaScript and WebGL. Use the related-file, concept, and source links on this page while the interactive map is unavailable.

1 package backoff
2
3 import (
4 "context"
5 "math"
6 "slices"
7 "time"
8
9 commonpb "go.temporal.io/api/common/v1"
10 "go.temporal.io/api/serviceerror"
11 "go.temporal.io/server/common/clock"
12 "google.golang.org/protobuf/types/known/durationpb"
13 )
14
15 const (
16 throttleRetryInitialInterval = time.Second
17 throttleRetryMaxInterval = 10 * time.Second
18 throttleRetryExpirationInterval = NoInterval
19 )
20
21 var (
22 throttleRetryPolicy = NewExponentialRetryPolicy(throttleRetryInitialInterval).
23 WithMaximumInterval(throttleRetryMaxInterval).
24 WithExpirationInterval(throttleRetryExpirationInterval)
25 )
26
27 type (
28 // Operation to retry
29 Operation func() error
30
31 // OperationCtx plays the same role as Operation but for context-aware
32 // retryable functions.
33 OperationCtx func(context.Context) error
34
35 // IsRetryable handler can be used to exclude certain errors during retry
36 IsRetryable func(error) bool
37 )
38
39 // ThrottleRetry is a resource aware version of Retry.
40 // Resource exhausted error will be retried using a different throttle retry policy, instead of the specified one.
41 > func ThrottleRetry(operation Operation, policy RetryPolicy, isRetryable IsRetryable) error { retry.go ×1
42 > ctxOp := func(context.Context) error { return operation() }
43 > return ThrottleRetryContext(context.Background(), ctxOp, policy, isRetryable)
44 }
45
46 // ThrottleRetryContext is a context and resource aware version of Retry.
47 // Context timeout/cancellation errors are never retried, regardless of IsRetryable.
48 // Resource exhausted error will be retried using a different throttle retry policy, instead of the specified one.
49 // TODO: allow customizing throttle retry policy and what kind of error are categorized as throttle error.
50 func ThrottleRetryContext(
51 ctx context.Context,
52 operation OperationCtx,
53 policy RetryPolicy,
54 isRetryable IsRetryable,
55 > ) error { retry.go ×2
56 > var err error
57 > var next time.Duration
58 >
59 > if isRetryable == nil {
60 > isRetryable = func(error) bool { return true } retry.go ×1
61 }
62
63 > deadline, hasDeadline := ctx.Deadline() retry.go ×2
64 >
65 > timeSrc := clock.NewRealTimeSource()
66 > r := NewRetrier(policy, timeSrc)
67 > t := NewRetrier(throttleRetryPolicy, timeSrc)
68 > for ctx.Err() == nil {
69 > if err = operation(ctx); err == nil { retry.go ×1
70 > return nil retry.go ×1
71 > }
72
73 > if next = r.NextBackOff(err); next == done { retry.go ×2
74 > return err retry.go ×1
75 > }
76
77 > if err == ctx.Err() || !isRetryable(err) { retry.go ×2
78 > return err retry.go ×1
79 > }
80
81 > if _, ok := err.(*serviceerror.ResourceExhausted); ok { retry.go ×2
82 > next = max(next, t.NextBackOff(err)) retry.go ×1
83 > }
84
85 > if hasDeadline && timeSrc.Now().Add(next).After(deadline) { retry.go ×2
86 > break retry.go ×1
87 }
88
89 > timer := time.NewTimer(next) retry.go ×1
90 > select {
91 > case <-timer.C: retry.go ×1
92 > case <-ctx.Done(): retry.go ×1
93 > timer.Stop()
94 }
95 }
96 // always return the last error we got from operation, even if it is not useful
97 // this retry utility does not have enough information to do any filtering/mapping
98 > if err != nil { retry.go ×1
99 > return err retry.go ×1
100 > }
101 > return ctx.Err() retry.go ×1
102 }
103
104 // ThrottleRetryContextWithReturn is a context and resource aware version of Retry.
105 // Context timeout/cancellation errors are never retried, regardless of IsRetryable.
106 // Resource exhausted error will be retried using a different throttle retry policy, instead of the specified one.
107 // TODO: allow customizing throttle retry policy and what kind of error are categorized as throttle error.
108 func ThrottleRetryContextWithReturn[T any](
109 ctx context.Context,
110 fn func(context.Context) (T, error),
111 policy RetryPolicy,
112 isRetryable IsRetryable,
113 > ) (T, error) { retry.go ×2
114 > var zero T
115 > var result T
116 > var err error
117 > var next time.Duration
118 >
119 > if isRetryable == nil {
120 > isRetryable = func(error) bool { return true } retry.go ×1
121 }
122
123 > deadline, hasDeadline := ctx.Deadline() retry.go ×2
124 >
125 > timeSrc := clock.NewRealTimeSource()
126 > r := NewRetrier(policy, timeSrc)
127 > t := NewRetrier(throttleRetryPolicy, timeSrc)
128 > for ctx.Err() == nil {
129 > result, err = fn(ctx) retry.go ×1
130 > if err == nil {
131 > return result, nil retry.go ×1
132 > }
133
134 > if next = r.NextBackOff(err); next == done { retry.go ×2
135 > return zero, err retry.go ×1
136 > }
137
138 > if err == ctx.Err() || !isRetryable(err) { retry.go ×2
139 > return zero, err registry.go ×7
140 > }
141
142 > if _, ok := err.(*serviceerror.ResourceExhausted); ok { retry.go ×2
143 next = max(next, t.NextBackOff(err))
144 }
145
146 > if hasDeadline && timeSrc.Now().Add(next).After(deadline) { retry.go ×2
147 > break retry.go ×2
148 }
149
150 > timer := time.NewTimer(next) retry.go ×1
151 > select {
152 > case <-timer.C:
153 case <-ctx.Done():
154 timer.Stop()
155 }
156 }
157 // always return the last error we got from operation, even if it is not useful
158 // this retry utility does not have enough information to do any filtering/mapping
159 > if err != nil { retry.go ×1
160 > return zero, err retry.go ×2
161 > }
162 > return zero, ctx.Err() retry.go ×1
163 }
164
165 // IgnoreErrors can be used as IsRetryable handler for Retry function to exclude certain errors from the retry list
166 > func IgnoreErrors(errorsToExclude []error) func(error) bool { retry.go ×1
167 > return func(err error) bool {
168 > return !slices.Contains(errorsToExclude, err)
169 > }
170 }
171
172 // BackoffCalculatorAlgorithmFunc is a function type that calculates backoff duration based on
173 // initial duration, coefficient, and current attempt number.
174 type BackoffCalculatorAlgorithmFunc func(duration *durationpb.Duration, coefficient float64, currentAttempt int32) time.Duration
175
176 // ExponentialBackoffAlgorithm calculates the backoff duration using exponential algorithm.
177 // The result is initInterval * (backoffCoefficient ^ (currentAttempt - 1)).
178 // If the calculation overflows int64, it returns the maximum possible duration. A negative result will also never be returned.
179 > func ExponentialBackoffAlgorithm(initInterval *durationpb.Duration, backoffCoefficient float64, currentAttempt int32) time.Duration { retry.go ×1
180 > result := float64(initInterval.AsDuration().Nanoseconds()) * math.Pow(backoffCoefficient, float64(currentAttempt-1))
181 > return time.Duration(max(0, min(int64(result), math.MaxInt64)))
182 > }
183
184 // MakeBackoffAlgorithm creates a BackoffCalculatorAlgorithmFunc that returns a fixed delay if requestedDelay is non-nil,
185 // otherwise falls back to exponential backoff algorithm.
186 > func MakeBackoffAlgorithm(requestedDelay *time.Duration) BackoffCalculatorAlgorithmFunc { mutable_state_impl.go ×4
187 > return func(duration *durationpb.Duration, coefficient float64, currentAttempt int32) time.Duration {
188 > if requestedDelay != nil {
189 > return *requestedDelay retry.go ×1
190 > }
191 > return ExponentialBackoffAlgorithm(duration, coefficient, currentAttempt) retry.go ×1
192 }
193 }
194
195 // CalculateExponentialRetryInterval calculates the retry interval using exponential backoff algorithm
196 > func CalculateExponentialRetryInterval(retryPolicy *commonpb.RetryPolicy, attempt int32) time.Duration { activity.go ×12
197 > interval := ExponentialBackoffAlgorithm(retryPolicy.GetInitialInterval(), retryPolicy.GetBackoffCoefficient(), attempt)
198 >
199 > maxInterval := retryPolicy.GetMaximumInterval()
200 >
201 > // Cap interval to maximum if it's set
202 > if maxInterval.AsDuration() != 0 && interval > maxInterval.AsDuration() {
203 interval = maxInterval.AsDuration()
204 }
205
206 > return interval activity.go ×12
207 }