-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
707 lines (535 loc) · 16.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
const RocksDB = require('rocksdb-native')
const rrp = require('resolve-reject-promise')
const ScopeLock = require('scope-lock')
const View = require('./lib/view.js')
const VERSION = 1
const COLUMN_FAMILY = 'corestore'
const {
CorestoreRX,
CorestoreTX,
CoreTX,
CoreRX
} = require('./lib/tx.js')
const {
createCoreStream,
createAliasStream,
createBlockStream,
createBitfieldStream,
createUserDataStream,
createTreeNodeStream
} = require('./lib/streams.js')
const EMPTY = new View()
class Atom {
constructor (db) {
this.db = db
this.view = new View()
this.flushing = false
this.flushes = []
}
onflush (fn) {
this.flushes.push(fn)
}
async flush () {
if (this.flushing) throw new Error('Atom already flushing')
this.flushing = true
try {
await View.flush(this.view.changes, this.db)
this.view.reset()
const promises = []
const len = this.flushes.length // in case of reentry
for (let i = 0; i < len; i++) promises.push(this.flushes[i]())
await Promise.all(promises)
} finally {
this.flushing = false
}
}
}
class HypercoreStorage {
constructor (store, db, core, view, atom) {
this.store = store
this.db = db
this.core = core
this.view = view
this.atom = atom
this.view.readStart()
}
get dependencies () {
return this.core.dependencies
}
getDependencyLength () {
return this.core.dependencies.length
? this.core.dependencies[this.core.dependencies.length - 1].length
: -1
}
getDependency (length) {
for (let i = this.core.dependencies.length - 1; i >= 0; i--) {
const dep = this.core.dependencies[i]
if (dep.length < length) return dep
}
return null
}
// TODO: this might have to be async if the dependents have changed, but prop ok for now
updateDependencyLength (length) {
const deps = this.core.dependencies
for (let i = deps.length - 1; i >= 0; i--) {
if (deps[i].length >= length) continue
deps[i].length = length
this.core.dependencies = deps.slice(0, i + 1)
return
}
throw new Error('Dependency not found')
}
get snapshotted () {
return this.db._snapshot !== null
}
snapshot () {
return new HypercoreStorage(this.store, this.db.snapshot(), this.core, this.view.snapshot(), this.atom)
}
atomize (atom) {
if (this.atom && this.atom !== atom) throw new Error('Cannot atomize and atomized session with a new atom')
return new HypercoreStorage(this.store, this.db.session(), this.core, atom.view, atom)
}
createAtom () {
return this.store.createAtom()
}
createBlockStream (opts) {
return createBlockStream(this.core, this.db, this.view, opts)
}
createTreeNodeStream (opts) {
return createTreeNodeStream(this.core, this.db, this.view, opts)
}
createBitfieldStream (opts) {
return createBitfieldStream(this.core, this.db, this.view, opts)
}
createUserDataStream (opts) {
return createUserDataStream(this.core, this.db, this.view, opts)
}
async resumeSession (name) {
const rx = this.read()
const existingSessionsPromise = rx.getSessions()
rx.tryFlush()
const existingSessions = await existingSessionsPromise
const sessions = existingSessions || []
const session = getBatch(sessions, name, false)
if (session === null) return null
const core = {
version: this.core.version,
corePointer: this.core.corePointer,
dataPointer: session.dataPointer,
dependencies: []
}
const coreRx = new CoreRX(core, this.db, this.view)
const dependencyPromise = coreRx.getDependency()
coreRx.tryFlush()
const dependency = await dependencyPromise
if (dependency) core.dependencies = this._addDependency(dependency)
return new HypercoreStorage(this.store, this.db.session(), core, this.atom ? this.view : new View(), this.atom)
}
async createSession (name, head) {
const rx = this.read()
const existingSessionsPromise = rx.getSessions()
const existingHeadPromise = rx.getHead()
rx.tryFlush()
const [existingSessions, existingHead] = await Promise.all([existingSessionsPromise, existingHeadPromise])
if (head === null) head = existingHead
if (existingHead !== null && head.length > existingHead.length) {
throw new Error('Invalid head passed, ahead of core')
}
const sessions = existingSessions || []
const session = getBatch(sessions, name, true)
if (session.dataPointer === -1) {
session.dataPointer = await this.store._allocData()
}
const tx = this.write()
tx.setSessions(sessions)
const length = head === null ? 0 : head.length
const core = {
version: this.core.version,
corePointer: this.core.corePointer,
dataPointer: session.dataPointer,
dependencies: this._addDependency({ dataPointer: this.core.dataPointer, length })
}
const coreTx = new CoreTX(core, this.db, tx.view, tx.changes)
if (length > 0) coreTx.setHead(head)
coreTx.setDependency(core.dependencies[core.dependencies.length - 1])
await tx.flush()
return new HypercoreStorage(this.store, this.db.session(), core, this.atom ? this.view : new View(), this.atom)
}
async createAtomicSession (atom, head) {
const length = head === null ? 0 : head.length
const core = {
version: this.core.version,
corePointer: this.core.corePointer,
dataPointer: this.core.dataPointer,
dependencies: this._addDependency({ dataPointer: this.core.dataPointer, length })
}
const coreTx = new CoreTX(core, this.db, atom.view, [])
if (length > 0) coreTx.setHead(head)
coreTx.setDependency(core.dependencies[core.dependencies.length - 1])
await coreTx.flush()
return this.atomize(atom)
}
_addDependency (dep) {
const deps = []
for (let i = 0; i < this.core.dependencies.length; i++) {
const d = this.core.dependencies[i]
if (d.length > dep.length) {
deps.push({ dataPointer: d.dataPointer, length: dep.length })
return deps
}
deps.push(d)
}
deps.push(dep)
return deps
}
read () {
return new CoreRX(this.core, this.db, this.view)
}
write () {
return new CoreTX(this.core, this.db, this.atom ? this.view : null, [])
}
close () {
if (this.view !== null) {
this.view.readStop()
this.view = null
}
return this.db.close()
}
}
class CorestoreStorage {
constructor (db) {
this.path = typeof db === 'string' ? db : db.path
this.rocks = typeof db === 'string' ? new RocksDB(db) : db
this.db = createColumnFamily(this.rocks)
this.view = null
this.enters = 0
this.lock = new ScopeLock()
this.flushing = null
this.version = 0
this.migrating = null
}
get opened () {
return this.db.opened
}
get closed () {
return this.db.closed
}
async ready () {
if (this.version === 0) await this._migrateStore()
return this.db.ready()
}
static isCoreStorage (db) {
return isCorestoreStorage(db)
}
static from (db) {
if (isCorestoreStorage(db)) return db
return new this(db)
}
async _flush () {
while (this.enters > 0) {
await this.lock.lock()
await this.lock.unlock()
}
}
// runs pre any other mutation and read
async _migrateStore () {
const view = await this._enter()
try {
if (this.version === VERSION) return
const rx = new CorestoreRX(this.db, view)
const headPromise = rx.getHead()
rx.tryFlush()
const head = await headPromise
const version = head === null ? 0 : head.version
if (version === VERSION) return
const target = { version: VERSION, dryRun: false }
switch (version) {
case 0: {
await require('./migrations/0').store(this, target)
break
}
default: {
throw new Error('Unsupported version: ' + version + ' - you should probably upgrade your dependencies')
}
}
this.version = VERSION
} finally {
await this._exit()
}
}
// runs pre the core is returned to the user
async _migrateCore (core, discoveryKey, locked) {
const view = locked ? this.view : await this._enter()
const version = core.core.version
try {
if (version === VERSION) return
const target = { version: VERSION, dryRun: false }
switch (version) {
case 0: {
await require('./migrations/0').core(core, target)
break
}
default: {
throw new Error('Unsupported version: ' + version + ' - you should probably upgrade your dependencies')
}
}
core.core.version = VERSION
if (locked === false) return
// if its locked, then move the core state into the memview
// in case the core is reopened from the memview, pre flush
const rx = new CorestoreRX(this.db, EMPTY)
const tx = new CorestoreTX(view)
const corePromise = rx.getCore(discoveryKey)
rx.tryFlush()
tx.putCore(discoveryKey, await corePromise)
tx.apply()
} finally {
if (!locked) await this._exit()
}
}
async _enter () {
this.enters++
await this.lock.lock()
if (this.view === null) this.view = new View()
return this.view
}
async _exit () {
this.enters--
if (this.flushing === null) this.flushing = rrp()
const flushed = this.flushing.promise
if (this.enters === 0 || this.view.size() > 128) {
try {
await View.flush(this.view.changes, this.db)
this.flushing.resolve()
} catch (err) {
this.flushing.reject(err)
} finally {
this.flushing = null
this.view = null
}
}
this.lock.unlock()
return flushed
}
// when used with core catches this isnt transactional for simplicity, HOWEVER, its just a number
// so worth the tradeoff
async _allocData () {
let dataPointer = 0
const view = await this._enter()
const tx = new CorestoreTX(view)
try {
const head = await this._getHead(view)
dataPointer = head.allocated.datas++
tx.setHead(head)
tx.apply()
} finally {
await this._exit()
}
return dataPointer
}
// exposes here so migrations can easily access the head in an init state
async _getHead (view) {
const rx = new CorestoreRX(this.db, view)
const headPromise = rx.getHead()
rx.tryFlush()
const head = await headPromise
return head === null ? initStoreHead() : head
}
createAtom () {
return new Atom(this.db)
}
async close () {
if (this.db.closed) return
await this._flush()
await this.db.close()
await this.rocks.close()
}
async clear () {
if (this.version === 0) await this._migrateStore()
const view = await this._enter()
const tx = new CorestoreTX(view)
tx.clear()
tx.apply()
await this._exit()
}
createCoreStream () {
// TODO: be nice to run the mgiration here also, but too much plumbing atm
return createCoreStream(this.db, EMPTY)
}
createAliasStream (namespace) {
// TODO: be nice to run the mgiration here also, but too much plumbing atm
return createAliasStream(this.db, EMPTY, namespace)
}
async getAlias (alias) {
if (this.version === 0) await this._migrateStore()
const rx = new CorestoreRX(this.db, EMPTY)
const discoveryKeyPromise = rx.getCoreByAlias(alias)
rx.tryFlush()
return discoveryKeyPromise
}
async getSeed () {
if (this.version === 0) await this._migrateStore()
const rx = new CorestoreRX(this.db, EMPTY)
const headPromise = rx.getHead()
rx.tryFlush()
const head = await headPromise
return head === null ? null : head.seed
}
async setSeed (seed, { overwrite = true } = {}) {
if (this.version === 0) await this._migrateStore()
const view = await this._enter()
const tx = new CorestoreTX(view)
try {
const rx = new CorestoreRX(this.db, view)
const headPromise = rx.getHead()
rx.tryFlush()
const head = (await headPromise) || initStoreHead()
if (head.seed === null || overwrite) head.seed = seed
tx.setHead(head)
tx.apply()
return head.seed
} finally {
await this._exit()
}
}
async getDefaultDiscoveryKey () {
if (this.version === 0) await this._migrateStore()
const rx = new CorestoreRX(this.db, EMPTY)
const headPromise = rx.getHead()
rx.tryFlush()
const head = await headPromise
return head === null ? null : head.defaultDiscoveryKey
}
async setDefaultDiscoveryKey (discoveryKey, { overwrite = true } = {}) {
if (this.version === 0) await this._migrateStore()
const view = await this._enter()
const tx = new CorestoreTX(view)
try {
const rx = new CorestoreRX(this.db, view)
const headPromise = rx.getHead()
rx.tryFlush()
const head = (await headPromise) || initStoreHead()
if (head.defaultDiscoveryKey === null || overwrite) head.defaultDiscoveryKey = discoveryKey
tx.setHead(head)
tx.apply()
return head.defaultDiscoveryKey
} finally {
await this._exit()
}
}
async has (discoveryKey) {
if (this.version === 0) await this._migrateStore()
const rx = new CorestoreRX(this.db, EMPTY)
const promise = rx.getCore(discoveryKey)
rx.tryFlush()
return (await promise) !== null
}
async resume (discoveryKey) {
if (this.version === 0) await this._migrateStore()
if (!discoveryKey) {
discoveryKey = await this.getDefaultDiscoveryKey()
if (!discoveryKey) return null
}
const rx = new CorestoreRX(this.db, EMPTY)
const corePromise = rx.getCore(discoveryKey)
rx.tryFlush()
const core = await corePromise
if (core === null) return null
return this._resumeFromPointers(EMPTY, discoveryKey, false, core)
}
async _resumeFromPointers (view, discoveryKey, create, { version, corePointer, dataPointer }) {
const core = { version, corePointer, dataPointer, dependencies: [] }
while (true) {
const rx = new CoreRX({ version, dataPointer, corePointer: 0, dependencies: [] }, this.db, view)
const dependencyPromise = rx.getDependency()
rx.tryFlush()
const dependency = await dependencyPromise
if (!dependency) break
core.dependencies.push(dependency)
dataPointer = dependency.dataPointer
}
const result = new HypercoreStorage(this, this.db.session(), core, EMPTY, null)
if (result.core.version === 0) await this._migrateCore(result, discoveryKey, create)
return result
}
// not allowed to throw validation errors as its a shared tx!
async _create (view, { key, manifest, keyPair, encryptionKey, discoveryKey, alias, userData }) {
const rx = new CorestoreRX(this.db, view)
const tx = new CorestoreTX(view)
const corePromise = rx.getCore(discoveryKey)
const headPromise = rx.getHead()
rx.tryFlush()
let [core, head] = await Promise.all([corePromise, headPromise])
if (core) return this._resumeFromPointers(view, discoveryKey, true, core)
if (head === null) head = initStoreHead()
if (head.defaultDiscoveryKey === null) head.defaultDiscoveryKey = discoveryKey
const corePointer = head.allocated.cores++
const dataPointer = head.allocated.datas++
core = { version: VERSION, corePointer, dataPointer, alias }
tx.setHead(head)
tx.putCore(discoveryKey, core)
if (alias) tx.putCoreByAlias(alias, discoveryKey)
const ptr = { corePointer, dataPointer, dependencies: [] }
const ctx = new CoreTX(ptr, this.db, view, tx.changes)
ctx.setAuth({
key,
discoveryKey,
manifest,
keyPair,
encryptionKey
})
if (userData) {
for (const { key, value } of userData) {
ctx.putUserData(key, value)
}
}
tx.apply()
return new HypercoreStorage(this, this.db.session(), ptr, EMPTY, null)
}
async create (data) {
if (this.version === 0) await this._migrateStore()
const view = await this._enter()
try {
return await this._create(view, data)
} finally {
await this._exit()
}
}
}
module.exports = CorestoreStorage
function initStoreHead () {
return {
version: 0, // cause we wanna run the migration
allocated: {
datas: 0,
cores: 0
},
seed: null,
defaultDiscoveryKey: null
}
}
function getBatch (sessions, name, alloc) {
for (let i = 0; i < sessions.length; i++) {
if (sessions[i].name === name) return sessions[i]
}
if (!alloc) return null
const result = { name, dataPointer: -1 }
sessions.push(result)
return result
}
function isCorestoreStorage (s) {
return typeof s === 'object' && !!s && typeof s.setDefaultDiscoveryKey === 'function'
}
function createColumnFamily (db) {
const col = new RocksDB.ColumnFamily(COLUMN_FAMILY, {
// tuning! atm just the default tuning from rocks, TODO: tweak
enableBlobFiles: false,
minBlobSize: 0,
blobFileSize: 0,
enableBlobGarbageCollection: true,
tableBlockSize: 16384,
tableCacheIndexAndFilterBlocks: true,
tableFormatVersion: 4
})
return db.columnFamily(col)
}