This repository was archived by the owner on Feb 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 232
/
Copy pathfield.go
2389 lines (2103 loc) · 66.6 KB
/
field.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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2022 Molecula Corp. (DBA FeatureBase).
// SPDX-License-Identifier: Apache-2.0
package pilosa
import (
"bytes"
"context"
"encoding/json"
"fmt"
"math"
"math/bits"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/featurebasedb/featurebase/v3/pql"
"github.com/featurebasedb/featurebase/v3/roaring"
"github.com/featurebasedb/featurebase/v3/stats"
"github.com/featurebasedb/featurebase/v3/testhook"
"github.com/featurebasedb/featurebase/v3/tracing"
"github.com/pkg/errors"
)
// Default field settings.
const (
DefaultFieldType = FieldTypeSet
DefaultCacheType = CacheTypeRanked
// Default ranked field cache
DefaultCacheSize = 50000
bitsPerWord = 32 << (^uint(0) >> 63) // either 32 or 64
maxInt = 1<<(bitsPerWord-1) - 1 // either 1<<31 - 1 or 1<<63 - 1
)
// Field types.
const (
FieldTypeSet = "set"
FieldTypeInt = "int"
FieldTypeTime = "time"
FieldTypeMutex = "mutex"
FieldTypeBool = "bool"
FieldTypeDecimal = "decimal"
FieldTypeTimestamp = "timestamp"
)
type protected struct {
mu sync.Mutex
duration time.Duration
}
func (p *protected) Set(d time.Duration) {
p.mu.Lock()
defer p.mu.Unlock()
p.duration = d
}
func (p *protected) Get() time.Duration {
p.mu.Lock()
defer p.mu.Unlock()
return p.duration
}
var availableShardFileFlushDuration = &protected{
duration: 5 * time.Second,
}
// Field represents a container for views.
type Field struct {
mu sync.RWMutex
createdAt int64
owner string
path string
index string
name string
qualifiedName string
idx *Index
viewMap map[string]*view
broadcaster broadcaster
Stats stats.StatsClient
serializer Serializer
// Field options.
options FieldOptions
bsiGroups []*bsiGroup
// Shards with data on any node in the cluster, according to this node.
remoteAvailableShardsMu sync.Mutex
remoteAvailableShards *roaring.Bitmap
translateStore TranslateStore
// Instantiates new translation stores
OpenTranslateStore OpenTranslateStoreFunc
// Used for looking up a foreign index.
holder *Holder
// Stores whether or not the field has keys enabled.
// This is most helpful for cases where the keys are
// based on a foreign index; this prevents having to
// call holder.index.Keys() every time.
usesKeys bool
// Synchronization primitives needed for async writing of
// the remoteAvailableShards
availableShardChan chan struct{}
wg sync.WaitGroup
// track whether we're shutting down
closing chan struct{}
}
// FieldOption is a functional option type for pilosa.fieldOptions.
type FieldOption func(fo *FieldOptions) error
// OptFieldKeys is a functional option on FieldOptions
// used to specify whether keys are used for this field.
func OptFieldKeys() FieldOption {
return func(fo *FieldOptions) error {
fo.Keys = true
return nil
}
}
// OptFieldForeignIndex marks this field as a foreign key to another
// index. That is, the values of this field should be interpreted as
// referencing records (Pilosa columns) in another index. TODO explain
// where/how this is used by Pilosa.
func OptFieldForeignIndex(index string) FieldOption {
return func(fo *FieldOptions) error {
fo.ForeignIndex = index
return nil
}
}
// OptFieldTypeDefault is a functional option on FieldOptions
// used to set the field type and cache setting to the default values.
func OptFieldTypeDefault() FieldOption {
return func(fo *FieldOptions) error {
if fo.Type != "" {
return errors.Errorf("field type is already set to: %s", fo.Type)
}
fo.Type = FieldTypeSet
fo.CacheType = DefaultCacheType
fo.CacheSize = DefaultCacheSize
return nil
}
}
// OptFieldTypeSet is a functional option on FieldOptions
// used to specify the field as being type `set` and to
// provide any respective configuration values.
func OptFieldTypeSet(cacheType string, cacheSize uint32) FieldOption {
return func(fo *FieldOptions) error {
if fo.Type != "" {
return errors.Errorf("field type is already set to: %s", fo.Type)
}
fo.Type = FieldTypeSet
fo.CacheType = cacheType
fo.CacheSize = cacheSize
return nil
}
}
// OptFieldTypeInt is a functional option on FieldOptions
// used to specify the field as being type `int` and to
// provide any respective configuration values.
func OptFieldTypeInt(min, max int64) FieldOption {
return func(fo *FieldOptions) error {
if fo.Type != "" {
return errors.Errorf("field type is already set to: %s", fo.Type)
}
if min > max {
return errors.New("int field min cannot be greater than max")
}
fo.Type = FieldTypeInt
fo.Min = pql.NewDecimal(min, 0)
fo.Max = pql.NewDecimal(max, 0)
fo.Base = bsiBase(min, max)
return nil
}
}
// OptFieldTypeTimestamp is a functional option on FieldOptions
// used to specify the field as being type `timestamp` and to
// provide any respective configuration values.
func OptFieldTypeTimestamp(epoch time.Time, timeUnit string) FieldOption {
return func(fo *FieldOptions) error {
if fo.Type != "" {
return errors.Errorf("field type is already set to: %s", fo.Type)
}
minTime := MinTimestamp
maxTime := MaxTimestamp
var base, minInt, maxInt int64
switch timeUnit {
case TimeUnitSeconds:
base = epoch.Unix()
minInt = minTime.Unix() - base
maxInt = maxTime.Unix() - base
case TimeUnitMilliseconds:
base = epoch.UnixMilli()
minInt = minTime.UnixMilli() - base
maxInt = maxTime.UnixMilli() - base
case TimeUnitMicroseconds, TimeUnitUSeconds:
base = epoch.UnixMicro()
minInt = minTime.UnixMicro() - base
maxInt = maxTime.UnixMicro() - base
case TimeUnitNanoseconds:
// Note: For nano, the min and max values are also the min and max integer
// values we support. Also, keep in mind that MinNano is a negative
// number. So if base is positive and we do MinNano - base...it would increase minInt
// beyond what we support. This isn't an issue with larger granularities.
base = epoch.UnixNano()
if base > 0 {
maxInt = MaxTimestampNano.UnixNano() - base
minInt = MinTimestampNano.UnixNano()
} else {
maxInt = MaxTimestampNano.UnixNano()
minInt = MinTimestampNano.UnixNano() - base
}
minTime = MinTimestampNano
maxTime = MaxTimestampNano
default:
return errors.Errorf("invalid time unit: '%q'", fo.TimeUnit)
}
if err := CheckEpochOutOfRange(epoch, minTime, maxTime); err != nil {
return err
}
fo.Type = FieldTypeTimestamp
fo.TimeUnit = timeUnit
fo.Base = base
fo.Min = pql.NewDecimal(minInt, 0)
fo.Max = pql.NewDecimal(maxInt, 0)
return nil
}
}
// OptFieldTypeDecimal is a functional option for creating a `decimal` field.
// Unless we decide to expand the range of supported values, `scale` is
// restricted to the range [0,19]. This supports anything from:
//
// scale = 0:
// min: -9223372036854775808.
// max: 9223372036854775807.
//
// to:
//
// scale = 19:
// min: -0.9223372036854775808
// max: 0.9223372036854775807
//
// While it's possible to support scale values outside of this range,
// the coverage for those scales are no longer continuous. For example,
//
// scale = -2:
// min : [-922337203685477580800, -100]
// GAPs: [-99, -1], [-199, -101] ... [-922337203685477580799, -922337203685477580701]
//
// 0
//
// max : [100, 922337203685477580700]
// GAPs: [1, 99], [101, 199] ... [922337203685477580601, 922337203685477580699]
//
// An alternative to this gap strategy would be to scale the supported range
// to a continuous 64-bit space (which is not unreasonable using bsiGroup.Base).
// The issue with this approach is that we would need to know which direction
// to favor. For example, there are two possible ranges for `scale = -2`:
//
// min : [-922337203685477580800, -922337203685477580800+(2^64)]
// max : [922337203685477580700-(2^64), 922337203685477580700]
func OptFieldTypeDecimal(scale int64, minmax ...pql.Decimal) FieldOption {
return func(fo *FieldOptions) error {
if fo.Type != "" {
return errors.Errorf("can't set field type to 'decimal', already set to: %s", fo.Type)
}
if scale < 0 || scale > 19 {
return errors.Errorf("scale values outside the range [0,19] are not supported: %d", scale)
}
fo.Min, fo.Max = pql.MinMax(scale)
if len(minmax) == 2 {
min := minmax[0]
max := minmax[1]
if !min.IsValid() || !max.IsValid() {
return errors.Errorf("min/max range %s-%s is not supported", min, max)
} else if !min.SupportedByScale(scale) || !max.SupportedByScale(scale) {
return errors.Errorf("min/max range %s-%s is not supported by scale %d", min, max, scale)
} else if min.GreaterThan(max) {
return errors.Errorf("decimal field min cannot be greater than max, got %s, %s", min, max)
}
fo.Min = min
fo.Max = max
} else if len(minmax) > 2 {
return errors.Errorf("unknown extra parameters beyond min and max: %v", minmax)
} else if len(minmax) == 1 {
min := minmax[0]
if !min.IsValid() {
return errors.Errorf("min %s is not supported", min)
} else if !min.SupportedByScale(scale) {
return errors.Errorf("min %s is not supported by scale %d", min, scale)
}
fo.Min = min
}
fo.Type = FieldTypeDecimal
fo.Base = bsiBase(fo.Min.ToInt64(scale), fo.Max.ToInt64(scale))
fo.Scale = scale
return nil
}
}
// OptFieldTypeTime is a functional option on FieldOptions
// used to specify the field as being type `time` and to
// provide any respective configuration values.
// Pass true to skip creation of the standard view.
func OptFieldTypeTime(timeQuantum TimeQuantum, ttl string, opt ...bool) FieldOption {
return func(fo *FieldOptions) error {
if fo.Type != "" {
return errors.Errorf("field type is already set to: %s", fo.Type)
}
if !timeQuantum.Valid() {
return ErrInvalidTimeQuantum
}
fo.Type = FieldTypeTime
fo.TimeQuantum = timeQuantum
ttlParsed, err := time.ParseDuration(ttl)
if err != nil {
return errors.Errorf("cannot parse ttl: %s", ttl)
}
if ttlParsed < 0 {
return errors.Errorf("ttl can't be negative: %s", ttl)
}
fo.TTL = ttlParsed
fo.NoStandardView = len(opt) >= 1 && opt[0]
return nil
}
}
// OptFieldTypeMutex is a functional option on FieldOptions
// used to specify the field as being type `mutex` and to
// provide any respective configuration values.
func OptFieldTypeMutex(cacheType string, cacheSize uint32) FieldOption {
return func(fo *FieldOptions) error {
if fo.Type != "" {
return errors.Errorf("field type is already set to: %s", fo.Type)
}
fo.Type = FieldTypeMutex
fo.CacheType = cacheType
fo.CacheSize = cacheSize
return nil
}
}
// OptFieldTypeBool is a functional option on FieldOptions
// used to specify the field as being type `bool` and to
// provide any respective configuration values.
func OptFieldTypeBool() FieldOption {
return func(fo *FieldOptions) error {
if fo.Type != "" {
return errors.Errorf("field type is already set to: %s", fo.Type)
}
fo.Type = FieldTypeBool
return nil
}
}
// newField returns a new instance of field (without name validation).
func newField(holder *Holder, path, index, name string, opts FieldOption) (*Field, error) {
// Apply functional option.
fo := FieldOptions{}
err := opts(&fo)
if err != nil {
return nil, errors.Wrap(err, "applying option")
}
f := &Field{
path: path,
index: index,
name: name,
qualifiedName: FormatQualifiedFieldName(index, name),
viewMap: make(map[string]*view),
broadcaster: NopBroadcaster,
Stats: stats.NopStatsClient,
serializer: NopSerializer,
options: applyDefaultOptions(&fo),
remoteAvailableShards: roaring.NewBitmap(),
holder: holder,
OpenTranslateStore: OpenInMemTranslateStore,
}
return f, nil
}
// Name returns the name the field was initialized with.
func (f *Field) Name() string { return f.name }
// CreatedAt is an timestamp for a specific version of field.
func (f *Field) CreatedAt() int64 {
f.mu.RLock()
defer f.mu.RUnlock()
return f.createdAt
}
// Index returns the index name the field was initialized with.
func (f *Field) Index() string { return f.index }
// Path returns the path the field was initialized with.
func (f *Field) Path() string { return f.path }
// TranslateStorePath returns the translation database path for the field.
func (f *Field) TranslateStorePath() string {
return filepath.Join(f.path, "keys")
}
// TranslateStore returns the field's translation store.
func (f *Field) TranslateStore() TranslateStore {
return f.translateStore
}
// AvailableShards returns a bitmap of shards that contain data.
func (f *Field) AvailableShards(localOnly bool) *roaring.Bitmap {
f.mu.RLock()
defer f.mu.RUnlock()
f.remoteAvailableShardsMu.Lock()
defer f.remoteAvailableShardsMu.Unlock()
var b *roaring.Bitmap
if localOnly {
b = roaring.NewBitmap()
} else {
b = f.remoteAvailableShards.Clone()
}
for viewname, view := range f.viewMap {
availableShards := view.availableShards()
if availableShards == nil || availableShards.Containers == nil {
f.holder.Logger.Warnf("empty available shards for view: %s on field %s available shards: %v", viewname, f.name, availableShards)
continue
}
b.UnionInPlace(view.availableShards())
}
return b
}
// LocalAvailableShards returns a bitmap of shards that contain data, but
// only from the local node. This prevents txfactory from making
// db-per-shard for remote shards.
func (f *Field) LocalAvailableShards() *roaring.Bitmap {
f.mu.RLock()
defer f.mu.RUnlock()
b := roaring.NewBitmap()
for _, view := range f.viewMap {
b.UnionInPlace(view.availableShards())
}
return b
}
// AddRemoteAvailableShards merges the set of available shards into the current known set
// and saves the set to a file.
func (f *Field) AddRemoteAvailableShards(b *roaring.Bitmap) error {
f.mergeRemoteAvailableShards(b)
// Save the updated bitmap to the data store.
return f.saveAvailableShards()
}
// mergeRemoteAvailableShards merges the set of available shards into the current known set.
func (f *Field) mergeRemoteAvailableShards(b *roaring.Bitmap) {
f.remoteAvailableShardsMu.Lock()
defer f.remoteAvailableShardsMu.Unlock()
f.remoteAvailableShards = f.remoteAvailableShards.Union(b)
}
// loadAvailableShards reads remoteAvailableShards data for the field, if any.
func (f *Field) loadAvailableShards() error {
shards, err := f.holder.sharder.Shards(context.Background(), f.index, f.name)
if err != nil {
return errors.Wrap(err, "loading available shards")
}
bm := roaring.NewBitmap()
for _, s := range shards {
b := roaring.NewBitmap()
if err = b.UnmarshalBinary(s); err != nil {
return errors.Wrap(err, "available shards corrupt")
}
bm.UnionInPlace(b)
}
// Merge bitmap from file into field.
f.mergeRemoteAvailableShards(bm)
return nil
}
// saveAvailableShards writes remoteAvailableShards data for the field.
func (f *Field) saveAvailableShards() error {
select {
case f.availableShardChan <- struct{}{}:
default:
}
return nil
}
// RemoveAvailableShard removes a shard from the bitmap cache.
//
// NOTE: This can be overridden on the next sync so all nodes should be updated.
func (f *Field) RemoveAvailableShard(v uint64) error {
f.remoteAvailableShardsMu.Lock()
defer f.remoteAvailableShardsMu.Unlock()
b := f.remoteAvailableShards.Clone()
if _, err := b.Remove(v); err != nil {
return err
}
f.remoteAvailableShards = b
return f.saveAvailableShards()
}
// Type returns the field type.
func (f *Field) Type() string {
f.mu.RLock()
defer f.mu.RUnlock()
return f.options.Type
}
// CacheSize returns the ranked field cache size.
func (f *Field) CacheSize() uint32 {
f.mu.RLock()
v := f.options.CacheSize
f.mu.RUnlock()
return v
}
// Options returns all options for this field.
func (f *Field) Options() FieldOptions {
f.mu.RLock()
defer f.mu.RUnlock()
return f.options
}
// Open opens and initializes the field.
func (f *Field) Open() error {
f.mu.Lock()
defer f.mu.Unlock()
if err := func() (err error) {
// Ensure the field's path exists.
f.holder.Logger.Debugf("ensure field path exists: %s", f.path)
if err := os.MkdirAll(f.path, 0750); err != nil {
return errors.Wrap(err, "creating field dir")
}
f.holder.Logger.Debugf("load available shards for index/field: %s/%s", f.index, f.name)
if err := f.loadAvailableShards(); err != nil {
return errors.Wrap(err, "loading available shards")
}
// Apply the field options loaded from etcd (or set via setOptions()).
f.holder.Logger.Debugf("apply options for index/field: %s/%s", f.index, f.name)
if err := f.applyOptions(f.options); err != nil {
return errors.Wrap(err, "applying options")
}
f.holder.Logger.Debugf("open views for index/field: %s/%s", f.index, f.name)
if err := f.openViews(); err != nil {
return errors.Wrap(err, "opening views")
}
// Apply the field-specific translateStore.
if err := f.applyTranslateStore(); err != nil {
return errors.Wrap(err, "applying translate store")
}
// If the field has a foreign index, make sure the index
// exists.
if f.options.ForeignIndex != "" {
if err := f.holder.checkForeignIndex(f); err != nil {
return errors.Wrap(err, "checking foreign index")
}
}
f.availableShardChan = make(chan struct{}, 1)
f.wg.Add(1)
go f.writeAvailableShards()
return nil
}(); err != nil {
f.unprotectedClose()
return err
}
f.closing = make(chan struct{})
_ = testhook.Opened(f.holder.Auditor, f, nil)
f.holder.Logger.Debugf("successfully opened field index/field: %s/%s", f.index, f.name)
return nil
}
func (f *Field) protectedRemoteAvailableShards() *roaring.Bitmap {
f.remoteAvailableShardsMu.Lock()
defer f.remoteAvailableShardsMu.Unlock()
f.remoteAvailableShards.Optimize()
return f.remoteAvailableShards.Clone()
}
func (f *Field) flushAvailableShards(ctx context.Context) {
shards := f.protectedRemoteAvailableShards()
var buf bytes.Buffer
if _, err := shards.WriteTo(&buf); err != nil {
f.holder.Logger.Errorf("writting available shards: %v", err)
return
}
if err := f.holder.sharder.SetShards(ctx, f.index, f.name, buf.Bytes()); err != nil {
f.holder.Logger.Errorf("setting available shards: %v", err)
}
}
func (f *Field) writeAvailableShards() {
defer f.wg.Done()
interval := availableShardFileFlushDuration.Get()
timer := time.NewTimer(interval)
defer timer.Stop()
for range f.availableShardChan {
// Available shards have been updated.
// Wait a bit so that we batch writes.
timerWait:
for {
select {
case _, ok := <-f.availableShardChan:
if !ok {
// The server is shutting down.
// Do the write immediately.
timer.Stop()
break timerWait
}
case <-timer.C:
// We have waited long enough.
break timerWait
}
}
// Set the timer for the next flush.
timer.Reset(interval)
// Actually write the shards.
f.flushAvailableShards(context.Background())
}
}
// applyTranslateStore opens the configured translate store.
func (f *Field) applyTranslateStore() error {
// Instantiate & open translation store.
var err error
f.translateStore, err = f.OpenTranslateStore(f.TranslateStorePath(), f.index, f.name, -1, -1, f.holder.cfg.StorageConfig.FsyncEnabled)
if err != nil {
return errors.Wrap(err, "opening field translate store")
}
f.usesKeys = f.options.Keys
// In the case where the field has a foreign index, set
// the usesKeys value accordingly.
if foreignIndexName := f.ForeignIndex(); foreignIndexName != "" {
if foreignIndex := f.holder.Index(foreignIndexName); foreignIndex != nil {
f.usesKeys = foreignIndex.Keys()
}
}
return nil
}
// applyForeignIndex used to set the field's translateStore to
// that of the foreign index, but since moving to partitioned
// translate stores on indexes, that doesn't happen anymore.
// So now all this method does is check that the foreign index
// actually exists. If we decided this was unnecessary (which
// it kind of is), we could remove the field.holder and all
// the logic which does this check on holder open after all
// indexes have opened.
func (f *Field) applyForeignIndex() error {
foreignIndex := f.holder.Index(f.options.ForeignIndex)
if foreignIndex == nil {
return errors.Wrapf(ErrForeignIndexNotFound, "%s", f.options.ForeignIndex)
}
f.usesKeys = foreignIndex.Keys()
return nil
}
// ForeignIndex returns the foreign index name attached to the field.
// Returns blank string if no foreign index exists.
func (f *Field) ForeignIndex() string {
return f.options.ForeignIndex
}
// TTL returns the ttl of the field.
func (f *Field) TTL() time.Duration {
return f.options.TTL
}
func (f *Field) bitDepth() (uint64, error) {
var maxBitDepth uint64
view2shards := f.idx.fieldView2shard.getViewsForField(f.name)
for name, shardset := range view2shards {
view := f.view(name)
if view == nil {
continue
}
bd, err := view.bitDepth(shardset.shards())
if err != nil {
return 0, errors.Wrapf(err, "getting view(%s) bit depth", name)
}
if bd > maxBitDepth {
maxBitDepth = bd
}
}
return maxBitDepth, nil
}
// cacheBitDepth is used by Index.setFieldBitDepths() to updated the in-memory
// bitDepth values for each field and its bsiGroup.
func (f *Field) cacheBitDepth(bd uint64) error {
// Get the assocated bsiGroup so that its bitDepth can be updated as well.
bsig := f.bsiGroup(f.name)
f.mu.Lock()
defer f.mu.Unlock()
if f.options.BitDepth < bd {
f.options.BitDepth = bd
}
if bsig != nil && bsig.BitDepth < bd {
bsig.BitDepth = bd
}
return nil
}
// openViews opens and initializes the views inside the field.
func (f *Field) openViews() error {
view2shards := f.idx.fieldView2shard.getViewsForField(f.name)
if view2shards == nil {
// no data
return nil
}
for name, shardset := range view2shards {
view := f.newView(f.viewPath(name), name)
if err := view.openWithShardSet(shardset); err != nil {
return fmt.Errorf("opening view: view=%s, err=%s", view.name, err)
}
f.holder.Logger.Debugf("add index/field/view to field.viewMap: %s/%s/%s", f.index, f.name, view.name)
f.viewMap[view.name] = view
}
return nil
}
// setOptions saves options for final application during Open().
func (f *Field) setOptions(opts *FieldOptions) {
f.options = applyDefaultOptions(opts)
}
// applyOptions configures the field based on opt.
func (f *Field) applyOptions(opt FieldOptions) error {
switch opt.Type {
case FieldTypeSet, FieldTypeMutex, "":
fldType := opt.Type
if fldType == "" {
fldType = FieldTypeSet
}
f.options.Type = fldType
if opt.CacheType != "" {
f.options.CacheType = opt.CacheType
}
if opt.CacheType == CacheTypeNone {
f.options.CacheSize = 0
} else if opt.CacheSize != 0 {
f.options.CacheSize = opt.CacheSize
}
f.options.Min = pql.Decimal{}
f.options.Max = pql.Decimal{}
f.options.Base = 0
f.options.BitDepth = 0
f.options.TimeQuantum = ""
f.options.TTL = 0
f.options.Keys = opt.Keys
f.options.ForeignIndex = opt.ForeignIndex
case FieldTypeInt, FieldTypeDecimal, FieldTypeTimestamp:
f.options.Type = opt.Type
f.options.CacheType = CacheTypeNone
f.options.CacheSize = 0
f.options.Min = opt.Min
f.options.Max = opt.Max
f.options.Base = opt.Base
f.options.Scale = opt.Scale
f.options.BitDepth = opt.BitDepth
f.options.TimeUnit = opt.TimeUnit
f.options.TimeQuantum = ""
f.options.TTL = 0
f.options.Keys = opt.Keys
f.options.ForeignIndex = opt.ForeignIndex
// Create new bsiGroup.
bsig := &bsiGroup{
Name: f.name,
Type: bsiGroupTypeInt,
Min: opt.Min.ToInt64(opt.Scale),
Max: opt.Max.ToInt64(opt.Scale),
Base: opt.Base,
Scale: opt.Scale,
TimeUnit: opt.TimeUnit,
BitDepth: opt.BitDepth,
}
// Validate and create bsiGroup.
if err := f.createBSIGroup(bsig); err != nil {
return errors.Wrap(err, "creating bsigroup")
}
case FieldTypeTime:
f.options.Type = opt.Type
f.options.CacheType = CacheTypeNone
f.options.CacheSize = 0
f.options.Min = pql.Decimal{}
f.options.Max = pql.Decimal{}
f.options.Base = 0
f.options.BitDepth = 0
f.options.Keys = opt.Keys
f.options.NoStandardView = opt.NoStandardView
// Validate the time quantum.
if !opt.TimeQuantum.Valid() {
return ErrInvalidTimeQuantum
}
f.options.TimeQuantum = opt.TimeQuantum
f.options.TTL = opt.TTL
f.options.ForeignIndex = opt.ForeignIndex
case FieldTypeBool:
f.options.Type = FieldTypeBool
f.options.CacheType = CacheTypeNone
f.options.CacheSize = 0
f.options.Min = pql.Decimal{}
f.options.Max = pql.Decimal{}
f.options.Base = 0
f.options.BitDepth = 0
f.options.TimeQuantum = ""
f.options.TTL = 0
f.options.Keys = false
f.options.ForeignIndex = ""
default:
return errors.New("invalid field type")
}
return nil
}
// Close closes the field and its views.
func (f *Field) Close() error {
f.mu.Lock()
defer f.mu.Unlock()
return f.unprotectedClose()
}
// unprotectedClose is the actual closing part of the operation, without the
// locking.
func (f *Field) unprotectedClose() error {
if f.closing != nil {
select {
case <-f.closing:
// already closed. prevent double-close
return errors.New("double close of field")
default:
}
close(f.closing)
}
defer func() {
_ = testhook.Closed(f.holder.Auditor, f, nil)
}()
// Shutdown the available shards writer
if f.availableShardChan != nil {
close(f.availableShardChan)
f.wg.Wait()
f.availableShardChan = nil
}
// Close field translation store.
if f.translateStore != nil {
if err := f.translateStore.Close(); err != nil {
return err
}
}
// Close all views.
for _, view := range f.viewMap {
if err := view.close(); err != nil {
return err
}
}
f.viewMap = make(map[string]*view)
return nil
}
func (f *Field) flushCaches() {
// look up the close channel so if we somehow end up living until the
// field gets reopened, we don't have a data race, but correctly detect
// that the old one is closed.
f.mu.RLock()
closing := f.closing
f.mu.RUnlock()
for _, v := range f.views() {
select {
case <-closing:
return
default:
v.flushCaches()
}
}
}
// Keys returns true if the field uses string keys.
func (f *Field) Keys() bool {
f.mu.RLock()
defer f.mu.RUnlock()
return f.usesKeys
}
// bsiGroup returns a bsiGroup by name.
func (f *Field) bsiGroup(name string) *bsiGroup {
f.mu.RLock()
defer f.mu.RUnlock()
for _, bsig := range f.bsiGroups {
if bsig.Name == name {
return bsig
}
}
return nil
}
// hasBSIGroup returns true if a bsiGroup exists on the field.
func (f *Field) hasBSIGroup(name string) bool {
for _, bsig := range f.bsiGroups {
if bsig.Name == name {
return true
}
}
return false
}
// createBSIGroup creates a new bsiGroup on the field.
func (f *Field) createBSIGroup(bsig *bsiGroup) error {
// Append bsiGroup.
if err := bsig.validate(); err != nil {
return errors.Wrap(err, "validating bsigroup")
} else if f.hasBSIGroup(bsig.Name) {
return ErrBSIGroupExists
}
// Add bsiGroup to list.
f.bsiGroups = append(f.bsiGroups, bsig)
// Sort bsiGroups by name.
sort.Slice(f.bsiGroups, func(i, j int) bool {
return f.bsiGroups[i].Name < f.bsiGroups[j].Name
})
return nil
}
// TimeQuantum returns the time quantum for the field.
func (f *Field) TimeQuantum() TimeQuantum {
f.mu.Lock()
defer f.mu.Unlock()
return f.options.TimeQuantum
}