manage caches in SkRateLimiterService

This commit is contained in:
Hazelnoot 2025-10-01 11:30:35 -04:00
parent 338dad9a87
commit b32f3b5019
2 changed files with 32 additions and 32 deletions

View file

@ -5,14 +5,14 @@
import { Inject, Injectable } from '@nestjs/common';
import Redis from 'ioredis';
import type { TimeService } from '@/core/TimeService.js';
import type { EnvService } from '@/core/EnvService.js';
import type { MiUser } from '@/models/_.js';
import { TimeService } from '@/core/TimeService.js';
import { EnvService } from '@/core/EnvService.js';
import { BucketRateLimit, LegacyRateLimit, LimitInfo, RateLimit, hasMinLimit, isLegacyRateLimit, Keyed, hasMaxLimit, disabledLimitInfo, MaxLegacyLimit, MinLegacyLimit } from '@/misc/rate-limit-utils.js';
import { RoleService } from '@/core/RoleService.js';
import { CacheManagementService, type ManagedMemoryKVCache } from '@/core/CacheManagementService.js';
import { ConflictError } from '@/misc/errors/ConflictError.js';
import { DI } from '@/di-symbols.js';
import { MemoryKVCache } from '@/misc/cache.js';
import type { MiUser } from '@/models/_.js';
import type { RoleService } from '@/core/RoleService.js';
// Sentinel value used for caching the default role template.
// Required because MemoryKVCache doesn't support null keys.
@ -30,26 +30,24 @@ interface ParsedLimit {
@Injectable()
export class SkRateLimiterService {
// 1-minute cache interval
private readonly factorCache = new MemoryKVCache<number>(1000 * 60);
// 10-second cache interval
private readonly lockoutCache = new MemoryKVCache<number>(1000 * 10);
private readonly factorCache: ManagedMemoryKVCache<number>;
private readonly lockoutCache: ManagedMemoryKVCache<number>;
private readonly requestCounts = new Map<string, number>();
private readonly disabled: boolean;
constructor(
@Inject('TimeService')
private readonly timeService: TimeService,
@Inject(DI.redisForRateLimit)
private readonly redisClient: Redis.Redis,
@Inject('RoleService')
private readonly roleService: RoleService,
private readonly timeService: TimeService,
@Inject('EnvService')
envService: EnvService,
cacheManagementService: CacheManagementService,
) {
this.factorCache = cacheManagementService.createMemoryKVCache<number>(1000 * 60); // 1m
this.lockoutCache = cacheManagementService.createMemoryKVCache<number>(1000 * 10); // 10s
this.disabled = envService.env.NODE_ENV === 'test';
}