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