-
Notifications
You must be signed in to change notification settings - Fork 0
/
inflight.go
92 lines (74 loc) · 2.02 KB
/
inflight.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
package raft
import (
"sync"
raftpb "github.com/dimitarvdimitrov/sporkfs/raft/pb"
)
type UnactionedMessage struct {
*raftpb.Entry
Action func()
}
// entryTracker is used to track raft committed entry ids after they have been sent to channels. It provides
// methods to register/watch entries and then wait until all registered entries are confirmed.
// It is not safe to call watch and wait concurrently.
type entryTracker struct {
*sync.Mutex
firstId uint64
entries []bool // true or false if the entry is confirmed/actioned or not
allDone chan struct{}
}
func newInFlight() *entryTracker {
return &entryTracker{
Mutex: &sync.Mutex{},
}
}
// watch returns a callback that will confirm the actioning of RAFT entry with the provided id. It assumes the
// calls to it will contain subsequent values for id; i.e. that id will increment by one on each call.
// It is not safe to call watch and wait concurrently.
func (i *entryTracker) watch(id uint64) func() {
i.Lock()
defer i.Unlock()
if len(i.entries) == 0 {
i.firstId = id
}
// fill in the gap if not all entries had to be watched
for j := i.firstId + 1; j < id-1; j++ {
i.entries = append(i.entries, true)
}
i.entries = append(i.entries, false)
return i.pruneFunc(id)
}
func (i *entryTracker) pruneFunc(id uint64) func() {
return func() {
i.Lock()
defer i.Unlock()
i.entries[id-i.firstId] = true
pruneUntil := 0
for _, isConfirmed := range i.entries {
if isConfirmed {
pruneUntil++
} else {
break
}
}
i.entries = i.entries[pruneUntil:]
i.firstId += uint64(pruneUntil)
if len(i.entries) == 0 && i.allDone != nil {
select {
case <-i.allDone: // is it already closed and not waiting anymore
default: // or are we the last one?
close(i.allDone)
}
}
}
}
// wait blocks until all inflight messages have been confirmed. It is not safe to call watch and wait concurrently.
func (i *entryTracker) wait() {
i.Lock()
if len(i.entries) == 0 {
i.Unlock()
return
}
i.allDone = make(chan struct{})
i.Unlock()
<-i.allDone
}