-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
88 lines (70 loc) · 2.11 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
const { OplogMessage, Wakeup } = require('autobase/lib/messages.js')
const c = require('compact-encoding')
module.exports = class AutobaseLightWriter {
constructor (store, key, opts = {}) {
const active = opts.active !== false
const encryptionKey = opts.encryptionKey
const blockEncryptionKey = opts.blockEncryptionKey
this.bootstrap = store.get({ key, active })
this.store = store
this.valueEncoding = opts.valueEncoding || null
this.local = this.store.get({ name: 'autobase-light-writer', active, compat: false, encryptionKey })
if (blockEncryptionKey) this.local.setEncryptionKey(blockEncryptionKey, { block: true })
this.wokeup = false
this.extension = this.bootstrap.registerExtension('autobase', {
onmessage: this._onmessage.bind(this)
})
this.bootstrap.on('peer-add', (peer) => {
if (this.local.opened === false) return
this.extension.send(this._encodeWakeup(), peer)
})
this.ready().catch(noop)
}
get key () {
return this.bootstrap.key
}
get discoveryKey () {
return this.bootstrap.discoveryKey
}
_onmessage (msg, peer) {
if (this.local.opened === false) return
let value = null
try {
value = c.decode(Wakeup, msg)
} catch {
return
}
if (value.type === 0) this.extension.send(this._encodeWakeup(), peer)
}
async ready () {
await this.bootstrap.ready()
await this.local.ready()
if (!this.wokeup) {
this.wokeup = true
this.extension.broadcast(this._encodeWakeup())
}
}
close () {
return this.store.close()
}
_encodeWakeup () {
const writers = [{ key: this.local.key, length: this.local.length }]
return c.encode(Wakeup, { version: 1, type: 1, writers })
}
append (message) {
const value = this.valueEncoding === null ? message : c.encode(this.valueEncoding, message)
const buffer = c.encode(OplogMessage, {
version: 1,
maxSupportedVersion: 1,
digest: null,
checkpoint: null,
node: {
heads: [],
batch: 1,
value
}
})
return this.local.append(buffer)
}
}
function noop () {}