fix: long term / short term limitがないときでもそれぞれ用のnew Limiterとlimiter.getが呼ばれる問題

This commit is contained in:
anatawa12 2024-06-14 17:18:33 +09:00
parent 03c2919b69
commit 28c8d318e1
No known key found for this signature in database
GPG Key ID: 9CA909848B8E4EA6
1 changed files with 22 additions and 20 deletions

View File

@ -32,13 +32,13 @@ export class RateLimiterService {
@bindThis @bindThis
public limit(limitation: IEndpointMeta['limit'] & { key: NonNullable<string> }, actor: string, factor = 1) { public limit(limitation: IEndpointMeta['limit'] & { key: NonNullable<string> }, actor: string, factor = 1) {
{
if (this.disabled) { if (this.disabled) {
return Promise.resolve(); return Promise.resolve();
} }
// Short-term limit // Short-term limit
const min = new Promise<void>((ok, reject) => { const min = () => {
return new Promise<void>((ok, reject) => {
const minIntervalLimiter = new Limiter({ const minIntervalLimiter = new Limiter({
id: `${actor}:${limitation.key}:min`, id: `${actor}:${limitation.key}:min`,
duration: limitation.minInterval! * factor, duration: limitation.minInterval! * factor,
@ -57,16 +57,18 @@ export class RateLimiterService {
return reject({ code: 'BRIEF_REQUEST_INTERVAL', info }); return reject({ code: 'BRIEF_REQUEST_INTERVAL', info });
} else { } else {
if (hasLongTermLimit) { if (hasLongTermLimit) {
return max.then(ok, reject); return max().then(ok, reject);
} else { } else {
return ok(); return ok();
} }
} }
}); });
}); });
};
// Long term limit // Long term limit
const max = new Promise<void>((ok, reject) => { const max = () => {
return new Promise<void>((ok, reject) => {
const limiter = new Limiter({ const limiter = new Limiter({
id: `${actor}:${limitation.key}`, id: `${actor}:${limitation.key}`,
duration: limitation.duration! * factor, duration: limitation.duration! * factor,
@ -88,6 +90,7 @@ export class RateLimiterService {
} }
}); });
}); });
};
const hasShortTermLimit = typeof limitation.minInterval === 'number'; const hasShortTermLimit = typeof limitation.minInterval === 'number';
@ -96,12 +99,11 @@ export class RateLimiterService {
typeof limitation.max === 'number'; typeof limitation.max === 'number';
if (hasShortTermLimit) { if (hasShortTermLimit) {
return min; return min();
} else if (hasLongTermLimit) { } else if (hasLongTermLimit) {
return max; return max();
} else { } else {
return Promise.resolve(); return Promise.resolve();
} }
} }
}
} }