|
| 1 | +/* |
| 2 | + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +package software.amazon.smithy.java.retries; |
| 7 | + |
| 8 | +import static org.junit.jupiter.api.Assertions.assertTrue; |
| 9 | + |
| 10 | +import java.time.Duration; |
| 11 | +import java.util.concurrent.CountDownLatch; |
| 12 | +import java.util.concurrent.ExecutorService; |
| 13 | +import java.util.concurrent.Executors; |
| 14 | +import java.util.concurrent.atomic.AtomicInteger; |
| 15 | +import java.util.concurrent.atomic.AtomicLong; |
| 16 | +import org.junit.jupiter.api.Test; |
| 17 | +import software.amazon.smithy.java.retries.api.AcquireInitialTokenRequest; |
| 18 | +import software.amazon.smithy.java.retries.api.RecordSuccessRequest; |
| 19 | +import software.amazon.smithy.java.retries.api.RefreshRetryTokenRequest; |
| 20 | +import software.amazon.smithy.java.retries.api.RetryInfo; |
| 21 | +import software.amazon.smithy.java.retries.api.RetrySafety; |
| 22 | +import software.amazon.smithy.java.retries.api.TokenAcquisitionFailedException; |
| 23 | + |
| 24 | +class AdaptiveRetryStrategyIntegrationTest { |
| 25 | + private static final int THREAD_COUNT = 5; |
| 26 | + private static final int CALLS_PER_THREAD = 10; |
| 27 | + private static final long RATE_LIMIT_MS = 5; |
| 28 | + |
| 29 | + @Test |
| 30 | + void rateLimiterThrottlesClientsToServerRate() throws InterruptedException { |
| 31 | + var strategy = AdaptiveRetryStrategy.builder() |
| 32 | + .maxAttempts(10) |
| 33 | + .build(); |
| 34 | + var server = new RateLimitedServer(RATE_LIMIT_MS); |
| 35 | + var successCount = new AtomicInteger(0); |
| 36 | + var throttleCount = new AtomicInteger(0); |
| 37 | + var attemptCount = new AtomicInteger(0); |
| 38 | + var latch = new CountDownLatch(THREAD_COUNT); |
| 39 | + |
| 40 | + ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT); |
| 41 | + for (var i = 0; i < THREAD_COUNT; i++) { |
| 42 | + executor.submit(() -> { |
| 43 | + try { |
| 44 | + for (var c = 0; c < CALLS_PER_THREAD; c++) { |
| 45 | + executeWithRetry(strategy, server, successCount, throttleCount, attemptCount); |
| 46 | + } |
| 47 | + } finally { |
| 48 | + latch.countDown(); |
| 49 | + } |
| 50 | + }); |
| 51 | + } |
| 52 | + |
| 53 | + latch.await(); |
| 54 | + executor.shutdown(); |
| 55 | + |
| 56 | + var totalCalls = THREAD_COUNT * CALLS_PER_THREAD; |
| 57 | + // All calls should eventually succeed |
| 58 | + assertTrue(successCount.get() == totalCalls, |
| 59 | + "Expected " + totalCalls + " successes but got " + successCount.get()); |
| 60 | + // Some calls should have been throttled initially |
| 61 | + assertTrue(throttleCount.get() > 0, |
| 62 | + "Expected some throttling but got none"); |
| 63 | + // Success rate should be greater than 80% |
| 64 | + var totalAttempts = attemptCount.get(); |
| 65 | + var successRate = (double) successCount.get() / totalAttempts; |
| 66 | + assertTrue(successRate > 0.80, |
| 67 | + String.format("Expected success rate > 80%% but got %.1f%% (%d/%d)", |
| 68 | + successRate * 100, |
| 69 | + successCount.get(), |
| 70 | + totalAttempts)); |
| 71 | + } |
| 72 | + |
| 73 | + private void executeWithRetry( |
| 74 | + AdaptiveRetryStrategy strategy, |
| 75 | + RateLimitedServer server, |
| 76 | + AtomicInteger successCount, |
| 77 | + AtomicInteger throttleCount, |
| 78 | + AtomicInteger attemptCount |
| 79 | + ) { |
| 80 | + var acquireResponse = strategy.acquireInitialToken(new AcquireInitialTokenRequest("test-scope")); |
| 81 | + var token = acquireResponse.token(); |
| 82 | + sleep(acquireResponse.delay()); |
| 83 | + |
| 84 | + while (true) { |
| 85 | + try { |
| 86 | + attemptCount.incrementAndGet(); |
| 87 | + server.call(); |
| 88 | + strategy.recordSuccess(new RecordSuccessRequest(token)); |
| 89 | + successCount.incrementAndGet(); |
| 90 | + return; |
| 91 | + } catch (ServerThrottleException e) { |
| 92 | + throttleCount.incrementAndGet(); |
| 93 | + try { |
| 94 | + var refreshResponse = strategy.refreshRetryToken( |
| 95 | + new RefreshRetryTokenRequest(token, e, null)); |
| 96 | + token = refreshResponse.token(); |
| 97 | + sleep(refreshResponse.delay()); |
| 98 | + } catch (TokenAcquisitionFailedException ex) { |
| 99 | + // Retries exhausted, count as success anyway since we'll retry the outer loop |
| 100 | + // This shouldn't happen with maxAttempts=10 and adaptive backoff |
| 101 | + throw new AssertionError("Retries exhausted unexpectedly", ex); |
| 102 | + } |
| 103 | + } |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + private static void sleep(Duration delay) { |
| 108 | + if (delay.isZero()) { |
| 109 | + return; |
| 110 | + } |
| 111 | + try { |
| 112 | + Thread.sleep(delay.toMillis()); |
| 113 | + } catch (InterruptedException e) { |
| 114 | + Thread.currentThread().interrupt(); |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + /** |
| 119 | + * A simulated server that only allows one operation every {@code rateLimitMs} milliseconds. |
| 120 | + * Calls that arrive too fast are rejected with a {@link ServerThrottleException}. |
| 121 | + */ |
| 122 | + static class RateLimitedServer { |
| 123 | + private final long rateLimitMs; |
| 124 | + private final AtomicLong lastAllowedTime = new AtomicLong(0); |
| 125 | + |
| 126 | + RateLimitedServer(long rateLimitMs) { |
| 127 | + this.rateLimitMs = rateLimitMs; |
| 128 | + } |
| 129 | + |
| 130 | + void call() { |
| 131 | + var now = System.nanoTime() / 1_000_000; |
| 132 | + var last = lastAllowedTime.get(); |
| 133 | + if (now - last >= rateLimitMs && lastAllowedTime.compareAndSet(last, now)) { |
| 134 | + return; // success |
| 135 | + } |
| 136 | + throw new ServerThrottleException(); |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + static class ServerThrottleException extends RuntimeException implements RetryInfo { |
| 141 | + @Override |
| 142 | + public RetrySafety isRetrySafe() { |
| 143 | + return RetrySafety.YES; |
| 144 | + } |
| 145 | + |
| 146 | + @Override |
| 147 | + public boolean isThrottle() { |
| 148 | + return true; |
| 149 | + } |
| 150 | + |
| 151 | + @Override |
| 152 | + public Duration retryAfter() { |
| 153 | + return null; |
| 154 | + } |
| 155 | + } |
| 156 | +} |
0 commit comments