refactor: check if there is rate limit inside min/max function

This commit is contained in:
anatawa12 2024-06-14 17:41:39 +09:00
parent f72c768407
commit 3eb1875804
No known key found for this signature in database
GPG Key ID: 9CA909848B8E4EA6
1 changed files with 30 additions and 40 deletions

View File

@ -50,53 +50,43 @@ export class RateLimiterService {
// Short-term limit // Short-term limit
const min = async () => { const min = async () => {
const info = await this.checkLimiter({ if (limitation.minInterval != null) {
id: `${actor}:${limitation.key}:min`, const info = await this.checkLimiter({
duration: limitation.minInterval! * factor, id: `${actor}:${limitation.key}:min`,
max: 1, duration: limitation.minInterval * factor,
db: this.redisClient, max: 1,
}); db: this.redisClient,
});
this.logger.debug(`${actor} ${limitation.key} min remaining: ${info.remaining}`); this.logger.debug(`${actor} ${limitation.key} min remaining: ${info.remaining}`);
if (info.remaining === 0) {
if (info.remaining === 0) { // eslint-disable-next-line no-throw-literal
// eslint-disable-next-line no-throw-literal throw { code: 'BRIEF_REQUEST_INTERVAL', info };
throw { code: 'BRIEF_REQUEST_INTERVAL', info }; } else {
} else { return;
return; }
} }
}; };
// Long term limit // Long term limit
const max = async () => { const max = async () => {
const info = await this.checkLimiter({ if (limitation.duration != null && limitation.max != null) {
id: `${actor}:${limitation.key}`, const info = await this.checkLimiter({
duration: limitation.duration! * factor, id: `${actor}:${limitation.key}`,
max: limitation.max! / factor, duration: limitation.duration * factor,
db: this.redisClient, max: limitation.max / factor,
}); db: this.redisClient,
});
this.logger.debug(`${actor} ${limitation.key} max remaining: ${info.remaining}`); this.logger.debug(`${actor} ${limitation.key} max remaining: ${info.remaining}`);
if (info.remaining === 0) {
if (info.remaining === 0) { // eslint-disable-next-line no-throw-literal
// eslint-disable-next-line no-throw-literal throw { code: 'RATE_LIMIT_EXCEEDED', info };
throw { code: 'RATE_LIMIT_EXCEEDED', info }; } else {
} else { return;
return; }
} }
}; };
const hasShortTermLimit = typeof limitation.minInterval === 'number'; await min();
await max();
const hasLongTermLimit =
typeof limitation.duration === 'number' &&
typeof limitation.max === 'number';
if (hasShortTermLimit) {
await min();
}
if (hasLongTermLimit) {
await max();
}
} }
} }