From c5f22c8e437cb46c95f5f2e5e95120358325cdc6 Mon Sep 17 00:00:00 2001 From: Robertbaelde Date: Mon, 13 May 2024 21:13:59 +0200 Subject: [PATCH 1/2] Add failing test --- src/ExponentialBackOffStrategyTest.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/ExponentialBackOffStrategyTest.php b/src/ExponentialBackOffStrategyTest.php index 5ee82a8..4b79017 100644 --- a/src/ExponentialBackOffStrategyTest.php +++ b/src/ExponentialBackOffStrategyTest.php @@ -148,4 +148,11 @@ public function it_does_not_throw_an_exception_when_max_tries_is_infinite(): voi $backoff->backOff(PHP_INT_MAX, $exception); } + + /** @test */ + public function it_does_not_throw_exception_when_sleep_time_overflows_and_instead_respects_the_max_sleep_time() + { + $backoff = new ExponentialBackOffStrategy(50, 10000, 5000); + $backoff->backOff(60, new RuntimeException('oops')); + } } From dd93c1d81d3120ddc07a46c906390bc027ff9af8 Mon Sep 17 00:00:00 2001 From: Robertbaelde Date: Mon, 13 May 2024 21:15:50 +0200 Subject: [PATCH 2/2] Fix overflow --- src/ExponentialBackOffStrategy.php | 3 +++ src/ExponentialBackOffStrategyTest.php | 4 +++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/ExponentialBackOffStrategy.php b/src/ExponentialBackOffStrategy.php index c7652f3..2a30342 100644 --- a/src/ExponentialBackOffStrategy.php +++ b/src/ExponentialBackOffStrategy.php @@ -50,6 +50,9 @@ public function backOff(int $tries, Throwable $throwable): void } $delay = (int) ($this->initialDelayMs * $this->base ** ($tries - 1)); + if($delay < 0){ + $delay = $this->maxDelay; + } $delay = min($this->maxDelay, $delay); $delay = $this->jitter->jitter($delay); diff --git a/src/ExponentialBackOffStrategyTest.php b/src/ExponentialBackOffStrategyTest.php index 4b79017..9a32d29 100644 --- a/src/ExponentialBackOffStrategyTest.php +++ b/src/ExponentialBackOffStrategyTest.php @@ -152,7 +152,9 @@ public function it_does_not_throw_an_exception_when_max_tries_is_infinite(): voi /** @test */ public function it_does_not_throw_exception_when_sleep_time_overflows_and_instead_respects_the_max_sleep_time() { - $backoff = new ExponentialBackOffStrategy(50, 10000, 5000); + $backoff = new ExponentialBackOffStrategy(50, 10000, 5000, 2.0, $this->sleeper); $backoff->backOff(60, new RuntimeException('oops')); + + self::assertEquals(5000, $this->recordedSleep); } }