work on sharding

This commit is contained in:
Amish Shah
2016-08-31 13:36:05 +01:00
parent cde3bcb3bd
commit 8c3ae2fd90
2 changed files with 33 additions and 1 deletions

29
src/sharding/Shard.js Normal file
View File

@@ -0,0 +1,29 @@
const childProcess = require('child_process');
const path = require('path');
const crypto = require('crypto');
class Shard {
constructor(manager, id) {
this.manager = manager;
this.id = id;
this.process = childProcess.fork(path.resolve(this.manager.file), [id, this.manager.shards.size], { silent: true });
this.process.on('message', m => {
if (m && m.type && m.id) {
}
});
}
send(type, timeout = 60000, data = {}) {
return new Promise((resolve, reject) => {
const id = crypto.randomBytes(16).toString('hex');
this.process.send({
type,
id,
data,
});
});
}
}
module.exports = Shard;

View File

@@ -2,6 +2,8 @@ const childProcess = require('child_process');
const path = require('path');
const EventEmitter = require('events').EventEmitter;
const Collection = require('../util/Collection');
const Shard = require('./Shard');
const crypto = require('crypto');
class ShardingManager extends EventEmitter {
constructor(file, totalShards) {
@@ -12,11 +14,12 @@ class ShardingManager extends EventEmitter {
}
this.totalShards = totalShards;
this.shards = new Collection();
this.waiting = new Collection();
}
createShard() {
const id = this.shards.size;
const shard = childProcess.fork(path.resolve(this.file), [id, this.totalShards], { silent: true });
const shard = new Shard(this, id);
this.shards.set(id, shard);
this.emit('launch', id, shard);
}