greenlock-express.js/worker.js

76 lines
2.0 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() {
2019-11-01 21:14:07 +00:00
var greenlock = {};
2019-11-03 03:01:29 +00:00
["getAcmeHttp01ChallengeResponse", "get", "notify", "_notify"].forEach(function(k) {
2019-11-01 21:14:07 +00:00
greenlock[k] = function(args) {
return rpc(k, args);
};
});
2019-10-27 05:52:19 +00:00
2019-11-01 21:14:07 +00:00
var worker = {
2019-11-03 08:28:37 +00:00
ready: function(fn) {
2019-11-01 21:14:07 +00:00
var servers = require("./servers.js").create(greenlock);
fn(servers);
return worker;
},
master: function() {
// ignore
return worker;
2019-11-05 18:50:38 +00:00
},
serve: function(fn) {
// keeping backwards compat
if (1 === fn.length) {
worker.ready(fn);
return;
}
// serving the express app, right away
worker.ready(function(glx) {
glx.serveApp(fn);
});
2019-11-01 21:14:07 +00:00
}
};
2019-11-03 08:28:37 +00:00
// backwards compat starts early...
worker.serve = worker.ready;
2019-11-01 21:14:07 +00:00
return worker;
2019-10-27 05:52:19 +00:00
};
2019-10-28 07:06:43 +00:00
function rpc(funcname, msg) {
2019-11-01 21:14:07 +00:00
return new Promise(function(resolve, reject) {
var rnd = Math.random()
.toString()
.slice(2)
.toString(16);
var id = msgPrefix + rnd;
var timeout;
2019-10-27 05:52:19 +00:00
2019-11-01 21:14:07 +00:00
function getResponse(msg) {
if (msg._id !== id) {
return;
}
process.removeListener("message", getResponse);
clearTimeout(timeout);
resolve(msg._result);
}
2019-10-27 05:52:19 +00:00
2019-11-01 21:14:07 +00:00
// TODO keep a single listener than just responds
// via a collection of callbacks? or leave as is?
process.on("message", getResponse);
process.send({
_id: id,
_funcname: funcname,
_input: msg
});
2019-10-27 05:52:19 +00:00
2019-11-01 21:14:07 +00:00
timeout = setTimeout(function() {
process.removeListener("message", getResponse);
reject(new Error("worker rpc request timeout"));
}, messageTimeout);
});
2019-10-27 05:52:19 +00:00
}