-
Notifications
You must be signed in to change notification settings - Fork 2
/
policy.go
68 lines (57 loc) · 1.34 KB
/
policy.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
package https
import (
"math"
"math/rand"
"sync/atomic"
)
// policy defines a policy we use for selecting upstreams.
type policy interface {
List(poolLen int) []int
}
// randomPolicy is a policy that implements random upstream selection.
type randomPolicy struct{}
func newRandomPolicy() *randomPolicy {
return &randomPolicy{}
}
func (*randomPolicy) List(poolLen int) []int {
if poolLen <= 0 {
return nil
}
return rand.Perm(poolLen)
}
// roundRobinPolicy is a policy that selects hosts based on round robin ordering.
type roundRobinPolicy struct {
robin uint32
}
func newRoundRobinPolicy() *roundRobinPolicy {
return &roundRobinPolicy{robin: math.MaxUint32}
}
func (p *roundRobinPolicy) List(poolLen int) (result []int) {
if poolLen <= 0 {
return
}
result = make([]int, 0, poolLen)
i := int(atomic.AddUint32(&p.robin, 1) % uint32(poolLen))
for j := i; j < poolLen; j++ {
result = append(result, j)
}
for j := 0; j < i; j++ {
result = append(result, j)
}
return
}
// sequentialPolicy is a policy that selects hosts based on sequential ordering.
type sequentialPolicy struct{}
func newSequentialPolicy() *sequentialPolicy {
return &sequentialPolicy{}
}
func (*sequentialPolicy) List(poolLen int) (result []int) {
if poolLen <= 0 {
return
}
result = make([]int, poolLen)
for i := 0; i < poolLen; i++ {
result[i] = i
}
return
}