refactor: reimplement max/min with async
This commit is contained in:
parent
d8844aed6f
commit
1d6d90d62d
|
@ -49,47 +49,45 @@ export class RateLimiterService {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Short-term limit
|
// Short-term limit
|
||||||
const min = () => {
|
const min = async () => {
|
||||||
return new Promise<void>((ok, reject) => {
|
const info = await this.checkLimiter({
|
||||||
this.checkLimiter({
|
id: `${actor}:${limitation.key}:min`,
|
||||||
id: `${actor}:${limitation.key}:min`,
|
duration: limitation.minInterval! * factor,
|
||||||
duration: limitation.minInterval! * factor,
|
max: 1,
|
||||||
max: 1,
|
db: this.redisClient,
|
||||||
db: this.redisClient,
|
|
||||||
}).then((info) => {
|
|
||||||
this.logger.debug(`${actor} ${limitation.key} min remaining: ${info.remaining}`);
|
|
||||||
|
|
||||||
if (info.remaining === 0) {
|
|
||||||
return reject({ code: 'BRIEF_REQUEST_INTERVAL', info });
|
|
||||||
} else {
|
|
||||||
if (hasLongTermLimit) {
|
|
||||||
return max().then(ok, reject);
|
|
||||||
} else {
|
|
||||||
return ok();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
this.logger.debug(`${actor} ${limitation.key} min remaining: ${info.remaining}`);
|
||||||
|
|
||||||
|
if (info.remaining === 0) {
|
||||||
|
// eslint-disable-next-line no-throw-literal
|
||||||
|
throw { code: 'BRIEF_REQUEST_INTERVAL', info };
|
||||||
|
} else {
|
||||||
|
if (hasLongTermLimit) {
|
||||||
|
await max();
|
||||||
|
} else {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Long term limit
|
// Long term limit
|
||||||
const max = () => {
|
const max = async () => {
|
||||||
return new Promise<void>((ok, reject) => {
|
const info = await this.checkLimiter({
|
||||||
this.checkLimiter({
|
id: `${actor}:${limitation.key}`,
|
||||||
id: `${actor}:${limitation.key}`,
|
duration: limitation.duration! * factor,
|
||||||
duration: limitation.duration! * factor,
|
max: limitation.max! / factor,
|
||||||
max: limitation.max! / factor,
|
db: this.redisClient,
|
||||||
db: this.redisClient,
|
|
||||||
}).then((info) => {
|
|
||||||
this.logger.debug(`${actor} ${limitation.key} max remaining: ${info.remaining}`);
|
|
||||||
|
|
||||||
if (info.remaining === 0) {
|
|
||||||
return reject({ code: 'RATE_LIMIT_EXCEEDED', info });
|
|
||||||
} else {
|
|
||||||
return ok();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
this.logger.debug(`${actor} ${limitation.key} max remaining: ${info.remaining}`);
|
||||||
|
|
||||||
|
if (info.remaining === 0) {
|
||||||
|
// eslint-disable-next-line no-throw-literal
|
||||||
|
throw { code: 'RATE_LIMIT_EXCEEDED', info };
|
||||||
|
} else {
|
||||||
|
return;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const hasShortTermLimit = typeof limitation.minInterval === 'number';
|
const hasShortTermLimit = typeof limitation.minInterval === 'number';
|
||||||
|
|
Loading…
Reference in New Issue