forked from dogmatiq/linger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
50 lines (45 loc) · 1.46 KB
/
context.go
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
package linger
import (
"context"
"time"
)
// FromContextDeadline returns the duration until the deadline of ctx is
// reached.
//
// ok is false if ctx does not have a deadline.
func FromContextDeadline(ctx context.Context) (d time.Duration, ok bool) {
if dl, ok := ctx.Deadline(); ok {
return time.Until(dl), true
}
return 0, false
}
// ContextWithTimeout returns a context with a deadline some duration after the
// current time.
//
// The timeout duration is computed by finding the first of the supplied
// durations that is positive. It uses a zero duration if none of the supplied
// durations are positive.
func ContextWithTimeout(
ctx context.Context,
durations ...time.Duration,
) (context.Context, func()) {
return ContextWithTimeoutX(ctx, Identity, durations...)
}
// ContextWithTimeoutX returns a context with a deadline some duration after the
// current time.
//
// The timeout duration is computed by finding the first of the supplied
// durations that is positive, then applying the transform x. It uses a zero
// duration if none of the supplied durations are positive.
//
// The transform can be used to apply jitter to the timeout duration, for
// example, by using one of the built-in jitter transforms such as FullJitter()
// or ProportionalJitter().
func ContextWithTimeoutX(
ctx context.Context,
x DurationTransform,
durations ...time.Duration,
) (context.Context, func()) {
d, _ := Coalesce(durations...)
return context.WithTimeout(ctx, x(d))
}