semantic-network
Version:
A utility library for manipulating a list of links that form a semantic interface to a network of resources.
290 lines • 13.5 kB
JavaScript
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.bottleneckLoader = exports.BottleneckLoader = void 0;
var bottleneck_1 = __importDefault(require("bottleneck"));
var anylogger_1 = __importDefault(require("anylogger"));
var log = (0, anylogger_1.default)('Loader');
/**
* Loading service to allow for rate limiting and prioritising concurrent requests and
* being able to cancel some or all requests.
*
* Wraps bottleneck and axios cancellable in the background using es6 promises.
*
*/
var BottleneckLoader = /** @class */ (function () {
function BottleneckLoader(options) {
if (options === void 0) { options = {}; }
this._currentOptions = options;
this._limiter = BottleneckLoader.limiterFactory(options);
this.requests = new Map();
this._limiter.on(BottleneckLoader.event.ERROR, function (error) {
log.error('[Limiter] Error: %s', error);
});
this._limiter.on(BottleneckLoader.event.DEBUG, function (message) {
// this is quite noisy so limiting down to trace
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (log.level === 7) {
log.debug('[Limiter] %s', message);
}
});
}
Object.defineProperty(BottleneckLoader, "defaultOptions", {
/**
*/
get: function () {
return {
// num of jobs that can be running at the same time
maxConcurrent: 5,
// immediately launch the next job
minTime: 0,
// default: how long can the queue get? At this stage unlimited
highWater: null,
// this is actually the default
strategy: bottleneck_1.default.strategy.LEAK,
// use es6 promise over the default Bluebird
Promise: Promise,
};
},
enumerable: false,
configurable: true
});
Object.defineProperty(BottleneckLoader, "defaultStopOptions", {
get: function () {
return {
dropWaitingJobs: true,
};
},
enumerable: false,
configurable: true
});
Object.defineProperty(BottleneckLoader, "event", {
/**
* @see {@link Bottleneck.on}
* @return {{EMPTY: string, IDLE: string, DROPPED: string, DEPLETED: string, DEBUG: string, ERROR: string}}
*/
get: function () {
return {
EMPTY: 'empty',
IDLE: 'idle',
DROPPED: 'dropped',
DEPLETED: 'depleted',
DEBUG: 'debug',
ERROR: 'error',
};
},
enumerable: false,
configurable: true
});
Object.defineProperty(BottleneckLoader.prototype, "limiter", {
/**
* Access to the limiter. Chain the methods of this instance if you require it
*
* @example loader.limiter.on(loader.event.DEBUG, () => {});
* @example itemsInQueue = loader.limiter.queued();
* @example loader.limiter.schedule( ...
*/
get: function () {
return this._limiter;
},
enumerable: false,
configurable: true
});
Object.defineProperty(BottleneckLoader.prototype, "currentOptions", {
/**
* Current options in the limiter
*/
get: function () {
return this._currentOptions;
},
enumerable: false,
configurable: true
});
/**
* Make a new limiter with the options
*/
BottleneckLoader.limiterFactory = function (options) {
log.debug('limiter factory created');
return new bottleneck_1.default(__assign(__assign({}, BottleneckLoader.defaultOptions), options));
};
/**
* This method wraps the limiter scheduler because it cannot deal with multiple requests at the same time on
* the same 'id'. This queues up subsequent requests and then resolves them upon the original request.
*
* This is primarily used for GET requests.
*
* Note: this is a naive implementation of queue clearing.
*
* TODO: cancelled promises need to be cleared out of this queue too
*
* @see https://github.com/SGrondin/bottleneck/issues/68
*
*/
BottleneckLoader.prototype.schedule = function (id, action, options) {
return __awaiter(this, void 0, void 0, function () {
var request, p, p;
var _this = this;
return __generator(this, function (_a) {
log.debug('request queue pending (%s total)', this.requests.size);
request = this.requests.get(id);
if (!request) {
p = new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
var loaderJob, result, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
loaderJob = __assign({}, options).loaderJob;
return [4 /*yield*/, this._limiter.schedule(__assign(__assign({}, loaderJob), { id: id }), action)];
case 1:
result = _a.sent();
// Do this before request is resolved,
// so a request with the same id must now resolve to a new request
log.debug('request queue remove \'%s\'', id);
this.requests.delete(id);
// resolving with chain through to the pending requests
resolve(result);
return [3 /*break*/, 3];
case 2:
error_1 = _a.sent();
// Do this before request is resolved,
// so a request with the same id must now resolve to a new request
this.requests.delete(id);
reject(error_1);
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
}); });
this.requests.set(id, { request: p, promises: [] });
log.debug('request queue add \'%s\'', id);
return [2 /*return*/, p];
}
else {
p = new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
var result, e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, request.request];
case 1:
result = _a.sent();
resolve(result);
return [3 /*break*/, 3];
case 2:
e_1 = _a.sent();
reject(e_1);
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
}); });
request.promises.push(p);
log.debug('request queue resolved \'%s\' (%s in queue)', id, request.promises.length);
return [2 /*return*/, p];
}
return [2 /*return*/];
});
});
};
/**
* This method wraps the limiter scheduler.
*
* This is primarily used for POST, PUT, PATCH, DELETE requests
*/
BottleneckLoader.prototype.submit = function (action, options) {
return this._limiter.schedule(action, options);
};
/**
* Stop all current and pending requests and reset all queues.
*/
BottleneckLoader.prototype.clearAll = function (options) {
return __awaiter(this, void 0, void 0, function () {
var _a, RECEIVED, RUNNING, EXECUTING, QUEUED, itemsQueued, e_2;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = this._limiter.counts(), RECEIVED = _a.RECEIVED, RUNNING = _a.RUNNING, EXECUTING = _a.EXECUTING, QUEUED = _a.QUEUED;
itemsQueued = RECEIVED + QUEUED + RUNNING + EXECUTING;
if (itemsQueued === 0) {
log.debug('no requests to clear');
return [2 /*return*/];
}
log.debug('aborting all request (%s in queue)', itemsQueued);
_b.label = 1;
case 1:
_b.trys.push([1, 3, , 4]);
return [4 /*yield*/, this._limiter.stop(__assign(__assign({}, BottleneckLoader.defaultStopOptions), options))];
case 2:
_b.sent();
this._limiter = BottleneckLoader.limiterFactory(this._currentOptions);
return [3 /*break*/, 4];
case 3:
e_2 = _b.sent();
log.warn('stopping loader failure');
return [3 /*break*/, 4];
case 4: return [2 /*return*/];
}
});
});
};
BottleneckLoader.prototype.getRequest = function (id) {
return this.requests.get(id);
};
return BottleneckLoader;
}());
exports.BottleneckLoader = BottleneckLoader;
var bottleneckLoader = new BottleneckLoader();
exports.bottleneckLoader = bottleneckLoader;
//# sourceMappingURL=bottleneckLoader.js.map