-
Notifications
You must be signed in to change notification settings - Fork 453
/
store.go
295 lines (241 loc) · 6.58 KB
/
store.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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package mem
import (
"errors"
"sync"
"github.com/m3db/m3/src/cluster/kv"
"github.com/golang/protobuf/proto"
)
// NewStore returns a new in-process store that can be used for testing
func NewStore() kv.TxnStore {
return &store{
values: make(map[string][]*value),
watchables: make(map[string]kv.ValueWatchable),
}
}
// NewValue returns a new fake Value around the given proto
func NewValue(vers int, msg proto.Message) kv.Value {
data, _ := proto.Marshal(msg)
return &value{
version: vers,
data: data,
}
}
// NewValueWithData returns a new fake Value around the given data
func NewValueWithData(vers int, data []byte) kv.Value {
return &value{
version: vers,
data: data,
}
}
type value struct {
version int
revision int
data []byte
}
func (v value) Version() int { return v.version }
func (v value) Unmarshal(msg proto.Message) error { return proto.Unmarshal(v.data, msg) }
func (v value) IsNewer(other kv.Value) bool {
otherValue, ok := other.(*value)
if !ok {
return v.version > other.Version()
}
if v.revision == otherValue.revision {
return v.version > other.Version()
}
return v.revision > otherValue.revision
}
type store struct {
sync.RWMutex
revision int
values map[string][]*value
watchables map[string]kv.ValueWatchable
}
func (s *store) Get(key string) (kv.Value, error) {
s.RLock()
defer s.RUnlock()
return s.getWithLock(key)
}
func (s *store) getWithLock(key string) (kv.Value, error) {
val, ok := s.values[key]
if !ok {
return nil, kv.ErrNotFound
}
if len(val) == 0 {
return nil, kv.ErrNotFound
}
return val[len(val)-1], nil
}
func (s *store) Watch(key string) (kv.ValueWatch, error) {
s.Lock()
val := s.values[key]
watchable, ok := s.watchables[key]
if !ok {
watchable = kv.NewValueWatchable()
s.watchables[key] = watchable
}
s.Unlock()
if !ok && len(val) != 0 {
watchable.Update(val[len(val)-1])
}
_, watch, _ := watchable.Watch()
return watch, nil
}
func (s *store) Set(key string, val proto.Message) (int, error) {
s.Lock()
defer s.Unlock()
return s.setWithLock(key, val)
}
func (s *store) setWithLock(key string, val proto.Message) (int, error) {
data, err := proto.Marshal(val)
if err != nil {
return 0, err
}
lastVersion := 0
vals := s.values[key]
if len(vals) != 0 {
lastVersion = vals[len(vals)-1].version
}
newVersion := lastVersion + 1
s.updateInternalWithLock(key, newVersion, data)
return newVersion, nil
}
func (s *store) SetIfNotExists(key string, val proto.Message) (int, error) {
data, err := proto.Marshal(val)
if err != nil {
return 0, err
}
s.Lock()
defer s.Unlock()
if _, exists := s.values[key]; exists {
return 0, kv.ErrAlreadyExists
}
s.updateInternalWithLock(key, 1, data)
return 1, nil
}
func (s *store) CheckAndSet(key string, version int, val proto.Message) (int, error) {
data, err := proto.Marshal(val)
if err != nil {
return 0, err
}
s.Lock()
defer s.Unlock()
lastVersion := 0
vals, exists := s.values[key]
if exists && len(vals) != 0 {
lastVersion = vals[len(vals)-1].version
}
if version != lastVersion {
return 0, kv.ErrVersionMismatch
}
newVersion := version + 1
s.updateInternalWithLock(key, newVersion, data)
return newVersion, nil
}
func (s *store) updateInternalWithLock(key string, newVersion int, data []byte) {
s.revision++
fv := &value{
version: newVersion,
revision: s.revision,
data: data,
}
s.values[key] = append(s.values[key], fv)
s.updateWatchable(key, fv)
}
func (s *store) Delete(key string) (kv.Value, error) {
s.Lock()
defer s.Unlock()
val, ok := s.values[key]
if !ok {
return nil, kv.ErrNotFound
}
prev := val[len(val)-1]
s.updateWatchable(key, nil)
delete(s.values, key)
return prev, nil
}
func (s *store) History(key string, from, to int) ([]kv.Value, error) {
if from <= 0 || to <= 0 || from > to {
return nil, errors.New("bad request")
}
if from == to {
return nil, nil
}
s.RLock()
defer s.RUnlock()
vals, ok := s.values[key]
if !ok {
return nil, kv.ErrNotFound
}
l := len(vals)
if l == 0 {
return nil, kv.ErrNotFound
}
var res []kv.Value
for i := from; i < to; i++ {
idx := i - 1
if idx >= 0 && idx < l {
res = append(res, vals[idx])
}
}
return res, nil
}
// NB(cw) When there is an error in one of the ops, the finished ops will not be rolled back
func (s *store) Commit(conditions []kv.Condition, ops []kv.Op) (kv.Response, error) {
s.Lock()
defer s.Unlock()
for _, condition := range conditions {
if condition.CompareType() != kv.CompareEqual || condition.TargetType() != kv.TargetVersion {
return nil, errors.New("invalid condition")
}
v, err := s.getWithLock(condition.Key())
expectedVersion := condition.Value().(int)
if err != nil {
if err == kv.ErrNotFound && expectedVersion == 0 {
continue
}
return nil, err
}
if expectedVersion != v.Version() {
return nil, kv.ErrConditionCheckFailed
}
}
oprs := make([]kv.OpResponse, len(ops))
for i, op := range ops {
if op.Type() != kv.OpSet {
return nil, errors.New("invalid op")
}
opSet := op.(kv.SetOp)
v, err := s.setWithLock(opSet.Key(), opSet.Value)
if err != nil {
return nil, err
}
oprs[i] = kv.NewOpResponse(op).SetValue(v)
}
return kv.NewResponse().SetResponses(oprs), nil
}
// updateWatchable updates all subscriptions for the given key. It assumes
// the fakeStore write lock is acquired outside of this call
func (s *store) updateWatchable(key string, newVal kv.Value) {
if watchable, ok := s.watchables[key]; ok {
watchable.Update(newVal)
}
}