package com.krylov.refound.ratelimit; import java.time.Duration; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.script.DefaultRedisScript; import org.springframework.data.redis.core.script.RedisScript; import org.springframework.stereotype.Component; /** * Счётчик с фиксированным окном в Redis: ключ {@code rl:<правило>:<субъект>:<номер окна>}, * INCR и EXPIRE выполняются одним Lua-скриптом (атомарно, без «вечных» ключей). * *

Лимиты — защитный слой, а не бизнес-логика: при недоступном Redis запрос * пропускается (fail-open), чтобы сбой кэша не положил весь API. */ @Slf4j @Component public class RedisRateLimiter { private static final RedisScript INCREMENT = new DefaultRedisScript<>(""" local count = redis.call('INCR', KEYS[1]) if count == 1 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end return count """, Long.class); private final StringRedisTemplate redisTemplate; public RedisRateLimiter(StringRedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; } /** Результат проверки: разрешён ли запрос и через сколько секунд откроется окно. */ public record Decision(boolean allowed, long count, long retryAfterSeconds) { static Decision allow() { return new Decision(true, 0, 0); } } /** Учитывает запрос и решает, укладывается ли он в лимит. */ public Decision hit(String rule, String subject, int limit, Duration window) { long windowMillis = window.toMillis(); long now = System.currentTimeMillis(); long windowIndex = now / windowMillis; String key = "rl:" + rule + ":" + subject + ":" + windowIndex; try { Long count = redisTemplate.execute(INCREMENT, List.of(key), Long.toString(windowMillis)); if (count == null) { return Decision.allow(); } long retryAfter = Math.max(1, ((windowIndex + 1) * windowMillis - now + 999) / 1000); return new Decision(count <= limit, count, retryAfter); } catch (RuntimeException e) { log.warn("Rate limit '{}' не проверен, Redis недоступен: {}", rule, e.getMessage()); return Decision.allow(); } } /** Сбрасывает текущее окно (например, после успешного входа). */ public void reset(String rule, String subject, Duration window) { long windowIndex = System.currentTimeMillis() / window.toMillis(); try { redisTemplate.delete("rl:" + rule + ":" + subject + ":" + windowIndex); } catch (RuntimeException e) { log.debug("Rate limit '{}' не сброшен: {}", rule, e.getMessage()); } } /** Текущее значение счётчика без увеличения (0, если ключа нет или Redis недоступен). */ public long current(String rule, String subject, Duration window) { long windowIndex = System.currentTimeMillis() / window.toMillis(); try { String value = redisTemplate.opsForValue().get("rl:" + rule + ":" + subject + ":" + windowIndex); return value == null ? 0 : Long.parseLong(value); } catch (RuntimeException e) { return 0; } } }