~emersion/soju

ref: ce19f76673b5bfd369766f6696e042b0a8df7691 soju/rate.go -rw-r--r-- 603 bytes
ce19f766Simon Ser database/postgres: fix inverted networkID check in ListWebPushSubscriptions 4 months ago
                                                                                
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
package soju

import (
	"math/rand"
	"time"
)

// backoffer implements a simple exponential backoff.
type backoffer struct {
	min, max, jitter time.Duration
	n                int64
}

func newBackoffer(min, max, jitter time.Duration) *backoffer {
	return &backoffer{min: min, max: max, jitter: jitter}
}

func (b *backoffer) Reset() {
	b.n = 0
}

func (b *backoffer) Next() time.Duration {
	if b.n == 0 {
		b.n = 1
		return 0
	}

	d := time.Duration(b.n) * b.min
	if d > b.max {
		d = b.max
	} else {
		b.n *= 2
	}

	if b.jitter != 0 {
		d += time.Duration(rand.Int63n(int64(b.jitter)))
	}

	return d
}