Skip to content

Commit fd6cfb7

Browse files
committed
fix: messed up duplicated code
1 parent 1e1224a commit fd6cfb7

File tree

4 files changed

+0
-261
lines changed

4 files changed

+0
-261
lines changed

src/main/java/com/gautam/ratelimiter/ratelimiter/AdaptiveRateLimiter.java

Lines changed: 0 additions & 130 deletions
Original file line numberDiff line numberDiff line change
@@ -285,134 +285,4 @@ public int getRemainingPermits(HttpServletRequest request, Principal user) {
285285

286286
return Math.min(globalRemaining, Math.min(userRemaining, ipRemaining));
287287
}
288-
}
289-
this.factory = factory;
290-
this.config = config;
291-
this.meterRegistry = meterRegistry;
292-
this.userLimiters = Caffeine.newBuilder()
293-
.expireAfterAccess(5, TimeUnit.MINUTES)
294-
.maximumSize(10_000)
295-
.build();
296-
this.ipLimiters = Caffeine.newBuilder()
297-
.expireAfterAccess(5, TimeUnit.MINUTES)
298-
.maximumSize(50_000)
299-
.build();
300-
}
301-
302-
private void ensureInitialized() {
303-
if (!initialized) {
304-
synchronized (this) {
305-
if (!initialized) {
306-
String algorithmName = config.getAlgorithm();
307-
Algorithm algorithm = Algorithm.valueOf(algorithmName);
308-
309-
globalLimiter = factory.create(
310-
"GLOBAL",
311-
algorithm,
312-
config.getLimits().getGlobal().getRequestsPerSecond()
313-
);
314-
315-
log.info("Adaptive Rate Limiter initialized with algorithm: {}", algorithmName);
316-
initialized = true;
317-
}
318-
}
319-
}
320-
}
321-
322-
public boolean tryConsume(HttpServletRequest request, Principal user) {
323-
ensureInitialized();
324-
325-
// Layer 1. Check global limit.
326-
if (!globalLimiter.allowRequest()) {
327-
log.warn("Rate limit exceeded: GLOBAL");
328-
count("global", "blocked");
329-
return false;
330-
}
331-
count("global", "allowed");
332-
333-
// LAYER 2. Check per-user limit (if authenticated)
334-
if (user != null) {
335-
String username = user.getName();
336-
RateLimiter userLimiter = userLimiters.get(username, key ->
337-
factory.create(
338-
"USER_" + key,
339-
config.getAlgorithm(),
340-
config.getLimits().getPerUser().getRequestsPerSecond()
341-
)
342-
);
343-
344-
if (!userLimiter.allowRequest()) {
345-
log.warn("Rate limit exceeded: USER_{}", username);
346-
count("user", "blocked");
347-
return false;
348-
}
349-
count("user", "allowed");
350-
}
351-
352-
// LAYER 3. Check per-IP limit
353-
String clientIp = extractClientIp(request);
354-
RateLimiter ipLimiter = ipLimiters.get(clientIp, key ->
355-
factory.create(
356-
"IP_" + clientIp,
357-
config.getAlgorithm(),
358-
config.getLimits().getPerIp().getRequestsPerSecond()
359-
)
360-
);
361-
362-
if (!ipLimiter.allowRequest()) {
363-
log.warn("Rate limit exceeded: IP_{}", clientIp);
364-
count("ip", "blocked");
365-
return false;
366-
}
367-
count("ip", "allowed");
368-
369-
return true;
370-
}
371-
372-
private void count(String layer, String result) {
373-
Counter.builder("ratelimiter.requests")
374-
.tag("layer", layer)
375-
.tag("result", result)
376-
.tag("algorithm", config.getAlgorithm())
377-
.register(meterRegistry)
378-
.increment();
379-
}
380-
381-
private String extractClientIp(HttpServletRequest request) {
382-
String xForwardedFor = request.getHeader("X-Forwarded-For");
383-
if (xForwardedFor != null && !xForwardedFor.isEmpty()) {
384-
// Format: client, proxy1, proxy2
385-
return xForwardedFor.split(",")[0].trim();
386-
}
387-
388-
String xRealIp = request.getHeader("X-Real-IP");
389-
if (xRealIp != null && !xRealIp.isEmpty()) {
390-
return xRealIp;
391-
}
392-
393-
return request.getRemoteAddr();
394-
}
395-
396-
public int getRemainingPermits(HttpServletRequest request, Principal user) {
397-
ensureInitialized();
398-
399-
int globalRemaining = globalLimiter.getRemainingPermits();
400-
401-
int userRemaining = Integer.MAX_VALUE;
402-
if (user != null) {
403-
RateLimiter userLimiter = userLimiters.getIfPresent(user.getName());
404-
if (userLimiter != null) {
405-
userRemaining = userLimiter.getRemainingPermits();
406-
}
407-
}
408-
409-
String clientIp = extractClientIp(request);
410-
int ipRemaining = Integer.MAX_VALUE;
411-
RateLimiter ipLimiter = ipLimiters.getIfPresent(clientIp);
412-
if (ipLimiter != null) {
413-
ipRemaining = ipLimiter.getRemainingPermits();
414-
}
415-
416-
return Math.min(globalRemaining, Math.min(userRemaining, ipRemaining));
417-
}
418288
}

src/main/java/com/gautam/ratelimiter/ratelimiter/algorithms/LeakyBucketRateLimiter.java

Lines changed: 0 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -126,49 +126,4 @@ private void leak() {
126126
log.debug("Leaky Bucket {} leaked {} requests. New load: {}", name, leaked, currentLoad);
127127
}
128128
}
129-
}
130-
this.name = name;
131-
this.capacity = capacity;
132-
this.leakRate = leakRate;
133-
this.lastLeakTime = System.currentTimeMillis();
134-
this.currentLoad = 0;
135-
}
136-
137-
@Override
138-
public synchronized boolean allowRequest() {
139-
leak();
140-
141-
if (currentLoad < capacity) {
142-
currentLoad++;
143-
log.debug("Leaky Bucket {} allowed request. Load: {}/{}", name, currentLoad, capacity);
144-
return true;
145-
}
146-
147-
log.debug("Leaky Bucket {} blocked request. Queue full: {}/{}", name, currentLoad, capacity);
148-
return false;
149-
}
150-
151-
@Override
152-
public synchronized int getRemainingPermits() {
153-
leak();
154-
return (int) (capacity - currentLoad);
155-
}
156-
157-
@Override
158-
public String getName() {
159-
return name;
160-
}
161-
162-
private void leak() {
163-
long now = System.currentTimeMillis();
164-
long elapsed = now - lastLeakTime;
165-
166-
long leaked = (elapsed / 1000) * leakRate;
167-
168-
if (leaked > 0) {
169-
currentLoad = Math.max(currentLoad - leaked, 0);
170-
lastLeakTime = now;
171-
log.debug("Leaky Bucket {} leaked {} requests. New load: {}", name, leaked, currentLoad);
172-
}
173-
}
174129
}

src/main/java/com/gautam/ratelimiter/ratelimiter/algorithms/SlidingWindowRateLimiter.java

Lines changed: 0 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -120,46 +120,4 @@ private void checkAndResetWindow() {
120120
log.debug("Sliding window {} reset", name);
121121
}
122122
}
123-
}
124-
this.name = name;
125-
this.limit = limit;
126-
this.windowSizeMs = windowSizeMs;
127-
this.requestCount = 0;
128-
this.windowStartTime = System.currentTimeMillis();
129-
}
130-
131-
@Override
132-
public String getName() {
133-
return name;
134-
}
135-
136-
@Override
137-
public synchronized boolean allowRequest() {
138-
checkAndResetWindow();
139-
140-
if (requestCount < limit) {
141-
requestCount++;
142-
log.debug("Sliding window {} allowed request. Count {}/{}", name, requestCount, limit);
143-
return true;
144-
}
145-
146-
log.debug("Sliding window {} blocked request. Limit {} reached", name, limit);
147-
return false;
148-
}
149-
150-
@Override
151-
public synchronized int getRemainingPermits() {
152-
checkAndResetWindow();
153-
return limit - requestCount;
154-
}
155-
156-
private void checkAndResetWindow() {
157-
long now = System.currentTimeMillis();
158-
159-
if (now - windowStartTime >= windowSizeMs) {
160-
requestCount = 0;
161-
windowStartTime = now;
162-
log.debug("Sliding window {} reset", name);
163-
}
164-
}
165123
}

src/main/java/com/gautam/ratelimiter/ratelimiter/algorithms/TokenBucketRateLimiter.java

Lines changed: 0 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -125,48 +125,4 @@ private void refillTokens() {
125125
lastRefillTime = now;
126126
}
127127
}
128-
}
129-
this.name = name;
130-
this.capacity = capacity;
131-
this.refillRate = refillRate;
132-
this.tokens = capacity;
133-
this.lastRefillTime = System.currentTimeMillis();
134-
}
135-
136-
@Override
137-
public synchronized boolean allowRequest() {
138-
refillTokens();
139-
140-
if (tokens > 0) {
141-
tokens--;
142-
log.debug("Token bucket {} allowed request. Tokens remaining: {}", name, tokens);
143-
return true;
144-
}
145-
146-
log.debug("Token bucket {} blocked request. No tokens available.", name);
147-
return false;
148-
}
149-
150-
@Override
151-
public synchronized int getRemainingPermits() {
152-
refillTokens();
153-
return (int) Math.min(tokens, Integer.MAX_VALUE);
154-
}
155-
156-
@Override
157-
public String getName() {
158-
return name;
159-
}
160-
161-
private void refillTokens() {
162-
long now = System.currentTimeMillis();
163-
long elapsed = now - lastRefillTime;
164-
165-
long tokensToAdd = (elapsed / 1000) * refillRate;
166-
167-
if (tokensToAdd > 0) {
168-
tokens = Math.min(tokens + tokensToAdd, capacity);
169-
lastRefillTime = now;
170-
}
171-
}
172128
}

0 commit comments

Comments
 (0)