Last change
on this file since 791 was 735, checked in by contact, 4 years ago |
Add exponential backoff when re-connecting to upstream
The first reconnection attempt waits for 1min, the second the 2min,
and so on up to 10min. There's a 1min jitter so that multiple failed
connections don't try to reconnect at the exact same time.
Closes: https://todo.sr.ht/~emersion/soju/161
|
File size:
603 bytes
|
Rev | Line | |
---|
[735] | 1 | package soju
|
---|
| 2 |
|
---|
| 3 | import (
|
---|
| 4 | "math/rand"
|
---|
| 5 | "time"
|
---|
| 6 | )
|
---|
| 7 |
|
---|
| 8 | // backoffer implements a simple exponential backoff.
|
---|
| 9 | type backoffer struct {
|
---|
| 10 | min, max, jitter time.Duration
|
---|
| 11 | n int64
|
---|
| 12 | }
|
---|
| 13 |
|
---|
| 14 | func newBackoffer(min, max, jitter time.Duration) *backoffer {
|
---|
| 15 | return &backoffer{min: min, max: max, jitter: jitter}
|
---|
| 16 | }
|
---|
| 17 |
|
---|
| 18 | func (b *backoffer) Reset() {
|
---|
| 19 | b.n = 0
|
---|
| 20 | }
|
---|
| 21 |
|
---|
| 22 | func (b *backoffer) Next() time.Duration {
|
---|
| 23 | if b.n == 0 {
|
---|
| 24 | b.n = 1
|
---|
| 25 | return 0
|
---|
| 26 | }
|
---|
| 27 |
|
---|
| 28 | d := time.Duration(b.n) * b.min
|
---|
| 29 | if d > b.max {
|
---|
| 30 | d = b.max
|
---|
| 31 | } else {
|
---|
| 32 | b.n *= 2
|
---|
| 33 | }
|
---|
| 34 |
|
---|
| 35 | if b.jitter != 0 {
|
---|
| 36 | d += time.Duration(rand.Int63n(int64(b.jitter)))
|
---|
| 37 | }
|
---|
| 38 |
|
---|
| 39 | return d
|
---|
| 40 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.