-
Notifications
You must be signed in to change notification settings - Fork 901
/
utils.go
57 lines (48 loc) · 1.35 KB
/
utils.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
51
52
53
54
55
56
57
package getters
import (
"context"
"errors"
"time"
logging "github.com/ipfs/go-log/v2"
"go.opentelemetry.io/otel"
)
var (
tracer = otel.Tracer("share/getters")
log = logging.Logger("share/getters")
errOperationNotSupported = errors.New("operation is not supported")
)
// ctxWithSplitTimeout will split timeout stored in context by splitFactor and return the result if
// it is greater than minTimeout. minTimeout == 0 will be ignored, splitFactor <= 0 will be ignored
func ctxWithSplitTimeout(
ctx context.Context,
splitFactor int,
minTimeout time.Duration,
) (context.Context, context.CancelFunc) {
deadline, ok := ctx.Deadline()
if !ok || splitFactor <= 0 {
if minTimeout == 0 {
return context.WithCancel(ctx)
}
return context.WithTimeout(ctx, minTimeout)
}
timeout := time.Until(deadline)
if timeout < minTimeout {
return context.WithCancel(ctx)
}
splitTimeout := timeout / time.Duration(splitFactor)
if splitTimeout < minTimeout {
return context.WithTimeout(ctx, minTimeout)
}
return context.WithTimeout(ctx, splitTimeout)
}
// ErrorContains reports whether any error in err's tree matches any error in targets tree.
func ErrorContains(err, target error) bool {
if errors.Is(err, target) || target == nil {
return true
}
target = errors.Unwrap(target)
if target == nil {
return false
}
return ErrorContains(err, target)
}