Skip to content

Commit 2927eeb

Browse files
committed
Fix calculation of sleeping time in surveyhero HTTP client
1 parent 8da81cf commit 2927eeb

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

src/Http/SurveyheroClient.php

+8-6
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,14 @@
33
namespace Statikbe\Surveyhero\Http;
44

55
use Carbon\Carbon;
6+
use Illuminate\Support\Facades\Cache;
67
use Illuminate\Support\Facades\Http;
78
use stdClass;
89

910
class SurveyheroClient
1011
{
1112
const CACHE_LATEST_REQUEST_TIME_KEY = 'latest-surveyhero-api-request-time';
1213

13-
const REQUEST_RATE_LIMIT_WAIT_TIME = 60000;
14-
1514
public function getSurveys(): array
1615
{
1716
$responsesData = $this->fetchFromSurveyHero('surveys');
@@ -120,7 +119,7 @@ private function fetchFromSurveyHero(string $urlPath, array $queryStringArgs = [
120119
{
121120
$this->preventThrottle();
122121

123-
$response = Http::retry(3, 600)
122+
$response = Http::retry(3, 800)
124123
->withBasicAuth(config('surveyhero.api_username'), config('surveyhero.api_password'))
125124
->get(config('surveyhero.api_url').$urlPath, $queryStringArgs);
126125

@@ -176,14 +175,17 @@ private function deleteFromSurveyHero(string $urlPath, array $queryStringArgs =
176175
//Ensure sleep between requests
177176
private function preventThrottle(): void
178177
{
179-
if (cache(self::CACHE_LATEST_REQUEST_TIME_KEY)) {
180-
usleep(self::REQUEST_RATE_LIMIT_WAIT_TIME);
178+
if (Cache::has(self::CACHE_LATEST_REQUEST_TIME_KEY)) {
179+
//usleep is in microseconds, 1000000 is 1s.
180+
//Surveyhero only allows 2 requests per second.
181+
$sleepTime = 1000000 - (Carbon::now()->getTimestampMs() - Cache::get(self::CACHE_LATEST_REQUEST_TIME_KEY)) * 1000;
182+
usleep($sleepTime);
181183
}
182184
}
183185

184186
//Set latest request time with 1s TTL
185187
private function updateThrottle(): void
186188
{
187-
cache([self::CACHE_LATEST_REQUEST_TIME_KEY => now()->format('Y-m-d H:i:s.u')], 1);
189+
Cache::put(self::CACHE_LATEST_REQUEST_TIME_KEY, Carbon::now()->getTimestampMs(), 1);
188190
}
189191
}

0 commit comments

Comments
 (0)