-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #4 from sagacorp/add-retry-request
Add retry request
- Loading branch information
Showing
4 changed files
with
158 additions
and
79 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
<?php | ||
|
||
namespace sagacorp\queue\azure\service; | ||
|
||
use yii\httpclient\Exception as HttpClientException; | ||
|
||
class Request extends \yii\httpclient\Request | ||
{ | ||
// region Public Properties | ||
public int $maxRetries; | ||
// endregion Public Properties | ||
|
||
// region Protected Properties | ||
protected int $attempts = 0; | ||
// endregion Protected Properties | ||
|
||
// region Public Methods | ||
/** | ||
* @throws HttpClientException | ||
*/ | ||
public function sendAndRetryOnFailure(array $successStatusCodes): \yii\httpclient\Response | ||
{ | ||
try { | ||
$response = $this->send(); | ||
|
||
if (!in_array($response->statusCode, $successStatusCodes, true)) { | ||
throw new HttpClientException($response->toString()); | ||
} | ||
} catch (HttpClientException $e) { | ||
\Yii::error($e); | ||
|
||
if (!$this->canContinue($this->attempts)) { | ||
throw $e; | ||
} | ||
|
||
$delay = $this->getRetryDelay($this->attempts); | ||
|
||
\Yii::error('Retry request in ' . $delay . ' seconds'); | ||
sleep($delay); | ||
|
||
++$this->attempts; | ||
|
||
$response = $this->sendAndRetryOnFailure($successStatusCodes); | ||
} | ||
|
||
return $response; | ||
} | ||
|
||
// endregion Public Methods | ||
|
||
// region Protected Methods | ||
protected function canContinue(int $attempts): bool | ||
{ | ||
return $attempts < $this->maxRetries; | ||
} | ||
|
||
protected function getRetryDelay(int $attempts): int | ||
{ | ||
return 4 ** $attempts; | ||
} | ||
// endregion Protected Methods | ||
} |
Oops, something went wrong.