-
Notifications
You must be signed in to change notification settings - Fork 22
/
request_controller.go
82 lines (65 loc) · 1.67 KB
/
request_controller.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
78
79
80
81
82
package api
import (
"fmt"
"sync"
"time"
)
type RequestController struct {
publicKeysInUse sync.Map
maximumAttempt uint
intervalDelayBetweenRetries time.Duration
}
func (c *RequestController) IsPublicKeyAlreadyInUse(publicKey string) (func(), error) {
doneCh, err := c.impatientWait(publicKey)
if err != nil {
return nil, err
}
go func() {
<-doneCh
c.publicKeysInUse.Delete(publicKey)
}()
return func() {
close(doneCh)
}, nil
}
func (c *RequestController) impatientWait(publicKey string) (chan interface{}, error) {
tick := time.NewTicker(c.intervalDelayBetweenRetries)
defer tick.Stop()
doneCh := make(chan interface{})
attemptsLeft := c.maximumAttempt
for attemptsLeft > 0 {
if _, alreadyInUse := c.publicKeysInUse.LoadOrStore(publicKey, doneCh); !alreadyInUse {
return doneCh, nil
}
<-tick.C
attemptsLeft--
}
close(doneCh)
return nil, fmt.Errorf("this public key %q is already in use, retry later", publicKey)
}
func DefaultRequestController() *RequestController {
return NewRequestController(
WithMaximumAttempt(10),
WithIntervalDelayBetweenRetries(2*time.Second),
)
}
func NewRequestController(opts ...RequestControllerOptionFn) *RequestController {
rq := &RequestController{
publicKeysInUse: sync.Map{},
}
for _, opt := range opts {
opt(rq)
}
return rq
}
type RequestControllerOptionFn func(rq *RequestController)
func WithMaximumAttempt(max uint) RequestControllerOptionFn {
return func(rq *RequestController) {
rq.maximumAttempt = max
}
}
func WithIntervalDelayBetweenRetries(duration time.Duration) RequestControllerOptionFn {
return func(rq *RequestController) {
rq.intervalDelayBetweenRetries = duration
}
}