-
Notifications
You must be signed in to change notification settings - Fork 24
/
example.mjs
86 lines (65 loc) · 1.56 KB
/
example.mjs
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
import Autobase from './index.js'
import Corestore from 'corestore'
import RAM from 'random-access-memory'
function open (store) {
return store.get('view', { valueEncoding: 'json' })
}
async function apply (nodes, view, base) {
for (const node of nodes) {
if (node.value.add) {
await base.addWriter(Buffer.from(node.value.add, 'hex'))
}
await view.append(node.value)
}
}
const a = new Autobase(makeStore('a'), {
valueEncoding: 'json',
open,
apply
})
await a.ready()
const b = new Autobase(makeStore('b'), a.key, {
valueEncoding: 'json',
open,
apply
})
await b.ready()
a.debug = true
await a.append({
add: b.local.key.toString('hex')
})
await sync(a, b)
console.log('pre append...')
await b.append('sup')
console.log('nu')
async function list (name, base) {
console.log('**** list ' + name + ' ****')
for (let i = 0; i < base.length; i++) {
console.log(i, (await base.get(i)).value)
}
console.log('')
}
async function sync (a, b) {
const s1 = a.store.replicate(true)
const s2 = b.store.replicate(false)
s1.on('error', () => {})
s2.on('error', () => {})
s1.pipe(s2).pipe(s1)
await new Promise(r => setImmediate(r))
await a.update()
await b.update()
s1.destroy()
s2.destroy()
}
async function syncAll () {
console.log('**** sync all ****')
await sync(a, b)
console.log('**** synced a and b ****')
await sync(a, c)
// await sync(b, a)
console.log('**** sync all done ****')
console.log()
}
function makeStore (seed) {
return new Corestore(RAM, { primaryKey: Buffer.alloc(32).fill(seed) })
}