more shard stuff

This commit is contained in:
Amish Shah
2016-08-31 14:04:20 +01:00
parent 631626a3f9
commit 7f09da5d35
2 changed files with 50 additions and 2 deletions

View File

@@ -7,21 +7,41 @@ class Shard {
this.manager = manager;
this.id = id;
this.process = childProcess.fork(path.resolve(this.manager.file), [id, this.manager.shards.size], { silent: true });
this.waitingForResponse = new Map();
this.process.on('message', m => {
if (m && m.type && m.id) {
if (this.waitingForResponse.get(m.id)) {
const resp = this.waitingForResponse.get(m.id);
resp.resolve(m.data);
this.waitingForResponse.delete(m.id);
} else {
const reply = data => {
this.send(m.id);
}
}
}
});
}
send(type, timeout = 60000, data = {}) {
const id = crypto.randomBytes(16).toString('hex');
this._send(id, type, timeout, data);
}
_send(id, type, timeout, data) {
return new Promise((resolve, reject) => {
const id = crypto.randomBytes(16).toString('hex');
this.process.send({
type,
id,
data,
});
this.waitingForResponse.set(id, {
resolve,
});
setTimeout(() => {
reject(new Error('did not receive response'));
this.waitingForResponse.delete(id);
}, timeout);
});
}
}

View File

@@ -0,0 +1,28 @@
const crypto = require('crypto');
class ShardListener {
constructor() {
this.waitingForResponse = new Map();
this.process = process;
}
send(type, timeout = 60000, data = {}) {
return new Promise((resolve, reject) => {
const id = crypto.randomBytes(16).toString('hex');
this.process.send({
type,
id,
data,
});
this.waitingForResponse.set(id, {
resolve,
});
setTimeout(() => {
reject(new Error('did not receive response'));
this.waitingForResponse.delete(id);
}, timeout);
});
}
}
module.exports = ShardListener;