Skip to content

Commit

Permalink
Add retry middleware on asset upload
Browse files Browse the repository at this point in the history
  • Loading branch information
joedixon committed Oct 31, 2022
1 parent ac6be7d commit 71208bb
Showing 1 changed file with 36 additions and 4 deletions.
40 changes: 36 additions & 4 deletions src/Aws/AwsStorageProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,25 @@
namespace Laravel\VaporCli\Aws;

use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Request;
use Illuminate\Support\LazyCollection;
use Illuminate\Support\Str;
use Laravel\VaporCli\ConsoleVaporClient;
use Laravel\VaporCli\Exceptions\RequestFailedException;
use Laravel\VaporCli\Helpers;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\Console\Helper\ProgressBar;

class AwsStorageProvider
{
protected $vapor;

const MAX_RETRIES = 3;

/**
* Create a new storage provider instance.
*
Expand Down Expand Up @@ -55,8 +62,8 @@ public function store($url, array $headers, $file, $withProgress = false)
: null;

$response = (new Client())->request('PUT', $url, array_filter([
'body' => $stream,
'headers' => empty($headers) ? null : $headers,
'body' => $stream,
'headers' => empty($headers) ? null : $headers,
'progress' => $progressCallback,
]));

Expand Down Expand Up @@ -119,7 +126,7 @@ public function executeStoreRequests($requests, $assetPath, $callback)
}
};

(new Pool(new Client(), $generator(), [
(new Pool(new Client(['handler' => $this->retryHandler()]), $generator(), [
'concurrency' => 10,
'rejected' => function ($reason, $index) {
throw new RequestFailedException($reason->getMessage(), $index);
Expand Down Expand Up @@ -158,7 +165,7 @@ public function executeCopyRequests($requests, $callback)
}
};

(new Pool(new Client(), $generator(), [
(new Pool(new Client(['handler' => $this->retryHandler()]), $generator(), [
'concurrency' => 10,
'rejected' => function ($reason, $index) {
throw new RequestFailedException($reason->getMessage(), $index);
Expand All @@ -167,4 +174,29 @@ public function executeCopyRequests($requests, $callback)
->promise()
->wait();
}

/**
* Get a handler stack containing the retry middleware configuration.
*
* @return \GuzzleHttp\HandlerStack
*/
private function retryHandler()
{
$stack = HandlerStack::create();
$stack->push(Middleware::retry(function (int $retries, RequestInterface $request, ResponseInterface $response = null) {
if ($retries === 0) {
return true;
}

if ($response && $response->getStatusCode() < 300) {
return false;
}

Helpers::step('<comment>Retrying Request: </comment><options=bold>'.$request->getMethod().'</> '.Str::before($request->getUri(), '?'));

return $retries < self::MAX_RETRIES;
}));

return $stack;
}
}

0 comments on commit 71208bb

Please sign in to comment.