UNPKG

@splitsoftware/splitio-commons

Version:
70 lines (69 loc) 3.34 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.UniqueKeysCacheInRedis = void 0; var tslib_1 = require("tslib"); var UniqueKeysCacheInMemory_1 = require("../inMemory/UniqueKeysCacheInMemory"); var constants_1 = require("./constants"); var constants_2 = require("./constants"); var sets_1 = require("../../utils/lang/sets"); var UniqueKeysCacheInRedis = /** @class */ (function (_super) { tslib_1.__extends(UniqueKeysCacheInRedis, _super); function UniqueKeysCacheInRedis(log, key, redis, uniqueKeysQueueSize, refreshRate) { if (uniqueKeysQueueSize === void 0) { uniqueKeysQueueSize = constants_1.DEFAULT_CACHE_SIZE; } if (refreshRate === void 0) { refreshRate = constants_1.REFRESH_RATE; } var _this = _super.call(this, uniqueKeysQueueSize) || this; _this.log = log; _this.key = key; _this.redis = redis; _this.refreshRate = refreshRate; _this.onFullQueue = function () { _this.postUniqueKeysInRedis(); }; return _this; } UniqueKeysCacheInRedis.prototype.postUniqueKeysInRedis = function () { var _a; var _this = this; var featureNames = Object.keys(this.uniqueKeysTracker); if (!featureNames.length) return Promise.resolve(false); var uniqueKeysArray = featureNames.map(function (featureName) { var featureKeys = (0, sets_1.setToArray)(_this.uniqueKeysTracker[featureName]); var uniqueKeysPayload = { f: featureName, ks: featureKeys }; return JSON.stringify(uniqueKeysPayload); }); this.clear(); return (_a = this.redis).rpush.apply(_a, tslib_1.__spreadArray([this.key], uniqueKeysArray, false)).then(function (data) { // If this is the creation of the key on Redis, set the expiration for it in 3600 seconds. if (data === featureNames.length) { return _this.redis.expire(_this.key, constants_1.TTL_REFRESH); } }) .catch(function (err) { _this.log.error("".concat(constants_2.LOG_PREFIX, "Error in uniqueKeys pipeline: ").concat(err, ".")); return false; }); }; UniqueKeysCacheInRedis.prototype.start = function () { this.intervalId = setInterval(this.postUniqueKeysInRedis.bind(this), this.refreshRate); }; UniqueKeysCacheInRedis.prototype.stop = function () { clearInterval(this.intervalId); return this.postUniqueKeysInRedis(); }; /** * Async consumer API, used by synchronizer. * @param count - number of items to pop from the queue. If not provided or equal 0, all items will be popped. */ UniqueKeysCacheInRedis.prototype.popNRaw = function (count) { var _this = this; if (count === void 0) { count = 0; } return this.redis.lrange(this.key, 0, count - 1).then(function (uniqueKeyItems) { return _this.redis.ltrim(_this.key, uniqueKeyItems.length, -1) .then(function () { return uniqueKeyItems.map(function (uniqueKeyItem) { return JSON.parse(uniqueKeyItem); }); }); }); }; return UniqueKeysCacheInRedis; }(UniqueKeysCacheInMemory_1.UniqueKeysCacheInMemory)); exports.UniqueKeysCacheInRedis = UniqueKeysCacheInRedis;