All files / server/services rate-limiter.ts

100% Statements 55/55
100% Branches 12/12
100% Functions 14/14
100% Lines 53/53

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156      5x                                       21x   21x     21x 21x   21x 4x     21x 21x           31x 31x   31x 16x 16x 16x     15x 15x 2x 2x           13x 2x 2x     13x 13x 13x 10x 10x 10x     10x                 3x 3x         4x 4x 5x         15x 15x       27x 27x       11x             5x           5x             5x     16x       50x 50x         5x     5x       15x 15x       5x 35x   5x 14x  
import { Logger } from "@shared/logger";
import { config as serverConfig } from "../config";
 
const logger = new Logger("RateLimiter");
 
interface RateLimitEntry {
  timestamps: number[];
  blockedUntil: number;
  lastActivity: number;
}
 
export interface RateLimitConfig {
  maxRequests: number;
  windowMs: number;
  blockDurationMs: number;
}
 
export type RateLimitResult = { allowed: true } | {
  allowed: false;
  retryAfter: number;
};
 
class IdentityRateLimiter {
  private readonly identityLimits = new Map<string, RateLimitEntry>();
  private readonly cleanupInterval: NodeJS.Timeout;
  private rejectedTotal = 0;
 
  constructor(
    private readonly name: string,
    private readonly rateConfig: RateLimitConfig,
  ) {
    this.cleanupInterval = setInterval(
      () => this.cleanup(),
      serverConfig.server.simulationRateLimitCleanupIntervalMs,
    );
    this.cleanupInterval.unref?.();
    logger.info(
      `${name} rate limiter initialized: ${rateConfig.maxRequests} request(s) per ${rateConfig.windowMs}ms`,
    );
  }
 
  checkLimit(identity: string): RateLimitResult {
    const now = Date.now();
    let entry = this.identityLimits.get(identity);
 
    if (!entry) {
      entry = { timestamps: [now], blockedUntil: 0, lastActivity: now };
      this.identityLimits.set(identity, entry);
      return { allowed: true };
    }
 
    entry.lastActivity = now;
    if (now < entry.blockedUntil) {
      this.rejectedTotal++;
      return {
        allowed: false,
        retryAfter: Math.max(1, Math.ceil((entry.blockedUntil - now) / 1_000)),
      };
    }
 
    if (entry.blockedUntil > 0) {
      entry.blockedUntil = 0;
      entry.timestamps = [];
    }
 
    const cutoff = now - this.rateConfig.windowMs;
    entry.timestamps = entry.timestamps.filter((timestamp) => timestamp > cutoff);
    if (entry.timestamps.length >= this.rateConfig.maxRequests) {
      entry.blockedUntil = now + this.rateConfig.blockDurationMs;
      this.rejectedTotal++;
      logger.warn(
        `${this.name} rate limit exceeded; blocking identity for ${this.rateConfig.blockDurationMs}ms`,
      );
      return {
        allowed: false,
        retryAfter: Math.max(
          1,
          Math.ceil(this.rateConfig.blockDurationMs / 1_000),
        ),
      };
    }
 
    entry.timestamps.push(now);
    return { allowed: true };
  }
 
  private cleanup(): void {
    const cutoff =
      Date.now() - serverConfig.server.simulationRateLimitInactiveTtlMs;
    for (const [identity, entry] of this.identityLimits) {
      if (entry.lastActivity < cutoff) this.identityLimits.delete(identity);
    }
  }
 
  destroy(): void {
    clearInterval(this.cleanupInterval);
    this.identityLimits.clear();
  }
 
  getStats() {
    const now = Date.now();
    return {
      config: this.rateConfig,
      activeClients: this.identityLimits.size,
      blockedClients: Array.from(this.identityLimits.values()).filter(
        (entry) => entry.blockedUntil > now,
      ).length,
      rejectedTotal: this.rejectedTotal,
    };
  }
}
 
const SIMULATION_DEFAULTS: RateLimitConfig = {
  maxRequests: serverConfig.server.simulationRateLimitMaxRequests,
  windowMs: serverConfig.server.simulationRateLimitWindowMs,
  blockDurationMs: serverConfig.server.simulationRateLimitBlockDurationMs,
};
 
const COMPILE_DEFAULTS: RateLimitConfig = {
  maxRequests: serverConfig.server.compileRateLimitMaxRequests,
  windowMs: serverConfig.server.compileRateLimitWindowMs,
  blockDurationMs: serverConfig.server.compileRateLimitBlockDurationMs,
};
 
export class SimulationRateLimiter extends IdentityRateLimiter {
  private static instance: SimulationRateLimiter | null = null;
 
  private constructor(config: Partial<RateLimitConfig> = {}) {
    super("Simulation start", { ...SIMULATION_DEFAULTS, ...config });
  }
 
  static getInstance(config?: Partial<RateLimitConfig>): SimulationRateLimiter {
    SimulationRateLimiter.instance ??= new SimulationRateLimiter(config);
    return SimulationRateLimiter.instance;
  }
}
 
export class CompileRateLimiter extends IdentityRateLimiter {
  private static instance: CompileRateLimiter | null = null;
 
  private constructor(config: Partial<RateLimitConfig> = {}) {
    super("Compile", { ...COMPILE_DEFAULTS, ...config });
  }
 
  static getInstance(config?: Partial<RateLimitConfig>): CompileRateLimiter {
    CompileRateLimiter.instance ??= new CompileRateLimiter(config);
    return CompileRateLimiter.instance;
  }
}
 
export const getSimulationRateLimiter = (): SimulationRateLimiter =>
  SimulationRateLimiter.getInstance();
 
export const getCompileRateLimiter = (): CompileRateLimiter =>
  CompileRateLimiter.getInstance();