embark/lib/core/ipc.js

91 lines
2.1 KiB
JavaScript
Raw Normal View History

2018-06-04 19:36:43 +00:00
let fs = require('./fs.js');
let ipc = require('node-ipc');
class IPC {
constructor(options) {
this.logger = options.logger;
this.socketPath = options.socketPath || fs.dappPath(".embark/embark.ipc");
this.ipcRole = options.ipcRole || "server";
2018-06-04 19:36:43 +00:00
ipc.config.silent = true;
this.connected = false;
2018-06-04 19:36:43 +00:00
}
connect(done) {
const self = this;
2018-06-05 12:37:27 +00:00
function connecting(_socket) {
let connectedBefore = false, alreadyDisconnected = false;
2018-06-04 19:36:43 +00:00
ipc.of['embark'].on('connect',function() {
connectedBefore = true;
if (!alreadyDisconnected) {
self.connected = true;
done();
}
});
ipc.of['embark'].on('disconnect',function() {
self.connected = false;
ipc.disconnect('embark');
// we only want to trigger the error callback the first time
if (!connectedBefore && !alreadyDisconnected) {
alreadyDisconnected = true;
done(new Error("no connection found"));
}
2018-06-04 19:36:43 +00:00
});
}
ipc.connectTo('embark', this.socketPath, connecting);
}
serve() {
2018-06-05 12:37:27 +00:00
ipc.serve(this.socketPath, () => {});
ipc.server.start();
2018-06-04 19:36:43 +00:00
this.logger.info(`pid ${process.pid} listening on ${this.socketPath}`);
}
on(action, done) {
const self = this;
2018-06-04 19:36:43 +00:00
ipc.server.on('message', function(data, socket) {
if (data.action !== action) {
return;
}
let reply = function(replyData) {
self.reply(socket, 'compile', replyData);
2018-06-05 12:37:27 +00:00
};
done(data.message, reply, socket);
2018-06-04 19:36:43 +00:00
});
}
reply(client, action, data) {
ipc.server.emit(client, 'message', {action: action, message: data});
}
once(action, cb) {
ipc.of['embark'].once('message', function(msg) {
if (msg.action !== action) {
return;
}
cb(msg.message);
});
}
request(action, data, cb) {
if (cb) {
this.once(action, cb);
}
2018-06-04 19:36:43 +00:00
ipc.of['embark'].emit('message', {action: action, message: data});
}
isClient() {
return this.ipcRole === 'client';
}
isServer() {
return this.ipcRole === 'server';
}
2018-06-04 19:36:43 +00:00
}
module.exports = IPC;