From 9e592c1d3639c79faa9eba26788de64de5916e4c Mon Sep 17 00:00:00 2001 From: Max Lambrecht Date: Wed, 1 Jul 2020 09:51:21 -0300 Subject: [PATCH] Adding validation in ExponentialBackoffPolicy to prevent overflows Signed-off-by: Max Lambrecht --- .../retry/ExponentialBackoffPolicy.java | 16 ++++++++++++---- .../retry/ExponentialBackoffPolicyTest.java | 11 +++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/java-spiffe-core/src/main/java/io/spiffe/workloadapi/retry/ExponentialBackoffPolicy.java b/java-spiffe-core/src/main/java/io/spiffe/workloadapi/retry/ExponentialBackoffPolicy.java index f3f4e3b..8c13b6a 100644 --- a/java-spiffe-core/src/main/java/io/spiffe/workloadapi/retry/ExponentialBackoffPolicy.java +++ b/java-spiffe-core/src/main/java/io/spiffe/workloadapi/retry/ExponentialBackoffPolicy.java @@ -62,11 +62,11 @@ public class ExponentialBackoffPolicy { * @return a {@link Duration} representing the next delay */ public Duration nextDelay(final Duration currentDelay) { - val next = backoffFunction.apply(currentDelay); - if (next.compareTo(maxDelay) > 0) { - return maxDelay; + // current delay didn't exceed maxDelay already + if (currentDelay.compareTo(maxDelay) < 0) { + return calculateNextDelay(currentDelay); } - return next; + return maxDelay; } /** @@ -79,4 +79,12 @@ public class ExponentialBackoffPolicy { public boolean reachedMaxRetries(final int retriesCount) { 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; + } } diff --git a/java-spiffe-core/src/test/java/io/spiffe/workloadapi/retry/ExponentialBackoffPolicyTest.java b/java-spiffe-core/src/test/java/io/spiffe/workloadapi/retry/ExponentialBackoffPolicyTest.java index cb15b3e..0de2029 100644 --- a/java-spiffe-core/src/test/java/io/spiffe/workloadapi/retry/ExponentialBackoffPolicyTest.java +++ b/java-spiffe-core/src/test/java/io/spiffe/workloadapi/retry/ExponentialBackoffPolicyTest.java @@ -27,6 +27,17 @@ class ExponentialBackoffPolicyTest { 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 void testNextDelayCustomPolicy() { ExponentialBackoffPolicy exponentialBackoffPolicy = ExponentialBackoffPolicy