Adding validation in ExponentialBackoffPolicy to prevent overflows

Signed-off-by: Max Lambrecht <maxlambrecht@gmail.com>
This commit is contained in:
Max Lambrecht 2020-07-01 09:51:21 -03:00
parent 7b61cb8c47
commit 9e592c1d36
2 changed files with 23 additions and 4 deletions

View File

@ -62,11 +62,11 @@ public class ExponentialBackoffPolicy {
* @return a {@link Duration} representing the next delay * @return a {@link Duration} representing the next delay
*/ */
public Duration nextDelay(final Duration currentDelay) { public Duration nextDelay(final Duration currentDelay) {
val next = backoffFunction.apply(currentDelay); // current delay didn't exceed maxDelay already
if (next.compareTo(maxDelay) > 0) { if (currentDelay.compareTo(maxDelay) < 0) {
return maxDelay; return calculateNextDelay(currentDelay);
} }
return next; return maxDelay;
} }
/** /**
@ -79,4 +79,12 @@ public class ExponentialBackoffPolicy {
public boolean reachedMaxRetries(final int retriesCount) { public boolean reachedMaxRetries(final int retriesCount) {
return maxRetries != UNLIMITED_RETRIES && retriesCount >= maxRetries; return maxRetries != UNLIMITED_RETRIES && retriesCount >= maxRetries;
} }
private Duration calculateNextDelay(final Duration currentDelay) {
val next = backoffFunction.apply(currentDelay);
if (next.compareTo(maxDelay) > 0) {
return maxDelay;
}
return next;
}
} }

View File

@ -27,6 +27,17 @@ class ExponentialBackoffPolicyTest {
assertEquals(Duration.ofSeconds(60), exponentialBackoffPolicy.nextDelay(Duration.ofSeconds(50))); assertEquals(Duration.ofSeconds(60), exponentialBackoffPolicy.nextDelay(Duration.ofSeconds(50)));
} }
@Test
void testNextDelayDefaultPolicy_currentDelayExceedsMaxDelay_returnsMaxDelay() {
ExponentialBackoffPolicy exponentialBackoffPolicy = ExponentialBackoffPolicy
.builder()
.initialDelay(Duration.ofSeconds(1))
.maxDelay(Duration.ofSeconds(60))
.build();
assertEquals(Duration.ofSeconds(60), exponentialBackoffPolicy.nextDelay(Duration.ofSeconds(70)));
}
@Test @Test
void testNextDelayCustomPolicy() { void testNextDelayCustomPolicy() {
ExponentialBackoffPolicy exponentialBackoffPolicy = ExponentialBackoffPolicy ExponentialBackoffPolicy exponentialBackoffPolicy = ExponentialBackoffPolicy