Search in sources :

Example 6 with RequestRateLimiter

use of es.moki.ratelimitj.core.limiter.request.RequestRateLimiter in project ratelimitj by mokies.

the class AbstractSyncRequestRateLimiterTest method shouldGeLimitSingleWindowSync.

@Test
void shouldGeLimitSingleWindowSync() {
    ImmutableSet<RequestLimitRule> rules = ImmutableSet.of(RequestLimitRule.of(10, TimeUnit.SECONDS, 5));
    RequestRateLimiter requestRateLimiter = getRateLimiter(rules, timeBandit);
    IntStream.rangeClosed(1, 4).forEach(value -> {
        timeBandit.addUnixTimeMilliSeconds(1000L);
        assertThat(requestRateLimiter.geLimitWhenIncremented("ip:127.0.1.2")).isFalse();
    });
    assertThat(requestRateLimiter.geLimitWhenIncremented("ip:127.0.1.2")).isTrue();
}
Also used : RequestRateLimiter(es.moki.ratelimitj.core.limiter.request.RequestRateLimiter) RequestLimitRule(es.moki.ratelimitj.core.limiter.request.RequestLimitRule) Test(org.junit.jupiter.api.Test)

Example 7 with RequestRateLimiter

use of es.moki.ratelimitj.core.limiter.request.RequestRateLimiter in project ratelimitj by mokies.

the class RedisRateLimiterFactoryTest method shouldReturnTheSameInstanceForSameRules.

@Test
void shouldReturnTheSameInstanceForSameRules() {
    RequestLimitRule rule1 = RequestLimitRule.of(1, TimeUnit.MINUTES, 10);
    RequestRateLimiter rateLimiter1 = factory.getInstance(ImmutableSet.of(rule1));
    RequestLimitRule rule2 = RequestLimitRule.of(1, TimeUnit.MINUTES, 10);
    RequestRateLimiter rateLimiter2 = factory.getInstance(ImmutableSet.of(rule2));
    assertThat(rateLimiter1).isSameAs(rateLimiter2);
}
Also used : RequestRateLimiter(es.moki.ratelimitj.core.limiter.request.RequestRateLimiter) RequestLimitRule(es.moki.ratelimitj.core.limiter.request.RequestLimitRule) Test(org.junit.jupiter.api.Test)

Example 8 with RequestRateLimiter

use of es.moki.ratelimitj.core.limiter.request.RequestRateLimiter in project ratelimitj by mokies.

the class RateLimit429EnforcerFilter method filter.

@Override
public void filter(final ContainerRequestContext requestContext) {
    try {
        AnnotatedMethod method = new AnnotatedMethod(resource.getResourceMethod());
        RateLimited rateLimited = method.getAnnotation(RateLimited.class);
        RequestRateLimiter rateLimit = factory.getInstance(toLimitRules(rateLimited));
        KeyProvider keyProvider = rateLimited.key();
        KeyPart[] keyParts = rateLimited.keys();
        if (keyProvider == Key.NO_VALUE && keyParts.length == 0) {
            LOG.warn("No keys were provided by the key provide");
            return;
        }
        Optional<CharSequence> legacyKey = keyProvider.create(request, resource, securityContext);
        CharSequence key;
        if (legacyKey.isPresent()) {
            key = legacyKey.get();
        } else {
            Optional<CharSequence> keyResult = KeyPart.combineKeysParts(rateLimited.groupKeyPrefix(), Arrays.asList(keyParts), request, resource, securityContext);
            if (keyResult.isPresent()) {
                key = keyResult.get();
            } else {
                LOG.warn("No keys were provided by the key providers '{}'", Arrays.stream(keyParts).map(KeyPart::getClass).map(Object::toString).collect(Collectors.joining(", ")));
                return;
            }
        }
        // if (legacyKey.isPresent()) {
        boolean overLimit = rateLimit.overLimitWhenIncremented(key.toString());
        if (overLimit) {
            if (!rateLimited.reportOnly()) {
                LOG.info("rate-limit key '{}' over limit. HTTP Status 429 returned.", key);
                requestContext.abortWith(Response.status(HTTP_STATUS_TOO_MANY_REQUESTS).build());
            } else {
                LOG.info("rate-limit key '{}' over limit. ReportOnly is true, no action taken.", key);
            }
            LOG.debug("rate-limit key '{}' under limit.", key);
        }
    // } else {
    // //LOG.warn("No key was provided by the key provide '{}'", keyProvider.getClass());
    // }
    } catch (Exception e) {
        LOG.error("Error occurred checking rate-limit. Assuming under limit", e);
    }
}
Also used : RequestRateLimiter(es.moki.ratelimitj.core.limiter.request.RequestRateLimiter) AnnotatedMethod(org.glassfish.jersey.server.model.AnnotatedMethod) RateLimited(es.moki.ratelimij.dropwizard.annotation.RateLimited)

Example 9 with RequestRateLimiter

use of es.moki.ratelimitj.core.limiter.request.RequestRateLimiter in project ratelimitj by mokies.

the class AbstractSyncRequestRateLimiterPerformanceTest method shouldLimitDualWindowSyncTimed.

@Test
void shouldLimitDualWindowSyncTimed() {
    Stopwatch watch = Stopwatch.createStarted();
    ImmutableSet<RequestLimitRule> rules = ImmutableSet.of(RequestLimitRule.of(2, TimeUnit.SECONDS, 100), RequestLimitRule.of(10, TimeUnit.SECONDS, 100));
    RequestRateLimiter requestRateLimiter = getRateLimiter(rules, timeBandit);
    Random rand = new Random();
    int total = 10_000;
    IntStream.rangeClosed(1, total).map(i -> rand.nextInt(128)).forEach(value -> {
        timeBandit.addUnixTimeMilliSeconds(200L);
        requestRateLimiter.overLimitWhenIncremented("ip:127.0.0." + value);
    });
    double transactionsPerSecond = Math.ceil((double) total / watch.elapsed(TimeUnit.MILLISECONDS) * 1000);
    log.info("total time {} checks {}/sec", watch.stop(), NumberFormat.getNumberInstance(Locale.US).format(transactionsPerSecond));
}
Also used : IntStream(java.util.stream.IntStream) ImmutableSet(com.google.common.collect.ImmutableSet) Logger(org.slf4j.Logger) Stopwatch(com.google.common.base.Stopwatch) LoggerFactory(org.slf4j.LoggerFactory) Set(java.util.Set) Random(java.util.Random) NumberFormat(java.text.NumberFormat) Test(org.junit.jupiter.api.Test) TimeUnit(java.util.concurrent.TimeUnit) RequestRateLimiter(es.moki.ratelimitj.core.limiter.request.RequestRateLimiter) TimeSupplier(es.moki.ratelimitj.core.time.TimeSupplier) Locale(java.util.Locale) RequestLimitRule(es.moki.ratelimitj.core.limiter.request.RequestLimitRule) TimeBanditSupplier(es.moki.ratelimitj.test.time.TimeBanditSupplier) RequestRateLimiter(es.moki.ratelimitj.core.limiter.request.RequestRateLimiter) Random(java.util.Random) Stopwatch(com.google.common.base.Stopwatch) RequestLimitRule(es.moki.ratelimitj.core.limiter.request.RequestLimitRule) Test(org.junit.jupiter.api.Test)

Example 10 with RequestRateLimiter

use of es.moki.ratelimitj.core.limiter.request.RequestRateLimiter in project ratelimitj by mokies.

the class InMemoryRateLimiterFactoryTest method shouldNotReturnTheSameInstanceForSameRules.

@Test
void shouldNotReturnTheSameInstanceForSameRules() {
    RequestLimitRule rule1 = RequestLimitRule.of(1, TimeUnit.MINUTES, 22);
    RequestRateLimiter rateLimiter1 = factory.getInstance(ImmutableSet.of(rule1));
    RequestLimitRule rule2 = RequestLimitRule.of(1, TimeUnit.MINUTES, 33);
    RequestRateLimiter rateLimiter2 = factory.getInstance(ImmutableSet.of(rule2));
    assertThat(rateLimiter1).isNotSameAs(rateLimiter2);
}
Also used : RequestRateLimiter(es.moki.ratelimitj.core.limiter.request.RequestRateLimiter) RequestLimitRule(es.moki.ratelimitj.core.limiter.request.RequestLimitRule) Test(org.junit.jupiter.api.Test)

Aggregations

RequestRateLimiter (es.moki.ratelimitj.core.limiter.request.RequestRateLimiter)15 RequestLimitRule (es.moki.ratelimitj.core.limiter.request.RequestLimitRule)14 Test (org.junit.jupiter.api.Test)14 Stopwatch (com.google.common.base.Stopwatch)1 ImmutableSet (com.google.common.collect.ImmutableSet)1 DistributedObject (com.hazelcast.core.DistributedObject)1 RateLimited (es.moki.ratelimij.dropwizard.annotation.RateLimited)1 TimeSupplier (es.moki.ratelimitj.core.time.TimeSupplier)1 TimeBanditSupplier (es.moki.ratelimitj.test.time.TimeBanditSupplier)1 NumberFormat (java.text.NumberFormat)1 Locale (java.util.Locale)1 Random (java.util.Random)1 Set (java.util.Set)1 TimeUnit (java.util.concurrent.TimeUnit)1 IntStream (java.util.stream.IntStream)1 AnnotatedMethod (org.glassfish.jersey.server.model.AnnotatedMethod)1 Disabled (org.junit.jupiter.api.Disabled)1 Logger (org.slf4j.Logger)1 LoggerFactory (org.slf4j.LoggerFactory)1