copy RateLimiterService from MisskeyIO

This implementation allocates fewer Promises, might help with the
memory leaks
This commit is contained in:
dakkar 2024-09-20 08:35:45 +01:00
parent 7439230401
commit 3f6beb97d2

View File

@ -32,18 +32,11 @@ 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) {
{ return new Promise<void>((ok, reject) => {
if (this.disabled) { if (this.disabled) ok();
return Promise.resolve();
}
// those lines with the "wrong" brace style / indentation are
// done that way so that the *other* lines stay identical to
// Misskey, simplifying merges
// Short-term limit // Short-term limit
// eslint-disable-next-line brace-style const minP = (): void => {
const minP = () => { 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,
@ -62,18 +55,16 @@ export class RateLimiterService {
return reject({ code: 'BRIEF_REQUEST_INTERVAL', info }); return reject({ code: 'BRIEF_REQUEST_INTERVAL', info });
} else { } else {
if (hasLongTermLimit) { if (hasLongTermLimit) {
return maxP().then(ok, reject); return maxP();
} else { } else {
return ok(); return ok();
} }
} }
}); });
// eslint-disable-next-line brace-style };
}); };
// Long term limit // Long term limit
// eslint-disable-next-line brace-style const maxP = (): void => {
const maxP = () => { 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,
@ -94,8 +85,7 @@ export class RateLimiterService {
return ok(); return ok();
} }
}); });
// eslint-disable-next-line brace-style };
}); };
const hasShortTermLimit = typeof limitation.minInterval === 'number'; const hasShortTermLimit = typeof limitation.minInterval === 'number';
@ -104,12 +94,12 @@ export class RateLimiterService {
typeof limitation.max === 'number'; typeof limitation.max === 'number';
if (hasShortTermLimit) { if (hasShortTermLimit) {
return minP(); minP();
} else if (hasLongTermLimit) { } else if (hasLongTermLimit) {
return maxP(); maxP();
} else { } else {
return Promise.resolve(); ok();
} }
} });
} }
} }