|
| 1 | +/** |
| 2 | + * Jooby https://jooby.io |
| 3 | + * Apache License Version 2.0 https://jooby.io/LICENSE.txt |
| 4 | + * Copyright 2014 Edgar Espina |
| 5 | + */ |
| 6 | +package io.jooby; |
| 7 | + |
| 8 | +import io.github.bucket4j.Bucket; |
| 9 | +import io.github.bucket4j.ConsumptionProbe; |
| 10 | + |
| 11 | +import javax.annotation.Nonnull; |
| 12 | +import java.util.Map; |
| 13 | +import java.util.concurrent.ConcurrentHashMap; |
| 14 | +import java.util.function.Function; |
| 15 | + |
| 16 | +import static java.util.concurrent.TimeUnit.NANOSECONDS; |
| 17 | + |
| 18 | +/** |
| 19 | + * Rate limit handler using https://github.com/vladimir-bukhtoyarov/bucket4j. |
| 20 | + * |
| 21 | + * NOTE: bucket4j must be included as part of your project dependencies (classpath). |
| 22 | + * |
| 23 | + * Example 1: 10 requests per minute |
| 24 | + * <pre>{@code |
| 25 | + * { |
| 26 | + * Bandwidth limit = Bandwidth.simple(10, Duration.ofMinutes(1)); |
| 27 | + * Bucket bucket = Bucket4j.builder().addLimit(limit).build(); |
| 28 | + * |
| 29 | + * before(new RateLimitHandler(bucket)); |
| 30 | + * } |
| 31 | + * }</pre> |
| 32 | + * |
| 33 | + * Example 2: 10 requests per minute per IP address |
| 34 | + * <pre>{@code |
| 35 | + * { |
| 36 | + * before(new RateLimitHandler(remoteAddress -> { |
| 37 | + * Bandwidth limit = Bandwidth.simple(10, Duration.ofMinutes(1)); |
| 38 | + * return Bucket4j.builder().addLimit(limit).build(); |
| 39 | + * })); |
| 40 | + * } |
| 41 | + * }</pre> |
| 42 | + * |
| 43 | + * Example 3: 10 requests per minute using an <code>ApiKey</code> header. |
| 44 | + * <pre>{@code |
| 45 | + * { |
| 46 | + * before(new RateLimitHandler(key -> { |
| 47 | + * Bandwidth limit = Bandwidth.simple(10, Duration.ofMinutes(1)); |
| 48 | + * return Bucket4j.builder().addLimit(limit).build(); |
| 49 | + * }, "ApiKey")); |
| 50 | + * } |
| 51 | + * }</pre> |
| 52 | + * |
| 53 | + * Example 4: Rate limit in a cluster |
| 54 | + * <pre>{@code |
| 55 | + * { |
| 56 | + * // Get one of the proxy manager from bucket4j |
| 57 | + * ProxyManager<String> buckets = ...; |
| 58 | + * before(RateLimitHandler.cluster(key -> { |
| 59 | + * buckets.getProxy(key, () -> { |
| 60 | + * return Bucket4j.configurationBuilder() |
| 61 | + * .addLimit(Bandwidth.classic(100, Refill.intervally(100, Duration.ofMinutes(1)))) |
| 62 | + * .build(); |
| 63 | + * }); |
| 64 | + * })); |
| 65 | + * } |
| 66 | + * }</pre> |
| 67 | + * |
| 68 | + * @author edgar |
| 69 | + * @since 2.5.2 |
| 70 | + */ |
| 71 | +public class RateLimitHandler implements Route.Before { |
| 72 | + |
| 73 | + private final Function<Context, Bucket> factory; |
| 74 | + |
| 75 | + /** |
| 76 | + * Rate limit per IP/Remote Address. |
| 77 | + * |
| 78 | + * @param bucketFactory Bucket factory. |
| 79 | + */ |
| 80 | + public RateLimitHandler(@Nonnull SneakyThrows.Function<String, Bucket> bucketFactory) { |
| 81 | + this(bucketFactory, Context::getRemoteAddress); |
| 82 | + } |
| 83 | + |
| 84 | + /** |
| 85 | + * Rate limit per header key. |
| 86 | + * |
| 87 | + * @param bucketFactory Bucket factory. |
| 88 | + * @param headerName Header to use as key. |
| 89 | + */ |
| 90 | + public RateLimitHandler(@Nonnull SneakyThrows.Function<String, Bucket> bucketFactory, |
| 91 | + @Nonnull String headerName) { |
| 92 | + this(bucketFactory, ctx -> ctx.header(headerName).value()); |
| 93 | + } |
| 94 | + |
| 95 | + /** |
| 96 | + * Rate limiter with a custom key provider. |
| 97 | + * |
| 98 | + * @param bucketFactory Bucket factory. |
| 99 | + * @param classifier Key provider. |
| 100 | + */ |
| 101 | + public RateLimitHandler(@Nonnull SneakyThrows.Function<String, Bucket> bucketFactory, |
| 102 | + @Nonnull SneakyThrows.Function<Context, String> classifier) { |
| 103 | + this(byKey(bucketFactory, classifier)); |
| 104 | + } |
| 105 | + |
| 106 | + /** |
| 107 | + * Rate limiter with a shared/global bucket. |
| 108 | + * |
| 109 | + * @param bucket Bucket to use. |
| 110 | + */ |
| 111 | + public RateLimitHandler(@Nonnull Bucket bucket) { |
| 112 | + this((Function<Context, Bucket>) ctx -> bucket); |
| 113 | + } |
| 114 | + |
| 115 | + private RateLimitHandler(Function<Context, Bucket> factory) { |
| 116 | + this.factory = factory; |
| 117 | + } |
| 118 | + |
| 119 | + /** |
| 120 | + * Rate limiter per IP/Remote address using a cluster. |
| 121 | + * |
| 122 | + * @param proxyManager Cluster bucket configuration. |
| 123 | + * @return Rate limiter. |
| 124 | + */ |
| 125 | + public static @Nonnull RateLimitHandler cluster( |
| 126 | + @Nonnull SneakyThrows.Function<String, Bucket> proxyManager) { |
| 127 | + return cluster(proxyManager, Context::getRemoteAddress); |
| 128 | + } |
| 129 | + |
| 130 | + /** |
| 131 | + * Rate limiter per header key using a cluster. |
| 132 | + * |
| 133 | + * @param proxyManager Cluster bucket configuration. |
| 134 | + * @param headerName Header to use as key. |
| 135 | + * @return Rate limiter. |
| 136 | + */ |
| 137 | + public static @Nonnull RateLimitHandler cluster( |
| 138 | + @Nonnull SneakyThrows.Function<String, Bucket> proxyManager, @Nonnull String headerName) { |
| 139 | + return cluster(proxyManager, ctx -> ctx.header(headerName).value()); |
| 140 | + } |
| 141 | + |
| 142 | + /** |
| 143 | + * Rate limiter per key using a cluster. |
| 144 | + * |
| 145 | + * @param proxyManager Cluster bucket configuration. |
| 146 | + * @param classifier Key provider. |
| 147 | + * @return Rate limiter. |
| 148 | + */ |
| 149 | + public static RateLimitHandler cluster( |
| 150 | + @Nonnull SneakyThrows.Function<String, Bucket> proxyManager, |
| 151 | + @Nonnull SneakyThrows.Function<Context, String> classifier) { |
| 152 | + return new RateLimitHandler( |
| 153 | + (Function<Context, Bucket>) ctx -> proxyManager.apply(classifier.apply(ctx))); |
| 154 | + } |
| 155 | + |
| 156 | + @Override public void apply(@Nonnull Context ctx) throws Exception { |
| 157 | + Bucket bucket = factory.apply(ctx); |
| 158 | + // tryConsume returns false immediately if no tokens available with the bucket |
| 159 | + ConsumptionProbe probe = bucket.tryConsumeAndReturnRemaining(1); |
| 160 | + if (probe.isConsumed()) { |
| 161 | + ctx.setResponseHeader("X-Rate-Limit-Remaining", probe.getRemainingTokens()); |
| 162 | + } else { |
| 163 | + ctx.setResponseHeader("X-Rate-Limit-Retry-After-Milliseconds", |
| 164 | + NANOSECONDS.toMillis(probe.getNanosToWaitForRefill())); |
| 165 | + ctx.send(StatusCode.TOO_MANY_REQUESTS); |
| 166 | + } |
| 167 | + } |
| 168 | + |
| 169 | + private static Function<Context, Bucket> byKey( |
| 170 | + SneakyThrows.Function<String, Bucket> bucketFactory, |
| 171 | + SneakyThrows.Function<Context, String> classifier) { |
| 172 | + Map<String, Bucket> buckets = new ConcurrentHashMap<>(); |
| 173 | + return ctx -> buckets.computeIfAbsent(classifier.apply(ctx), bucketFactory); |
| 174 | + } |
| 175 | +} |
0 commit comments