-
Notifications
You must be signed in to change notification settings - Fork 23
/
index.js
2431 lines (1851 loc) · 64.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
const b4a = require('b4a')
const ReadyResource = require('ready-resource')
const debounceify = require('debounceify')
const c = require('compact-encoding')
const safetyCatch = require('safety-catch')
const hypercoreId = require('hypercore-id-encoding')
const assert = require('nanoassert')
const SignalPromise = require('signal-promise')
const CoreCoupler = require('core-coupler')
const mutexify = require('mutexify/promise')
const Linearizer = require('./lib/linearizer')
const AutoStore = require('./lib/store')
const SystemView = require('./lib/system')
const messages = require('./lib/messages')
const Timer = require('./lib/timer')
const Writer = require('./lib/writer')
const ActiveWriters = require('./lib/active-writers')
const CorePool = require('./lib/core-pool')
const AutoWakeup = require('./lib/wakeup')
const inspect = Symbol.for('nodejs.util.inspect.custom')
const INTERRUPT = new Error('Apply interrupted')
const AUTOBASE_VERSION = 1
// default is to automatically ack
const DEFAULT_ACK_INTERVAL = 10_000
const DEFAULT_ACK_THRESHOLD = 4
const FF_THRESHOLD = 16
const DEFAULT_FF_TIMEOUT = 10_000
const REMOTE_ADD_BATCH = 64
module.exports = class Autobase extends ReadyResource {
constructor (store, bootstrap, handlers = {}) {
if (Array.isArray(bootstrap)) bootstrap = bootstrap[0] // TODO: just a quick compat, lets remove soon
if (bootstrap && typeof bootstrap !== 'string' && !b4a.isBuffer(bootstrap)) {
handlers = bootstrap
bootstrap = null
}
super()
this.bootstrap = bootstrap ? toKey(bootstrap) : null
this.keyPair = handlers.keyPair || null
this.valueEncoding = c.from(handlers.valueEncoding || 'binary')
this.store = store
this.globalCache = store.globalCache || null
this.encrypted = handlers.encrypted || !!handlers.encryptionKey
this.encryptionKey = handlers.encryptionKey || null
this._tryLoadingLocal = true
this._primaryBootstrap = null
if (this.bootstrap) {
this._primaryBootstrap = this.store.get({ key: this.bootstrap, compat: false, active: false, encryptionKey: this.encryptionKey })
this.store = this.store.namespace(this._primaryBootstrap, { detach: false })
}
this.local = null
this.localWriter = null
this.isIndexer = false
this.activeWriters = new ActiveWriters()
this.corePool = new CorePool()
this.linearizer = null
this.updating = false
this.fastForwardEnabled = handlers.fastForward !== false
this.fastForwarding = 0
this.fastForwardTo = null
if (this.fastForwardEnabled && isObject(handlers.fastForward)) {
this.fastForwardTo = handlers.fastForward
}
this._bootstrapWriters = [] // might contain dups, but thats ok
this._bootstrapWritersChanged = false
this._checkWriters = []
this._appending = null
this._wakeup = new AutoWakeup(this)
this._wakeupHints = new Map()
this._wakeupPeerBound = this._wakeupPeer.bind(this)
this._coupler = null
this._queueViewReset = false
this._lock = mutexify()
this._applying = null
this._updatingCores = false
this._localDigest = null
this._needsWakeup = true
this._needsWakeupHeads = true
this._addCheckpoints = false
this._firstCheckpoint = true
this._hasPendingCheckpoint = false
this._completeRemovalAt = null
this._systemPointer = 0
this._maybeStaticFastForward = false // writer bumps this
this._updates = []
this._handlers = handlers || {}
this._warn = emitWarning.bind(this)
this._draining = false
this._advancing = null
this._advanced = null
this._interrupting = false
this.reindexing = false
this.paused = false
this._bump = debounceify(() => {
this._advancing = this._advance()
return this._advancing
})
this._onremotewriterchangeBound = this._onremotewriterchange.bind(this)
this.maxSupportedVersion = AUTOBASE_VERSION // working version
this._presystem = null
this._prebump = null
this._hasApply = !!this._handlers.apply
this._hasOpen = !!this._handlers.open
this._hasClose = !!this._handlers.close
this.onindex = handlers.onindex || noop
this._viewStore = new AutoStore(this)
this.view = null
this.system = null
this.version = -1
this.interrupted = null
const {
ackInterval = DEFAULT_ACK_INTERVAL,
ackThreshold = DEFAULT_ACK_THRESHOLD
} = handlers
this._ackInterval = ackInterval
this._ackThreshold = ackThreshold
this._ackTickThreshold = ackThreshold
this._ackTick = 0
this._ackTimer = null
this._acking = false
this._initialHeads = []
this._initialSystem = null
this._initialViews = null
this._waiting = new SignalPromise()
const sysCore = this._viewStore.get({ name: '_system', exclusive: true })
this.system = new SystemView(sysCore, {
checkout: 0
})
this.view = this._hasOpen ? this._handlers.open(this._viewStore, this) : null
this.ready().catch(safetyCatch)
}
[inspect] (depth, opts) {
let indent = ''
if (typeof opts.indentationLvl === 'number') {
while (indent.length < opts.indentationLvl) indent += ' '
}
return indent + 'Autobase { ... }'
}
// TODO: compat, will be removed
get bootstraps () {
return [this.bootstrap]
}
get writable () {
return this.localWriter !== null && !this.localWriter.isRemoved
}
get ackable () {
return this.localWriter !== null // prop should add .isIndexer but keeping it simple for now
}
get key () {
return this._primaryBootstrap === null ? this.local.key : this._primaryBootstrap.key
}
get discoveryKey () {
return this._primaryBootstrap === null ? this.local.discoveryKey : this._primaryBootstrap.discoveryKey
}
_isActiveIndexer () {
return this.localWriter ? this.localWriter.isActiveIndexer : false
}
replicate (init, opts) {
return this.store.replicate(init, opts)
}
heads () {
const nodes = new Array(this.system.heads.length)
for (let i = 0; i < this.system.heads.length; i++) nodes[i] = this.system.heads[i]
return nodes.sort(compareNodes)
}
// any pending indexers
hasPendingIndexers () {
if (this.system.pendingIndexers.length > 0) return true
return this.hasUnflushedIndexers()
}
// confirmed indexers that aren't in linearizer yet
hasUnflushedIndexers () {
if (this.linearizer.indexers.length !== this.system.indexers.length) return true
for (let i = 0; i < this.system.indexers.length; i++) {
const w = this.linearizer.indexers[i]
if (!b4a.equals(w.core.key, this.system.indexers[i].key)) return true
}
return false
}
hintWakeup (hints) {
if (!Array.isArray(hints)) hints = [hints]
for (const { key, length } of hints) {
const hex = b4a.toString(key, 'hex')
const prev = this._wakeupHints.get(hex)
if (!prev || length === -1 || prev < length) this._wakeupHints.set(hex, length)
}
this._queueBump()
}
_queueBump () {
this._bump().catch(safetyCatch)
}
async _openPreSystem () {
if (this._handlers.wait) await this._handlers.wait()
await this.store.ready()
const opts = {
valueEncoding: this.valueEncoding,
keyPair: this.keyPair,
key: this._primaryBootstrap ? await this._primaryBootstrap.getUserData('autobase/local') : null
}
this.local = Autobase.getLocalCore(this.store, opts, this.encryptionKey)
await this.local.ready()
if (this.encryptionKey) {
await this.local.setUserData('autobase/encryption', this.encryptionKey)
} else {
this.encryptionKey = await this.local.getUserData('autobase/encryption')
if (this.encryptionKey) {
await this.local.setEncryptionKey(this.encryptionKey)
// not needed but, just for good meassure
if (this._primaryBootstrap) this._primaryBootstrap.setEncryptionKey(this.encryptionKey)
}
}
if (this.encrypted) {
assert(this.encryptionKey !== null, 'Encryption key is expected')
}
// stateless open
const ref = await this.local.getUserData('referrer')
if (ref && !b4a.equals(ref, this.local.key) && !this._primaryBootstrap) {
this._primaryBootstrap = this.store.get({ key: ref, compat: false, active: false, encryptionKey: this.encryptionKey })
this.store = this.store.namespace(this._primaryBootstrap, { detach: false })
}
await this.local.setUserData('referrer', this.key)
if (this._primaryBootstrap) {
await this._primaryBootstrap.ready()
this._primaryBootstrap.setUserData('autobase/local', this.local.key)
if (this.encryptionKey) await this._primaryBootstrap.setUserData('autobase/encryption', this.encryptionKey)
} else {
this.local.setUserData('autobase/local', this.local.key)
}
const { bootstrap, system, heads } = await this._loadSystemInfo()
this.version = system
? system.version
: this.bootstrap && !b4a.equals(this.bootstrap, this.local.key)
? -1
: this.maxSupportedVersion
this.bootstrap = bootstrap
this._initialSystem = system
this._initialHeads = heads
await this._makeLinearizer(system)
}
async _loadSystemInfo () {
const pointer = await this.local.getUserData('autobase/boot')
const bootstrap = this.bootstrap || (await this.local.getUserData('referrer')) || this.local.key
if (!pointer) return { bootstrap, system: null, heads: [] }
const { indexed, views, heads } = c.decode(messages.BootRecord, pointer)
const { key, length } = indexed
this._systemPointer = length
if (!length) return { bootstrap, system: null, heads: [] }
const encryptionKey = AutoStore.getBlockKey(bootstrap, this.encryptionKey, '_system')
const actualCore = this.store.get({ key, exclusive: false, compat: false, encryptionKey, isBlockKey: true })
await actualCore.ready()
const core = actualCore.batch({ checkout: length, session: false })
// safety check the batch is not corrupt
if (length === 0 || !(await core.has(length - 1))) {
await this.local.setUserData('autobase/boot', null)
this._systemPointer = 0
return { bootstrap, system: null, heads: [] }
}
const system = new SystemView(core, {
checkout: length
})
await system.ready()
if (system.version > this.maxSupportedVersion) {
throw new Error('Autobase upgrade required')
}
this._initialViews = [{ name: '_system', key, length }]
for (let i = 0; i < system.views.length; i++) {
this._initialViews.push({ name: views[i], ...system.views[i] })
}
return {
bootstrap,
system,
heads
}
}
interrupt (reason) {
assert(this._applying !== null, 'Interrupt is only allowed in apply')
this._interrupting = true
if (reason) this.interrupted = reason
throw INTERRUPT
}
async flush () {
if (this.opened === false) await this.ready()
await this._advancing
}
getSystemKey () {
const core = this.system.core.getBackingCore()
return core ? core.key : null
}
recouple () {
if (this._coupler) this._coupler.destroy()
const core = this.system.core.getBackingCore()
this._coupler = new CoreCoupler(core.session, this._wakeupPeerBound)
}
_updateBootstrapWriters () {
const writers = this.linearizer.getBootstrapWriters()
// first clear all, but without applying it for churn reasons
for (const writer of this._bootstrapWriters) writer.isBootstrap = false
// all passed are bootstraps
for (const writer of writers) writer.setBootstrap(true)
// reset activity on old ones, all should be in sync now
for (const writer of this._bootstrapWriters) {
if (writer.isBootstrap === false) writer.setBootstrap(false)
}
this._bootstrapWriters = writers
this._bootstrapWritersChanged = false
}
async _openPreBump () {
this._presystem = this._openPreSystem()
try {
await this._presystem
await this._viewStore.flush()
} catch (err) {
safetyCatch(err)
if (err.code === 'ELOCKED') throw err
await this.local.setUserData('autobase/last-error', b4a.from(err.stack + ''))
await this.local.setUserData('autobase/boot', null)
this.store.close().catch(safetyCatch)
throw err
}
// see if we can load from indexer checkpoint
await this.system.ready()
if (this._initialSystem) {
await this._initialSystem.close()
this._initialSystem = null
this._initialViews = null
}
// check if this is a v0 base
const record = await this.local.getUserData('autobase/system')
if (record !== null && (await this.local.getUserData('autobase/reindexed')) === null) {
this.reindexing = true
this.emit('reindexing')
this._onreindexing(record).catch(safetyCatch)
}
// load previous digest if available
if (this.localWriter && !this.system.bootstrapping) {
await this._restoreLocalState()
}
this.recouple()
if (this.fastForwardTo !== null) {
const { key, timeout } = this.fastForwardTo
this.fastForwardTo = null // will get reset once ready
this.initialFastForward(key, timeout || DEFAULT_FF_TIMEOUT * 2)
}
if (this.localWriter && this._ackInterval) this._startAckTimer()
}
async _onreindexing (record) {
const { key, length } = messages.Checkout.decode({ buffer: record, start: 0, end: record.byteLength })
const encryptionKey = this._viewStore.getBlockKey(this._viewStore.getSystemCore().name)
const core = this.store.get({ key, encryptionKey, isBlockKey: true }).batch({ checkout: length, session: false })
const base = this
const system = new SystemView(core, {
checkout: length
})
await system.ready()
const indexerCores = []
for (const { key } of system.indexers) {
const core = this.store.get({ key, compat: false, valueEncoding: messages.OplogMessage, encryptionKey: this.encryptionKey })
indexerCores.push(core)
}
await system.close()
for (const core of indexerCores) tail(core).catch(safetyCatch)
async function onsyskey (key) {
for (const core of indexerCores) await core.close()
if (key === null || !base.reindexing || base._isFastForwarding()) return
base.initialFastForward(key, DEFAULT_FF_TIMEOUT * 2)
}
async function tail (core) {
await core.ready()
while (base.reindexing && !base._isFastForwarding()) {
const seq = core.length - 1
const blk = seq >= 0 ? await core.get(seq) : null
if (blk && blk.version >= 1) {
const sysKey = await getSystemKey(core, seq, blk)
if (sysKey) return onsyskey(sysKey)
}
await core.get(core.length) // force get next blk
}
return onsyskey(null)
}
async function getSystemKey (core, seq, blk) {
if (!blk.digest) return null
if (blk.digest.key) return blk.digest.key
const p = await core.get(seq - blk.digest.pointer)
return p.digest && p.digest.key
}
}
async _restoreLocalState () {
const version = await this.localWriter.getVersion()
if (version > this.maxSupportedVersion) {
this.store.close().catch(safetyCatch)
throw new Error('Autobase version cannot be downgraded')
}
await this._updateDigest()
}
async _open () {
this._prebump = this._openPreBump()
await this._prebump
await this._catchup(this._initialHeads)
await this._wakeup.ready()
this.system.requestWakeup()
// queue a full bump that handles wakeup etc (not legal to wait for that here)
this._queueBump()
this._advanced = this._advancing
if (this.reindexing) this._setReindexed()
this.queueFastForward()
this._updateBootstrapWriters()
}
async _catchup (nodes) {
if (!nodes.length) return
const visited = new Set()
const writers = new Map()
while (nodes.length) {
const { key, length } = nodes.pop()
const hex = b4a.toString(key, 'hex')
const ref = hex + ':' + length
if (visited.has(ref)) continue
visited.add(ref)
let w = writers.get(hex)
if (!w) {
const writer = await this._getWriterByKey(key, -1, 0, true, false, null)
w = { writer, end: writer.length }
writers.set(hex, w)
}
if (w.writer.length >= length) continue
if (length > w.end) w.end = length
// we should have all nodes locally
const block = await w.writer.core.get(length - 1, { wait: false })
assert(block !== null, 'Catchup failed: local block not available')
for (const dep of block.node.heads) {
nodes.push(dep)
}
}
while (writers.size) {
for (const [hex, info] of writers) {
const { writer, end } = info
if (writer === null || writer.length === end) {
writers.delete(hex)
continue
}
if (writer.available <= writer.length) {
// force in case they are not indexed yet
await writer.update(true)
}
const node = writer.advance()
if (!node) continue
this.linearizer.addHead(node)
}
}
await this._drain() // runs for one tick
}
_reindexersIdle () {
for (const idx of this.linearizer.indexers) {
if (idx.core.length !== idx.length) return false
}
return !this.localWriter || this.localWriter.core.length === this.localWriter.length
}
async _setReindexed () {
try {
while (true) {
await this._bump()
let p = this.progress()
if (p.processed === p.total && !(this.linearizer.indexers.length === 1 && this.linearizer.indexers[0].core.length === 0)) break
await this._waiting.wait(2000)
await this._advancing
p = this.progress()
if (p.processed === p.total) break
if (this._reindexersIdle()) break
}
if (this._interrupting) return
await this.local.setUserData('autobase/reindexed', b4a.from([0]))
this.reindexing = false
this.emit('reindexed')
} catch (err) {
safetyCatch(err)
}
}
async _close () {
this._interrupting = true
await Promise.resolve() // defer one tick
if (this._coupler) this._coupler.destroy()
this._coupler = null
this._waiting.notify(null)
const closing = this._advancing.catch(safetyCatch)
if (this._ackTimer) {
this._ackTimer.stop()
await this._ackTimer.flush()
}
await this._wakeup.close()
if (this._hasClose) await this._handlers.close(this.view)
if (this._primaryBootstrap) await this._primaryBootstrap.close()
await this.activeWriters.clear()
await this.corePool.clear()
await this.store.close()
await closing
}
_onError (err) {
if (this.closing) return
if (err === INTERRUPT) {
this.emit('interrupt', this.interrupted)
return
}
this.close().catch(safetyCatch)
// if no one is listening we should crash! we cannot rely on the EE here
// as this is wrapped in a promise so instead of nextTick throw it
if (ReadyResource.listenerCount(this, 'error') === 0) {
crashSoon(err)
return
}
this.emit('error', err)
}
async _closeWriter (w, now) {
this.activeWriters.delete(w)
if (!now) this.corePool.linger(w.core)
await w.close()
}
async _gcWriters () {
// just return early, why not
if (this._checkWriters.length === 0) return
while (this._checkWriters.length > 0) {
const w = this._checkWriters.pop()
if (!w.flushed()) continue
const unqueued = this._wakeup.unqueue(w.core.key, w.core.length)
this._coupler.remove(w.core)
if (!unqueued || w.isActiveIndexer) continue
if (this.localWriter === w) continue
await this._closeWriter(w, false)
}
await this._wakeup.flush()
}
_startAckTimer () {
if (this._ackTimer) return
this._ackTimer = new Timer(this._backgroundAck.bind(this), this._ackInterval)
this._bumpAckTimer()
}
_bumpAckTimer () {
if (!this._ackTimer) return
this._ackTimer.bump()
}
async _waitForIdle () {
let p = this.progress()
while (!this.closing && this.reindexing) {
if (p.processed === p.total && !(this.linearizer.indexers.length === 1 && this.linearizer.indexers[0].core.length === 0)) break
await this._waiting.wait(2000)
await this._advancing
const next = this.progress()
if (next.processed === p.processed && next.total === p.total) break
p = next
}
if (this.localWriter) {
await this.localWriter.ready()
while (!this.closing && this.localWriter.core.length > this.localWriter.length) {
await this.localWriter.waitForSynced()
await this._bump() // make sure its all flushed...
}
}
}
async update () {
if (this.opened === false) await this.ready()
try {
await this._bump()
if (this._acking) await this._bump() // if acking just rebump incase it was triggered from above...
await this._waitForIdle()
} catch (err) {
if (this._interrupting) return
throw err
}
}
// runs in bg, not allowed to throw
// TODO: refactor so this only moves the writer affected to a updated set
async _onremotewriterchange () {
this._bumpAckTimer()
try {
await this._bump()
} catch (err) {
if (!this._interrupting) throw err
}
}
_onwakeup () {
this._needsWakeup = true
this._queueBump()
}
_isPending () {
for (const key of this.system.pendingIndexers) {
if (b4a.equals(key, this.local.key)) return true
}
return false
}
_isFastForwarding () {
if (this.fastForwardTo !== null) return true
return this.fastForwardEnabled && this.fastForwarding > 0
}
_backgroundAck () {
return this.ack(true)
}
async ack (bg = false) {
if (this.localWriter === null) return
const isPendingIndexer = this._isPending()
// if no one is waiting for our index manifest, wait for FF before pushing an ack
if (!isPendingIndexer && this._isFastForwarding()) return
const isIndexer = this.localWriter.isActiveIndexer || isPendingIndexer
if (!isIndexer || this._acking || this._interrupting) return
this._acking = true
try {
await this._bump()
} catch (err) {
if (!this._interrupting) throw err
}
// avoid lumping acks together due to the bump wait here
if (this._ackTimer && bg) await this._ackTimer.asapStandalone()
if (this._interrupting) return
const unflushed = this._hasPendingCheckpoint || this.hasUnflushedIndexers()
if (!this._interrupting && (isPendingIndexer || this.linearizer.shouldAck(this.localWriter, unflushed))) {
try {
if (this.localWriter) await this.append(null)
} catch (err) {
if (!this._interrupting) throw err
}
if (!this._interrupting) {
this._updateAckThreshold()
this._bumpAckTimer()
}
}
this._acking = false
}
async append (value) {
if (!this.opened) await this.ready()
if (this._interrupting) throw new Error('Autobase is closing')
// if a reset is scheduled await those
while (this._queueViewReset && !this._interrupting) await this._bump()
// we wanna allow acks so interdexers can flush
if (this.localWriter === null || (this.localWriter.isRemoved && value !== null)) {
throw new Error('Not writable')
}
if (this._appending === null) this._appending = []
if (Array.isArray(value)) {
for (const v of value) this._append(v)
} else {
this._append(value)
}
// await in case append is in current tick
if (this._advancing) await this._advancing
// only bump if there are unflushed nodes
if (this._appending !== null) return this._bump()
}
_append (value) {
// if prev value is an ack that hasnt been flushed, skip it
if (this._appending.length > 0) {
if (value === null) return
if (this._appending[this._appending.length - 1] === null) {
this._appending.pop()
}
}
this._appending.push(value)
}
async checkpoint () {
await this.ready()
const all = []
for (const w of this.activeWriters) {
all.push(w.getCheckpoint())
}
const checkpoints = await Promise.all(all)
let best = null
for (const c of checkpoints) {
if (!c) continue
if (best === null || c.length > best.length) best = c
}
return best
}
static getLocalCore (store, handlers, encryptionKey) {
const opts = { ...handlers, compat: false, active: false, exclusive: true, valueEncoding: messages.OplogMessage, encryptionKey }
return opts.keyPair ? store.get(opts) : store.get({ ...opts, name: 'local' })
}
static async getUserData (core) {
const view = await core.getUserData('autobase/view')
return {
referrer: await core.getUserData('referrer'),
view: (!view || view[0] !== 0) ? null : c.decode(messages.ViewRecord, view)
}
}
static async isAutobase (core, opts = {}) {
const block = await core.get(0, opts)
if (!block) throw new Error('Core is empty.')
if (!b4a.isBuffer(block)) return isAutobaseMessage(block)
try {
const m = c.decode(messages.OplogMessage, block)
return isAutobaseMessage(m)
} catch {
return false
}
}
// no guarantees where the user data is stored, just that its associated with the base
async setUserData (key, val) {
await this._presystem
const core = this._primaryBootstrap === null ? this.local : this._primaryBootstrap
await core.setUserData(key, val)
}
async getUserData (key) {
await this._presystem
const core = this._primaryBootstrap === null ? this.local : this._primaryBootstrap
return await core.getUserData(key)
}
getNamespace (key, core) {
const w = this.activeWriters.get(key)
if (!w) return null
const namespace = w.deriveNamespace(core.name)
const publicKey = w.core.manifest.signers[0].publicKey
return {
namespace,
publicKey
}
}
// no guarantees about writer.isActiveIndexer property here
async _getWriterByKey (key, len, seen, allowGC, isAdded, system) {
assert(this._draining === true || (this.opening && !this.opened))
const release = await this._lock()
if (this._interrupting) {
release()
throw new Error('Autobase is closing')
}
try {
let w = this.activeWriters.get(key)
if (w !== null) {
if (isAdded && w.core.writable && this.localWriter === null) this._setLocalWriter(w)
if (w.isRemoved && isAdded) w.isRemoved = false
w.seen(seen)
return w
}
const sys = system || this.system
const writerInfo = await sys.get(key)
if (len === -1) {
if (!allowGC && writerInfo === null) return null
len = writerInfo === null ? 0 : writerInfo.length
}
const isActive = writerInfo !== null && (isAdded || !writerInfo.isRemoved)
// assumes that seen is passed 0 everywhere except in writer._ensureNodeDependencies
const isRemoved = seen === 0
? writerInfo !== null && (!isAdded && writerInfo.isRemoved)
: !isActive // a writer might have referenced a removed writer
w = this._makeWriter(key, len, isActive, isRemoved)
if (!w) return null
w.seen(seen)
await w.ready()
if (allowGC && w.flushed()) {
this._wakeup.unqueue(key, len)
if (w !== this.localWriter) {
this.corePool.linger(w.core)
await w.close()
return w
}
}
this.activeWriters.add(w)
this._checkWriters.push(w)
// will only add non-indexer writers
if (this._coupler) this._coupler.add(w.core)
assert(w.opened)
assert(!w.closed)
this._resumeWriter(w)
return w
} finally {
release()
}
}
_updateAll () {
const p = []
for (const w of this.activeWriters) p.push(w.update(false).catch(this._warn))
return Promise.all(p)
}
_makeWriterCore (key) {
const pooled = this.corePool.get(key)
if (pooled) {