-
Notifications
You must be signed in to change notification settings - Fork 2
/
ring.go
130 lines (110 loc) · 2.21 KB
/
ring.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
125
126
127
128
129
130
package ring
import (
"errors"
"fmt"
hash1 "github.com/OneOfOne/xxhash"
"github.com/arriqaaq/rbt"
"sync"
)
var (
ERR_EMPTY_RING = errors.New("empty ring")
ERR_KEY_NOT_FOUND = errors.New("key not found")
)
type hasher interface {
hash(string) int64
}
func newXXHash() hasher {
return xxHash{}
}
// https://cyan4973.github.io/xxHash/
type xxHash struct {
}
func (x xxHash) hash(data string) int64 {
h := hash1.New32()
h.Write([]byte(data))
r := h.Sum32()
h.Reset()
return int64(r)
}
type Ring struct {
store *rbt.Tree
nodeMap map[string]bool
virtualNodes int
hashfn hasher
mu sync.RWMutex
}
func New() *Ring {
r := &Ring{
store: rbt.NewTree(),
nodeMap: make(map[string]bool),
hashfn: newXXHash(),
}
return r
}
func NewRing(nodes []string, virtualNodes int) *Ring {
r := &Ring{
store: rbt.NewTree(),
nodeMap: make(map[string]bool),
virtualNodes: virtualNodes,
hashfn: newXXHash(),
}
for _, node := range nodes {
r.Add(node)
}
return r
}
func (r *Ring) hash(val string) int64 {
return r.hashfn.hash(val)
}
func (r *Ring) Add(node string) {
r.mu.Lock()
defer r.mu.Unlock()
if _, ok := r.nodeMap[node]; ok {
return
}
r.nodeMap[node] = true
hashKey := r.hash(node)
r.store.Insert(hashKey, node)
for i := 0; i < r.virtualNodes; i++ {
vNodeKey := fmt.Sprintf("%s-%d", node, i)
r.nodeMap[vNodeKey] = true
hashKey := r.hash(vNodeKey)
r.store.Insert(hashKey, node)
}
}
func (r *Ring) Remove(node string) {
r.mu.Lock()
defer r.mu.Unlock()
if _, ok := r.nodeMap[node]; !ok {
return
}
hashKey := r.hash(node)
r.store.Delete(hashKey)
for i := 0; i < r.virtualNodes; i++ {
vNodeKey := fmt.Sprintf("%s-%d", node, i)
hashKey := r.hash(vNodeKey)
r.store.Delete(hashKey)
delete(r.nodeMap, vNodeKey)
}
delete(r.nodeMap, node)
}
func (r *Ring) Get(key string) (string, error) {
r.mu.RLock()
defer r.mu.RUnlock()
if r.store.Size() == 0 {
return "", ERR_EMPTY_RING
}
var q *rbt.Node
hashKey := r.hash(key)
q = r.store.Nearest(hashKey)
if hashKey > q.GetKey() {
g := rbt.FindSuccessor(q)
if g != nil {
q = g
} else {
// If no successor found, return root(wrap around)
q = r.store.Minimum()
}
}
return q.GetValue(), nil
}