/
rotational_slice.go
63 lines (50 loc) · 1.15 KB
/
rotational_slice.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
package rollKeys
import (
"context"
"errors"
)
type RotationalSlice[T any] struct {
s []*Limiter[T]
pickStrategy func([]*Limiter[T]) *Limiter[T]
}
func NewRotationalSlice[T any](slice []T, r int, options ...func(*RotationalSlice[T])) (*RotationalSlice[T], error) {
if len(slice) == 0 {
return nil, errors.New("empty slice")
}
if r <= 0 {
return nil, errors.New("rate must be positive")
}
var ls = make([]*Limiter[T], len(slice))
for i, obj := range slice {
ls[i] = NewLimiter(obj, r)
}
c := &RotationalSlice[T]{
s: ls,
pickStrategy: DefaultPickStrategy[T](0),
}
for _, option := range options {
option(c)
}
return c, nil
}
func (c *RotationalSlice[T]) Get(ctx context.Context) (T, error) {
for _, l := range c.s {
if l.Allow() {
return l.key, nil
}
}
l := c.pick()
err := l.Wait(ctx)
if err != nil {
return l.key, err
}
return l.key, nil
}
func (c *RotationalSlice[T]) pick() *Limiter[T] {
return c.pickStrategy(c.s)
}
func WithPickStrategy[T any](pickStrategy func([]*Limiter[T]) *Limiter[T]) func(*RotationalSlice[T]) {
return func(c *RotationalSlice[T]) {
c.pickStrategy = pickStrategy
}
}