-
Notifications
You must be signed in to change notification settings - Fork 0
/
leecher.go
285 lines (238 loc) · 6.27 KB
/
leecher.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package streamleecher
import (
"math/rand"
"sync"
"time"
"github.com/EktaMind/Thank_Sirus/gossip/dagstream"
"github.com/EktaMind/Thank_Sirus/gossip/dagstream/streamleecher/peerleecher"
"github.com/EktaMind/Thank_Sirus/hash"
"github.com/EktaMind/Thank_Sirus/inter/dag"
"github.com/EktaMind/Thank_Sirus/inter/idx"
)
// Leecher is responsible for requesting events based on lexicographic event streams
type Leecher struct {
// Callbacks
callback Callbacks
cfg Config
// State
session sessionState
epoch idx.Epoch
emptyState bool
forceSyncing bool
peers map[string]struct{}
quit chan struct{}
wg sync.WaitGroup
mu *sync.RWMutex
terminated bool
}
// New creates an events downloader to request events based on lexicographic event streams
func New(epoch idx.Epoch, emptyState bool, cfg Config, callback Callbacks) *Leecher {
return &Leecher{
cfg: cfg,
callback: callback,
quit: make(chan struct{}),
emptyState: emptyState,
epoch: epoch,
peers: make(map[string]struct{}),
mu: new(sync.RWMutex),
}
}
type Callbacks struct {
OnlyNotConnected peerleecher.OnlyNotConnectedFn
RequestChunk func(peer string, r dagstream.Request) error
Suspend func(peer string) bool
PeerEpoch func(peer string) idx.Epoch
}
type sessionState struct {
agent *peerleecher.PeerLeecher
peer string
startTime time.Time
endTime time.Time
lastReceived time.Time
try uint32
}
func (d *Leecher) Start() {
d.wg.Add(1)
go func() {
defer d.wg.Done()
d.loop()
}()
}
func (d *Leecher) shouldTerminateSession() bool {
if d.session.agent.Stopped() {
return true
}
noProgress := time.Since(d.session.lastReceived) >= d.cfg.BaseProgressWatchdog*time.Duration(d.session.try+5)/5
stuck := time.Since(d.session.startTime) >= d.cfg.BaseSessionWatchdog*time.Duration(d.session.try+5)/5
return stuck || noProgress
}
func (d *Leecher) terminateSession() {
// force the epoch download to end
if d.session.agent != nil {
d.session.agent.Terminate()
d.session.agent = nil
d.session.endTime = time.Now()
}
}
func (d *Leecher) selectSessionPeerCandidates() []string {
var selected []string
currentEpochPeers := make([]string, 0, len(d.peers))
futureEpochPeers := make([]string, 0, len(d.peers))
for p, _ := range d.peers {
epoch := d.callback.PeerEpoch(p)
if epoch == d.epoch {
currentEpochPeers = append(currentEpochPeers, p)
}
if epoch > d.epoch {
futureEpochPeers = append(futureEpochPeers, p)
}
}
sinceEnd := time.Since(d.session.endTime)
waitUntilProcessed := d.session.try == 0 || sinceEnd > d.cfg.MinSessionRestart
hasSomethingToSync := d.session.try == 0 || len(futureEpochPeers) > 0 || sinceEnd >= d.cfg.MaxSessionRestart || d.forceSyncing
if waitUntilProcessed && hasSomethingToSync {
if len(futureEpochPeers) > 0 && (d.session.try%5 != 4 || len(currentEpochPeers) == 0) {
// normally work only with peers which have a higher epoch
selected = futureEpochPeers
} else {
// if above doesn't work, try peers on current epoch every 5th try
selected = currentEpochPeers
}
}
return selected
}
func getSessionID(epoch idx.Epoch, try uint32) uint32 {
return (uint32(epoch) << 12) ^ try
}
func (d *Leecher) startSession(candidates []string) {
peer := candidates[rand.Intn(len(candidates))]
typ := dagstream.RequestIDs
if d.callback.PeerEpoch(peer) > d.epoch && d.emptyState && d.session.try == 0 {
typ = dagstream.RequestEvents
}
session := dagstream.Session{
ID: getSessionID(d.epoch, d.session.try),
Start: d.epoch.Bytes(),
Stop: (d.epoch + 1).Bytes(),
}
d.session.agent = peerleecher.New(&d.wg, d.cfg.Session, peerleecher.EpochDownloaderCallbacks{
OnlyNotConnected: d.callback.OnlyNotConnected,
RequestChunks: func(n dag.Metric, maxChunks uint32) error {
return d.callback.RequestChunk(peer, dagstream.Request{session, n, typ, maxChunks})
},
Suspend: func() bool {
return d.callback.Suspend(peer)
},
Done: func() bool {
return false
},
})
now := time.Now()
d.session.startTime = now
d.session.lastReceived = now
d.session.endTime = now
d.session.try++
d.session.peer = peer
d.session.agent.Start()
d.forceSyncing = false
}
func (d *Leecher) routine() {
if d.terminated {
return
}
if d.session.agent != nil && d.shouldTerminateSession() {
d.terminateSession()
}
if d.session.agent == nil {
candidates := d.selectSessionPeerCandidates()
if len(candidates) != 0 {
d.startSession(candidates)
}
}
}
func (d *Leecher) loop() {
syncTicker := time.NewTicker(d.cfg.RecheckInterval)
defer syncTicker.Stop()
for {
select {
case <-d.quit:
return
case <-syncTicker.C:
d.mu.Lock()
d.routine()
d.mu.Unlock()
}
}
}
// RegisterPeer injects a new download peer to download epochs from.
func (d *Leecher) RegisterPeer(peer string) error {
d.mu.Lock()
defer d.mu.Unlock()
if d.terminated {
return nil
}
d.peers[peer] = struct{}{}
return nil
}
func (d *Leecher) OnNewEpoch(myEpoch idx.Epoch) {
d.mu.Lock()
defer d.mu.Unlock()
if d.terminated {
return
}
d.terminateSession()
d.epoch = myEpoch
d.session.try = 0
d.emptyState = true
d.routine()
}
func (d *Leecher) PeersNum() int {
d.mu.RLock()
defer d.mu.RUnlock()
return len(d.peers)
}
func (d *Leecher) ForceSyncing() {
d.mu.Lock()
defer d.mu.Unlock()
d.forceSyncing = true
}
// UnregisterPeer removes a peer from the known list, preventing current or any future sessions with the peer
func (d *Leecher) UnregisterPeer(peer string) error {
d.mu.Lock()
defer d.mu.Unlock()
if d.session.peer == peer {
d.terminateSession()
d.routine()
}
delete(d.peers, peer)
return nil
}
func (d *Leecher) terminate() {
d.mu.Lock()
defer d.mu.Unlock()
d.terminated = true
close(d.quit)
d.terminateSession()
}
// Stop interrupts the leecher, canceling all the pending operations.
// Stop waits until all the internal goroutines have finished.
func (d *Leecher) Stop() {
d.terminate()
d.wg.Wait()
}
func (d *Leecher) NotifyChunkReceived(sessionID uint32, last hash.Event, done bool) error {
d.mu.Lock()
defer d.mu.Unlock()
if d.session.agent == nil {
return nil
}
if getSessionID(d.epoch, d.session.try-1) != sessionID {
return nil
}
d.session.lastReceived = time.Now()
if done {
d.terminateSession()
return nil
}
return d.session.agent.NotifyChunkReceived(last)
}