Skip to content

Commit 08248be

Browse files
committed
Added test
1 parent e841cbc commit 08248be

File tree

3 files changed

+32
-10
lines changed

3 files changed

+32
-10
lines changed

src/Traits/Connector/SendsRequests.php

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,10 @@ public function send(Request $request, MockClient $mockClient = null, callable $
5454
// the interval (if it has been provided)
5555

5656
if ($attempts > 1) {
57-
$sleepTime = $useExponentialBackoff
58-
? $retryInterval * (2 ** ($attempts - 1)) * 1000
59-
: $retryInterval * 1000;
57+
$sleepTime = $useExponentialBackoff
58+
? $retryInterval * (2 ** ($attempts - 2)) * 1000
59+
: $retryInterval * 1000;
60+
6061
usleep($sleepTime);
6162
}
6263

src/Traits/RequestProperties/HasTries.php

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,13 @@ trait HasTries
2626
*/
2727
public ?int $retryInterval = null;
2828

29+
/**
30+
* Should Saloon use exponential backoff during retries?
31+
*
32+
* When true, Saloon will double the retry interval after each attempt.
33+
*/
34+
public bool $useExponentialBackoff = false;
35+
2936
/**
3037
* Should Saloon throw an exception after exhausting the maximum number of retries?
3138
*
@@ -35,13 +42,6 @@ trait HasTries
3542
*/
3643
public ?bool $throwOnMaxTries = null;
3744

38-
/**
39-
* Should Saloon use exponential backoff during retries?
40-
*
41-
* When true, Saloon will double the retry interval after each attempt.
42-
*/
43-
public bool $useExponentialBackoff = false;
44-
4545
/**
4646
* Define whether the request should be retried.
4747
*

tests/Feature/SendAndRetryTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,27 @@
108108
expect(round(microtime(true) - $start))->toBeGreaterThanOrEqual(2);
109109
});
110110

111+
test('a failed request can have an interval with exponential backoff between each attempt', function () {
112+
$mockClient = new MockClient([
113+
MockResponse::make(['name' => 'Sam'], 500), // 1,000
114+
MockResponse::make(['name' => 'Gareth'], 500), // 2,000
115+
MockResponse::make(['name' => 'Michael'], 500), // 4,000
116+
MockResponse::make(['name' => 'Teodor'], 200),
117+
]);
118+
119+
$connector = new TestConnector;
120+
$connector->withMockClient($mockClient);
121+
122+
$start = microtime(true);
123+
124+
$connector->sendAndRetry(new UserRequest, 4, 1000, useExponentialBackoff: true);
125+
126+
// It should be a duration of > 7000ms (7 seconds) because the there are four requests
127+
// after the first.
128+
129+
expect(round(microtime(true) - $start))->toBeGreaterThanOrEqual(7);
130+
});
131+
111132
test('an exception other than a request exception will not be retried', function () {
112133
$mockClient = new MockClient([
113134
MockResponse::make(['name' => 'Sam'], 500),

0 commit comments

Comments
 (0)