forked from ssbc/jitdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1349 lines (1180 loc) · 37.8 KB
/
index.js
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
const path = require('path')
const bipf = require('bipf')
const push = require('push-stream')
const pull = require('pull-stream')
const toPull = require('push-stream-to-pull-stream')
const pullAsync = require('pull-async')
const TypedFastBitSet = require('typedfastbitset')
const bsb = require('binary-search-bounds')
const multicb = require('multicb')
const FastPriorityQueue = require('fastpriorityqueue')
const debug = require('debug')('jitdb')
const debugQuery = debug.extend('query')
const Status = require('./status')
const {
saveTypedArrayFile,
loadTypedArrayFile,
savePrefixMapFile,
loadPrefixMapFile,
saveBitsetFile,
loadBitsetFile,
safeFilename,
listFilesIDB,
listFilesFS,
} = require('./files')
module.exports = function (log, indexesPath) {
debug('indexes path', indexesPath)
let bitsetCache = new WeakMap()
let sortedCache = { ascending: new WeakMap(), descending: new WeakMap() }
let cacheOffset = -1
const status = Status()
const indexes = {}
let isReady = false
let waiting = []
loadIndexes(() => {
debug('loaded indexes', Object.keys(indexes))
if (!indexes['seq']) {
indexes['seq'] = {
offset: -1,
count: 0,
tarr: new Uint32Array(16 * 1000),
}
}
if (!indexes['timestamp']) {
indexes['timestamp'] = {
offset: -1,
count: 0,
tarr: new Float64Array(16 * 1000),
}
}
if (!indexes['sequence']) {
indexes['sequence'] = {
offset: -1,
count: 0,
tarr: new Uint32Array(16 * 1000),
}
}
status.batchUpdate(indexes, ['seq', 'timestamp', 'sequence'])
isReady = true
for (let i = 0; i < waiting.length; ++i) waiting[i]()
waiting = []
})
function onReady(cb) {
if (isReady) cb()
else waiting.push(cb)
}
const bTimestamp = Buffer.from('timestamp')
const bSequence = Buffer.from('sequence')
const bValue = Buffer.from('value')
// FIXME: handle the errors in these callbacks
function loadIndexes(cb) {
function parseIndexes(err, files) {
push(
push.values(files),
push.asyncMap((file, cb) => {
const indexName = path.parse(file).name
if (file === 'seq.index') {
loadTypedArrayFile(
path.join(indexesPath, file),
Uint32Array,
(e, idx) => {
indexes[indexName] = idx
cb()
}
)
} else if (file === 'timestamp.index') {
loadTypedArrayFile(
path.join(indexesPath, file),
Float64Array,
(e, idx) => {
indexes[indexName] = idx
cb()
}
)
} else if (file === 'sequence.index') {
loadTypedArrayFile(
path.join(indexesPath, file),
Uint32Array,
(e, idx) => {
indexes[indexName] = idx
cb()
}
)
} else if (file.endsWith('.32prefix')) {
// Don't load it yet, just tag it `lazy`
indexes[indexName] = {
offset: -1,
count: 0,
tarr: new Uint32Array(16 * 1000),
lazy: true,
prefix: 32,
filepath: path.join(indexesPath, file),
}
cb()
} else if (file.endsWith('.32prefixmap')) {
// Don't load it yet, just tag it `lazy`
indexes[indexName] = {
offset: -1,
count: 0,
map: {},
lazy: true,
prefix: 32,
filepath: path.join(indexesPath, file),
}
cb()
} else if (file.endsWith('.index')) {
// Don't load it yet, just tag it `lazy`
indexes[indexName] = {
offset: 0,
bitset: new TypedFastBitSet(),
lazy: true,
filepath: path.join(indexesPath, file),
}
cb()
} else cb()
}),
push.collect(cb)
)
}
if (typeof window !== 'undefined') {
// browser
listFilesIDB(indexesPath, parseIndexes)
} else {
// node.js
listFilesFS(indexesPath, parseIndexes)
}
}
function updateCacheWithLog() {
if (log.since.value > cacheOffset) {
cacheOffset = log.since.value
bitsetCache = new WeakMap()
sortedCache.ascending = new WeakMap()
sortedCache.descending = new WeakMap()
}
}
function saveCoreIndex(name, coreIndex, count) {
if (coreIndex.offset < 0) return
debug('saving core index: %s', name)
const filename = path.join(indexesPath, name + '.index')
saveTypedArrayFile(
filename,
coreIndex.version || 1,
coreIndex.offset,
count,
coreIndex.tarr
)
}
function saveIndex(name, index, cb) {
if (index.offset < 0 || index.bitset.size() === 0) return
debug('saving index: %s', name)
const filename = path.join(indexesPath, name + '.index')
saveBitsetFile(filename, index.version || 1, index.offset, index.bitset, cb)
}
function savePrefixIndex(name, prefixIndex, count, cb) {
if (prefixIndex.offset < 0) return
debug('saving prefix index: %s', name)
const num = prefixIndex.prefix
const filename = path.join(indexesPath, name + `.${num}prefix`)
saveTypedArrayFile(
filename,
prefixIndex.version || 1,
prefixIndex.offset,
count,
prefixIndex.tarr,
cb
)
}
function savePrefixMapIndex(name, prefixIndex, count, cb) {
if (prefixIndex.offset < 0) return
debug('saving prefix map index: %s', name)
const num = prefixIndex.prefix
const filename = path.join(indexesPath, name + `.${num}prefixmap`)
savePrefixMapFile(
filename,
prefixIndex.version || 1,
prefixIndex.offset,
count,
prefixIndex.map,
cb
)
}
function growTarrIndex(index, Type) {
debug('growing index')
const newArray = new Type(index.tarr.length * 2)
newArray.set(index.tarr)
index.tarr = newArray
}
function updateSeqIndex(seq, offset) {
if (seq > indexes['seq'].count - 1) {
if (seq > indexes['seq'].tarr.length - 1) {
growTarrIndex(indexes['seq'], Uint32Array)
}
indexes['seq'].offset = offset
indexes['seq'].tarr[seq] = offset
indexes['seq'].count = seq + 1
return true
}
}
function updateTimestampIndex(seq, offset, buffer) {
if (seq > indexes['timestamp'].count - 1) {
if (seq > indexes['timestamp'].tarr.length - 1)
growTarrIndex(indexes['timestamp'], Float64Array)
indexes['timestamp'].offset = offset
var p = 0 // note you pass in p!
p = bipf.seekKey(buffer, p, bTimestamp)
const arrivalTimestamp = bipf.decode(buffer, p)
p = 0
p = bipf.seekKey(buffer, p, bValue)
p = bipf.seekKey(buffer, p, bTimestamp)
const declaredTimestamp = bipf.decode(buffer, p)
const timestamp = Math.min(arrivalTimestamp, declaredTimestamp)
indexes['timestamp'].tarr[seq] = timestamp
indexes['timestamp'].count = seq + 1
return true
}
}
function updateSequenceIndex(seq, offset, buffer) {
if (seq > indexes['sequence'].count - 1) {
if (seq > indexes['sequence'].tarr.length - 1)
growTarrIndex(indexes['sequence'], Uint32Array)
indexes['sequence'].offset = offset
var p = 0 // note you pass in p!
p = bipf.seekKey(buffer, p, bValue)
p = bipf.seekKey(buffer, p, bSequence)
indexes['sequence'].tarr[seq] = bipf.decode(buffer, p)
indexes['sequence'].count = seq + 1
return true
}
}
function checkEqual(opData, buffer) {
const fieldStart = opData.seek(buffer)
if (!opData.value) return fieldStart === -1
else if (
~fieldStart &&
bipf.compareString(buffer, fieldStart, opData.value) === 0
)
return true
else return false
}
function checkIncludes(opData, buffer) {
const fieldStart = opData.seek(buffer)
if (!~fieldStart) return false
const type = bipf.getEncodedType(buffer, fieldStart)
if (type === bipf.types.string) {
return checkEqual(opData, buffer)
} else if (type === bipf.types.array) {
let found = false
bipf.iterate(buffer, fieldStart, (_, itemStart) => {
const valueStart = opData.pluck
? opData.pluck(buffer, itemStart)
: itemStart
if (bipf.compareString(buffer, valueStart, opData.value) === 0) {
found = true
return true // abort the bipf.iterate
}
})
return found
} else {
return false
}
}
function safeReadUint32(buf, prefixOffset = 0) {
if (buf.length < 4) {
const bigger = Buffer.alloc(4)
buf.copy(bigger)
return bigger.readUInt32LE(0)
} else if (buf.length === 4) {
return buf.readUInt32LE(0)
} else {
return buf.readUInt32LE(prefixOffset)
}
}
function addToPrefixMap(map, seq, prefix) {
if (prefix === 0) return
const arr = map[prefix] || (map[prefix] = [])
arr.push(seq)
}
function updatePrefixMapIndex(opData, index, buffer, seq, offset) {
if (seq > index.count - 1) {
const fieldStart = opData.seek(buffer)
if (~fieldStart) {
const buf = bipf.slice(buffer, fieldStart)
if (buf.length) {
const prefix = safeReadUint32(buf, opData.prefixOffset)
addToPrefixMap(index.map, seq, prefix)
}
}
index.offset = offset
index.count = seq + 1
}
}
function updatePrefixIndex(opData, index, buffer, seq, offset) {
if (seq > index.count - 1) {
if (seq > index.tarr.length - 1) growTarrIndex(index, Uint32Array)
const fieldStart = opData.seek(buffer)
if (~fieldStart) {
const buf = bipf.slice(buffer, fieldStart)
index.tarr[seq] = buf.length
? safeReadUint32(buf, opData.prefixOffset)
: 0
} else {
index.tarr[seq] = 0
}
index.offset = offset
index.count = seq + 1
}
}
function updateIndexValue(op, index, buffer, seq) {
if (op.type === 'EQUAL' && checkEqual(op.data, buffer))
index.bitset.add(seq)
else if (op.type === 'INCLUDES' && checkIncludes(op.data, buffer))
index.bitset.add(seq)
}
function updateAllIndexValue(opData, newIndexes, buffer, seq) {
const fieldStart = opData.seek(buffer)
const value = bipf.decode(buffer, fieldStart)
const indexName = safeFilename(opData.indexType + '_' + value)
if (!newIndexes[indexName]) {
newIndexes[indexName] = {
offset: 0,
bitset: new TypedFastBitSet(),
}
}
newIndexes[indexName].bitset.add(seq)
}
// concurrent index helpers
function onlyOneIndexAtATime(waitingMap, indexName, cb) {
if (waitingMap.has(indexName)) {
waitingMap.get(indexName).push(cb)
return true // wait for other index update
} else waitingMap.set(indexName, [])
}
function runWaitingIndexLoadCbs(waitingMap, indexName) {
waitingMap.get(indexName).forEach((cb) => cb())
waitingMap.delete(indexName)
}
// concurrent index update
const waitingIndexUpdate = new Map()
function updateIndex(op, cb) {
const index = indexes[op.data.indexName]
const indexNamesForStatus = [
'seq',
'timestamp',
'sequence',
op.data.indexName,
]
const waitingKey = op.data.indexName
if (onlyOneIndexAtATime(waitingIndexUpdate, waitingKey, cb)) return
// find the next possible seq
let seq = 0
if (index.offset !== -1) {
const { tarr } = indexes['seq']
const indexOffset = index.offset
for (const len = tarr.length; seq < len; ++seq)
if (tarr[seq] === indexOffset) {
seq++
break
}
}
let updatedSeqIndex = false
let updatedTimestampIndex = false
let updatedSequenceIndex = false
const startSeq = seq
const start = Date.now()
let lastSaved = start
const indexNeedsUpdate =
op.data.indexName !== 'sequence' &&
op.data.indexName !== 'timestamp' &&
op.data.indexName !== 'seq'
function save(count, offset) {
if (updatedSeqIndex) saveCoreIndex('seq', indexes['seq'], count)
if (updatedTimestampIndex)
saveCoreIndex('timestamp', indexes['timestamp'], count)
if (updatedSequenceIndex)
saveCoreIndex('sequence', indexes['sequence'], count)
index.offset = offset
if (indexNeedsUpdate) {
if (index.prefix && index.map)
savePrefixMapIndex(op.data.indexName, index, count)
else if (index.prefix) savePrefixIndex(op.data.indexName, index, count)
else saveIndex(op.data.indexName, index)
}
}
const logstreamId = Math.ceil(Math.random() * 1000)
debug(`log.stream #${logstreamId} started, to update index ${waitingKey}`)
log.stream({ gt: index.offset }).pipe({
paused: false,
write: function (record) {
const offset = record.offset
const buffer = record.value
if (updateSeqIndex(seq, offset)) updatedSeqIndex = true
if (!buffer) {
// deleted
seq++
return
}
if (updateTimestampIndex(seq, offset, buffer))
updatedTimestampIndex = true
if (updateSequenceIndex(seq, offset, buffer))
updatedSequenceIndex = true
if (indexNeedsUpdate) {
if (op.data.prefix && op.data.useMap)
updatePrefixMapIndex(op.data, index, buffer, seq, offset)
else if (op.data.prefix)
updatePrefixIndex(op.data, index, buffer, seq, offset)
else updateIndexValue(op, index, buffer, seq)
}
if (seq % 1000 === 0) {
status.batchUpdate(indexes, indexNamesForStatus)
const now = Date.now()
if (now - lastSaved >= 60e3) {
lastSaved = now
save(seq, offset)
}
}
seq++
},
end: () => {
const count = seq // incremented at end
debug(
`log.stream #${logstreamId} done ${seq - startSeq} records in ${
Date.now() - start
}ms`
)
save(count, indexes['seq'].offset)
status.batchUpdate(indexes, indexNamesForStatus)
runWaitingIndexLoadCbs(waitingIndexUpdate, waitingKey)
cb()
},
})
}
// concurrent index create
const waitingIndexCreate = new Map()
function createIndexes(opsMissingIndexes, cb) {
const newIndexes = {}
const coreIndexNames = ['seq', 'timestamp', 'sequence']
const newIndexNames = opsMissingIndexes.map((op) => op.data.indexName)
const waitingKey = newIndexNames.join('|')
if (onlyOneIndexAtATime(waitingIndexCreate, waitingKey, cb)) return
opsMissingIndexes.forEach((op) => {
if (op.data.prefix && op.data.useMap) {
newIndexes[op.data.indexName] = {
offset: 0,
count: 0,
map: {},
prefix: typeof op.data.prefix === 'number' ? op.data.prefix : 32,
}
} else if (op.data.prefix)
newIndexes[op.data.indexName] = {
offset: 0,
count: 0,
tarr: new Uint32Array(16 * 1000),
prefix: typeof op.data.prefix === 'number' ? op.data.prefix : 32,
}
else
newIndexes[op.data.indexName] = {
offset: 0,
bitset: new TypedFastBitSet(),
}
})
let seq = 0
let updatedSeqIndex = false
let updatedTimestampIndex = false
let updatedSequenceIndex = false
const start = Date.now()
let lastSaved = start
function save(count, offset, done) {
if (updatedSeqIndex) saveCoreIndex('seq', indexes['seq'], count)
if (updatedTimestampIndex)
saveCoreIndex('timestamp', indexes['timestamp'], count)
if (updatedSequenceIndex)
saveCoreIndex('sequence', indexes['sequence'], count)
for (var indexName in newIndexes) {
const index = newIndexes[indexName]
if (done) indexes[indexName] = index
index.offset = offset
if (index.prefix && index.map)
savePrefixMapIndex(indexName, index, count)
else if (index.prefix) savePrefixIndex(indexName, index, count)
else saveIndex(indexName, index)
}
}
const logstreamId = Math.ceil(Math.random() * 1000)
debug(`log.stream #${logstreamId} started, to create indexes ${waitingKey}`)
log.stream({}).pipe({
paused: false,
write: function (record) {
const offset = record.offset
const buffer = record.value
if (updateSeqIndex(seq, offset)) updatedSeqIndex = true
if (!buffer) {
// deleted
seq++
return
}
if (updateTimestampIndex(seq, offset, buffer))
updatedTimestampIndex = true
if (updateSequenceIndex(seq, offset, buffer))
updatedSequenceIndex = true
opsMissingIndexes.forEach((op) => {
if (op.data.prefix && op.data.useMap)
updatePrefixMapIndex(
op.data,
newIndexes[op.data.indexName],
buffer,
seq,
offset
)
if (op.data.prefix)
updatePrefixIndex(
op.data,
newIndexes[op.data.indexName],
buffer,
seq,
offset
)
else if (op.data.indexAll)
updateAllIndexValue(op.data, newIndexes, buffer, seq)
else updateIndexValue(op, newIndexes[op.data.indexName], buffer, seq)
})
if (seq % 1000 === 0) {
status.batchUpdate(indexes, coreIndexNames)
status.batchUpdate(newIndexes, newIndexNames)
const now = Date.now()
if (now - lastSaved >= 60e3) {
lastSaved = now
save(seq, offset, false)
}
}
seq++
},
end: () => {
const count = seq // incremented at end
debug(
`log.stream #${logstreamId} done ${count} records in ${
Date.now() - start
}ms`
)
save(count, indexes['seq'].offset, true)
status.batchUpdate(indexes, coreIndexNames)
status.batchUpdate(newIndexes, newIndexNames)
runWaitingIndexLoadCbs(waitingIndexCreate, waitingKey)
cb()
},
})
}
// concurrent index load
const waitingIndexLoad = new Map()
function loadLazyIndex(indexName, cb) {
if (onlyOneIndexAtATime(waitingIndexLoad, indexName, cb)) return
debug('lazy loading %s', indexName)
let index = indexes[indexName]
if (index.prefix && index.map) {
loadPrefixMapFile(index.filepath, (err, data) => {
if (err) return cb(err)
const { version, offset, count, map } = data
index.version = version
index.offset = offset
index.count = count
index.map = map
index.lazy = false
runWaitingIndexLoadCbs(waitingIndexLoad, indexName)
cb()
})
} else if (index.prefix) {
loadTypedArrayFile(index.filepath, Uint32Array, (err, data) => {
if (err) return cb(err)
const { version, offset, count, tarr } = data
index.version = version
index.offset = offset
index.count = count
index.tarr = tarr
index.lazy = false
runWaitingIndexLoadCbs(waitingIndexLoad, indexName)
cb()
})
} else {
loadBitsetFile(index.filepath, (err, data) => {
if (err) return cb(err)
const { version, offset, bitset } = data
index.version = version
index.offset = offset
index.bitset = bitset
index.lazy = false
runWaitingIndexLoadCbs(waitingIndexLoad, indexName)
cb()
})
}
}
function loadLazyIndexes(indexNames, cb) {
push(
push.values(indexNames),
push.asyncMap(loadLazyIndex),
push.collect(cb)
)
}
function ensureIndexSync(op, cb) {
if (log.since.value > indexes[op.data.indexName].offset) {
updateIndex(op, cb)
} else {
debug('ensureIndexSync %s is already synced', op.data.indexName)
cb()
}
}
function ensureSeqIndexSync(cb) {
ensureIndexSync({ data: { indexName: 'seq' } }, cb)
}
function filterIndex(op, filterCheck, cb) {
ensureIndexSync(op, () => {
if (op.data.indexName === 'sequence') {
const bitset = new TypedFastBitSet()
const { tarr, count } = indexes['sequence']
for (let seq = 0; seq < count; ++seq) {
if (filterCheck(tarr[seq], op)) bitset.add(seq)
}
cb(bitset)
} else if (op.data.indexName === 'timestamp') {
const bitset = new TypedFastBitSet()
const { tarr, count } = indexes['timestamp']
for (let seq = 0; seq < count; ++seq) {
if (filterCheck(tarr[seq], op)) bitset.add(seq)
}
cb(bitset)
} else {
debug('filterIndex() is unsupported for %s', op.data.indexName)
}
})
}
function getFullBitset(cb) {
ensureIndexSync({ data: { indexName: 'sequence' } }, () => {
const bitset = new TypedFastBitSet()
const { count } = indexes['sequence']
bitset.addRange(0, count)
cb(bitset)
})
}
function getOffsetsBitset(opOffsets, cb) {
const seqs = []
opOffsets.sort((x, y) => x - y)
const opOffsetsLen = opOffsets.length
const { tarr } = indexes['seq']
for (let seq = 0, len = tarr.length; seq < len; ++seq) {
if (bsb.eq(opOffsets, tarr[seq]) !== -1) seqs.push(seq)
if (seqs.length === opOffsetsLen) break
}
cb(new TypedFastBitSet(seqs))
}
function matchAgainstPrefix(op, prefixIndex, cb) {
const target = op.data.value
const targetPrefix = target
? safeReadUint32(target, op.data.prefixOffset)
: 0
const bitset = new TypedFastBitSet()
const bitsetFilters = new Map()
const seek = op.data.seek
function checker(value) {
if (!value) return false // deleted
const fieldStart = seek(value)
const candidate = bipf.slice(value, fieldStart)
if (target) {
if (Buffer.compare(candidate, target)) return false
} else {
if (~fieldStart) return false
}
return true
}
if (prefixIndex.map) {
if (prefixIndex.map[targetPrefix]) {
prefixIndex.map[targetPrefix].forEach((seq) => {
bitset.add(seq)
bitsetFilters.set(seq, [checker])
})
}
} else {
const count = prefixIndex.count
const tarr = prefixIndex.tarr
for (let seq = 0; seq < count; ++seq) {
if (tarr[seq] === targetPrefix) {
bitset.add(seq)
bitsetFilters.set(seq, [checker])
}
}
}
cb(bitset, bitsetFilters)
}
function nestLargeOpsArray(ops, type) {
let op = ops[0]
ops.slice(1).forEach((rest) => {
op = {
type,
data: [op, rest],
}
})
return op
}
function getNameFromOperation(op) {
if (op.type === 'EQUAL' || op.type === 'INCLUDES') {
const value = op.data.value
? op.data.value.toString().substring(0, 10)
: ''
return `${op.data.indexType}(${value})`
} else if (
op.type === 'GT' ||
op.type === 'GTE' ||
op.type === 'LT' ||
op.type === 'LTE'
) {
const value = op.data.value
? op.data.value.toString().substring(0, 10)
: ''
return `${op.type}(${value})`
} else if (op.type === 'SEQS') {
return `SEQS(${op.seqs.toString().substring(0, 10)})`
} else if (op.type === 'OFFSETS') {
return `OFFSETS(${op.offsets.toString().substring(0, 10)})`
} else if (op.type === 'LIVESEQS') {
return `LIVESEQS()`
} else if (op.type === 'AND') {
if (op.data.length > 2) op = nestLargeOpsArray(op.data, 'AND')
const op1name = getNameFromOperation(op.data[0])
const op2name = getNameFromOperation(op.data[1])
if (!op1name) return op2name
if (!op2name) return op1name
return `AND(${op1name},${op2name})`
} else if (op.type === 'OR') {
if (op.data.length > 2) op = nestLargeOpsArray(op.data, 'AND')
const op1name = getNameFromOperation(op.data[0])
const op2name = getNameFromOperation(op.data[1])
if (!op1name) return op2name
if (!op2name) return op1name
return `OR(${op1name},${op2name})`
} else if (op.type === 'NOT') {
return `NOT(${getNameFromOperation(op.data[0])})`
} else {
return '*'
}
}
function mergeFilters(filters1, filters2) {
if (!filters1 && !filters2) return null
else if (filters1 && !filters2) return filters1
else if (!filters1 && filters2) return filters2
else {
const filters = new Map(filters1)
for (let seq of filters2.keys()) {
const f1 = filters1.get(seq) || []
const f2 = filters2.get(seq)
filters.set(seq, [...f1, ...f2])
}
return filters
}
}
function getBitsetForOperation(op, cb) {
if (op.type === 'EQUAL' || op.type === 'INCLUDES') {
if (op.data.prefix) {
ensureIndexSync(op, () => {
matchAgainstPrefix(op, indexes[op.data.indexName], cb)
})
} else {
ensureIndexSync(op, () => {
cb(indexes[op.data.indexName].bitset)
})
}
} else if (op.type === 'GT') {
filterIndex(op, (num, op) => num > op.data.value, cb)
} else if (op.type === 'GTE') {
filterIndex(op, (num, op) => num >= op.data.value, cb)
} else if (op.type === 'LT') {
filterIndex(op, (num, op) => num < op.data.value, cb)
} else if (op.type === 'LTE') {
filterIndex(op, (num, op) => num <= op.data.value, cb)
} else if (op.type === 'OFFSETS') {
ensureSeqIndexSync(() => {
getOffsetsBitset(op.offsets, cb)
})
} else if (op.type === 'SEQS') {
ensureSeqIndexSync(() => {
cb(new TypedFastBitSet(op.seqs))
})
} else if (op.type === 'LIVESEQS') {
cb(new TypedFastBitSet())
} else if (op.type === 'AND') {
if (op.data.length > 2) op = nestLargeOpsArray(op.data, 'AND')
getBitsetForOperation(op.data[0], (op1, filters1) => {
getBitsetForOperation(op.data[1], (op2, filters2) => {
cb(op1.new_intersection(op2), mergeFilters(filters1, filters2))
})
})
} else if (op.type === 'OR') {
if (op.data.length > 2) op = nestLargeOpsArray(op.data, 'OR')
getBitsetForOperation(op.data[0], (op1, filters1) => {
getBitsetForOperation(op.data[1], (op2, filters2) => {
cb(op1.new_union(op2), mergeFilters(filters1, filters2))
})
})
} else if (op.type === 'NOT') {
getBitsetForOperation(op.data[0], (op1, filters) => {
getFullBitset((fullBitset) => {
cb(fullBitset.difference(op1), filters)
})
})
} else if (!op.type) {
// to support `query(fromDB(jitdb), toCallback(cb))`
getFullBitset(cb)
} else console.error('Unknown type', op)
}
function executeOperation(operation, cb) {
updateCacheWithLog()
if (bitsetCache.has(operation)) return cb(...bitsetCache.get(operation))
const opsMissingIndexes = []
const lazyIndexes = []
function detectMissingAndLazyIndexes(ops) {
ops.forEach((op) => {
if (op.type === 'EQUAL' || op.type === 'INCLUDES') {
const indexName = op.data.indexName
if (!indexes[indexName]) opsMissingIndexes.push(op)
else if (indexes[indexName].lazy) lazyIndexes.push(indexName)
} else if (op.type === 'AND' || op.type === 'OR' || op.type === 'NOT')
detectMissingAndLazyIndexes(op.data)
else if (
op.type === 'SEQS' ||
op.type === 'LIVESEQS' ||
op.type === 'OFFSETS' ||
op.type === 'LT' ||
op.type === 'LTE' ||
op.type === 'GT' ||
op.type === 'GTE' ||
!op.type // e.g. query(fromDB, toCallback), or empty deferred()
);
else debug('Unknown operator type: ' + op.type)
})
}
function getBitset() {
getBitsetForOperation(operation, (bitset, filters) => {
bitsetCache.set(operation, [bitset, filters])
cb(bitset, filters)
})
}
function createMissingIndexes() {
if (opsMissingIndexes.length > 0)
createIndexes(opsMissingIndexes, getBitset)
else getBitset()
}
detectMissingAndLazyIndexes([operation])
ensureSeqIndexSync(() => {
if (opsMissingIndexes.length > 0)
debug('missing indexes: %o', opsMissingIndexes)
if (lazyIndexes.length > 0)
loadLazyIndexes(lazyIndexes, createMissingIndexes)