encapsulate retry delay calculation

This commit is contained in:
Matthias Radestock committed 2015-06-03 12:04:33 +01:00
1 parent fe5102580d
commit d1c41a97b1
1 file changed
+11 -11
+11 -11
View File
@@ -73,7 +73,7 @@ func (cm *ConnectionMaker) InitiateConnections(peers []string, replace bool) []e
cm.directPeers[peer] = addr
// curtail any existing reconnect interval
if target, found := cm.targets[addr.String()]; found {
target.tryAfter, target.tryInterval = tryImmediately()
target.tryNow()
}
}
return true
@@ -95,7 +95,7 @@ func (cm *ConnectionMaker) ConnectionTerminated(address string, err error) {
if target, found := cm.targets[address]; found {
target.attempting = false
target.lastError = err
target.tryAfter, target.tryInterval = tryAfter(target.tryInterval)
target.retry()
}
return true
}
@@ -191,7 +191,7 @@ func (cm *ConnectionMaker) checkStateAndAttemptConnections() time.Duration {
return
}
target := &Target{}
target.tryAfter, target.tryInterval = tryImmediately()
target.tryNow()
cm.targets[address] = target
}
@@ -303,17 +303,17 @@ func (cm *ConnectionMaker) attemptConnection(address string, acceptNewPeer bool)
}
}
func tryImmediately() (time.Time, time.Duration) {
return time.Now(), InitialInterval
func (t *Target) tryNow() {
t.tryAfter = time.Now()
t.tryInterval = InitialInterval
}
// The delay at the nth retry is a random value in the range
// [i-i/2,i+i/2], where i = InitialInterval * 1.5^(n-1).
func tryAfter(interval time.Duration) (time.Time, time.Duration) {
delay := interval/2 + time.Duration(rand.Int63n(int64(interval)))
nextInterval := interval * 3 / 2
if nextInterval > MaxInterval {
nextInterval = MaxInterval
func (t *Target) retry() {
t.tryAfter = time.Now().Add(t.tryInterval/2 + time.Duration(rand.Int63n(int64(t.tryInterval))))
t.tryInterval = t.tryInterval * 3 / 2
if t.tryInterval > MaxInterval {
t.tryInterval = MaxInterval
}
return time.Now().Add(delay), nextInterval
}