forked from ipfs/go-ds-badger2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
datastore.go
987 lines (824 loc) · 22.2 KB
/
datastore.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
package badger
import (
"context"
"errors"
"fmt"
"runtime"
"strings"
"sync"
"time"
badger "github.com/dgraph-io/badger/v2"
options "github.com/dgraph-io/badger/v2/options"
ds "github.com/ipfs/go-datastore"
dsq "github.com/ipfs/go-datastore/query"
logger "github.com/ipfs/go-log/v2"
goprocess "github.com/jbenet/goprocess"
"go.uber.org/zap"
)
var log = logger.Logger("badger")
var ErrClosed = errors.New("datastore closed")
type Datastore struct {
DB *badger.DB
closeLk sync.RWMutex
closed bool
closeOnce sync.Once
closing chan struct{}
gcDiscardRatio float64
gcSleep time.Duration
gcInterval time.Duration
syncWrites bool
ttl time.Duration
}
// Implements the datastore.Batch interface, enabling batching support for
// the badger Datastore.
type batch struct {
ds *Datastore
writeBatch *badger.WriteBatch
}
// Implements the datastore.Txn interface, enabling transaction support for
// the badger Datastore.
type txn struct {
ds *Datastore
txn *badger.Txn
// Whether this transaction has been implicitly created as a result of a direct Datastore
// method invocation.
implicit bool
}
// Options are the badger datastore options, reexported here for convenience.
type Options struct {
// Please refer to the Badger docs to see what this is for
GcDiscardRatio float64
// Interval between GC cycles
//
// If zero, the datastore will perform no automatic garbage collection.
GcInterval time.Duration
// Sleep time between rounds of a single GC cycle.
//
// If zero, the datastore will only perform one round of GC per
// GcInterval.
GcSleep time.Duration
// TTL sets the expiration time for all newly added keys. After expiration,
// the keys will no longer be retrievable and will be removed by garbage
// collection.
//
// The default value is 0, which means no TTL.
TTL time.Duration
badger.Options
}
// DefaultOptions are the default options for the badger datastore.
var DefaultOptions Options
// WithGcDiscardRatio returns a new Options value with GcDiscardRatio set to the given value.
//
// Please refer to the Badger docs to see what this is for
//
// Default value is 0.2
func (opt Options) WithGcDiscardRatio(ratio float64) Options {
opt.GcDiscardRatio = ratio
return opt
}
// WithGcInterval returns a new Options value with GcInterval set to the given
// value.
//
// GcInterval specifies the interval between garbage collection cycles. If zero,
// the datastore will perform no automatic garbage collection.
//
// Default value is 15 minutes.
func (opt Options) WithGcInterval(interval time.Duration) Options {
opt.GcInterval = interval
return opt
}
// WithGcSleep returns a new Options value with GcSleep set to the given value.
//
// GcSleep specifies the sleep time between rounds of a single garbage collection
// cycle. If zero, the datastore will only perform one round of GC per GcInterval.
//
// Default value is 10 seconds.
func (opt Options) WithGcSleep(sleep time.Duration) Options {
opt.GcSleep = sleep
return opt
}
// WithTTL returns a new Options value with TTL set to the given value.
//
// TTL sets the expiration time for all newly added keys. After expiration,
// the keys will no longer be retrievable and will be removed by garbage
// collection.
//
// Default value is 0, which means no TTL.
func (opt Options) WithTTL(ttl time.Duration) Options {
opt.TTL = ttl
return opt
}
func init() {
DefaultOptions = Options{
GcDiscardRatio: 0.2,
GcInterval: 15 * time.Minute,
GcSleep: 10 * time.Second,
Options: badger.DefaultOptions(""),
}
// This is to optimize the database on close so it can be opened
// read-only and efficiently queried. We don't do that and hanging on
// stop isn't nice.
DefaultOptions.Options.CompactL0OnClose = false
// The alternative is "crash on start and tell the user to fix it". This
// will truncate corrupt and unsynced data, which we don't guarantee to
// persist anyways.
DefaultOptions.Options.Truncate = true
// Uses less memory, is no slower when writing, and is faster when
// reading (in some tests).
DefaultOptions.Options.ValueLogLoadingMode = options.FileIO
// Explicitly set this to mmap. This doesn't use much memory anyways.
DefaultOptions.Options.TableLoadingMode = options.MemoryMap
// Reduce this from 64MiB to 16MiB. That means badger will hold on to
// 20MiB by default instead of 80MiB.
//
// This does not appear to have a significant performance hit.
DefaultOptions.Options.MaxTableSize = 16 << 20
}
var _ ds.Datastore = (*Datastore)(nil)
var _ ds.PersistentDatastore = (*Datastore)(nil)
var _ ds.TxnDatastore = (*Datastore)(nil)
var _ ds.Txn = (*txn)(nil)
var _ ds.TTLDatastore = (*Datastore)(nil)
var _ ds.GCDatastore = (*Datastore)(nil)
var _ ds.Batching = (*Datastore)(nil)
// NewDatastore creates a new badger datastore.
//
// DO NOT set the Dir and/or ValuePath fields of opt, they will be set for you.
func NewDatastore(path string, options *Options) (*Datastore, error) {
// Copy the options because we modify them.
var opt badger.Options
var gcDiscardRatio float64
var gcSleep time.Duration
var gcInterval time.Duration
var ttl time.Duration
if options == nil {
opt = DefaultOptions.Options
gcDiscardRatio = DefaultOptions.GcDiscardRatio
gcSleep = DefaultOptions.GcSleep
gcInterval = DefaultOptions.GcInterval
ttl = DefaultOptions.TTL
} else {
opt = options.Options
gcDiscardRatio = options.GcDiscardRatio
gcSleep = options.GcSleep
gcInterval = options.GcInterval
ttl = options.TTL
}
if gcSleep <= 0 {
// If gcSleep is 0, we don't perform multiple rounds of GC per
// cycle.
gcSleep = gcInterval
}
opt.Dir = path
opt.ValueDir = path
opt.Logger = &compatLogger{
SugaredLogger: *log.Desugar().WithOptions(zap.AddCallerSkip(1)).Sugar(),
skipLogger: *log.Desugar().WithOptions(zap.AddCallerSkip(2)).Sugar(),
}
kv, err := badger.Open(opt)
if err != nil {
if strings.HasPrefix(err.Error(), "manifest has unsupported version:") {
err = fmt.Errorf("unsupported badger version, use github.com/ipfs/badgerds-upgrade to upgrade: %s", err.Error())
}
return nil, err
}
ds := &Datastore{
DB: kv,
closing: make(chan struct{}),
gcDiscardRatio: gcDiscardRatio,
gcSleep: gcSleep,
gcInterval: gcInterval,
syncWrites: opt.SyncWrites,
ttl: ttl,
}
// Start the GC process if requested.
if ds.gcInterval > 0 {
go ds.periodicGC()
}
return ds, nil
}
// Keep scheduling GC's AFTER `gcInterval` has passed since the previous GC
func (d *Datastore) periodicGC() {
gcTimeout := time.NewTimer(d.gcInterval)
defer gcTimeout.Stop()
for {
select {
case <-gcTimeout.C:
switch err := d.gcOnce(); err {
case badger.ErrNoRewrite, badger.ErrRejected:
// No rewrite means we've fully garbage collected.
// Rejected means someone else is running a GC
// or we're closing.
gcTimeout.Reset(d.gcInterval)
case nil:
gcTimeout.Reset(d.gcSleep)
case ErrClosed:
return
default:
log.Errorf("error during a GC cycle: %s", err)
// Not much we can do on a random error but log it and continue.
gcTimeout.Reset(d.gcInterval)
}
case <-d.closing:
return
}
}
}
// NewTransaction starts a new transaction. The resulting transaction object
// can be mutated without incurring changes to the underlying Datastore until
// the transaction is Committed.
func (d *Datastore) NewTransaction(ctx context.Context, readOnly bool) (ds.Txn, error) {
d.closeLk.RLock()
defer d.closeLk.RUnlock()
if d.closed {
return nil, ErrClosed
}
return &txn{d, d.DB.NewTransaction(!readOnly), false}, nil
}
// newImplicitTransaction creates a transaction marked as 'implicit'.
// Implicit transactions are created by Datastore methods performing single operations.
func (d *Datastore) newImplicitTransaction(readOnly bool) *txn {
return &txn{d, d.DB.NewTransaction(!readOnly), true}
}
func (d *Datastore) Put(ctx context.Context, key ds.Key, value []byte) error {
d.closeLk.RLock()
defer d.closeLk.RUnlock()
if d.closed {
return ErrClosed
}
txn := d.newImplicitTransaction(false)
defer txn.discard()
if d.ttl > 0 {
if err := txn.putWithTTL(key, value, d.ttl); err != nil {
return err
}
} else {
if err := txn.put(key, value); err != nil {
return err
}
}
return txn.commit()
}
func (d *Datastore) Sync(ctx context.Context, prefix ds.Key) error {
d.closeLk.RLock()
defer d.closeLk.RUnlock()
if d.closed {
return ErrClosed
}
if d.syncWrites {
return nil
}
return d.DB.Sync()
}
func (d *Datastore) PutWithTTL(ctx context.Context, key ds.Key, value []byte, ttl time.Duration) error {
d.closeLk.RLock()
defer d.closeLk.RUnlock()
if d.closed {
return ErrClosed
}
txn := d.newImplicitTransaction(false)
defer txn.discard()
if err := txn.putWithTTL(key, value, ttl); err != nil {
return err
}
return txn.commit()
}
func (d *Datastore) SetTTL(ctx context.Context, key ds.Key, ttl time.Duration) error {
d.closeLk.RLock()
defer d.closeLk.RUnlock()
if d.closed {
return ErrClosed
}
txn := d.newImplicitTransaction(false)
defer txn.discard()
if err := txn.setTTL(key, ttl); err != nil {
return err
}
return txn.commit()
}
func (d *Datastore) GetExpiration(ctx context.Context, key ds.Key) (time.Time, error) {
d.closeLk.RLock()
defer d.closeLk.RUnlock()
if d.closed {
return time.Time{}, ErrClosed
}
txn := d.newImplicitTransaction(false)
defer txn.discard()
return txn.getExpiration(key)
}
func (d *Datastore) Get(ctx context.Context, key ds.Key) (value []byte, err error) {
d.closeLk.RLock()
defer d.closeLk.RUnlock()
if d.closed {
return nil, ErrClosed
}
txn := d.newImplicitTransaction(true)
defer txn.discard()
return txn.get(key)
}
func (d *Datastore) Has(ctx context.Context, key ds.Key) (bool, error) {
d.closeLk.RLock()
defer d.closeLk.RUnlock()
if d.closed {
return false, ErrClosed
}
txn := d.newImplicitTransaction(true)
defer txn.discard()
return txn.has(key)
}
func (d *Datastore) GetSize(ctx context.Context, key ds.Key) (size int, err error) {
d.closeLk.RLock()
defer d.closeLk.RUnlock()
if d.closed {
return -1, ErrClosed
}
txn := d.newImplicitTransaction(true)
defer txn.discard()
return txn.getSize(key)
}
func (d *Datastore) Delete(ctx context.Context, key ds.Key) error {
d.closeLk.RLock()
defer d.closeLk.RUnlock()
txn := d.newImplicitTransaction(false)
defer txn.discard()
err := txn.delete(key)
if err != nil {
return err
}
return txn.commit()
}
func (d *Datastore) Query(ctx context.Context, q dsq.Query) (dsq.Results, error) {
d.closeLk.RLock()
defer d.closeLk.RUnlock()
if d.closed {
return nil, ErrClosed
}
txn := d.newImplicitTransaction(true)
// We cannot defer txn.Discard() here, as the txn must remain active while the iterator is open.
// https://github.com/dgraph-io/badger/commit/b1ad1e93e483bbfef123793ceedc9a7e34b09f79
// The closing logic in the query goprocess takes care of discarding the implicit transaction.
return txn.query(q)
}
// DiskUsage implements the PersistentDatastore interface.
// It returns the sum of lsm and value log files sizes in bytes.
func (d *Datastore) DiskUsage(ctx context.Context) (uint64, error) {
d.closeLk.RLock()
defer d.closeLk.RUnlock()
if d.closed {
return 0, ErrClosed
}
lsm, vlog := d.DB.Size()
return uint64(lsm + vlog), nil
}
func (d *Datastore) Close() error {
d.closeOnce.Do(func() {
close(d.closing)
})
d.closeLk.Lock()
defer d.closeLk.Unlock()
if d.closed {
return ErrClosed
}
d.closed = true
return d.DB.Close()
}
// Batch creates a new Batch object. This provides a way to do many writes, when
// there may be too many to fit into a single transaction.
func (d *Datastore) Batch(ctx context.Context) (ds.Batch, error) {
d.closeLk.RLock()
defer d.closeLk.RUnlock()
if d.closed {
return nil, ErrClosed
}
b := &batch{d, d.DB.NewWriteBatch()}
// Ensure that incomplete transaction resources are cleaned up in case
// batch is abandoned.
runtime.SetFinalizer(b, func(b *batch) {
b.cancel()
log.Error("batch not committed or canceled")
})
return b, nil
}
func (d *Datastore) CollectGarbage(ctx context.Context) (err error) {
// The idea is to keep calling DB.RunValueLogGC() till Badger no longer has any log files
// to GC(which would be indicated by an error, please refer to Badger GC docs).
for err == nil {
err = d.gcOnce()
}
if err == badger.ErrNoRewrite {
err = nil
}
return err
}
func (d *Datastore) gcOnce() error {
d.closeLk.RLock()
defer d.closeLk.RUnlock()
if d.closed {
return ErrClosed
}
return d.DB.RunValueLogGC(d.gcDiscardRatio)
}
var _ ds.Batch = (*batch)(nil)
func (b *batch) Put(ctx context.Context, key ds.Key, value []byte) error {
b.ds.closeLk.RLock()
defer b.ds.closeLk.RUnlock()
if b.ds.closed {
return ErrClosed
}
if b.ds.ttl > 0 {
return b.putWithTTL(key, value, b.ds.ttl)
}
return b.put(key, value)
}
func (b *batch) put(key ds.Key, value []byte) error {
return b.writeBatch.Set(key.Bytes(), value)
}
func (b *batch) putWithTTL(key ds.Key, value []byte, ttl time.Duration) error {
return b.writeBatch.SetEntry(badger.NewEntry(key.Bytes(), value).WithTTL(ttl))
}
func (b *batch) Delete(ctx context.Context, key ds.Key) error {
b.ds.closeLk.RLock()
defer b.ds.closeLk.RUnlock()
if b.ds.closed {
return ErrClosed
}
return b.delete(key)
}
func (b *batch) delete(key ds.Key) error {
return b.writeBatch.Delete(key.Bytes())
}
func (b *batch) Commit(ctx context.Context) error {
b.ds.closeLk.RLock()
defer b.ds.closeLk.RUnlock()
if b.ds.closed {
return ErrClosed
}
return b.commit()
}
func (b *batch) commit() error {
err := b.writeBatch.Flush()
if err != nil {
// Discard incomplete transaction held by b.writeBatch
b.cancel()
return err
}
runtime.SetFinalizer(b, nil)
return nil
}
func (b *batch) Cancel() error {
b.ds.closeLk.RLock()
defer b.ds.closeLk.RUnlock()
if b.ds.closed {
return ErrClosed
}
b.cancel()
return nil
}
func (b *batch) cancel() {
b.writeBatch.Cancel()
runtime.SetFinalizer(b, nil)
}
var _ ds.Datastore = (*txn)(nil)
var _ ds.TTLDatastore = (*txn)(nil)
func (t *txn) Put(ctx context.Context, key ds.Key, value []byte) error {
t.ds.closeLk.RLock()
defer t.ds.closeLk.RUnlock()
if t.ds.closed {
return ErrClosed
}
if t.ds.ttl > 0 {
return t.putWithTTL(key, value, t.ds.ttl)
}
return t.put(key, value)
}
func (t *txn) put(key ds.Key, value []byte) error {
return t.txn.Set(key.Bytes(), value)
}
func (t *txn) Sync(ctx context.Context, prefix ds.Key) error {
t.ds.closeLk.RLock()
defer t.ds.closeLk.RUnlock()
if t.ds.closed {
return ErrClosed
}
return nil
}
func (t *txn) PutWithTTL(ctx context.Context, key ds.Key, value []byte, ttl time.Duration) error {
t.ds.closeLk.RLock()
defer t.ds.closeLk.RUnlock()
if t.ds.closed {
return ErrClosed
}
return t.putWithTTL(key, value, ttl)
}
func (t *txn) putWithTTL(key ds.Key, value []byte, ttl time.Duration) error {
return t.txn.SetEntry(badger.NewEntry(key.Bytes(), value).WithTTL(ttl))
}
func (t *txn) GetExpiration(ctx context.Context, key ds.Key) (time.Time, error) {
t.ds.closeLk.RLock()
defer t.ds.closeLk.RUnlock()
if t.ds.closed {
return time.Time{}, ErrClosed
}
return t.getExpiration(key)
}
func (t *txn) getExpiration(key ds.Key) (time.Time, error) {
item, err := t.txn.Get(key.Bytes())
if err == badger.ErrKeyNotFound {
return time.Time{}, ds.ErrNotFound
} else if err != nil {
return time.Time{}, err
}
return time.Unix(int64(item.ExpiresAt()), 0), nil
}
func (t *txn) SetTTL(ctx context.Context, key ds.Key, ttl time.Duration) error {
t.ds.closeLk.RLock()
defer t.ds.closeLk.RUnlock()
if t.ds.closed {
return ErrClosed
}
return t.setTTL(key, ttl)
}
func (t *txn) setTTL(key ds.Key, ttl time.Duration) error {
item, err := t.txn.Get(key.Bytes())
if err != nil {
return err
}
return item.Value(func(data []byte) error {
return t.putWithTTL(key, data, ttl)
})
}
func (t *txn) Get(ctx context.Context, key ds.Key) ([]byte, error) {
t.ds.closeLk.RLock()
defer t.ds.closeLk.RUnlock()
if t.ds.closed {
return nil, ErrClosed
}
return t.get(key)
}
func (t *txn) get(key ds.Key) ([]byte, error) {
item, err := t.txn.Get(key.Bytes())
if err == badger.ErrKeyNotFound {
err = ds.ErrNotFound
}
if err != nil {
return nil, err
}
return item.ValueCopy(nil)
}
func (t *txn) Has(ctx context.Context, key ds.Key) (bool, error) {
t.ds.closeLk.RLock()
defer t.ds.closeLk.RUnlock()
if t.ds.closed {
return false, ErrClosed
}
return t.has(key)
}
func (t *txn) has(key ds.Key) (bool, error) {
_, err := t.txn.Get(key.Bytes())
switch err {
case badger.ErrKeyNotFound:
return false, nil
case nil:
return true, nil
default:
return false, err
}
}
func (t *txn) GetSize(ctx context.Context, key ds.Key) (int, error) {
t.ds.closeLk.RLock()
defer t.ds.closeLk.RUnlock()
if t.ds.closed {
return -1, ErrClosed
}
return t.getSize(key)
}
func (t *txn) getSize(key ds.Key) (int, error) {
item, err := t.txn.Get(key.Bytes())
switch err {
case nil:
return int(item.ValueSize()), nil
case badger.ErrKeyNotFound:
return -1, ds.ErrNotFound
default:
return -1, err
}
}
func (t *txn) Delete(ctx context.Context, key ds.Key) error {
t.ds.closeLk.RLock()
defer t.ds.closeLk.RUnlock()
if t.ds.closed {
return ErrClosed
}
return t.delete(key)
}
func (t *txn) delete(key ds.Key) error {
return t.txn.Delete(key.Bytes())
}
func (t *txn) Query(ctx context.Context, q dsq.Query) (dsq.Results, error) {
t.ds.closeLk.RLock()
defer t.ds.closeLk.RUnlock()
if t.ds.closed {
return nil, ErrClosed
}
return t.query(q)
}
func (t *txn) query(q dsq.Query) (dsq.Results, error) {
opt := badger.DefaultIteratorOptions
opt.PrefetchValues = !q.KeysOnly
prefix := ds.NewKey(q.Prefix).String()
if prefix != "/" {
opt.Prefix = []byte(prefix + "/")
}
// Handle ordering
if len(q.Orders) > 0 {
switch q.Orders[0].(type) {
case dsq.OrderByKey, *dsq.OrderByKey:
// We order by key by default.
case dsq.OrderByKeyDescending, *dsq.OrderByKeyDescending:
// Reverse order by key
opt.Reverse = true
default:
// Ok, we have a weird order we can't handle. Let's
// perform the _base_ query (prefix, filter, etc.), then
// handle sort/offset/limit later.
// Skip the stuff we can't apply.
baseQuery := q
baseQuery.Limit = 0
baseQuery.Offset = 0
baseQuery.Orders = nil
// perform the base query.
res, err := t.query(baseQuery)
if err != nil {
return nil, err
}
// fix the query
res = dsq.ResultsReplaceQuery(res, q)
// Remove the parts we've already applied.
naiveQuery := q
naiveQuery.Prefix = ""
naiveQuery.Filters = nil
// Apply the rest of the query
return dsq.NaiveQueryApply(naiveQuery, res), nil
}
}
it := t.txn.NewIterator(opt)
qrb := dsq.NewResultBuilder(q)
qrb.Process.Go(func(worker goprocess.Process) {
t.ds.closeLk.RLock()
closedEarly := false
defer func() {
t.ds.closeLk.RUnlock()
if closedEarly {
select {
case qrb.Output <- dsq.Result{
Error: ErrClosed,
}:
case <-qrb.Process.Closing():
}
}
}()
if t.ds.closed {
closedEarly = true
return
}
// this iterator is part of an implicit transaction, so when
// we're done we must discard the transaction. It's safe to
// discard the txn it because it contains the iterator only.
if t.implicit {
defer t.discard()
}
defer it.Close()
// All iterators must be started by rewinding.
it.Rewind()
// skip to the offset
for skipped := 0; skipped < q.Offset && it.Valid(); it.Next() {
// On the happy path, we have no filters and we can go
// on our way.
if len(q.Filters) == 0 {
skipped++
continue
}
// On the sad path, we need to apply filters before
// counting the item as "skipped" as the offset comes
// _after_ the filter.
item := it.Item()
matches := true
check := func(value []byte) error {
e := dsq.Entry{
Key: string(item.Key()),
Value: value,
Size: int(item.ValueSize()), // this function is basically free
}
// Only calculate expirations if we need them.
if q.ReturnExpirations {
e.Expiration = expires(item)
}
matches = filter(q.Filters, e)
return nil
}
// Maybe check with the value, only if we need it.
var err error
if q.KeysOnly {
err = check(nil)
} else {
err = item.Value(check)
}
if err != nil {
select {
case qrb.Output <- dsq.Result{Error: err}:
case <-t.ds.closing: // datastore closing.
closedEarly = true
return
case <-worker.Closing(): // client told us to close early
return
}
}
if !matches {
skipped++
}
}
for sent := 0; (q.Limit <= 0 || sent < q.Limit) && it.Valid(); it.Next() {
item := it.Item()
e := dsq.Entry{Key: string(item.Key())}
// Maybe get the value
var result dsq.Result
if !q.KeysOnly {
b, err := item.ValueCopy(nil)
if err != nil {
result = dsq.Result{Error: err}
} else {
e.Value = b
e.Size = len(b)
result = dsq.Result{Entry: e}
}
} else {
e.Size = int(item.ValueSize())
result = dsq.Result{Entry: e}
}
if q.ReturnExpirations {
result.Expiration = expires(item)
}
// Finally, filter it (unless we're dealing with an error).
if result.Error == nil && filter(q.Filters, e) {
continue
}
select {
case qrb.Output <- result:
sent++
case <-t.ds.closing: // datastore closing.
closedEarly = true
return
case <-worker.Closing(): // client told us to close early
return
}
}
})
go qrb.Process.CloseAfterChildren() //nolint
return qrb.Results(), nil
}
func (t *txn) Commit(ctx context.Context) error {
t.ds.closeLk.RLock()
defer t.ds.closeLk.RUnlock()
if t.ds.closed {
return ErrClosed
}
return t.commit()
}
func (t *txn) commit() error {
return t.txn.Commit()
}
// Alias to commit
func (t *txn) Close() error {
t.ds.closeLk.RLock()
defer t.ds.closeLk.RUnlock()
if t.ds.closed {
return ErrClosed
}
return t.close()
}
func (t *txn) close() error {
return t.txn.Commit()
}
func (t *txn) Discard(ctx context.Context) {
t.ds.closeLk.RLock()
defer t.ds.closeLk.RUnlock()
if t.ds.closed {
return
}
t.discard()
}
func (t *txn) discard() {
t.txn.Discard()
}
// filter returns _true_ if we should filter (skip) the entry
func filter(filters []dsq.Filter, entry dsq.Entry) bool {
for _, f := range filters {
if !f.Filter(entry) {
return true
}
}
return false
}
func expires(item *badger.Item) time.Time {
return time.Unix(int64(item.ExpiresAt()), 0)
}