/
waiter.go
67 lines (55 loc) · 1.56 KB
/
waiter.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
63
64
65
66
67
package util
import (
"sync"
"time"
)
const waitTimeout = 50 * time.Millisecond // polling interval when waiting for initial value
// Waiter provides monitoring of receive timeouts and reception of initial value
type Waiter struct {
sync.Mutex
log func()
once sync.Once
updated time.Time
timeout time.Duration
}
// NewWaiter creates new waiter
func NewWaiter(timeout time.Duration, logInitialWait func()) *Waiter {
return &Waiter{
log: logInitialWait,
timeout: timeout,
}
}
// Update is called when client has received data. Update resets the timeout counter.
// It is client responsibility to ensure that the waiter is not locked when Update is called.
func (p *Waiter) Update() {
p.updated = time.Now()
}
// waitForInitialValue blocks until Update has been called at least once.
// It assumes lock has been obtained before and returns with lock active.
func (p *Waiter) waitForInitialValue() {
if p.updated.IsZero() {
p.log()
// wait for initial update
waitStarted := time.Now()
for p.updated.IsZero() {
p.Unlock()
time.Sleep(waitTimeout)
p.Lock()
// abort initial wait with error
if p.timeout != 0 && time.Since(waitStarted) > p.timeout {
p.updated = waitStarted
return
}
}
}
}
// LockWithTimeout waits for initial value and checks if update timeout has elapsed
func (p *Waiter) LockWithTimeout() time.Duration {
p.Lock()
// waiting assumes lock acquired and returns with lock
p.once.Do(p.waitForInitialValue)
if elapsed := time.Since(p.updated); p.timeout != 0 && elapsed > p.timeout {
return elapsed
}
return 0
}