-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathindex.js
1820 lines (1389 loc) · 48.6 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 ProtomuxWakeup = require('protomux-wakeup')
const rrp = require('resolve-reject-promise')
const Linearizer = require('./lib/linearizer.js')
const SystemView = require('./lib/system.js')
const UpdateChanges = require('./lib/updates.js')
const messages = require('./lib/messages.js')
const Timer = require('./lib/timer.js')
const Writer = require('./lib/writer.js')
const ActiveWriters = require('./lib/active-writers.js')
const AutoWakeup = require('./lib/wakeup.js')
const FastForward = require('./lib/fast-forward.js')
const AutoStore = require('./lib/store.js')
const ApplyState = require('./lib/apply-state.js')
const { PublicApplyCalls } = require('./lib/apply-calls.js')
const boot = require('./lib/boot.js')
const inspect = Symbol.for('nodejs.util.inspect.custom')
const INTERRUPT = new Error('Apply interrupted')
const BINARY_ENCODING = c.from('binary')
const AUTOBASE_VERSION = 1
const RECOVERIES = 3
const FF_RECOVERY = 1
// default is to automatically ack
const DEFAULT_ACK_INTERVAL = 10_000
const DEFAULT_ACK_THRESHOLD = 4
const REMOTE_ADD_BATCH = 64
const MIN_FF_WAIT = 300_000 // wait at least 5min before attempting to ff again after failure
class WakeupHandler {
constructor (base, discoveryKey) {
this.active = true
this.discoveryKey = discoveryKey
this.base = base
}
onpeeradd (peer, session) {
if (this.base._coupler) this.base._coupler.update(peer.stream)
}
onpeerremove (peer, session) {
// do nothing
}
onlookup (req, peer, session) {
const wakeup = this.base._getWakeup()
if (wakeup.length === 0) return
session.announce(peer, wakeup)
}
onannounce (wakeup, peer, session) {
if (this.base.isFastForwarding()) return
this.base.hintWakeup(wakeup)
}
}
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()
const key = bootstrap ? toKey(bootstrap) : null
this.id = null
this.key = key
this.discoveryKey = null
this.keyPair = null
this.valueEncoding = c.from(handlers.valueEncoding || 'binary')
this.store = store
this.globalCache = store.globalCache || null
this.migrated = false
this.encrypted = handlers.encrypted || !!handlers.encryptionKey
this.encrypt = !!handlers.encrypt
this.encryptionKey = handlers.encryptionKey || null
this.encryption = null
this.local = null
this.localWriter = null
this.isIndexer = false
this.activeWriters = new ActiveWriters()
this.linearizer = null
this.updating = false
this.nukeTip = !!handlers.nukeTip
this.wakeupOwner = !handlers.wakeup
this.wakeupCapability = handlers.wakeupCapability || null
this.wakeupProtocol = handlers.wakeup || new ProtomuxWakeup()
this.wakeupSession = null
this._primaryBootstrap = null
this.fastForwardEnabled = handlers.fastForward !== false
this.fastForwarding = null
this.fastForwardTo = null
this.fastForwardFailedAt = 0
this._bootstrapWriters = [] // might contain dups, but thats ok
this._bootstrapWritersChanged = false
this._checkWriters = []
this._optimistic = -1
this._appended = 0
this._appending = null
this._wakeup = new AutoWakeup(this)
this._wakeupHints = new Map()
this._wakeupPeerBound = this._wakeupPeer.bind(this)
this._coupler = null
this._lock = mutexify()
this._needsWakeup = true
this._needsWakeupHeads = true
this._updates = []
this._handlers = handlers || {}
this._warn = emitWarning.bind(this)
this._draining = false
this._writable = null
this._advancing = null
this._interrupting = false
this._caughtup = 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._preopen = null
this._hasOpen = !!this._handlers.open
this._hasApply = !!this._handlers.apply
this._hasOptimisticApply = !!this._handlers.optimistic
this._hasUpdate = !!this._handlers.update
this._hasClose = !!this._handlers.close
this._viewStore = new AutoStore(this)
this._applyState = null
this.view = null
this.core = null
this.version = -1
this.interrupted = null
this.recoveries = RECOVERIES
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._waiting = new SignalPromise()
this._bootRecovery = false
this.view = this._hasOpen ? this._handlers.open(this._viewStore, new PublicApplyCalls(this)) : null
this.core = this._viewStore.get({ name: '_system' })
if (this.fastForwardEnabled && isObject(handlers.fastForward)) {
this._runFastForward(new FastForward(this, handlers.fastForward.key, { verified: false })).catch(noop)
}
this.ready().catch(safetyCatch)
}
[inspect] (depth, opts) {
let indent = ''
if (typeof opts.indentationLvl === 'number') {
while (indent.length < opts.indentationLvl) indent += ' '
}
return indent + 'Autobase { ... }'
}
// just compat, use .key
get bootstrap () {
return this.key
}
// 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 && this.localWriter.isActiveIndexer
}
get signedLength () {
return this.core.signedLength
}
get indexedLength () {
return this._applyState ? this._applyState.indexedLength : 0
}
get length () {
return this.core.length
}
hash () {
return this.core.treeHash()
}
// deprecated, use .core.key
getSystemKey () {
return this.core.key
}
get system () {
return this._applyState && this._applyState.system
}
// deprecated
async getIndexedInfo () {
if (this.opened === false) await this.ready()
return this._applyState && this._applyState.system.getIndexedInfo(this._applyState.indexedLength)
}
_isActiveIndexer () {
return this.localWriter ? this.localWriter.isActiveIndexer : false
}
replicate (isInitiator, opts) {
const stream = this.store.replicate(isInitiator, opts)
this.wakeupProtocol.addStream(stream)
return stream
}
heads () {
if (!this._applyState || !this._applyState.opened) return []
const nodes = new Array(this._applyState.system.heads.length)
for (let i = 0; i < this._applyState.system.heads.length; i++) nodes[i] = this._applyState.system.heads[i]
return nodes.sort(compareNodes)
}
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 _runPreOpen () {
if (this._handlers.wait) await this._handlers.wait()
await this.store.ready()
this.keyPair = (await this._handlers.keyPair) || null
const result = await boot(this.store, this.key, {
encryptionKey: this.encryptionKey,
encrypt: this.encrypt,
keyPair: this.keyPair
})
const pointer = await result.local.getUserData('autobase/boot')
if (pointer) {
const { recoveries } = c.decode(messages.BootRecord, pointer)
this.recoveries = recoveries
}
this._primaryBootstrap = result.bootstrap
this.local = result.local
this.key = result.bootstrap.key
this.discoveryKey = result.bootstrap.discoveryKey
this.id = result.bootstrap.id
this.encryptionKey = result.encryptionKey
if (this.encryptionKey) this.encryption = { key: this.encryptionKey }
if (this.encrypted) {
assert(this.encryptionKey !== null, 'Encryption key is expected')
}
if (this.nukeTip) await this._nukeTip()
this.setWakeup(this.wakeupCapability || this.key, null)
}
async _nukeTipBatch (key, length) {
const core = this.store.get({ key, active: false })
await core.ready()
const batch = core.session({ name: 'batch' })
await batch.ready()
if (batch.length > length) await batch.truncate(length)
await batch.close()
await core.close()
}
// TODO: not atomic atm, so more of a (very useful) debug helper
async _nukeTip () {
const pointer = await this.local.getUserData('autobase/boot')
if (!pointer) return
const boot = c.decode(messages.BootRecord, pointer)
const tx = this.local.state.storage.write()
tx.deleteLocalRange(b4a.from([messages.LINEARIZER_PREFIX]), b4a.from([messages.LINEARIZER_PREFIX + 1]))
await tx.flush()
await this._nukeTipBatch(boot.key, boot.indexedLength)
const encryption = this.encryptionKey
? { key: AutoStore.getBlockKey(this.bootstrap, this.encryptionKey, '_system'), block: true }
: null
const core = this.store.get({ key: boot.key, encryption, active: false })
await core.ready()
const batch = core.session({ name: 'batch' })
await batch.ready()
const info = await SystemView.getIndexedInfo(batch, boot.indexedLength)
await batch.close()
for (const view of info.views) { // ensure any views ref'ed by system are consistent as well
await this._nukeTipBatch(view.key, view.length)
}
if (boot.heads) this.hintWakeup(boot.heads)
if (this.local.length) this.hintWakeup([{ key: this.local.key, length: this.local.length }])
}
setWakeup (cap, discoveryKey) {
if (this.wakeupSession) this.wakeupSession.destroy()
if (!discoveryKey && b4a.equals(cap, this.key)) discoveryKey = this.discoveryKey
this.wakeupSession = this.wakeupProtocol.session(cap, new WakeupHandler(this, discoveryKey || null))
}
async _getMigrationPointer (key, length) {
const encryption = this.encryptionKey
? { key: AutoStore.getBlockKey(this.bootstrap, this.encryptionKey, '_system'), block: true }
: null
const core = this.store.get({ key, active: false, encryption })
await core.ready()
const min = (core.manifest && core.manifest.prologue) ? core.manifest.prologue.length : 0
for (let i = length - 1; i >= min; i--) {
if (!(await core.has(i))) continue
const sys = new SystemView(core, { checkout: i + 1 })
await sys.ready()
let good = true
for (const v of sys.views) {
const vc = this.store.get({ key: v.key, active: false })
await vc.ready()
if (vc.length < v.length) good = false
await vc.close()
}
await sys.close()
if (!good) continue
return i + 1
}
return min
}
// migrating from 6 -> latest
async _migrate6 (key, length) {
const core = this.store.get({ key, active: false })
await core.ready()
const batch = core.session({ name: 'batch', overwrite: true, checkout: length })
await batch.ready()
await batch.close()
await core.close()
}
// called by view-store for bootstrapping
async _getSystemInfo () {
const boot = await this._getBootRecord()
if (!boot.key) return null
const migrated = !!boot.heads
if (migrated) { // ensure system batch is consistent on initial migration
await this._migrate6(boot.key, boot.indexedLength)
}
const encryption = this.encryptionKey
? { key: AutoStore.getBlockKey(this.bootstrap, this.encryptionKey, '_system'), block: true }
: null
const core = this.store.get({ key: boot.key, encryption, active: false })
await core.ready()
const batch = core.session({ name: 'batch' })
const info = await SystemView.getIndexedInfo(batch, boot.indexedLength)
await batch.close()
await core.close()
if (info.version > AUTOBASE_VERSION) {
throw new Error('Autobase upgrade required.')
}
// just compat
if (migrated) {
this.migrated = true
for (const view of info.views) { // ensure any views ref'ed by system are consistent as well
await this._migrate6(view.key, view.length)
}
if (boot.heads) this.hintWakeup(boot.heads)
if (this.local.length) this.hintWakeup([{ key: this.local.key, length: this.local.length }])
}
return {
key: boot.key,
indexers: info.indexers,
views: info.views
}
}
// called by the apply state for bootstrapping
async _getBootRecord () {
await this._preopen
const pointer = await this.local.getUserData('autobase/boot')
const boot = pointer
? c.decode(messages.BootRecord, pointer)
: { key: null, indexedLength: 0, indexersUpdated: false, fastForwarding: false, recoveries: RECOVERIES, heads: null }
if (boot.heads) {
const len = await this._getMigrationPointer(boot.key, boot.indexedLength)
if (len !== boot.indexedLength) this._warn(new Error('Invalid pointer in migration, correcting (' + len + ' vs ' + boot.indexedLength + ')'))
boot.indexedLength = len
}
return boot
}
_interrupt (reason) {
assert(this._applyState.applying, '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
}
recouple () {
if (this._coupler) this._coupler.destroy()
const core = this._viewStore.getSystemCore()
this._coupler = new CoreCoupler(core, 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
writer.isCoupled = false
}
// all passed are bootstraps
for (const writer of writers) {
writer.isCoupled = true
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 _openLinearizer () {
if (this._applyState.system.bootstrapping) {
await this._makeLinearizer(null)
this._bootstrapLinearizer()
return
}
await this._makeLinearizerFromViewState()
}
async _catchupApplyState () {
if (await this._applyState.shouldMigrate()) {
await this._migrate()
} else {
await this._applyState.catchup(this.linearizer)
}
this._caughtup = true
}
async _open () {
this._preopen = this._runPreOpen()
await this._preopen
if (this.closing) return
this._applyState = new ApplyState(this)
try {
await this._applyState.ready()
} catch (err) {
if (this.closing) return
try {
await this._applyState.close()
} catch {}
try {
await this.core.ready()
} catch {}
this._applyState = null
if (this.closing) return
this._warn(new Error('Failed to boot due to: ' + err.message))
if (this.recoveries < RECOVERIES) {
this._bootRecovery = true
this._queueBump()
return
}
throw err
}
try {
await this._openLinearizer()
await this.core.ready()
await this._wakeup.ready()
} catch (err) {
if (this.closing) return
throw err
}
if (this.core.length - this._applyState.indexedLength > this._ackTickThreshold) {
this._ackTick = this._ackTickThreshold
}
if (this.localWriter && this._ackInterval) {
this._startAckTimer()
}
this._updateBootstrapWriters()
this.recouple()
this._queueFastForward()
// queue a full bump that handles wakeup etc (not legal to wait for that here)
this._queueBump()
}
async _closeLocalCores () {
const closing = []
if (this._primaryBootstrap) closing.push(this._primaryBootstrap.close())
if (this.localWriter) closing.push(this._unsetLocalWriter())
closing.push(this._closeAllActiveWriters())
if (this.localWriter) await this.localWriter.close()
await Promise.all(closing)
await this.local.close()
}
async _close () {
this._interrupting = true
await Promise.resolve() // defer one tick
if (this.wakeupSession) this.wakeupSession.destroy()
if (this.wakeupOwner) this.wakeupProtocol.destroy()
if (this.fastForwarding) await this.fastForwarding.close()
if (this._coupler) this._coupler.destroy()
this._coupler = null
this._waiting.notify(null)
await this.activeWriters.clear()
const closing = this._advancing ? this._advancing.catch(safetyCatch) : null
await this._closeLocalCores()
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._applyState) await this._applyState.close()
await this._viewStore.close()
await this.core.close()
await this.store.close()
if (this._writable) this._writable.resolve(false)
await closing
}
_onError (err) {
if (this.closing) return
if (err === INTERRUPT) {
this.emit('interrupt', this.interrupted)
this.emit('update')
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)
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()
// doesnt hurt
w.updateActivity()
if (!w.flushed()) continue
const unqueued = this._wakeup.unqueue(w.core.key, w.core.length)
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 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...
} 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 {}
}
_onwakeup () {
this._needsWakeup = true
this._queueBump()
}
isFastForwarding () {
if (this.fastForwardTo !== null) return true
return this.fastForwardEnabled && this.fastForwarding !== null
}
_backgroundAck () {
return this.ack(true)
}
async ack (bg = false) {
if (this.opened === false) await this.ready()
if (this.localWriter === null || this._acking || this._interrupting || this._appending !== null) return
if (this._applyState === null) {
try {
await this._bump()
} catch {}
if (this._applyState === null || this._interrupting) return
}
const applyState = this._applyState
if (applyState.opened === false) await applyState.ready()
const isPendingIndexer = applyState.isLocalPendingIndexer()
// if no one is waiting for our index manifest, wait for FF before pushing an ack
if ((!isPendingIndexer && this.isFastForwarding()) || this._interrupting) return
const isIndexer = applyState.isLocalIndexer() || isPendingIndexer
if (!isIndexer) return
this._acking = true
try {
await this._bump()
} catch (err) {
if (!this._interrupting) throw err
}
if (this._interrupting || !this.localWriter || this.localWriter.closed) {
this._acking = false
return
}
// avoid lumping acks together due to the bump wait here
if (this._ackTimer && bg) await this._ackTimer.asapStandalone()
if (this._interrupting) {
this._acking = false
return
}
const alwaysWrite = isPendingIndexer || this._applyState.shouldWrite()
if (alwaysWrite || this.linearizer.shouldAck(this.localWriter, false)) {
try {
if (this.localWriter && !this.localWriter.closed) await this.append(null)
} catch (err) {
if (!this._interrupting) throw err
}
}
if (!this._interrupting) {
this._updateAckThreshold()
this._bumpAckTimer()
}
this._acking = false
}
async append (value, opts) {
if (this.opened === false) await this.ready()
if (this._interrupting) throw new Error('Autobase is closing')
if (value && this.valueEncoding !== BINARY_ENCODING) value = normalize(this.valueEncoding, value)
const optimistic = !!opts && !!opts.optimistic && !!value
// we wanna allow acks so interdexers can flush
if (!optimistic && (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)
}
if (optimistic) this._optimistic = this._appending.length - 1
const target = this._appended + this._appending.length
// await in case append is in current tick
if (this._advancing) await this._advancing
// bump until we've flushed the nodes
while (this._appended < target && !this._interrupting) {
await this._bump()
// safety
if (this.localWriter && this.localWriter.idle()) return
}
}
_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)
}
static encodeValue (value, opts = {}) {
return c.encode(messages.OplogMessage, {
version: AUTOBASE_VERSION,
maxSupportedVersion: AUTOBASE_VERSION,
digist: null,
checkpoint: null,
optimistic: !!opts.optimistic,
node: {
heads: opts.heads || [],
batch: 1,
value
}
})
}
static async getLocalKey (store, opts = {}) {
const core = opts.keyPair ? store.get({ ...opts, active: false }) : store.get({ ...opts, name: 'local', active: false })
await core.ready()
const key = core.key
await core.close()
return key
}
static getLocalCore (store, handlers, encryptionKey) {
const encryption = !encryptionKey ? null : { key: encryptionKey }
const opts = { ...handlers, compat: false, active: false, exclusive: true, valueEncoding: messages.OplogMessage, encryption }
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 ? b4a.toString(view) : null
}
}
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._preopen
const core = this._primaryBootstrap === null ? this.local : this._primaryBootstrap
await core.setUserData(key, val)
}
async getUserData (key) {
await this._preopen
const core = this._primaryBootstrap === null ? this.local : this._primaryBootstrap
return await core.getUserData(key)
}
_needsLocalWriter () {
return this.localWriter === null || this.localWriter.closed
}
// no guarantees about writer.isActiveIndexer property here
async _getWriterByKey (key, len, seen, allowGC, isAdded, system) {
assert(this._draining === true || (this.opening && !this.opened) || this._optimistic > -1)
const release = await this._lock()
if (this._interrupting) {
release()
throw new Error('Autobase is closing')
}
try {
let w = this.activeWriters.get(key)
const alreadyActive = !!w
const sys = system || this._applyState.system
const writerInfo = await sys.get(key)
if (len === -1) {
if (!allowGC && writerInfo === null) {
if (w) w.isRemoved = !isAdded
return null
}
len = writerInfo === null ? 0 : writerInfo.length
}
const isActive = writerInfo !== null && (isAdded || !writerInfo.isRemoved)
const isRemoved = !isActive
if (w) {
w.isRemoved = isRemoved
} else {
w = this._makeWriter(key, len, isActive, isRemoved)
if (!w) return null
}
if (isRemoved && sys.bootstrapping && b4a.equals(w.core.key, this.key)) {
w.isRemoved = false
}
if (this._isLocalCore(w.core) && this._needsLocalWriter()) {
this._setLocalWriter(w)
}
w.seen(seen)
if (alreadyActive) return w
await w.ready()
if (this._isLocalCore(w.core) && this._needsLocalWriter()) {
this._setLocalWriter(w)
}
if (allowGC && w.flushed()) {
this._wakeup.unqueue(key, len)
if (w !== this.localWriter) {
await w.close()
return w
}
}
this.activeWriters.add(w)
this._checkWriters.push(w)
assert(w.opened)
assert(!w.closed)