Skip to content

Commit

Permalink
Watch downloads (#2)
Browse files Browse the repository at this point in the history
* Watch downloads

* Use event listener changes for (un)watching downloads.

* Remove unused argument

* Use noReply for (un)watching downloads
  • Loading branch information
Frando authored Sep 16, 2020
1 parent 618b3d9 commit aeba9eb
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,10 @@ Emitted when a peer is removed.

Emitted when the feed is appended to, either locally or remotely.

#### `feed.on('download', seq)`

Emitted when a block is downloaded.

# License

MIT
38 changes: 38 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,11 @@ class RemoteCorestore extends EventEmitter {
const remoteCore = this._sessions.get(id)
if (!remoteCore) throw new Error('Invalid RemoteHypercore ID.')
remoteCore._onwait(onWaitId, seq)
},
onDownload ({ id, seq }) {
const remoteCore = this._sessions.get(id)
if (!remoteCore) throw new Error('Invalid RemoteHypercore ID.')
remoteCore._ondownload({ seq })
}
})
this._client.corestore.onRequest(this, {
Expand Down Expand Up @@ -359,6 +364,18 @@ class RemoteHypercore extends Nanoresource {
this._extensions = new Map()
this._onwaits = new FreeMap(1)

// Track listeners for the download event, and enable/disable download watching.
this.on('newListener', (event) => {
if (event === 'download' && !this.listenerCount(event)) {
this._watchDownloads()
}
})
this.on('removeListener', (event) => {
if (event === 'download' && !this.listenerCount(event)) {
this._unwatchDownloads()
}
})

if (!this.lazy) this.ready(() => {})
}

Expand Down Expand Up @@ -447,6 +464,11 @@ class RemoteHypercore extends Nanoresource {
ext.onmessage(data, remotePeer)
}

_ondownload (rsp) {
// TODO: Add to local bitfield?
this.emit('download', rsp.seq)
}

// Private Methods

_indexOfPeer (remotePublicKey) {
Expand Down Expand Up @@ -569,6 +591,22 @@ class RemoteHypercore extends Nanoresource {
return rsp.bytes
}

async _watchDownloads () {
try {
if (!this.opened) await this.open()
if (this.closed) return
this._client.hypercore.watchDownloadsNoReply({ id: this._id })
} catch (_) {}
}

async _unwatchDownloads () {
try {
if (!this.opened) await this.open()
if (this.closed) return
this._client.hypercore.unwatchDownloadsNoReply({ id: this._id })
} catch (_) {}
}

// Public Methods

append (blocks, cb) {
Expand Down

0 comments on commit aeba9eb

Please sign in to comment.