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
package netretry
import (
"context"
"errors"
"io"
"net"
"net/http"
"sync"
"time"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/authretry"
)
const (
First = 2 * time.Second
Cap = 30 * time.Second
)
func Transient(err error) bool {
if err == nil || errors.Is(err, context.Canceled) {
return false
}
if status := authretry.Status(err); status != 0 {
return status >= http.StatusInternalServerError || status == http.StatusTooManyRequests
}
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, io.ErrUnexpectedEOF) {
return true
}
var netErr net.Error
return errors.As(err, &netErr)
}
func After(err error) time.Duration {
var hinted interface{ RetryAfter() time.Duration }
if errors.As(err, &hinted) {
return max(hinted.RetryAfter(), 0)
}
return 0
}
func Delay(failures int) time.Duration {
d := First
for i := 1; i < failures && d < Cap; i++ {
d *= 2
}
return min(d, Cap)
}
type Tracker[K comparable] struct {
mu sync.Mutex
failures map[K]int
}
func NewTracker[K comparable]() *Tracker[K] {
return &Tracker[K]{failures: map[K]int{}}
}
func (t *Tracker[K]) Fail(key K) (int, time.Duration) {
t.mu.Lock()
defer t.mu.Unlock()
n := t.failures[key] + 1
t.failures[key] = n
return n, Delay(n)
}
func (t *Tracker[K]) Reset(key K) {
t.mu.Lock()
defer t.mu.Unlock()
delete(t.failures, key)
}