-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathstore.go
442 lines (366 loc) · 9.07 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
// Copyright (c) 2020 SDSLabs
// Use of this source code is governed by an MIT license
// details of which can be found in the LICENSE file.
package kiwi
import (
"encoding/json"
"fmt"
"strings"
"sync"
)
// Various errors related to keys.
var (
ErrKeyExists = fmt.Errorf("key already exists")
ErrKeyNotExist = fmt.Errorf("key does not exist")
)
// newKeyErr creates a new err with related key.
func newKeyErr(err error, key string) error {
return fmt.Errorf("%w: %s", err, key)
}
// Store is the main element that contains and manages all the key value pairs.
type Store struct {
kv map[string]valWrapper
mu sync.RWMutex
}
// NewStore creates an empty store without any key value pairs initialized.
func NewStore() *Store {
return &Store{
kv: make(map[string]valWrapper),
mu: sync.RWMutex{},
}
}
// NewStoreFromSchema creates a new store from the provided schema.
func NewStoreFromSchema(schema Schema) (*Store, error) {
s := NewStore()
for key, val := range schema {
if err := s.AddKey(key, val); err != nil {
return nil, err
}
}
return s, nil
}
// KeyExists tells if the key exists or not.
func (s *Store) KeyExists(key string) bool {
s.mu.RLock()
exists := s.keyExists(key) == nil
s.mu.RUnlock()
return exists
}
// AddKey adds a new key to the store. It throws an error if the key already exists.
func (s *Store) AddKey(key string, typ ValueType) error {
s.mu.Lock()
if err := s.keyNotExist(key); err != nil {
s.mu.Unlock()
return err
}
v, err := newValue(typ)
if err != nil {
s.mu.Unlock()
return err
}
s.setValWrapper(key, v)
s.mu.Unlock()
return nil
}
// UpdateKey updates the key if it exists. Throws an error if it doesn't.
func (s *Store) UpdateKey(key string, typ ValueType) error {
s.mu.Lock()
if err := s.keyExists(key); err != nil {
s.mu.Unlock()
return err
}
v, err := newValue(typ)
if err != nil {
s.mu.Unlock()
return err
}
old := s.kv[key]
old.mu.Lock()
s.setValWrapper(key, v)
old.mu.Unlock()
s.mu.Unlock()
return nil
}
// setValWrapper sets the value for given key in store.
func (s *Store) setValWrapper(key string, val Value) {
s.kv[key] = valWrapper{
val: val,
mu: &sync.RWMutex{},
doMapCached: val.DoMap(),
}
}
// DeleteKey deletes the key if it exists. Throws an error if it doesn't.
func (s *Store) DeleteKey(key string) error {
s.mu.Lock()
if err := s.keyExists(key); err != nil {
s.mu.Unlock()
return err
}
old := s.kv[key]
old.mu.Lock()
delete(s.kv, key)
old.mu.Unlock()
s.mu.Unlock()
return nil
}
// GetValueType returns the type of value corresponding to the key.
func (s *Store) GetValueType(key string) (ValueType, error) {
s.mu.RLock()
if err := s.keyExists(key); err != nil {
s.mu.RUnlock()
return "", err
}
v := s.kv[key]
s.mu.RUnlock()
v.mu.RLock()
typ := v.val.Type()
v.mu.RUnlock()
return typ, nil
}
// GetSchema returns the schema of the store.
func (s *Store) GetSchema() Schema {
s.mu.RLock()
schema := s.getSchema()
s.mu.RUnlock()
return schema
}
// getSchema returns the schema.
func (s *Store) getSchema() Schema {
schema := make(Schema)
for k := range s.kv {
schema[k] = s.kv[k].val.Type()
}
return schema
}
// Do executes the action for the value associated with the key.
func (s *Store) Do(key string, action Action, params ...interface{}) (interface{}, error) {
s.mu.RLock()
if err := s.keyExists(key); err != nil {
s.mu.RUnlock()
return nil, err
}
v := s.kv[key]
s.mu.RUnlock()
doFunc, ok := v.doMapCached[action]
if !ok {
return nil, fmt.Errorf("%w: %v", ErrInvalidAction, action)
}
v.mu.Lock()
res, err := doFunc(params...)
v.mu.Unlock()
return res, err
}
// ToJSON converts the data associated with the value into JSON format.
func (s *Store) ToJSON(key string) (json.RawMessage, error) {
s.mu.RLock()
if err := s.keyExists(key); err != nil {
s.mu.RUnlock()
return nil, err
}
v := s.kv[key]
s.mu.RUnlock()
v.mu.RLock()
jsonval, err := s.toJSON(&v)
v.mu.RUnlock()
return jsonval, err
}
// toJSON converts the value's data to JSON.
func (s *Store) toJSON(v *valWrapper) (json.RawMessage, error) {
res, err := v.val.ToJSON()
if err != nil {
return nil, fmt.Errorf("error in ToJSON: %v", err)
}
return res, nil
}
// FromJSON takes the raw JSON form of data and loads it into the value.
func (s *Store) FromJSON(key string, rawmessage json.RawMessage) error {
s.mu.RLock()
if err := s.keyExists(key); err != nil {
s.mu.RUnlock()
return err
}
v := s.kv[key]
s.mu.RUnlock()
v.mu.Lock()
err := s.fromJSON(&v, rawmessage)
v.mu.Unlock()
return err
}
// fromJSON converts the raw JSON to the value.
func (s *Store) fromJSON(v *valWrapper, rawmessage json.RawMessage) error {
if err := v.val.FromJSON(rawmessage); err != nil {
return fmt.Errorf("error in FromJSON: %v", err)
}
return nil
}
// ValJSON is the JSON object for each value.
type ValJSON struct {
Type string `json:"type"`
Data json.RawMessage `json:"data"`
}
// StoreJSON is the type which includes all the data for the store.
type StoreJSON = map[string]ValJSON
// Export returns JSON data for the store.
//
// The data is in the format (StoreJSON):
//
// {
// "key_1": {
// "type": "str",
// "data": "hello"
// },
// "key_2": {
// "type": "hash",
// "data": {
// "a": "b",
// "c": "d"
// }
// }
// }
//
func (s *Store) Export() (json.RawMessage, error) {
s.mu.RLock()
schema := s.getSchema()
sjson := make(StoreJSON, len(schema))
for k, v := range schema {
vw := s.kv[k]
vw.mu.RLock()
data, err := s.toJSON(&vw)
vw.mu.Unlock()
if err != nil {
s.mu.RUnlock()
return nil, fmt.Errorf("error exporting for %q key: %v", k, err)
}
sjson[k] = ValJSON{
Type: string(v),
Data: data,
}
}
s.mu.RUnlock()
c, err := json.Marshal(sjson)
if err != nil {
return nil, err
}
return c, nil
}
// ImportOpts are the options that can be used to configure how to import
// data into the store from raw JSON.
type ImportOpts struct {
// AddKeys specifies whether to add keys that do not exist.
AddKeys bool
// UpdateTypes specifies if the type of key in JSON doesn't match the one
// with already-defined key, should the type of key be updated or not.
UpdateTypes bool
// ErrOnInvalidKey specifies whether to throw error if the key in the JSON
// does not exist in the actual schema of the Store.
// This option is considered only when `AddKeys` is false.
ErrOnInvalidKey bool
}
// Import loads store from the data.
//
// The default behavior is that the store takes the data from the JSON and
// if an unknown key exists, i.e., a key that is not already added to the
// store, it silently skips the value associated with it. This can be
// configured using the ImportOpts.
//
// The data is in the format (StoreJSON):
//
// {
// "key_1": {
// "type": "str",
// "data": "hello"
// },
// "key_2": {
// "type": "hash",
// "data": {
// "a": "b",
// "c": "d"
// }
// }
// }
//
func (s *Store) Import(rawmessage json.RawMessage, opts ImportOpts) error {
var sjson StoreJSON
if err := json.Unmarshal(rawmessage, &sjson); err != nil {
return err
}
// Lock the store for whole of the process now.
s.mu.Lock()
for k := range sjson {
if err := s.keyExists(k); err != nil {
if !opts.AddKeys && !opts.ErrOnInvalidKey {
continue
}
if !opts.AddKeys && opts.ErrOnInvalidKey {
s.mu.Unlock()
return err
}
if opts.AddKeys {
if er := s.AddKey(k, ValueType(sjson[k].Type)); er != nil {
s.mu.Unlock()
return er
}
}
}
// now that the key exists
v := s.kv[k]
v.mu.Lock()
if sjson[k].Type != string(v.val.Type()) {
if !opts.UpdateTypes {
v.mu.Unlock()
s.mu.Unlock()
return fmt.Errorf("value type in JSON and store schema do not match")
}
if er := s.UpdateKey(k, ValueType(sjson[k].Type)); er != nil {
v.mu.Unlock()
s.mu.Unlock()
return er
}
}
if err := s.FromJSON(k, sjson[k].Data); err != nil {
v.mu.Unlock()
s.mu.Unlock()
return err
}
v.mu.Unlock()
}
s.mu.Unlock()
return nil
}
// keyExists checks if the key exists in the store. Throws an error if it doesn't.
func (s *Store) keyExists(key string) error {
if _, ok := s.kv[key]; !ok {
return newKeyErr(ErrKeyNotExist, key)
}
return nil
}
// keyExists checks if the key does not exist in the store. Throws an error if it does.
func (s *Store) keyNotExist(key string) error {
if err := s.keyExists(key); err == nil {
return newKeyErr(ErrKeyExists, key)
}
return nil
}
// Schema contains the value types corresponding to their keys.
type Schema map[string]ValueType
// String implements the fmt.Stringer interface.
func (s Schema) String() string {
strs := make([]string, len(s)+2)
i := 1
for key := range s {
strs[i] = fmt.Sprintf("\t%s: %s", key, s[key])
i++
}
strs[0], strs[len(s)+1] = "{", "}"
return strings.Join(strs, "\n")
}
// valWrapper contains the value as well as it's mutex.
type valWrapper struct {
mu *sync.RWMutex
val Value
// caching do map avoids allocation for the map each time an action is
// executed, hence, improving the performance.
doMapCached map[Action]DoFunc
}
// Interface guard.
var _ fmt.Stringer = (*Schema)(nil)