diff --git a/README.adoc b/README.adoc index 7c7365d7..8adf2a45 100644 --- a/README.adoc +++ b/README.adoc @@ -9,316 +9,182 @@ image:{url-repo}/actions/workflows/maven.yml/badge.svg[Build Status,link={url-re image:{url-repo}/actions/workflows/codeql.yml/badge.svg[Build Status,link={url-repo}/actions/worklows/codeql.yml] image:{url-repo}/actions/workflows/pmd.yml/badge.svg[Build Status,link={url-repo}/actions/worklows/pmd.yml] -= Spring Boot Starter for Bucket4j - -https://github.com/vladimir-bukhtoyarov/bucket4j - Project version overview: * 0.11.x - Bucket4j 8.8.0 - Spring Boot 3.2.x * 0.10.x - Bucket4j 8.7.0 - Spring Boot 3.1.x - -*Examples:* - -* {url-examples}/ehcache[Ehcache] -* {url-examples}/hazelcast[Hazelcast] -* {url-examples}/caffeine[Caffeine] -* {url-examples}/webflux[Webflux (Async)] -* {url-examples}/gateway[Spring Cloud Gateway (Async)] - -= Contents +== Contents * <> -* <> -* <> -* <> -* <> -* <> -* <> -* <> -* <> -* <> -* <> -* <> - - -[[introduction]] -== Introduction - -This project is a http://projects.spring.io/spring-boot/[Spring Boot Starter] for Bucket4j. -It can be used limit the rate of access to your REST APIs. +* <> +** <> +*** <> +*** <> +*** <> +*** <> +*** <> -* Prevention of DoS Attacks, brute-force logins attempts -* Request throttling for specific regions, unauthenticated users, authenticated users, not paying users. +* <> +** <> +** <> -The benefit of this project is the configuration of Bucket4j via Spring Boots *properties* or *yaml* files. You don't -have to write a single line of code. +* <> +** <> +** <> +** <> +** <> -[[migration_guide]] -== Migration Guide - -This section is meant to help you migrate your application to new version of this starter project. - -=== Spring Boot Starter Bucket4j 0.9 - -* Upgrade to Spring Boot 3 -* Spring Boot 3 requires Java 17 so use at least Java 17 -* Replaced Java 8 compatible Bucket4j dependencies -* Exclude example webflux-infinispan due to startup problems - -=== Spring Boot Starter Bucket4j 0.8 - -==== Compatibility to Java 8 - -The version 0.8 tries to be compatible with Java 8 as long as Bucket4j is supporting Java 8. With the release -of Bucket4j 8.0.0 Bucket4j decided to migrate to Java 11 but provides dedicated artifacts for Java 8. -The project is switching to the dedicated artifacts which supports Java 8. You can read more about -it https://github.com/bucket4j/bucket4j#java-compatibility-matrix[here]. -==== Rename property expression to cache-key - -The property *..rate-limits[0].expression* is renamed to *..rate-limits[0].cache-key*. -An Exception is thrown on startup if the *expression* property is configured. - -To ensure that the property is not filled falsely the property is marked with *@Null*. This change requires -a Bean Validation implementation. - -==== JSR 380 - Bean Validation implementation required +[[introduction]] +== Spring Boot Starter for Bucket4j -To ensure that the Bucket4j property configuration is correct an Validation API implementation is required. -You can add the Spring Boot Starter Validation which will automatically configures one. +This project is a Spring Boot Starter for Bucket4j, allowing you to set access limits on your API effortlessly. Its key advantage lies in the configuration via properties or yaml files, eliminating the need for manual code authoring. -[source, xml] ----- - - org.springframework.boot - spring-boot-starter-validation - ----- -==== Explicit Configuration of the Refill Speed - API Break -The refill speed of the Buckets can now configured explicitly with the Enum RefillSpeed. You can choose between -a greedy or interval refill see the https://bucket4j.com/8.1.1/toc.html#refill[official documentation]. +Here are some example use cases: -Before 0.8 the refill speed was configured implicitly by setting the fixed-refill-interval property explicit. +* Preventing DoS Attacks +* Thwarting brute-force login attempts +* Implementing request throttling for specific regions, unauthenticated users, and authenticated users +* Applying rate limits for non-paying users or users with varying permissions -[source, properties] ----- -bucket4j.filters[0].rate-limits[0].bandwidths[0].fixed-refill-interval=0 -bucket4j.filters[0].rate-limits[0].bandwidths[0].fixed-refill-interval-unit=minutes ----- +The project offers several features, some utilizing Spring's Expression Language for dynamic condition interpretation: -These properties are removed and replaced by the following configuration: +* Cache key for differentiate the by username, IP address, ...) +* Execution based on specific conditions +* Skipping based on specific conditions +* <> +* Post-token consumption actions based on filter/method results -[source, properties] ----- -bucket4j.filters[0].rate-limits[0].bandwidths[0].refill-speed=interval ----- +You have two options for rate limit configuration: adding a filter for incoming web requests or applying fine-grained control at the method level. -You can read more about the refill speed configuration here <> +=== Filter -[[getting_started]] -== Getting started +Filters are customizable components designed to intercept incoming web requests, capable of rejecting requests to halt further processing. You can incorporate multiple filters for various URLs or opt to bypass rate limits entirely for authenticated users. When the limit is exceeded, the web request is aborted, and the client receives an HTTP Status 429 Too Many Requests error. -To use the rate limit in your project you have to add the Bucket4j Spring Boot Starter dependency in -your project. Additionally you have to choose a caching provider <>. +This projects supports the following filters: -The next example uses https://www.jcp.org/en/jsr/detail?id=107[JSR 107] Ehcache which will be auto configured with the https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-caching.html[Spring Boot Starter Cache]. +* https://docs.oracle.com/javaee%2F6%2Fapi%2F%2F/javax/servlet/Filter.html[Servlet Filter] (Default) +* https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/server/WebFilter.html[Webflux Webfilter] (reactive) +* https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway/global-filters.html[Spring Cloud Gateway Global Filter] (reactive) -[source, xml] +[source,properties] ---- - - com.giffing.bucket4j.spring.boot.starter - bucket4j-spring-boot-starter - - - org.springframework.boot - spring-boot-starter-cache - - - org.ehcache - ehcache - +bucket4j.filters[0].cache-name=buckets # the name of the cache +bucket4j.filters[0].url=^(/hello).* # regular expression for the url +bucket4j.filters[0].rate-limits[0].bandwidths[0].capacity=5 # refills 5 tokens every 10 seconds (intervall) +bucket4j.filters[0].rate-limits[0].bandwidths[0].time=10 +bucket4j.filters[0].rate-limits[0].bandwidths[0].unit=seconds +bucket4j.filters[0].rate-limits[0].bandwidths[0].refill-speed=intervall ---- -> Don't forget to enable the caching feature by adding the @EnableCaching annotation to any of the configuration classes. +=== Method -The configuration can be done in the application.properties / application.yml. -The following configuration limits all requests independently from the user. It allows a maximum of 5 requests within 10 seconds independently from the user. +Utilizing the '@RateLimiting' annotation, AOP intercepts your method. This grants you comprehensive access to method parameters, empowering you to define the rate limit key or conditionally skip rate limiting with ease. - -[source,yml] +[source,properties] ---- -bucket4j: - enabled: true - filters: - - cache-name: buckets - url: .* - rate-limits: - - bandwidths: - - capacity: 5 - time: 10 - unit: seconds ----- - -For Ehcache 3 you also need a *ehcache.xml* which can be placed in the classpath. -The configured cache name *buckets* must be defined in the configuration file. - -[source,yml] ----- -spring: - cache: - jcache: - config: classpath:ehcache.xml ----- - -[source,xml] +bucket4j.methods[0].name=not_an_admin # the name of the configuration for annotation reference +bucket4j.methods[0].cache-name=buckets # the name of the cache +bucket4j.methods[0].rate-limits[0].bandwidths[0].capacity=5 # refills 5 tokens every 10 seconds (intervall) +bucket4j.methods[0].rate-limits[0].bandwidths[0].time=10 +bucket4j.methods[0].rate-limits[0].bandwidths[0].unit=seconds +bucket4j.methods[0].rate-limits[0].bandwidths[0].refill-speed=intervall ---- - - - - 3600 - - 1000000 - - +[source,java] ---- +@RateLimiting( + // reference to the property file + name = "not_an_admin", + // only when the parameter is not admin + executeCondition = "#myParamName != 'admin'", + // the method name is added to the cache key to prevent conflicts with other methods + ratePerMethod = true, + // if the limit is exceeded the fallback method is called. If not provided an exception is thrown + fallbackMethodName = "myFallbackMethod") + public String execute(String myParamName) { + log.info("Method with Param {} executed", myParamName); + return myParamName; + } -[[overview_cache_autoconfiguration]] -== Overview Cache Autoconfiguration - -The following list contains the Caching implementation which will be autoconfigured by this starter. - -[cols="1,1,1"] -|=== -|*Reactive* -|*Name* -|*cache-to-use* - -|N -|{url-config-cache}/jcache/JCacheBucket4jConfiguration.java[JSR 107 -JCache] -|jcache - -|Yes -|{url-config-cache}/ignite/IgniteBucket4jCacheConfiguration.java[Ignite] -|jcache-ignite - -|no -|{url-config-cache}/hazelcast/HazelcastSpringBucket4jCacheConfiguration.java[Hazelcast] -|hazelcast-spring - -|yes -|{url-config-cache}/hazelcast/HazelcastReactiveBucket4jCacheConfiguration.java[Hazelcast] -|hazelcast-reactive - -|Yes -|{url-config-cache}/infinispan/InfinispanBucket4jCacheConfiguration.java[Infinispan] -|infinispan - -|No -|{url-config-cache}/redis/jedis/JedisBucket4jConfiguration.java[Redis-Jedis] -|redis-jedis - -|Yes -|{url-config-cache}/redis/lettuce/LettuceBucket4jConfiguration.java[Redis-Lettuce] -|redis-lettuce - -|Yes -|{url-config-cache}/redis/redission/RedissonBucket4jConfiguration.java[Redis-Redisson] -|redis-redisson - -|=== - -Instead of determine the Caching Provider by the Bucket4j Spring Boot Starter project you can implement the SynchCacheResolver -or the AsynchCacheResolver by yourself. - -You can enable the cache auto configuration explicitly by using the *cache-to-use* property name or setting -it to an invalid value to disable all auto configurations. - -[source, properties] + public String myFallbackMethod(String myParamName) { + log.info("Fallback-Method with Param {} executed", myParamName); + return myParamName; + } ---- -bucket4j.cache-to-use=jcache # ----- -[[filters]] -== Filter -=== Filter strategy +[[project_configuration]] +== Project Configuration -The filter strategy defines how the execution of the rate limits will be performed. +[[bucket4j_complete_properties]] +=== General Bucket4j properties [source, properties] ---- -bucket4j.filters[0].strategy=first # [first, all] ----- - -==== first - -The *first* is the default strategy. This the default strategy which only executes one rate limit configuration. - -==== all - -The *all* strategy executes all rate limit independently. - -[[cache_key]] -== Cache Key - -To differentiate incoming request you can provide an expression which is used as a key resolver for the underlying cache. - -The expression uses the https://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html[Spring Expression Language] (SpEL) which -provides the most flexible solution to determine the cache key written in one line of code. https://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html#expressions-spel-compilation[The expression compiles to a Java class which will be used]. - -Depending on the filter method [servlet, webflux, gateway] different SpEL root objects can be used in the expression so that you have a direct access to the method of these request objects: - -* servlet: jakarta.servlet.http.HttpServletRequest (e.g. getRemoteAddr() or getRequestURI()) -* webflux: org.springframework.http.server.reactive.ServerHttpRequest -* gateway: org.springframework.http.server.reactive.ServerHttpRequest - -The configured URL which is used for filtering is added to the cache-key to provide a unique cache-key for multiple URL. -You can read more about it https://github.com/MarcGiffing/bucket4j-spring-boot-starter/issues/19[here]. +bucket4j.enabled=true # enable/disable bucket4j support +bucket4j.cache-to-use= # If you use multiple caching implementation in your project and you want to choose a specific one you can set the cache here (jcache, hazelcast, ignite, redis) -*Limiting based on IP-Address*: -[source] ----- -getRemoteAddress() +# Optional default metric tags for all filters +bucket4j.default-metric-tags[0].key=IP +bucket4j.default-metric-tags[0].expression=getRemoteAddr() +bucket4j.default-metric-tags[0].types=REJECTED_COUNTER ---- +==== Filter Bucket4j properties -*Limiting based on Username - If not logged in use IP-Address*: -[source] ----- -@securityService.username()?: getRemoteAddr() ----- -[source,java] +[source, properties] ---- -/** -* You can define custom beans like the SecurityService which can be used in the SpEl expressions. -**/ -@Service -public class SecurityService { - - public String username() { - String name = SecurityContextHolder.getContext().getAuthentication().getName(); - if(name == "anonymousUser") { - return null; - } - return name; - } - -} +bucket4j.filter-config-caching-enabled=true #Enable/disable caching of filter configurations. +bucket4j.filter-config-cache-name=filterConfigCache #The name of the cache where the configurations are stored. Defaults to 'filterConfigCache'. +bucket4j.filters[0].id=filter1 # The id of the filter. This field is mandatory when configuration caching is enabled and should always be a unique string. +bucket4j.filters[0].major-version=1 # [min = 1, max = 92 million] Major version number of the configuration. +bucket4j.filters[0].minor-version=1 # [min = 1, max = 99 billion] Minor version number of the configuration. (intended for internal updates, for example based on CPU-usage, but can also be used for regular updates) +bucket4j.filters[0].cache-name=buckets # the name of the cache key +bucket4j.filters[0].filter-method=servlet # [servlet,webflux,gateway] +bucket4j.filters[0].filter-order= # Per default the lowest integer plus 10. Set it to a number higher then zero to execute it after e.g. Spring Security. +bucket4j.filters[0].http-content-type=application/json +bucket4j.filters[0].http-status-code=TOO_MANY_REQUESTS # Enum value of org.springframework.http.HttpStatus +bucket4j.filters[0].http-response-body={ "message": "Too many requests" } # the json response which should be added to the body +bucket4j.filters[0].http-response-headers.=MY_CUSTOM_HEADER_VALUE # You can add any numbers of custom headers +bucket4j.filters[0].hide-http-response-headers=true # Hides response headers like x-rate-limit-remaining or x-rate-limit-retry-after-seconds on rate limiting +bucket4j.filters[0].url=.* # a regular expression +bucket4j.filters[0].strategy=first # [first, all] if multiple rate limits configured the 'first' strategy stops the processing after the first matching +bucket4j.filters[0].rate-limits[0].cache-key=getRemoteAddr() # defines the cache key. It will be evaluated with the Spring Expression Language +bucket4j.filters[0].rate-limits[0].num-tokens=1 # The number of tokens to consume +bucket4j.filters[0].rate-limits[0].execute-condition=1==1 # an optional SpEl expression to decide to execute the rate limit or not +bucket4j.filters[1].rate-limits[0].post-execute-condition= # an optional SpEl expression to decide if the token consumption should only estimated for the incoming request and the returning response used to check if the token must be consumed: getStatus() eq 401 +bucket4j.filters[0].rate-limits[0].execute-predicates[0]=PATH=/hello,/world # On the HTTP Path as a list +bucket4j.filters[0].rate-limits[0].execute-predicates[1]=METHOD=GET,POST # On the HTTP Method +bucket4j.filters[0].rate-limits[0].execute-predicates[2]=QUERY=HELLO # Checks for the existence of a Query Parameter +bucket4j.filters[0].rate-limits[0].skip-condition=1==1 # an optional SpEl expression to skip the rate limit +bucket4j.filters[0].rate-limits[0].tokens-inheritance-strategy=RESET # [RESET, AS_IS, ADDITIVE, PROPORTIONALLY], defaults to RESET and is only used for dynamically updating configurations +bucket4j.filters[0].rate-limits[0].bandwidths[0].id=bandwidthId # Optional when using tokensInheritanceStrategy.RESET or if the rate-limit only contains 1 bandwidth. The id should be unique within the rate-limit. +bucket4j.filters[0].rate-limits[0].bandwidths[0].capacity=10 +bucket4j.filters[0].rate-limits[0].bandwidths[0].refill-capacity= # default is capacity +bucket4j.filters[0].rate-limits[0].bandwidths[0].time=1 +bucket4j.filters[0].rate-limits[0].bandwidths[0].unit=minutes +bucket4j.filters[0].rate-limits[0].bandwidths[0].initial-capacity= # Optional initial tokens +bucket4j.filters[0].rate-limits[0].bandwidths[0].refill-speed=greedy # [greedy,interval] +bucket4j.filters[0].metrics.enabled=true +bucket4j.filters[0].metrics.types=CONSUMED_COUNTER,REJECTED_COUNTER # (optional) if your not interested in the consumed counter you can specify only the rejected counter +bucket4j.filters[0].metrics.tags[0].key=IP +bucket4j.filters[0].metrics.tags[0].expression=getRemoteAddr() +bucket4j.filters[0].metrics.tags[0].types=REJECTED_COUNTER # (optionial) this tag should for example only be applied for the rejected counter +bucket4j.filters[0].metrics.tags[1].key=URL +bucket4j.filters[0].metrics.tags[1].expression=getRequestURI() +bucket4j.filters[0].metrics.tags[2].key=USERNAME +bucket4j.filters[0].metrics.tags[2].expression=@securityService.username() != null ? @securityService.username() : 'anonym' ---- -[[cache_overview]] - - [[refill_speed]] -== Refill Speed +==== Refill Speed The refill speed defines the period of the regeneration of consumed tokens. -This starter supports two types of token regeneration. The refill speed can be set with the following +This starter supports two types of token regeneration. The refill speed can be set with the following property: [source, properties] @@ -331,16 +197,33 @@ bucket4j.filters[0].rate-limits[0].bandwidths[0].refill-speed=greedy # [greedy,i You can read more about the refill speed in the https://bucket4j.com/8.1.1/toc.html#refill[official documentation]. +[[rate_limit_strategy]] +==== Rate Limit Strategy + +If multiple rate limits are defined the strategy defines how many of them should be executed. + +[source, properties] +---- +bucket4j.filters[0].strategy=first # [first, all] +---- + +===== first + +The *first* is the default strategy. This the default strategy which only executes one rate limit configuration. If a rate limit configuration is skipped due to the provided condition. It does not count as an executed rate limit. + +===== all + +The *all* strategy executes all rate limit independently. [[skip_execution_predicates]] -== Skip and Execution Predicates (experimental) +==== Skip and Execution Predicates (experimental) Skip and Execution Predicates can be used to conditionally skip or execute the rate limiting. Each predicate has a unique name and a self-contained configuration. The following section describes the build in Execution Predicates and how to use them. -=== Path Predicates +===== Path Predicates -The Path Predicate takes a list of path parameters where any of the paths must match. +The Path Predicate takes a list of path parameters where any of the paths must match. See https://github.com/spring-projects/spring-framework/blob/main/spring-web/src/main/java/org/springframework/web/util/pattern/PathPattern.java[PathPattern] for the available configuration options. Segments are not evaluated further. [source, properties] @@ -351,7 +234,7 @@ bucket4j.filters[0].rate-limits[0].execute-predicates[0]=PATH=/hello,/world,/adm Matches the paths '/hello', '/world' or '/admin'. -=== Method Predicate +===== Method Predicate The Method Predicate takes a list of method parameters where any of the methods must match the used HTTP method. @@ -361,7 +244,7 @@ bucket4j.filters[0].rate-limits[0].execute-predicates[0]=METHOD=GET,POST ---- Matches if the HTTP method is 'GET' or 'POST'. -=== Query Predicate +===== Query Predicate The Query Predicate takes a single parameter to check for the existence of the query parameter. @@ -371,7 +254,7 @@ bucket4j.filters[0].rate-limits[0].execute-predicates[0]=QUERY=PARAM_1 ---- Matches if the query parameter 'PARAM_1' exists. -=== Header Predicate +===== Header Predicate The Header Predicate takes to parameters. @@ -383,7 +266,7 @@ bucket4j.filters[0].rate-limits[0].execute-predicates[0]=Content-Type,.*PDF.* ---- Matches if the query parameter 'PARAM_1' exists. -=== Custom Predicate +===== Custom Predicate You can also define you own Execution Predicate: @@ -394,7 +277,7 @@ You can also define you own Execution Predicate: public class MyQueryExecutePredicate extends ExecutePredicate { private String query; - + public String name() { // The name which can be used on the properties return "MY_QUERY"; @@ -410,22 +293,78 @@ public class MyQueryExecutePredicate extends ExecutePredicate parseSimpleConfig(String simpleConfig) { // the configuration which is configured behind the equal sign // MY_QUERY=P_1 -> simpleConfig == "P_1" - // + // this.query = simpleConfig; return this; } } ---- +[[cache_key_filter]] +=== Cache Key for Filter + +To differentiate incoming request (e.g. by IP address) you can provide an expression which is used as a key resolver for the underlying cache. + +Depending on the filter method [servlet, webflux, gateway] different SpEL root objects can be used in the expression so that you have a direct access to the method of these request objects: + +* servlet: jakarta.servlet.http.HttpServletRequest (e.g. getRemoteAddr() or getRequestURI()) +* webflux: org.springframework.http.server.reactive.ServerHttpRequest +* gateway: org.springframework.http.server.reactive.ServerHttpRequest + +The configured URL which is used for filtering is added to the cache-key to provide a unique cache-key for multiple URL. +You can read more about it https://github.com/MarcGiffing/bucket4j-spring-boot-starter/issues/19[here]. + +*Limiting based on IP-Address*: +[source] +---- +getRemoteAddress() +---- + +*Limiting based on Username - If not logged in use IP-Address*: +[source] +---- +@securityService.username()?: getRemoteAddr() +---- +[source,java] +---- +/** +* You can define custom beans like the SecurityService which can be used in the SpEl expressions. +**/ +@Service +public class SecurityService { + + public String username() { + String name = SecurityContextHolder.getContext().getAuthentication().getName(); + if(name.equals("anonymousUser")) { + return null; + } + return name; + } + +} +---- + +[[post-execute-condition]] +=== Post Execution (Consume) Condition + +If you define a post execution condition the available tokens are not consumed on a rate limit configuration execution. It will only estimate the remaining available tokens. Only if there are no tokens left the rate limit is applied by. If the request was proceeded by the application we can check the return value check if the token should be consumed. + +Example: You want to limit the rate only for unauthorized users. You can't consume the available token for the incoming request because you don't know if the user will be authenticated afterward. With the post execute condition you can check the HTTP response status code and only consume the token if it has the status Code 401 UNAUTHORIZED. + +image::src/main/doc/plantuml/post_execution_condition.png[] + +[[features]] +== Features + [[dynamic_config_updates]] -== Dynamically updating rate limits (experimental) +=== Dynamically updating rate limits (experimental) Sometimes it might be useful to modify filter configurations during runtime. In order to support this behaviour a cache-based configuration update system has been added. The following section describes what configurations are required to enable this feature. -=== Properties +==== Properties -==== base properties +===== base properties In order to dynamically update rate limits, it is required to enable caching for filter configurations. [source, properties] ---- @@ -433,7 +372,7 @@ bucket4j.filter-config-caching-enabled=true #Enable/disable caching of filter c bucket4j.filter-config-cache-name=filterConfigCache #The name of the cache where the configurations are stored. Defaults to 'filterConfigCache'. ---- -==== Filter properties +===== Filter properties - When filter caching is enabled, it is mandatory to configure a unique id for every filter. - Configurations are implicitly replaced based on a combination of the major and minor version. If changes are made to the configuration without increasing either of the version numbers, it is most likely that the changes will not be applied. Instead the cached configuration will be used. [source, properties] @@ -443,7 +382,7 @@ bucket4j.filters[0].major-version=1 #[min = 1, max = 92 million] Major version n bucket4j.filters[0].minor-version=1 #[min = 1, max = 99 billion] Minor version number. (intended for internal updates, for example based on CPU-usage, but can also be used for regular updates) ---- -==== RateLimit properties +===== RateLimit properties For each ratelimit a tokens inheritance strategy can be configured. This strategy will determine how to handle existing rate limits when replacing a configuration. If no strategy is configured it will default to 'RESET'. Further explanation of the strategies can be found at https://bucket4j.com/8.1.1/toc.html#tokensinheritancestrategy-explanation[Bucket4J TokensInheritanceStrategy explanation] @@ -453,7 +392,7 @@ Further explanation of the strategies can be found at https://bucket4j.com/8.1.1 bucket4j.filters[0].rate-limits[0].tokens-inheritance-strategy=RESET #[RESET, AS_IS, ADDITIVE, PROPORTIONALLY] ---- -==== Bandwidth properties +===== Bandwidth properties This property is only mandatory when *BOTH* of the following statements apply to your configuration. - The rate-limit uses a different TokensInheritanceStrategy than 'RESET' @@ -466,7 +405,7 @@ It is possible to configure id's when 'RESET' strategy is applied, but the id's bucket4j.filters[0].rate-limits[0].bandwidths[0].id=bandwidthId #The id of the bandwidth; Optional when the rate-limit only contains 1 bandwidth or when using tokensInheritanceStrategy.RESET. ---- -=== Example project +==== Example project An example on how to dynamically update a filter can be found at: {url-examples}/caffeine[Caffeine example project]. @@ -483,66 +422,8 @@ Some important considerations: ** cacheName not changed -> BAD_REQUEST - The configCacheManager currently does *not* contain validation in the setValue method. The configuration should be validated before calling the this method. -[[bucket4j_complete_properties]] -== Bucket4j properties - - -[source, properties] ----- -bucket4j.enabled=true # enable/disable bucket4j support -bucket4j.cache-to-use= # If you use multiple caching implementation in your project and you want to choose a specific one you can set the cache here (jcache, hazelcast, ignite, redis) -bucket4j.filter-config-caching-enabled=true #Enable/disable caching of filter configurations. -bucket4j.filter-config-cache-name=filterConfigCache #The name of the cache where the configurations are stored. Defaults to 'filterConfigCache'. -bucket4j.filters[0].id=filter1 # The id of the filter. This field is mandatory when configuration caching is enabled and should always be a unique string. -bucket4j.filters[0].major-version=1 # [min = 1, max = 92 million] Major version number of the configuration. -bucket4j.filters[0].minor-version=1 # [min = 1, max = 99 billion] Minor version number of the configuration. (intended for internal updates, for example based on CPU-usage, but can also be used for regular updates) -bucket4j.filters[0].cache-name=buckets # the name of the cache key -bucket4j.filters[0].filter-method=servlet # [servlet,webflux,gateway] -bucket4j.filters[0].filter-order= # Per default the lowest integer plus 10. Set it to a number higher then zero to execute it after e.g. Spring Security. -bucket4j.filters[0].http-content-type=application/json -bucket4j.filters[0].http-status-code=TOO_MANY_REQUESTS # Enum value of org.springframework.http.HttpStatus -bucket4j.filters[0].http-response-body={ "message": "Too many requests" } # the json response which should be added to the body -bucket4j.filters[0].http-response-headers.=MY_CUSTOM_HEADER_VALUE # You can add any numbers of custom headers -bucket4j.filters[0].hide-http-response-headers=true # Hides response headers like x-rate-limit-remaining or x-rate-limit-retry-after-seconds on rate limiting -bucket4j.filters[0].url=.* # a regular expression -bucket4j.filters[0].strategy=first # [first, all] if multiple rate limits configured the 'first' strategy stops the processing after the first matching -bucket4j.filters[0].rate-limits[0].cache-key=getRemoteAddr() # defines the cache key. It will be evaluated with the Spring Expression Language -bucket4j.filters[0].rate-limits[0].num-tokens=1 # The number of tokens to consume -bucket4j.filters[0].rate-limits[0].execute-condition=1==1 # an optional SpEl expression to decide to execute the rate limit or not -bucket4j.filters[1].rate-limits[0].post-execute-condition= # an optional SpEl expression to decide if the token consumption should only estimated for the incoming request and the returning response used to check if the token must be consumed: getStatus() eq 401 -bucket4j.filters[0].rate-limits[0].execute-predicates[0]=PATH=/hello,/world # On the HTTP Path as a list -bucket4j.filters[0].rate-limits[0].execute-predicates[1]=METHOD=GET,POST # On the HTTP Method -bucket4j.filters[0].rate-limits[0].execute-predicates[2]=QUERY=HELLO # Checks for the existence of a Query Parameter -bucket4j.filters[0].rate-limits[0].skip-condition=1==1 # an optional SpEl expression to skip the rate limit -bucket4j.filters[0].rate-limits[0].tokens-inheritance-strategy=RESET # [RESET, AS_IS, ADDITIVE, PROPORTIONALLY], defaults to RESET and is only used for dynamically updating configurations -bucket4j.filters[0].rate-limits[0].bandwidths[0].id=bandwidthId # Optional when using tokensInheritanceStrategy.RESET or if the rate-limit only contains 1 bandwidth. The id should be unique within the rate-limit. -bucket4j.filters[0].rate-limits[0].bandwidths[0].capacity=10 -bucket4j.filters[0].rate-limits[0].bandwidths[0].refill-capacity= # default is capacity -bucket4j.filters[0].rate-limits[0].bandwidths[0].time=1 -bucket4j.filters[0].rate-limits[0].bandwidths[0].unit=minutes -bucket4j.filters[0].rate-limits[0].bandwidths[0].initial-capacity= # Optional initial tokens -bucket4j.filters[0].rate-limits[0].bandwidths[0].refill-speed=greedy # [greedy,interval] -bucket4j.filters[0].metrics.enabled=true -bucket4j.filters[0].metrics.types=CONSUMED_COUNTER,REJECTED_COUNTER # (optional) if your not interested in the consumed counter you can specify only the rejected counter -bucket4j.filters[0].metrics.tags[0].key=IP -bucket4j.filters[0].metrics.tags[0].expression=getRemoteAddr() -bucket4j.filters[0].metrics.tags[0].types=REJECTED_COUNTER # (optionial) this tag should for example only be applied for the rejected counter -bucket4j.filters[0].metrics.tags[1].key=URL -bucket4j.filters[0].metrics.tags[1].expression=getRequestURI() -bucket4j.filters[0].metrics.tags[2].key=USERNAME -bucket4j.filters[0].metrics.tags[2].expression=@securityService.username() != null ? @securityService.username() : 'anonym' - -# Optional default metric tags for all filters -bucket4j.default-metric-tags[0].key=IP -bucket4j.default-metric-tags[0].expression=getRemoteAddr() -bucket4j.default-metric-tags[0].types=REJECTED_COUNTER - -# Hide HTTP response headers ----- - - [[monitoring]] -== Monitoring - Spring Boot Actuator +=== Monitoring - Spring Boot Actuator Spring Boot ships with a great support for collecting metrics. This project automatically provides metric information about the consumed and rejected buckets. You can extend these information with configurable https://micrometer.io/docs/concepts#_tag_naming[custom tags] like the username or the IP-Address which can then be evaluated in a monitoring system like prometheus/grafana. @@ -551,7 +432,7 @@ Spring Boot ships with a great support for collecting metrics. This project auto bucket4j: enabled: true filters: - - cache-name: buckets + - cache-name: buckets filter-method: servlet filter-order: 1 url: .* @@ -573,9 +454,148 @@ bucket4j: unit: minutes ---- +[[appendix]] +== Appendix + +[[migration_guide]] +=== Migration Guide + +This section is meant to help you migrate your application to new version of this starter project. + +==== Spring Boot Starter Bucket4j 0.12 + +* Removed deprecated expression property + +==== Spring Boot Starter Bucket4j 0.9 + +* Upgrade to Spring Boot 3 +* Spring Boot 3 requires Java 17 so use at least Java 17 +* Replaced Java 8 compatible Bucket4j dependencies +* Exclude example webflux-infinispan due to startup problems + +==== Spring Boot Starter Bucket4j 0.8 + +===== Compatibility to Java 8 + +The version 0.8 tries to be compatible with Java 8 as long as Bucket4j is supporting Java 8. With the release +of Bucket4j 8.0.0 Bucket4j decided to migrate to Java 11 but provides dedicated artifacts for Java 8. +The project is switching to the dedicated artifacts which supports Java 8. You can read more about +it https://github.com/bucket4j/bucket4j#java-compatibility-matrix[here]. + +===== Rename property expression to cache-key + +The property *..rate-limits[0].expression* is renamed to *..rate-limits[0].cache-key*. +An Exception is thrown on startup if the *expression* property is configured. + +To ensure that the property is not filled falsely the property is marked with *@Null*. This change requires +a Bean Validation implementation. + +===== JSR 380 - Bean Validation implementation required + +To ensure that the Bucket4j property configuration is correct an Validation API implementation is required. +You can add the Spring Boot Starter Validation which will automatically configures one. + +[source, xml] +---- + + org.springframework.boot + spring-boot-starter-validation + +---- + +===== Explicit Configuration of the Refill Speed - API Break + +The refill speed of the Buckets can now configured explicitly with the Enum RefillSpeed. You can choose between +a greedy or interval refill see the https://bucket4j.com/8.1.1/toc.html#refill[official documentation]. + +Before 0.8 the refill speed was configured implicitly by setting the fixed-refill-interval property explicit. + +[source, properties] +---- +bucket4j.filters[0].rate-limits[0].bandwidths[0].fixed-refill-interval=0 +bucket4j.filters[0].rate-limits[0].bandwidths[0].fixed-refill-interval-unit=minutes +---- + +These properties are removed and replaced by the following configuration: + +[source, properties] +---- +bucket4j.filters[0].rate-limits[0].bandwidths[0].refill-speed=interval +---- + +You can read more about the refill speed configuration here <> + +[[overview_cache_autoconfiguration]] +=== Overview Cache Autoconfiguration + +The following list contains the Caching implementation which will be autoconfigured by this starter. + +[cols="1,1,1"] +|=== +|*Reactive* +|*Name* +|*cache-to-use* + +|N +|{url-config-cache}/jcache/JCacheBucket4jConfiguration.java[JSR 107 -JCache] +|jcache + +|Yes +|{url-config-cache}/ignite/IgniteBucket4jCacheConfiguration.java[Ignite] +|jcache-ignite + +|no +|{url-config-cache}/hazelcast/HazelcastSpringBucket4jCacheConfiguration.java[Hazelcast] +|hazelcast-spring + +|yes +|{url-config-cache}/hazelcast/HazelcastReactiveBucket4jCacheConfiguration.java[Hazelcast] +|hazelcast-reactive + +|Yes +|{url-config-cache}/infinispan/InfinispanBucket4jCacheConfiguration.java[Infinispan] +|infinispan + +|No +|{url-config-cache}/redis/jedis/JedisBucket4jConfiguration.java[Redis-Jedis] +|redis-jedis + +|Yes +|{url-config-cache}/redis/lettuce/LettuceBucket4jConfiguration.java[Redis-Lettuce] +|redis-lettuce + +|Yes +|{url-config-cache}/redis/redission/RedissonBucket4jConfiguration.java[Redis-Redisson] +|redis-redisson + +|=== + +Instead of determine the Caching Provider by the Bucket4j Spring Boot Starter project you can implement the SynchCacheResolver +or the AsynchCacheResolver by yourself. + +You can enable the cache auto configuration explicitly by using the *cache-to-use* property name or setting +it to an invalid value to disable all auto configurations. + +[source, properties] +---- +bucket4j.cache-to-use=jcache # +---- + +[[examples]] +=== Examples + +* {url-examples}/ehcache[Ehcache] +* {url-examples}/hazelcast[Hazelcast] +* {url-examples}/caffeine[Caffeine] +* {url-examples}/redis-jedis[Redis Jedis] +* {url-examples}/redis-lettuce[Redis Lettuce] +* {url-examples}/redis-redisson[Redis Redisson] +* {url-examples}/webflux[Webflux (Async)] +* {url-examples}/gateway[Spring Cloud Gateway (Async)] +* {url-examples}/webflux-infinispan[Infinispan] -[[configuration_examples]] -== Configuration via properties +[[property_configuration_examples]] +=== Property Configuration Examples Simple configuration to allow a maximum of 5 requests within 10 seconds independently from the user. @@ -583,12 +603,12 @@ Simple configuration to allow a maximum of 5 requests within 10 seconds independ ---- bucket4j: enabled: true - filters: - - cache-name: buckets + filters: + - cache-name: buckets url: .* rate-limits: - - bandwidths: - - capacity: 5 + - bandwidths: + - capacity: 5 time: 10 unit: seconds ---- @@ -601,8 +621,8 @@ you havn't to check in the second rate-limit that the user is logged in. Only th bucket4j: enabled: true filters: - - cache-name: buckets - filter-method: servlet + - cache-name: buckets + filter-method: servlet url: .* rate-limits: - execute-condition: @securityService.notSignedIn() # only for not logged in users @@ -611,7 +631,7 @@ bucket4j: - capacity: 10 time: 1 unit: minutes - - execute-condition: "@securityService.username() != 'admin'" # strategy is only evaluate first. so the user must be logged in and user is not admin + - execute-condition: "@securityService.username() != 'admin'" # strategy is only evaluate first. so the user must be logged in and user is not admin expression: @securityService.username() bandwidths: - capacity: 1000 @@ -636,27 +656,27 @@ bucket4j: url: /admin* rate-limits: bandwidths: # maximum of 5 requests within 10 seconds - - capacity: 5 + - capacity: 5 time: 10 unit: seconds - - cache-name: buckets + - cache-name: buckets url: /public* rate-limits: - expression: getRemoteAddress() # IP based filter bandwidths: # maximum of 5 requests within 10 seconds - - capacity: 5 + - capacity: 5 time: 10 unit: seconds - - cache-name: buckets + - cache-name: buckets url: /users* rate-limits: - skip-condition: "@securityService.username() == 'admin'" # we don't check the rate limit if user is the admin user - expression: "@securityService.username()?: getRemoteAddr()" # use the username as key. if authenticated use the ip address - bandwidths: + expression: "@securityService.username()?: getRemoteAddr()" # use the username as key. if authenticated use the ip address + bandwidths: - capacity: 100 time: 1 unit: seconds - capacity: 10000 time: 1 - unit: minutes ----- + unit: minutes +---- \ No newline at end of file diff --git a/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/Condition.java b/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/Condition.java index 38495138..05d5826e 100644 --- a/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/Condition.java +++ b/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/Condition.java @@ -9,9 +9,9 @@ public interface Condition { /** * - * @param request e.g. to skip or execute rate limit based on the IP address + * @param expressionParams parameters to evaluate the expression * @return true if the rate limit check should be skipped */ - boolean evalute(R request); + boolean evaluate(ExpressionParams expressionParams); } diff --git a/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/ExpressionParams.java b/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/ExpressionParams.java new file mode 100644 index 00000000..183ab4a2 --- /dev/null +++ b/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/ExpressionParams.java @@ -0,0 +1,33 @@ +package com.giffing.bucket4j.spring.boot.starter.context; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.expression.Expression; + +import java.util.HashMap; +import java.util.Map; + +/** + * Parameter information for the evaluation of a Spring {@link Expression} + * + * @param the type of the root object which us used for the SpEl expression. + */ +@RequiredArgsConstructor +public class ExpressionParams { + + @Getter + private final R rootObject; + + @Getter + private final Map params = new HashMap<>(); + + public void addParam(String name, Object value) { + params.put(name, value); + } + + public ExpressionParams addParams(Map params) { + this.params.putAll(params); + return this; + } + +} diff --git a/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/KeyFilter.java b/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/KeyFilter.java index 83956e20..5a1d926b 100644 --- a/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/KeyFilter.java +++ b/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/KeyFilter.java @@ -9,11 +9,11 @@ public interface KeyFilter { /** * Return the unique Bucket4j storage key. You can think of the key as a unique identifier - * which is for example an IP-Address or a user name. The rate limit is then applied to each individual key. + * which is for example an IP-Address or a username. The rate limit is then applied to each individual key. * - * @param request HTTP request information of the current request - * @return the key to identify the the rate limit (IP, username, ...) + * @param expressionParams the expression params + * @return the key to identify the rate limit (IP, username, ...) */ - String key(R request); + String key(ExpressionParams expressionParams); } diff --git a/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/RateLimitCheck.java b/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/RateLimitCheck.java index 7ec5e7fe..b82213c6 100644 --- a/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/RateLimitCheck.java +++ b/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/RateLimitCheck.java @@ -1,19 +1,19 @@ package com.giffing.bucket4j.spring.boot.starter.context; +import com.giffing.bucket4j.spring.boot.starter.context.properties.RateLimit; /** - * Used to check if the rate limit should be performed independently from the servlet|webflux|gateway request filter - * + * Used to check if the rate limit should be performed independently from the servlet|webflux|gateway request filter */ @FunctionalInterface public interface RateLimitCheck { - /** - * @param request the request information object - * - * @return null if no rate limit should be performed. (maybe skipped or shouldn't be executed). - */ - RateLimitResultWrapper rateLimit(R request); - + /** + * @param params parameter information + * @param mainRateLimit overwrites the rate limit configuration from the properties + * @return null if no rate limit should be performed. (maybe skipped or shouldn't be executed). + */ + RateLimitResultWrapper rateLimit(ExpressionParams params, RateLimit mainRateLimit); + } diff --git a/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/RateLimitConditionMatchingStrategy.java b/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/RateLimitConditionMatchingStrategy.java index 1a42f1b7..698e241a 100644 --- a/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/RateLimitConditionMatchingStrategy.java +++ b/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/RateLimitConditionMatchingStrategy.java @@ -2,21 +2,18 @@ /** * Bad name :-) - * - * If multiple rate limits configured this strategy decides when to stop - * the evaluation. - * - * + *

+ * If multiple rate limits configured this strategy decides when to stop the evaluation. */ public enum RateLimitConditionMatchingStrategy { - /** - * All rate limits should be evaluated - */ - ALL, - /** - * Only the first matching rate limit will be evaluated - */ - FIRST, - + /** + * All rate limits should be evaluated + */ + ALL, + /** + * Only the first matching rate limit will be evaluated + */ + FIRST, + } diff --git a/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/RateLimitException.java b/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/RateLimitException.java new file mode 100644 index 00000000..96f6e74a --- /dev/null +++ b/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/RateLimitException.java @@ -0,0 +1,8 @@ +package com.giffing.bucket4j.spring.boot.starter.context; + +/** + * This exception is thrown when the rate limit is reached in the context of a method level when using the + * {@link RateLimiting} annotation. + */ +public class RateLimitException extends RuntimeException { +} diff --git a/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/RateLimiting.java b/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/RateLimiting.java new file mode 100644 index 00000000..4ce760c2 --- /dev/null +++ b/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/RateLimiting.java @@ -0,0 +1,55 @@ +package com.giffing.bucket4j.spring.boot.starter.context; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface RateLimiting { + + /** + * @return The name of the rate limit configuration as a reference to the property file + */ + String name(); + + /** + * The cache key which is mayby modified the e.g. the method name {@link RateLimiting#ratePerMethod()} + * + * @return the cache key. + */ + String cacheKey() default ""; + + /** + * An optional execute condition which overrides the execute condition from the property file + * + * @return the expression in the Spring Expression Language format. + */ + String executeCondition() default ""; + + /** + * An optional execute condition which overrides the execute condition from the property file + * + * @return the expression in the Spring Expression Language format. + */ + String skipCondition() default ""; + + /** + * The Name of the annotated method will be added to the cache key. + * It's maybe a problem + * + * @return true if the method name should be added to the cache key. + */ + boolean ratePerMethod() default false; + + /** + * An optional fall back method when the rate limit occurs instead of throwing an exception. + * The return type must be the same... + * + * TODO + * + * @return the name of the public method which resists in the same class. + */ + String fallbackMethodName() default ""; +} diff --git a/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/Bucket4JBootProperties.java b/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/Bucket4JBootProperties.java index 40b9add6..b63eb379 100644 --- a/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/Bucket4JBootProperties.java +++ b/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/Bucket4JBootProperties.java @@ -3,6 +3,7 @@ import java.util.ArrayList; import java.util.List; +import com.giffing.bucket4j.spring.boot.starter.context.RateLimiting; import jakarta.validation.Valid; import jakarta.validation.constraints.AssertTrue; import jakarta.validation.constraints.NotBlank; @@ -15,58 +16,65 @@ /** * Holds all the relevant starter properties which can be configured with - * Spring Boots application.properties / application.yml configuration files. + * Spring Boots application.properties / application.yml configuration files. */ @Data @ConfigurationProperties(prefix = Bucket4JBootProperties.PROPERTY_PREFIX) @Validated public class Bucket4JBootProperties { - public static final String PROPERTY_PREFIX = "bucket4j"; - - /** - * Enables or disables the Bucket4j Spring Boot Starter. - */ - @NotNull - private Boolean enabled = true; - - /** - * Sets the cache implementation which should be auto configured. - * This property can be used if multiple caches are configured by the starter - * and you have to choose one due to a startup error. - *

    - *
  • jcache
  • - *
  • hazelcast
  • - *
  • ignite
  • - *
  • redis
  • - *
- */ - private String cacheToUse; - - private boolean filterConfigCachingEnabled = false; - - /** - * If Filter configuration caching is enabled, a cache with this name should exist, or it will cause an exception. - */ - @NotBlank - private String filterConfigCacheName = "filterConfigCache"; - - @Valid - private List filters = new ArrayList<>(); - - @AssertTrue(message = "FilterConfiguration caching is enabled, but not all filters have an identifier configured") - public boolean isValidFilterIds(){ - return !filterConfigCachingEnabled || filters.stream().noneMatch(filter -> filter.getId() == null); - } - - /** - * A list of default metric tags which should be applied to all filters - */ - @Valid - private List defaultMetricTags = new ArrayList<>(); - - public static String getPropertyPrefix() { - return PROPERTY_PREFIX; - } + public static final String PROPERTY_PREFIX = "bucket4j"; + + /** + * Enables or disables the Bucket4j Spring Boot Starter. + */ + @NotNull + private Boolean enabled = true; + + /** + * Sets the cache implementation which should be auto configured. + * This property can be used if multiple caches are configured by the starter + * and you have to choose one due to a startup error. + *
    + *
  • jcache
  • + *
  • hazelcast
  • + *
  • ignite
  • + *
  • redis
  • + *
+ */ + private String cacheToUse; + + /** + * Configuration for the {@link RateLimiting} annotation on method level. + */ + @Valid + private List methods = new ArrayList<>(); + + private boolean filterConfigCachingEnabled = false; + + /** + * If Filter configuration caching is enabled, a cache with this name should exist, or it will cause an exception. + */ + @NotBlank + private String filterConfigCacheName = "filterConfigCache"; + + + @Valid + private List filters = new ArrayList<>(); + + @AssertTrue(message = "FilterConfiguration caching is enabled, but not all filters have an identifier configured") + public boolean isValidFilterIds() { + return !filterConfigCachingEnabled || filters.stream().noneMatch(filter -> filter.getId() == null); + } + + /** + * A list of default metric tags which should be applied to all filters + */ + @Valid + private List defaultMetricTags = new ArrayList<>(); + + public static String getPropertyPrefix() { + return PROPERTY_PREFIX; + } } diff --git a/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/MethodProperties.java b/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/MethodProperties.java new file mode 100644 index 00000000..4d3bd615 --- /dev/null +++ b/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/MethodProperties.java @@ -0,0 +1,31 @@ +package com.giffing.bucket4j.spring.boot.starter.context.properties; + +import com.giffing.bucket4j.spring.boot.starter.context.RateLimiting; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import lombok.Data; +import lombok.ToString; + +@Data +@ToString +public class MethodProperties { + + /** + * The name of the configuration to reference in the {@link RateLimiting} annotation. + */ + @NotBlank + private String name; + + /** + * The name of the cache. + */ + @NotBlank + private String cacheName; + + /** + * The rate limit configuration + */ + @NotNull + private RateLimit rateLimit; + +} \ No newline at end of file diff --git a/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/RateLimit.java b/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/RateLimit.java index accbdf53..9b8a8b9f 100644 --- a/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/RateLimit.java +++ b/bucket4j-spring-boot-starter-context/src/main/java/com/giffing/bucket4j/spring/boot/starter/context/properties/RateLimit.java @@ -1,67 +1,117 @@ package com.giffing.bucket4j.spring.boot.starter.context.properties; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - import com.giffing.bucket4j.spring.boot.starter.context.ExecutePredicateDefinition; import com.giffing.bucket4j.spring.boot.starter.context.constraintvalidations.ValidBandWidthIds; - -import jakarta.validation.Valid; -import jakarta.validation.constraints.*; - import io.github.bucket4j.TokensInheritanceStrategy; +import jakarta.validation.Valid; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; import lombok.Data; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + @Data @ValidBandWidthIds public class RateLimit implements Serializable { - - /** - * SpEl condition to check if the rate limit should be executed. If null there is no check. - */ - private String executeCondition; - - /** - * TODO comment - */ - private String postExecuteCondition; - - @Valid - private List executePredicates = new ArrayList<>(); - - /** - * SpEl condition to check if the rate-limit should apply. If null there is no check. - */ - private String skipCondition; - - @Valid - private List skipPredicates = new ArrayList<>(); - - /** - * SPEL expression to dynamic evaluate filter key - */ - @NotBlank - private String cacheKey = "1"; - - @Null(message = "The expression is depcreated since 0.8. Please use cache-key instead") - @Deprecated - private String expression; - - /** - * The number of tokens that should be consumed - */ - @NotNull - @Min(1) - private Integer numTokens = 1; - - @NotEmpty - @Valid - private List bandwidths = new ArrayList<>(); - - /** - * The token inheritance strategy to use when replacing the configuration of a bucket - */ - @NotNull - private TokensInheritanceStrategy tokensInheritanceStrategy = TokensInheritanceStrategy.RESET; + + /** + * SpEl condition to check if the rate limit should be executed. If null there is no check. + */ + private String executeCondition; + + /** + * If you provide a post execution condition. The incoming check only estimates the + * token consumption. It will not consume a token. This check is based on the response + * to decide if the token should be consumed or not. + * + * + */ + private String postExecuteCondition; + + @Valid + private List executePredicates = new ArrayList<>(); + + /** + * SpEl condition to check if the rate-limit should apply. If null there is no check. + */ + private String skipCondition; + + @Valid + private List skipPredicates = new ArrayList<>(); + + /** + * SPEL expression to dynamic evaluate filter key + */ + @NotBlank + private String cacheKey = "1"; + + /** + * The number of tokens that should be consumed + */ + @NotNull + @Min(1) + private Integer numTokens = 1; + + @NotEmpty + @Valid + private List bandwidths = new ArrayList<>(); + + /** + * The token inheritance strategy to use when replacing the configuration of a bucket + */ + @NotNull + private TokensInheritanceStrategy tokensInheritanceStrategy = TokensInheritanceStrategy.RESET; + + public RateLimit copy() { + var copy = new RateLimit(); + copy.setExecuteCondition(this.executeCondition); + copy.setPostExecuteCondition(this.postExecuteCondition); + copy.setExecutePredicates(this.executePredicates); + copy.setSkipCondition(this.skipCondition); + copy.setSkipPredicates(this.skipPredicates); + copy.setCacheKey(this.cacheKey); + copy.setNumTokens(this.numTokens); + copy.setBandwidths(this.bandwidths); + copy.setTokensInheritanceStrategy(this.tokensInheritanceStrategy); + return copy; + } + + public void consumeNotNullValues(RateLimit toConsume) { + if(toConsume == null) { + return; + } + + if (toConsume.getExecuteCondition() != null && !toConsume.getExecuteCondition().isEmpty()) { + this.setExecuteCondition(toConsume.getExecuteCondition()); + } + if (toConsume.getPostExecuteCondition() != null && !toConsume.getPostExecuteCondition().isEmpty()) { + this.setPostExecuteCondition(toConsume.getPostExecuteCondition()); + } + if (toConsume.getExecutePredicates() != null && !toConsume.getExecutePredicates().isEmpty()) { + this.setExecutePredicates(toConsume.getExecutePredicates()); + } + if (toConsume.getSkipCondition() != null && !toConsume.getSkipCondition().isEmpty()) { + this.setSkipCondition(toConsume.getSkipCondition()); + } + if (toConsume.getSkipPredicates() != null && !toConsume.getSkipPredicates().isEmpty()) { + this.setSkipPredicates(toConsume.getSkipPredicates()); + } + if (toConsume.getCacheKey() != null && !toConsume.getCacheKey().equals("1") && !toConsume.getCacheKey().isEmpty()) { + this.setCacheKey(toConsume.getCacheKey()); + } + if(toConsume.getNumTokens() != null && toConsume.getNumTokens() != 1) { + this.setNumTokens(toConsume.getNumTokens()); + } + if(toConsume.getBandwidths() != null && !toConsume.getBandwidths().isEmpty()) { + this.setBandwidths(toConsume.getBandwidths()); + } + if(toConsume.getTokensInheritanceStrategy() != null) { + this.setTokensInheritanceStrategy(toConsume.getTokensInheritanceStrategy()); + } + } + } \ No newline at end of file diff --git a/bucket4j-spring-boot-starter/pom.xml b/bucket4j-spring-boot-starter/pom.xml index c5c53153..da1657f2 100644 --- a/bucket4j-spring-boot-starter/pom.xml +++ b/bucket4j-spring-boot-starter/pom.xml @@ -98,6 +98,16 @@ ${redisson.version} provided + + org.springframework + spring-aop + provided + + + org.aspectj + aspectjweaver + provided + com.hazelcast hazelcast diff --git a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/aspect/AopConfig.java b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/aspect/AopConfig.java new file mode 100644 index 00000000..a9e8570d --- /dev/null +++ b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/aspect/AopConfig.java @@ -0,0 +1,38 @@ +package com.giffing.bucket4j.spring.boot.starter.config.aspect; + +import com.giffing.bucket4j.spring.boot.starter.config.cache.Bucket4jCacheConfiguration; +import com.giffing.bucket4j.spring.boot.starter.config.cache.SyncCacheResolver; +import com.giffing.bucket4j.spring.boot.starter.config.metrics.actuator.SpringBootActuatorConfig; +import com.giffing.bucket4j.spring.boot.starter.config.service.ServiceConfiguration; +import com.giffing.bucket4j.spring.boot.starter.context.RateLimiting; +import com.giffing.bucket4j.spring.boot.starter.context.properties.Bucket4JBootProperties; +import com.giffing.bucket4j.spring.boot.starter.service.RateLimitService; +import org.aspectj.lang.annotation.Aspect; +import org.springframework.boot.autoconfigure.AutoConfigureAfter; +import org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; + +/** + * Enables the support for the {@link RateLimiting} annotation to rate limit on method level. + */ +@Configuration +@ConditionalOnClass(Aspect.class) +@ConditionalOnProperty(prefix = Bucket4JBootProperties.PROPERTY_PREFIX, value = {"enabled"}, matchIfMissing = true) +@EnableConfigurationProperties({Bucket4JBootProperties.class}) +@AutoConfigureAfter(value = { CacheAutoConfiguration.class, Bucket4jCacheConfiguration.class }) +@ConditionalOnBean(value = SyncCacheResolver.class) +@Import(value = {ServiceConfiguration.class, Bucket4jCacheConfiguration.class, SpringBootActuatorConfig.class}) +public class AopConfig { + + @Bean + public RateLimitAspect rateLimitAspect(RateLimitService rateLimitService, Bucket4JBootProperties bucket4JBootProperties, SyncCacheResolver syncCacheResolver) { + return new RateLimitAspect(rateLimitService, bucket4JBootProperties.getMethods(), syncCacheResolver); + } + +} diff --git a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/aspect/RateLimitAspect.java b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/aspect/RateLimitAspect.java new file mode 100644 index 00000000..81f286ac --- /dev/null +++ b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/aspect/RateLimitAspect.java @@ -0,0 +1,173 @@ +package com.giffing.bucket4j.spring.boot.starter.config.aspect; + +import com.giffing.bucket4j.spring.boot.starter.config.cache.SyncCacheResolver; +import com.giffing.bucket4j.spring.boot.starter.context.*; +import com.giffing.bucket4j.spring.boot.starter.context.properties.MethodProperties; +import com.giffing.bucket4j.spring.boot.starter.context.properties.Metrics; +import com.giffing.bucket4j.spring.boot.starter.context.properties.RateLimit; +import com.giffing.bucket4j.spring.boot.starter.service.RateLimitService; +import jakarta.annotation.PostConstruct; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.aspectj.lang.reflect.MethodSignature; +import org.springframework.stereotype.Component; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Aspect +@Component +@RequiredArgsConstructor +@Slf4j +public class RateLimitAspect { + + private final RateLimitService rateLimitService; + + private final List methodProperties; + + private final SyncCacheResolver syncCacheResolver; + + private Map> rateLimitConfigResults = new HashMap<>(); + + @PostConstruct + public void init() { + for(var methodProperty : methodProperties) { + var proxyManagerWrapper = syncCacheResolver.resolve(methodProperty.getCacheName()); + var rateLimitConfig = RateLimitService.RateLimitConfig.builder() + .rateLimits(List.of(methodProperty.getRateLimit())) + .metricHandlers(List.of()) + .executePredicates(Map.of()) + .cacheName(methodProperty.getCacheName()) + .configVersion(0) + .keyFunction((rl, sr) -> { + KeyFilter keyFilter = rateLimitService.getKeyFilter(sr.getRootObject().getName(), rl); + return keyFilter.key(sr); + }) + .metrics(new Metrics()) + .proxyWrapper(proxyManagerWrapper) + .build(); + var rateLimitConfigResult = rateLimitService.configureRateLimit(rateLimitConfig); + rateLimitConfigResults.put(methodProperty.getName(), rateLimitConfigResult); + } + } + + @Pointcut("@annotation(com.giffing.bucket4j.spring.boot.starter.context.RateLimiting)") + private void methodsAnnotatedWithRateLimitAnnotation() { + } + + @Around("methodsAnnotatedWithRateLimitAnnotation()") + public Object processMethodsAnnotatedWithRateLimitAnnotation(ProceedingJoinPoint joinPoint) throws Throwable { + MethodSignature signature = (MethodSignature) joinPoint.getSignature(); + Method method = signature.getMethod(); + RateLimiting rateLimitAnnotation = method.getAnnotation(RateLimiting.class); + + Method fallbackMethod = null; + if(rateLimitAnnotation.fallbackMethodName() != null) { + var fallbackMethods = Arrays.stream(method.getDeclaringClass().getMethods()) + .filter(p -> p.getName().equals(rateLimitAnnotation.fallbackMethodName())) + .toList(); + if(fallbackMethods.size() > 1) { + throw new IllegalStateException("Found " + fallbackMethods.size() + " fallbackMethods for " + rateLimitAnnotation.fallbackMethodName()); + } + if(!fallbackMethods.isEmpty()) { + fallbackMethod = joinPoint.getTarget().getClass().getMethod(rateLimitAnnotation.fallbackMethodName(), ((MethodSignature) joinPoint.getSignature()).getParameterTypes()); + } + } + + Map params = collectExpressionParameter( + joinPoint.getArgs(), + signature.getParameterNames()); + + assertValidCacheName(rateLimitAnnotation); + + var annotationRateLimit = buildMainRateLimitConfiguration(rateLimitAnnotation); + var rateLimitConfigResult = rateLimitConfigResults.get(rateLimitAnnotation.name()); + + RateLimitConsumedResult consumedResult = performRateLimit(rateLimitConfigResult, method, params, annotationRateLimit); + + Object methodResult; + + if (consumedResult.allConsumed()) { + // no rate limit - execute the surrounding method + methodResult = joinPoint.proceed(); + performPostRateLimit(rateLimitConfigResult, method, methodResult); + } else if (fallbackMethod != null){ + return fallbackMethod.invoke(joinPoint.getTarget(), joinPoint.getArgs()); + } else { + throw new RateLimitException(); + } + + return methodResult; + } + + private static void performPostRateLimit(RateLimitService.RateLimitConfigresult rateLimitConfigResult, Method method, Object methodResult) { + for (var rlc : rateLimitConfigResult.getPostRateLimitChecks()) { + var result = rlc.rateLimit(method, methodResult); + if (result != null) { + log.debug("post-rate-limit;remaining-tokens:{}", result.getRateLimitResult().getRemainingTokens()); + } + } + } + + private static RateLimitConsumedResult performRateLimit(RateLimitService.RateLimitConfigresult rateLimitConfigResult, Method method, Map params, RateLimit annotationRateLimit) { + boolean allConsumed = true; + Long remainingLimit = null; + for (RateLimitCheck rl : rateLimitConfigResult.getRateLimitChecks()) { + var wrapper = rl.rateLimit(new ExpressionParams<>(method).addParams(params), annotationRateLimit); + if (wrapper != null && wrapper.getRateLimitResult() != null) { + var rateLimitResult = wrapper.getRateLimitResult(); + if (rateLimitResult.isConsumed()) { + remainingLimit = RateLimitService.getRemainingLimit(remainingLimit, rateLimitResult); + } else { + allConsumed = false; + break; + } + } + } + if(allConsumed) { + log.debug("rate-limit-remaining;limit:{}", remainingLimit); + } + return new RateLimitConsumedResult(allConsumed, remainingLimit); + } + + private record RateLimitConsumedResult(boolean allConsumed, Long remainingLimit) { + } + + /* + * Uses the configuration of the annotation to crate a main RateLimit which overrides + * the configuration from the property files. + */ + private static RateLimit buildMainRateLimitConfiguration(RateLimiting rateLimitAnnotation) { + var annotationRateLimit = new RateLimit(); + annotationRateLimit.setExecuteCondition(rateLimitAnnotation.executeCondition()); + annotationRateLimit.setCacheKey(rateLimitAnnotation.cacheKey()); + annotationRateLimit.setSkipCondition(rateLimitAnnotation.skipCondition()); + return annotationRateLimit; + } + + private void assertValidCacheName(RateLimiting rateLimitAnnotation) { + if(!rateLimitConfigResults.containsKey(rateLimitAnnotation.name())) { + throw new IllegalStateException("Could not find cache " + rateLimitAnnotation.name()); + } + } + + private static Map collectExpressionParameter(Object[] args, String[] parameterNames) { + Map params = new HashMap<>(); + for (int i = 0; i< args.length; i++) { + log.debug("expresion-params;name:{};arg:{}", parameterNames[i], args[i]); + params.put(parameterNames[i], args[i]); + } + return params; + } + + + + +} diff --git a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/Bucket4JBaseConfiguration.java b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/Bucket4JBaseConfiguration.java index 95979cbd..0e30693c 100644 --- a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/Bucket4JBaseConfiguration.java +++ b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/Bucket4JBaseConfiguration.java @@ -1,37 +1,21 @@ package com.giffing.bucket4j.spring.boot.starter.config.filter; -import java.lang.reflect.InvocationTargetException; -import java.time.Duration; -import java.util.List; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -import org.jetbrains.annotations.Nullable; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.expression.BeanFactoryResolver; -import org.springframework.expression.Expression; -import org.springframework.expression.ExpressionParser; -import org.springframework.expression.spel.support.StandardEvaluationContext; - import com.giffing.bucket4j.spring.boot.starter.config.cache.CacheManager; import com.giffing.bucket4j.spring.boot.starter.config.cache.CacheUpdateListener; import com.giffing.bucket4j.spring.boot.starter.config.cache.ProxyManagerWrapper; import com.giffing.bucket4j.spring.boot.starter.config.filter.reactive.gateway.Bucket4JAutoConfigurationSpringCloudGatewayFilter; import com.giffing.bucket4j.spring.boot.starter.config.filter.reactive.webflux.Bucket4JAutoConfigurationWebfluxFilter; import com.giffing.bucket4j.spring.boot.starter.config.filter.servlet.Bucket4JAutoConfigurationServletFilter; +import com.giffing.bucket4j.spring.boot.starter.service.RateLimitService; import com.giffing.bucket4j.spring.boot.starter.context.*; -import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricBucketListener; import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricHandler; -import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricTagResult; import com.giffing.bucket4j.spring.boot.starter.context.properties.*; -import com.giffing.bucket4j.spring.boot.starter.exception.ExecutePredicateInstantiationException; - -import io.github.bucket4j.Bandwidth; -import io.github.bucket4j.BucketConfiguration; -import io.github.bucket4j.ConfigurationBuilder; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import java.util.List; +import java.util.Map; + /** * Holds helper Methods which are reused by the * {@link Bucket4JAutoConfigurationServletFilter} @@ -40,79 +24,46 @@ * configuration classes */ @Slf4j +@RequiredArgsConstructor public abstract class Bucket4JBaseConfiguration implements CacheUpdateListener { + private final RateLimitService rateLimitService; + private final CacheManager configCacheManager; - protected Bucket4JBaseConfiguration(CacheManager configCacheManager) { - this.configCacheManager = configCacheManager; - } + private final List metricHandlers; - public abstract List getMetricHandlers(); + private final Map> executePredicates; public FilterConfiguration buildFilterConfig( Bucket4JConfiguration config, - ProxyManagerWrapper proxyWrapper, - ExpressionParser expressionParser, - ConfigurableBeanFactory beanFactory) { + ProxyManagerWrapper proxyWrapper) { + + var rateLimitConfig = RateLimitService.RateLimitConfig.builder() + .rateLimits(config.getRateLimits()) + .metricHandlers(metricHandlers) + .executePredicates(executePredicates) + .cacheName(config.getCacheName()) + .configVersion(config.getBucket4JVersionNumber()) + .keyFunction((rl, sr) -> { + KeyFilter keyFilter = rateLimitService.getKeyFilter(config.getUrl(), rl); + return keyFilter.key(sr); + }) + .metrics(config.getMetrics()) + .proxyWrapper(proxyWrapper) + .build(); + + var rateLimitConfigResult = rateLimitService.configureRateLimit(rateLimitConfig); FilterConfiguration filterConfig = mapFilterConfiguration(config); - - config.getRateLimits().forEach(rl -> { - log.debug("RL: {}", rl.toString()); - var configurationBuilder = prepareBucket4jConfigurationBuilder(rl); - var executionPredicate = prepareExecutionPredicates(rl); - var skipPredicate = prepareSkipPredicates(rl); - var bucketConfiguration = configurationBuilder.build(); - RateLimitCheck rlc = servletRequest -> { - var skipRateLimit = performSkipRateLimitCheck(expressionParser, beanFactory, rl, executionPredicate, skipPredicate, servletRequest); - if (!skipRateLimit) { - var key = getKeyFilter(filterConfig.getUrl(), rl, expressionParser, beanFactory).key(servletRequest); - var metricBucketListener = createMetricListener(config.getCacheName(), expressionParser, beanFactory, filterConfig, servletRequest); - log.debug("try-and-consume;key:{};tokens:{}", key, rl.getNumTokens()); - final long configVersion = config.getBucket4JVersionNumber(); - return proxyWrapper.tryConsumeAndReturnRemaining( - key, - rl.getNumTokens(), - rl.getPostExecuteCondition() != null, - bucketConfiguration, - metricBucketListener, - configVersion, - rl.getTokensInheritanceStrategy() - ); - } - return null; - }; - filterConfig.addRateLimitCheck(rlc); - - if (rl.getPostExecuteCondition() != null) { - log.debug("PRL: {}", rl); - PostRateLimitCheck postRlc = (request, response) -> { - var skipRateLimit = performPostSkipRateLimitCheck(expressionParser, beanFactory, rl, - executionPredicate, skipPredicate, request, response); - if (!skipRateLimit) { - var key = getKeyFilter(filterConfig.getUrl(), rl, expressionParser, beanFactory).key(request); - var metricBucketListener = createMetricListener(config.getCacheName(), expressionParser, beanFactory, filterConfig, request); - log.debug("try-and-consume-post;key:{};tokens:{}", key, rl.getNumTokens()); - final long configVersion = config.getBucket4JVersionNumber(); - return proxyWrapper.tryConsumeAndReturnRemaining( - key, - rl.getNumTokens(), - false, - bucketConfiguration, - metricBucketListener, - configVersion, - rl.getTokensInheritanceStrategy() - ); - } - return null; - }; - filterConfig.addPostRateLimitCheck(postRlc); - } - }); + rateLimitConfigResult.getRateLimitChecks().forEach(filterConfig::addRateLimitCheck); + rateLimitConfigResult.getPostRateLimitChecks().forEach(filterConfig::addPostRateLimitCheck); + return filterConfig; } + + private FilterConfiguration mapFilterConfiguration(Bucket4JConfiguration config) { FilterConfiguration filterConfig = new FilterConfiguration<>(); filterConfig.setUrl(config.getUrl().strip()); @@ -127,245 +78,7 @@ private FilterConfiguration mapFilterConfiguration(Bucket4JConfiguration c return filterConfig; } - private boolean performPostSkipRateLimitCheck(ExpressionParser expressionParser, - ConfigurableBeanFactory beanFactory, - RateLimit rl, - Predicate executionPredicate, - Predicate skipPredicate, - R request, - P response - ) { - var skipRateLimit = performSkipRateLimitCheck( - expressionParser, beanFactory, - rl, executionPredicate, - skipPredicate, request); - - if (!skipRateLimit && rl.getPostExecuteCondition() != null) { - skipRateLimit = !executeResponseCondition(rl, expressionParser, beanFactory).evalute(response); - log.debug("skip-rate-limit - post-execute-condition: {}", skipRateLimit); - } - - return skipRateLimit; - } - - private boolean performSkipRateLimitCheck(ExpressionParser expressionParser, - ConfigurableBeanFactory beanFactory, - RateLimit rl, - Predicate executionPredicate, - Predicate skipPredicate, - R request) { - boolean skipRateLimit = false; - if (rl.getSkipCondition() != null) { - skipRateLimit = skipCondition(rl, expressionParser, beanFactory).evalute(request); - log.debug("skip-rate-limit - skip-condition: {}", skipRateLimit); - } - - if (!skipRateLimit) { - skipRateLimit = skipPredicate.test(request); - log.debug("skip-rate-limit - skip-predicates: {}", skipRateLimit); - } - - if (!skipRateLimit && rl.getExecuteCondition() != null) { - skipRateLimit = !executeCondition(rl, expressionParser, beanFactory).evalute(request); - log.debug("skip-rate-limit - execute-condition: {}", skipRateLimit); - } - - if (!skipRateLimit) { - skipRateLimit = !executionPredicate.test(request); - log.debug("skip-rate-limit - execute-predicates: {}", skipRateLimit); - } - return skipRateLimit; - } - - protected abstract ExecutePredicate getExecutePredicateByName(String name); - - private ConfigurationBuilder prepareBucket4jConfigurationBuilder(RateLimit rl) { - var configBuilder = BucketConfiguration.builder(); - for (BandWidth bandWidth : rl.getBandwidths()) { - long capacity = bandWidth.getCapacity(); - long refillCapacity = bandWidth.getRefillCapacity() != null ? bandWidth.getRefillCapacity() : bandWidth.getCapacity(); - var refillPeriod = Duration.of(bandWidth.getTime(), bandWidth.getUnit()); - var bucket4jBandWidth = switch (bandWidth.getRefillSpeed()) { - case GREEDY -> - Bandwidth.builder().capacity(capacity).refillGreedy(refillCapacity, refillPeriod).id(bandWidth.getId()); - case INTERVAL -> - Bandwidth.builder().capacity(capacity).refillIntervally(refillCapacity, refillPeriod).id(bandWidth.getId()); - }; - - if (bandWidth.getInitialCapacity() != null) { - bucket4jBandWidth = bucket4jBandWidth.initialTokens(bandWidth.getInitialCapacity()); - } - configBuilder = configBuilder.addLimit(bucket4jBandWidth.build()); - } - return configBuilder; - } - - private MetricBucketListener createMetricListener(String cacheName, - ExpressionParser expressionParser, - ConfigurableBeanFactory beanFactory, - FilterConfiguration filterConfig, - R servletRequest) { - - var metricTagResults = getMetricTags( - expressionParser, - beanFactory, - filterConfig, - servletRequest); - - return new MetricBucketListener( - cacheName, - getMetricHandlers(), - filterConfig.getMetrics().getTypes(), - metricTagResults); - } - - private List getMetricTags( - ExpressionParser expressionParser, - ConfigurableBeanFactory beanFactory, - FilterConfiguration filterConfig, - R servletRequest) { - - return filterConfig - .getMetrics() - .getTags() - .stream() - .map(metricMetaTag -> { - var context = new StandardEvaluationContext(); - context.setBeanResolver(new BeanFactoryResolver(beanFactory)); - //TODO performance problem - how can the request object reused in the expression without setting it as a rootObject - var expr = expressionParser.parseExpression(metricMetaTag.getExpression()); - var value = expr.getValue(context, servletRequest, String.class); - - return new MetricTagResult(metricMetaTag.getKey(), value, metricMetaTag.getTypes()); - }).toList(); - } - /** - * Creates the key filter lambda which is responsible to decide how the rate limit will be performed. The key - * is the unique identifier like an IP address or a username. - * - * @param url is used to generated a unique cache key - * @param rateLimit the {@link RateLimit} configuration which holds the skip condition string - * @param expressionParser is used to evaluate the expression if the filter key type is EXPRESSION. - * @param beanFactory used to get full access to all java beans in the SpEl - * @return should not been null. If no filter key type is matching a plain 1 is returned so that all requests uses the same key. - */ - public KeyFilter getKeyFilter(String url, RateLimit rateLimit, ExpressionParser expressionParser, BeanFactory beanFactory) { - var cacheKeyexpression = rateLimit.getCacheKey(); - var context = new StandardEvaluationContext(); - context.setBeanResolver(new BeanFactoryResolver(beanFactory)); - return request -> { - //TODO performance problem - how can the request object reused in the expression without setting it as a rootObject - Expression expr = expressionParser.parseExpression(cacheKeyexpression); - final String value = expr.getValue(context, request, String.class); - return url + "-" + value; - }; - } - - /** - * Creates the lambda for the skip condition which will be evaluated on each request - * - * @param rateLimit the {@link RateLimit} configuration which holds the skip condition string - * @param expressionParser is used to evaluate the skip expression - * @param beanFactory used to get full access to all java beans in the SpEl - * @return the lambda condition which will be evaluated lazy - null if there is no condition available. - */ - public Condition skipCondition(RateLimit rateLimit, ExpressionParser expressionParser, BeanFactory beanFactory) { - var context = new StandardEvaluationContext(); - context.setBeanResolver(new BeanFactoryResolver(beanFactory)); - - if (rateLimit.getSkipCondition() != null) { - return request -> { - Expression expr = expressionParser.parseExpression(rateLimit.getSkipCondition()); - return expr.getValue(context, request, Boolean.class); - }; - } - return null; - } - - /** - * Creates the lambda for the execute condition which will be evaluated on each request. - * - * @param rateLimit the {@link RateLimit} configuration which holds the execute condition string - * @param expressionParser is used to evaluate the execution expression - * @param beanFactory used to get full access to all java beans in the SpEl - * @return the lambda condition which will be evaluated lazy - null if there is no condition available. - */ - public Condition executeCondition(RateLimit rateLimit, ExpressionParser expressionParser, BeanFactory beanFactory) { - return executeExpression(rateLimit.getExecuteCondition(), expressionParser, beanFactory); - } - - /** - * Creates the lambda for the execute condition which will be evaluated on each request. - * - * @param rateLimit the {@link RateLimit} configuration which holds the execute condition string - * @param expressionParser is used to evaluate the execution expression - * @param beanFactory used to get full access to all java beans in the SpEl - * @return the lambda condition which will be evaluated lazy - null if there is no condition available. - */ - public Condition

executeResponseCondition(RateLimit rateLimit, ExpressionParser expressionParser, BeanFactory beanFactory) { - return executeExpression(rateLimit.getPostExecuteCondition(), expressionParser, beanFactory); - } - - @Nullable - private static Condition executeExpression(String condition, ExpressionParser expressionParser, BeanFactory beanFactory) { - var context = new StandardEvaluationContext(); - context.setBeanResolver(new BeanFactoryResolver(beanFactory)); - - if (condition != null) { - return request -> { - Expression expr = expressionParser.parseExpression(condition); - return Boolean.TRUE.equals(expr.getValue(context, request, Boolean.class)); - }; - } - return null; - } - - - - protected void addDefaultMetricTags(Bucket4JBootProperties properties, Bucket4JConfiguration filter) { - if (!properties.getDefaultMetricTags().isEmpty()) { - var metricTags = filter.getMetrics().getTags(); - var filterMetricTagKeys = metricTags - .stream() - .map(MetricTag::getKey) - .collect(Collectors.toSet()); - properties.getDefaultMetricTags().forEach(defaultTag -> { - if (!filterMetricTagKeys.contains(defaultTag.getKey())) { - metricTags.add(defaultTag); - } - }); - } - } - - private Predicate prepareExecutionPredicates(RateLimit rl) { - return rl.getExecutePredicates() - .stream() - .map(this::createPredicate) - .reduce(Predicate::and) - .orElseGet(() -> p -> true); - } - - private Predicate prepareSkipPredicates(RateLimit rl) { - return rl.getSkipPredicates() - .stream() - .map(this::createPredicate) - .reduce(Predicate::and) - .orElseGet(() -> p -> false); - } - - protected Predicate createPredicate(ExecutePredicateDefinition pd) { - var predicate = getExecutePredicateByName(pd.getName()); - log.debug("create-predicate;name:{};value:{}", pd.getName(), pd.getArgs()); - try { - @SuppressWarnings("unchecked") - ExecutePredicate newPredicateInstance = predicate.getClass().getDeclaredConstructor().newInstance(); - return newPredicateInstance.init(pd.getArgs()); - } catch (InstantiationException | IllegalAccessException | IllegalArgumentException - | InvocationTargetException | NoSuchMethodException | SecurityException e) { - throw new ExecutePredicateInstantiationException(pd.getName(), predicate.getClass()); - } - } /** * Try to load a filter configuration from the cache with the same id as the provided filter. diff --git a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/reactive/gateway/Bucket4JAutoConfigurationSpringCloudGatewayFilter.java b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/reactive/gateway/Bucket4JAutoConfigurationSpringCloudGatewayFilter.java index b9aebf59..d3c564cf 100644 --- a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/reactive/gateway/Bucket4JAutoConfigurationSpringCloudGatewayFilter.java +++ b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/reactive/gateway/Bucket4JAutoConfigurationSpringCloudGatewayFilter.java @@ -7,6 +7,7 @@ import com.giffing.bucket4j.spring.boot.starter.config.filter.Bucket4JBaseConfiguration; import com.giffing.bucket4j.spring.boot.starter.config.filter.reactive.predicate.WebfluxExecutePredicateConfiguration; import com.giffing.bucket4j.spring.boot.starter.config.metrics.actuator.SpringBootActuatorConfig; +import com.giffing.bucket4j.spring.boot.starter.config.service.ServiceConfiguration; import com.giffing.bucket4j.spring.boot.starter.context.Bucket4jConfigurationHolder; import com.giffing.bucket4j.spring.boot.starter.context.ExecutePredicate; import com.giffing.bucket4j.spring.boot.starter.context.FilterMethod; @@ -14,9 +15,9 @@ import com.giffing.bucket4j.spring.boot.starter.context.properties.Bucket4JBootProperties; import com.giffing.bucket4j.spring.boot.starter.context.properties.Bucket4JConfiguration; import com.giffing.bucket4j.spring.boot.starter.filter.reactive.gateway.SpringCloudGatewayRateLimitFilter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import com.giffing.bucket4j.spring.boot.starter.service.RateLimitService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration; @@ -29,14 +30,14 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.support.GenericApplicationContext; -import org.springframework.expression.ExpressionParser; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.util.StringUtils; import java.util.List; -import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; +import java.util.stream.Collectors; /** * Configures Servlet Filters for Bucket4Js rate limit. @@ -48,42 +49,39 @@ @AutoConfigureBefore(GatewayAutoConfiguration.class) @AutoConfigureAfter(value = { CacheAutoConfiguration.class, Bucket4jCacheConfiguration.class }) @ConditionalOnBean(value = AsyncCacheResolver.class) -@Import(value = { WebfluxExecutePredicateConfiguration.class, SpringBootActuatorConfig.class, Bucket4JAutoConfigurationSpringCloudGatewayFilterBeans.class }) +@Import(value = { ServiceConfiguration.class, WebfluxExecutePredicateConfiguration.class, SpringBootActuatorConfig.class, Bucket4JAutoConfigurationSpringCloudGatewayFilterBeans.class }) +@Slf4j public class Bucket4JAutoConfigurationSpringCloudGatewayFilter extends Bucket4JBaseConfiguration { - private final Logger log = LoggerFactory.getLogger(Bucket4JAutoConfigurationSpringCloudGatewayFilter.class); - private final Bucket4JBootProperties properties; - private final ConfigurableBeanFactory beanFactory; - private final GenericApplicationContext context; private final AsyncCacheResolver cacheResolver; - private final List metricHandlers; + private final RateLimitService rateLimitService; private final Bucket4jConfigurationHolder gatewayConfigurationHolder; - private final ExpressionParser gatewayFilterExpressionParser; public Bucket4JAutoConfigurationSpringCloudGatewayFilter( Bucket4JBootProperties properties, - ConfigurableBeanFactory beanFactory, GenericApplicationContext context, AsyncCacheResolver cacheResolver, List metricHandlers, + List> executePredicates, Bucket4jConfigurationHolder gatewayConfigurationHolder, - ExpressionParser gatewayFilterExpressionParser, - Optional> configCacheManager) { - super(configCacheManager.orElse(null)); + RateLimitService rateLimitService, + @Autowired(required = false) CacheManager configCacheManager) { + + super(rateLimitService, configCacheManager, metricHandlers, executePredicates + .stream() + .collect(Collectors.toMap(ExecutePredicate::name, Function.identity()))); this.properties = properties; - this.beanFactory = beanFactory; this.context = context; this.cacheResolver = cacheResolver; - this.metricHandlers = metricHandlers; + this.rateLimitService = rateLimitService; this.gatewayConfigurationHolder = gatewayConfigurationHolder; - this.gatewayFilterExpressionParser = gatewayFilterExpressionParser; initFilters(); } @@ -96,13 +94,9 @@ public void initFilters() { .filter(filter -> StringUtils.hasText(filter.getUrl()) && filter.getFilterMethod().equals(FilterMethod.GATEWAY)) .map(filter -> properties.isFilterConfigCachingEnabled() ? getOrUpdateConfigurationFromCache(filter) : filter) .forEach(filter -> { - addDefaultMetricTags(properties, filter); + rateLimitService.addDefaultMetricTags(properties, filter); filterCount.incrementAndGet(); - var filterConfig = buildFilterConfig( - filter, - cacheResolver.resolve(filter.getCacheName()), - gatewayFilterExpressionParser, - beanFactory); + var filterConfig = buildFilterConfig(filter, cacheResolver.resolve(filter.getCacheName())); gatewayConfigurationHolder.addFilterConfiguration(filter); @@ -114,16 +108,6 @@ public void initFilters() { }); } - @Override - public List getMetricHandlers() { - return this.metricHandlers; - } - - - @Override - protected ExecutePredicate getExecutePredicateByName(String name) { - throw new UnsupportedOperationException("Execution predicates not supported"); - } @Override public void onCacheUpdateEvent(CacheUpdateEvent event) { @@ -132,11 +116,7 @@ public void onCacheUpdateEvent(CacheUpdateEvent e if (newConfig.getFilterMethod().equals(FilterMethod.GATEWAY)) { try { SpringCloudGatewayRateLimitFilter filter = context.getBean(event.getKey(), SpringCloudGatewayRateLimitFilter.class); - var newFilterConfig = buildFilterConfig( - newConfig, - cacheResolver.resolve(newConfig.getCacheName()), - gatewayFilterExpressionParser, - beanFactory); + var newFilterConfig = buildFilterConfig(newConfig, cacheResolver.resolve(newConfig.getCacheName())); filter.setFilterConfig(newFilterConfig); } catch (Exception exception) { log.warn("Failed to update Gateway Filter configuration. {}", exception.getMessage()); diff --git a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/reactive/gateway/Bucket4JAutoConfigurationSpringCloudGatewayFilterBeans.java b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/reactive/gateway/Bucket4JAutoConfigurationSpringCloudGatewayFilterBeans.java index ddcfb4ed..4010a4ea 100644 --- a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/reactive/gateway/Bucket4JAutoConfigurationSpringCloudGatewayFilterBeans.java +++ b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/reactive/gateway/Bucket4JAutoConfigurationSpringCloudGatewayFilterBeans.java @@ -4,10 +4,6 @@ import com.giffing.bucket4j.spring.boot.starter.context.qualifier.Gateway; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.expression.ExpressionParser; -import org.springframework.expression.spel.SpelCompilerMode; -import org.springframework.expression.spel.SpelParserConfiguration; -import org.springframework.expression.spel.standard.SpelExpressionParser; @Configuration public class Bucket4JAutoConfigurationSpringCloudGatewayFilterBeans { @@ -18,12 +14,5 @@ public Bucket4jConfigurationHolder gatewayConfigurationHolder() { return new Bucket4jConfigurationHolder(); } - @Bean - public ExpressionParser gatewayFilterExpressionParser() { - SpelParserConfiguration config = new SpelParserConfiguration( - SpelCompilerMode.IMMEDIATE, - this.getClass().getClassLoader()); - return new SpelExpressionParser(config); - } - + } diff --git a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/reactive/webflux/Bucket4JAutoConfigurationWebfluxFilter.java b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/reactive/webflux/Bucket4JAutoConfigurationWebfluxFilter.java index e8ac0097..1e25c121 100644 --- a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/reactive/webflux/Bucket4JAutoConfigurationWebfluxFilter.java +++ b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/reactive/webflux/Bucket4JAutoConfigurationWebfluxFilter.java @@ -1,15 +1,24 @@ package com.giffing.bucket4j.spring.boot.starter.config.filter.reactive.webflux; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Function; -import java.util.stream.Collectors; - +import com.giffing.bucket4j.spring.boot.starter.config.cache.AsyncCacheResolver; +import com.giffing.bucket4j.spring.boot.starter.config.cache.Bucket4jCacheConfiguration; +import com.giffing.bucket4j.spring.boot.starter.config.cache.CacheManager; +import com.giffing.bucket4j.spring.boot.starter.config.cache.CacheUpdateEvent; +import com.giffing.bucket4j.spring.boot.starter.config.filter.Bucket4JBaseConfiguration; +import com.giffing.bucket4j.spring.boot.starter.config.filter.reactive.predicate.WebfluxExecutePredicateConfiguration; +import com.giffing.bucket4j.spring.boot.starter.config.metrics.actuator.SpringBootActuatorConfig; +import com.giffing.bucket4j.spring.boot.starter.config.service.ServiceConfiguration; +import com.giffing.bucket4j.spring.boot.starter.context.Bucket4jConfigurationHolder; +import com.giffing.bucket4j.spring.boot.starter.context.ExecutePredicate; +import com.giffing.bucket4j.spring.boot.starter.context.FilterMethod; +import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricHandler; +import com.giffing.bucket4j.spring.boot.starter.context.properties.Bucket4JBootProperties; +import com.giffing.bucket4j.spring.boot.starter.context.properties.Bucket4JConfiguration; +import com.giffing.bucket4j.spring.boot.starter.filter.reactive.webflux.WebfluxWebFilter; +import com.giffing.bucket4j.spring.boot.starter.service.RateLimitService; import jakarta.annotation.PostConstruct; - -import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration; @@ -21,30 +30,15 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.support.GenericApplicationContext; -import org.springframework.expression.ExpressionParser; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.util.StringUtils; import org.springframework.web.server.WebFilter; -import com.giffing.bucket4j.spring.boot.starter.config.cache.AsyncCacheResolver; -import com.giffing.bucket4j.spring.boot.starter.config.cache.Bucket4jCacheConfiguration; -import com.giffing.bucket4j.spring.boot.starter.config.cache.CacheManager; -import com.giffing.bucket4j.spring.boot.starter.config.cache.CacheUpdateEvent; -import com.giffing.bucket4j.spring.boot.starter.config.filter.Bucket4JBaseConfiguration; -import com.giffing.bucket4j.spring.boot.starter.config.filter.reactive.predicate.WebfluxExecutePredicateConfiguration; -import com.giffing.bucket4j.spring.boot.starter.config.metrics.actuator.SpringBootActuatorConfig; -import com.giffing.bucket4j.spring.boot.starter.context.Bucket4jConfigurationHolder; -import com.giffing.bucket4j.spring.boot.starter.context.ExecutePredicate; -import com.giffing.bucket4j.spring.boot.starter.context.FilterMethod; -import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricHandler; -import com.giffing.bucket4j.spring.boot.starter.context.properties.Bucket4JBootProperties; -import com.giffing.bucket4j.spring.boot.starter.context.properties.Bucket4JConfiguration; -import com.giffing.bucket4j.spring.boot.starter.context.properties.FilterConfiguration; -import com.giffing.bucket4j.spring.boot.starter.filter.reactive.webflux.WebfluxWebFilter; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; +import java.util.stream.Collectors; /** * Configures Servlet Filters for Bucket4Js rate limit. @@ -56,48 +50,37 @@ @AutoConfigureAfter(value = { CacheAutoConfiguration.class, Bucket4jCacheConfiguration.class }) @ConditionalOnBean(value = AsyncCacheResolver.class) @EnableConfigurationProperties({ Bucket4JBootProperties.class}) -@Import(value = { WebfluxExecutePredicateConfiguration.class, Bucket4JAutoConfigurationWebfluxFilterBeans.class, SpringBootActuatorConfig.class }) +@Import(value = { ServiceConfiguration.class, WebfluxExecutePredicateConfiguration.class, Bucket4JAutoConfigurationWebfluxFilterBeans.class, SpringBootActuatorConfig.class }) +@Slf4j public class Bucket4JAutoConfigurationWebfluxFilter extends Bucket4JBaseConfiguration { - private final Logger log = LoggerFactory.getLogger(Bucket4JAutoConfigurationWebfluxFilter.class); - private final Bucket4JBootProperties properties; - private final ConfigurableBeanFactory beanFactory; - private final GenericApplicationContext context; private final AsyncCacheResolver cacheResolver; - private final List metricHandlers; - - private final Map> executePredicates; + private final RateLimitService rateLimitService; private final Bucket4jConfigurationHolder servletConfigurationHolder; - private final ExpressionParser webfluxFilterExpressionParser; - public Bucket4JAutoConfigurationWebfluxFilter( Bucket4JBootProperties properties, - ConfigurableBeanFactory beanFactory, GenericApplicationContext context, AsyncCacheResolver cacheResolver, List metricHandlers, List> executePredicates, Bucket4jConfigurationHolder servletConfigurationHolder, - ExpressionParser webfluxFilterExpressionParser, - Optional> configCacheManager) { - super(configCacheManager.orElse(null)); + RateLimitService rateLimitService, + @Autowired(required = false) CacheManager configCacheManager) { + super(rateLimitService, configCacheManager, metricHandlers, executePredicates + .stream() + .collect(Collectors.toMap(ExecutePredicate::name, Function.identity()))); this.properties = properties; - this.beanFactory = beanFactory; this.context = context; this.cacheResolver = cacheResolver; - this.metricHandlers = metricHandlers; - this.executePredicates = executePredicates - .stream() - .collect(Collectors.toMap(ExecutePredicate::name, Function.identity())); + this.rateLimitService = rateLimitService; this.servletConfigurationHolder = servletConfigurationHolder; - this.webfluxFilterExpressionParser = webfluxFilterExpressionParser; } @PostConstruct @@ -109,12 +92,9 @@ public void initFilters() { .filter(filter -> StringUtils.hasText(filter.getUrl()) && filter.getFilterMethod().equals(FilterMethod.WEBFLUX)) .map(filter -> properties.isFilterConfigCachingEnabled() ? getOrUpdateConfigurationFromCache(filter) : filter) .forEach(filter -> { - addDefaultMetricTags(properties, filter); + rateLimitService.addDefaultMetricTags(properties, filter); filterCount.incrementAndGet(); - FilterConfiguration filterConfig = buildFilterConfig(filter, cacheResolver.resolve( - filter.getCacheName()), - webfluxFilterExpressionParser, - beanFactory); + var filterConfig = buildFilterConfig(filter, cacheResolver.resolve(filter.getCacheName())); servletConfigurationHolder.addFilterConfiguration(filter); @@ -126,15 +106,6 @@ public void initFilters() { }); } - @Override - public List getMetricHandlers() { - return this.metricHandlers; - } - - @Override - protected ExecutePredicate getExecutePredicateByName(String name) { - return executePredicates.getOrDefault(name, null); - } @Override public void onCacheUpdateEvent(CacheUpdateEvent event) { @@ -143,11 +114,7 @@ public void onCacheUpdateEvent(CacheUpdateEvent e if (newConfig.getFilterMethod().equals(FilterMethod.WEBFLUX)) { try { WebfluxWebFilter filter = context.getBean(event.getKey(), WebfluxWebFilter.class); - FilterConfiguration newFilterConfig = buildFilterConfig( - newConfig, - cacheResolver.resolve(newConfig.getCacheName()), - webfluxFilterExpressionParser, - beanFactory); + var newFilterConfig = buildFilterConfig(newConfig, cacheResolver.resolve(newConfig.getCacheName())); filter.setFilterConfig(newFilterConfig); } catch (Exception exception) { log.warn("Failed to update Webflux Filter configuration. {}", exception.getMessage()); diff --git a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/reactive/webflux/Bucket4JAutoConfigurationWebfluxFilterBeans.java b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/reactive/webflux/Bucket4JAutoConfigurationWebfluxFilterBeans.java index 21e6fc08..fbfb6237 100644 --- a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/reactive/webflux/Bucket4JAutoConfigurationWebfluxFilterBeans.java +++ b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/reactive/webflux/Bucket4JAutoConfigurationWebfluxFilterBeans.java @@ -4,10 +4,6 @@ import com.giffing.bucket4j.spring.boot.starter.context.qualifier.Webflux; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.expression.ExpressionParser; -import org.springframework.expression.spel.SpelCompilerMode; -import org.springframework.expression.spel.SpelParserConfiguration; -import org.springframework.expression.spel.standard.SpelExpressionParser; @Configuration public class Bucket4JAutoConfigurationWebfluxFilterBeans { @@ -18,12 +14,4 @@ public Bucket4jConfigurationHolder servletConfigurationHolder() { return new Bucket4jConfigurationHolder(); } - @Bean - public ExpressionParser webfluxFilterExpressionParser() { - SpelParserConfiguration config = new SpelParserConfiguration( - SpelCompilerMode.IMMEDIATE, - this.getClass().getClassLoader()); - return new SpelExpressionParser(config); - } - } diff --git a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/servlet/Bucket4JAutoConfigurationServletFilter.java b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/servlet/Bucket4JAutoConfigurationServletFilter.java index 95d25193..f688b6cf 100644 --- a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/servlet/Bucket4JAutoConfigurationServletFilter.java +++ b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/servlet/Bucket4JAutoConfigurationServletFilter.java @@ -7,6 +7,8 @@ import com.giffing.bucket4j.spring.boot.starter.config.filter.Bucket4JBaseConfiguration; import com.giffing.bucket4j.spring.boot.starter.config.filter.servlet.predicate.ServletRequestExecutePredicateConfiguration; import com.giffing.bucket4j.spring.boot.starter.config.metrics.actuator.SpringBootActuatorConfig; +import com.giffing.bucket4j.spring.boot.starter.service.RateLimitService; +import com.giffing.bucket4j.spring.boot.starter.config.service.ServiceConfiguration; import com.giffing.bucket4j.spring.boot.starter.context.Bucket4jConfigurationHolder; import com.giffing.bucket4j.spring.boot.starter.context.ExecutePredicate; import com.giffing.bucket4j.spring.boot.starter.context.FilterMethod; @@ -18,7 +20,7 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration; @@ -32,12 +34,9 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.support.GenericApplicationContext; -import org.springframework.expression.ExpressionParser; import org.springframework.util.StringUtils; import java.util.List; -import java.util.Map; -import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.stream.Collectors; @@ -52,48 +51,38 @@ @AutoConfigureBefore(ServletWebServerFactoryAutoConfiguration.class) @AutoConfigureAfter(value = { CacheAutoConfiguration.class, Bucket4jCacheConfiguration.class }) @ConditionalOnBean(value = SyncCacheResolver.class) -@Import(value = {ServletRequestExecutePredicateConfiguration.class, Bucket4JAutoConfigurationServletFilterBeans.class, Bucket4jCacheConfiguration.class, SpringBootActuatorConfig.class }) +@Import(value = { ServiceConfiguration.class, ServletRequestExecutePredicateConfiguration.class, Bucket4JAutoConfigurationServletFilterBeans.class, Bucket4jCacheConfiguration.class, SpringBootActuatorConfig.class }) @Slf4j public class Bucket4JAutoConfigurationServletFilter extends Bucket4JBaseConfiguration implements WebServerFactoryCustomizer { private final Bucket4JBootProperties properties; - private final ConfigurableBeanFactory beanFactory; - private final GenericApplicationContext context; private final SyncCacheResolver cacheResolver; - private final List metricHandlers; - - private final Map> executePredicates; + private final RateLimitService rateLimitService; private final Bucket4jConfigurationHolder servletConfigurationHolder; - private final ExpressionParser servletFilterExpressionParser; - public Bucket4JAutoConfigurationServletFilter( Bucket4JBootProperties properties, - ConfigurableBeanFactory beanFactory, GenericApplicationContext context, SyncCacheResolver cacheResolver, List metricHandlers, List> executePredicates, Bucket4jConfigurationHolder servletConfigurationHolder, - ExpressionParser servletFilterExpressionParser, - Optional> configCacheManager) { - super(configCacheManager.orElse(null)); + RateLimitService rateLimitService, + @Autowired(required = false) CacheManager configCacheManager) { + super(rateLimitService, configCacheManager, metricHandlers, executePredicates + .stream() + .collect(Collectors.toMap(ExecutePredicate::name, Function.identity()))); this.properties = properties; - this.beanFactory = beanFactory; this.context = context; this.cacheResolver = cacheResolver; - this.metricHandlers = metricHandlers; - this.executePredicates = executePredicates - .stream() - .collect(Collectors.toMap(ExecutePredicate::name, Function.identity())); + this.rateLimitService = rateLimitService; this.servletConfigurationHolder = servletConfigurationHolder; - this.servletFilterExpressionParser = servletFilterExpressionParser; } @Override @@ -105,44 +94,28 @@ public void customize(ConfigurableServletWebServerFactory factory) { .filter(filter -> StringUtils.hasText(filter.getUrl()) && filter.getFilterMethod().equals(FilterMethod.SERVLET)) .map(filter -> properties.isFilterConfigCachingEnabled() ? getOrUpdateConfigurationFromCache(filter) : filter) .forEach(filter -> { - addDefaultMetricTags(properties, filter); + rateLimitService.addDefaultMetricTags(properties, filter); filterCount.incrementAndGet(); - var filterConfig = buildFilterConfig( - filter, - cacheResolver.resolve(filter.getCacheName()), - servletFilterExpressionParser, beanFactory); + var filterConfig = buildFilterConfig(filter, cacheResolver.resolve(filter.getCacheName())); servletConfigurationHolder.addFilterConfiguration(filter); //Use either the filter id as bean name or the prefix + counter if no id is configured - String beanName = filter.getId() != null ? filter.getId() : ("bucket4JServletRequestFilter" + filterCount); + var beanName = filter.getId() != null ? filter.getId() : ("bucket4JServletRequestFilter" + filterCount); context.registerBean(beanName, Filter.class, () -> new ServletRequestFilter(filterConfig)); log.info("create-servlet-filter;{};{};{}", filterCount, filter.getCacheName(), filter.getUrl()); }); } - @Override - public List getMetricHandlers() { - return this.metricHandlers; - } - - @Override - protected ExecutePredicate getExecutePredicateByName(String name) { - return executePredicates.getOrDefault(name, null); - } - @Override public void onCacheUpdateEvent(CacheUpdateEvent event) { //only handle servlet filter updates Bucket4JConfiguration newConfig = event.getNewValue(); if(newConfig.getFilterMethod().equals(FilterMethod.SERVLET)) { try { - ServletRequestFilter filter = context.getBean(event.getKey(), ServletRequestFilter.class); - var newFilterConfig = buildFilterConfig( - newConfig, - cacheResolver.resolve(newConfig.getCacheName()), - servletFilterExpressionParser, beanFactory); + var filter = context.getBean(event.getKey(), ServletRequestFilter.class); + var newFilterConfig = buildFilterConfig(newConfig, cacheResolver.resolve(newConfig.getCacheName())); filter.setFilterConfig(newFilterConfig); } catch (Exception exception) { log.warn("Failed to update Servlet Filter configuration. {}", exception.getMessage()); diff --git a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/servlet/Bucket4JAutoConfigurationServletFilterBeans.java b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/servlet/Bucket4JAutoConfigurationServletFilterBeans.java index 569e3335..b136a942 100644 --- a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/servlet/Bucket4JAutoConfigurationServletFilterBeans.java +++ b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/filter/servlet/Bucket4JAutoConfigurationServletFilterBeans.java @@ -4,10 +4,6 @@ import com.giffing.bucket4j.spring.boot.starter.context.qualifier.Servlet; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.expression.ExpressionParser; -import org.springframework.expression.spel.SpelCompilerMode; -import org.springframework.expression.spel.SpelParserConfiguration; -import org.springframework.expression.spel.standard.SpelExpressionParser; @Configuration public class Bucket4JAutoConfigurationServletFilterBeans { @@ -17,11 +13,5 @@ public class Bucket4JAutoConfigurationServletFilterBeans { public Bucket4jConfigurationHolder servletConfigurationHolder() { return new Bucket4jConfigurationHolder(); } - - @Bean - public ExpressionParser servletFilterExpressionParser() { - SpelParserConfiguration config = new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE, this.getClass().getClassLoader()); - return new SpelExpressionParser(config); - } - + } diff --git a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/metrics/actuator/Bucket4jEndpoint.java b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/metrics/actuator/Bucket4jEndpoint.java index 7c431186..08aa6c42 100644 --- a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/metrics/actuator/Bucket4jEndpoint.java +++ b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/metrics/actuator/Bucket4jEndpoint.java @@ -52,11 +52,9 @@ public Map bucket4jConfig() { if(webfluxConfigs != null) { result.put("webflux", webfluxConfigs.getFilterConfiguration()); } - if(gatewayConfigs != null) { result.put("gateway", gatewayConfigs.getFilterConfiguration()); } - return result; } diff --git a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/service/ServiceConfiguration.java b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/service/ServiceConfiguration.java new file mode 100644 index 00000000..069ee800 --- /dev/null +++ b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/config/service/ServiceConfiguration.java @@ -0,0 +1,37 @@ +package com.giffing.bucket4j.spring.boot.starter.config.service; + +import com.giffing.bucket4j.spring.boot.starter.service.ExpressionService; +import com.giffing.bucket4j.spring.boot.starter.service.RateLimitService; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.expression.ExpressionParser; +import org.springframework.expression.spel.SpelCompilerMode; +import org.springframework.expression.spel.SpelParserConfiguration; +import org.springframework.expression.spel.standard.SpelExpressionParser; + +/** + * General Service configuration which can be imported from other autoconfiguration classes. + */ +@Configuration +public class ServiceConfiguration { + + + @Bean + public ExpressionParser expressionParser() { + SpelParserConfiguration config = new SpelParserConfiguration( + SpelCompilerMode.IMMEDIATE, + this.getClass().getClassLoader()); + return new SpelExpressionParser(config); + } + + @Bean + ExpressionService expressionService(ExpressionParser expressionParser, ConfigurableBeanFactory beanFactory) { + return new ExpressionService(expressionParser, beanFactory); + } + + @Bean + RateLimitService rateLimitService(ExpressionService expressionService) { + return new RateLimitService(expressionService); + } +} diff --git a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/filter/reactive/AbstractReactiveFilter.java b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/filter/reactive/AbstractReactiveFilter.java index 1d85571c..a2e35ec2 100644 --- a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/filter/reactive/AbstractReactiveFilter.java +++ b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/filter/reactive/AbstractReactiveFilter.java @@ -1,8 +1,8 @@ package com.giffing.bucket4j.spring.boot.starter.filter.reactive; +import com.giffing.bucket4j.spring.boot.starter.context.ExpressionParams; import com.giffing.bucket4j.spring.boot.starter.context.RateLimitConditionMatchingStrategy; import com.giffing.bucket4j.spring.boot.starter.context.RateLimitResult; -import com.giffing.bucket4j.spring.boot.starter.context.RateLimitResultWrapper; import com.giffing.bucket4j.spring.boot.starter.context.properties.FilterConfiguration; import lombok.Data; import lombok.extern.slf4j.Slf4j; @@ -42,7 +42,7 @@ protected Mono chainWithRateLimitCheck(ServerWebExchange exchange, Reactiv var response = exchange.getResponse(); List> asyncConsumptionProbes = new ArrayList<>(); for (var rlc : filterConfig.getRateLimitChecks()) { - var wrapper = rlc.rateLimit(request); + var wrapper = rlc.rateLimit(new ExpressionParams<>(request), null); if(wrapper != null && wrapper.getRateLimitResultCompletableFuture() != null){ asyncConsumptionProbes.add(Mono.fromFuture(wrapper.getRateLimitResultCompletableFuture())); if(filterConfig.getStrategy() == RateLimitConditionMatchingStrategy.FIRST){ diff --git a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/filter/servlet/ServletRequestFilter.java b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/filter/servlet/ServletRequestFilter.java index 52b700d7..9e3aca93 100644 --- a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/filter/servlet/ServletRequestFilter.java +++ b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/filter/servlet/ServletRequestFilter.java @@ -1,10 +1,12 @@ package com.giffing.bucket4j.spring.boot.starter.filter.servlet; +import com.giffing.bucket4j.spring.boot.starter.context.ExpressionParams; import com.giffing.bucket4j.spring.boot.starter.context.RateLimitCheck; import com.giffing.bucket4j.spring.boot.starter.context.RateLimitConditionMatchingStrategy; import com.giffing.bucket4j.spring.boot.starter.context.RateLimitResult; -import com.giffing.bucket4j.spring.boot.starter.context.RateLimitResultWrapper; import com.giffing.bucket4j.spring.boot.starter.context.properties.FilterConfiguration; +import com.giffing.bucket4j.spring.boot.starter.context.properties.RateLimit; +import com.giffing.bucket4j.spring.boot.starter.service.RateLimitService; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; @@ -43,12 +45,12 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse throws ServletException, IOException { boolean allConsumed = true; Long remainingLimit = null; - for (RateLimitCheck rl : filterConfig.getRateLimitChecks()) { - var wrapper = rl.rateLimit(request); + for (var rl : filterConfig.getRateLimitChecks()) { + var wrapper = rl.rateLimit(new ExpressionParams<>(request), null); if (wrapper != null && wrapper.getRateLimitResult() != null) { var rateLimitResult = wrapper.getRateLimitResult(); if (rateLimitResult.isConsumed()) { - remainingLimit = getRemainingLimit(remainingLimit, rateLimitResult); + remainingLimit = RateLimitService.getRemainingLimit(remainingLimit, rateLimitResult); } else { allConsumed = false; handleHttpResponseOnRateLimiting(response, rateLimitResult); @@ -58,7 +60,6 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse break; } } - } if (allConsumed) { @@ -90,16 +91,6 @@ private void handleHttpResponseOnRateLimiting(HttpServletResponse httpResponse, } } - private long getRemainingLimit(Long remaining, RateLimitResult rateLimitResult) { - if (rateLimitResult != null) { - if (remaining == null) { - remaining = rateLimitResult.getRemainingTokens(); - } else if (rateLimitResult.getRemainingTokens() < remaining) { - remaining = rateLimitResult.getRemainingTokens(); - } - } - return remaining; - } @Override diff --git a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/service/ExpressionService.java b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/service/ExpressionService.java new file mode 100644 index 00000000..8d5e362b --- /dev/null +++ b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/service/ExpressionService.java @@ -0,0 +1,46 @@ +package com.giffing.bucket4j.spring.boot.starter.service; + +import com.giffing.bucket4j.spring.boot.starter.context.ExpressionParams; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.expression.BeanFactoryResolver; +import org.springframework.expression.ExpressionParser; +import org.springframework.expression.spel.support.StandardEvaluationContext; + +import java.util.Map; + +/** + * The expression service wraps Springs {@link ExpressionParser} to execute SpEl expressions. + */ +@RequiredArgsConstructor +@Slf4j +public class ExpressionService { + + private final ExpressionParser expressionParser; + + private final ConfigurableBeanFactory beanFactory; + + public String parseString(String expression, ExpressionParams params) { + var context = getContext(params.getParams()); + var expr = expressionParser.parseExpression(expression); + String result = expr.getValue(context, params.getRootObject(), String.class); + log.info("parse-string-expression;result:{};expression:{};root:{};params:{}", result, expression, params.getRootObject(), params.getParams()); + return result; + } + + public Boolean parseBoolean(String expression, ExpressionParams params) { + var context = getContext(params.getParams()); + var expr = expressionParser.parseExpression(expression); + boolean result = Boolean.TRUE.equals(expr.getValue(context, params.getRootObject(), Boolean.class)); + log.info("parse-boolean-expression;result:{};expression:{};root:{};params:{}", result, expression, params.getRootObject(), params.getParams()); + return result; + } + + private StandardEvaluationContext getContext(Map params) { + var context = new StandardEvaluationContext(); + params.forEach(context::setVariable); + context.setBeanResolver(new BeanFactoryResolver(beanFactory)); + return context; + } +} diff --git a/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/service/RateLimitService.java b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/service/RateLimitService.java new file mode 100644 index 00000000..e13dbfe4 --- /dev/null +++ b/bucket4j-spring-boot-starter/src/main/java/com/giffing/bucket4j/spring/boot/starter/service/RateLimitService.java @@ -0,0 +1,308 @@ +package com.giffing.bucket4j.spring.boot.starter.service; + + +import com.giffing.bucket4j.spring.boot.starter.config.cache.ProxyManagerWrapper; +import com.giffing.bucket4j.spring.boot.starter.context.*; +import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricBucketListener; +import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricHandler; +import com.giffing.bucket4j.spring.boot.starter.context.metrics.MetricTagResult; +import com.giffing.bucket4j.spring.boot.starter.context.properties.*; +import com.giffing.bucket4j.spring.boot.starter.exception.ExecutePredicateInstantiationException; +import io.github.bucket4j.Bandwidth; +import io.github.bucket4j.BucketConfiguration; +import io.github.bucket4j.ConfigurationBuilder; +import lombok.Builder; +import lombok.Data; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +import java.lang.reflect.InvocationTargetException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.function.BiFunction; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +@Slf4j +@RequiredArgsConstructor +public class RateLimitService { + + private final ExpressionService expressionService; + + @Builder + @Data + public static class RateLimitConfig { + @NonNull + private List rateLimits; + @NonNull + private List metricHandlers; + @NonNull + private Map> executePredicates; + @NonNull + private String cacheName; + @NonNull + private ProxyManagerWrapper proxyWrapper; + @NonNull + private BiFunction, String> keyFunction; + @NonNull + private Metrics metrics; + private long configVersion; + } + + @Builder + @Data + public static class RateLimitConfigresult { + private List> rateLimitChecks; + private List> postRateLimitChecks; + } + + public RateLimitConfigresult configureRateLimit(RateLimitConfig rateLimitConfig) { + + + var executePredicates = rateLimitConfig.getExecutePredicates(); + + + List> rateLimitChecks = new ArrayList<>(); + List> postRateLimitChecks = new ArrayList<>(); + rateLimitConfig.getRateLimits().forEach(rl -> { + log.debug("RL: {}", rl.toString()); + var bucketConfiguration = prepareBucket4jConfigurationBuilder(rl).build(); + var executionPredicate = prepareExecutionPredicates(rl, executePredicates); + var skipPredicate = prepareSkipPredicates(rl, executePredicates); + + RateLimitCheck rlc = (expressionParams, overridableRateLimit) -> { + + var rlToUse = rl.copy(); + rlToUse.consumeNotNullValues(overridableRateLimit); + + var skipRateLimit = performSkipRateLimitCheck(rlToUse, executionPredicate, skipPredicate, expressionParams); + boolean isEstimation = rlToUse.getPostExecuteCondition() != null; + RateLimitResultWrapper rateLimitResultWrapper = null; + if (!skipRateLimit) { + + rateLimitResultWrapper = tryConsume(rateLimitConfig, expressionParams, rlToUse, isEstimation, bucketConfiguration); + } + return rateLimitResultWrapper; + }; + rateLimitChecks.add(rlc); + + + if (rl.getPostExecuteCondition() != null) { + log.debug("PRL: {}", rl); + PostRateLimitCheck postRlc = (request, response) -> { + ExpressionParams expressionParams = new ExpressionParams<>(request); + var skipRateLimit = performPostSkipRateLimitCheck(rl, + executionPredicate, + skipPredicate, + expressionParams, + response); + boolean isEstimation = false; + RateLimitResultWrapper rateLimitResultWrapper = null; + if (!skipRateLimit) { + rateLimitResultWrapper = tryConsume(rateLimitConfig, expressionParams, rl, isEstimation, bucketConfiguration); + } + return rateLimitResultWrapper; + }; + postRateLimitChecks.add(postRlc); + + } + }); + + return new RateLimitConfigresult<>(rateLimitChecks, postRateLimitChecks); + } + + private RateLimitResultWrapper tryConsume(RateLimitConfig rateLimitConfig, ExpressionParams expressionParams, RateLimit rlToUse, boolean isEstimation, BucketConfiguration bucketConfiguration) { + RateLimitResultWrapper rateLimitResultWrapper; + var metricHandlers = rateLimitConfig.getMetricHandlers(); + var cacheName = rateLimitConfig.getCacheName(); + var metrics = rateLimitConfig.getMetrics(); + var keyFunction = rateLimitConfig.getKeyFunction(); + var proxyWrapper = rateLimitConfig.getProxyWrapper(); + var configVersion = rateLimitConfig.getConfigVersion(); + + var key = keyFunction.apply(rlToUse, expressionParams); + var metricBucketListener = createMetricListener(cacheName, metrics, metricHandlers, expressionParams); + log.debug("try-and-consume;key:{};tokens:{}", key, rlToUse.getNumTokens()); + rateLimitResultWrapper = proxyWrapper.tryConsumeAndReturnRemaining( + key, + rlToUse.getNumTokens(), + isEstimation, + bucketConfiguration, + metricBucketListener, + configVersion, + rlToUse.getTokensInheritanceStrategy() + ); + return rateLimitResultWrapper; + } + + + private boolean performPostSkipRateLimitCheck(RateLimit rl, + Predicate executionPredicate, + Predicate skipPredicate, + ExpressionParams expressionParams, + P response + ) { + var skipRateLimit = performSkipRateLimitCheck( + rl, executionPredicate, + skipPredicate, expressionParams); + + if (!skipRateLimit && rl.getPostExecuteCondition() != null) { + Condition

condition = exp -> expressionService.parseBoolean(rl.getPostExecuteCondition(), exp); + skipRateLimit = !condition.evaluate(new ExpressionParams<>(response).addParams(expressionParams.getParams())); + log.debug("skip-rate-limit - post-execute-condition: {}", skipRateLimit); + } + + return skipRateLimit; + } + + private boolean performSkipRateLimitCheck(RateLimit rl, + Predicate executionPredicate, + Predicate skipPredicate, + ExpressionParams expressionParams) { + boolean skipRateLimit = false; + if (rl.getSkipCondition() != null) { + Condition expresison = exp -> expressionService.parseBoolean(rl.getSkipCondition(), exp); + skipRateLimit = expresison.evaluate(expressionParams); + log.debug("skip-rate-limit - skip-condition: {}", skipRateLimit); + } + + if (!skipRateLimit) { + skipRateLimit = skipPredicate.test(expressionParams.getRootObject()); + log.debug("skip-rate-limit - skip-predicates: {}", skipRateLimit); + } + + if (!skipRateLimit && rl.getExecuteCondition() != null) { + Condition condition = exp -> expressionService.parseBoolean(rl.getExecuteCondition(), exp); + skipRateLimit = !condition.evaluate(expressionParams); + log.debug("skip-rate-limit - execute-condition: {}", skipRateLimit); + } + + if (!skipRateLimit) { + skipRateLimit = !executionPredicate.test(expressionParams.getRootObject()); + log.debug("skip-rate-limit - execute-predicates: {}", skipRateLimit); + } + return skipRateLimit; + } + + public List getMetricTagResults(ExpressionParams expressionParams, Metrics metrics) { + return metrics + .getTags() + .stream() + .map(metricMetaTag -> { + var value = expressionService.parseString(metricMetaTag.getExpression(), expressionParams); + return new MetricTagResult(metricMetaTag.getKey(), value, metricMetaTag.getTypes()); + }).toList(); + } + + /** + * Creates the key filter lambda which is responsible to decide how the rate limit will be performed. The key + * is the unique identifier like an IP address or a username. + * + * @param url is used to generated a unique cache key + * @param rateLimit the {@link RateLimit} configuration which holds the skip condition string + * @return should not been null. If no filter key type is matching a plain 1 is returned so that all requests uses the same key. + */ + public KeyFilter getKeyFilter(String url, RateLimit rateLimit) { + return expressionParams -> { + String value = expressionService.parseString(rateLimit.getCacheKey(), expressionParams); + return url + "-" + value; + }; + } + + + private ConfigurationBuilder prepareBucket4jConfigurationBuilder(RateLimit rl) { + var configBuilder = BucketConfiguration.builder(); + for (BandWidth bandWidth : rl.getBandwidths()) { + long capacity = bandWidth.getCapacity(); + long refillCapacity = bandWidth.getRefillCapacity() != null ? bandWidth.getRefillCapacity() : bandWidth.getCapacity(); + var refillPeriod = Duration.of(bandWidth.getTime(), bandWidth.getUnit()); + var bucket4jBandWidth = switch (bandWidth.getRefillSpeed()) { + case GREEDY -> + Bandwidth.builder().capacity(capacity).refillGreedy(refillCapacity, refillPeriod).id(bandWidth.getId()); + case INTERVAL -> + Bandwidth.builder().capacity(capacity).refillIntervally(refillCapacity, refillPeriod).id(bandWidth.getId()); + }; + + if (bandWidth.getInitialCapacity() != null) { + bucket4jBandWidth = bucket4jBandWidth.initialTokens(bandWidth.getInitialCapacity()); + } + configBuilder = configBuilder.addLimit(bucket4jBandWidth.build()); + } + return configBuilder; + } + + private MetricBucketListener createMetricListener(String cacheName, + Metrics metrics, + List metricHandlers, + ExpressionParams expressionParams) { + + var metricTagResults = getMetricTags(metrics, expressionParams); + return new MetricBucketListener( + cacheName, + metricHandlers, + metrics.getTypes(), + metricTagResults); + } + + private List getMetricTags( + Metrics metrics, + ExpressionParams expressionParams) { + + return getMetricTagResults(expressionParams, metrics); + } + + public void addDefaultMetricTags(Bucket4JBootProperties properties, Bucket4JConfiguration filter) { + if (!properties.getDefaultMetricTags().isEmpty()) { + var metricTags = filter.getMetrics().getTags(); + var filterMetricTagKeys = metricTags + .stream() + .map(MetricTag::getKey) + .collect(Collectors.toSet()); + properties.getDefaultMetricTags().forEach(defaultTag -> { + if (!filterMetricTagKeys.contains(defaultTag.getKey())) { + metricTags.add(defaultTag); + } + }); + } + } + + private Predicate prepareExecutionPredicates(RateLimit rl, Map> executePredicates) { + return rl.getExecutePredicates() + .stream() + .map(p -> createPredicate(p, executePredicates)) + .reduce(Predicate::and) + .orElseGet(() -> p -> true); + } + + private Predicate prepareSkipPredicates(RateLimit rl, Map> executePredicates) { + return rl.getSkipPredicates() + .stream() + .map(p -> createPredicate(p, executePredicates)) + .reduce(Predicate::and) + .orElseGet(() -> p -> false); + } + + protected Predicate createPredicate(ExecutePredicateDefinition pd, Map> executePredicates) { + var predicate = executePredicates.getOrDefault(pd.getName(), null); + log.debug("create-predicate;name:{};value:{}", pd.getName(), pd.getArgs()); + try { + @SuppressWarnings("unchecked") + ExecutePredicate newPredicateInstance = predicate.getClass().getDeclaredConstructor().newInstance(); + return newPredicateInstance.init(pd.getArgs()); + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException + | InvocationTargetException | NoSuchMethodException | SecurityException e) { + throw new ExecutePredicateInstantiationException(pd.getName(), predicate.getClass()); + } + } + + public static long getRemainingLimit(Long remaining, RateLimitResult rateLimitResult) { + if (rateLimitResult != null && (remaining == null || rateLimitResult.getRemainingTokens() < remaining)) { + remaining = rateLimitResult.getRemainingTokens(); + } + return remaining; + } + +} diff --git a/bucket4j-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/bucket4j-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports index e1387ab7..3ef6295b 100644 --- a/bucket4j-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ b/bucket4j-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -1,4 +1,5 @@ com.giffing.bucket4j.spring.boot.starter.config.cache.Bucket4jCacheConfiguration +com.giffing.bucket4j.spring.boot.starter.config.aspect.AopConfig com.giffing.bucket4j.spring.boot.starter.config.filter.reactive.gateway.Bucket4JAutoConfigurationSpringCloudGatewayFilter com.giffing.bucket4j.spring.boot.starter.config.filter.servlet.Bucket4JAutoConfigurationServletFilter com.giffing.bucket4j.spring.boot.starter.config.filter.reactive.webflux.Bucket4JAutoConfigurationWebfluxFilter diff --git a/bucket4j-spring-boot-starter/src/test/java/com/giffing/bucket4j/spring/boot/starter/gateway/SpringCloudGatewayRateLimitFilterTest.java b/bucket4j-spring-boot-starter/src/test/java/com/giffing/bucket4j/spring/boot/starter/gateway/SpringCloudGatewayRateLimitFilterTest.java index edc5fa7b..01eeafb6 100644 --- a/bucket4j-spring-boot-starter/src/test/java/com/giffing/bucket4j/spring/boot/starter/gateway/SpringCloudGatewayRateLimitFilterTest.java +++ b/bucket4j-spring-boot-starter/src/test/java/com/giffing/bucket4j/spring/boot/starter/gateway/SpringCloudGatewayRateLimitFilterTest.java @@ -107,9 +107,9 @@ void should_execute_all_checks_when_using_RateLimitConditionMatchingStrategy_All result.block(); }); - verify(rateLimitCheck1, times(1)).rateLimit(any()); - verify(rateLimitCheck2, times(1)).rateLimit(any()); - verify(rateLimitCheck3, times(1)).rateLimit(any()); + verify(rateLimitCheck1, times(1)).rateLimit(any(), any()); + verify(rateLimitCheck2, times(1)).rateLimit(any(), any()); + verify(rateLimitCheck3, times(1)).rateLimit(any(), any()); } @Test @@ -132,9 +132,9 @@ void should_execute_only_one_check_when_using_RateLimitConditionMatchingStrategy List values = captor.getAllValues(); Assertions.assertEquals("30", values.stream().findFirst().get()); - verify(rateLimitCheck1, times(1)).rateLimit(any()); - verify(rateLimitCheck2, times(0)).rateLimit(any()); - verify(rateLimitCheck3, times(0)).rateLimit(any()); + verify(rateLimitCheck1, times(1)).rateLimit(any(), any()); + verify(rateLimitCheck2, times(0)).rateLimit(any(), any()); + verify(rateLimitCheck3, times(0)).rateLimit(any(), any()); } private void rateLimitConfig(Long remainingTokens, RateLimitCheck rateLimitCheck) { @@ -144,6 +144,6 @@ private void rateLimitConfig(Long remainingTokens, RateLimitCheck values = captor.getAllValues(); Assertions.assertEquals("30", values.stream().findFirst().get()); - verify(rateLimitCheck1, times(1)).rateLimit(any()); - verify(rateLimitCheck2, times(0)).rateLimit(any()); - verify(rateLimitCheck3, times(0)).rateLimit(any()); + verify(rateLimitCheck1, times(1)).rateLimit(any(), any()); + verify(rateLimitCheck2, times(0)).rateLimit(any(), any()); + verify(rateLimitCheck3, times(0)).rateLimit(any(), any()); } private void rateLimitConfig(Long remainingTokens, RateLimitCheck rateLimitCheck) { @@ -147,7 +141,7 @@ private void rateLimitConfig(Long remainingTokens, RateLimitCheckorg.springframework.boot spring-boot-starter-validation + + org.springframework.boot + spring-boot-starter-aop + org.springframework.boot spring-boot-starter-actuator diff --git a/examples/caffeine/src/main/java/com/giffing/bucket4j/spring/boot/starter/examples/caffeine/CaffeineApplication.java b/examples/caffeine/src/main/java/com/giffing/bucket4j/spring/boot/starter/examples/caffeine/CaffeineApplication.java index ad2c9e28..947e97d7 100644 --- a/examples/caffeine/src/main/java/com/giffing/bucket4j/spring/boot/starter/examples/caffeine/CaffeineApplication.java +++ b/examples/caffeine/src/main/java/com/giffing/bucket4j/spring/boot/starter/examples/caffeine/CaffeineApplication.java @@ -3,9 +3,11 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.EnableAspectJAutoProxy; @SpringBootApplication @EnableCaching +@EnableAspectJAutoProxy public class CaffeineApplication { public static void main(String[] args) { diff --git a/examples/caffeine/src/main/java/com/giffing/bucket4j/spring/boot/starter/examples/caffeine/RateLimitExceptionHandler.java b/examples/caffeine/src/main/java/com/giffing/bucket4j/spring/boot/starter/examples/caffeine/RateLimitExceptionHandler.java new file mode 100644 index 00000000..3be62030 --- /dev/null +++ b/examples/caffeine/src/main/java/com/giffing/bucket4j/spring/boot/starter/examples/caffeine/RateLimitExceptionHandler.java @@ -0,0 +1,17 @@ +package com.giffing.bucket4j.spring.boot.starter.examples.caffeine; + +import com.giffing.bucket4j.spring.boot.starter.context.RateLimitException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +@ControllerAdvice +public class RateLimitExceptionHandler { + + @ExceptionHandler(value = {RateLimitException.class}) + protected ResponseEntity handleRateLimit(RateLimitException e) { + return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).build(); + } + +} diff --git a/examples/caffeine/src/main/java/com/giffing/bucket4j/spring/boot/starter/examples/caffeine/TestController.java b/examples/caffeine/src/main/java/com/giffing/bucket4j/spring/boot/starter/examples/caffeine/TestController.java index 43bccd15..1fa78cdc 100644 --- a/examples/caffeine/src/main/java/com/giffing/bucket4j/spring/boot/starter/examples/caffeine/TestController.java +++ b/examples/caffeine/src/main/java/com/giffing/bucket4j/spring/boot/starter/examples/caffeine/TestController.java @@ -1,28 +1,26 @@ package com.giffing.bucket4j.spring.boot.starter.examples.caffeine; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; - +import com.giffing.bucket4j.spring.boot.starter.config.cache.CacheManager; +import com.giffing.bucket4j.spring.boot.starter.context.properties.BandWidth; +import com.giffing.bucket4j.spring.boot.starter.context.properties.Bucket4JConfiguration; +import com.giffing.bucket4j.spring.boot.starter.context.properties.RateLimit; +import com.giffing.bucket4j.spring.boot.starter.utils.Bucket4JUtils; import jakarta.annotation.Nullable; import jakarta.validation.ConstraintViolation; import jakarta.validation.Valid; import jakarta.validation.Validator; - import org.springframework.context.support.DefaultMessageSourceResolvable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; - -import com.giffing.bucket4j.spring.boot.starter.config.cache.CacheManager; -import com.giffing.bucket4j.spring.boot.starter.context.properties.BandWidth; -import com.giffing.bucket4j.spring.boot.starter.context.properties.Bucket4JConfiguration; -import com.giffing.bucket4j.spring.boot.starter.context.properties.RateLimit; -import com.giffing.bucket4j.spring.boot.starter.utils.Bucket4JUtils; import org.springframework.web.util.HtmlUtils; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; + @RestController public class TestController { @@ -30,9 +28,14 @@ public class TestController { private final CacheManager configCacheManager; - public TestController(Validator validator, @Nullable CacheManager configCacheManager) { + private final TestService testService; + + public TestController(Validator validator, + @Nullable CacheManager configCacheManager, + TestService testService) { this.validator = validator; this.configCacheManager = configCacheManager; + this.testService = testService; } @GetMapping("unsecure") @@ -41,7 +44,8 @@ public ResponseEntity unsecure() { } @GetMapping("hello") - public ResponseEntity hello() { + public ResponseEntity hello(@RequestParam(required = false) String name) { + testService.execute(name); return ResponseEntity.ok("Hello World"); } diff --git a/examples/caffeine/src/main/java/com/giffing/bucket4j/spring/boot/starter/examples/caffeine/TestService.java b/examples/caffeine/src/main/java/com/giffing/bucket4j/spring/boot/starter/examples/caffeine/TestService.java new file mode 100644 index 00000000..84f1b75b --- /dev/null +++ b/examples/caffeine/src/main/java/com/giffing/bucket4j/spring/boot/starter/examples/caffeine/TestService.java @@ -0,0 +1,26 @@ +package com.giffing.bucket4j.spring.boot.starter.examples.caffeine; + +import com.giffing.bucket4j.spring.boot.starter.context.RateLimiting; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +@Service +@Slf4j +public class TestService { + + + @RateLimiting(name = "default", + executeCondition = "#myParamName != 'admin'", + ratePerMethod = true, + fallbackMethodName = "dummy") + public String execute(String myParamName) { + log.info("Method with Param {} executed", myParamName); + return myParamName; + } + + public String dummy(String myParamName) { + log.info("Fallback-Method with Param {} executed", myParamName); + return myParamName; + } + +} diff --git a/examples/caffeine/src/main/resources/application.yml b/examples/caffeine/src/main/resources/application.yml index 63cdab69..ba046996 100644 --- a/examples/caffeine/src/main/resources/application.yml +++ b/examples/caffeine/src/main/resources/application.yml @@ -21,6 +21,18 @@ bucket4j: enabled: true filter-config-caching-enabled: true filter-config-cache-name: filterConfigCache + methods: + - name: default + cache-name: buckets + rate-limit: + cache-key: 1 + bandwidths: + - capacity: 1 + refill-capacity: 1 + time: 2 + unit: seconds + initial-capacity: 1 + refill-speed: interval filters: - id: filter1 cache-name: buckets diff --git a/examples/caffeine/src/test/java/com/giffing/bucket4j/spring/boot/starter/examples/caffeine/CaffeineGeneralSuiteTest.java b/examples/caffeine/src/test/java/com/giffing/bucket4j/spring/boot/starter/examples/caffeine/CaffeineGeneralSuiteTest.java index c9b2d3b9..9dce3395 100644 --- a/examples/caffeine/src/test/java/com/giffing/bucket4j/spring/boot/starter/examples/caffeine/CaffeineGeneralSuiteTest.java +++ b/examples/caffeine/src/test/java/com/giffing/bucket4j/spring/boot/starter/examples/caffeine/CaffeineGeneralSuiteTest.java @@ -1,12 +1,14 @@ package com.giffing.bucket4j.spring.boot.starter.examples.caffeine; +import com.giffing.bucket4j.spring.boot.starter.general.tests.filter.method.MethodTestSuite; import com.giffing.bucket4j.spring.boot.starter.general.tests.filter.servlet.ServletTestSuite; import org.junit.platform.suite.api.SelectClasses; import org.junit.platform.suite.api.Suite; @Suite @SelectClasses({ - ServletTestSuite.class + ServletTestSuite.class, + MethodTestSuite.class }) public class CaffeineGeneralSuiteTest { } diff --git a/examples/ehcache/src/test/java/com/giffing/bucket4j/spring/boot/starter/examples/ehcache/EhcacheGeneralSuiteTest.java b/examples/ehcache/src/test/java/com/giffing/bucket4j/spring/boot/starter/examples/ehcache/EhcacheGeneralSuiteTest.java index a07b9d2c..dcfd47e8 100644 --- a/examples/ehcache/src/test/java/com/giffing/bucket4j/spring/boot/starter/examples/ehcache/EhcacheGeneralSuiteTest.java +++ b/examples/ehcache/src/test/java/com/giffing/bucket4j/spring/boot/starter/examples/ehcache/EhcacheGeneralSuiteTest.java @@ -6,7 +6,7 @@ @Suite @SelectClasses({ - ServletTestSuite.class + ServletTestSuite.class, }) public class EhcacheGeneralSuiteTest { } diff --git a/examples/general-tests/pom.xml b/examples/general-tests/pom.xml index 53d38e6d..5f021d70 100644 --- a/examples/general-tests/pom.xml +++ b/examples/general-tests/pom.xml @@ -23,6 +23,11 @@ org.springframework.boot spring-boot-starter-test + + org.springframework.boot + spring-boot-starter-aop + provided + org.springframework.boot spring-boot-starter-validation diff --git a/examples/general-tests/src/main/java/com/giffing/bucket4j/spring/boot/starter/general/tests/filter/method/MethodRateLimitTest.java b/examples/general-tests/src/main/java/com/giffing/bucket4j/spring/boot/starter/general/tests/filter/method/MethodRateLimitTest.java new file mode 100644 index 00000000..f1a4b80e --- /dev/null +++ b/examples/general-tests/src/main/java/com/giffing/bucket4j/spring/boot/starter/general/tests/filter/method/MethodRateLimitTest.java @@ -0,0 +1,88 @@ +package com.giffing.bucket4j.spring.boot.starter.general.tests.filter.method; + +import com.giffing.bucket4j.spring.boot.starter.context.RateLimitException; +import lombok.RequiredArgsConstructor; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; + +import static org.junit.jupiter.api.Assertions.*; + +@SpringBootTest(properties = { + "debug=true", + "bucket4j.methods[0].name=default", + "bucket4j.methods[0].cache-name=buckets", + "bucket4j.methods[0].rate-limit.bandwidths[0].capacity=5", + "bucket4j.methods[0].rate-limit.bandwidths[0].time=10", + "bucket4j.methods[0].rate-limit.bandwidths[0].unit=seconds", + "bucket4j.methods[0].rate-limit.bandwidths[0].refill-speed=greedy", +}) +@RequiredArgsConstructor +@DirtiesContext +public class MethodRateLimitTest { + + @Autowired + private TestService testService; + + + @Test + public void assert_rate_limit_with_execute_condition_matches() { + for(int i = 0; i < 5; i++) { + // rate limit executed because it's not the admin + testService.withExecuteCondition("normal_user"); + } + assertThrows(RateLimitException.class, () -> testService.withExecuteCondition("normal_user")); + } + + @Test + public void assert_no_rate_limit_with_execute_condition_does_not_match() { + assertAll(() -> { + for(int i = 0; i < 10; i++) { + // rate limit not executed for admin parameter + testService.withExecuteCondition("admin"); + } + }); + } + + @Test + public void assert_rate_limit_with_fallback_method() { + for(int i = 0; i < 5; i++) { + assertEquals("normal-method-executed;param:my-test", testService.withFallbackMethod("my-test")); + } + // no exception is thrown. fall back method is executed + assertEquals("fallback-method-executed;param:my-test", testService.withFallbackMethod("my-test")); + } + + @Test + public void assert_rate_limit_with_skip_condition_does_not_match() { + for(int i = 0; i < 5; i++) { + // skip condition does not match. rate limit is performed + testService.withSkipCondition("normal_user"); + } + assertThrows(RateLimitException.class, () -> testService.withSkipCondition("normal_user")); + } + + @Test + public void assert_no_rate_limit_with_skip_condition_matches() { + assertAll(() -> { + for(int i = 0; i < 10; i++) { + // no token consumption. admin is skipped + testService.withSkipCondition("admin"); + } + }); + } + + @Test + public void assert_rate_limit_with_cache_key() { + for(int i = 0; i < 5; i++) { + // rate limit by parameter value + testService.withCacheKey("key1"); + testService.withCacheKey("key2"); + // all tokens consumed + } + assertThrows(RateLimitException.class, () -> testService.withCacheKey("key1")); + assertThrows(RateLimitException.class, () -> testService.withCacheKey("key2")); + } + +} diff --git a/examples/general-tests/src/main/java/com/giffing/bucket4j/spring/boot/starter/general/tests/filter/method/MethodTestApplication.java b/examples/general-tests/src/main/java/com/giffing/bucket4j/spring/boot/starter/general/tests/filter/method/MethodTestApplication.java new file mode 100644 index 00000000..39ba101e --- /dev/null +++ b/examples/general-tests/src/main/java/com/giffing/bucket4j/spring/boot/starter/general/tests/filter/method/MethodTestApplication.java @@ -0,0 +1,17 @@ +package com.giffing.bucket4j.spring.boot.starter.general.tests.filter.method; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.EnableAspectJAutoProxy; + +@SpringBootApplication +@EnableCaching +@EnableAspectJAutoProxy +public class MethodTestApplication { + + public static void main(String[] args) { + SpringApplication.run(MethodTestApplication.class, args); + } + +} \ No newline at end of file diff --git a/examples/general-tests/src/main/java/com/giffing/bucket4j/spring/boot/starter/general/tests/filter/method/MethodTestSuite.java b/examples/general-tests/src/main/java/com/giffing/bucket4j/spring/boot/starter/general/tests/filter/method/MethodTestSuite.java new file mode 100644 index 00000000..a0e9764e --- /dev/null +++ b/examples/general-tests/src/main/java/com/giffing/bucket4j/spring/boot/starter/general/tests/filter/method/MethodTestSuite.java @@ -0,0 +1,11 @@ +package com.giffing.bucket4j.spring.boot.starter.general.tests.filter.method; + +import org.junit.platform.suite.api.SelectClasses; +import org.junit.platform.suite.api.Suite; + +@Suite +@SelectClasses({ + MethodRateLimitTest.class +}) +public class MethodTestSuite { +} diff --git a/examples/general-tests/src/main/java/com/giffing/bucket4j/spring/boot/starter/general/tests/filter/method/TestService.java b/examples/general-tests/src/main/java/com/giffing/bucket4j/spring/boot/starter/general/tests/filter/method/TestService.java new file mode 100644 index 00000000..5ec5c18e --- /dev/null +++ b/examples/general-tests/src/main/java/com/giffing/bucket4j/spring/boot/starter/general/tests/filter/method/TestService.java @@ -0,0 +1,45 @@ +package com.giffing.bucket4j.spring.boot.starter.general.tests.filter.method; + +import com.giffing.bucket4j.spring.boot.starter.context.RateLimiting; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +@Component +@Slf4j +public class TestService { + + + @RateLimiting( + name = "default", + executeCondition = "#myParamName != 'admin'") + public String withExecuteCondition(String myParamName) { + log.info("Method withExecuteCondition with Param {} executed", myParamName); + return myParamName; + } + + @RateLimiting( + name = "default", + skipCondition = "#myParamName eq 'admin'") + public String withSkipCondition(String myParamName) { + log.info("Method withSkipCondition with Param {} executed", myParamName); + return myParamName; + } + + @RateLimiting( + name = "default", + cacheKey = "#cacheKey") + public String withCacheKey(String cacheKey) { + log.info("Method withCacheKey with Param {} executed", cacheKey); + return cacheKey; + } + + @RateLimiting(name = "default", cacheKey = "'normal'", fallbackMethodName = "fallbackMethod") + public String withFallbackMethod(String myParamName) { + return "normal-method-executed;param:" + myParamName; + } + + public String fallbackMethod(String myParamName) { + return "fallback-method-executed;param:" + myParamName; + } + +} diff --git a/pom.xml b/pom.xml index 777e0722..0fa248ff 100644 --- a/pom.xml +++ b/pom.xml @@ -45,7 +45,7 @@ bucket4j-spring-boot-starter-parent-0.3.4 - 0.11.0 + 0.12.0 UTF-8 UTF-8 17 diff --git a/src/main/doc/plantuml/post_execution_condition.plantuml b/src/main/doc/plantuml/post_execution_condition.plantuml new file mode 100644 index 00000000..22c89377 --- /dev/null +++ b/src/main/doc/plantuml/post_execution_condition.plantuml @@ -0,0 +1,35 @@ +@startuml + +User -> Bucket4jFilter: request + +box "Webserver" #f5e4e4 + + Bucket4jFilter -> Bucket4jFilter : estimate_remaining_tokens + participant Bucket4jFilter + participant SpringSecurityFilter + alt 1 token available + + note right of Bucket4jFilter: There is one token available. \nThe request will not be aborted + Bucket4jFilter -> SpringSecurityFilter : request + SpringSecurityFilter -> SpringSecurityFilter : authenticate + SpringSecurityFilter -> Bucket4jFilter : response(401) + alt HTTP Response Status == 401 + note right of Bucket4jFilter: The token will only be consumed\n if the HTTP Status is 401\n + Bucket4jFilter -> Bucket4jFilter : consume_token + end + Bucket4jFilter -> User : response(401) + + else 0 token available + note right of Bucket4jFilter: The token was consumed \nbecause of the HTTP Response Status 401 + Bucket4jFilter -> Bucket4jFilter : reject request + Bucket4jFilter -> User : response\n(429 Too Many Requests) + end + + + + + +end box + + +@enduml \ No newline at end of file diff --git a/src/main/doc/plantuml/post_execution_condition.png b/src/main/doc/plantuml/post_execution_condition.png new file mode 100644 index 00000000..31f3f8cb Binary files /dev/null and b/src/main/doc/plantuml/post_execution_condition.png differ