Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add exponential retry mechanism #59

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
"require": {
"php": "^7.2|^8.0",
"ext-json": "*",
"guzzlehttp/guzzle": "^6.5.7|^7.4.4"
"guzzlehttp/guzzle": "^6.5.7|^7.4.4",
"ramsey/uuid": "3.9.7"
},
"require-dev": {
"pestphp/pest": "^1.20.0",
Expand Down
196 changes: 147 additions & 49 deletions src/MakeHttpRequests.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@

namespace Novu\SDK;

use Closure;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Novu\SDK\Exceptions\FailedAction;
use Novu\SDK\Exceptions\NotFound;
use Novu\SDK\Exceptions\RateLimitExceeded;
use Novu\SDK\Exceptions\Timeout;
use Novu\SDK\Exceptions\ValidationFailed;
use Psr\Http\Message\ResponseInterface;

Expand Down Expand Up @@ -72,16 +73,7 @@ public function delete($uri, array $payload = [])
return $this->request('DELETE', $uri, $payload);
}

/**
* Make request to Novu servers and return the response.
*
* @param string $verb
* @param string $uri
* @param array $payload
* @param array $query
* @return mixed
*/
protected function request($verb, $uri, array $payload = [], array $query = [])
protected function populateRequestPayload(array $payload = [], array $query = [])
{
if (isset($payload['json'])) {
$payload = ['json' => $payload['json']];
Expand All @@ -93,90 +85,196 @@ protected function request($verb, $uri, array $payload = [], array $query = [])
$payload = array_merge($payload, ['query' => $query]);
}

$response = $this->client->request($verb, $uri, $payload);
return $payload;
}

/**
* Make request to Novu servers and return the response.
*
* @param string $method
* @param string $uri
* @param array $payload
* @param array $query
* @return mixed
* @throws GuzzleException|Exception
*/
protected function request($method, $uri, array $payload = [], array $query = [])
{
$payload = $this->populateRequestPayload($payload, $query);

$shouldRetry = null;

return $this->retry($this->retryConfig->retryMax ?? 1, function ($attempt) use ($method, $uri, $payload, &$shouldRetry) {
$response = $this->buildClient()->request($method, $uri, $payload);

$statusCode = $response->getStatusCode();

$isSucessful = $statusCode >= 200 && $statusCode < 300;

if (! $isSucessful) {
$e = $this->handleRequestError($response);

try {
$shouldRetry = is_callable($this->retryConfig->retryCondition)
? call_user_func($this->retryConfig->retryCondition, $e)
: $this->getDefaultRetryCondition($e);
} catch (Exception $exception) {
$shouldRetry = false;

throw $exception;
}

if ((! empty ($retries = $this->retryConfig->retryMax) && $attempt < $retries) && $shouldRetry) {
throw $e;
}

throw $e;
}

$responseBody = (string) $response->getBody();

return json_decode($responseBody, true) ?: $responseBody;

}, $this->determineBackoff(), function ($exception) use (&$shouldRetry) {
$result = $shouldRetry ??
(is_callable($this->retryConfig->retryCondition)
? call_user_func($this->retryConfig->retryCondition, $exception)
: $this->getDefaultRetryCondition($exception));

$shouldRetry = null;

return $result;
});
}

/**
* Calculate the time delay for the next request.
*
* @return \Closure
*/
protected function determineBackoff()
{
$minDelay = $this->retryConfig->waitMin ?? 1;
$maxDelay = $this->retryConfig->waitMax ?? 30;
$initialDelay = $this->retryConfig->initialDelay ?? $minDelay;

return function ($attempt) use ($minDelay, $maxDelay, $initialDelay) {
if ($attempt === 1) {
return $initialDelay;
}

$statusCode = $response->getStatusCode();
$delay = $attempt * $minDelay;
if ($delay > $maxDelay) {
return $maxDelay;
}

return $delay;
};
}

if ($statusCode < 200 || $statusCode > 299) {
return $this->handleRequestError($response);
/**
* Get default retry condition callback
*
* @param Exception $exception
* @return bool
*/
protected function getDefaultRetryCondition($exception)
{
if ($exception->getCode() >= 500 && $exception->getCode() <= 599) {
return true;
}

$responseBody = (string) $response->getBody();
if (in_array($exception->getCode(), [408, 429, 422])) {
return true;
}

return json_decode($responseBody, true) ?: $responseBody;
return false;
}

/**
* Handle the request error.
*
* @param \Psr\Http\Message\ResponseInterface $response
* @return void
*
* @throws \Exception
* @throws \Novu\SDK\Exceptions\FailedAction
* @throws \Novu\SDK\Exceptions\NotFound
* @throws \Novu\SDK\Exceptions\Validation
* @throws \Novu\SDK\Exceptions\RateLimitExceeded
* @return mixed
*/
protected function handleRequestError(ResponseInterface $response)
{
if ($response->getStatusCode() == 422) {
throw new ValidationFailed(json_decode((string) $response->getBody(), true));
return new ValidationFailed(json_decode((string) $response->getBody(), true));
}

if ($response->getStatusCode() == 404) {
throw new NotFound();
return new NotFound();
}

if ($response->getStatusCode() == 400) {
throw new FailedAction((string) $response->getBody());
return new FailedAction((string) $response->getBody());
}

if ($response->getStatusCode() === 429) {
throw new RateLimitExceeded(
return new RateLimitExceeded(
$response->hasHeader('x-ratelimit-reset')
? (int) $response->getHeader('x-ratelimit-reset')[0]
: null
);
}

throw new Exception((string) $response->getBody());
return new Exception((string) $response->getBody());
}

/**
* Retry the callback or fail after x seconds.
* Retry an operation a given number of times.
*
* @param int $timeout
* @param int|array $times
* @param callable $callback
* @param int $sleep
* @param int|\Closure $sleepMilliseconds
* @param callable|null $when
* @return mixed
*
* @throws \Novu\SDK\Exceptions\Timeout
* @throws \Exception
*/
public function retry($timeout, $callback, $sleep = 5)
public function retry($times, callable $callback, $sleepMilliseconds = 0, $when = null)
{
$start = time();
$attempts = 0;

beginning:
$backoff = [];

if ($output = $callback()) {
return $output;
if (is_array($times)) {
$backoff = $times;

$times = count($times) + 1;
}

if (time() - $start < $timeout) {
sleep($sleep);
beginning:
$attempts++;
$times--;

try {
return $callback($attempts);
} catch (Exception $e) {
if ($times < 1 || ($when && ! $when($e))) {
throw $e;
}

goto beginning;
}
$sleepMilliseconds = $backoff[$attempts - 1] ?? $sleepMilliseconds;

if ($output === null || $output === false) {
$output = [];
}
if ($sleepMilliseconds) {
usleep($this->value($sleepMilliseconds, $attempts, $e) * 1000);
}

if (! is_array($output)) {
$output = [$output];
goto beginning;
}
}

throw new Timeout($output);
/**
* Return the default value of the given value.
*
* @param mixed $value
* @param mixed ...$args
* @return mixed
*/
private function value($value, ...$args)
{
return $value instanceof Closure ? $value(...$args) : $value;
}
}
}
Loading
Loading