forked from algorand/indexer
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathutil.go
More file actions
74 lines (63 loc) · 2.01 KB
/
util.go
File metadata and controls
74 lines (63 loc) · 2.01 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
package api
import (
"context"
"errors"
"time"
log "github.com/sirupsen/logrus"
)
// ErrTimeout is returned when callWithTimeout has a normal timeout.
var errTimeout = errors.New("timeout during call")
// isTimeoutError compares the given error against the timeout errors.
func isTimeoutError(err error) bool {
return errors.Is(err, errTimeout)
}
// errMisbehavingHandler is written to the log when a handler does not return.
var errMisbehavingHandler = "Misbehaving handler did not exit after 1 second."
// misbehavingHandlerDetector warn if ch does not exit after 1 second.
func misbehavingHandlerDetector(log *log.Logger, ch chan struct{}) {
if log == nil {
return
}
select {
case <-ch:
// Good. This means the handler returns shortly after the context finished.
return
case <-time.After(1 * time.Second):
log.Warnf(errMisbehavingHandler)
}
}
// callWithTimeout manages the channel / select loop required for timing
// out a function using a WithTimeout context. No timeout if timeout = 0.
// A new context is passed into handler, and cancelled at the end of this
// call.
func callWithTimeout(ctx context.Context, log *log.Logger, timeout time.Duration, handler func(ctx context.Context) error) error {
if timeout == 0 {
return handler(ctx)
}
timeoutCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
// Call function in go routine
done := make(chan struct{})
var err error
go func(routineCtx context.Context) {
err = handler(routineCtx)
close(done)
}(timeoutCtx)
// wait for task to finish or context to timeout/cancel
select {
case <-done:
// This may not be possible, but in theory the handler would quickly terminate
// when the context deadline is reached. So make sure the handler didn't finish
// due to a timeout.
if timeoutCtx.Err() == context.DeadlineExceeded {
return errTimeout
}
return err
case <-timeoutCtx.Done():
go misbehavingHandlerDetector(log, done)
if timeoutCtx.Err() == context.DeadlineExceeded {
return errTimeout
}
return timeoutCtx.Err()
}
}