Skip to content
This repository has been archived by the owner on Feb 6, 2025. It is now read-only.

Commit

Permalink
Merge pull request #52 from DBX12/retry-connection
Browse files Browse the repository at this point in the history
Retry connection
  • Loading branch information
marcus-campos authored Nov 1, 2017
2 parents fbf4703 + 66bdb0b commit 8591245
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/Rest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,13 @@
namespace Maestro;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Handler\CurlMultiHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Maestro\Cache\Cache;
use Maestro\Exceptions\NoMethodException;
use Maestro\Exceptions\NoUrlException;
Expand Down Expand Up @@ -40,6 +44,11 @@ class Rest
*/
private $client;

/**
* @var int how many times should we retry before we give up
*/
const MAX_RETRIES = 5;

/**
* {string} The response body as a string to make it cachable.
*/
Expand Down Expand Up @@ -198,6 +207,7 @@ public function sendAsync()
{
$curl = new CurlMultiHandler();
$handler = HandlerStack::create($curl);
$handler->push(Middleware::retry(self::getRetryDecider()));
$this->setClient(new Client(['handler' => $handler]));

$request = $this->newRequest();
Expand Down Expand Up @@ -265,4 +275,38 @@ public function assoc()

return $this;
}

private static function getRetryDecider()
{
return function (
$retries,
Request $request,
Response $response = null,
RequestException $exception = null
) {
$returnValue = null;
// if we failed more than MAX_RETRIES times, we give up
if ($retries >= self::MAX_RETRIES) {
$returnValue = false;
}

// if we failed to establish a connection, we retry
if ($exception instanceof ConnectException && $returnValue === null) {
$returnValue = true;
}

if ($response && $returnValue === null) {
// if there was an server error, we retry
if ($response->getStatusCode() >= 500) {
$returnValue = true;
}
}
if ($returnValue === null) {
// nothing did help, finally give up
$returnValue = false;
}

return $returnValue;
};
}
}

0 comments on commit 8591245

Please sign in to comment.