|
| 1 | +const fs = require('fs'); |
| 2 | + |
| 3 | +const Redis = require('ioredis'); |
| 4 | + |
| 5 | +const { config } = require('../../../Config'); |
| 6 | + |
| 7 | +const updateCounterScript = fs.readFileSync(`${__dirname }/updateCounter.lua`).toString(); |
| 8 | + |
| 9 | +const SCRIPTS = { |
| 10 | + updateCounter: { |
| 11 | + numberOfKeys: 1, |
| 12 | + lua: updateCounterScript, |
| 13 | + }, |
| 14 | +}; |
| 15 | + |
| 16 | +class RateLimitClient { |
| 17 | + constructor(redisConfig) { |
| 18 | + this.redis = new Redis({ |
| 19 | + ...redisConfig, |
| 20 | + scripts: SCRIPTS, |
| 21 | + lazyConnect: true, |
| 22 | + }); |
| 23 | + } |
| 24 | + |
| 25 | + /** |
| 26 | + * @typedef {Object} CounterUpdateBatch |
| 27 | + * @property {string} key - counter key |
| 28 | + * @property {number} cost - cost to add to counter |
| 29 | + */ |
| 30 | + |
| 31 | + /** |
| 32 | + * @typedef {Object} CounterUpdateBatchResult |
| 33 | + * @property {string} key - counter key |
| 34 | + * @property {number} value - current value of counter |
| 35 | + */ |
| 36 | + |
| 37 | + /** |
| 38 | + * @callback RateLimitClient~batchUpdate |
| 39 | + * @param {Error|null} err |
| 40 | + * @param {CounterUpdateBatchResult[]|undefined} |
| 41 | + */ |
| 42 | + |
| 43 | + /** |
| 44 | + * Add cost to the counter at key. |
| 45 | + * Returns the new value for the counter |
| 46 | + * |
| 47 | + * @param {CounterUpdateBatch[]} batch - batch of counter updates |
| 48 | + * @param {RateLimitClient~batchUpdate} cb |
| 49 | + */ |
| 50 | + updateLocalCounters(batch, cb) { |
| 51 | + const pipeline = this.redis.pipeline(); |
| 52 | + for (const { key, cost } of batch) { |
| 53 | + pipeline.updateCounter(key, cost); |
| 54 | + } |
| 55 | + |
| 56 | + pipeline.exec((err, results) => { |
| 57 | + if (err) { |
| 58 | + cb(err); |
| 59 | + return; |
| 60 | + } |
| 61 | + |
| 62 | + cb(null, results.map((res, i) => ({ |
| 63 | + key: batch[i].key, |
| 64 | + value: res[1], |
| 65 | + }))); |
| 66 | + }); |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +let counterClient; |
| 71 | +if (config.rateLimiting.enabled) { |
| 72 | + counterClient = new RateLimitClient(config.localCache); |
| 73 | +} |
| 74 | + |
| 75 | +module.exports = { |
| 76 | + counterClient, |
| 77 | + RateLimitClient |
| 78 | +}; |
0 commit comments