|
| 1 | +/** |
| 2 | + * @athenna/ratelimiter |
| 3 | + * |
| 4 | + * (c) João Lenon <lenon@athenna.io> |
| 5 | + * |
| 6 | + * For the full copyright and license information, please view the LICENSE |
| 7 | + * file that was distributed with this source code. |
| 8 | + */ |
| 9 | + |
| 10 | +import { debug } from '#src/debug' |
| 11 | +import { Cache } from '@athenna/cache' |
| 12 | +import { Macroable } from '@athenna/common' |
| 13 | +import { WINDOW_MS } from '#src/constants/window' |
| 14 | +import type { Reserve, RateLimitRule, RateLimitStoreOptions } from '#src/types' |
| 15 | + |
| 16 | +export class RateLimitStore extends Macroable { |
| 17 | + /** |
| 18 | + * Holds the options that will be used to build the rate limiter |
| 19 | + * store. |
| 20 | + */ |
| 21 | + public options: RateLimitStoreOptions |
| 22 | + |
| 23 | + public constructor(options: RateLimitStoreOptions) { |
| 24 | + super() |
| 25 | + |
| 26 | + options.windowMs = options.windowMs ?? WINDOW_MS |
| 27 | + |
| 28 | + this.options = options |
| 29 | + } |
| 30 | + |
| 31 | + public async truncate() { |
| 32 | + await Cache.store(this.options.store).truncate() |
| 33 | + } |
| 34 | + |
| 35 | + /** |
| 36 | + * Get the rate limit buckets from the cache or initialize them. |
| 37 | + */ |
| 38 | + public async getOrInit(key: string, rules: RateLimitRule[]) { |
| 39 | + const cache = Cache.store(this.options.store) |
| 40 | + |
| 41 | + let buckets = await cache.get(key) |
| 42 | + |
| 43 | + if (!buckets) { |
| 44 | + buckets = JSON.stringify(rules.map(() => [])) |
| 45 | + |
| 46 | + await cache.set(key, buckets) |
| 47 | + } |
| 48 | + |
| 49 | + return JSON.parse(buckets) as number[][] |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * Get the defined cooldown if it exists in the cache. |
| 54 | + * If it cannot be found, return 0. |
| 55 | + */ |
| 56 | + public async getCooldown(key: string) { |
| 57 | + const cdKey = `${key}:cooldown` |
| 58 | + |
| 59 | + debug('getting cooldown in %s store for key %s', this.options.store, cdKey) |
| 60 | + |
| 61 | + const cooldown = await Cache.store(this.options.store).get(cdKey) |
| 62 | + |
| 63 | + if (!cooldown) { |
| 64 | + return 0 |
| 65 | + } |
| 66 | + |
| 67 | + return Number(cooldown) |
| 68 | + } |
| 69 | + |
| 70 | + /** |
| 71 | + * Put the key in cooldown for some milliseconds. Also saves |
| 72 | + * the timestamp into the cache for when it will be available |
| 73 | + * again. |
| 74 | + */ |
| 75 | + public async setCooldown(key: string, ms: number) { |
| 76 | + if (!ms || ms <= 0) { |
| 77 | + return |
| 78 | + } |
| 79 | + |
| 80 | + const cdKey = `${key}:cooldown` |
| 81 | + const cdMs = `${Date.now() + ms}` |
| 82 | + |
| 83 | + debug( |
| 84 | + 'setting cooldown of %s ms in %s store for key %s', |
| 85 | + cdMs, |
| 86 | + this.options.store, |
| 87 | + cdKey |
| 88 | + ) |
| 89 | + |
| 90 | + await Cache.store(this.options.store).set(cdKey, cdMs, { ttl: ms }) |
| 91 | + } |
| 92 | + |
| 93 | + /** |
| 94 | + * Try to reserve a token for all rules of the key. If not |
| 95 | + * allowed to reserve, return the maximum waitMs necessary. |
| 96 | + */ |
| 97 | + public async tryReserve(key: string, rules: RateLimitRule[]) { |
| 98 | + debug( |
| 99 | + 'running %s store tryReserve for key %s with rules %o', |
| 100 | + this.options.store, |
| 101 | + key, |
| 102 | + rules |
| 103 | + ) |
| 104 | + |
| 105 | + let wait = 0 |
| 106 | + const now = Date.now() |
| 107 | + const cache = Cache.store(this.options.store) |
| 108 | + const cooldown = await this.getCooldown(key) |
| 109 | + |
| 110 | + if (Number.isFinite(cooldown) && cooldown > now) { |
| 111 | + return { allowed: false, waitMs: cooldown - now } |
| 112 | + } |
| 113 | + |
| 114 | + await cache.delete(`${key}:cooldown`) |
| 115 | + |
| 116 | + const buckets = await this.getOrInit(key, rules) |
| 117 | + |
| 118 | + for (let i = 0; i < rules.length; i++) { |
| 119 | + const bucket = buckets[i] |
| 120 | + const window = this.options.windowMs[rules[i].type] |
| 121 | + |
| 122 | + while (bucket.length && bucket[0] <= now - window) { |
| 123 | + bucket.shift() |
| 124 | + } |
| 125 | + |
| 126 | + if (bucket.length >= rules[i].limit) { |
| 127 | + const earliest = bucket[0] |
| 128 | + const rem = earliest + window - now |
| 129 | + |
| 130 | + if (rem > wait) { |
| 131 | + wait = rem |
| 132 | + } |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + const reserve: Reserve = { allowed: false, waitMs: wait } |
| 137 | + |
| 138 | + if (wait > 0) { |
| 139 | + await cache.set(key, JSON.stringify(buckets)) |
| 140 | + |
| 141 | + return reserve |
| 142 | + } |
| 143 | + |
| 144 | + for (let i = 0; i < rules.length; i++) { |
| 145 | + buckets[i].push(now) |
| 146 | + } |
| 147 | + |
| 148 | + await cache.set(key, JSON.stringify(buckets)) |
| 149 | + |
| 150 | + reserve.waitMs = 0 |
| 151 | + reserve.allowed = true |
| 152 | + |
| 153 | + return reserve |
| 154 | + } |
| 155 | +} |
0 commit comments