|
16 | 16 | package software.amazon.awssdk.retries.internal.ratelimiter; |
17 | 17 |
|
18 | 18 | import java.time.Duration; |
| 19 | +import java.util.ArrayDeque; |
| 20 | +import java.util.Deque; |
| 21 | +import java.util.concurrent.CompletableFuture; |
| 22 | +import java.util.concurrent.Executors; |
| 23 | +import java.util.concurrent.ScheduledExecutorService; |
| 24 | +import java.util.concurrent.TimeUnit; |
19 | 25 | import java.util.concurrent.atomic.AtomicReference; |
20 | 26 | import java.util.function.Consumer; |
21 | 27 | import java.util.function.Function; |
22 | 28 | import software.amazon.awssdk.annotations.SdkInternalApi; |
| 29 | +import software.amazon.awssdk.annotations.SdkTestInternalApi; |
| 30 | +import software.amazon.awssdk.annotations.ThreadSafe; |
| 31 | +import software.amazon.awssdk.utils.SdkAutoCloseable; |
23 | 32 |
|
24 | 33 | /** |
25 | 34 | * The {@link RateLimiterTokenBucket} keeps track of past throttling responses and adapts to slow down the send rate to adapt to |
26 | | - * the service. It does this by suggesting a delay amount as result of a {@link #tryAcquire()} call. Callers must update its |
27 | | - * internal state by calling {@link #updateRateAfterThrottling()} when getting a throttling response or |
28 | | - * {@link #updateRateAfterSuccess()} when getting successful response. |
| 35 | + * the service. It does this by delaying the completion of the future returned by {@link #acquireAsync()} until the requested |
| 36 | + * capacity is available. Callers must update its internal state by calling {@link #updateRateAfterThrottling()} when getting a |
| 37 | + * throttling response or {@link #updateRateAfterSuccess()} when getting successful response. |
29 | 38 | * |
30 | | - * <p>This class is thread-safe, its internal current state is kept in the inner class {@link PersistentState} which is stored |
31 | | - * using an {@link AtomicReference}. This class is converted to {@link TransientState} when the state needs to be mutated and |
32 | | - * converted back to a {@link PersistentState} and stored using {@link AtomicReference#compareAndSet(Object, Object)}. |
| 39 | + * <p>This class is thread-safe. |
33 | 40 | * |
34 | 41 | * <p>The algorithm used is adapted from the network congestion avoidance algorithm |
35 | 42 | * <a href="https://en.wikipedia.org/wiki/CUBIC_TCP">CUBIC</a>. |
36 | 43 | */ |
37 | 44 | @SdkInternalApi |
38 | | -public class RateLimiterTokenBucket { |
| 45 | +@ThreadSafe |
| 46 | +public class RateLimiterTokenBucket implements SdkAutoCloseable { |
| 47 | + // Thread used for capacity waiting and notifying. |
| 48 | + private final ScheduledExecutorService scheduler; |
| 49 | + // the collection of futures returned to threads currently waiting for capacity. Futures are completed in FIFO order. |
| 50 | + private final Deque<CompletableFuture<Void>> waiting = new ArrayDeque<>(); |
39 | 51 | private final AtomicReference<PersistentState> stateReference; |
40 | 52 | private final RateLimiterClock clock; |
| 53 | + private final Object lock = new Object(); |
41 | 54 |
|
42 | | - RateLimiterTokenBucket(RateLimiterClock clock) { |
| 55 | + private boolean notifierRunning = false; |
| 56 | + |
| 57 | + RateLimiterTokenBucket(RateLimiterClock clock, ScheduledExecutorService scheduler) { |
43 | 58 | this.clock = clock; |
| 59 | + this.scheduler = scheduler; |
44 | 60 | this.stateReference = new AtomicReference<>(new PersistentState()); |
45 | 61 | } |
46 | 62 |
|
| 63 | + @Override |
| 64 | + public void close() { |
| 65 | + scheduler.shutdownNow(); |
| 66 | + } |
| 67 | + |
47 | 68 | /** |
48 | | - * Acquire tokens from the bucket. If the bucket contains enough capacity to satisfy the request, this method will return in |
49 | | - * {@link RateLimiterAcquireResponse#delay()} a {@link Duration#ZERO} value, otherwise it will return the amount of time the |
50 | | - * callers need to wait until enough tokens are refilled. |
| 69 | + * Acquire a token from the bucket. |
| 70 | + * |
| 71 | + * @return A future that is completed when the requested amount is acquired from this bucket. |
51 | 72 | */ |
52 | | - public RateLimiterAcquireResponse tryAcquire() { |
53 | | - StateUpdate<Duration> update = updateState(ts -> ts.tokenBucketAcquire(clock, 1.0)); |
54 | | - return RateLimiterAcquireResponse.create(update.result); |
| 73 | + public CompletableFuture<Void> acquireAsync() { |
| 74 | + synchronized (lock) { |
| 75 | + CompletableFuture<Void> future = new CompletableFuture<>(); |
| 76 | + if (!notifierRunning) { |
| 77 | + waiting.add(future); |
| 78 | + boolean scheduled = scheduleOrFail(this::doNotify, Duration.ZERO, future); |
| 79 | + if (scheduled) { |
| 80 | + notifierRunning = true; |
| 81 | + } else { |
| 82 | + waiting.pop(); |
| 83 | + } |
| 84 | + } |
| 85 | + return future; |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + public void doNotify() { |
| 90 | + synchronized (lock) { |
| 91 | + while (true) { |
| 92 | + CompletableFuture<Void> w = waiting.poll(); |
| 93 | + if (w == null) { |
| 94 | + notifierRunning = false; |
| 95 | + return; |
| 96 | + } |
| 97 | + |
| 98 | + PersistentState persistentState = stateReference.get(); |
| 99 | + TransientState ts = persistentState.toTransient(); |
| 100 | + TransientState.AcquireResult acquireResult = ts.tokenBucketAcquire(clock, 1.0); |
| 101 | + stateReference.set(ts.toPersistent()); |
| 102 | + |
| 103 | + // Not enough capacity. Try again later when enough time has passed to refill the bucket at the current rate. |
| 104 | + if (!acquireResult.isSuccessful()) { |
| 105 | + waiting.push(w); |
| 106 | + |
| 107 | + if (!scheduleOrFail(this::doNotify, acquireResult.refillWait(), w)) { |
| 108 | + waiting.pop(); |
| 109 | + return; |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + // Acquire was successful, signal the waiting thread. |
| 114 | + w.complete(null); |
| 115 | + } |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + @SdkTestInternalApi |
| 120 | + Deque<CompletableFuture<Void>> waiting() { |
| 121 | + return waiting; |
| 122 | + } |
| 123 | + |
| 124 | + private void schedule(Runnable command, Duration d) { |
| 125 | + scheduler.schedule(command, d.toMillis(), TimeUnit.MILLISECONDS); |
| 126 | + } |
| 127 | + |
| 128 | + /** |
| 129 | + * @return true if schedule was successful, false otherwise. |
| 130 | + */ |
| 131 | + private boolean scheduleOrFail(Runnable command, Duration d, CompletableFuture<?> future) { |
| 132 | + try { |
| 133 | + schedule(command, d); |
| 134 | + return true; |
| 135 | + } catch (Throwable t) { |
| 136 | + RuntimeException e = new RuntimeException("Unable to initiate token acquire", t); |
| 137 | + future.completeExceptionally(e); |
| 138 | + } |
| 139 | + return false; |
55 | 140 | } |
56 | 141 |
|
57 | 142 | /** |
@@ -95,17 +180,20 @@ private StateUpdate<Void> consumeState(Consumer<TransientState> mutator) { |
95 | 180 | * retried until succeeded. |
96 | 181 | */ |
97 | 182 | private <T> StateUpdate<T> updateState(Function<TransientState, T> mutator) { |
98 | | - PersistentState current; |
99 | | - PersistentState updated; |
100 | | - T result; |
101 | | - do { |
102 | | - current = stateReference.get(); |
103 | | - TransientState transientState = current.toTransient(); |
104 | | - result = mutator.apply(transientState); |
105 | | - updated = transientState.toPersistent(); |
106 | | - } while (!stateReference.compareAndSet(current, updated)); |
107 | | - |
108 | | - return new StateUpdate<>(updated, result); |
| 183 | + synchronized (lock) { |
| 184 | + PersistentState current; |
| 185 | + PersistentState updated; |
| 186 | + T result; |
| 187 | + do { |
| 188 | + current = stateReference.get(); |
| 189 | + TransientState transientState = current.toTransient(); |
| 190 | + result = mutator.apply(transientState); |
| 191 | + updated = transientState.toPersistent(); |
| 192 | + } while (!stateReference.compareAndSet(current, updated)); |
| 193 | + |
| 194 | + |
| 195 | + return new StateUpdate<>(updated, result); |
| 196 | + } |
109 | 197 | } |
110 | 198 |
|
111 | 199 | static class StateUpdate<T> { |
@@ -163,17 +251,39 @@ PersistentState toPersistent() { |
163 | 251 | * a {@link Duration#ZERO} value, otherwise it will return the amount of time the callers need to wait until enough tokens |
164 | 252 | * are refilled. |
165 | 253 | */ |
166 | | - Duration tokenBucketAcquire(RateLimiterClock clock, double amount) { |
| 254 | + AcquireResult tokenBucketAcquire(RateLimiterClock clock, double amount) { |
167 | 255 | if (!this.enabled) { |
168 | | - return Duration.ZERO; |
| 256 | + return new AcquireResult(true, Duration.ZERO); |
169 | 257 | } |
170 | 258 | refill(clock); |
171 | | - double waitTime = 0.0; |
172 | 259 | if (this.currentCapacity < amount) { |
173 | | - waitTime = (amount - this.currentCapacity) / this.fillRate; |
| 260 | + double diff = amount - currentCapacity; |
| 261 | + this.currentCapacity = 0; |
| 262 | + double waitTime = diff / this.fillRate; |
| 263 | + double waitTimeMs = waitTime * 1_000.0; |
| 264 | + Duration duration = Duration.ofMillis((long) Math.ceil(waitTimeMs)); |
| 265 | + return new AcquireResult(false, duration); |
174 | 266 | } |
175 | 267 | this.currentCapacity -= amount; |
176 | | - return Duration.ofNanos((long) (waitTime * 1_000_000_000.0)); |
| 268 | + return new AcquireResult(true, Duration.ZERO); |
| 269 | + } |
| 270 | + |
| 271 | + private static class AcquireResult { |
| 272 | + final boolean successful; |
| 273 | + final Duration refillWait; |
| 274 | + |
| 275 | + public AcquireResult(boolean successful, Duration refillWait) { |
| 276 | + this.successful = successful; |
| 277 | + this.refillWait = refillWait; |
| 278 | + } |
| 279 | + |
| 280 | + public boolean isSuccessful() { |
| 281 | + return successful; |
| 282 | + } |
| 283 | + |
| 284 | + public Duration refillWait() { |
| 285 | + return refillWait; |
| 286 | + } |
177 | 287 | } |
178 | 288 |
|
179 | 289 | /** |
|
0 commit comments