UNPKG

@splitsoftware/splitio-commons

Version:
83 lines (82 loc) 3.62 kB
import { __extends } from "tslib"; import { forOwn } from '../../utils/lang'; import { ImpressionCountsCacheInMemory } from '../inMemory/ImpressionCountsCacheInMemory'; import { LOG_PREFIX, REFRESH_RATE, TTL_REFRESH } from './constants'; var ImpressionCountsCacheInRedis = /** @class */ (function (_super) { __extends(ImpressionCountsCacheInRedis, _super); function ImpressionCountsCacheInRedis(log, key, redis, impressionCountsCacheSize, refreshRate) { if (refreshRate === void 0) { refreshRate = REFRESH_RATE; } var _this = _super.call(this, impressionCountsCacheSize) || this; _this.log = log; _this.key = key; _this.redis = redis; _this.refreshRate = refreshRate; _this.onFullQueue = function () { _this.postImpressionCountsInRedis(); }; return _this; } ImpressionCountsCacheInRedis.prototype.postImpressionCountsInRedis = function () { var _this = this; var counts = this.pop(); var keys = Object.keys(counts); if (!keys.length) return Promise.resolve(false); var pipeline = this.redis.pipeline(); keys.forEach(function (key) { pipeline.hincrby(_this.key, key, counts[key]); }); return pipeline.exec() .then(function (data) { // If this is the creation of the key on Redis, set the expiration for it in 3600 seconds. if (data && data.length && data.length === keys.length) { return _this.redis.expire(_this.key, TTL_REFRESH); } }) .catch(function (err) { _this.log.error("".concat(LOG_PREFIX, "Error in impression counts pipeline: ").concat(err, ".")); return false; }); }; ImpressionCountsCacheInRedis.prototype.start = function () { this.intervalId = setInterval(this.postImpressionCountsInRedis.bind(this), this.refreshRate); }; ImpressionCountsCacheInRedis.prototype.stop = function () { clearInterval(this.intervalId); return this.postImpressionCountsInRedis(); }; // Async consumer API, used by synchronizer ImpressionCountsCacheInRedis.prototype.getImpressionsCount = function () { var _this = this; return this.redis.hgetall(this.key) .then(function (counts) { if (!Object.keys(counts).length) return undefined; _this.redis.del(_this.key).catch(function () { }); var pf = []; forOwn(counts, function (count, key) { var nameAndTime = key.split('::'); if (nameAndTime.length !== 2) { _this.log.error("".concat(LOG_PREFIX, "Error spliting key ").concat(key)); return; } var timeFrame = parseInt(nameAndTime[1]); if (isNaN(timeFrame)) { _this.log.error("".concat(LOG_PREFIX, "Error parsing time frame ").concat(nameAndTime[1])); return; } var rawCount = parseInt(count); if (isNaN(rawCount)) { _this.log.error("".concat(LOG_PREFIX, "Error parsing raw count ").concat(count)); return; } pf.push({ f: nameAndTime[0], m: timeFrame, rc: rawCount, }); }); return { pf: pf }; }); }; return ImpressionCountsCacheInRedis; }(ImpressionCountsCacheInMemory)); export { ImpressionCountsCacheInRedis };