This commit is contained in:
dahyeon committed 2026-04-26 03:33:24 -07:00
1 parent 6d62de4ec4
commit 285f72b3ee
16 files changed
+2095 -136

No files matched your search

@@ -0,0 +1,107 @@
import { Injectable, Logger } from '@nestjs/common';
import type { RiotPlatformRoute, RiotRegionalRoute } from './riot.types';
import { GarnetService } from '../global/garnet/garnet.service';
const APP_LIMITS = [
{ windowMs: 1_000, max: 20 },
{ windowMs: 120_000, max: 100 },
] as const;
const ACQUIRE_SCRIPT = `
local now = tonumber(ARGV[1])
local member = ARGV[2]
local maxWait = 0
for i = 1, #KEYS do
local argIndex = 3 + ((i - 1) * 2)
local windowMs = tonumber(ARGV[argIndex])
local limit = tonumber(ARGV[argIndex + 1])
local key = KEYS[i]
redis.call('ZREMRANGEBYSCORE', key, '-inf', now - windowMs)
local count = redis.call('ZCARD', key)
if count >= limit then
local oldest = redis.call('ZRANGE', key, 0, 0, 'WITHSCORES')
local waitMs = windowMs
if oldest[2] then
waitMs = windowMs - (now - tonumber(oldest[2])) + 1
end
if waitMs > maxWait then
maxWait = waitMs
end
end
end
if maxWait > 0 then
return maxWait
end
for i = 1, #KEYS do
local argIndex = 3 + ((i - 1) * 2)
local windowMs = tonumber(ARGV[argIndex])
local key = KEYS[i]
redis.call('ZADD', key, now, member)
redis.call('PEXPIRE', key, windowMs)
end
return 0
`;
@Injectable()
export class RiotRateLimiterService {
private readonly logger = new Logger(RiotRateLimiterService.name);
constructor(private readonly garnet: GarnetService) {}
public async acquire(
route: RiotRegionalRoute | RiotPlatformRoute,
): Promise<void> {
for (;;) {
const now = Date.now();
const waitMs = await this.checkAndAdd(route, now);
if (waitMs <= 0) return;
if (waitMs >= 100) {
this.logger.warn(
`Riot API throttle waiting ${waitMs}ms for route=${route}.`,
);
}
await sleep(waitMs);
}
}
private async checkAndAdd(
route: RiotRegionalRoute | RiotPlatformRoute,
now: number,
): Promise<number> {
const client = this.garnet.raw();
const keys = APP_LIMITS.map(
(limit) => `riot:rl:${route}:${limit.windowMs}`,
);
const member = `${process.pid}:${now}:${Math.random().toString(36).slice(2)}`;
const argumentsList = [
String(now),
member,
...APP_LIMITS.flatMap((limit) => [
String(limit.windowMs),
String(limit.max),
]),
];
const response = await client.sendCommand([
'EVAL',
ACQUIRE_SCRIPT,
String(keys.length),
...keys,
...argumentsList,
]);
const waitMs = Number(response ?? 0);
if (!Number.isFinite(waitMs) || waitMs < 0) return 0;
return waitMs;
}
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}