forked from lafikl/consistent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconsistent.go
124 lines (103 loc) · 2.36 KB
/
consistent.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
// An implementation of Consistent Hashing and
// Consistent Hashing With Bounded Loads.
//
// https://en.wikipedia.org/wiki/Consistent_hashing
//
// https://research.googleblog.com/2017/04/consistent-hashing-with-bounded-loads.html
package consistent
import (
"errors"
"fmt"
"sort"
"sync"
"github.com/OneOfOne/xxhash"
)
var ErrNoHosts = errors.New("no hosts added")
type Host struct {
Name string
}
type Consistent struct {
hosts map[uint64]string
sortedSet []uint64
replicationFactor int
sync.RWMutex
}
func New(factor int) *Consistent {
return &Consistent{
hosts: map[uint64]string{},
sortedSet: []uint64{},
replicationFactor: factor,
}
}
func (c *Consistent) Add(host string) {
c.Lock()
defer c.Unlock()
for i := 0; i < c.replicationFactor; i++ {
h := c.hash(fmt.Sprintf("%s%d", host, i))
c.hosts[h] = host
c.sortedSet = append(c.sortedSet, h)
}
// sort hashes ascendingly
sort.Slice(c.sortedSet, func(i int, j int) bool {
if c.sortedSet[i] < c.sortedSet[j] {
return true
}
return false
})
}
// Returns the host that owns `key`.
//
// As described in https://en.wikipedia.org/wiki/Consistent_hashing
//
// It returns ErrNoHosts if the ring has no hosts in it.
func (c *Consistent) Get(key string) (string, error) {
c.RLock()
defer c.RUnlock()
if len(c.hosts) == 0 {
return "", ErrNoHosts
}
h := c.hash(key)
idx := c.search(h)
return c.hosts[c.sortedSet[idx]], nil
}
func (c *Consistent) search(key uint64) int {
idx := sort.Search(len(c.sortedSet), func(i int) bool {
return c.sortedSet[i] >= key
})
if idx >= len(c.sortedSet) {
idx = 0
}
return idx
}
// Deletes host from the ring
func (c *Consistent) Remove(host string) bool {
c.Lock()
defer c.Unlock()
for i := 0; i < c.replicationFactor; i++ {
h := c.hash(fmt.Sprintf("%s%d", host, i))
delete(c.hosts, h)
c.delSlice(h)
}
return true
}
// Return the list of hosts in the ring
func (c *Consistent) Hosts() (hosts []string) {
c.RLock()
defer c.RUnlock()
for _, host := range c.hosts {
hosts = append(hosts, host)
}
return hosts
}
func (c *Consistent) delSlice(val uint64) {
for i := 0; i < len(c.sortedSet); i++ {
if c.sortedSet[i] == val {
c.sortedSet = append(c.sortedSet[:i], c.sortedSet[i+1:]...)
}
}
}
func (c *Consistent) hash(key string) uint64 {
h := xxhash.New64()
h.Write([]byte(key))
return h.Sum64()
}