diff --git a/lib/spider.js b/lib/spider.js index 1fb1b4a..aa6826a 100644 --- a/lib/spider.js +++ b/lib/spider.js @@ -5,6 +5,7 @@ const Emiter = require('events') const bencode = require('bencode') const {Table, Node} = require('./table') const Token = require('./token') +const cpuUsage = require('./cpu-usage') const bootstraps = [{ address: 'router.bittorrent.com', @@ -40,6 +41,8 @@ class Spider extends Emiter { this.ignore = false; // ignore all requests this.walkInterval = 5; + this.cpuLimit = 0; + this.cpuInterval = 10; } send(message, address) { @@ -68,7 +71,7 @@ class Spider extends Emiter { walk() { if(!this.client || this.client.isIdle()) { - if(!this.ignore) + if(!this.ignore && (this.cpuLimit <= 0 || cpuUsage() < this.cpuLimit + this.cpuInterval)) { const node = this.table.shift() if (node) { @@ -90,6 +93,10 @@ class Spider extends Emiter { } onFindNodeRequest(message, address) { + if(this.cpuLimit > 0 && cpuUsage() > this.cpuLimit) { + return + } + const {t: tid, a: {id: nid, target: infohash}} = message if (tid === undefined || target.length != 20 || nid.length != 20) { @@ -107,6 +114,10 @@ class Spider extends Emiter { } onGetPeersRequest(message, address) { + if(this.cpuLimit > 0 && cpuUsage() > this.cpuLimit) { + return + } + const {t: tid, a: {id: nid, info_hash: infohash}} = message if (tid === undefined || infohash.length != 20 || nid.length != 20) { @@ -143,7 +154,10 @@ class Spider extends Emiter { }; this.emit('ensureHash', infohash.toString('hex').toUpperCase(), addressPair) if(this.client && !this.ignore) { - this.client.add(addressPair, infohash); + console.log('cpu usage:' + cpuUsage()) + if(this.cpuLimit <= 0 || cpuUsage() <= this.cpuLimit + this.cpuInterval) { + this.client.add(addressPair, infohash); + } } }