UNPKG

@splitsoftware/splitio-commons

Version:
67 lines (66 loc) 3.08 kB
import { __extends } from "tslib"; import { UniqueKeysCacheInMemory } from '../inMemory/UniqueKeysCacheInMemory'; import { DEFAULT_CACHE_SIZE, REFRESH_RATE, TTL_REFRESH } from './constants'; import { LOG_PREFIX } from './constants'; import { setToArray } from '../../utils/lang/sets'; var UniqueKeysCacheInRedis = /** @class */ (function (_super) { __extends(UniqueKeysCacheInRedis, _super); function UniqueKeysCacheInRedis(log, key, redis, uniqueKeysQueueSize, refreshRate) { if (uniqueKeysQueueSize === void 0) { uniqueKeysQueueSize = DEFAULT_CACHE_SIZE; } if (refreshRate === void 0) { refreshRate = 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 _this = this; var featureNames = Object.keys(this.uniqueKeysTracker); if (!featureNames.length) return Promise.resolve(false); var uniqueKeysArray = featureNames.map(function (featureName) { var featureKeys = setToArray(_this.uniqueKeysTracker[featureName]); var uniqueKeysPayload = { f: featureName, ks: featureKeys }; return JSON.stringify(uniqueKeysPayload); }); this.clear(); return this.redis.rpush(this.key, uniqueKeysArray) .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, TTL_REFRESH); } }) .catch(function (err) { _this.log.error(LOG_PREFIX + "Error in uniqueKeys pipeline: " + 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)); export { UniqueKeysCacheInRedis };