|
| 1 | +package org.juv25d.filter; |
| 2 | + |
| 3 | +import io.github.bucket4j.Bandwidth; |
| 4 | +import io.github.bucket4j.Bucket; |
| 5 | +import io.github.bucket4j.Refill; |
| 6 | +import org.juv25d.http.HttpRequest; |
| 7 | +import org.juv25d.http.HttpResponse; |
| 8 | +import org.juv25d.logging.ServerLogging; |
| 9 | + |
| 10 | +import java.io.IOException; |
| 11 | +import java.nio.charset.StandardCharsets; |
| 12 | +import java.time.Duration; |
| 13 | +import java.util.Map; |
| 14 | +import java.util.concurrent.ConcurrentHashMap; |
| 15 | +import java.util.logging.Logger; |
| 16 | + |
| 17 | +/** |
| 18 | + * A filter that implements rate limiting for incoming HTTP requests. |
| 19 | + * It uses a token bucket algorithm via Bucket4J to limit the number of requests per client IP. |
| 20 | + */ |
| 21 | +public class RateLimitingFilter implements Filter { |
| 22 | + |
| 23 | + private static final Logger logger = ServerLogging.getLogger(); |
| 24 | + |
| 25 | + private final Map<String, Bucket> buckets = new ConcurrentHashMap<>(); |
| 26 | + |
| 27 | + private final long capacity; |
| 28 | + private final long refillTokens; |
| 29 | + private final Duration refillPeriod; |
| 30 | + |
| 31 | + /** |
| 32 | + * Constructs a new RateLimitingFilter. |
| 33 | + * |
| 34 | + * @param requestsPerMinute the number of requests allowed per minute for each IP |
| 35 | + * @param burstCapacity the maximum number of requests that can be handled in a burst |
| 36 | + * @throws IllegalArgumentException if requestsPerMinute or burstCapacity is not positive |
| 37 | + */ |
| 38 | + public RateLimitingFilter(long requestsPerMinute, long burstCapacity) { |
| 39 | + if (requestsPerMinute <= 0) { |
| 40 | + throw new IllegalArgumentException("requestsPerMinute must be positive"); |
| 41 | + } |
| 42 | + if (burstCapacity <= 0) { |
| 43 | + throw new IllegalArgumentException("burstCapacity must be positive"); |
| 44 | + } |
| 45 | + |
| 46 | + this.capacity = burstCapacity; |
| 47 | + this.refillTokens = requestsPerMinute; |
| 48 | + this.refillPeriod = Duration.ofMinutes(1); |
| 49 | + |
| 50 | + logger.info(String.format( |
| 51 | + "RateLimitingFilter initialized - Limit: %d req/min, Burst: %d", |
| 52 | + requestsPerMinute, burstCapacity |
| 53 | + )); |
| 54 | + } |
| 55 | + |
| 56 | + /** |
| 57 | + * Applies the rate limiting logic to the incoming request. |
| 58 | + * If the rate limit is exceeded, a 429 Too Many Requests response is sent. |
| 59 | + * |
| 60 | + * @param req the HTTP request |
| 61 | + * @param res the HTTP response |
| 62 | + * @param chain the filter chain |
| 63 | + * @throws IOException if an I/O error occurs |
| 64 | + */ |
| 65 | + @Override |
| 66 | + public void doFilter(HttpRequest req, HttpResponse res, FilterChain chain) throws IOException { |
| 67 | + String clientIp = getClientIp(req); |
| 68 | + |
| 69 | + Bucket bucket = buckets.computeIfAbsent(clientIp, k -> createBucket()); |
| 70 | + |
| 71 | + if (bucket.tryConsume(1)) { |
| 72 | + chain.doFilter(req, res); |
| 73 | + } else { |
| 74 | + logRateLimitExceeded(clientIp, req.method(), req.path()); |
| 75 | + sendTooManyRequests(res, clientIp); |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + private String getClientIp(HttpRequest req) { |
| 80 | + return req.remoteIp(); |
| 81 | + } |
| 82 | + |
| 83 | + private Bucket createBucket() { |
| 84 | + Bandwidth limit = Bandwidth.classic( |
| 85 | + capacity, |
| 86 | + Refill.intervally(refillTokens, refillPeriod)); |
| 87 | + |
| 88 | + return Bucket.builder() |
| 89 | + .addLimit(limit) |
| 90 | + .build(); |
| 91 | + } |
| 92 | + |
| 93 | + /** |
| 94 | + * Returns the number of currently tracked IP addresses. |
| 95 | + * |
| 96 | + * @return the number of tracked IP addresses |
| 97 | + */ |
| 98 | + public int getTrackedIpCount() { |
| 99 | + return buckets.size(); |
| 100 | + } |
| 101 | + |
| 102 | + private void logRateLimitExceeded(String ip, String method, String path) { |
| 103 | + logger.warning(String.format( |
| 104 | + "Rate limit exceeded - IP: %s, Method: %s, Path: %s", |
| 105 | + ip, method, path |
| 106 | + )); |
| 107 | + } |
| 108 | + |
| 109 | + private void sendTooManyRequests(HttpResponse res, String ip) { |
| 110 | + byte[] body = ("429 Too Many Requests: Rate limit exceeded for IP " + ip + "\n") |
| 111 | + .getBytes(StandardCharsets.UTF_8); |
| 112 | + |
| 113 | + res.setStatusCode(429); |
| 114 | + res.setStatusText("Too Many Requests"); |
| 115 | + res.setHeader("Content-Type", "text/plain; charset=utf-8"); |
| 116 | + res.setHeader("Content-Length", String.valueOf(body.length)); |
| 117 | + res.setHeader("Retry-After", "60"); |
| 118 | + res.setBody(body); |
| 119 | + } |
| 120 | + |
| 121 | + /** |
| 122 | + * Clears all tracked rate limiting buckets. |
| 123 | + */ |
| 124 | + @Override |
| 125 | + public void destroy() { |
| 126 | + buckets.clear(); |
| 127 | + } |
| 128 | +} |
0 commit comments