-
Notifications
You must be signed in to change notification settings - Fork 1k
[UNDERTOW-2537] Implement bit shift window rate limiter and limiter h… #1777
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
baranowb
wants to merge
1
commit into
undertow-io:main
Choose a base branch
from
baranowb:UNDERTOW-2537
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
208 changes: 208 additions & 0 deletions
208
.../src/main/java/io/undertow/server/handlers/ratelimit/BitShiftSingleWindowRateLimiter.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,208 @@ | ||
/* | ||
* JBoss, Home of Professional Open Source. | ||
* Copyright 2025 Red Hat, Inc., and individual contributors | ||
* as indicated by the @author tags. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
package io.undertow.server.handlers.ratelimit; | ||
|
||
import java.net.InetAddress; | ||
import java.net.InetSocketAddress; | ||
import java.util.concurrent.ConcurrentHashMap; | ||
import java.util.concurrent.TimeUnit; | ||
import java.util.concurrent.atomic.AtomicInteger; | ||
|
||
import org.xnio.XnioExecutor; | ||
|
||
import io.undertow.UndertowLogger; | ||
import io.undertow.server.HttpServerExchange; | ||
import io.undertow.util.WorkerUtils; | ||
|
||
/** | ||
* This is bit shift implementation of sliding window. Both rate and duration are converted to next 2^n in order to simply | ||
* bitshift values, rather than perform 10 based math and convert back into 2 base representation. This implementation of | ||
* {@link RateLimiter} has single, common window for all entries. For which keys are computed with bit shifting ops. This is not | ||
* precise, but has very low performance impact. | ||
*/ | ||
public class BitShiftSingleWindowRateLimiter implements RateLimiter<HttpServerExchange, HttpServerExchange> { | ||
// Single window to make it less resource hungry and simpler for first iteration. | ||
private int windowDuration; // duration in seconds. | ||
private int requestLimit; | ||
private volatile XnioExecutor.Key evictionKey; | ||
// numbers of bits to shift. This will be used to determine prefix for 'requestCounter'; Its based on duration next power of | ||
// 2; | ||
private int bitsToShift; | ||
// This map will store entries under key == prefix-IPAddress. where prefix is | ||
// "major" part of timestamp | ||
// Prefix math: | ||
// 10000 --> 10 | ||
// 10001 --> 10 | ||
// Next: 10+1 --> 11000 | ||
// In other words as long as bitsToShift wont cover ++, prefix will remain constant and allow fast and predictable | ||
// calculation of key. | ||
// Any key that does not start with prefix is outdated(window slid over it). | ||
// NOTE: this can be improved with Long as key and having upper store ~tstamp and lower having pure byte[] representation | ||
// of IP. Rest of logic would remain the same as for String key. | ||
// TODO: sanity check, this is IO thread, so no need for cuncurrent map and AtomicInteger ? | ||
private ConcurrentHashMap<String, AtomicInteger> requestCounter = new ConcurrentHashMap<String, AtomicInteger>(5000); | ||
private static final String PREFIX_SEPARATOR = "-"; | ||
private static final int TICK_BORDER = Integer.MAX_VALUE - 1; | ||
/** | ||
* Create bit shift limiter. Implementation will adjust values of bot windowDuration and requestLimit, to adjust to next ^2. | ||
* Meaning duration of 33, will become 64. requestLimit will be adjusted to reflect this "stretch". | ||
* | ||
* @param windowDuration | ||
* @param requestLimit | ||
*/ | ||
public BitShiftSingleWindowRateLimiter(final int windowDuration, final int requestLimit) { | ||
assert windowDuration > 0; | ||
assert requestLimit > 0; | ||
this.bitsToShift = determineBitShiftForDuration(windowDuration); | ||
this.windowDuration = Math.toIntExact(1L << this.bitsToShift) / 1000; | ||
// need to adjust requests, based on difference between bitshift duration and one that was passed here. | ||
// This is done to cover cases when nextP2 is not close to duration, for instance original duration 33s, will | ||
// switch to ~64, to have it work properly, we need to adjust limit as well. | ||
this.requestLimit = (int)(((float)this.windowDuration/windowDuration) * requestLimit); | ||
} | ||
|
||
@Override | ||
public int getWindowDuration() { | ||
return this.windowDuration; | ||
} | ||
|
||
@Override | ||
public int getRequestLimit() { | ||
return this.requestLimit; | ||
} | ||
|
||
@Override | ||
public int timeToWindowSlide(final HttpServerExchange exchange) { | ||
// window is common so we ignore parameter. | ||
// nextPrefix->miliseconds-currentMilis/1000->s; | ||
final long currentMilis = System.currentTimeMillis(); | ||
return Math.toIntExact((((generatePrefix(currentMilis) + 1)<<bitsToShift) - currentMilis)/1000); | ||
} | ||
|
||
@Override | ||
public int increment(HttpServerExchange exchange) { | ||
evictionCheck(exchange); | ||
|
||
final String ipAddress = getIPAddress(exchange, true); | ||
final String key = generateKey(ipAddress); | ||
AtomicInteger ai = requestCounter.computeIfAbsent(key, v -> new AtomicInteger()); | ||
return ai.accumulateAndGet(1, (value, upTick) -> { | ||
// JIC | ||
if (value < TICK_BORDER) { | ||
return value + upTick; //uptick = +1 | ||
} else { | ||
return Integer.MAX_VALUE; | ||
} | ||
}); | ||
} | ||
|
||
@Override | ||
public int current(HttpServerExchange exchange) { | ||
final String ipAddress = getIPAddress(exchange, true); | ||
final String key = generateKey(ipAddress); | ||
AtomicInteger entry = requestCounter.get(key); | ||
if(entry != null) { | ||
return entry.get(); | ||
} else { | ||
return -1; | ||
} | ||
} | ||
|
||
private String getIPAddress(final HttpServerExchange exchange, final boolean warn) { | ||
final InetSocketAddress sourceAddress = exchange.getSourceAddress(); | ||
InetAddress address = sourceAddress.getAddress(); | ||
if (address == null) { | ||
// this can happen when we have an unresolved X-forwarded-for address | ||
// in this case we just return the IP of the balancer | ||
//TODO: this needs impr | ||
address = ((InetSocketAddress) exchange.getConnection().getPeerAddress()).getAddress(); | ||
if(warn) { | ||
UndertowLogger.REQUEST_LOGGER.rateLimitFailedToGetProperAddress(exchange.getRequestURI(), address.getHostAddress()); | ||
} | ||
} | ||
return address.getHostAddress(); | ||
} | ||
|
||
@Override | ||
public String getLimiterID() { | ||
return "bit-shift-window"; | ||
} | ||
|
||
@Override | ||
public RateLimitUnit getUnit() { | ||
return RateLimitUnit.REQUEST; | ||
} | ||
|
||
private void evictionCheck(HttpServerExchange exchange) { | ||
// we need to parasite on IO threads for eviction. | ||
XnioExecutor.Key key = this.evictionKey; | ||
if (key == null) { | ||
this.evictionKey = WorkerUtils.executeAfter(exchange.getIoThread(), new Runnable() { | ||
@Override | ||
public void run() { | ||
evictionKey = null; | ||
evictOldWindow(); | ||
} | ||
}, this.windowDuration, TimeUnit.SECONDS); | ||
} | ||
} | ||
|
||
private void evictOldWindow() { | ||
// evict entries that are not 'current' or 'current+1' - just in case eviction starts in one window and finish in next. | ||
// in such case 'current' will become stale already and will be evicted on next call. Thats fine. | ||
// prefix + 1 will translate into bitshift ++ | ||
final long currentPrefix = generatePrefix(); | ||
final String current = String.valueOf(currentPrefix); | ||
final String next = String.valueOf(currentPrefix + 1); | ||
|
||
ConcurrentHashMap.KeySetView<String, AtomicInteger> keys = requestCounter.keySet(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. String could be turned into Long with high bits holding IP in pure form and lower working as in this case. But its harder to follow. |
||
// remove obsolete keys | ||
keys.removeIf(k -> !k.startsWith(current) && !k.startsWith(next)); | ||
|
||
} | ||
|
||
private String generateKey(String ipAddress) { | ||
return generatePrefix() + PREFIX_SEPARATOR + ipAddress; | ||
} | ||
|
||
private long generatePrefix(long timeMilis) { | ||
return timeMilis >> this.bitsToShift; | ||
} | ||
|
||
private long generatePrefix() { | ||
return generatePrefix(System.currentTimeMillis()); | ||
} | ||
|
||
private int nextPowerOf2(final int v) { | ||
// this will return closest one bit, for 19, it will be 16. << 1 to get next highest | ||
final int higherOneBitValue = Integer.highestOneBit(v); | ||
if (v == higherOneBitValue) { | ||
return higherOneBitValue; | ||
} else { | ||
return higherOneBitValue << 1; | ||
} | ||
} | ||
|
||
private int determineBitShiftForDuration(final int duration) { | ||
// duration to milliseconds. | ||
final int nextP2 = nextPowerOf2(duration * 1000); | ||
// since its pure next power of 2, it has leading 1 and trailing zeros, which are equal to bit shift | ||
return Integer.numberOfTrailingZeros(nextP2); | ||
} | ||
|
||
} |
34 changes: 34 additions & 0 deletions
34
core/src/main/java/io/undertow/server/handlers/ratelimit/RateLimitUnit.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
/* | ||
* JBoss, Home of Professional Open Source. | ||
* Copyright 2025 Red Hat, Inc., and individual contributors | ||
* as indicated by the @author tags. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
package io.undertow.server.handlers.ratelimit; | ||
|
||
public enum RateLimitUnit { | ||
//see: https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/ -> 10.3. RateLimit quota unit registry | ||
REQUEST("request"), CONTENT_BYTES("content-bytes"), CONCURRENT_REQUESTS("concurrent-requests"); | ||
|
||
private final String label; | ||
|
||
RateLimitUnit(String label) { | ||
this.label = label; | ||
} | ||
|
||
@Override | ||
public String toString() { | ||
return label; | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is not ideal, this code is repeated in Handler class to get log details as well.