-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
347 lines (281 loc) · 10 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
const { EventEmitter } = require('events')
const datEncoding = require('dat-encoding')
const sub = require('subleveldown')
const crypto = require('hypercore-crypto')
const corestore = require('random-access-corestore')
const collect = require('stream-collector')
const CORESTORE_PREFIX = 'corestore/'
const DISCOVERABLE_PREFIX = 'discoverable/'
const SUBCORE_PREFIX = 'subcore/'
const CORE_PREFIX = 'core/'
class Megastore extends EventEmitter {
constructor (storage, db, networking, opts) {
if (typeof storage !== 'function') storage = path => storage(path)
super()
this.opts = opts
this.storage = storage
this.db = db
this.networking = networking
this._id = Date.now()
if (this.networking) {
this.networking.on('error', err => this.emit('error', err))
this.networking.setReplicatorFactory(async dkey => {
const existing = this._corestoresByDKey.get(dkey)
if (existing) return existing.replicate
try {
const { name, key, opts: coreOpts } = await this._storeIndex.get('corestore/' + dkey)
if (coreOpts.seed === false) return null
const store = this._corestoresByDKey.get(dkey) || this.get(name)
// Inflating the default hypercore here will set the default key and bootstrap replication.
store.default(datEncoding.decode(key))
return store.replicate
} catch (err) {
if (!err.notFound) throw err
return null
}
})
}
this._storeIndex = sub(this.db, 'stores', { valueEncoding: 'json' })
this._keyIndex = sub(this.db, 'keys', { valueEncoding: 'json' })
// The megastore duplicates storage across corestore instances. This top-level cache allows us to
// reuse in-memory hypercores.
this._cores = new Map()
this._corestores = new Map()
this._corestoresByDKey = new Map()
// The set of seeded discovery keys. Created in _reseed.
this._seeding = new Set()
// Default feed keys are cached here so that they can be fetched synchronously. Created in _loadKeys.
this._keys = null
this.isReady = false
this._ready = async () => {
await this._loadKeys()
await (this.networking ? this._reseed() : Promise.resolve())
}
}
_collect(index, prefix) {
return new Promise((resolve, reject) => {
if (prefix) var opts = {
gt: prefix,
lt: prefix + String.fromCharCode(65535)
}
collect(index.createReadStream(opts), (err, list) => {
if (err) return reject(err)
return resolve(list)
})
})
}
async _loadKeys () {
const keyList = await this._collect(this._keyIndex)
this._keys = new Map()
for (const { key, value } of keyList) {
this._keys.set(key, {
publicKey: Buffer.from(value.publicKey, 'hex'),
secretKey: Buffer.from(value.secretKey, 'hex')
})
}
}
_seed (dkey) {
this._seeding.add(dkey)
this.networking.seed(datEncoding.decode(dkey))
}
_unseed (dkey) {
this._seeding.delete(dkey)
this.networking.unseed(datEncoding.decode(dkey))
}
async _seedDiscoverableSubfeeds (dkey) {
const feedList = await this._collect(this._storeIndex, DISCOVERABLE_PREFIX + dkey + '/')
for (const { key, value } of feedList) {
this._seed(key.split('/')[2])
}
}
async _unseedDiscoverableSubfeeds (dkey) {
const feedList = await this._collect(this._storeIndex, DISCOVERABLE_PREFIX + dkey + '/')
for (const { key, value } of feedList) {
this._unseed(key.split('/')[2])
}
}
async _reseed () {
const storeList = await this._collect(this._storeIndex, CORESTORE_PREFIX)
for (let { key, value } of storeList) {
if (value.seed === false) continue
key = key.slice(10)
try {
this._seed(key)
} catch (err) {
// If it could not be seeded, then it was indexed by name
continue
}
}
}
async ready () {
if (this.isReady) return
await this._ready()
this.isReady = true
}
isSeeding (dkey) {
return this._seeding.has(dkey)
}
get (name, opts = {}) {
const self = this
var mainDiscoveryKeyString, mainKeyString
const store = corestore(this.storage, { ...this.opts, ...opts })
const {
get: innerGet,
replicate: innerReplicate,
default: innerGetDefault,
list: innerList
} = store
const wrappedStore = {
default: wrappedDefault,
get: wrappedGet,
replicate: innerReplicate,
list: innerList,
close
}
return wrappedStore
function getCore (getter, coreOpts) {
if (coreOpts && coreOpts.key) {
const existing = self._cores.get(datEncoding.encode(coreOpts.key))
if (existing) {
if (existing.refs.indexOf(name) === -1) existing.refs.push(name)
return existing.core
}
}
const core = getter(coreOpts)
core.on('ready', () => processCore(core, coreOpts))
return core
}
function processCore (core, coreOpts) {
const batch = []
const encodedKey = datEncoding.encode(core.key)
const encodedDiscoveryKey = datEncoding.encode(core.discoveryKey)
const value = {
key: core.key,
seed: opts.seed !== false,
writable: core.writable,
}
batch.push({ type: 'put', key: CORE_PREFIX + encodedDiscoveryKey, value })
self._cores.set(encodedKey, { core, refs: [name] })
if (coreOpts.default || coreOpts.discoverable) {
const record = { name, opts: { ...opts, ...coreOpts }, key: encodedKey, discoveryKey: encodedDiscoveryKey }
batch.push({ type: 'put', key: CORESTORE_PREFIX + name, value: record })
batch.push({ type: 'put', key: CORESTORE_PREFIX + encodedDiscoveryKey, value: record })
self._corestores.set(encodedKey, wrappedStore)
self._corestoresByDKey.set(encodedDiscoveryKey, wrappedStore)
if (coreOpts.default) {
mainDiscoveryKeyString = encodedDiscoveryKey
mainKeyString = encodedKey
self._corestores.set(name, wrappedStore)
} else {
batch.push({ type: 'put', key: DISCOVERABLE_PREFIX + mainDiscoveryKeyString + '/' + encodedDiscoveryKey, value: {}})
}
if (self.networking && opts.seed !== false) {
self._seed(encodedDiscoveryKey)
}
} else {
batch.push({ type: 'put', key: SUBCORE_PREFIX + mainDiscoveryKeyString + '/' + encodedDiscoveryKey, value: {}})
}
self._storeIndex.batch(batch, err => {
if (err) this.emit('error', err)
})
}
function close (cb) {
if (self.networking && mainDiscoveryKeyString && self.isSeeding(mainDiscoveryKeyString)) {
self._unseed(mainDiscoveryKeyString)
}
const cores = innerList()
var pending = 0
// TODO: How do we mark the corestore as closed when the close behavior is here?
for (let [key, core] of cores) {
const outerCore = self._cores.get(key)
if (!outerCore) continue
const { refs } = outerCore
refs.splice(refs.indexOf(name), 1)
if (!refs.length) {
pending++
core.close(err => {
if (err) return cb(err)
self._cores.delete(key)
if (!--pending) return onclosed()
})
}
}
if (!pending) return process.nextTick(onclosed)
function onclosed () {
self._corestores.delete(mainKeyString)
self._corestoresByDKey.delete(mainDiscoveryKeyString)
return cb(null)
}
}
function wrappedDefault (coreOpts) {
if (coreOpts instanceof Buffer) coreOpts = { key: coreOpts }
const key = coreOpts && coreOpts.key
if (!key) {
var keyPair = crypto.keyPair()
var { publicKey, secretKey } = keyPair
self._keys.set(name, keyPair)
self._keyIndex.put(name, {
secretKey: keyPair.secretKey.toString('hex'),
publicKey: keyPair.publicKey.toString('hex')
}, err => {
if (err) return self.emit('error', err)
})
} else {
keyPair = self._keys.get(name)
if (keyPair) secretKey = keyPair.secretKey
}
coreOpts = { ...coreOpts, secretKey, keyPair, default: true }
return getCore(innerGetDefault, coreOpts)
}
function wrappedGet (coreOpts = {}) {
if (coreOpts instanceof Buffer) coreOpts = { key: coreOpts }
return getCore(innerGet, coreOpts)
}
}
async info (opts) {
}
async seed (idx) {
if (idx instanceof Buffer) idx = datEncoding.encode(idx)
const record = await this._storeIndex.get(CORESTORE_PREFIX + idx)
const dkey = datEncoding.decode(record.discoveryKey)
if (!this.networking || this.isSeeding(record.discoveryKey)) return
record.opts.seed = true
await this._storeIndex.batch([
{ type: 'put', key: CORESTORE_PREFIX + idx, value: record },
{ type: 'put', key: CORESTORE_PREFIX + record.discoveryKey, value: record }
])
this._seeding.add(record.discoveryKey)
this.networking.seed(dkey)
await this._seedDiscoverableSubfeeds(record.discoveryKey)
}
async unseed (idx) {
if (idx instanceof Buffer) idx = datEncoding.encode(idx)
const record = await this._storeIndex.get(CORESTORE_PREFIX + idx)
const dkey = datEncoding.decode(record.discoveryKey)
if (!this.networking || !this.isSeeding(record.discoveryKey)) return
record.opts.seed = false
await this._storeIndex.batch([
{ type: 'put', key: CORESTORE_PREFIX + idx, value: record },
{ type: 'put', key: CORESTORE_PREFIX + record.discoveryKey, value: record }
])
this._seeding.delete(record.discoveryKey)
this.networking.unseed(dkey)
await this._unseedDiscoverableSubfeeds(record.discoveryKey)
}
async delete (opts) {
}
async list () {
}
async close () {
return Promise.all([
this.networking ? this.networking.close() : Promise.resolve(),
[...this._corestores].map(([, store]) => new Promise((resolve, reject) => {
store.close(err => {
if (err) return reject(err)
return resolve()
})
}))
])
}
}
module.exports = Megastore