This repository has been archived by the owner on Jun 4, 2024. It is now read-only.
forked from Nuhvi/hyperdrive-next
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
455 lines (356 loc) · 10.1 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
const Hyperbee = require('hyperbee')
const Hyperblobs = require('hyperblobs')
const isOptions = require('is-options')
const { EventEmitter } = require('events')
const { Writable, Readable } = require('streamx')
module.exports = class HyperBundle extends EventEmitter {
constructor (corestore, key, opts = {}) {
super()
if (isOptions(key)) {
opts = key
key = null
}
const { _checkout, _db, _files, onwait } = opts
this._onwait = onwait || null
this.corestore = corestore
this.db = _db || makeBee(key, corestore, this._onwait)
this.files = _files || this.db.sub('files')
this.blobs = null
this.opening = this._open()
this.opening.catch(noop)
this.opened = false
this._openingBlobs = null
this._checkout = _checkout || null
this._batching = !!_files
this._closing = null
}
[Symbol.asyncIterator] () {
return this.entries()[Symbol.asyncIterator]()
}
get key () {
return this.core.key
}
get discoveryKey () {
return this.core.discoveryKey
}
get contentKey () {
return this.blobs?.core.key
}
get core () {
return this.db.feed
}
get version () {
return this.db.version
}
findingPeers () {
return this.db.feed.findingPeers()
}
update () {
return this.db.feed.update()
}
ready () {
return this.opening
}
checkout (len) {
return new HyperBundle(this.corestore, this.key, {
onwait: this._onwait,
_checkout: this,
_db: this.db.checkout(len),
_files: null
})
}
batch () {
return new HyperBundle(this.corestore, this.key, {
onwait: this._onwait,
_checkout: null,
_db: this.db,
_files: this.files.batch()
})
}
flush () {
return this.files.flush()
}
close () {
if (this._closing) return this._closing
this._closing = this._close()
return this._closing
}
async _close () {
if (this._batching) return this.files.close()
try {
await this.ready()
await this.blobs.core.close()
await this.db.feed.close()
} catch {}
this.emit('close')
}
async _openBlobsFromHeader (opts) {
if (this.blobs) return true
const header = await this.db.getHeader(opts)
if (!header) return false
if (this.blobs) return true
const blobsKey = header.metadata && header.metadata.contentFeed.subarray(0, 32)
if (!blobsKey || blobsKey.length < 32) throw new Error('Invalid or no Blob store key set')
const blobsCore = this.corestore.get({
key: blobsKey,
cache: false,
onwait: this._onwait
})
await blobsCore.ready()
this.blobs = new Hyperblobs(blobsCore)
this.emit('blobs', this.blobs)
this.emit('content-key', blobsCore.key)
return true
}
async _open () {
if (this._checkout) return this._checkout.ready()
await this._openBlobsFromHeader({ wait: false })
if (this.db.feed.writable && !this.blobs) {
const blobsCore = this.corestore.get({
name: 'blobs',
cache: false,
onwait: this._onwait
})
await blobsCore.ready()
this.blobs = new Hyperblobs(blobsCore)
this.db.metadata.contentFeed = this.blobs.core.key
}
await this.db.ready()
if (!this.blobs) {
// eagerly load the blob store....
this._openingBlobs = this._openBlobsFromHeader()
this._openingBlobs.catch(noop)
}
this.opened = true
this.emit('ready')
}
async getBlobs () {
if (this.blobs) return this.blobs
if (this._checkout) {
this.blobs = await this._checkout.getBlobs()
} else {
await this.ready()
await this._openingBlobs
}
return this.blobs
}
async get (name) {
const node = await this.entry(name)
if (!node?.value.blob) return null
await this.getBlobs()
return this.blobs.get(node.value.blob)
}
async put (name, buf, { executable = false, metadata = null } = {}) {
await this.getBlobs()
const id = await this.blobs.put(buf)
return this.files.put(name, { executable, linkname: null, blob: id, metadata })
}
async del (name) {
if (!this.opened) await this.ready()
return this.files.del(name)
}
async symlink (name, dst, { metadata = null } = {}) {
if (!this.opened) await this.ready()
return this.files.put(name, { executable: false, linkname: dst, blob: null, metadata })
}
entry (name) {
return typeof name === 'string'
? this.files.get(name)
: Promise.resolve(name)
}
diff (length, folder, opts) {
if (typeof folder === 'object' && folder && !opts) return this.diff(length, null, folder)
if (folder) {
if (folder.endsWith('/')) folder = folder.slice(0, -1)
opts = { gt: folder + '/', lt: folder + '0', ...opts }
}
return this.files.createDiffStream(length, opts)
}
async downloadDiff (length, folder, opts) {
const dls = []
for await (const entry of this.diff(length, folder, opts)) {
if (!entry.left) continue
const b = entry.left.value.blob
if (!b) continue
const blobs = await this.getBlobs()
dls.push(blobs.core.download({ start: b.blockOffset, length: b.blockLength }))
}
const proms = []
for (const r of dls) proms.push(r.downloaded())
await Promise.allSettled(proms)
}
async downloadRange (dbRanges, blobRanges) {
const dls = []
await this.ready()
for (const range of dbRanges) {
dls.push(this.db.feed.download(range))
}
const blobs = await this.getBlobs()
for (const range of blobRanges) {
dls.push(blobs.core.download(range))
}
const proms = []
for (const r of dls) proms.push(r.downloaded())
await Promise.allSettled(proms)
}
entries (opts) {
return this.files.createReadStream(opts)
}
async download (folder, opts) {
const dls = []
for await (const entry of this.list(folder, opts)) {
const b = entry.value.blob
if (!b) continue
const blobs = await this.getBlobs()
dls.push(blobs.core.download({ start: b.blockOffset, length: b.blockLength }))
}
const proms = []
for (const r of dls) proms.push(r.downloaded())
await Promise.allSettled(proms)
}
// atm always recursive, but we should add some depth thing to it
list (folder, { recursive = true } = {}) {
if (folder.endsWith('/')) folder = folder.slice(0, -1)
if (recursive === false) return shallowReadStream(this.files, folder, false)
// '0' is binary +1 of /
return folder ? this.entries({ gt: folder + '/', lt: folder + '0' }) : this.entries()
}
readdir (folder) {
if (folder.endsWith('/')) folder = folder.slice(0, -1)
return shallowReadStream(this.files, folder, true)
}
createReadStream (name) {
const self = this
let destroyed = false
let rs = null
const stream = new Readable({
open (cb) {
self.getBlobs().then(onblobs, cb)
function onblobs () {
self.entry(name).then(onnode, cb)
}
function onnode (node) {
if (destroyed) return cb(null)
if (!node) return cb(new Error('Blob does not exist'))
if (!node.value.blob) {
stream.push(null)
return cb(null)
}
rs = self.blobs.createReadStream(node.value.blob)
rs.on('data', function (data) {
if (!stream.push(data)) rs.pause()
})
rs.on('end', function () {
stream.push(null)
})
rs.on('error', function (err) {
stream.destroy(err)
})
cb(null)
}
},
read (cb) {
rs.resume()
cb(null)
},
predestroy () {
destroyed = true
if (rs) rs.destroy()
}
})
return stream
}
createWriteStream (name, { executable = false, metadata = null } = {}) {
const self = this
let destroyed = false
let ws = null
let ondrain = null
let onfinish = null
const stream = new Writable({
open (cb) {
self.getBlobs().then(onblobs, cb)
function onblobs () {
if (destroyed) return cb(null)
ws = self.blobs.createWriteStream()
ws.on('error', function (err) {
stream.destroy(err)
})
ws.on('close', function () {
const err = new Error('Closed')
callOndrain(err)
callOnfinish(err)
})
ws.on('finish', function () {
callOnfinish(null)
})
ws.on('drain', function () {
callOndrain(null)
})
cb(null)
}
},
write (data, cb) {
if (ws.write(data) === true) return cb(null)
ondrain = cb
},
final (cb) {
onfinish = cb
ws.end()
},
predestroy () {
destroyed = true
if (ws) ws.destroy()
}
})
return stream
function callOnfinish (err) {
if (!onfinish) return
const cb = onfinish
onfinish = null
if (err) return cb(err)
self.files.put(name, { executable, linkname: null, blob: ws.id, metadata }).then(() => cb(null), cb)
}
function callOndrain (err) {
if (ondrain) {
const cb = ondrain
ondrain = null
cb(err)
}
}
}
}
function shallowReadStream (files, folder, keys) {
let prev = '/'
return new Readable({
async read (cb) {
let node = null
try {
node = await files.peek({
gt: folder + prev,
lt: folder + '0'
})
} catch (err) {
return cb(err)
}
if (!node) {
this.push(null)
return cb(null)
}
const suffix = node.key.slice(folder.length + 1)
const i = suffix.indexOf('/')
const name = i === -1 ? suffix : suffix.slice(0, i)
prev = '/' + name + '0'
this.push(keys ? name : node)
cb(null)
}
})
}
function noop () {}
function makeBee (key, corestore, onwait) {
const metadataOpts = key
? { key, cache: true, onwait }
: { name: 'db', cache: true, onwait }
const core = corestore.get(metadataOpts)
const metadata = { contentFeed: null }
return new Hyperbee(core, { keyEncoding: 'utf-8', valueEncoding: 'json', metadata })
}