Skip to content

Commit 99382e0

Browse files
authored
Merge pull request #14 from Spoje-NET/feature/add-retry-mechanism
Add retry mechanism for cURL requests
2 parents 1cefd06 + b3dc467 commit 99382e0

1 file changed

Lines changed: 21 additions & 7 deletions

File tree

src/Discomp/ApiClient.php

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,11 @@ class ApiClient extends \Ease\Molecule
6868
*/
6969
private string $apiPassword;
7070

71+
/**
72+
* Discomp API Retry count on curl error.
73+
*/
74+
private int $retryCount = 10;
75+
7176
/**
7277
* May be huge response.
7378
*
@@ -91,6 +96,7 @@ public function __construct($username = '', $password = '')
9196
$this->apiUsername = \strlen($username) ? $username : \Ease\Shared::cfg('DISCOMP_USERNAME');
9297
$this->apiPassword = \strlen($password) ? $password : \Ease\Shared::cfg('DISCOMP_PASSWORD');
9398
$this->debug = strtolower((string) \Ease\Shared::cfg('DISCOMP_API_DEBUG', false)) === 'True';
99+
$this->retryCount = (int) \Ease\Shared::cfg('DISCOMP_RETRY', 10);
94100
$this->curlInit();
95101
$this->setObjectName();
96102
}
@@ -160,19 +166,27 @@ public function curlInit()
160166
public function doCurlRequest($url, $method = 'GET', $postParams = [])
161167
{
162168
curl_setopt($this->curl, \CURLOPT_URL, $url);
163-
164169
curl_setopt($this->curl, \CURLOPT_CUSTOMREQUEST, strtoupper($method));
165170

166-
$this->lastCurlResponse = curl_exec($this->curl);
167-
$this->curlInfo = curl_getinfo($this->curl);
168-
$this->curlInfo['when'] = microtime();
169-
$this->lastResponseCode = $this->curlInfo['http_code'];
170-
$this->lastCurlError = curl_error($this->curl);
171+
for ($try = 1; $try <= $this->retryCount; $try++) {
172+
$this->lastCurlResponse = curl_exec($this->curl);
173+
$this->curlInfo = curl_getinfo($this->curl);
174+
$this->curlInfo['when'] = microtime();
175+
$this->lastResponseCode = $this->curlInfo['http_code'];
176+
$this->lastCurlError = curl_error($this->curl);
177+
178+
if (\strlen($this->lastCurlError)) {
179+
$msg = sprintf('Curl Error (HTTP %d): %s', $this->lastResponseCode, $this->lastCurlError);
180+
$this->addStatusMessage(sprintf(_('Try %d/%d: %s'), $try, $this->retryCount, $msg), 'warning');
181+
sleep(60);
182+
} else {
183+
break; // No error, exit the loop
184+
}
185+
}
171186

172187
if (\strlen($this->lastCurlError)) {
173188
$msg = sprintf('Curl Error (HTTP %d): %s', $this->lastResponseCode, $this->lastCurlError);
174189
$this->addStatusMessage($msg, 'error');
175-
176190
if ($this->throwException) {
177191
throw new \Ease\Exception($msg, $this->lastResponseCode);
178192
}

0 commit comments

Comments
 (0)