Skip to content

Commit

Permalink
clear timeout intervals after finish to free up the memory
Browse files Browse the repository at this point in the history
  • Loading branch information
pofider committed Dec 1, 2016
1 parent 51a08b0 commit 1522c55
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 15 deletions.
20 changes: 7 additions & 13 deletions lib/manager-processes.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,22 +19,25 @@ ScriptsManager.prototype.ensureStarted = function (cb) {

ScriptsManager.prototype.execute = function (inputs, options, cb) {
var self = this;
var isDone = false;

var worker = childProcess.fork(path.join(__dirname, "worker-processes.js"), self.options.forkOptions || {});

worker.on('message', function (m) {
var timeout = setTimeout(function () {
worker.kill();

cb(new Error("Timeout error during executing script"));
}, options.timeout || this.options.timeout).unref();

worker.on('message', function (m) {
if (m.error) {
isDone = true;
clearTimeout(timeout);
var error = new Error(m.error);
error.stack = m.errorStack;
return cb(error);
}

if (m.action === "process-response") {
isDone = true;
clearTimeout(timeout);
return cb(null, m.value);
}

Expand All @@ -57,15 +60,6 @@ ScriptsManager.prototype.execute = function (inputs, options, cb) {
inputs: inputs,
options: options
});

setTimeout(function () {
if (isDone)
return;

worker.kill();

cb(new Error("Timeout error during executing script"));
}, options.timeout || this.options.timeout).unref();
};

ScriptsManager.prototype.kill = function () {
Expand Down
8 changes: 6 additions & 2 deletions lib/manager-servers.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ ScriptsManager.prototype.start = function (cb) {
return;

//TODO we should actually kill only the script that caused timeout and resend other requests from the same worker... some more complicated logic is required here
setTimeout(function () {
reqOptions.timeoutRef = setTimeout(function () {
if (reqOptions.isDone)
return;

Expand All @@ -135,7 +135,7 @@ ScriptsManager.prototype.start = function (cb) {
self._runningRequests = _.without(self._runningRequests, _.findWhere(self._runningRequests, {rid: reqOptions.rid}));

reqOptions.cb(error);
}, reqOptions.timeout || self.options.timeout);
}, reqOptions.timeout || self.options.timeout).unref();
}
});

Expand Down Expand Up @@ -178,6 +178,10 @@ ScriptsManager.prototype.execute = function (inputs, options, cb) {
body: body,
json: true
}, function (err, httpResponse, body) {
if (options.timeoutRef) {
clearTimeout(options.timeoutRef)
}

if (options.isDone)
return;

Expand Down

0 comments on commit 1522c55

Please sign in to comment.