-
Notifications
You must be signed in to change notification settings - Fork 10
/
tracker.go
106 lines (93 loc) · 1.79 KB
/
tracker.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package util
import (
"errors"
"sync/atomic"
)
type StaleMode int
const (
BothStale StaleMode = iota
EitherStale
LeftStale
RightStale
)
func (m *StaleMode) String() string {
if m == nil {
return "<nil>"
}
switch *m {
case BothStale:
return "both"
case EitherStale:
return "either"
case LeftStale:
return "left"
case RightStale:
return "right"
}
return "<unknown>"
}
func (m *StaleMode) Set(val string) error {
switch val {
case "both":
*m = BothStale
case "either":
*m = EitherStale
case "left":
*m = LeftStale
case "right":
*m = RightStale
default:
return errors.New("unknown stale mode")
}
return nil
}
type tracker struct {
leftCounter atomic.Int32
rightCounter atomic.Int32
leftTimedOutAt atomic.Int32
rightTimedOutAt atomic.Int32
staleFunc func() bool
}
func newTracker(staleMode StaleMode) *tracker {
t := &tracker{}
switch staleMode {
case BothStale:
t.staleFunc = t.bothStale
case EitherStale:
t.staleFunc = t.eitherStale
case LeftStale:
t.staleFunc = t.leftStale
case RightStale:
t.staleFunc = t.rightStale
default:
panic("unsupported stale mode")
}
return t
}
func (t *tracker) notify(isLeft bool) {
if isLeft {
t.leftCounter.Add(1)
} else {
t.rightCounter.Add(1)
}
}
func (t *tracker) handleTimeout(isLeft bool) bool {
if isLeft {
t.leftTimedOutAt.Store(t.leftCounter.Load())
} else {
t.rightTimedOutAt.Store(t.rightCounter.Load())
}
return !t.staleFunc()
}
func (t *tracker) leftStale() bool {
return t.leftCounter.Load() == t.leftTimedOutAt.Load()
}
func (t *tracker) rightStale() bool {
return t.rightCounter.Load() == t.rightTimedOutAt.Load()
}
func (t *tracker) bothStale() bool {
return t.leftStale() && t.rightStale()
}
func (t *tracker) eitherStale() bool {
return t.leftStale() || t.rightStale()
}