galactic-bot/middleware/ShardManager.js

159 lines
6.2 KiB
JavaScript
Raw Normal View History

/*Adopted from Discord.js */
2020-04-08 18:08:46 +02:00
const EventEmitter = require('events');
2021-06-09 01:45:50 +02:00
const fs = require('fs');
const path = require('path');
2020-04-08 18:08:46 +02:00
2021-06-09 01:45:50 +02:00
const Shard = require('./Shard');
2020-04-09 16:30:52 +02:00
const { Util, Collection } = require('../util/');
2020-04-08 18:08:46 +02:00
2021-06-09 01:45:50 +02:00
class ShardingManager extends EventEmitter {
2020-04-08 18:08:46 +02:00
2020-04-09 16:30:52 +02:00
constructor(file, options = {}) {
2020-04-08 18:08:46 +02:00
super();
options = Util.mergeDefault({
totalShards: 'auto',
mode: 'process',
respawn: true,
shardArgs: [],
execArgv: [],
token: options.bot.token
}, options.shard);
this.file = file;
2021-06-09 01:45:50 +02:00
if (!file) throw new Error('[shardmanager] File must be specified.');
if (!path.isAbsolute(file)) this.file = path.resolve(process.cwd(), file);
2020-04-08 18:08:46 +02:00
const stats = fs.statSync(this.file);
2021-06-09 01:45:50 +02:00
if (!stats.isFile()) throw new Error('[shardmanager] File path does not point to a valid file.');
2020-04-08 18:08:46 +02:00
this.shardList = options.shardList || 'auto';
2021-06-09 01:45:50 +02:00
if (this.shardList !== 'auto') {
if (!Array.isArray(this.shardList)) {
2020-05-08 19:36:28 +02:00
throw new TypeError('[shardmanager] ShardList must be an array.');
2020-04-08 18:08:46 +02:00
}
this.shardList = [...new Set(this.shardList)];
2021-06-09 01:45:50 +02:00
if (this.shardList.length < 1) throw new RangeError('[shardmanager] ShardList must have one ID.');
if (this.shardList.some(shardID => typeof shardID !== 'number' ||
isNaN(shardID) ||
!Number.isInteger(shardID) ||
shardID < 0)
2020-04-08 18:08:46 +02:00
) {
2020-05-08 19:36:28 +02:00
throw new TypeError('[shardmanager] ShardList must be an array of positive integers.');
2020-04-08 18:08:46 +02:00
}
}
this.totalShards = options.totalShards || 'auto';
2021-06-09 01:45:50 +02:00
if (this.totalShards !== 'auto') {
if (typeof this.totalShards !== 'number' || isNaN(this.totalShards)) {
2020-05-08 19:36:28 +02:00
throw new TypeError('[shardmanager] TotalShards must be an integer.');
2020-04-08 18:08:46 +02:00
}
2021-06-09 01:45:50 +02:00
if (this.totalShards < 1) throw new RangeError('[shardmanager] TotalShards must be at least one.');
if (!Number.isInteger(this.totalShards)) {
2020-05-08 19:36:28 +02:00
throw new RangeError('[shardmanager] TotalShards must be an integer.');
2020-04-08 18:08:46 +02:00
}
}
this.mode = options.mode;
2021-06-09 01:45:50 +02:00
if (this.mode !== 'process' && this.mode !== 'worker') {
2020-05-08 19:36:28 +02:00
throw new RangeError('[shardmanager] Mode must be either \'worker\' or \'process\'.');
2020-04-08 18:08:46 +02:00
}
this.respawn = options.respawn;
this.shardArgs = options.shardArgs;
this.execArgv = options.execArgv;
2021-06-09 01:45:50 +02:00
this.token = options.token ? options.token.replace(/^Bot\s*/i, '') : null;
2020-04-08 18:08:46 +02:00
this.shards = new Collection();
process.env.SHARDING_MANAGER = true;
process.env.SHARDING_MANAGER_MODE = this.mode;
process.env.DISCORD_TOKEN = this.token;
}
createShard(id = this.shards.size) {
const shard = new Shard(this, id);
this.shards.set(id, shard);
this.emit('shardCreate', shard);
return shard;
}
2021-06-09 01:45:50 +02:00
async spawn(amount = this.totalShards, delay = 5500, spawnTimeout) {
if (amount === 'auto') {
2020-04-08 18:08:46 +02:00
amount = await Util.fetchRecommendedShards(this.token);
} else {
2021-06-09 01:45:50 +02:00
if (typeof amount !== 'number' || isNaN(amount)) {
2020-05-08 19:36:28 +02:00
throw new TypeError('[shardmanager] Amount of shards must be a number.');
2020-04-08 18:08:46 +02:00
}
2021-06-09 01:45:50 +02:00
if (amount < 1) throw new RangeError('[shardmanager] Amount of shards must be at least one.');
if (!Number.isInteger(amount)) {
2020-05-08 19:36:28 +02:00
throw new TypeError('[shardmanager] Amount of shards must be an integer.');
2020-04-08 18:08:46 +02:00
}
}
2021-06-09 01:45:50 +02:00
// Make sure this many shards haven't already been spawned
if (this.shards.size >= amount) throw new Error('[shardmanager] Already spawned all necessary shards.');
if (this.shardList === 'auto' || this.totalShards === 'auto' || this.totalShards !== amount) {
2020-04-08 18:08:46 +02:00
this.shardList = [...Array(amount).keys()];
}
2021-06-09 01:45:50 +02:00
if (this.totalShards === 'auto' || this.totalShards !== amount) {
2020-04-08 18:08:46 +02:00
this.totalShards = amount;
}
2021-06-09 01:45:50 +02:00
if (this.shardList.some((shardID) => shardID >= amount)) {
2020-05-08 19:36:28 +02:00
throw new RangeError('[shardmanager] Amount of shards cannot be larger than the highest shard ID.');
2020-04-08 18:08:46 +02:00
}
2021-06-09 01:45:50 +02:00
// Spawn the shards
for (const shardID of this.shardList) {
2020-04-08 18:08:46 +02:00
const promises = [];
const shard = this.createShard(shardID);
2021-06-09 01:45:50 +02:00
promises.push(shard.spawn(spawnTimeout));
if (delay > 0 && this.shards.size !== this.shardList.length) promises.push(Util.delayFor(delay));
await Promise.all(promises); // eslint-disable-line no-await-in-loop
2020-04-08 18:08:46 +02:00
}
return this.shards;
}
broadcast(message) {
const promises = [];
2021-06-09 01:45:50 +02:00
for (const shard of this.shards.values()) promises.push(shard.send(message));
2020-04-08 18:08:46 +02:00
return Promise.all(promises);
}
2021-06-09 01:45:50 +02:00
broadcastEval(script, shard) {
return this._performOnShards('eval', [script], shard);
}
fetchClientValues(prop, shard) {
return this._performOnShards('fetchClientValue', [prop], shard);
2020-04-08 18:08:46 +02:00
}
2021-06-09 01:45:50 +02:00
_performOnShards(method, args, shard) {
if (this.shards.size === 0) return Promise.reject(new Error('[shardmanager] No shards available.'));
if (this.shards.size !== this.shardList.length) return Promise.reject(new Error('[shardmanager] Sharding in progress.'));
if (typeof shard === 'number') {
if (this.shards.has(shard)) return this.shards.get(shard)[method](...args);
return Promise.reject(new Error(`[shardmanager] Shard ${shard} not found.`));
}
2020-04-08 18:08:46 +02:00
const promises = [];
2021-06-09 01:45:50 +02:00
for (const sh of this.shards.values()) promises.push(sh[method](...args));
2020-04-08 18:08:46 +02:00
return Promise.all(promises);
}
2021-06-09 01:45:50 +02:00
async respawnAll(shardDelay = 5000, respawnDelay = 500, spawnTimeout) {
2020-04-08 18:08:46 +02:00
let s = 0;
2021-06-09 01:45:50 +02:00
for (const shard of this.shards.values()) {
const promises = [shard.respawn(respawnDelay, spawnTimeout)];
if (++s < this.shards.size && shardDelay > 0) promises.push(Util.delayFor(shardDelay));
await Promise.all(promises); // eslint-disable-line no-await-in-loop
2020-04-08 18:08:46 +02:00
}
return this.shards;
}
}
2021-06-09 01:45:50 +02:00
module.exports = ShardingManager;