From 1522c5575cc3b35b071ca2b50c17cfd2a9681831 Mon Sep 17 00:00:00 2001 From: "honza.pofider@seznam.cz" Date: Thu, 1 Dec 2016 12:09:06 +0100 Subject: [PATCH] clear timeout intervals after finish to free up the memory --- lib/manager-processes.js | 20 +++++++------------- lib/manager-servers.js | 8 ++++++-- 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/lib/manager-processes.js b/lib/manager-processes.js index d5c71bd..26b5a0f 100644 --- a/lib/manager-processes.js +++ b/lib/manager-processes.js @@ -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); } @@ -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 () { diff --git a/lib/manager-servers.js b/lib/manager-servers.js index de52037..1d79121 100644 --- a/lib/manager-servers.js +++ b/lib/manager-servers.js @@ -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; @@ -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(); } }); @@ -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;