UNPKG

node-cache-redis

Version:

Simplistic node redis cache ready can scale with generic-pool support

340 lines (339 loc) 13.8 kB
"use strict"; 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 (_) 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 }); var util_1 = __importDefault(require("util")); var debug_1 = __importDefault(require("debug")); var generic_pool_1 = __importDefault(require("generic-pool")); var redis_1 = __importDefault(require("redis")); // @ts-ignore var retry_as_promised_1 = __importDefault(require("retry-as-promised")); var helpers_1 = require("./helpers"); var debug = debug_1.default('nodeRedisPool'); var createClient = function (redisOptions) { return new Promise(function (resolve, reject) { debug('Start redis createClient', redisOptions); var client = redis_1.default.createClient(redisOptions); client.on('error', function (err) { debug('Failed redis createClient', err); reject(err); }); client.on('connect', function () { debug('Succeeded redis createClient', redisOptions); resolve(client); }); }); }; var selectDB = function (client, db) { return new Promise(function (resolve, reject) { client.select(db, function (err) { if (err) reject(err); debug('DB selected: ', db); resolve(client); }); }); }; /** * RedisPool */ var RedisPool = /** @class */ (function () { /** * @constructor * @param options * @param options.name - Name your pool * @param * @param * @param options.logger - Inject your custom logger */ function RedisPool(_a) { var _this = this; var name = _a.name, redisOptions = _a.redisOptions, poolOptions = _a.poolOptions, logger = _a.logger; this.name = name || "redisPool-" + helpers_1.genRandomStr(); this.redisOptions = redisOptions; this.poolOptions = poolOptions || {}; this.logger = helpers_1.createLogger(logger); var factory = { create: function () { // for retry var createAttempts = 0; // this is due to the limitation of node-pool ATM // https://github.com/coopernurse/node-pool/issues/161#issuecomment-261109882 return retry_as_promised_1.default(function () { createAttempts += 1; if (createAttempts > 3) { var err = new Error("Failed redis createClient, " + JSON.stringify(redisOptions || {})); err.name = 'CONN_FAILED'; debug('Max conn createAttempts reached: %s, resolving to error:', createAttempts, err); // reset for next try createAttempts = 0; return Promise.resolve(err); } return createClient(redisOptions); }, { max: 10, name: 'factory.create', report: debug }); }, destroy: function (client) { return new Promise(function (resolve) { try { // Flush when closing. client.end(true); debug('Client conn closed. Available count : %s. Pool size: %s', _this.availableCount(), _this.getPoolSize()); _this.logger.log('Client conn closed. Available count : %s. Pool size: %s', _this.availableCount(), _this.getPoolSize()); resolve(); } catch (err) { debug('Failed to destroy connection', err); _this.logger.error('Failed to destroy connection', err); // throw error cause infinite event loop; limitation of node-pool // throw err; } }); } }; // Now that the pool settings are ready create a pool instance. debug('Creating pool', this.poolOptions); this.pool = generic_pool_1.default.createPool(factory, this.poolOptions); this.pool.on('factoryCreateError', function (e) { debug('Errored while connecting Redis', e); _this.logger.error('Errored while connecting Redis', e); }); this.pool.on('factoryDestroyError', function (e) { debug('Errored while destroying Redis conn', e); _this.logger.error('Errored while destroying Redis conn', e); }); } /** * Send redis instructions * @async * @param commandName - Name of the command * @param commandArgs - Args sent to the command * @returns Promise resolve with the result or Error */ RedisPool.prototype.sendCommand = function (commandName, commandArgs) { if (commandArgs === void 0) { commandArgs = []; } return __awaiter(this, void 0, void 0, function () { var conn, sendCommand, result, error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: debug('Executing send_command', commandName, commandArgs); return [4 /*yield*/, this.pool.acquire(this.poolOptions.priorityRange || 1)]; case 1: conn = _a.sent(); if (!conn) { throw new Error('No connection acquired'); } sendCommand = util_1.default.promisify(conn.send_command).bind(conn); _a.label = 2; case 2: _a.trys.push([2, 5, , 7]); return [4 /*yield*/, sendCommand(commandName, commandArgs)]; case 3: result = _a.sent(); return [4 /*yield*/, this.pool.release(conn)]; case 4: _a.sent(); return [3 /*break*/, 7]; case 5: error_1 = _a.sent(); return [4 /*yield*/, this.pool.release(conn)]; case 6: _a.sent(); this.logger.error('Errored send_command', error_1); debug('Errored send_command', error_1); throw error_1; case 7: return [2 /*return*/, result]; } }); }); }; /** * Acquire a Redis connection and use an optional priority. * @async * @param priority - priority list number * @param * @returns Promise resolve with the connection or Error */ RedisPool.prototype.acquire = function (priority, db) { return __awaiter(this, void 0, void 0, function () { var client; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.pool.acquire(priority)]; case 1: client = _a.sent(); if (client instanceof Error) { debug("Couldn't acquire connection to %j", this.redisOptions); this.logger.error("Couldn't acquire connection to %j", this.redisOptions); throw client; } if (db) { this.logger.info('select DB:', db); return [2 /*return*/, selectDB(client, db)]; } return [2 /*return*/, client]; } }); }); }; /** * Release a Redis connection to the pool. * @async * @param client - Redis connection * @returns void */ RedisPool.prototype.release = function (client) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.pool.release(client)]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; /** * Destroy a Redis connection. * @async * @param client - Redis connection * @returns void */ RedisPool.prototype.destroy = function (client) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.pool.destroy(client)]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; /** * Drains the connection pool and call the callback id provided. * @async * @returns Promise */ RedisPool.prototype.drain = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.pool.drain()]; case 1: _a.sent(); return [4 /*yield*/, this.pool.clear()]; case 2: _a.sent(); return [2 /*return*/]; } }); }); }; /** * Returns factory.name for this pool * * @returns Name of the pool */ RedisPool.prototype.getName = function () { return this.name; }; /** * Returns this.redisOptions for this pool * * @returns redis options given */ RedisPool.prototype.getRedisOptions = function () { return this.redisOptions; }; /** * Returns this.poolOptions for this pool * * @returns pool options given */ RedisPool.prototype.getPoolOptions = function () { return this.poolOptions; }; /** * Returns size of the pool * * @returns size of the pool */ RedisPool.prototype.getPoolSize = function () { return this.pool.size; }; /** * Returns available connections count of the pool * * @returns available connections count of the pool */ RedisPool.prototype.availableCount = function () { return this.pool.available; }; /** * Returns pending connections count of the pool * * @returns pending connections count of the pool */ RedisPool.prototype.pendingCount = function () { return this.pool.pending; }; /** * Returns pool status and stats * * @returns pool status and stats */ RedisPool.prototype.status = function () { return { name: this.name, size: this.pool.size, available: this.pool.available, pending: this.pool.pending }; }; return RedisPool; }()); exports.default = RedisPool;