Commit 973a500a authored by Björn Hjortsten's avatar Björn Hjortsten

Changed a constant sleep to retries with back off

When creating Images, the API sometimes returns 404 if calling get() to fast. Solved this by retrying the get() with exponential back off.
parent b0c375c3
......@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace QBNK\TemplafyApi\Controller;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\TransferException;
use QBNK\TemplafyApi\Model\Image;
use QBNK\TemplafyApi\Model\ImageResponse;
......@@ -61,8 +62,9 @@ class ImageController extends BaseController {
}
$assetUrl = $response->getHeader('Location')[0];
$imageId = str_replace('https://api-v1.templafy.com/images/', '', $assetUrl);
sleep(1); // Do not fetch to early as we get a 404
return $this->get($imageId);
// Sometimes the API doesn't realize the image we just uploaded exists. Retry up to 5 times.
return $this->retryGuzzle(5, function() use ($imageId) { return $this->get($imageId); });
}
public function get(string $id): ImageResponse {
......@@ -87,4 +89,27 @@ class ImageController extends BaseController {
public function delete(string $id): void {
$this->apiHttpClient->delete('/images/'.$id);
}
/**
* Retries $fn up to $retries times with exponential back off when 4xx responses are returned.
* @param int $retries
* @param callable $fn
* @throws ClientException Thrown when $retries attempts has been made. Is the last real ClientException.
* @return mixed The return value from $fn
*/
protected function retryGuzzle(int $retries, callable $fn) {
$attempts = 1;
beginning:
try {
return $fn();
} catch (ClientException $ce) {
if (!$retries) {
throw $ce;
}
$retries--;
sleep(2 ** $attempts); // Exponential back off
$attempts++;
goto beginning;
}
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment