-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtimeout.go
More file actions
38 lines (31 loc) · 981 Bytes
/
timeout.go
File metadata and controls
38 lines (31 loc) · 981 Bytes
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
package matr
import (
"context"
"fmt"
"time"
)
const (
timeoutEnvVar = "MATR_TIMEOUT"
defaultTaskTimeout = 5 * time.Minute
)
// ContextWithTimeoutValue builds the runner context from the configured timeout value.
// An empty value uses the default timeout and zero disables the deadline.
func ContextWithTimeoutValue(timeoutValue string) (context.Context, context.CancelFunc, error) {
if timeoutValue == "" {
ctx, cancel := context.WithTimeout(context.Background(), defaultTaskTimeout)
return ctx, cancel, nil
}
timeout, err := time.ParseDuration(timeoutValue)
if err != nil {
return nil, nil, fmt.Errorf("invalid timeout %q: %w", timeoutValue, err)
}
if timeout < 0 {
return nil, nil, fmt.Errorf("invalid timeout %q: must be >= 0", timeoutValue)
}
if timeout == 0 {
ctx, cancel := context.WithCancel(context.Background())
return ctx, cancel, nil
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
return ctx, cancel, nil
}