greenlock-express.js/worker.js

63 lines
1.3 KiB
JavaScript
Raw Normal View History

2019-10-27 05:52:19 +00:00
"use strict";
var Worker = module.exports;
2019-10-28 07:06:43 +00:00
// *very* generous, but well below the http norm of 120
var messageTimeout = 30 * 1000;
2019-10-28 09:43:42 +00:00
var msgPrefix = "greenlock:";
2019-10-28 07:06:43 +00:00
Worker.create = function() {
var greenlock = {};
["getAcmeHttp01ChallengeResponse", "get", "notify"].forEach(function(k) {
2019-10-28 07:06:43 +00:00
greenlock[k] = function(args) {
return rpc(k, args);
};
});
2019-10-27 05:52:19 +00:00
var worker = {
2019-10-28 07:06:43 +00:00
serve: function(fn) {
var servers = require("./servers.js").create(greenlock);
2019-10-27 05:52:19 +00:00
fn(servers);
return worker;
},
master: function() {
// ignore
return worker;
}
};
return worker;
};
2019-10-28 07:06:43 +00:00
function rpc(funcname, msg) {
2019-10-27 05:52:19 +00:00
return new Promise(function(resolve, reject) {
var rnd = Math.random()
2019-10-28 09:43:42 +00:00
.toString()
2019-10-27 05:52:19 +00:00
.slice(2)
.toString(16);
2019-10-28 07:06:43 +00:00
var id = msgPrefix + rnd;
2019-10-27 05:52:19 +00:00
var timeout;
function getResponse(msg) {
2019-10-28 07:06:43 +00:00
if (msg._id !== id) {
2019-10-27 05:52:19 +00:00
return;
}
process.removeListener("message", getResponse);
2019-10-27 05:52:19 +00:00
clearTimeout(timeout);
2019-10-28 07:06:43 +00:00
resolve(msg._result);
2019-10-27 05:52:19 +00:00
}
// TODO keep a single listener than just responds
// via a collection of callbacks? or leave as is?
2019-10-27 05:52:19 +00:00
process.on("message", getResponse);
2019-10-28 07:06:43 +00:00
process.send({
_id: id,
_funcname: funcname,
_input: msg
});
2019-10-27 05:52:19 +00:00
timeout = setTimeout(function() {
process.removeListener("message", getResponse);
2019-10-28 07:06:43 +00:00
reject(new Error("worker rpc request timeout"));
}, messageTimeout);
2019-10-27 05:52:19 +00:00
});
}