Skip to content

Commit 233f13d

Browse files
lideljacobheun
authored andcommitted
fix: limit concurrent HTTP requests (#13)
This is a backport of the fix from #12 that works with 0.2.x License: MIT Signed-off-by: Marcin Rataj <[email protected]>
1 parent 92c8e8b commit 233f13d

File tree

3 files changed

+13
-12
lines changed

3 files changed

+13
-12
lines changed

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
},
2828
"dependencies": {
2929
"ipfs-http-client": "^33.0.1",
30+
"p-queue": "^6.1.0",
3031
"peer-id": "^0.12.2",
3132
"peer-info": "^0.15.1"
3233
},

src/index.js

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,22 @@
33
const PeerId = require('peer-id')
44
const dht = require('ipfs-http-client/src/dht')
55
const defaultConfig = require('ipfs-http-client/src/utils/default-config')
6+
const { default: PQueue } = require('p-queue')
67

78
const DEFAULT_MAX_TIMEOUT = 30e3 // 30 second default
89
const DEFAULT_IPFS_API = {
910
protocol: 'https',
1011
port: 443,
11-
host: 'ipfs.io'
12+
host: 'node0.delegate.ipfs.io'
1213
}
1314

1415
class DelegatedPeerRouting {
1516
constructor (api) {
1617
this.api = Object.assign({}, defaultConfig(), DEFAULT_IPFS_API, api)
1718
this.dht = dht(this.api)
19+
// limit concurrency to avoid request flood in web browser
20+
// (backport of: https://github.com/libp2p/js-libp2p-delegated-peer-routing/pull/12)
21+
this._httpQueue = new PQueue({ concurrency: 4 })
1822
}
1923

2024
/**
@@ -44,17 +48,13 @@ class DelegatedPeerRouting {
4448

4549
options.maxTimeout = options.maxTimeout || DEFAULT_MAX_TIMEOUT
4650

47-
this.dht.findPeer(id, {
51+
this._httpQueue.add(() => this.dht.findPeer(id, {
4852
timeout: `${options.maxTimeout}ms`// The api requires specification of the time unit (s/ms)
49-
}, (err, info) => {
50-
if (err) {
51-
if (err.message.includes('not found')) {
52-
return callback()
53-
}
54-
return callback(err)
53+
})).then(res => callback(null, res), err => {
54+
if (err.message.includes('not found')) {
55+
return callback()
5556
}
56-
57-
callback(null, info)
57+
return callback(err)
5858
})
5959
}
6060
}

test/index.spec.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,14 +81,14 @@ describe('DelegatedPeerRouting', function () {
8181
})
8282

8383
describe('create', () => {
84-
it('should default to https://ipfs.io as the delegate', () => {
84+
it('should default to https://node0.delegate.ipfs.io as the delegate', () => {
8585
const router = new DelegatedPeerRouting()
8686

8787
expect(router.api).to.include({
8888
'api-path': '/api/v0/',
8989
protocol: 'https',
9090
port: 443,
91-
host: 'ipfs.io'
91+
host: 'node0.delegate.ipfs.io'
9292
})
9393
})
9494

0 commit comments

Comments
 (0)