hypercore 10.38.1 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/download.js CHANGED
@@ -1,10 +1,39 @@
1
1
  module.exports = class Download {
2
- constructor (req) {
3
- this.req = req
2
+ constructor (session, range) {
3
+ this.session = session
4
+ this.range = range
5
+ this.request = null
6
+ this.opened = false
7
+ this.opening = this._open()
8
+ this.opening.catch(noop)
9
+ }
10
+
11
+ ready () {
12
+ return this.opening
13
+ }
14
+
15
+ async _open () {
16
+ if (this.session.opened === false) await this.session.opening
17
+ this._download()
18
+ this.opened = true
4
19
  }
5
20
 
6
21
  async done () {
7
- return (await this.req).promise
22
+ await this.ready()
23
+
24
+ try {
25
+ return await this.request.promise
26
+ } catch (err) {
27
+ if (isSessionMoved(err)) return this._download()
28
+ throw err
29
+ }
30
+ }
31
+
32
+ _download () {
33
+ const activeRequests = (this.range && this.range.activeRequests) || this.session.activeRequests
34
+ this.request = this.session.core.replicator.addRange(activeRequests, this.range)
35
+ this.request.promise.catch(noop)
36
+ return this.request.promise
8
37
  }
9
38
 
10
39
  /**
@@ -15,8 +44,17 @@ module.exports = class Download {
15
44
  }
16
45
 
17
46
  destroy () {
18
- this.req.then(req => req.context && req.context.detach(req), noop)
47
+ this._destroyBackground().catch(noop)
48
+ }
49
+
50
+ async _destroyBackground () {
51
+ if (this.opened === false) await this.ready()
52
+ if (this.request.context) this.request.context.detach(this.request)
19
53
  }
20
54
  }
21
55
 
22
56
  function noop () {}
57
+
58
+ function isSessionMoved (err) {
59
+ return err.code === 'SESSION_MOVED'
60
+ }