-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimeout.go
More file actions
291 lines (252 loc) · 6.48 KB
/
timeout.go
File metadata and controls
291 lines (252 loc) · 6.48 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package result
import (
"context"
"time"
)
// WithTimeout runs a function with a timeout, returning Err if it exceeds the duration.
// The context passed to fn will be cancelled after timeout.
//
// Example:
//
// result := result.WithTimeout(ctx, 5*time.Second, func(ctx context.Context) result.Result[*User] {
// return repo.FindByID(ctx, id)
// })
func WithTimeout[T any](
ctx context.Context,
timeout time.Duration,
fn func(context.Context) Result[T],
) Result[T] {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
resultChan := make(chan Result[T], 1)
go func() {
resultChan <- fn(ctx)
}()
select {
case result := <-resultChan:
return result
case <-ctx.Done():
return Err[T](Internal("timeout", ctx.Err()))
}
}
// WithDeadline runs a function with an absolute deadline.
// The context passed to fn will be cancelled at the deadline.
//
// Example:
//
// deadline := time.Now().Add(10 * time.Second)
// result := result.WithDeadline(ctx, deadline, func(ctx context.Context) result.Result[*User] {
// return repo.FindByID(ctx, id)
// })
func WithDeadline[T any](
ctx context.Context,
deadline time.Time,
fn func(context.Context) Result[T],
) Result[T] {
ctx, cancel := context.WithDeadline(ctx, deadline)
defer cancel()
resultChan := make(chan Result[T], 1)
go func() {
resultChan <- fn(ctx)
}()
select {
case result := <-resultChan:
return result
case <-ctx.Done():
return Err[T](Internal("deadline", ctx.Err()))
}
}
// Retry retries a function up to maxAttempts with exponential backoff.
// Returns the first successful Result or the last error if all attempts fail.
//
// Backoff formula: initialBackoff * 2^attempt
//
// Example:
//
// result := result.Retry(ctx, 3, time.Second, func() result.Result[*User] {
// return externalAPI.GetUser(id)
// })
// // Tries at: 0s, 1s, 2s (exponential backoff)
func Retry[T any](
ctx context.Context,
maxAttempts int,
initialBackoff time.Duration,
fn func() Result[T],
) Result[T] {
if maxAttempts < 1 {
maxAttempts = 1
}
var lastResult Result[T]
for attempt := 0; attempt < maxAttempts; attempt++ {
// Check if context is cancelled before retry
if ctx.Err() != nil {
return Err[T](Internal("retry.cancelled", ctx.Err()))
}
// Execute function
lastResult = fn()
if lastResult.IsOk() {
return lastResult // Success!
}
// Don't sleep after last attempt
if attempt < maxAttempts-1 {
backoff := initialBackoff * time.Duration(1<<uint(attempt))
select {
case <-time.After(backoff):
// Continue to next attempt
case <-ctx.Done():
return Err[T](Internal("retry.cancelled", ctx.Err()))
}
}
}
// All attempts failed, return last error
return lastResult
}
// RetryIf retries only if the error matches specific kinds.
// This is useful when you only want to retry transient errors (e.g., infrastructure failures).
//
// Example:
//
// result := result.RetryIf(
// ctx,
// 3,
// time.Second,
// []result.Kind{result.KindInfrastructure, result.KindInternal},
// func() result.Result[*User] {
// return externalAPI.GetUser(id)
// },
// )
func RetryIf[T any](
ctx context.Context,
maxAttempts int,
initialBackoff time.Duration,
retryableKinds []Kind,
fn func() Result[T],
) Result[T] {
if maxAttempts < 1 {
maxAttempts = 1
}
// Create a map for O(1) lookup
retryableMap := make(map[Kind]bool)
for _, kind := range retryableKinds {
retryableMap[kind] = true
}
var lastResult Result[T]
for attempt := 0; attempt < maxAttempts; attempt++ {
// Check if context is cancelled
if ctx.Err() != nil {
return Err[T](Internal("retry.cancelled", ctx.Err()))
}
// Execute function
lastResult = fn()
if lastResult.IsOk() {
return lastResult // Success!
}
// Check if error is retryable
errorKind := KindOf(lastResult.UnwrapErr())
if !retryableMap[errorKind] {
// Non-retryable error, return immediately
return lastResult
}
// Don't sleep after last attempt
if attempt < maxAttempts-1 {
backoff := initialBackoff * time.Duration(1<<uint(attempt))
select {
case <-time.After(backoff):
// Continue to next attempt
case <-ctx.Done():
return Err[T](Internal("retry.cancelled", ctx.Err()))
}
}
}
// All attempts failed, return last error
return lastResult
}
// RetryWithBackoff retries with a custom backoff strategy.
//
// Example:
//
// result := result.RetryWithBackoff(
// ctx,
// 3,
// func(attempt int) time.Duration {
// return time.Duration(attempt*attempt) * time.Second // Quadratic backoff
// },
// func() result.Result[*User] {
// return externalAPI.GetUser(id)
// },
// )
func RetryWithBackoff[T any](
ctx context.Context,
maxAttempts int,
backoffFn func(attempt int) time.Duration,
fn func() Result[T],
) Result[T] {
if maxAttempts < 1 {
maxAttempts = 1
}
var lastResult Result[T]
for attempt := 0; attempt < maxAttempts; attempt++ {
// Check if context is cancelled
if ctx.Err() != nil {
return Err[T](Internal("retry.cancelled", ctx.Err()))
}
// Execute function
lastResult = fn()
if lastResult.IsOk() {
return lastResult // Success!
}
// Don't sleep after last attempt
if attempt < maxAttempts-1 {
backoff := backoffFn(attempt)
select {
case <-time.After(backoff):
// Continue to next attempt
case <-ctx.Done():
return Err[T](Internal("retry.cancelled", ctx.Err()))
}
}
}
// All attempts failed, return last error
return lastResult
}
// RetryContext is like Retry but passes context to the function.
//
// Example:
//
// result := result.RetryContext(ctx, 3, time.Second, func(ctx context.Context) result.Result[*User] {
// return repo.FindByID(ctx, id)
// })
func RetryContext[T any](
ctx context.Context,
maxAttempts int,
initialBackoff time.Duration,
fn func(context.Context) Result[T],
) Result[T] {
if maxAttempts < 1 {
maxAttempts = 1
}
var lastResult Result[T]
for attempt := 0; attempt < maxAttempts; attempt++ {
// Check if context is cancelled
if ctx.Err() != nil {
return Err[T](Internal("retry.cancelled", ctx.Err()))
}
// Execute function
lastResult = fn(ctx)
if lastResult.IsOk() {
return lastResult // Success!
}
// Don't sleep after last attempt
if attempt < maxAttempts-1 {
backoff := initialBackoff * time.Duration(1<<uint(attempt))
select {
case <-time.After(backoff):
// Continue to next attempt
case <-ctx.Done():
return Err[T](Internal("retry.cancelled", ctx.Err()))
}
}
}
// All attempts failed, return last error
return lastResult
}