forked from lavanet/lava
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeout.go
62 lines (52 loc) · 1.65 KB
/
timeout.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
58
59
60
61
62
package common
import (
"context"
"errors"
"math"
"time"
"github.com/gogo/status"
"google.golang.org/grpc/codes"
)
const (
TimePerCU = uint64(100 * time.Millisecond)
MinimumTimePerRelayDelay = time.Second
DataReliabilityTimeoutIncrease = 5 * time.Second
AverageWorldLatency = 300 * time.Millisecond
CommunicateWithLocalLavaNodeTimeout = (3 * time.Second) + AverageWorldLatency
)
func LocalNodeTimePerCu(cu uint64) time.Duration {
return BaseTimePerCU(cu) + AverageWorldLatency // TODO: remove average world latency once our providers run locally, or allow a flag that says local to make it tight, tighter timeouts are better
}
func BaseTimePerCU(cu uint64) time.Duration {
return time.Duration(cu * TimePerCU)
}
func GetTimePerCu(cu uint64) time.Duration {
if LocalNodeTimePerCu(cu) < MinimumTimePerRelayDelay {
return MinimumTimePerRelayDelay
}
return LocalNodeTimePerCu(cu)
}
func ContextOutOfTime(ctx context.Context) bool {
return errors.Is(ctx.Err(), context.DeadlineExceeded)
}
func GetRemainingTimeoutFromContext(ctx context.Context) (timeRemaining time.Duration) {
deadline, ok := ctx.Deadline()
if ok {
return time.Until(deadline)
}
return time.Duration(math.MaxInt64)
}
func LowerContextTimeout(ctx context.Context, timeout time.Duration) (context.Context, context.CancelFunc) {
if GetRemainingTimeoutFromContext(ctx) > timeout {
return context.WithTimeout(ctx, timeout)
}
return context.WithCancel(ctx)
}
func IsTimeout(errArg error) bool {
if statusCode, ok := status.FromError(errArg); ok {
if statusCode.Code() == codes.DeadlineExceeded {
return true
}
}
return false
}