futoin-asyncsteps
Version:
Mimic traditional threads in single threaded event loop
151 lines (148 loc) • 7.86 kB
JavaScript
;
/**
* @file
* @author Andrey Galkin <andrey@futoin.org>
*
*
* Copyright 2014-2017 FutoIn Project (https://futoin.org)
* Copyright 2014-2017 Andrey Galkin <andrey@futoin.org>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
var ISync = require('./ISync');
var _require = require('./Errors'),
DefenseRejected = _require.DefenseRejected;
var _require2 = require('./lib/common'),
prev_queue = _require2.prev_queue;
var throttle_sync = function throttle_sync(asp, throttle, step, on_error) {
var root = asp._root;
if (throttle._lock(asp)) {
asp._on_error = on_error;
step.apply(void 0, [asp].concat(_toConsumableArray(asp._call_args)));
} else {
asp._on_cancel = throttle._cancel_handler;
root._next_args = asp._call_args;
prev_queue(root).unshift([step, on_error]);
}
};
/**
* Throttling for AsyncSteps
*/
var Throttle = /*#__PURE__*/function (_ISync) {
/**
* C-tor
* @param {number} [max] - maximum number of simultaneous critical section entries
* @param {number} [period_ms] - time period in milliseconds
* @param {?number} [max_queue] - limit queue length, if set
*/
function Throttle(max) {
var _this;
var period_ms = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1e3;
var max_queue = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
_classCallCheck(this, Throttle);
_this = _callSuper(this, Throttle);
_this._max = max;
_this._current = 0;
var queue = _this._queue = [];
_this._timer = null;
_this._period_ms = period_ms;
_this._max_queue = max_queue;
_this._cancel_handler = function (asi) {
var idx = queue.indexOf(asi);
if (idx >= 0) {
queue.splice(idx, 1);
}
};
return _this;
}
_inherits(Throttle, _ISync);
return _createClass(Throttle, [{
key: "_lock",
value: function _lock(asi) {
this._ensureTimer();
if (this._current >= this._max) {
var queue = this._queue;
var max_queue = this._max_queue;
if (max_queue !== null && queue.length >= max_queue) {
asi.error(DefenseRejected, 'Throttle queue limit');
}
queue.push(asi);
return false;
} else {
this._current += 1;
return true;
}
}
}, {
key: "_ensureTimer",
value: function _ensureTimer() {
var _this2 = this;
if (!this._timer) {
this._timer = setInterval(function () {
_this2._resetPeriod();
}, this._period_ms);
}
}
}, {
key: "_resetPeriod",
value: function _resetPeriod() {
this._current = 0;
var queue = this._queue;
if (!queue.length) {
clearInterval(this._timer);
this._timer = null;
return;
}
var max = this._max;
var current = 0;
while (queue.length && current < max) {
var other_as = queue.shift();
if (other_as.state) {
++current;
var other_root = other_as._root;
other_root._handle_success(other_root._next_args);
}
}
this._current = current;
}
}, {
key: "sync",
value: function sync(as, step, onerror) {
var _this3 = this;
as.add(function (as) {
throttle_sync(as, _this3, step, onerror);
});
}
}]);
}(ISync);
module.exports = Throttle;
//# sourceMappingURL=Throttle.js.map