-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
1667 lines (1483 loc) · 48.9 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
// SPDX-FileCopyrightText: 2021 Anders Rune Jensen
//
// SPDX-License-Identifier: LGPL-3.0-only
const path = require('path')
const bipf = require('bipf')
const push = require('push-stream')
const pull = require('pull-stream')
const mutexify = require('mutexify')
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 Obv = require('obz')
const debug = require('debug')('jitdb')
const debugQuery = debug.extend('query')
const Status = require('./status')
const {
saveTypedArrayFile,
loadTypedArrayFile,
savePrefixMapFile,
loadPrefixMapFile,
saveBitsetFile,
loadBitsetFile,
safeFilename,
listFiles,
EmptyFile,
} = require('./files')
module.exports = function (log, indexesPath) {
debug('indexes path', indexesPath)
let bitsetCache = new WeakMap()
let sortedTSCache = { ascending: new WeakMap(), descending: new WeakMap() }
let sortedSeqCache = { ascending: new WeakMap(), descending: new WeakMap() }
let cacheOffset = -1
const status = Status()
const indexes = new Map() // indexName (string) -> Index (object)
let seqIndex
let timestampIndex
let sequenceIndex
let isReady = false
const waitingReady = new Set()
let compacting = false
let compactStartOffset = null
const postCompactReindexPath = path.join(indexesPath, 'post-compact-reindex')
const waitingCompaction = new Set()
const coreIndexNames = ['seq', 'timestamp', 'sequence']
const indexingActive = Obv().set(0)
const queriesActive = Obv().set(0)
loadIndexes(() => {
debug('loaded indexes', [...indexes.keys()])
if (!indexes.has('seq')) {
indexes.set('seq', {
offset: -1,
count: 0,
tarr: new Uint32Array(16 * 1000),
version: 1,
})
}
if (!indexes.has('timestamp')) {
indexes.set('timestamp', {
offset: -1,
count: 0,
tarr: new Float64Array(16 * 1000),
version: 1,
})
}
if (!indexes.has('sequence')) {
indexes.set('sequence', {
offset: -1,
count: 0,
tarr: new Uint32Array(16 * 1000),
version: 1,
})
}
seqIndex = indexes.get('seq')
timestampIndex = indexes.get('timestamp')
sequenceIndex = indexes.get('sequence')
status.update(indexes, coreIndexNames)
isReady = true
for (const cb of waitingReady) cb()
waitingReady.clear()
})
function onReady(cb) {
if (isReady) cb()
else waitingReady.add(cb)
}
log.compactionProgress((stats) => {
if (typeof stats.startOffset === 'number' && compactStartOffset === null) {
compactStartOffset = stats.startOffset
}
if (!stats.done && !compacting) {
compacting = true
EmptyFile.create(postCompactReindexPath)
} else if (stats.done && compacting) {
compacting = false
const offset = compactStartOffset || 0
compactStartOffset = null
if (stats.sizeDiff > 0) {
EmptyFile.exists(postCompactReindexPath, (err, exists) => {
if (exists) {
reindex(offset, (err) => {
if (err) console.error('reindex jitdb after compact', err)
conclude()
})
} else {
conclude()
}
})
} else {
conclude()
}
function conclude() {
EmptyFile.delete(postCompactReindexPath, () => {
if (waitingCompaction.size === 0) return
for (const cb of waitingCompaction) cb()
waitingCompaction.clear()
})
}
}
})
const BIPF_TIMESTAMP = bipf.allocAndEncode('timestamp')
const BIPF_SEQUENCE = bipf.allocAndEncode('sequence')
const BIPF_VALUE = bipf.allocAndEncode('value')
const BIPF_KEY = bipf.allocAndEncode('key')
function loadIndexes(cb) {
listFiles(indexesPath, 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,
(err, idx) => {
if (!err) indexes.set(indexName, idx)
cb()
}
)
} else if (file === 'timestamp.index') {
loadTypedArrayFile(
path.join(indexesPath, file),
Float64Array,
(err, idx) => {
if (!err) indexes.set(indexName, idx)
cb()
}
)
} else if (file === 'sequence.index') {
loadTypedArrayFile(
path.join(indexesPath, file),
Uint32Array,
(err, idx) => {
if (!err) indexes.set(indexName, idx)
cb()
}
)
} else if (file.endsWith('.32prefix')) {
// Don't load it yet, just tag it `lazy`
indexes.set(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.set(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.set(indexName, {
offset: 0,
bitset: new TypedFastBitSet(),
lazy: true,
filepath: path.join(indexesPath, file),
})
cb()
} else cb()
}),
push.drain(null, cb)
)
})
}
function clearCache() {
bitsetCache = new WeakMap()
sortedTSCache.ascending = new WeakMap()
sortedTSCache.descending = new WeakMap()
sortedSeqCache.ascending = new WeakMap()
sortedSeqCache.descending = new WeakMap()
}
function updateCacheWithLog() {
if (log.since.value > cacheOffset) {
cacheOffset = log.since.value
clearCache()
}
}
function saveCoreIndex(name, coreIndex, count, cb) {
if (coreIndex.offset < 0) return
debug('saving core index: %s', name)
const filename = path.join(indexesPath, name + '.index')
saveTypedArrayFile(
filename,
coreIndex.version,
coreIndex.offset,
count,
coreIndex.tarr,
cb
)
}
function saveIndex(name, index, count, cb) {
if (index.prefix && index.map) savePrefixMapIndex(name, index, count, cb)
else if (index.prefix) savePrefixIndex(name, index, count, cb)
else saveBitsetIndex(name, index, cb)
}
function saveBitsetIndex(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, 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,
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,
prefixIndex.offset,
count,
prefixIndex.map,
cb
)
}
function growTarrIndex(index, Type) {
debug('growing index %s', index.name)
const newArray = new Type(index.tarr.length * 2)
newArray.set(index.tarr)
index.tarr = newArray
}
function updateSeqIndex(seq, offset) {
if (seq > seqIndex.count - 1) {
if (seq > seqIndex.tarr.length - 1) {
growTarrIndex(seqIndex, Uint32Array)
}
seqIndex.tarr[seq] = offset
seqIndex.offset = offset
seqIndex.count = seq + 1
return true
}
}
function seekMinTimestamp(buffer, pValue) {
const pTimestamp = bipf.seekKey2(buffer, 0, BIPF_TIMESTAMP, 0)
const arrivalTimestamp = bipf.decode(buffer, pTimestamp)
const pValueTimestamp = bipf.seekKey2(buffer, pValue, BIPF_TIMESTAMP, 0)
const declaredTimestamp = bipf.decode(buffer, pValueTimestamp)
return Math.min(arrivalTimestamp, declaredTimestamp)
}
function seekSequence(buffer, pValue) {
const pValueSequence = bipf.seekKey2(buffer, pValue, BIPF_SEQUENCE, 0)
return bipf.decode(buffer, pValueSequence)
}
function updateTimestampIndex(seq, offset, buffer, pValue) {
if (seq > timestampIndex.count - 1) {
if (seq > timestampIndex.tarr.length - 1) {
growTarrIndex(timestampIndex, Float64Array)
}
timestampIndex.tarr[seq] = seekMinTimestamp(buffer, pValue)
timestampIndex.offset = offset
timestampIndex.count = seq + 1
return true
}
}
function updateSequenceIndex(seq, offset, buffer, pValue) {
if (seq > sequenceIndex.count - 1) {
if (seq > sequenceIndex.tarr.length - 1) {
growTarrIndex(sequenceIndex, Uint32Array)
}
sequenceIndex.tarr[seq] = seekSequence(buffer, pValue)
sequenceIndex.offset = offset
sequenceIndex.count = seq + 1
return true
}
}
function getSeqFromOffset(offset) {
if (offset === -1) return -1
const { tarr, count } = seqIndex
if (tarr[count - 1] === offset) return count - 1
const seq = bsb.eq(tarr, offset, 0, count - 1)
if (seq < 0) return 0
return seq
}
const undefinedBipf = bipf.allocAndEncode(undefined)
function checkEqual(opData, buffer, pValue) {
const fieldStart = opData.seek(buffer, 0, pValue)
if (fieldStart === -1 && opData.value.equals(undefinedBipf)) return true
else return bipf.compare(buffer, fieldStart, opData.value, 0) === 0
}
function compareWithRangeOp(op, value) {
if (op.type === 'GT') return value > op.data.value
else if (op.type === 'GTE') return value >= op.data.value
else if (op.type === 'LT') return value < op.data.value
else if (op.type === 'LTE') return value <= op.data.value
else {
console.warn('Unknown op type: ' + op.type)
return true
}
}
function checkComparison(op, buffer) {
const pValue = bipf.seekKey2(buffer, 0, BIPF_VALUE, 0)
if (op.data.indexName === 'timestamp') {
const timestamp = seekMinTimestamp(buffer, pValue)
return compareWithRangeOp(op, timestamp)
} else if (op.data.indexName === 'sequence') {
const sequence = seekSequence(buffer, pValue)
return compareWithRangeOp(op, sequence)
} else {
console.warn(
`Attempted to do a ${op.type} comparison on unsupported index ${op.data.indexName}`
)
return true
}
}
function checkPredicate(opData, buffer, pValue) {
const fieldStart = opData.seek(buffer, 0, pValue)
const predicateFn = opData.value
if (fieldStart < 0) return false
const fieldValue = bipf.decode(buffer, fieldStart)
return predicateFn(fieldValue)
}
function checkAbsent(opData, buffer, pValue) {
const fieldStart = opData.seek(buffer, 0, pValue)
return fieldStart < 0
}
function checkIncludes(opData, buffer, pValue) {
const fieldStart = opData.seek(buffer, 0, pValue)
if (!~fieldStart) return false
const type = bipf.getEncodedType(buffer, fieldStart)
if (type === bipf.types.array) {
let found = false
bipf.iterate(buffer, fieldStart, (_, itemStart) => {
const valueStart = opData.pluck
? opData.pluck(buffer, itemStart)
: itemStart
if (bipf.compare(buffer, valueStart, opData.value, 0) === 0) {
found = true
return true // abort the bipf.iterate
}
})
return found
} else return checkEqual(opData, buffer, pValue)
}
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, pValue) {
if (seq > index.count - 1) {
const fieldStart = opData.seek(buffer, 0, pValue)
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, pValue) {
if (seq > index.count - 1) {
if (seq > index.tarr.length - 1) growTarrIndex(index, Uint32Array)
const fieldStart = opData.seek(buffer, 0, pValue)
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, pValue) {
if (op.type === 'EQUAL' && checkEqual(op.data, buffer, pValue))
index.bitset.add(seq)
else if (op.type === 'PREDICATE' && checkPredicate(op.data, buffer, pValue))
index.bitset.add(seq)
else if (op.type === 'ABSENT' && checkAbsent(op.data, buffer, pValue))
index.bitset.add(seq)
else if (op.type === 'INCLUDES' && checkIncludes(op.data, buffer, pValue))
index.bitset.add(seq)
}
function updateAllIndexValue(opData, newIndexes, buffer, seq, pValue) {
const fieldStart = opData.seek(buffer, 0, pValue)
const value = bipf.decode(buffer, fieldStart)
const indexName = safeFilename(opData.indexType + '_' + value)
if (!newIndexes.has(indexName)) {
newIndexes.set(indexName, {
offset: 0,
bitset: new TypedFastBitSet(),
version: opData.version || 1,
})
}
newIndexes.get(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)
}
const updateIndexesLock = mutexify()
function updateIndexes(ops, cb) {
updateIndexesLock(function onUpdateIndexesLockReleased(unlock) {
const oldOps = ops
.filter((op) => indexes.has(op.data.indexName))
.map((op) => {
if (coreIndexNames.includes(op.data.indexName)) op.isCore = true
return op
})
const newOps = ops.filter((op) => !indexes.has(op.data.indexName))
const oldIndexNames = oldOps.map((op) => op.data.indexName)
const newIndexNames = newOps.map((op) => op.data.indexName)
const indexNamesForStatus = [...coreIndexNames, ...oldIndexNames]
// Reset old index if version was bumped
for (const op of oldOps) {
const index = indexes.get(op.data.indexName)
if (op.data.version > index.version) {
index.offset = -1
index.count = 0
}
}
// Prepare new indexes
const newIndexes = new Map()
for (const op of newOps) {
if (op.data.prefix && op.data.useMap)
newIndexes.set(op.data.indexName, {
offset: 0,
count: 0,
map: {},
prefix: typeof op.data.prefix === 'number' ? op.data.prefix : 32,
version: op.data.version || 1,
})
else if (op.data.prefix)
newIndexes.set(op.data.indexName, {
offset: 0,
count: 0,
tarr: new Uint32Array(16 * 1000),
prefix: typeof op.data.prefix === 'number' ? op.data.prefix : 32,
version: op.data.version || 1,
})
else
newIndexes.set(op.data.indexName, {
offset: 0,
bitset: new TypedFastBitSet(),
version: op.data.version || 1,
})
}
const latestOffset =
newOps.length > 0
? -1
: Math.min(...oldIndexNames.map((name) => indexes.get(name).offset))
if (latestOffset === log.since.value && latestOffset >= 0) {
unlock(cb)
return
}
let seq = getSeqFromOffset(latestOffset) + 1
let updatedSeqIndex = false
let updatedTimestampIndex = false
let updatedSequenceIndex = false
const startSeq = seq
const start = Date.now()
let lastSaved = start
function save(count, offset, doneIndexing) {
const done = multicb({ pluck: 1 })
if (updatedSeqIndex) saveCoreIndex('seq', seqIndex, count, done())
if (updatedTimestampIndex)
saveCoreIndex('timestamp', timestampIndex, count, done())
if (updatedSequenceIndex)
saveCoreIndex('sequence', sequenceIndex, count, done())
for (const op of oldOps) {
const indexName = op.data.indexName
const index = indexes.get(indexName)
if (index.offset < offset) {
index.offset = offset
if (op.data.version > index.version) index.version = op.data.version
}
}
for (const [indexName, index] of newIndexes) {
index.offset = offset
if (doneIndexing) indexes.set(indexName, index)
}
done(() => {
for (const op of oldOps) {
if (op.isCore) continue
const indexName = op.data.indexName
const index = indexes.get(indexName)
saveIndex(indexName, index, count)
}
for (const [indexName, index] of newIndexes) {
saveIndex(indexName, index, count)
}
})
}
const logstreamId = Math.ceil(Math.random() * 1000)
// prettier-ignore
debug(`log.stream #${logstreamId} started, updating indexes ${oldIndexNames.concat(newIndexNames).join('|')} from offset ${latestOffset}`)
status.update(indexes, indexNamesForStatus)
status.update(newIndexes, newIndexNames)
indexingActive.set(indexingActive.value + 1)
log.stream({ gt: latestOffset }).pipe({
paused: false,
write(record) {
const offset = record.offset
const buffer = record.value
if (updateSeqIndex(seq, offset)) updatedSeqIndex = true
if (!buffer) {
// deleted
seq++
return
}
const pValue = bipf.seekKey2(buffer, 0, BIPF_VALUE, 0)
if (updateTimestampIndex(seq, offset, buffer, pValue))
updatedTimestampIndex = true
if (updateSequenceIndex(seq, offset, buffer, pValue))
updatedSequenceIndex = true
for (const op of oldOps) {
if (op.isCore) continue
const index = indexes.get(op.data.indexName)
if (op.data.prefix && op.data.useMap)
updatePrefixMapIndex(op.data, index, buffer, seq, offset, pValue)
else if (op.data.prefix)
updatePrefixIndex(op.data, index, buffer, seq, offset, pValue)
else updateIndexValue(op, index, buffer, seq, pValue)
}
for (const op of newOps) {
const index = newIndexes.get(op.data.indexName)
if (op.data.prefix && op.data.useMap)
updatePrefixMapIndex(op.data, index, buffer, seq, offset, pValue)
else if (op.data.prefix)
updatePrefixIndex(op.data, index, buffer, seq, offset, pValue)
else if (op.data.indexAll)
updateAllIndexValue(op.data, newIndexes, buffer, seq, pValue)
else updateIndexValue(op, index, buffer, seq, pValue)
}
if (seq % 1000 === 0) {
status.update(indexes, indexNamesForStatus)
status.update(newIndexes, newIndexNames)
const now = Date.now()
if (now - lastSaved >= 60e3) {
lastSaved = now
save(seq + 1, offset, false)
}
}
seq++
},
end() {
// prettier-ignore
debug(`log.stream #${logstreamId} ended, scanned ${seq - startSeq} records in ${Date.now() - start}ms`)
const count = seq // incremented at the end of write()
save(count, seqIndex.offset, true)
status.update(indexes, indexNamesForStatus)
status.update(newIndexes, newIndexNames)
status.done(indexNamesForStatus)
status.done(newIndexNames)
indexingActive.set(indexingActive.value - 1)
unlock(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.get(indexName)
if (index.prefix && index.map) {
loadPrefixMapFile(index.filepath, (err, data) => {
if (err) {
debug('index %s failed to load with %s', indexName, err)
indexes.delete(indexName)
return cb() // don't return a error, index will be rebuild
}
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) {
debug('index %s failed to load with %s', indexName, err)
indexes.delete(indexName)
return cb() // don't return a error, index will be rebuild
}
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) {
debug('index %s failed to load with %s', indexName, err)
indexes.delete(indexName)
return cb() // don't return a error, index will be rebuild
}
const { version, offset, bitset } = data
index.version = version
index.offset = offset
index.bitset = bitset
index.lazy = false
runWaitingIndexLoadCbs(waitingIndexLoad, indexName)
cb()
})
}
}
function ensureIndexSync(op, cb) {
const index = indexes.get(op.data.indexName)
if (log.since.value > index.offset || op.data.version > index.version) {
updateIndexes([op], cb)
} else {
cb()
}
}
function filterIndex(op, filterCheck, cb) {
if (op.data.indexName === 'sequence') {
const bitset = new TypedFastBitSet()
const { tarr, count } = sequenceIndex
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 } = timestampIndex
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) {
const bitset = new TypedFastBitSet()
const { count } = sequenceIndex
bitset.addRange(0, count)
cb(bitset)
}
function getOffsetsBitset(opOffsets, cb) {
const seqs = []
opOffsets.sort((x, y) => x - y)
const opOffsetsLen = opOffsets.length
const { tarr, count } = seqIndex
for (let seq = 0; seq < count; ++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(bipf.slice(target, 0), 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 pValue = bipf.seekKey2(value, 0, BIPF_VALUE, 0)
const fieldStart = seek(value, 0, pValue)
if (target) return bipf.compare(value, fieldStart, target, 0) === 0
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' ||
op.type === 'PREDICATE'
) {
const value = op.data.value
? op.data.value.toString().substring(0, 10)
: ''
return `${op.data.indexType}(${value})`
} else if (op.type === 'ABSENT') {
return `ABSENT(${op.data.indexType})`
} 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' ||
op.type === 'PREDICATE' ||
op.type === 'ABSENT'
) {
if (op.data.prefix) {
matchAgainstPrefix(op, indexes.get(op.data.indexName), cb)
} else {
cb(indexes.get(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') {
getOffsetsBitset(op.offsets, cb)
} else if (op.type === 'SEQS') {
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 if (op.type === 'DEFERRED') {
// DEFERRED only appears in this pipeline when using `prepare()` API,
// and only updateIndexes() is the important part in `prepare()`.
cb(new TypedFastBitSet())
} else console.error('Unknown type in jitdb executeOperation:', op)
}