use of es.moki.ratelimij.dropwizard.annotation.RateLimited in project ratelimitj by mokies.
the class RateLimited429EnforcerFeature method configure.
@Override
public void configure(final ResourceInfo resourceInfo, final FeatureContext context) {
final AnnotatedMethod method = new AnnotatedMethod(resourceInfo.getResourceMethod());
final RateLimited rateLimited = method.getAnnotation(RateLimited.class);
if (null != rateLimited) {
context.register(RateLimit429EnforcerFilter.class);
}
}
use of es.moki.ratelimij.dropwizard.annotation.RateLimited 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);
}
}
Aggregations