smarter sharding™ (#732)

This commit is contained in:
Gus Caplan
2016-09-23 15:43:16 -05:00
committed by Amish Shah
parent fc9d049cc1
commit 063be5cee2
4 changed files with 18 additions and 12 deletions

View File

@@ -69,7 +69,6 @@
"no-mixed-requires": "error",
"no-new-require": "error",
"no-path-concat": "error",
"no-process-env": "error",
"array-bracket-spacing": "error",
"block-spacing": "error",

View File

@@ -27,6 +27,14 @@ class Client extends EventEmitter {
*/
this.options = mergeDefault(Constants.DefaultOptions, options);
if (!this.options.shard_id && process.env.hasOwnProperty('SHARD_ID')) {
this.options.shard_id = process.env.SHARD_ID;
}
if (!this.options.shard_count && process.env.hasOwnProperty('SHARD_COUNT')) {
this.options.shard_count = process.env.SHARD_COUNT;
}
/**
* The REST manager of the client
* @type {RESTManager}

View File

@@ -26,15 +26,19 @@ class Shard {
* The process of the shard
* @type {ChildProcess}
*/
this.process = childProcess.fork(path.resolve(this.manager.file), [id, this.manager.shards.size]);
this.process.once('exit', () => {
if (this.manager.respawn) this.manager.createShard(this.id);
this.process = childProcess.fork(path.resolve(this.manager.file), [], {
env: {
SHARD_ID: this.id, SHARD_COUNT: this.manager.totalShards,
},
});
this.process.on('message', message => {
this.manager.emit('message', this, message);
});
this.process.once('exit', () => {
if (this.manager.respawn) this.manager.createShard(this.id);
});
}
/**

View File

@@ -69,13 +69,8 @@ class ShardingManager extends EventEmitter {
* @param {number} [amount=this.totalShards] Number of shards to spawn
* @param {number} [delay=5500] How long to wait in between spawning each shard (in milliseconds)
*/
spawn(amount, delay = 5500) {
if (typeof amount !== 'undefined') {
if (typeof amount !== 'number' || isNaN(amount)) throw new TypeError('Amount of shards must be a number.');
if (amount < 1) throw new RangeError('Amount of shards must be at least 1.');
this.totalShards = amount;
}
spawn(amount = this.totalShards, delay = 5500) {
this.totalShards = amount;
this.createShard();
const interval = setInterval(() => {
if (this.shards.size === this.totalShards) clearInterval(interval);