Shard.js
11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
'use strict';
const EventEmitter = require('events');
const path = require('path');
const { Error } = require('../errors');
const Util = require('../util/Util');
let childProcess = null;
let Worker = null;
/**
* A self-contained shard created by the {@link ShardingManager}. Each one has a {@link ChildProcess} that contains
* an instance of the bot and its {@link Client}. When its child process/worker exits for any reason, the shard will
* spawn a new one to replace it as necessary.
* @extends EventEmitter
*/
class Shard extends EventEmitter {
/**
* @param {ShardingManager} manager Manager that is creating this shard
* @param {number} id ID of this shard
*/
constructor(manager, id) {
super();
if (manager.mode === 'process') childProcess = require('child_process');
else if (manager.mode === 'worker') Worker = require('worker_threads').Worker;
/**
* Manager that created the shard
* @type {ShardingManager}
*/
this.manager = manager;
/**
* ID of the shard in the manager
* @type {number}
*/
this.id = id;
/**
* Arguments for the shard's process (only when {@link ShardingManager#mode} is `process`)
* @type {string[]}
*/
this.args = manager.shardArgs || [];
/**
* Arguments for the shard's process executable (only when {@link ShardingManager#mode} is `process`)
* @type {string[]}
*/
this.execArgv = manager.execArgv;
/**
* Environment variables for the shard's process, or workerData for the shard's worker
* @type {Object}
*/
this.env = Object.assign({}, process.env, {
SHARDING_MANAGER: true,
SHARDS: this.id,
SHARD_COUNT: this.manager.totalShards,
DISCORD_TOKEN: this.manager.token,
});
/**
* Whether the shard's {@link Client} is ready
* @type {boolean}
*/
this.ready = false;
/**
* Process of the shard (if {@link ShardingManager#mode} is `process`)
* @type {?ChildProcess}
*/
this.process = null;
/**
* Worker of the shard (if {@link ShardingManager#mode} is `worker`)
* @type {?Worker}
*/
this.worker = null;
/**
* Ongoing promises for calls to {@link Shard#eval}, mapped by the `script` they were called with
* @type {Map<string, Promise>}
* @private
*/
this._evals = new Map();
/**
* Ongoing promises for calls to {@link Shard#fetchClientValue}, mapped by the `prop` they were called with
* @type {Map<string, Promise>}
* @private
*/
this._fetches = new Map();
/**
* Listener function for the {@link ChildProcess}' `exit` event
* @type {Function}
* @private
*/
this._exitListener = this._handleExit.bind(this, undefined);
}
/**
* Forks a child process or creates a worker thread for the shard.
* <warn>You should not need to call this manually.</warn>
* @param {number} [spawnTimeout=30000] The amount in milliseconds to wait until the {@link Client} has become ready
* before resolving. (-1 or Infinity for no wait)
* @returns {Promise<ChildProcess>}
*/
async spawn(spawnTimeout = 30000) {
if (this.process) throw new Error('SHARDING_PROCESS_EXISTS', this.id);
if (this.worker) throw new Error('SHARDING_WORKER_EXISTS', this.id);
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);
}
this._evals.clear();
this._fetches.clear();
/**
* Emitted upon the creation of the shard's child process/worker.
* @event Shard#spawn
* @param {ChildProcess|Worker} process Child process/worker that was created
*/
this.emit('spawn', this.process || this.worker);
if (spawnTimeout === -1 || spawnTimeout === Infinity) return this.process || this.worker;
await new Promise((resolve, reject) => {
const cleanup = () => {
clearTimeout(spawnTimeoutTimer);
this.off('ready', onReady);
this.off('disconnect', onDisconnect);
this.off('death', onDeath);
};
const onReady = () => {
cleanup();
resolve();
};
const onDisconnect = () => {
cleanup();
reject(new Error('SHARDING_READY_DISCONNECTED', this.id));
};
const onDeath = () => {
cleanup();
reject(new Error('SHARDING_READY_DIED', this.id));
};
const onTimeout = () => {
cleanup();
reject(new Error('SHARDING_READY_TIMEOUT', this.id));
};
const spawnTimeoutTimer = setTimeout(onTimeout, spawnTimeout);
this.once('ready', onReady);
this.once('disconnect', onDisconnect);
this.once('death', onDeath);
});
return this.process || this.worker;
}
/**
* Immediately kills the shard's process/worker and does not restart it.
*/
kill() {
if (this.process) {
this.process.removeListener('exit', this._exitListener);
this.process.kill();
} else {
this.worker.removeListener('exit', this._exitListener);
this.worker.terminate();
}
this._handleExit(false);
}
/**
* Kills and restarts the shard's process/worker.
* @param {number} [delay=500] How long to wait between killing the process/worker and restarting it (in milliseconds)
* @param {number} [spawnTimeout=30000] The amount in milliseconds to wait until the {@link Client} has become ready
* before resolving. (-1 or Infinity for no wait)
* @returns {Promise<ChildProcess>}
*/
async respawn(delay = 500, spawnTimeout) {
this.kill();
if (delay > 0) await Util.delayFor(delay);
return this.spawn(spawnTimeout);
}
/**
* Sends a message to the shard's process/worker.
* @param {*} message Message to send to the shard
* @returns {Promise<Shard>}
*/
send(message) {
return new Promise((resolve, reject) => {
if (this.process) {
this.process.send(message, err => {
if (err) reject(err);
else resolve(this);
});
} else {
this.worker.postMessage(message);
resolve(this);
}
});
}
/**
* Fetches a client property value of the shard.
* @param {string} prop Name of the client property to get, using periods for nesting
* @returns {Promise<*>}
* @example
* shard.fetchClientValue('guilds.cache.size')
* .then(count => console.log(`${count} guilds in shard ${shard.id}`))
* .catch(console.error);
*/
fetchClientValue(prop) {
// Shard is dead (maybe respawning), don't cache anything and error immediately
if (!this.process && !this.worker) return Promise.reject(new Error('SHARDING_NO_CHILD_EXISTS', this.id));
// Cached promise from previous call
if (this._fetches.has(prop)) return this._fetches.get(prop);
const promise = new Promise((resolve, reject) => {
const child = this.process || this.worker;
const listener = message => {
if (!message || message._fetchProp !== prop) return;
child.removeListener('message', listener);
this._fetches.delete(prop);
resolve(message._result);
};
child.on('message', listener);
this.send({ _fetchProp: prop }).catch(err => {
child.removeListener('message', listener);
this._fetches.delete(prop);
reject(err);
});
});
this._fetches.set(prop, promise);
return promise;
}
/**
* Evaluates a script or function on the shard, in the context of the {@link Client}.
* @param {string|Function} script JavaScript to run on the shard
* @returns {Promise<*>} Result of the script execution
*/
eval(script) {
// Shard is dead (maybe respawning), don't cache anything and error immediately
if (!this.process && !this.worker) return Promise.reject(new Error('SHARDING_NO_CHILD_EXISTS', this.id));
// Cached promise from previous call
if (this._evals.has(script)) return this._evals.get(script);
const promise = new Promise((resolve, reject) => {
const child = this.process || this.worker;
const listener = message => {
if (!message || message._eval !== script) return;
child.removeListener('message', listener);
this._evals.delete(script);
if (!message._error) resolve(message._result);
else reject(Util.makeError(message._error));
};
child.on('message', listener);
const _eval = typeof script === 'function' ? `(${script})(this)` : script;
this.send({ _eval }).catch(err => {
child.removeListener('message', listener);
this._evals.delete(script);
reject(err);
});
});
this._evals.set(script, promise);
return promise;
}
/**
* Handles a message received from the child process/worker.
* @param {*} message Message received
* @private
*/
_handleMessage(message) {
if (message) {
// Shard is ready
if (message._ready) {
this.ready = true;
/**
* Emitted upon the shard's {@link Client#ready} event.
* @event Shard#ready
*/
this.emit('ready');
return;
}
// Shard has disconnected
if (message._disconnect) {
this.ready = false;
/**
* Emitted upon the shard's {@link Client#disconnect} event.
* @event Shard#disconnect
*/
this.emit('disconnect');
return;
}
// Shard is attempting to reconnect
if (message._reconnecting) {
this.ready = false;
/**
* Emitted upon the shard's {@link Client#reconnecting} event.
* @event Shard#reconnecting
*/
this.emit('reconnecting');
return;
}
// 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) }),
);
return;
}
// 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) }),
);
return;
}
// 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
});
return;
}
}
/**
* Emitted upon receiving a message from the child process/worker.
* @event Shard#message
* @param {*} message Message that was received
*/
this.emit('message', message);
}
/**
* Handles the shard's process/worker 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/worker exiting.
* @event Shard#death
* @param {ChildProcess|Worker} process Child process/worker that exited
*/
this.emit('death', this.process || this.worker);
this.ready = false;
this.process = null;
this.worker = null;
this._evals.clear();
this._fetches.clear();
if (respawn) this.spawn().catch(err => this.emit('error', err));
}
}
module.exports = Shard;