UNPKG

status-sharding

Version:

Welcome to Status Sharding! This package is designed to provide an efficient and flexible solution for sharding Discord bots, allowing you to scale your bot across multiple processes or workers.

95 lines 2.75 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WorkerClient = exports.Worker = void 0; const worker_threads_1 = require("worker_threads"); /** Worker class. */ class Worker { file; /** The worker process. */ process = null; /** The options for the worker process. */ workerOptions; /** Creates an instance of Worker. */ constructor(file, options) { this.file = file; this.workerOptions = { workerData: options.clusterData, ...options, }; } /** Spawns the worker. */ spawn() { return (this.process = new worker_threads_1.Worker(this.file, this.workerOptions)); } /** Respawns the worker. */ async respawn() { await this.kill(); return this.spawn(); } /** Kills the worker. */ async kill() { if (!this.process || !this.process.threadId) { console.warn('No process to kill.'); return false; } try { this.process.terminate(); return new Promise((resolve, reject) => { this.process?.once('exit', () => { this.process?.removeAllListeners?.(); resolve(true); }); this.process?.once('error', (err) => { console.error('Error with worker thread:', err); reject(err); }); }); } catch (error) { console.error('Child termination failed:', error); return false; } } /** Sends a message to the worker. */ send(message) { return new Promise((resolve) => { try { this.process?.postMessage(message); resolve(); } catch (error) { console.error('Data sending failed:', message); throw error; } }); } } exports.Worker = Worker; /** Worker client class. */ class WorkerClient { /** The IPC port of the worker. */ ipc; /** Creates an instance of WorkerClient. */ constructor() { this.ipc = worker_threads_1.parentPort; } /** Respawns the worker. */ send(message) { return new Promise((resolve) => { try { this.ipc?.postMessage(message); resolve(); } catch (error) { console.error('Data sending failed:', message); throw error; } }); } /** Gets the data from the worker. */ getData() { return worker_threads_1.workerData; } } exports.WorkerClient = WorkerClient; //# sourceMappingURL=worker.js.map