forked from aergoio/aergo
/
reconnect.go
77 lines (66 loc) · 1.73 KB
/
reconnect.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
/** @file
* @copyright defined in aergo/LICENSE.txt
*/
package p2p
import (
"math"
"time"
"github.com/aergoio/aergo/p2p/p2pcommon"
"github.com/aergoio/aergo/p2p/p2putil"
"github.com/aergoio/aergo-lib/log"
)
var (
durations []time.Duration
maxTrial = 15
)
func init() {
// It will get [20s 36s 1m6s 2m1s 3m40s 6m42s 12m12s 22m14s 40m30s 1h13m48s 2h14m29s 4h5m2s 7h26m29s 13h33m32s 24h42m21s]
durations = generateExpDuration(20, 0.6, maxTrial)
}
type reconnectJob struct {
meta p2pcommon.PeerMeta
trial int
pm p2pcommon.PeerManager
logger *log.Logger
cancel chan struct{}
}
func newReconnectRunner(meta p2pcommon.PeerMeta, pm p2pcommon.PeerManager, logger *log.Logger) *reconnectJob {
return &reconnectJob{meta: meta, trial: 0, pm: pm, cancel: make(chan struct{}, 1), logger: logger}
}
func (rj *reconnectJob) runJob() {
timer := time.NewTimer(getNextInterval(rj.trial))
RETRYLOOP:
for {
// wait for duration
select {
case <-timer.C:
_, found := rj.pm.GetPeer(rj.meta.ID)
if found {
break RETRYLOOP
}
rj.logger.Debug().Str("peer_meta", p2putil.ShortMetaForm(rj.meta)).Int("trial", rj.trial).Msg("Trying to connect")
rj.pm.AddNewPeer(rj.meta)
rj.trial++
timer.Reset(getNextInterval(rj.trial))
case <-rj.cancel:
break RETRYLOOP
}
}
//rj.rm.jobFinished(rj.meta.ID)
}
func getNextInterval(trial int) time.Duration {
if trial < maxTrial {
return durations[trial]
}
return durations[maxTrial-1]
}
func generateExpDuration(initSecs int, inc float64, count int) []time.Duration {
arr := make([]time.Duration, 0, count)
num := float64(0)
for i := 0; i < count; i++ {
x := math.Exp(num) * float64(initSecs)
arr = append(arr, time.Second*time.Duration(math.Round(x)))
num += inc
}
return arr
}