forked from influxdata/influxdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
store_base.go
576 lines (489 loc) · 14.3 KB
/
store_base.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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
package kv
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/influxdata/influxdb/v2/kit/platform"
errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors"
"github.com/influxdata/influxdb/v2/kit/tracing"
"github.com/opentracing/opentracing-go"
)
type Entity struct {
PK EncodeFn
UniqueKey EncodeFn
Body interface{}
}
// EncodeEntFn encodes the entity. This is used both for the key and vals in the store base.
type EncodeEntFn func(ent Entity) ([]byte, string, error)
// EncIDKey encodes an entity into a key that represents the encoded ID provided.
func EncIDKey(ent Entity) ([]byte, string, error) {
if ent.PK == nil {
return nil, "ID", errors.New("no ID provided")
}
key, err := ent.PK()
return key, "ID", err
}
// EncUniqKey encodes the unique key.
func EncUniqKey(ent Entity) ([]byte, string, error) {
if ent.UniqueKey == nil {
return nil, "Unique Key", errors.New("no unique key provided")
}
key, err := ent.UniqueKey()
return key, "Unique Key", err
}
// EncBodyJSON JSON encodes the entity body and returns the raw bytes and indicates
// that it uses the entity body.
func EncBodyJSON(ent Entity) ([]byte, string, error) {
v, err := json.Marshal(ent.Body)
return v, "entity body", err
}
// DecodeBucketValFn decodes the raw []byte.
type DecodeBucketValFn func(key, val []byte) (keyRepeat []byte, decodedVal interface{}, err error)
// DecIndexID decodes the bucket val into an influxdb.ID.
func DecIndexID(key, val []byte) ([]byte, interface{}, error) {
var i platform.ID
return key, i, i.Decode(val)
}
// ConvertValToEntFn converts a key and decoded bucket value to an entity.
type ConvertValToEntFn func(k []byte, v interface{}) (Entity, error)
// DecodeOrgNameKey decodes a raw bucket key into the organization id and name
// used to create it.
func DecodeOrgNameKey(k []byte) (platform.ID, string, error) {
var orgID platform.ID
if err := orgID.Decode(k[:platform.IDLength]); err != nil {
return 0, "", err
}
return orgID, string(k[platform.IDLength:]), nil
}
// NewOrgNameKeyStore creates a store for an entity's unique index on organization id and name.
// This is used throughout the kv pkg here to provide an entity uniquness by name within an org.
func NewOrgNameKeyStore(resource string, bktName []byte, caseSensitive bool) *StoreBase {
var decValToEntFn ConvertValToEntFn = func(k []byte, v interface{}) (Entity, error) {
id, ok := v.(platform.ID)
if err := IsErrUnexpectedDecodeVal(ok); err != nil {
return Entity{}, err
}
ent := Entity{PK: EncID(id)}
if len(k) == 0 {
return ent, nil
}
orgID, name, err := DecodeOrgNameKey(k)
if err != nil {
return Entity{}, err
}
nameEnc := EncString(name)
if !caseSensitive {
nameEnc = EncStringCaseInsensitive(name)
}
ent.UniqueKey = Encode(EncID(orgID), nameEnc)
return ent, nil
}
return NewStoreBase(resource, bktName, EncUniqKey, EncIDKey, DecIndexID, decValToEntFn)
}
// StoreBase is the base behavior for accessing buckets in kv. It provides mechanisms that can
// be used in composing stores together (i.e. IndexStore).
type StoreBase struct {
Resource string
BktName []byte
EncodeEntKeyFn EncodeEntFn
EncodeEntBodyFn EncodeEntFn
DecodeEntFn DecodeBucketValFn
ConvertValToEntFn ConvertValToEntFn
}
// NewStoreBase creates a new store base.
func NewStoreBase(resource string, bktName []byte, encKeyFn, encBodyFn EncodeEntFn, decFn DecodeBucketValFn, decToEntFn ConvertValToEntFn) *StoreBase {
return &StoreBase{
Resource: resource,
BktName: bktName,
EncodeEntKeyFn: encKeyFn,
EncodeEntBodyFn: encBodyFn,
DecodeEntFn: decFn,
ConvertValToEntFn: decToEntFn,
}
}
// EntKey returns the key for the entity provided. This is a shortcut for grabbing the EntKey without
// having to juggle the encoding funcs.
func (s *StoreBase) EntKey(ctx context.Context, ent Entity) ([]byte, error) {
span, ctx := s.startSpan(ctx)
defer span.Finish()
return s.encodeEnt(ctx, ent, s.EncodeEntKeyFn)
}
type (
// DeleteOpts provides indicators to the store.Delete call for deleting a given
// entity. The FilterFn indicates the current value should be deleted when returning
// true.
DeleteOpts struct {
DeleteRelationFns []DeleteRelationsFn
FilterFn FilterFn
}
// DeleteRelationsFn is a hook that a store that composes other stores can use to
// delete an entity and any relations it may share. An example would be deleting an
// an entity and its associated index.
DeleteRelationsFn func(key []byte, decodedVal interface{}) error
)
// Delete deletes entities by the provided options.
func (s *StoreBase) Delete(ctx context.Context, tx Tx, opts DeleteOpts) error {
span, ctx := s.startSpan(ctx)
defer span.Finish()
if opts.FilterFn == nil {
return nil
}
findOpts := FindOpts{
CaptureFn: func(k []byte, v interface{}) error {
for _, deleteFn := range opts.DeleteRelationFns {
if err := deleteFn(k, v); err != nil {
return err
}
}
return s.bucketDelete(ctx, tx, k)
},
FilterEntFn: opts.FilterFn,
}
return s.Find(ctx, tx, findOpts)
}
// DeleteEnt deletes an entity.
func (s *StoreBase) DeleteEnt(ctx context.Context, tx Tx, ent Entity) error {
span, ctx := s.startSpan(ctx)
defer span.Finish()
encodedID, err := s.EntKey(ctx, ent)
if err != nil {
return err
}
return s.bucketDelete(ctx, tx, encodedID)
}
type (
// FindOpts provided a means to search through the bucket. When a filter func
// is provided, that will run against the entity and if the filter responds true,
// will count it towards the number of entries seen and the capture func will be
// run with it provided to it.
FindOpts struct {
Descending bool
Offset int
Limit int
Prefix []byte
CaptureFn FindCaptureFn
FilterEntFn FilterFn
}
// FindCaptureFn is the mechanism for closing over the key and decoded value pair
// for adding results to the call sites collection. This generic implementation allows
// it to be reused. The returned decodedVal should always satisfy whatever decoding
// of the bucket value was set on the storeo that calls Find.
FindCaptureFn func(key []byte, decodedVal interface{}) error
// FilterFn will provide an indicator to the Find or Delete calls that the entity that
// was seen is one that is valid and should be either captured or deleted (depending on
// the caller of the filter func).
FilterFn func(key []byte, decodedVal interface{}) bool
)
// Find provides a mechanism for looking through the bucket via
// the set options. When a prefix is provided, the prefix is used to
// seek the bucket.
func (s *StoreBase) Find(ctx context.Context, tx Tx, opts FindOpts) error {
span, ctx := s.startSpan(ctx)
defer span.Finish()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
cur, err := s.bucketCursor(ctx, tx)
if err != nil {
return err
}
iter := &iterator{
cursor: cur,
descending: opts.Descending,
limit: opts.Limit,
offset: opts.Offset,
prefix: opts.Prefix,
decodeFn: s.DecodeEntFn,
filterFn: opts.FilterEntFn,
}
for k, v, err := iter.Next(ctx); k != nil; k, v, err = iter.Next(ctx) {
if err != nil {
return err
}
if err := opts.CaptureFn(k, v); err != nil {
return err
}
}
return nil
}
// FindEnt returns the decoded entity body via the provided entity.
// An example entity should not include a Body, but rather the ID,
// Name, or OrgID.
func (s *StoreBase) FindEnt(ctx context.Context, tx Tx, ent Entity) (interface{}, error) {
span, ctx := s.startSpan(ctx)
defer span.Finish()
encodedID, err := s.EntKey(ctx, ent)
if err != nil {
// TODO: fix this error up
return nil, err
}
body, err := s.bucketGet(ctx, tx, encodedID)
if err != nil {
return nil, err
}
return s.decodeEnt(ctx, body)
}
type (
putOption struct {
isNew bool
isUpdate bool
}
// PutOptionFn provides a hint to the store to make some guarantees about the
// put action. I.e. If it is new, then will validate there is no existing entity
// by the given PK.
PutOptionFn func(o *putOption) error
)
// PutNew will create an entity that is not does not already exist. Guarantees uniqueness
// by the store's uniqueness guarantees.
func PutNew() PutOptionFn {
return func(o *putOption) error {
o.isNew = true
return nil
}
}
// PutUpdate will update an entity that must already exist.
func PutUpdate() PutOptionFn {
return func(o *putOption) error {
o.isUpdate = true
return nil
}
}
// Put will persist the entity.
func (s *StoreBase) Put(ctx context.Context, tx Tx, ent Entity, opts ...PutOptionFn) error {
span, ctx := s.startSpan(ctx)
defer span.Finish()
var opt putOption
for _, o := range opts {
if err := o(&opt); err != nil {
return &errors2.Error{
Code: errors2.EConflict,
Err: err,
}
}
}
if err := s.putValidate(ctx, tx, ent, opt); err != nil {
return err
}
encodedID, err := s.EntKey(ctx, ent)
if err != nil {
return err
}
body, err := s.encodeEnt(ctx, ent, s.EncodeEntBodyFn)
if err != nil {
return err
}
return s.bucketPut(ctx, tx, encodedID, body)
}
func (s *StoreBase) putValidate(ctx context.Context, tx Tx, ent Entity, opt putOption) error {
span, ctx := tracing.StartSpanFromContext(ctx)
defer span.Finish()
if !opt.isUpdate && !opt.isNew {
return nil
}
_, err := s.FindEnt(ctx, tx, ent)
if opt.isNew {
if err == nil || errors2.ErrorCode(err) != errors2.ENotFound {
return &errors2.Error{
Code: errors2.EConflict,
Msg: fmt.Sprintf("%s is not unique", s.Resource),
Err: err,
}
}
return nil
}
return err
}
func (s *StoreBase) bucket(ctx context.Context, tx Tx) (Bucket, error) {
span, _ := tracing.StartSpanFromContext(ctx)
defer span.Finish()
bkt, err := tx.Bucket(s.BktName)
if err != nil {
return nil, &errors2.Error{
Code: errors2.EInternal,
Msg: fmt.Sprintf("unexpected error retrieving bucket %q; Err %v", string(s.BktName), err),
Err: err,
}
}
return bkt, nil
}
func (s *StoreBase) bucketCursor(ctx context.Context, tx Tx) (Cursor, error) {
span, _ := tracing.StartSpanFromContext(ctx)
defer span.Finish()
b, err := s.bucket(ctx, tx)
if err != nil {
return nil, err
}
cur, err := b.Cursor()
if err != nil {
return nil, &errors2.Error{
Code: errors2.EInternal,
Msg: "failed to retrieve cursor",
Err: err,
}
}
return cur, nil
}
func (s *StoreBase) bucketDelete(ctx context.Context, tx Tx, key []byte) error {
span, _ := tracing.StartSpanFromContext(ctx)
defer span.Finish()
b, err := s.bucket(ctx, tx)
if err != nil {
return err
}
err = b.Delete(key)
if err == nil {
return nil
}
iErr := &errors2.Error{
Code: errors2.EInternal,
Err: err,
}
if IsNotFound(err) {
iErr.Code = errors2.ENotFound
iErr.Msg = fmt.Sprintf("%s does exist for key: %q", s.Resource, string(key))
}
return iErr
}
func (s *StoreBase) bucketGet(ctx context.Context, tx Tx, key []byte) ([]byte, error) {
span, _ := tracing.StartSpanFromContext(ctx)
defer span.Finish()
b, err := s.bucket(ctx, tx)
if err != nil {
return nil, err
}
body, err := b.Get(key)
if IsNotFound(err) {
return nil, &errors2.Error{
Code: errors2.ENotFound,
Msg: fmt.Sprintf("%s not found for key %q", s.Resource, string(key)),
}
}
if err != nil {
return nil, &errors2.Error{
Code: errors2.EInternal,
Err: err,
}
}
return body, nil
}
func (s *StoreBase) bucketPut(ctx context.Context, tx Tx, key, body []byte) error {
span, _ := tracing.StartSpanFromContext(ctx)
defer span.Finish()
b, err := s.bucket(ctx, tx)
if err != nil {
return err
}
if err := b.Put(key, body); err != nil {
return &errors2.Error{
Code: errors2.EInternal,
Err: err,
}
}
return nil
}
func (s *StoreBase) decodeEnt(ctx context.Context, body []byte) (interface{}, error) {
span, _ := tracing.StartSpanFromContext(ctx)
defer span.Finish()
_, v, err := s.DecodeEntFn([]byte{}, body) // ignore key here
if err != nil {
return nil, &errors2.Error{
Code: errors2.EInternal,
Msg: fmt.Sprintf("failed to decode %s body", s.Resource),
Err: err,
}
}
return v, nil
}
func (s *StoreBase) encodeEnt(ctx context.Context, ent Entity, fn EncodeEntFn) ([]byte, error) {
span, _ := tracing.StartSpanFromContext(ctx)
defer span.Finish()
if fn == nil {
return nil, &errors2.Error{
Code: errors2.EInvalid,
Msg: fmt.Sprintf("no key was provided for %s", s.Resource),
}
}
encoded, field, err := fn(ent)
if err != nil {