-
Notifications
You must be signed in to change notification settings - Fork 199
/
timeoutHandler.go
58 lines (45 loc) · 1.27 KB
/
timeoutHandler.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
package common
import (
"fmt"
"sync"
"time"
)
const minTimeoutNodesReceived = time.Second
type timeoutHandler struct {
timeoutValue time.Duration
mutCheckpoint sync.RWMutex
checkpoint time.Time
getTimeHandler func() time.Time
}
// NewTimeoutHandler returns a new instance of the timeout handler
func NewTimeoutHandler(timeout time.Duration) (*timeoutHandler, error) {
if timeout < minTimeoutNodesReceived {
return nil, fmt.Errorf("%w provided: %v, minimum %v",
ErrInvalidTimeout, timeout, minTimeoutNodesReceived)
}
th := &timeoutHandler{
timeoutValue: timeout,
}
th.getTimeHandler = func() time.Time {
return time.Now()
}
th.checkpoint = th.getTimeHandler()
return th, nil
}
// ResetWatchdog resets the current time value
func (th *timeoutHandler) ResetWatchdog() {
th.mutCheckpoint.Lock()
defer th.mutCheckpoint.Unlock()
th.checkpoint = th.getTimeHandler()
}
// IsTimeout returns true if the timeoutValue has been reached
func (th *timeoutHandler) IsTimeout() bool {
th.mutCheckpoint.RLock()
defer th.mutCheckpoint.RUnlock()
now := th.getTimeHandler()
return now.Sub(th.checkpoint) > th.timeoutValue
}
// IsInterfaceNil returns true if there is no value under the interface
func (th *timeoutHandler) IsInterfaceNil() bool {
return th == nil
}