Overhaul sharding

This commit is contained in:
Schuyler Cebulskie
2017-11-19 01:28:46 -05:00
parent ad69e2ba4c
commit a414e4884f
4 changed files with 132 additions and 58 deletions

View File

@@ -3,6 +3,7 @@ const EventEmitter = require('events');
const path = require('path');
const Util = require('../util/Util');
const { Error } = require('../errors');
const delayFor = require('util').promisify(setTimeout);
/**
* Represents a Shard spawned by the ShardingManager.
@@ -15,6 +16,7 @@ class Shard extends EventEmitter {
*/
constructor(manager, id, args = []) {
super();
/**
* Manager that created the shard
* @type {ShardingManager}
@@ -27,6 +29,12 @@ class Shard extends EventEmitter {
*/
this.id = id;
/**
* Arguments for the shard's process
* @type {string[]}
*/
this.args = args;
/**
* Environment variables for the shard's process
* @type {Object}
@@ -37,20 +45,18 @@ class Shard extends EventEmitter {
CLIENT_TOKEN: this.manager.token,
});
/**
* Process of the shard
* @type {ChildProcess}
*/
this.process = childProcess.fork(path.resolve(this.manager.file), args, {
env: this.env,
}).on('message', this._handleMessage.bind(this));
/**
* Whether the shard's {@link Client} is ready
* @type {boolean}
*/
this.ready = false;
/**
* Process of the shard
* @type {?ChildProcess}
*/
this.process = null;
/**
* Ongoing promises for calls to {@link Shard#eval}, mapped by the `script` they were called with
* @type {Map<string, Promise>}
@@ -65,11 +71,55 @@ class Shard extends EventEmitter {
*/
this._fetches = new Map();
// Handle the death of the process
this.process.once('exit', () => {
this.ready = false;
if (this.manager.respawn) this.manager.createShard(this.id).catch(err => { this.manager.emit('error', err); });
/**
* Listener function for the {@link ChildProcess}' `exit` event
* @type {Function}
*/
this._exitListener = this._handleExit.bind(this);
}
/**
* Forks a child process for the shard.
* <warn>You should not need to call this manually.</warn>
* @param {boolean} [waitForReady=true] Whether to wait until the {@link Client} has become ready before resolving
* @returns {Promise<ChildProcess>}
*/
async spawn(waitForReady = true) {
if (this.process) throw new Error('SHARDING_PROCESS_EXISTS', this.id);
this.process = childProcess.fork(path.resolve(this.manager.file), this.args, { env: this.env })
.on('message', this._handleMessage.bind(this))
.on('exit', this._exitListener);
/**
* Emitted upon the creation of the shard's child process.
* @event Shard#spawn
* @param {ChildProcess} process Child process that was created
*/
this.emit('spawn', this.process);
if (!waitForReady) return this.process;
await new Promise((resolve, reject) => {
this.once('ready', resolve);
this.once('disconnect', () => reject(new Error('SHARDING_READY_DISCONNECTED', this.id)));
this.once('death', () => reject(new Error('SHARDING_READY_DIED', this.id)));
setTimeout(() => reject(new Error('SHARDING_READY_TIMEOUT', this.id)), 30000);
});
return this.process;
}
/**
* Kills and restarts the shard's process.
* @param {number} [delay=500] How long to wait between killing the process and restarting it (in milliseconds)
* @param {boolean} [waitForReady=true] Whether to wait the {@link Client} has become ready before resolving
* @returns {Promise<ChildProcess>}
*/
async respawn(delay = 500, waitForReady = true) {
this.process.removeListener('exit', this._exitListener);
this.process.kill();
this._handleExit(false);
if (delay > 0) await delayFor(delay);
return this.spawn(waitForReady);
}
/**
@@ -215,6 +265,23 @@ class Shard extends EventEmitter {
*/
this.manager.emit('message', this, message);
}
/**
* Handles the shard's process exiting.
* @param {boolean} [respawn=this.manager.respawn] Whether to spawn the shard again
* @private
*/
_handleExit(respawn = this.manager.respawn) {
/**
* Emitted upon the shard's child process exiting.
* @event Shard#death
* @param {ChildProcess} process Child process that exited
*/
this.emit('death', this.process);
this.ready = false;
this.process = null;
if (respawn) this.spawn().catch(err => this.emit('error', err));
}
}
module.exports = Shard;