galactic-bot/middleware/Shard.js

264 lines
8.8 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 path = require('path');
2020-04-08 18:08:46 +02:00
2020-04-09 16:30:52 +02:00
const { Util } = require('../util/');
2020-04-08 18:08:46 +02:00
let childProcess = null;
let Worker = null;
2020-04-08 16:27:34 +02:00
class Shard extends EventEmitter {
2021-06-09 01:45:50 +02:00
2020-04-09 16:30:52 +02:00
constructor(manager, id) {
2021-06-09 01:45:50 +02:00
2020-04-08 18:08:46 +02:00
super();
2021-06-09 01:45:50 +02:00
if (manager.mode === 'process') childProcess = require('child_process');
else if (manager.mode === 'worker') Worker = require('worker_threads').Worker; //eslint-disable-line prefer-destructuring
2020-04-08 18:08:46 +02:00
2020-04-09 16:30:52 +02:00
this.manager = manager;
2020-04-08 18:08:46 +02:00
this.id = id;
2020-04-09 16:30:52 +02:00
this.args = manager.shardArgs || [];
this.execArgv = manager.execArgv;
2021-06-09 01:45:50 +02:00
this.env = {
...process.env,
SHARDING_MANAGER: true,
2020-04-08 18:08:46 +02:00
SHARDS: this.id,
2021-06-09 01:45:50 +02:00
SHARD_COUNT: this.manager.totalShards,
DISCORD_TOKEN: this.manager.token
};
2020-04-08 18:08:46 +02:00
this.ready = false;
this.process = null;
this.worker = null;
this._evals = new Map();
this._fetches = new Map();
this._exitListener = this._handleExit.bind(this, undefined);
}
2021-06-09 01:45:50 +02:00
async spawn(spawnTimeout = 30000) {
if (this.process) throw new Error(`[shard${this.id}] Sharding process already exists.`);
if (this.worker) throw new Error(`[shard${this.id}] Sharding worker already exists.`);
if (this.manager.mode === 'process') {
this.process = childProcess
.fork(path.resolve(this.manager.file), this.args, {
env: this.env,
execArgv: this.execArgv
})
.on('message', this._handleMessage.bind(this))
.on('exit', this._exitListener);
} else if (this.manager.mode === 'worker') {
this.worker = new Worker(path.resolve(this.manager.file), { workerData: this.env })
.on('message', this._handleMessage.bind(this))
.on('exit', this._exitListener);
2020-04-08 18:08:46 +02:00
}
2021-06-09 01:45:50 +02:00
this._evals.clear();
this._fetches.clear();
2020-04-08 18:08:46 +02:00
this.emit('spawn', this.process || this.worker);
2021-06-09 01:45:50 +02:00
if (spawnTimeout === -1 || spawnTimeout === Infinity) return this.process || this.worker;
2020-04-08 18:08:46 +02:00
await new Promise((resolve, reject) => {
2021-06-09 01:45:50 +02:00
const cleanup = () => {
clearTimeout(spawnTimeoutTimer);
this.off('ready', onReady);
this.off('disconnect', onDisconnect);
this.off('death', onDeath);
};
2020-04-08 18:08:46 +02:00
2021-06-09 01:45:50 +02:00
const onReady = () => {
cleanup();
resolve();
};
const onDisconnect = () => {
cleanup();
reject(new Error(`[shard${this.id}] Shard disconnected while readying.`));
};
const onDeath = () => {
cleanup();
reject(new Error(`[shard${this.id}] Shard died while readying.`));
};
const onTimeout = () => {
cleanup();
reject(new Error(`[shard${this.id}] Shard timed out while readying.`));
};
2020-04-08 18:08:46 +02:00
2021-06-09 01:45:50 +02:00
const spawnTimeoutTimer = setTimeout(onTimeout, spawnTimeout);
this.once('ready', onReady);
this.once('disconnect', onDisconnect);
this.once('death', onDeath);
});
return this.process || this.worker;
2020-04-08 18:08:46 +02:00
}
kill() {
2021-06-09 01:45:50 +02:00
if (this.process) {
2020-04-08 18:08:46 +02:00
this.process.removeListener('exit', this._exitListener);
this.process.kill();
} else {
this.worker.removeListener('exit', this._exitListener);
this.worker.terminate();
}
this._handleExit(false);
}
2021-06-09 01:45:50 +02:00
async respawn(delay = 500, spawnTimeout) {
2020-04-08 18:08:46 +02:00
this.kill();
2021-06-09 01:45:50 +02:00
if (delay > 0) await Util.delayFor(delay);
return this.spawn(spawnTimeout);
2020-04-08 18:08:46 +02:00
}
send(message) {
return new Promise((resolve, reject) => {
2021-06-09 01:45:50 +02:00
if (this.process) {
this.process.send(message, err => {
if (err) reject(err);
else resolve(this);
2020-04-08 18:08:46 +02:00
});
} else {
this.worker.postMessage(message);
resolve(this);
}
});
}
fetchClientValue(prop) {
2021-06-09 01:45:50 +02:00
// Shard is dead (maybe respawning), don't cache anything and error immediately
if (!this.process && !this.worker) return Promise.reject(new Error(`[shard${this.id}] Shard process missing.`));
// Cached promise from previous call
if (this._fetches.has(prop)) return this._fetches.get(prop);
2020-04-08 18:08:46 +02:00
const promise = new Promise((resolve, reject) => {
const child = this.process || this.worker;
2021-06-09 01:45:50 +02:00
const listener = (message) => {
2021-06-09 01:45:50 +02:00
if (!message || message._fetchProp !== prop) return;
2020-04-08 18:08:46 +02:00
child.removeListener('message', listener);
this._fetches.delete(prop);
resolve(message._result);
};
child.on('message', listener);
2021-06-09 01:45:50 +02:00
this.send({ _fetchProp: prop }).catch((err) => {
2020-04-08 18:08:46 +02:00
child.removeListener('message', listener);
this._fetches.delete(prop);
reject(err);
});
});
2021-06-09 01:45:50 +02:00
2020-04-08 18:08:46 +02:00
this._fetches.set(prop, promise);
return promise;
}
eval(script) {
2021-06-09 01:45:50 +02:00
// Shard is dead (maybe respawning), don't cache anything and error immediately
if (!this.process && !this.worker) return Promise.reject(new Error(`[shard${this.id}] Shard process missing.`));
2020-04-08 18:08:46 +02:00
2021-06-09 01:45:50 +02:00
// Cached promise from previous call
if (this._evals.has(script)) return this._evals.get(script);
2020-04-08 18:08:46 +02:00
const promise = new Promise((resolve, reject) => {
const child = this.process || this.worker;
2021-06-09 01:45:50 +02:00
const listener = (message) => {
2021-06-09 01:45:50 +02:00
if (!message || message._eval !== script) return;
2020-04-08 18:08:46 +02:00
child.removeListener('message', listener);
this._evals.delete(script);
2021-06-09 01:45:50 +02:00
if (!message._error) resolve(message._result);
else reject(Util.makePlainError(message._error));
2020-04-08 18:08:46 +02:00
};
child.on('message', listener);
2021-06-09 01:45:50 +02:00
2020-04-08 18:08:46 +02:00
const _eval = typeof script === 'function' ? `(${script})(this)` : script;
this.send({ _eval }).catch((err) => {
2020-04-08 18:08:46 +02:00
child.removeListener('message', listener);
this._evals.delete(script);
reject(err);
});
});
2021-06-09 01:45:50 +02:00
2020-04-08 18:08:46 +02:00
this._evals.set(script, promise);
return promise;
}
_handleMessage(message) {
2021-06-09 01:45:50 +02:00
if (message) {
// Shard is ready
if (message._ready) {
2020-04-08 18:08:46 +02:00
this.ready = true;
this.emit('ready');
return;
}
2021-06-09 01:45:50 +02:00
// Shard has disconnected
if (message._disconnect) {
2020-04-08 18:08:46 +02:00
this.ready = false;
this.emit('disconnect');
return;
}
2021-06-09 01:45:50 +02:00
// Shard is attempting to reconnect
if (message._reconnecting) {
2020-04-08 18:08:46 +02:00
this.ready = false;
this.emit('reconnecting');
return;
}
2021-06-09 01:45:50 +02:00
// Shard is requesting a property fetch
if (message._sFetchProp) {
const resp = { _sFetchProp: message._sFetchProp, _sFetchPropShard: message._sFetchPropShard };
this.manager.fetchClientValues(message._sFetchProp, message._sFetchPropShard).then(
(results) => this.send({ ...resp, _result: results }),
(err) => this.send({ ...resp, _error: Util.makePlainError(err) })
2020-04-08 18:08:46 +02:00
);
return;
}
2021-06-09 01:45:50 +02:00
// Shard is requesting an eval broadcast
if (message._sEval) {
const resp = { _sEval: message._sEval, _sEvalShard: message._sEvalShard };
this.manager.broadcastEval(message._sEval, message._sEvalShard).then(
(results) => this.send({ ...resp, _result: results }),
(err) => this.send({ ...resp, _error: Util.makePlainError(err) })
2020-04-08 18:08:46 +02:00
);
return;
}
2021-06-09 01:45:50 +02:00
// Shard is requesting a respawn of all shards
if (message._sRespawnAll) {
const { shardDelay, respawnDelay, spawnTimeout } = message._sRespawnAll;
this.manager.respawnAll(shardDelay, respawnDelay, spawnTimeout).catch(() => {
// Do nothing
2020-04-08 18:08:46 +02:00
});
return;
}
}
2020-04-09 16:30:52 +02:00
this.manager.emit('message', this, message);
2020-04-08 18:08:46 +02:00
}
2020-04-09 16:30:52 +02:00
_handleExit(respawn = this.manager.respawn) {
2020-04-08 18:08:46 +02:00
this.emit('death', this.process || this.worker);
2021-06-09 01:45:50 +02:00
2020-04-08 18:08:46 +02:00
this.ready = false;
this.process = null;
this.worker = null;
this._evals.clear();
this._fetches.clear();
2021-06-09 01:45:50 +02:00
if (respawn) this.spawn().catch((err) => this.emit('error', err));
2020-04-08 18:08:46 +02:00
}
2020-04-08 16:27:34 +02:00
}
module.exports = Shard;