Skip to content

Commit 5a07814

Browse files
committed
add pause between requests to avoid a 503 response
1 parent 8ec7343 commit 5a07814

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"name": "ryancwalsh/stack-exchange-backup-laravel",
33
"description": "My aim is to back up all of my questions and answers and anything else valuable in my accounts across all of the StackExchange sites (StackOverflow, SuperUser, https://apple.stackexchange.com/, https://askubuntu.com/, etc).",
44
"type": "package",
5-
"version": "2.0.3",
5+
"version": "2.0.4",
66
"require": {
77
"guzzlehttp/guzzle": "^6.3",
88
"php": "^7.3",

src/ExportStackExchangeHelper.php

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ class ExportStackExchangeHelper {
1515
const APP_FOLDER = 'app/';
1616
const SE_FOLDER = 'StackExchange/';
1717
const DOT_ZIP = '.zip';
18+
const PAUSE_BETWEEN_REQUESTS_MS = 200;
1819

1920
protected $client_id;
2021
protected $client_secret;
@@ -114,7 +115,17 @@ public function get($uri = '', array $options = [], $cacheMinutes = self::SESSIO
114115
//Log::debug($fullUrl);
115116
$httpClient = new HttpClient();
116117
$response = $httpClient->request('get', $fullUrl);
117-
return $response->getBody()->getContents();
118+
$responseContentsJson = $response->getBody()->getContents();
119+
$responseArr = json_decode($responseContentsJson, true);
120+
Log::debug('quota_remaining=' . $responseArr['quota_remaining']); //https://stackapps.com/a/7832/55248
121+
$backoff = $responseArr['backoff'] ?? 0;
122+
if ($backoff) {
123+
Log::warning('Rate-limiting because backoff=' . $backoff . ' for ' . $uri);
124+
sleep($backoff); //ONEDAY: Figure out a better approach since `sleep` is highly discouraged. See https://github.com/ryancwalsh/StackExchangeBackupLaravelPHP/issues/11
125+
} else {
126+
usleep(self::PAUSE_BETWEEN_REQUESTS_MS * 1000); //preemptively rate-limiting the requests so that the API does not throw a 503 response. https://github.com/ryancwalsh/StackExchangeBackupLaravelPHP/issues/11
127+
}
128+
return $responseContentsJson;
118129
});
119130
return $response;
120131
}

0 commit comments

Comments
 (0)