diff --git a/package.json b/package.json index f771347..e06376f 100644 --- a/package.json +++ b/package.json @@ -27,6 +27,7 @@ }, "dependencies": { "ipfs-http-client": "^33.0.1", + "p-queue": "^6.1.0", "peer-id": "^0.12.2", "peer-info": "^0.15.1" }, diff --git a/src/index.js b/src/index.js index be18fa6..a8df829 100644 --- a/src/index.js +++ b/src/index.js @@ -3,18 +3,22 @@ const PeerId = require('peer-id') const dht = require('ipfs-http-client/src/dht') const defaultConfig = require('ipfs-http-client/src/utils/default-config') +const { default: PQueue } = require('p-queue') const DEFAULT_MAX_TIMEOUT = 30e3 // 30 second default const DEFAULT_IPFS_API = { protocol: 'https', port: 443, - host: 'ipfs.io' + host: 'node0.delegate.ipfs.io' } class DelegatedPeerRouting { constructor (api) { this.api = Object.assign({}, defaultConfig(), DEFAULT_IPFS_API, api) this.dht = dht(this.api) + // limit concurrency to avoid request flood in web browser + // (backport of: https://github.com/libp2p/js-libp2p-delegated-peer-routing/pull/12) + this._httpQueue = new PQueue({ concurrency: 4 }) } /** @@ -44,17 +48,13 @@ class DelegatedPeerRouting { options.maxTimeout = options.maxTimeout || DEFAULT_MAX_TIMEOUT - this.dht.findPeer(id, { + this._httpQueue.add(() => this.dht.findPeer(id, { timeout: `${options.maxTimeout}ms`// The api requires specification of the time unit (s/ms) - }, (err, info) => { - if (err) { - if (err.message.includes('not found')) { - return callback() - } - return callback(err) + })).then(res => callback(null, res), err => { + if (err.message.includes('not found')) { + return callback() } - - callback(null, info) + return callback(err) }) } } diff --git a/test/index.spec.js b/test/index.spec.js index b091c8d..4cc7769 100644 --- a/test/index.spec.js +++ b/test/index.spec.js @@ -81,14 +81,14 @@ describe('DelegatedPeerRouting', function () { }) describe('create', () => { - it('should default to https://ipfs.io as the delegate', () => { + it('should default to https://node0.delegate.ipfs.io as the delegate', () => { const router = new DelegatedPeerRouting() expect(router.api).to.include({ 'api-path': '/api/v0/', protocol: 'https', port: 443, - host: 'ipfs.io' + host: 'node0.delegate.ipfs.io' }) })