manticore
Version:
Mythical multi-process worker pool
85 lines (84 loc) • 2.82 kB
JavaScript
'use strict';
var assertMod = require('assert');
var typeOf = require('type-detect');
exports.TASK_RUN = 'task_run';
exports.TASK_RESULT = 'task_result';
exports.TASK_ABORT = 'task_abort';
exports.WORKER_DOWN = 'worker_down';
exports.WORKER_READY = 'worker_ready';
exports.ERROR = 'error';
exports.WORK_TO_CLIENT = 3;
exports.CLIENT_TO_WORK = 4;
exports.STATUS = 'status';
function assertProp(value, prop, type) {
assertMod(typeOf(value) === 'object', 'expected value to be an object');
assertMod(typeOf(value[prop]) === type, 'expected value.' + prop + ' to be a ' + type);
}
exports.assertProp = assertProp;
function assertType(value, type, label) {
assertMod(typeOf(value) === type, 'expected ' + (label || value) + ' to be a ' + type);
}
exports.assertType = assertType;
function optValue(value, alt) {
if (typeOf(value) !== 'undefined') {
return value;
}
return alt;
}
exports.optValue = optValue;
var timerIDI = 0;
var baseTime = Date.now();
var BumpTimeout = (function () {
function BumpTimeout(delay, call, unRef) {
if (typeof unRef === "undefined") { unRef = true; }
var _this = this;
// setTimeout that gets reaised a lot so limit resets on bumps
this._end = 0;
this._delay = 0;
this._timer = null;
this._bumped = Date.now();
this._prev = Date.now();
this._id = timerIDI++;
this._delay = delay;
this._call = call;
this._unRef = unRef;
this._check = function () {
var now = Date.now();
if (now < _this._end) {
clearTimeout(_this._timer);
_this._timer = setTimeout(_this._check, _this._end - now);
if (_this._unRef) {
_this._timer.unref();
}
} else {
// console.log('timeout #%s call %s %s', this._id, (now - this._prev), this._delay);
_this._call();
_this._prev = now;
_this._end = 0;
}
};
this.next();
}
BumpTimeout.prototype.next = function () {
var now = Date.now();
var end = now + this._delay;
// console.log('timeout #%s next %s %s', this._id, (now - this._bumped), this._delay);
this._bumped = now;
if (end < this._end || this._end === 0) {
clearTimeout(this._timer);
this._timer = setTimeout(this._check, this._delay);
this._timer.unref();
if (this._unRef) {
this._timer.unref();
}
}
this._end = end;
};
BumpTimeout.prototype.clear = function () {
clearTimeout(this._timer);
this._timer = null;
this._end = 0;
};
return BumpTimeout;
})();
exports.BumpTimeout = BumpTimeout;