Skip to content

Commit 9495b28

Browse files
committed
add retry support
1 parent 1c0b904 commit 9495b28

File tree

1 file changed

+49
-14
lines changed

1 file changed

+49
-14
lines changed

src/Illuminate/Http/Client/PendingRequest.php

Lines changed: 49 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,20 @@ class PendingRequest
5050
*/
5151
protected $options = [];
5252

53+
/**
54+
* The number of times to try the request.
55+
*
56+
* @var int
57+
*/
58+
protected $tries = 1;
59+
60+
/**
61+
* The number of milliseconds to wait between retries.
62+
*
63+
* @var int
64+
*/
65+
protected $retryDelay = 100;
66+
5367
/**
5468
* The callbacks that should execute before the request is sent.
5569
*
@@ -300,6 +314,21 @@ public function timeout(int $seconds)
300314
});
301315
}
302316

317+
/**
318+
* Specify the number of times the request should be attempted.
319+
*
320+
* @param int $times
321+
* @param int $sleep
322+
* @return $this
323+
*/
324+
public function retry(int $times, int $sleep = 0)
325+
{
326+
$this->tries = $times;
327+
$this->retryDelay = $sleep;
328+
329+
return $this;
330+
}
331+
303332
/**
304333
* Merge new options into the client.
305334
*
@@ -414,20 +443,26 @@ public function send(string $method, string $url, array $options = [])
414443

415444
$this->pendingFiles = [];
416445

417-
try {
418-
return tap(new Response($this->buildClient()->request($method, $url, $this->mergeOptions([
419-
'laravel_data' => $options[$this->bodyFormat] ?? [],
420-
'query' => $this->parseQueryParams($url),
421-
'on_stats' => function ($transferStats) {
422-
$this->transferStats = $transferStats;
423-
},
424-
], $options))), function ($response) {
425-
$response->cookies = $this->cookies;
426-
$response->transferStats = $this->transferStats;
427-
});
428-
} catch (\GuzzleHttp\Exception\ConnectException $e) {
429-
throw new ConnectionException($e->getMessage(), 0, $e);
430-
}
446+
return retry($this->tries ?? 1, function () use ($method, $url, $options) {
447+
try {
448+
return tap(new Response($this->buildClient()->request($method, $url, $this->mergeOptions([
449+
'laravel_data' => $options[$this->bodyFormat] ?? [],
450+
'query' => $this->parseQueryParams($url),
451+
'on_stats' => function ($transferStats) {
452+
$this->transferStats = $transferStats;
453+
},
454+
], $options))), function ($response) {
455+
$response->cookies = $this->cookies;
456+
$response->transferStats = $this->transferStats;
457+
458+
if ($this->tries > 1 && ! $response->successful()) {
459+
$response->throw();
460+
}
461+
});
462+
} catch (\GuzzleHttp\Exception\ConnectException $e) {
463+
throw new ConnectionException($e->getMessage(), 0, $e);
464+
}
465+
}, $this->retryDelay ?? 100);
431466
}
432467

433468
/**

0 commit comments

Comments
 (0)