UNPKG

typepool

Version:

Object pooling inspired by generic-pool - with Typing

367 lines 14.6 kB
"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) { 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) : new P(function (resolve) { resolve(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 (_) 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 __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var assert = __importStar(require("assert")); var Deferred_1 = __importDefault(require("./Deferred")); var PoolResourceStatus; (function (PoolResourceStatus) { PoolResourceStatus[PoolResourceStatus["Created"] = 0] = "Created"; PoolResourceStatus[PoolResourceStatus["Ready"] = 1] = "Ready"; PoolResourceStatus[PoolResourceStatus["Destroyed"] = 2] = "Destroyed"; })(PoolResourceStatus = exports.PoolResourceStatus || (exports.PoolResourceStatus = {})); var Pool = /** @class */ (function () { function Pool(factory, opts) { var _this = this; if (opts === void 0) { opts = {}; } this.factory = factory; this.resources = Array(); this.killed = false; this.running = true; /** * Create a resource * * @returns {Promise<IPoolResource>} */ this.createResource = function () { return __awaiter(_this, void 0, void 0, function () { var poolResource; return __generator(this, function (_a) { assert.ok(this.running, "Pool is not running"); poolResource = { resource: null, status: PoolResourceStatus.Created, reserved: false, createDeferred: new Deferred_1.default() }; this.resources.push(poolResource); this.factory .create() .then(function (resource) { Object.assign(poolResource, { resource: resource, status: PoolResourceStatus.Ready }); poolResource.createDeferred.resolve(resource); return poolResource; }) .catch(function (err) { Object.assign(poolResource, { status: PoolResourceStatus.Destroyed }); poolResource.createDeferred.reject(err); }); return [2 /*return*/, poolResource .createDeferred .promise .then(function () { return poolResource; })]; }); }); }; this.opts = __assign({ min: 0, max: -1, limit: -1 }, opts); this.checkInventory(); } /** * Start the pool */ Pool.prototype.checkInventory = function () { var _a = this.opts, min = _a.min, max = _a.max, limit = _a.limit, activeResources = this.getActiveResources(), activeCount = activeResources.length, availableResources = this.getAvailableResources(), availableCount = availableResources.length, newCount = min < 1 || availableCount >= min ? 0 : min - availableCount, destroyCount = max < 1 || availableCount <= max ? 0 : availableCount - max; // CHECK THE MAX VALUES if (limit > 0 && newCount + activeCount > limit) newCount = limit - availableCount; for (var i = 0; i < newCount; i++) { this.createResource(); } for (var i = 0; i < destroyCount; i++) { this.destroy(availableResources[i].resource); } // Array // .from(Array(this.opts.min).keys()) // .map(this.createResource) }; Object.defineProperty(Pool.prototype, "isRunning", { /** * is running * * @returns {boolean} */ get: function () { return this.running && !this.killed; }, enumerable: true, configurable: true }); Object.defineProperty(Pool.prototype, "isShuttingDown", { /** * is shutting down * * @returns {boolean} */ get: function () { return !this.running && !this.killed; }, enumerable: true, configurable: true }); Object.defineProperty(Pool.prototype, "isShutdown", { /** * is completely shutdown * * @returns {boolean} */ get: function () { return this.killed && !this.running; }, enumerable: true, configurable: true }); /** * Find a pooled resource record * * @param resource * @returns {IPoolResource} */ Pool.prototype.getPoolResource = function (resource) { return this.resources.find(function (it) { return it.resource === resource; }); }; /** * Get all resources * * @returns {List<IPoolResource>} */ Pool.prototype.getResources = function () { return this.resources; }; /** * Get active not destroyed resources * * @returns {List<IPoolResource>} */ Pool.prototype.getActiveResources = function () { return this.resources.filter(function (it) { return it.status < PoolResourceStatus.Destroyed; }); }; /** * Get available - active + not reserved instances * * @returns {any} */ Pool.prototype.getAvailableResources = function () { return this.getActiveResources() .filter(function (it) { return !it.reserved; }); }; Pool.prototype.canCreateResource = function () { var limit = this.opts.limit; return (limit < 1 || this.getActiveResources().length < limit); }; /** * Acquire a resource * * @returns {Promise<any>} */ Pool.prototype.acquire = function () { return __awaiter(this, void 0, void 0, function () { var resources, poolResource, _a, _b, resource, _c; return __generator(this, function (_d) { switch (_d.label) { case 0: assert.ok(this.running, "Pool is not running"); resources = this.getAvailableResources(); if (!(resources.length)) return [3 /*break*/, 1]; _a = resources[0]; return [3 /*break*/, 5]; case 1: if (!this.canCreateResource()) return [3 /*break*/, 3]; return [4 /*yield*/, this.createResource()]; case 2: _b = (_d.sent()); return [3 /*break*/, 4]; case 3: _b = null; _d.label = 4; case 4: _a = _b; _d.label = 5; case 5: poolResource = _a; assert.ok(poolResource, "Could not create pool resource, size=" + this.resources.length + " with max size=" + this.opts.max); // MARK RESERVED poolResource.reserved = true; _c = poolResource.resource; if (_c) return [3 /*break*/, 7]; return [4 /*yield*/, poolResource.createDeferred.promise]; case 6: _c = (_d.sent()); _d.label = 7; case 7: resource = _c; return [4 /*yield*/, this.validate(resource)]; case 8: if (!!(_d.sent())) return [3 /*break*/, 10]; return [4 /*yield*/, this.destroy(resource)]; case 9: _d.sent(); return [2 /*return*/, this.acquire()]; case 10: this.checkInventory(); return [2 /*return*/, poolResource.resource]; } }); }); }; /** * Validate a resource is still valid * * @param resource * @returns {boolean|Promise<boolean>} */ Pool.prototype.validate = function (resource) { return __awaiter(this, void 0, void 0, function () { var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: _a = !this.factory.validate; if (_a) return [3 /*break*/, 2]; return [4 /*yield*/, this.factory.validate(resource)]; case 1: _a = (_b.sent()); _b.label = 2; case 2: return [2 /*return*/, _a]; } }); }); }; /** * Release a resource * * @param resource * @returns {Promise<void>} */ Pool.prototype.release = function (resource) { return __awaiter(this, void 0, void 0, function () { var poolResource; return __generator(this, function (_a) { assert.ok(this.running, "Pool is not running"); poolResource = this.getPoolResource(resource); assert.ok(poolResource, "Unknown pool resource, can not release"); Object.assign(poolResource, { reserved: false }); this.checkInventory(); return [2 /*return*/]; }); }); }; /** * Destroy a resource * * @param resource * @returns {Promise<void>} */ Pool.prototype.destroy = function (resource) { return __awaiter(this, void 0, void 0, function () { var poolResource; return __generator(this, function (_a) { assert.ok(!this.killed, "Pool is not running"); poolResource = this.getPoolResource(resource); if (!poolResource) return [2 /*return*/]; Object.assign(resource, { reserved: true, status: PoolResourceStatus.Destroyed }); // IF NOT ALREADY DESTROYED, START THE PROCESS if (!poolResource.destroyDeferred) { poolResource.destroyDeferred = new Deferred_1.default(); this.factory .destroy(resource) .then(function () { poolResource.destroyDeferred.resolve(); }); } this.checkInventory(); return [2 /*return*/]; }); }); }; /** * Drain the pool */ Pool.prototype.drain = function () { return __awaiter(this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!this.running) return [2 /*return*/]; this.running = false; return [4 /*yield*/, Promise.all(this.resources.map(function (it) { return _this.destroy(it.resource); }))]; case 1: _a.sent(); this.killed = true; return [2 /*return*/]; } }); }); }; return Pool; }()); exports.Pool = Pool; //# sourceMappingURL=ObjectPool.js.map