-
Notifications
You must be signed in to change notification settings - Fork 0
/
indexer.go
executable file
·1251 lines (1015 loc) · 25.6 KB
/
indexer.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 indexer
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io"
"strings"
"time"
"github.com/RangerMauve/ipld-prolly-indexer/schema"
blocks "github.com/ipfs/go-block-format"
"github.com/ipfs/go-cid"
logging "github.com/ipfs/go-log/v2"
"github.com/ipld/go-ipld-prime/traversal/selector"
sb "github.com/ipld/go-ipld-prime/traversal/selector/builder"
datastore "github.com/ipfs/go-datastore"
blockstore "github.com/ipfs/go-ipfs-blockstore"
car2 "github.com/ipld/go-car/v2"
carBlockstore "github.com/ipld/go-car/v2/blockstore"
selectorparse "github.com/ipld/go-ipld-prime/traversal/selector/parse"
ipld "github.com/ipld/go-ipld-prime"
dagcbor "github.com/ipld/go-ipld-prime/codec/cbor"
dagjson "github.com/ipld/go-ipld-prime/codec/json"
datamodel "github.com/ipld/go-ipld-prime/datamodel"
qp "github.com/ipld/go-ipld-prime/fluent/qp"
cidlink "github.com/ipld/go-ipld-prime/linking/cid"
basicnode "github.com/ipld/go-ipld-prime/node/basicnode"
tree "github.com/kenlabs/go-ipld-prolly-trees/pkg/tree"
)
var log = logging.Logger("ipld-prolly-indexer")
type Database struct {
blockStore blockstore.Blockstore
linkSystem *ipld.LinkSystem
rootCid cid.Cid
tree *tree.ProllyTree
collections map[string]*Collection
}
type Collection struct {
db *Database
name string
primaryKey []string
}
type Index struct {
collection *Collection
fields []string
}
type op string
const (
GreaterThan op = "GreaterThan"
LessThan op = "LessThan"
)
type CompareCondition struct {
cmp op
indexName string
indexVal ipld.Node
}
func (cc *CompareCondition) Satisfy(record ipld.Node) (bool, error) {
keyBytes, err := fieldCborBytesFromRecord(cc.indexName, record)
if err != nil {
return false, err
}
cmpRes := bytes.Compare(keyBytes, cborBytesOfNode(cc.indexVal))
switch cc.cmp {
case GreaterThan:
if cmpRes > 0 {
return true, nil
} else {
return false, nil
}
case LessThan:
if cmpRes < 0 {
return true, nil
} else {
return false, nil
}
default:
return false, fmt.Errorf("unsupported compare type")
}
}
type Record struct {
Id []byte
Data ipld.Node
}
type Query struct {
Equal map[string]ipld.Node
Compare *CompareCondition
Sort string
Limit int
Skip int
}
type InclusionProof struct {
Key []byte
Proof tree.Proof
Root cid.Cid
}
var (
NULL_BYTE = []byte("\x00")
FULL_BYTE = []byte("\xFF")
DATA_PREFIX = []byte("\x00d")
INDEX_PREFIX = []byte("\x00i")
DB_METADATA_KEY = []byte("\xFF\x00")
)
var (
INDEX_VERSION_1 = int64(1)
CURRENT_DB_VERSION = INDEX_VERSION_1
)
const (
ChannelTimeOut = time.Second * 10
)
func FromBlockStore(blockStore blockstore.Blockstore, rootCid cid.Cid) (*Database, error) {
nodeStore, err := tree.NewBlockNodeStore(blockStore, &tree.StoreConfig{CacheSize: 1 << 10})
if err != nil {
return nil, err
}
ptree, err := tree.LoadProllyTreeFromRootCid(rootCid, nodeStore)
if err != nil {
return nil, err
}
collections := map[string]*Collection{}
loadedCid, err := ptree.TreeCid()
if err != nil {
return nil, err
}
if !loadedCid.Equals(rootCid) {
return nil, errors.New("Tree CID did not load properly")
}
db := &Database{
blockStore: blockStore,
linkSystem: nodeStore.LinkSystem(),
rootCid: rootCid,
tree: ptree,
collections: collections,
}
return db, nil
}
func NewDatabaseFromBlockStore(ctx context.Context, blockStore blockstore.Blockstore) (*Database, error) {
nodeStore, err := tree.NewBlockNodeStore(blockStore, &tree.StoreConfig{CacheSize: 1 << 10})
if err != nil {
return nil, err
}
// We're going to construct a fresh ProllyTree as our root to apply changes on
chunkConfig := tree.DefaultChunkConfig()
framework, err := tree.NewFramework(ctx, nodeStore, chunkConfig, nil)
if err != nil {
return nil, err
}
collections := map[string]*Collection{}
dbMetaInfo, err := schema.BuildDBMetaInfoNode(CURRENT_DB_VERSION, "database")
if err != nil {
return nil, err
}
// Initialize the tree with metadata saying it's an indexed tree
err = framework.Append(ctx, DB_METADATA_KEY, dbMetaInfo)
if err != nil {
return nil, err
}
ptree, rootCid, err := framework.BuildTree(ctx)
if err != nil {
return nil, err
}
db := &Database{
blockStore,
nodeStore.LinkSystem(),
rootCid,
ptree,
collections,
}
return db, nil
}
func NewMemoryDatabase() (*Database, error) {
ctx := context.Background()
blockStore := blockstore.NewBlockstore(datastore.NewMapDatastore())
return NewDatabaseFromBlockStore(ctx, blockStore)
}
func ImportFromFile(source string) (*Database, error) {
blockStore, err := carBlockstore.OpenReadOnly(source, carBlockstore.UseWholeCIDs(true))
if err != nil {
return nil, err
}
roots, err := blockStore.Roots()
if err != nil {
return nil, err
}
if len(roots) == 0 {
return nil, fmt.Errorf("No root CIDs found in CAR file")
}
rootCid := roots[0]
return FromBlockStore(blockStore, rootCid)
}
// Merge two db in ProllyTree level, but the collection merging is not handling now.(i.e. maybe here exists the case
// that two collections has same name but with different primary keys)
func Merge(ctx context.Context, db *Database, other *Database) (*Database, error) {
err := db.tree.Merge(ctx, other.tree)
if err != nil {
return nil, err
}
ch, err := other.blockStore.AllKeysChan(ctx)
if err != nil {
return nil, err
}
blksCh := make(chan blocks.Block, 0)
var innerError error
go func() {
defer close(blksCh)
for c := range ch {
blk, err := other.blockStore.Get(ctx, c)
if err != nil {
innerError = err
return
}
blksCh <- blk
}
}()
for blk := range blksCh {
if innerError != nil {
return nil, innerError
}
err = db.blockStore.Put(ctx, blk)
if err != nil {
return nil, err
}
}
db.rootCid = db.tree.Root
// todo: load all collection
// todo: handle pk and index merging
//for name, newCol := range other.collections {
// if col, ok := db.collections[name]; ok {
// // merge exist collection
// } else {
// // add new collection
// }
//}
return db, nil
}
func (db *Database) GetDBMetaInfo() (*schema.DBMetaInfo, error) {
res, err := db.tree.Get(DB_METADATA_KEY)
if err != nil {
return nil, err
}
dmi, err := schema.UnwrapDBMetaInfo(res)
if err != nil {
return nil, err
}
return dmi, nil
}
func (db *Database) ApplyChanges(ctx context.Context) error {
rootCid, err := db.tree.Rebuild(ctx)
if err != nil {
return err
}
db.rootCid = rootCid
return nil
}
func (db *Database) startMutating(ctx context.Context) error {
if !db.tree.IsMutating() {
return db.tree.Mutate()
}
return nil
}
func (db *Database) ExportToFile(ctx context.Context, destination string) error {
return car2.TraverseToFile(
ctx,
db.linkSystem,
db.rootCid,
selectorparse.CommonSelector_ExploreAllRecursively,
destination,
)
}
func (db *Database) saveProof(ctx context.Context, proof tree.Proof, prefix *cid.Prefix) (cid.Cid, error) {
return db.tree.NodeStore().WriteProof(ctx, proof, prefix)
}
func (db *Database) ExportProof(ctx context.Context, prfCid cid.Cid, destination string) error {
prf, err := db.tree.NodeStore().ReadProof(ctx, prfCid)
if err != nil {
return err
}
ssb := sb.NewSelectorSpecBuilder(basicnode.Prototype.Any)
sel := ssb.ExploreRange(0, int64(len(prf)-1), ssb.ExploreRecursive(selector.RecursionLimitDepth(2), ssb.ExploreAll(ssb.ExploreRecursiveEdge())))
return car2.TraverseToFile(
ctx,
db.linkSystem,
prfCid,
sel.Node(),
destination,
)
}
func (db *Database) RootCid() cid.Cid {
return db.rootCid
}
func (db *Database) GetBlockstore() *blockstore.Blockstore {
return &db.blockStore
}
func (db *Database) Collection(ctx context.Context, name string, primaryKey ...string) (*Collection, error) {
if db.collections[name] == nil {
collection := Collection{
db,
name,
primaryKey,
}
db.collections[name] = &collection
err := collection.Initialize(ctx)
if err != nil {
return nil, err
}
}
return db.collections[name], nil
}
func (db *Database) ListCollections(ctx context.Context) ([]string, error) {
start := concat(FULL_BYTE, FULL_BYTE)
end := concat(start, FULL_BYTE)
iterator, err := db.tree.Search(ctx, start, end)
if err != nil {
return nil, err
}
var collections []string
for !iterator.Done() {
// Ignore the key since we don't care about it
key, data, err := iterator.NextPair()
if err != nil {
return nil, err
} else if data == nil {
// Equivalent of done
break
}
// sice off the first two bytes and parse the rest as a string
name := string(key[2:])
collections = append(collections, name)
}
return collections, nil
}
func (collection *Collection) HasPrimaryKey() bool {
return (collection.primaryKey != nil) && (len(collection.primaryKey) != 0)
}
func (collection *Collection) PrimaryKey() []string {
if !collection.HasPrimaryKey() {
return []string{}
}
return collection.primaryKey[:]
}
func (collection *Collection) Initialize(ctx context.Context) error {
metadata, loadErr := collection.GetMetaInfo(ctx)
if !collection.HasPrimaryKey() {
if metadata != nil {
// Likely loading as a reader, try loading metadata
collection.primaryKey = metadata.PrimaryKey
}
} else {
// Likely loading as a writer, save metadata if not exists
if loadErr != nil {
return collection.saveMetaInfo(ctx)
}
}
// See if there is metadata (primary key, collection version number)
// If no metadata, take primary key and save it
return nil
}
func (collection *Collection) getMetaKey() []byte {
return concat(FULL_BYTE, FULL_BYTE, []byte(collection.name))
}
func (collection *Collection) GetMetaInfo(ctx context.Context) (*schema.CollectionMetaInfo, error) {
key := collection.getMetaKey()
node, err := collection.db.tree.Get(key)
if err != nil {
return nil, err
}
return schema.UnwrapCollectionMetaInfo(node)
}
func (collection *Collection) saveMetaInfo(ctx context.Context) error {
key := collection.getMetaKey()
metaInfo := schema.CollectionMetaInfo{
Version: 1,
PrimaryKey: collection.primaryKey,
}
node, err := metaInfo.ToNode()
if err != nil {
return err
}
err = collection.db.startMutating(ctx)
if err != nil {
return err
}
err = collection.db.tree.Put(ctx, key, node)
if err != nil {
return err
}
err = collection.db.ApplyChanges(ctx)
return nil
}
func (collection *Collection) IndexNDJSON(ctx context.Context, byteStream io.Reader) error {
err := collection.db.startMutating(ctx)
if err != nil {
return err
}
scanner := bufio.NewScanner(byteStream)
for scanner.Scan() {
line := scanner.Text()
buffer := strings.NewReader(line)
mapBuilder := basicnode.Prototype.Map.NewBuilder()
err = dagjson.Decode(mapBuilder, buffer)
if err != nil {
return err
}
node := mapBuilder.Build()
err = collection.Insert(ctx, node)
if err != nil {
return err
}
}
err = scanner.Err()
// For some reason it throws an EOF even when closed properly
if err != nil && err != io.EOF {
return err
}
err = collection.db.ApplyChanges(ctx)
if err != nil {
return err
}
return nil
}
func (collection *Collection) Indexes(ctx context.Context) ([]*Index, error) {
prefix := concat(collection.keyPrefix(), NULL_BYTE, INDEX_PREFIX, NULL_BYTE)
fieldsStart := len(prefix)
start := concat(prefix, NULL_BYTE)
end := concat(prefix, FULL_BYTE)
iterator, err := collection.db.tree.Search(ctx, start, end)
if err != nil {
return nil, err
}
var indexes []*Index
for !iterator.Done() {
// Ignore the key since we don't care about it
key, data, err := iterator.NextPair()
if err != nil {
return nil, err
} else if data == nil {
// Equivalent of done
break
}
indexMetaInfo, err := schema.UnwrapIndexMetaInfo(data)
if err != nil {
return nil, err
}
if indexMetaInfo.Version != INDEX_VERSION_1 {
return nil, fmt.Errorf("Unexpected version number in index metadata")
}
fields, err := parseStringsFromCBOR(key[fieldsStart:])
if err != nil {
return nil, err
}
indexes = append(indexes, &Index{
collection,
fields,
})
}
return indexes, nil
}
func (collection *Collection) CreateIndex(ctx context.Context, fields ...string) (*Index, error) {
err := collection.db.startMutating(ctx)
if err != nil {
return nil, err
}
index := Index{
collection,
fields,
}
if index.Exists() {
return &index, nil
}
err = index.persistMetadata(ctx)
if err != nil {
return nil, err
}
err = index.Rebuild(ctx)
if err != nil {
return nil, err
}
err = collection.db.ApplyChanges(ctx)
if err != nil {
return nil, err
}
return &index, nil
}
func (collection *Collection) Insert(ctx context.Context, record ipld.Node) error {
collection.db.startMutating(ctx)
indexes, err := collection.Indexes(ctx)
if err != nil {
return err
}
prefix := collection.keyPrefix()
treeConfig := collection.db.tree.TreeConfig()
linkPrefix := treeConfig.CidPrefix()
linkProto := cidlink.LinkPrototype{Prefix: *linkPrefix}
linkSystem := collection.db.linkSystem
link, err := linkSystem.Store(ipld.LinkContext{Ctx: ctx}, linkProto, record)
if err != nil {
return err
}
var recordId []byte = nil
if collection.HasPrimaryKey() {
recordId, err = collection.recordId(record)
if err != nil {
return err
}
} else {
recordId = []byte(link.Binary())
}
for _, index := range indexes {
err = index.insert(ctx, record, recordId)
if err != nil {
return err
}
}
recordKey := concat(prefix, DATA_PREFIX, NULL_BYTE, recordId)
return collection.db.tree.Put(ctx, recordKey, basicnode.NewLink(link))
}
func (collection *Collection) Get(ctx context.Context, recordId []byte) (ipld.Node, error) {
prefix := collection.keyPrefix()
recordKey := concat(prefix, DATA_PREFIX, NULL_BYTE, recordId)
rawNode, err := collection.db.tree.Get(recordKey)
if err != nil {
return nil, err
}
rawNodeCid, err := rawNode.AsLink()
if err != nil {
return nil, err
}
return collection.db.linkSystem.Load(
ipld.LinkContext{Ctx: ctx},
rawNodeCid,
basicnode.Prototype.Map,
)
}
func (collection *Collection) GetProof(recordId []byte) (*InclusionProof, error) {
prefix := collection.keyPrefix()
recordKey := concat(prefix, DATA_PREFIX, NULL_BYTE, recordId)
proof, err := collection.db.tree.GetProof(recordKey)
if err != nil {
return nil, err
}
root := collection.db.rootCid
lastProof := proof[len(proof)-1]
if !root.Equals(lastProof.Node) {
return nil, errors.New("Generated proof was invalid.")
}
inclusion := &InclusionProof{
Key: recordKey,
Root: root,
Proof: proof,
}
return inclusion, nil
}
func (collection *Collection) recordId(record ipld.Node) ([]byte, error) {
return indexKeyFromRecord(collection.primaryKey, record, nil)
}
func (collection *Collection) keyPrefix() []byte {
return concat(NULL_BYTE, []byte(collection.name))
}
func (index *Index) Fields() []string {
return index.fields
}
func (index *Index) recordKey(record ipld.Node, id []byte) ([]byte, error) {
indexPrefix, err := index.keyPrefix()
if err != nil {
return nil, err
}
recordIndexValues, err := indexKeyFromRecord(index.fields, record, id)
if err != nil {
return nil, err
}
return concat(indexPrefix, NULL_BYTE, recordIndexValues), nil
}
func (index *Index) queryPrefix(query Query) ([]byte, error) {
indexPrefix, err := index.keyPrefix()
if err != nil {
return nil, err
}
indexedFields := []ipld.Node{}
for _, name := range index.fields {
node, ok := query.Equal[name]
if !ok {
break
}
indexedFields = append(indexedFields, node)
}
toRemove := 0
// Pad any missing index values with 0 bytes
// This sets the correct "length" for the array in the key gen
// Add an extra padding at the end for the primary key of a record
for len(indexedFields) <= len(index.fields) {
indexedFields = append(indexedFields, basicnode.NewInt(0))
toRemove += 1
}
cborData, err := encodeListToCBOR(indexedFields)
if err != nil {
return nil, err
}
// Remove the padded 0s
unPadded := cborData[0 : len(cborData)-toRemove]
finalKey := concat(indexPrefix, NULL_BYTE, unPadded)
return finalKey, nil
}
func (index *Index) keyPrefix() ([]byte, error) {
nameBytes, err := indexKeyFromFields(index.fields)
if err != nil {
return nil, err
}
return concat(index.collection.keyPrefix(), INDEX_PREFIX, NULL_BYTE, nameBytes), nil
}
func (index *Index) metadataKey() ([]byte, error) {
nameBytes, err := indexKeyFromFields(index.fields)
if err != nil {
return nil, err
}
return concat(index.collection.keyPrefix(), NULL_BYTE, INDEX_PREFIX, NULL_BYTE, nameBytes), nil
}
func (index *Index) Exists() bool {
key, err := index.metadataKey()
if err != nil {
return false
}
// check existence
n, err := index.collection.db.tree.Get(key)
if err != nil {
return false
}
// check type
_, err = schema.UnwrapIndexMetaInfo(n)
return err == nil
}
func (index *Index) Rebuild(ctx context.Context) error {
// Iterate over records in collection
// Insert index keys for each one
return nil
}
func (index *Index) insert(ctx context.Context, record ipld.Node, recordId []byte) error {
indexRecordKey, err := index.recordKey(record, recordId)
if err != nil {
return err
}
ipldRecordId := basicnode.NewBytes(recordId)
return index.collection.db.tree.Put(ctx, indexRecordKey, ipldRecordId)
}
func (index *Index) persistMetadata(ctx context.Context) error {
key, err := index.metadataKey()
if err != nil {
return err
}
metadata, err := schema.BuildIndexMetaInfoNode(INDEX_VERSION_1)
if err != nil {
return err
}
return index.collection.db.tree.Put(ctx, key, metadata)
}
func (collection *Collection) Iterate(ctx context.Context) (<-chan Record, error) {
prefix := collection.keyPrefix()
idStart := len(prefix) + len(DATA_PREFIX) + len(NULL_BYTE)
start := concat(prefix, DATA_PREFIX, NULL_BYTE)
end := concat(prefix, DATA_PREFIX, FULL_BYTE)
iterator, err := collection.db.tree.Search(ctx, start, end)
if err != nil {
return nil, err
}
linkSystem := collection.db.linkSystem
c := make(chan Record)
// TODO: Better error handling
go func(ch chan<- Record) {
defer close(ch)
IteratorLoop:
for !iterator.Done() {
// Ignore the key since we don't care about it
key, rawNode, err := iterator.NextPair()
if err != nil {
panic(err)
} else if rawNode == nil {
break
}
rawNodeCid, err := rawNode.AsLink()
if err != nil {
panic(err)
}
data, err := linkSystem.Load(
ipld.LinkContext{Ctx: ctx},
rawNodeCid,
basicnode.Prototype.Map,
)
if err != nil {
panic(err)
}
id := key[idStart:]
record := Record{
Id: id,
Data: data,
}
// TODO: What about the error?
select {
case <-ctx.Done():
break IteratorLoop
case <-time.After(ChannelTimeOut):
break IteratorLoop
case ch <- record:
}
}
}(c)
return c, nil
}
func (collection *Collection) Search(ctx context.Context, query Query) (<-chan Record, error) {
index, err := collection.BestIndex(ctx, query)
if err != nil {
return nil, err
}
count := 0
skipped := 0
c := make(chan Record)
if index == nil {
// Iterate all and filter as you go
all, err := collection.Iterate(ctx)
if err != nil {
return nil, err
}
// TODO: Better error handling
go func(ch chan<- Record) {
defer close(ch)
IteratorLoop:
for record := range all {
if query.Matches(record) {
if skipped < query.Skip {
skipped++
continue
}
if query.Limit != 0 {
if count >= query.Limit {
break
} else {
count++
}
}
select {
case <-ctx.Done():
break IteratorLoop
case <-time.After(ChannelTimeOut):
break IteratorLoop
case ch <- record:
}
}
}
}(c)
} else {
// Get fields
start, err := index.queryPrefix(query)
if err != nil {
return nil, err
}
end := make([]byte, len(start))
copy(end, start)
// TODO: Detect if ending is already 0xFF and keep going back filling up
end[len(end)-1] = 0xFF
iterator, err := collection.db.tree.Search(ctx, start, end)
if err != nil {
return nil, err
}
// TODO: Better error handling
go func(ch chan<- Record) {
defer close(ch)
IteratorLoop:
for !iterator.Done() {
// Ignore the key since we don't care about it
_, recordIdNode, err := iterator.NextPair()
if recordIdNode == nil && err == nil {
break
}
if err != nil {
panic(err)
}
recordId, err := recordIdNode.AsBytes()
if err != nil {
panic(err)
}
// TODO: Pull additional fields from query key before loading record
data, err := collection.Get(ctx, recordId)
if err != nil {
panic(err)
}
record := Record{
Id: recordId,
Data: data,
}
if !query.Matches(record) {
continue
}
if skipped < query.Skip {
skipped++
continue
}
if query.Limit != 0 {
if count >= query.Limit {
break
} else {
count++
}
}
// TODO: What about the error?
select {
case <-ctx.Done():
break IteratorLoop
case <-time.After(ChannelTimeOut):
break IteratorLoop
case ch <- record:
}
}
}(c)