-
Notifications
You must be signed in to change notification settings - Fork 0
CELDEV-1343 EndpointConcurrencyLimiter #34
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
msladek
wants to merge
3
commits into
dev
Choose a base branch
from
CELDEV-1343
base: dev
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
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
24 changes: 1 addition & 23 deletions
24
celements-spring-mvc/src/main/java/com/celements/spring/mvc/HelloWorldController.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 |
|---|---|---|
| @@ -1,40 +1,18 @@ | ||
| package com.celements.spring.mvc; | ||
|
|
||
| import javax.inject.Inject; | ||
|
|
||
| import org.springframework.beans.factory.BeanFactory; | ||
| import org.springframework.security.access.prepost.PreAuthorize; | ||
| import org.springframework.web.bind.annotation.GetMapping; | ||
| import org.springframework.web.bind.annotation.RestController; | ||
| import org.xwiki.context.Execution; | ||
|
|
||
| import com.celements.execution.XWikiExecutionProp; | ||
| import com.celements.spring.security.AuthenticatedBaseController; | ||
| import com.xpn.xwiki.XWikiContext; | ||
|
|
||
| @RestController | ||
| public class HelloWorldController extends AuthenticatedBaseController { | ||
|
|
||
| private final BeanFactory beanFactory; | ||
|
|
||
| @Inject | ||
| public HelloWorldController(BeanFactory beanFactory) { | ||
| this.beanFactory = beanFactory; | ||
| } | ||
|
|
||
| @GetMapping("/helloworld") | ||
| @GetMapping | ||
| @PreAuthorize("permitAll()") | ||
| public String helloWorld() { | ||
| return "Hello World!"; | ||
| } | ||
|
|
||
| @GetMapping("/hellocontext") | ||
| public XWikiContext helloContext() { | ||
| return beanFactory | ||
| .getBean(Execution.class) | ||
| .getContext() | ||
| .get(XWikiExecutionProp.XWIKI_CONTEXT) | ||
| .orElseThrow(); | ||
| } | ||
|
|
||
| } |
11 changes: 11 additions & 0 deletions
11
...-spring-mvc/src/main/java/com/celements/spring/mvc/limiter/EndpointConcurrencyConfig.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,11 @@ | ||
| package com.celements.spring.mvc.limiter; | ||
|
|
||
| import static com.google.common.base.Preconditions.*; | ||
|
|
||
| public record EndpointConcurrencyConfig(int maxConcurrent, int waitMillis) { | ||
|
|
||
| public EndpointConcurrencyConfig { | ||
| checkArgument(maxConcurrent > 0, "Endpoint concurrency limit must be positive"); | ||
| checkArgument(waitMillis >= 0, "Endpoint concurrency wait time must be non-negative"); | ||
| } | ||
| } |
16 changes: 16 additions & 0 deletions
16
...s-spring-mvc/src/main/java/com/celements/spring/mvc/limiter/EndpointConcurrencyLimit.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,16 @@ | ||
| package com.celements.spring.mvc.limiter; | ||
|
|
||
| import static java.lang.annotation.ElementType.*; | ||
| import static java.lang.annotation.RetentionPolicy.*; | ||
|
|
||
| import java.lang.annotation.Documented; | ||
| import java.lang.annotation.Retention; | ||
| import java.lang.annotation.Target; | ||
|
|
||
| @Documented | ||
| @Retention(RUNTIME) | ||
| @Target({ TYPE, METHOD }) | ||
| public @interface EndpointConcurrencyLimit { | ||
|
|
||
| String value(); | ||
| } | ||
84 changes: 84 additions & 0 deletions
84
...spring-mvc/src/main/java/com/celements/spring/mvc/limiter/EndpointConcurrencyLimiter.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,84 @@ | ||
| package com.celements.spring.mvc.limiter; | ||
|
|
||
| import static com.google.common.base.Preconditions.*; | ||
| import static java.util.concurrent.TimeUnit.*; | ||
| import static org.springframework.core.annotation.AnnotatedElementUtils.*; | ||
| import static org.springframework.http.HttpStatus.*; | ||
|
|
||
| import java.io.IOException; | ||
| import java.lang.reflect.AnnotatedElement; | ||
| import java.util.Map; | ||
| import java.util.Optional; | ||
| import java.util.concurrent.Semaphore; | ||
|
|
||
| import javax.inject.Inject; | ||
| import javax.servlet.http.HttpServletRequest; | ||
| import javax.servlet.http.HttpServletResponse; | ||
|
|
||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.web.method.HandlerMethod; | ||
|
|
||
| import com.celements.spring.mvc.CelMvcInterceptor; | ||
|
|
||
| import one.util.streamex.EntryStream; | ||
|
|
||
| @Component | ||
| public class EndpointConcurrencyLimiter implements CelMvcInterceptor { | ||
|
|
||
| private final Map<String, EndpointConcurrencyConfig> configs; | ||
| private final Map<String, Semaphore> limiters; | ||
|
|
||
| @Inject | ||
| public EndpointConcurrencyLimiter(Optional<Map<String, EndpointConcurrencyConfig>> configs) { | ||
| this(configs.orElseGet(Map::of)); | ||
| } | ||
|
|
||
| EndpointConcurrencyLimiter(Map<String, EndpointConcurrencyConfig> configs) { | ||
| this.configs = Map.copyOf(configs); | ||
| this.limiters = EntryStream.of(configs) | ||
| .mapValues(config -> new Semaphore(config.maxConcurrent())) | ||
| .toMap(); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) | ||
| throws IOException { | ||
| if (findLimiterName(handler).map(this::tryAcquire).orElse(true)) { | ||
| return true; | ||
| } | ||
| response.sendError(SERVICE_UNAVAILABLE.value(), "Endpoint concurrency limit exhausted"); | ||
| return false; | ||
| } | ||
|
|
||
| private boolean tryAcquire(String limiterName) { | ||
| try { | ||
| var config = configs.get(limiterName); | ||
| checkState(config != null, "Missing EndpointConcurrencyConfig [%s]", limiterName); | ||
| return limiters.get(limiterName).tryAcquire(config.waitMillis(), MILLISECONDS); | ||
| } catch (InterruptedException exc) { | ||
| Thread.currentThread().interrupt(); | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public void afterCompletion(HttpServletRequest request, HttpServletResponse response, | ||
| Object handler, Exception exc) { | ||
| findLimiterName(handler) | ||
| .map(limiters::get) | ||
| .ifPresent(Semaphore::release); | ||
| } | ||
|
|
||
| private Optional<String> findLimiterName(Object handler) { | ||
| if (!(handler instanceof HandlerMethod methodHandler)) { | ||
| return Optional.empty(); | ||
| } | ||
| return findAnnotation(methodHandler.getMethod()) | ||
| .or(() -> findAnnotation(methodHandler.getBeanType())) | ||
| .map(EndpointConcurrencyLimit::value); | ||
| } | ||
|
|
||
| private Optional<EndpointConcurrencyLimit> findAnnotation(AnnotatedElement element) { | ||
| return Optional.ofNullable(findMergedAnnotation(element, EndpointConcurrencyLimit.class)); | ||
| } | ||
| } |
163 changes: 163 additions & 0 deletions
163
...ng-mvc/src/test/java/com/celements/spring/mvc/limiter/EndpointConcurrencyLimiterTest.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,163 @@ | ||
| package com.celements.spring.mvc.limiter; | ||
|
|
||
| import static org.junit.Assert.*; | ||
| import static org.springframework.http.HttpStatus.*; | ||
| import static java.util.concurrent.Executors.*; | ||
| import static java.util.concurrent.TimeUnit.*; | ||
|
|
||
| import java.util.Map; | ||
|
|
||
| import org.junit.Before; | ||
| import org.junit.Test; | ||
| import org.springframework.beans.factory.config.ConfigurableBeanFactory; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.context.annotation.Primary; | ||
| import org.springframework.context.annotation.Scope; | ||
| import org.springframework.mock.web.MockHttpServletRequest; | ||
| import org.springframework.mock.web.MockHttpServletResponse; | ||
| import org.springframework.web.method.HandlerMethod; | ||
|
|
||
| import com.celements.common.test.AbstractComponentTest; | ||
| import com.celements.spring.mvc.limiter.EndpointConcurrencyConfig; | ||
| import com.celements.spring.mvc.limiter.EndpointConcurrencyLimit; | ||
| import com.celements.spring.mvc.limiter.EndpointConcurrencyLimiter; | ||
|
|
||
| public class EndpointConcurrencyLimiterTest extends AbstractComponentTest { | ||
|
|
||
| private EndpointConcurrencyLimiter limiter; | ||
|
|
||
| @Before | ||
| public void prepareTest() { | ||
| limiter = getBeanFactory().getBean(EndpointConcurrencyLimiter.class); | ||
| } | ||
|
|
||
| @Test | ||
| public void test_unannotatedHandlersAreUnlimited() throws Exception { | ||
| assertTrue(limiter.preHandle(new MockHttpServletRequest(), new MockHttpServletResponse(), | ||
| handlerMethod("unlimitedEndpoint"))); | ||
| assertTrue(limiter.preHandle( | ||
| new MockHttpServletRequest(), new MockHttpServletResponse(), new Object())); | ||
| } | ||
|
|
||
| @Test | ||
| public void test_sameLimitSharesCapacityAcrossEndpoints() throws Exception { | ||
| var request = new MockHttpServletRequest(); | ||
| var handler = handlerMethod("limitedEndpoint"); | ||
| var otherHandler = handlerMethod("otherSearchEndpoint"); | ||
| assertTrue(limiter.preHandle(request, new MockHttpServletResponse(), handler)); | ||
|
|
||
| var response = new MockHttpServletResponse(); | ||
| assertFalse(limiter.preHandle(new MockHttpServletRequest(), response, otherHandler)); | ||
| assertEquals(SERVICE_UNAVAILABLE.value(), response.getStatus()); | ||
|
|
||
| limiter.afterCompletion(request, null, handler, null); | ||
| assertTrue(limiter.preHandle(new MockHttpServletRequest(), new MockHttpServletResponse(), | ||
| otherHandler)); | ||
| } | ||
|
|
||
| @Test | ||
| public void test_waitsForCapacity() throws Exception { | ||
| var waitingLimiter = new EndpointConcurrencyLimiter(Map.of( | ||
| "search", new EndpointConcurrencyConfig(1, 1000))); | ||
| var request = new MockHttpServletRequest(); | ||
| var handler = handlerMethod("limitedEndpoint"); | ||
| assertTrue(waitingLimiter.preHandle(request, new MockHttpServletResponse(), handler)); | ||
|
|
||
| var executor = newSingleThreadScheduledExecutor(); | ||
| try { | ||
| executor.schedule( | ||
| () -> waitingLimiter.afterCompletion(request, null, handler, null), 50, MILLISECONDS); | ||
| assertTrue(waitingLimiter.preHandle( | ||
| new MockHttpServletRequest(), new MockHttpServletResponse(), handler)); | ||
| } finally { | ||
| executor.shutdownNow(); | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| public void test_differentLimitsHaveIndependentCapacity() throws Exception { | ||
| assertTrue(limiter.preHandle(new MockHttpServletRequest(), new MockHttpServletResponse(), | ||
| handlerMethod("limitedEndpoint"))); | ||
| assertTrue(limiter.preHandle(new MockHttpServletRequest(), new MockHttpServletResponse(), | ||
| handlerMethod("otherLimitedEndpoint"))); | ||
| } | ||
|
|
||
| @Test | ||
| public void test_missingConfigFailsClosed() throws Exception { | ||
| assertThrows(IllegalStateException.class, () -> limiter.preHandle( | ||
| new MockHttpServletRequest(), new MockHttpServletResponse(), | ||
| handlerMethod("missingLimitEndpoint"))); | ||
| } | ||
|
|
||
| @Test | ||
| public void test_classAnnotation() throws Exception { | ||
| var request = new MockHttpServletRequest(); | ||
| var handler = new HandlerMethod( | ||
| new LimitedController(), LimitedController.class.getMethod("limitedEndpoint")); | ||
|
|
||
| assertTrue(limiter.preHandle(request, new MockHttpServletResponse(), handler)); | ||
| assertFalse(limiter.preHandle( | ||
| new MockHttpServletRequest(), new MockHttpServletResponse(), handler)); | ||
| } | ||
|
|
||
| @Test | ||
| public void test_configRejectsNonPositiveConcurrency() { | ||
| assertThrows(IllegalArgumentException.class, () -> new EndpointConcurrencyConfig(0, 0)); | ||
| assertThrows(IllegalArgumentException.class, () -> new EndpointConcurrencyConfig(-1, 0)); | ||
| assertThrows(IllegalArgumentException.class, () -> new EndpointConcurrencyConfig(1, -1)); | ||
| } | ||
|
|
||
| private HandlerMethod handlerMethod(String name) { | ||
| try { | ||
| return new HandlerMethod(new TestController(), TestController.class.getMethod(name)); | ||
| } catch (NoSuchMethodException exc) { | ||
| throw new IllegalArgumentException(exc); | ||
| } | ||
| } | ||
|
|
||
| private static class TestController { | ||
|
|
||
| public void unlimitedEndpoint() {} | ||
|
|
||
| @EndpointConcurrencyLimit("search") | ||
| public void limitedEndpoint() {} | ||
|
|
||
| @EndpointConcurrencyLimit("search") | ||
| public void otherSearchEndpoint() {} | ||
|
|
||
| @EndpointConcurrencyLimit("other") | ||
| public void otherLimitedEndpoint() {} | ||
|
|
||
| @EndpointConcurrencyLimit("missing") | ||
| public void missingLimitEndpoint() {} | ||
| } | ||
|
|
||
| @EndpointConcurrencyLimit("search") | ||
| private static class LimitedController { | ||
|
|
||
| public void limitedEndpoint() {} | ||
| } | ||
|
|
||
| @Configuration | ||
| static class TestConfig { | ||
|
|
||
| @Bean("search") | ||
| EndpointConcurrencyConfig searchLimiterConfig() { | ||
| return new EndpointConcurrencyConfig(1, 0); | ||
| } | ||
|
|
||
| @Bean("other") | ||
| EndpointConcurrencyConfig otherLimiterConfig() { | ||
| return new EndpointConcurrencyConfig(1, 0); | ||
| } | ||
|
|
||
| @Bean | ||
| @Primary | ||
| @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) | ||
| EndpointConcurrencyLimiter endpointConcurrencyLimiter( | ||
| Map<String, EndpointConcurrencyConfig> configs) { | ||
| return new EndpointConcurrencyLimiter(configs); | ||
| } | ||
| } | ||
| } |
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.
The limiter identity travels through the implementation as a raw
String, so a typo is detected only later at runtime. If the keys form a closed set, please use an enum annotation member; otherwise keep the annotation input as a string but convert it at the boundary to a small key type used by the maps and acquisition path.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.
The limiter names are intentionally application-owned and therefore form an open set. Java enums would prevent applications from adding their own limiter names. A wrapper created after reading the annotation would still originate from a string and would not provide additional compile-time safety. Consumers can reuse one constant for the
@Beanname and annotation value. Unknown names also fail closed on first use through the existing configuration check, so I’d keep the string-based contract.