Add rate limiting, CORS support, custom HTTP method annotations, and HTTP server enhancements

- Introduced rate limiting functionality with multiple algorithms (Token Bucket, Fixed Window, Leaky Bucket, Sliding Window) via `RateLimiter` interface.
- Added CORS handling with `CorsConfig` and `CorsHandler` for flexible origin, headers, and method configuration.
- Implemented support for custom HTTP methods via `PATCH` and `CUSTOM` annotations in `AnnotationScanner`.
- Enhanced `HttpServer` to support builder pattern and optional integrations for CORS and rate limiting.
- Updated `HttpRequestHandler` to incorporate CORS and rate limiting logic.
This commit is contained in:
CodingPhoenix
2026-05-08 12:00:09 +02:00
parent 392658d54e
commit 05c6ad3dd4
15 changed files with 733 additions and 7 deletions
@@ -0,0 +1,73 @@
package dev.coph.nextusweb.server.ratelimit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public final class RateLimitConfig {
private final Rule globalRule;
private final Map<String, Rule> exactPathRules;
private final List<PrefixRule> prefixRules;
private RateLimitConfig(Builder b) {
this.globalRule = b.globalRule;
this.exactPathRules = Map.copyOf(b.exactPathRules);
this.prefixRules = b.prefixRules.stream()
.sorted((a, c) -> Integer.compare(c.prefix.length(), a.prefix.length()))
.toList();
}
public static Builder builder() {
return new Builder();
}
public List<Rule> rulesFor(String path) {
List<Rule> rules = new ArrayList<>(2);
if (globalRule != null) rules.add(globalRule);
Rule exact = exactPathRules.get(path);
if (exact != null) {
rules.add(exact);
return rules;
}
for (PrefixRule pr : prefixRules) {
if (path.startsWith(pr.prefix)) {
rules.add(pr.rule);
return rules;
}
}
return rules;
}
public record Rule(RateLimiter limiter, KeyResolver keyResolver, String name) {
}
private record PrefixRule(String prefix, Rule rule) {
}
public static final class Builder {
private final Map<String, Rule> exactPathRules = new HashMap<>();
private final List<PrefixRule> prefixRules = new ArrayList<>();
private Rule globalRule;
public Builder global(RateLimiter limiter, KeyResolver keys) {
this.globalRule = new Rule(limiter, keys, "global");
return this;
}
public Builder forPath(String path, RateLimiter limiter, KeyResolver keys) {
exactPathRules.put(path, new Rule(limiter, keys, path));
return this;
}
public Builder forPrefix(String prefix, RateLimiter limiter, KeyResolver keys) {
prefixRules.add(new PrefixRule(prefix, new Rule(limiter, keys, prefix + "*")));
return this;
}
public RateLimitConfig build() {
return new RateLimitConfig(this);
}
}
}