Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Watch downloads #2

Merged
merged 4 commits into from
Sep 16, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -358,6 +363,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 @@ -446,6 +463,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 @@ -568,6 +590,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