-
Notifications
You must be signed in to change notification settings - Fork 10
/
segments.go
1448 lines (1348 loc) · 37.9 KB
/
segments.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
package rankdb
// Copyright 2019 Vivino. All rights reserved
//
// See LICENSE file for license details
//go:generate msgp $GOFILE
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"sort"
"sync"
"sync/atomic"
"time"
"github.com/Vivino/rankdb/blobstore"
"github.com/Vivino/rankdb/log"
)
// SegmentsID is the ID of a collection of segments.
type SegmentsID string
// segmentsVersion should be incremented if non-compatible changes are made.
const segmentsVersion = 2
// SegmentsID returns whether the segment ID is non-zero.
func (s SegmentsID) Unset() bool {
return s == ""
}
// Segments contains all segments of a list
// and contains and index to quickly look up the index of a segment.
type Segments struct {
ID SegmentsID
Segments []Segment // Individual segments
SegmentsLock sync.RWMutex `msg:"-" json:"-"` // Global lock for all stats on all segments (above)
NextID SegmentID // Next unused ID
IsIndex bool // These segments represents an index.
idx map[SegmentID]int // Segment ID -> Segments Index lookup.
cache Cache // Global segment cache
cacheHits uint64
cacheMisses uint64
}
// NewSegments creates new segments and preallocates space for segments.
// Optionally it will preallocate internal index as well.
func NewSegments(preAlloc int, withIdx bool) *Segments {
s := Segments{
ID: SegmentsID(RandString(8)),
Segments: make([]Segment, 0, preAlloc),
NextID: 1,
}
if withIdx {
s.idx = make(map[SegmentID]int, preAlloc)
}
return &s
}
// NewSegmentsElements creates segments from slices of elements.
// Each member of the slice will result in one segment.
// The Segment range will cover the entire possible space, so first segment
// will always be from MaxElement, etc.
// If idx is supplied it will be populated with index elements.
// If idx is not supplied it is assumed that this is index segments.
func NewSegmentsElements(ctx context.Context, bs blobstore.WithSet, e []Elements, idx *IndexElements) (*Segments, error) {
s := &Segments{
ID: SegmentsID(RandString(8)),
Segments: make([]Segment, 0, len(e)),
NextID: 1,
IsIndex: idx == nil,
}
next := MaxSegment()
timestamp := time.Now()
var ids IndexElements
if idx != nil {
ids = *idx
}
for i, elems := range e {
if len(elems) == 0 {
continue
}
e2 := elems.Clone(false)
ls := NewSegmentElements(s, e2)
seg := ls.seg
seg.Max = next.Max
seg.MaxTie = next.MaxTie
seg.Updated = timestamp.Unix()
// Last element covers down to 0.
if i == len(e)-1 {
seg.Min = 0
seg.MinTie = 0
}
s.Append(ls)
if idx != nil {
ids.Elements = append(ids.Elements, elems.ElementIDs(seg.ID).Elements...)
}
err := s.replaceSegment(ctx, bs, ls)
if err != nil {
return nil, err
}
// Next segment starts just before this the last of this.
e := elems[len(elems)-1]
next.Max, next.MaxTie = e.PrevMax()
}
// If empty, add one full-range segment.
if len(s.Segments) == 0 {
ls := s.newLockedSegment(ctx, bs, MaxSegment())
err := s.replaceSegment(ctx, bs, ls)
if err != nil {
return nil, err
}
}
s.AlignIndex()
if idx != nil {
*idx = ids
}
return s, nil
}
// Elements returns the number of elements in all segments.
// Caller must hold at least read lock for segment.
func (s *Segments) Elements() int {
s.SegmentsLock.RLock()
var n int
for i := range s.Segments {
seg := &s.Segments[i]
n += seg.N
}
s.SegmentsLock.RUnlock()
return n
}
// AlignIndex will align segments to be used for indexes.
// This ensure that segment splits are on score boundaries
// so changes in tiebreaker does not affect segment assignment.
// This should only be used on segment creation and not on segments with content.
func (s *Segments) AlignIndex() {
if !s.IsIndex {
return
}
for i := range s.Segments {
seg := s.Segments[i]
if i > 0 {
prev := s.Segments[i-1]
prev.MinTie = 0
seg.MaxTie = math.MaxUint32
seg.Max = prev.Min - 1
s.Segments[i] = seg
s.Segments[i-1] = prev
}
}
}
// Append a segment to the end of segments.
// The locked segment is updated with new index.
func (s *Segments) Append(ls *lockedSegment) {
s.SegmentsLock.Lock()
s.Segments = append(s.Segments, *ls.seg)
// Add to index if we have one.
idx := len(s.Segments) - 1
ls.index = idx
if s.idx != nil {
s.idx[ls.seg.ID] = idx
}
// Increment NextID if we need to.
if ls.seg.ID >= s.NextID {
s.NextID = ls.seg.ID + 1
}
s.SegmentsLock.Unlock()
}
// elementFullIdx returns full element by index.
// If the segment is unloaded it is loaded and the segments are updated.
// Caller must hold segments lock (to pin index).
// Returned segment.emu (if ok) is locked. If readonly an RLock is used.
func (s *Segments) elementFullIdx(ctx context.Context, bs blobstore.WithSet, i int, readOnly bool) (ls *lockedSegment, err error) {
// 1. Acquire the lock required
// If we have write lock, no-one else has it.
// If we have read lock others may have it or be attempting to load it.
// 2. Ask for segment elements in cache.
// 3. Check if someone is attempting to load it.
// 4A. Load it if none are loading it.
// 4B. Wait for others loading it.
// 5. Return segment elements with lock.
const debugLocks = false
ls = &lockedSegment{index: i, readOnly: readOnly}
seg := &s.Segments[i]
lock := &seg.loader.Mu
if readOnly {
if debugLocks {
log.Logger(ctx).Info("Read lock requested", "id", seg.cacheID())
}
lock.RLock()
ls.unlock = lock.RUnlock
if debugLocks {
log.Logger(ctx).Info("Read lock acquired", "id", seg.cacheID())
ls.unlock = func() {
if lock != &seg.loader.Mu {
panic("lock changed")
}
lock.RUnlock()
log.Logger(ctx).Info("Read lock released", "id", seg.cacheID())
ls.elements = nil
}
}
} else {
if debugLocks {
log.Logger(ctx).Info("Write lock requested", "id", seg.cacheID())
}
lock.Lock()
ls.unlock = lock.Unlock
if debugLocks {
log.Logger(ctx).Info("Write lock acquired", "id", seg.cacheID())
ls.unlock = func() {
if lock != &seg.loader.Mu {
panic("lock changed")
}
lock.Unlock()
log.Logger(ctx).Info("Write lock released", "id", seg.cacheID())
ls.elements = nil
}
}
}
ls.seg = seg
if s.cache != nil {
v, ok := s.cache.Get(seg.cacheID())
if ok {
ls.elements, ok = v.(Elements)
if ok {
atomic.AddUint64(&s.cacheHits, 1)
return ls, nil
}
}
atomic.AddUint64(&s.cacheMisses, 1)
}
ls.elements, err = seg.loadElements(ctx, bs, readOnly)
if err != nil {
ls.unlock()
return nil, err
}
if s.cache != nil {
s.cache.Add(seg.cacheID(), ls.elements)
}
return ls, nil
}
type lockedSegment struct {
seg *Segment
elements Elements
index int
readOnly bool
unlock func()
}
// Read lock must be held and locked segment must be write locked.
func (s *Segments) replaceSegment(ctx context.Context, bs blobstore.WithSet, ls *lockedSegment) error {
if ls.readOnly {
panic("replace with read only")
}
defer ls.unlock()
if ls.seg.loader == nil {
ls.seg.loader = &elementLoader{}
}
s.SegmentsLock.Lock()
ls.seg.elementsUpdated(ls.elements)
if ls.index >= len(s.Segments) || ls.index < 0 {
return fmt.Errorf("internal error: locked segment index (%d) out of range (0:%d)", ls.index, len(s.Segments))
}
s.Segments[ls.index] = *ls.seg
s.SegmentsLock.Unlock()
err := ls.saveElements(ctx, bs, ls.elements)
if err != nil {
return err
}
if s.cache != nil {
s.cache.Add(ls.seg.cacheID(), ls.elements)
}
ls.elements = nil
return nil
}
// newLockedSegment creates a new locked segment with the content of the provided segment.
// The segment is added to s, but not saved.
func (s *Segments) newLockedSegment(ctx context.Context, bs blobstore.WithSet, seg *Segment) *lockedSegment {
seg.ID = s.newID()
seg.Parent = s.ID
seg.Updated = time.Now().Unix()
seg.loader = &elementLoader{}
seg.loader.Mu.Lock()
ls := &lockedSegment{
seg: seg,
elements: Elements{},
index: -1,
readOnly: false,
unlock: seg.loader.Mu.Unlock,
}
s.Append(ls)
return ls
}
// deleteElements deletes specific elements in segments places at supplied index.
// Optionally returns index elements of deleted items.
// Read lock must be held for segments.
func (s *Segments) DeleteElementsIdx(ctx context.Context, bs blobstore.WithSet, ids IndexElements, withIdx bool) (IndexElements, error) {
// Collect indexes.
var idxC = make(chan IndexElements, len(s.Segments))
var errC = make(chan error)
// Split elements by segments IDs.
split := s.splitElementsID(ids)
var wg sync.WaitGroup
wg.Add(len(split))
for segIdx, ids := range split {
if len(ids) == 0 {
wg.Done()
continue
}
// Go through each segment that has elements that should be deleted.
go func(segIdx int, e ElementIDs) {
defer wg.Done()
ls, err := s.elementFullIdx(ctx, bs, segIdx, false)
if err != nil {
errC <- err
return
}
toDelete := e.Map()
deleted := IndexElements{}
if withIdx {
deleted = IndexElements{Elements: make(Elements, 0, len(e))}
}
wrtTo := 0
nDeleted := 0
for _, elem := range ls.elements {
if _, ok := toDelete[elem.ID]; !ok {
ls.elements[wrtTo] = elem
wrtTo++
continue
}
// Delete it
nDeleted++
if withIdx {
deleted.Elements = append(deleted.Elements, elem.AsIndex(ls.seg.ID).Element)
}
}
if nDeleted != len(toDelete) {
log.Info(ctx, "Did not find all elements", "left", len(toDelete)-nDeleted)
}
ls.elements = ls.elements[:wrtTo]
err = s.replaceSegment(ctx, bs, ls)
if err != nil {
errC <- err
return
}
if withIdx {
deleted.Sort()
idxC <- deleted
}
}(segIdx, ids)
}
err := waitErr(ctx, errC, &wg)
if err != nil {
return IndexElements{}, err
}
close(idxC)
var indexes IndexElements
for idx := range idxC {
indexes.Merge(idx.Elements, false)
}
return indexes, nil
}
// deleteElements deletes specific elements in segments.
// Optionally returns index elements of deleted items.
// Provided elements must be sorted.
func (s *Segments) DeleteElements(ctx context.Context, bs blobstore.WithSet, e Elements, withIdx bool) (IndexElements, error) {
in := e
var wg sync.WaitGroup
wg.Add(len(s.Segments))
// Collect indexes.
var idxC = make(chan IndexElements, len(s.Segments))
var errC = make(chan error)
s.SegmentsLock.RLock()
for i := range s.Segments {
seg := s.Segments[i]
start, end := seg.FilterIdx(in)
if start == end {
wg.Done()
continue
}
// Go through each segment that has elements that should be deleted.
go func(i int, e Elements) {
defer wg.Done()
ls, err := s.elementFullIdx(ctx, bs, i, false)
if err != nil {
errC <- err
return
}
seg := ls.seg
toDelete := make(map[ElementID]struct{})
deleted := IndexElements{Elements: make(Elements, 0)}
if withIdx {
deleted = IndexElements{Elements: make(Elements, 0, len(e))}
}
for _, elem := range e {
toDelete[elem.ID] = struct{}{}
}
wrtto := 0
ndeleted := 0
for _, elem := range ls.elements {
if _, ok := toDelete[elem.ID]; !ok {
ls.elements[wrtto] = elem
wrtto++
continue
}
// Delete it
ndeleted++
if withIdx {
deleted.Elements = append(deleted.Elements, elem.AsIndex(seg.ID).Element)
}
}
if ndeleted != len(toDelete) {
log.Info(ctx, "Did not find all elements", "left", len(toDelete)-ndeleted)
}
ls.elements = ls.elements[:wrtto]
err = s.replaceSegment(ctx, bs, ls)
if err != nil {
errC <- err
return
}
if withIdx {
deleted.Sort()
idxC <- deleted
}
}(i, in[start:end])
in = in[end:]
}
s.SegmentsLock.RUnlock()
err := waitErr(ctx, errC, &wg)
if err != nil {
return IndexElements{}, err
}
close(idxC)
var indexes IndexElements
for idx := range idxC {
indexes.Merge(idx.Elements, false)
}
return indexes, nil
}
// Insert sorted elements into segments.
// Returns indexes of elements if withIdx is true.
// Read lock must be held
func (s *Segments) Insert(ctx context.Context, bs blobstore.WithSet, in Elements, withIdx bool) (IndexElements, error) {
in.Sort()
if sanityChecks {
err := s.VerifyElements(ctx, bs, nil)
if err != nil {
log.Error(ctx, "Pre- Validation failed", "err", err)
return IndexElements{}, err
}
}
// Collect indexes.
s.SegmentsLock.RLock()
var wg sync.WaitGroup
wg.Add(len(s.Segments))
var idxC = make(chan IndexElements, len(s.Segments))
var errC = make(chan error)
for i := range s.Segments {
seg := &s.Segments[i]
start, end := seg.FilterIdx(in)
if start == end {
wg.Done()
continue
}
if start != 0 {
log.Error(ctx, "Expected start to be 0", "was", start)
}
go func(i int, e Elements) {
defer wg.Done()
ls, err := s.elementFullIdx(ctx, bs, i, false)
if err != nil {
errC <- err
return
}
seg := ls.seg
if sanityChecks {
if !sort.SliceIsSorted(e, e.Sorter()) {
err := fmt.Errorf("%d: incoming was not sorted before merge", seg.ID)
log.Error(ctx, err.Error())
errC <- err
ls.unlock()
return
}
if err := ls.elements.HasDuplicates(); err != nil {
log.Error(ctx, "Duplicates BEFORE merge", "error", err.Error())
errC <- err
}
if ol := ls.elements.IDs().Overlap(e.IDs()); len(ol) != 0 {
log.Error(ctx, "Insert overlaps existing", "ids", ol)
}
}
ls.elements.Merge(e, false)
if sanityChecks {
if !sort.SliceIsSorted(ls.elements, ls.elements.Sorter()) {
err := fmt.Errorf("%d: outgoing was not sorted after merge", seg.ID)
log.Error(ctx, err.Error(), "in_len", len(e), "seg_len", len(ls.elements))
errC <- err
ls.unlock()
return
}
if err := ls.elements.HasDuplicates(); err != nil {
log.Error(ctx, "Duplicates AFTER merge", "error", err.Error())
errC <- err
ls.unlock()
return
}
}
err = s.replaceSegment(ctx, bs, ls)
if err != nil {
errC <- err
}
if withIdx {
idxC <- e.ElementIDs(seg.ID)
}
}(i, in[start:end])
in = in[end:]
}
s.SegmentsLock.RUnlock()
err := waitErr(ctx, errC, &wg)
if err != nil {
return IndexElements{}, err
}
if sanityChecks {
err = s.VerifyElements(ctx, bs, nil)
if err != nil {
log.Error(ctx, "Post Validation failed", "err", err)
return IndexElements{}, err
}
}
close(idxC)
var idxs IndexElements
if withIdx {
idxs = IndexElements{Elements: make(Elements, 0, len(in))}
for idx := range idxC {
idxs.Elements = append(idxs.Elements, idx.Elements...)
}
idxs.Sort()
}
return idxs, nil
}
// newID returns a new segment ID.
// Caller must hold lock to segments.
func (s *Segments) newID() SegmentID {
id := s.NextID
s.NextID++
return id
}
// reindex will recreate the Segment ID index if needed.
// write lock must be held by caller.
func (s *Segments) reindex() {
s.SegmentsLock.RLock()
if len(s.idx) == len(s.Segments) {
s.SegmentsLock.RUnlock()
return
}
s.SegmentsLock.RUnlock()
s.SegmentsLock.Lock()
s.idx = make(map[SegmentID]int, len(s.Segments))
for i, v := range s.Segments {
s.idx[v.ID] = i
}
s.SegmentsLock.Unlock()
}
// segIdxTop returns the segment index and the offset of the element in the segment.
// Returns -1 if offset is after last element.
// caller must hold read lock.
func (s *Segments) segIdxTop(offset int) (segIdx, elementOffset int) {
n := 0
s.SegmentsLock.RLock()
defer s.SegmentsLock.RUnlock()
for i := range s.Segments {
seg := &s.Segments[i]
if n+seg.N > offset {
return i, offset - n
}
n += seg.N
}
return -1, -1
}
// segIdxBottom returns the segment index and the offset of the element in the segment.
// Returns -1 if offset is before first element.
// caller must hold read lock.
func (s *Segments) segIdxBottom(offset int) (segIdx, elementOffset int) {
n := 0
s.SegmentsLock.RLock()
defer s.SegmentsLock.RUnlock()
for i := len(s.Segments) - 1; i >= 0; i-- {
seg := &s.Segments[i]
if n+seg.N > offset {
return i, seg.N - (offset - n) - 1
}
n += seg.N
}
return -1, -1
}
// segIdxBottom returns the segment index containing first elements with provided score.
// Returns -1 if offset is before first element.
// caller must hold read lock.
func (s *Segments) segIdxScore(score uint64) (segIdx, above, total int) {
segIdx = -1
s.SegmentsLock.RLock()
defer s.SegmentsLock.RUnlock()
for i := range s.Segments {
seg := &s.Segments[i]
if segIdx < 0 && score >= seg.Min && score <= seg.Max {
segIdx = i
above = total
}
total += seg.N
}
return segIdx, above, total
}
// topOffsets returns the top offset of each segment and total number of elements.
// caller must hold read lock.
func (s *Segments) topOffsets() (elements []int, total int) {
res := make([]int, len(s.Segments))
n := 0
s.SegmentsLock.RLock()
defer s.SegmentsLock.RUnlock()
for i := range s.Segments {
seg := &s.Segments[i]
res[i] = n
n += seg.N
}
return res, n
}
// Verify segments without validating elements.
func (s *Segments) Verify(ctx context.Context, bs blobstore.WithSet) error {
if len(s.Segments) == 0 {
return fmt.Errorf("No segments found.")
}
foundSegs := make(map[SegmentID]int, len(s.Segments))
for i := range s.Segments {
err := func(i int) error {
s.SegmentsLock.RLock()
v := &s.Segments[i]
s.SegmentsLock.RUnlock()
prefix := fmt.Sprintf("Segment %v:", v.ID)
if v.Updated == 0 {
return fmt.Errorf(prefix + "Updated time not set")
}
if idx, ok := foundSegs[v.ID]; ok {
return fmt.Errorf(prefix+"Duplicate segment ID, at index %d and %d", idx, i)
}
foundSegs[v.ID] = i
// Check relation to previous.
if i == 0 {
// First segment should start at max.
if v.Max != math.MaxUint64 || v.MaxTie != math.MaxUint32 {
return fmt.Errorf(prefix+"First segment did not start at maximum, was %v, %v", v.Max, v.MaxTie)
}
} else {
s.SegmentsLock.RLock()
prev := &s.Segments[i-1]
s.SegmentsLock.RUnlock()
// Maximum of this should be just after minimum of previous
wantScore, wantTie := Element{Score: prev.Min, TieBreaker: prev.MinTie}.PrevMax()
if v.Max != wantScore || v.MaxTie != wantTie {
return fmt.Errorf(prefix+"Does not line up with previous segment. Want score, tie (%d, %d), got (%d, %d)",
wantScore, wantTie, v.Max, v.MaxTie)
}
if s.IsIndex {
// MaxTie should be 0 on indexes
if v.MinTie != 0 {
return fmt.Errorf(prefix + "Index segment did not end with mintie 0.")
}
if v.MaxTie != math.MaxUint32 {
return fmt.Errorf(prefix + "Index segment did not start with maxtie MAX.")
}
}
}
if i == len(s.Segments)-1 {
// Last element should go down to 0
if v.Min != 0 || v.MinTie != 0 {
return fmt.Errorf(prefix+"Last segment did not end at 0, was %v, %v", v.Min, v.MinTie)
}
}
return nil
}(i)
if err != nil {
return err
}
}
return nil
}
// VerifyElements verifies elements in segments.
// Supply a non-nil "IDs". It will be populated with the Element IDs found. The supplied map is overwritten.
// Segments must be read locked by callers.
func (s *Segments) VerifyElements(ctx context.Context, bs blobstore.WithSet, IDs *map[ElementID]SegmentID) error {
var errC = make(chan error)
var elems = make(map[ElementID]SegmentID, s.Elements())
if IDs != nil {
*IDs = elems
}
var elemsMu sync.Mutex
var wg sync.WaitGroup
wg.Add(len(s.Segments))
var b = NewBucket(8)
for i := range s.Segments {
go func(i int) {
defer wg.Done()
defer b.Get().Release()
ls, err := s.elementFullIdx(ctx, bs, i, true)
if err != nil {
errC <- err
return
}
defer ls.unlock()
seg := ls.seg
prefix := fmt.Sprintf("Segment ID %v (#%d) Elements:", seg.ID, i)
if !sort.SliceIsSorted(ls.elements, ls.elements.Sorter()) {
errC <- fmt.Errorf(prefix + "Not sorted")
}
if seg.N != len(ls.elements) {
errC <- fmt.Errorf(prefix+"Element counter wrong, is %d, should be %d", seg.N, len(ls.elements))
}
start, end := seg.FilterIdx(ls.elements)
if start != 0 {
log.Info(ctx, "Extra elements before start", "elements", len(ls.elements[start:]), "segment", seg)
errC <- fmt.Errorf(prefix+"%d Element(s) does not belong at START of segment", start)
}
if end != len(ls.elements) {
log.Info(ctx, "Extra elements after END", "elements", len(ls.elements[end:]), "segment", seg)
err := fmt.Errorf(prefix+"%d Element(s) does not belong at END of segment", len(ls.elements)-end)
errC <- err
}
if seg.N != len(ls.elements) {
errC <- fmt.Errorf("Segment length mismatch. N: %v, actual len: %v", seg.N, len(ls.elements))
}
// Big lock
elemsMu.Lock()
defer elemsMu.Unlock()
for _, elem := range ls.elements {
if _, ok := elems[elem.ID]; ok {
errC <- fmt.Errorf(prefix+"Duplicate element ID: %v", elem.ID)
return
}
if s.IsIndex {
elems[elem.ID] = SegmentID(elem.TieBreaker)
} else {
elems[elem.ID] = seg.ID
}
if elem.Updated == 0 {
errC <- fmt.Errorf(prefix+"Element %d does not have time set", 0)
return
}
}
}(i)
}
err := waitErr(ctx, errC, &wg)
if err != nil {
return err
}
return nil
}
// ElementIndexAll will return index for all elements in the list.
func (s *Segments) ElementIndexAll(ctx context.Context, bs blobstore.WithSet) (IndexElements, error) {
// Collect indexes.
res := IndexElements{Elements: make(Elements, 0, s.Elements())}
var idxC = make(chan IndexElements, len(s.Segments))
var errC = make(chan error)
var wg sync.WaitGroup
wg.Add(len(s.Segments))
var b = NewBucket(8)
for i := range s.Segments {
go func(i int) {
defer wg.Done()
defer b.Get().Release()
ls, err := s.elementFullIdx(ctx, bs, i, true)
if err != nil {
errC <- err
return
}
idxC <- ls.elements.ElementIDs(ls.seg.ID)
ls.unlock()
}(i)
}
err := waitErr(ctx, errC, &wg)
if err != nil {
return IndexElements{}, err
}
close(idxC)
for idx := range idxC {
res.Elements = append(res.Elements, idx.Elements...)
}
res.Sort()
return res, nil
}
// Save segments to disk.
func (s *Segments) Save(ctx context.Context, store blobstore.WithSet) error {
wm := NewWriterMsg()
defer wm.Close()
err := wm.SetVersion(segmentsVersion)
if err != nil {
return err
}
s.SegmentsLock.RLock()
err = s.EncodeMsg(wm.Writer())
s.SegmentsLock.RUnlock()
if err != nil {
return err
}
buf := wm.Buffer().Bytes()
return store.Set(ctx, string(s.ID), buf)
}
// Load will load the segments (but no elements) of the specified ID.
func (s SegmentsID) Load(ctx context.Context, store blobstore.WithSet, cache Cache) (*Segments, error) {
b, err := store.Get(ctx, string(s))
if err != nil {
return nil, err
}
var v uint8
b, v = MsgpGetVersion(b)
segs := Segments{}
switch v {
case 1:
return nil, errors.New("deprecated v1 found")
case segmentsVersion:
b, err = segs.UnmarshalMsg(b)
default:
return nil, ErrVersionMismatch
}
if err != nil {
log.Info(ctx, "Got err:", "error", err, "length", len(b))
return nil, err
}
segs.cache = cache
for i := range segs.Segments {
segs.Segments[i].loader = &elementLoader{}
}
return &segs, nil
}
// Delete will delete the segments representation and elements.
func (s *Segments) Delete(ctx context.Context, store blobstore.WithSet) error {
var wg sync.WaitGroup
wg.Add(len(s.Segments))
for i := range s.Segments {
elem := &s.Segments[i]
if s.cache != nil {
s.cache.Remove(elem.cacheID())
}
go func(s *Segment) {
defer wg.Done()
err := s.deleteElements(ctx, store)
if err != nil {
log.Error(ctx, "Unable to delete segment", "id", s.ID, "error", err)
}
}(elem)
}
wg.Wait()
s.Segments = nil
return store.Delete(ctx, string(s.ID))
}
// FindElements returns elements with the supplied indices.
// Not found errors are logged, but not fatal.
// Caller must hold s.scores read lock.
func (s *Segments) FindElements(ctx context.Context, bs blobstore.WithSet, ids IndexElements, radius int) ([]RankedElement, error) {
if len(ids.Elements) == 0 {
return nil, nil
}
// Split elements by segments IDs.
split := s.splitElementsID(ids)
// For each segment look up the collected elements.
var wg sync.WaitGroup
var errch = make(chan error)
var resch = make(chan []RankedElement, len(split))
wg.Add(len(split))
offsets, total := s.topOffsets()
for segIdx, id := range split {
go func(segIdx int, ids []ElementID) {
defer wg.Done()
ls, err := s.elementFullIdx(ctx, bs, segIdx, true)
if err != nil {
errch <- err
return
}
defer ls.unlock()
var res []RankedElement
for _, id := range ids {
re, err := s.findRanked(ctx, bs, ls, id, offsets[segIdx], radius)
if err != nil {
// We ignore not found elements.
continue
}
re.CalculateFromBottom(total)
res = append(res, *re)
}
resch <- res
}(segIdx, id)
}
err := waitErr(ctx, errch, &wg)
if err != nil {
return nil, err
}
close(resch)
var res []RankedElement
for e := range resch {
res = append(res, e...)
}
return res, nil
}
// getElementIndex returns element the element at supplied index in supplied segment.
// Must hold Read Lock
func (s *Segments) getElementIndex(ctx context.Context, bs blobstore.WithSet, segIdx, elementOff, offset, radius int) (*RankedElement, error) {
ls, err := s.elementFullIdx(ctx, bs, segIdx, true)
if err != nil {
return nil, err
}
defer ls.unlock()
if elementOff >= len(ls.elements) {
elementOff = len(ls.elements) - 1
}
re, err := s.findRanked(ctx, bs, ls, ls.elements[elementOff].ID, offset, radius)
if err != nil {
return nil, err
}
return re, nil
}
// findRanked returns ranked element.
// caller must hold segment read lock and element read lock for supplied segment.
func (s *Segments) findRanked(ctx context.Context, bs blobstore.WithSet, ls *lockedSegment, id ElementID, offset, radius int) (*RankedElement, error) {
eidx, err := ls.elements.FindIdx(id)
if err != nil {
//log.Info(ctx, "Unable to find element", "error", err, "segment_id", seg.ID, "element_id", id, "looking_in", seg)
log.Info(ctx, "Unable to find element", "error", err, "segment_id", ls.seg.ID, "element_id", id)
return nil, ErrNotFound
}
r := RankedElement{
Element: ls.elements[eidx],
FromTop: offset + eidx,
Above: make([]Element, 0, radius),
Below: make([]Element, 0, radius),
}
if radius <= 0 {
return &r, nil
}
segIdx := ls.index
// Below
func() {