diff --git a/HTTP/async_http.cpp b/HTTP/async_http.cpp index 9f1d0c2..cb22000 100644 --- a/HTTP/async_http.cpp +++ b/HTTP/async_http.cpp @@ -6,6 +6,7 @@ #include "async_http.h" #include "DelegateMQ.h" #include +#include #include #include #include @@ -112,25 +113,13 @@ namespace async { HttpResponse resp; if (!m_curl) { resp.error = "Not initialized"; return resp; } - std::string body; curl_easy_reset(m_curl); curl_easy_setopt(m_curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(m_curl, CURLOPT_HTTPGET, 1L); curl_easy_setopt(m_curl, CURLOPT_WRITEFUNCTION, WriteCallback); - curl_easy_setopt(m_curl, CURLOPT_WRITEDATA, &body); curl_easy_setopt(m_curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(m_curl, CURLOPT_TIMEOUT, 10L); - - CURLcode res = curl_easy_perform(m_curl); - if (res != CURLE_OK) { - resp.error = curl_easy_strerror(res); - } else { - long code = 0; - curl_easy_getinfo(m_curl, CURLINFO_RESPONSE_CODE, &code); - resp.statusCode = static_cast(code); - resp.body = std::move(body); - } - return resp; + return Perform(); } HttpResponse AsyncHttp::HttpPost(const std::string& url, @@ -140,7 +129,6 @@ namespace async { HttpResponse resp; if (!m_curl) { resp.error = "Not initialized"; return resp; } - std::string respBody; struct curl_slist* headers = nullptr; std::string ctHeader = "Content-Type: " + contentType; headers = curl_slist_append(headers, ctHeader.c_str()); @@ -152,22 +140,52 @@ namespace async { curl_easy_setopt(m_curl, CURLOPT_POSTFIELDSIZE, static_cast(body.size())); curl_easy_setopt(m_curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(m_curl, CURLOPT_WRITEFUNCTION, WriteCallback); - curl_easy_setopt(m_curl, CURLOPT_WRITEDATA, &respBody); curl_easy_setopt(m_curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(m_curl, CURLOPT_TIMEOUT, 10L); - CURLcode res = curl_easy_perform(m_curl); + resp = Perform(); curl_slist_free_all(headers); + return resp; + } - if (res != CURLE_OK) { - resp.error = curl_easy_strerror(res); - } else { + HttpResponse AsyncHttp::Perform() + { + for (int attempt = 0; ; ++attempt) { + HttpResponse resp; + std::string body; + curl_easy_setopt(m_curl, CURLOPT_WRITEDATA, &body); + + CURLcode res = curl_easy_perform(m_curl); + if (res != CURLE_OK) { + resp.error = curl_easy_strerror(res); + return resp; + } long code = 0; curl_easy_getinfo(m_curl, CURLINFO_RESPONSE_CODE, &code); resp.statusCode = static_cast(code); - resp.body = std::move(respBody); + resp.body = std::move(body); + + if (code != 429 || attempt >= m_maxRetries.load()) + return resp; + + // Rate limited: wait, then send the same request again + std::chrono::milliseconds wait(m_retryDelayMs.load()); +#if LIBCURL_VERSION_NUM >= 0x074200 // CURLINFO_RETRY_AFTER: libcurl 7.66.0 + curl_off_t retryAfter = 0; // seconds; 0 if the server sent none + if (curl_easy_getinfo(m_curl, CURLINFO_RETRY_AFTER, &retryAfter) == CURLE_OK && + retryAfter > 0) + wait = std::min( + std::chrono::seconds(retryAfter), MAX_RETRY_AFTER); +#endif + std::this_thread::sleep_for(wait); } - return resp; + } + + void AsyncHttp::SetRateLimitRetry(int maxRetries, dmq::Duration retryDelay) + { + m_maxRetries.store(maxRetries < 0 ? 0 : maxRetries); + auto ms = std::chrono::duration_cast(retryDelay).count(); + m_retryDelayMs.store(ms < 0 ? 0 : static_cast(ms)); } // Runs on m_thread: execute GET then invoke callback diff --git a/HTTP/async_http.h b/HTTP/async_http.h index 62bb2b6..681e397 100644 --- a/HTTP/async_http.h +++ b/HTTP/async_http.h @@ -32,6 +32,7 @@ #include "DelegateMQ.h" #include +#include #include #include #include @@ -87,6 +88,19 @@ namespace async { /// Accessor for the internal worker thread (e.g. to dispatch work directly onto it). dmq::os::Thread* get_thread(); + /// Retry a request that gets HTTP 429 (Too Many Requests) up to maxRetries times. + /// Each retry waits for the server's Retry-After (capped at MAX_RETRY_AFTER) or, if + /// the server sends none, retryDelay. Default: 3 retries, 1 s apart. + /// @note The wait runs on the worker thread, so while a request is rate limited it + /// holds up the requests queued behind it (about 3 s each with the defaults). + /// If the retries run out, the last 429 response is returned. Set maxRetries + /// to 0 to get a 429 back at once. Callable from any thread. + void SetRateLimitRetry(int maxRetries, + dmq::Duration retryDelay = std::chrono::seconds(1)); + + /// Longest Retry-After wait honored by the rate-limit retry. + static constexpr std::chrono::seconds MAX_RETRY_AFTER{5}; + // ------------------------------------------------------------------------- // Blocking API — caller blocks until response arrives or timeout expires // ------------------------------------------------------------------------- @@ -126,9 +140,14 @@ namespace async { dmq::os::Thread m_thread; CURL* m_curl = nullptr; bool m_running = false; + std::atomic m_maxRetries{3}; + std::atomic m_retryDelayMs{1000}; static size_t WriteCallback(char* ptr, size_t size, size_t nmemb, void* userdata); + /// Run the request set up on m_curl, retrying on HTTP 429. Runs on m_thread. + HttpResponse Perform(); + HttpResponse HttpGet(const std::string& url); HttpResponse HttpPost(const std::string& url, const std::string& body, diff --git a/README.md b/README.md index 14038ff..2832f71 100644 --- a/README.md +++ b/README.md @@ -271,6 +271,8 @@ namespace async { int init(); int shutdown(dmq::Duration timeout = MAX_WAIT); Thread* get_thread(); + // Retry HTTP 429 (Too Many Requests): default 3 retries, 1 s apart (or Retry-After) + void SetRateLimitRetry(int maxRetries, dmq::Duration retryDelay = std::chrono::seconds(1)); // Blocking API HttpResponse GetWait(const std::string& url, dmq::Duration timeout = MAX_WAIT); diff --git a/UnitTest/Blocking.cpp b/UnitTest/Blocking.cpp index 9d736a4..1d90de2 100644 --- a/UnitTest/Blocking.cpp +++ b/UnitTest/Blocking.cpp @@ -95,6 +95,36 @@ static void Test_SequentialRequests(AsyncHttp& http) std::cout << " 3 sequential requests succeeded" << std::endl; } +// ----------------------------------------------------------------------------- +// Test 7: HTTP 429 is retried, then returned once the retries run out +// ----------------------------------------------------------------------------- +static void Test_RateLimitRetry(AsyncHttp& http) +{ + // httpbin.org/status/429 always answers 429: 2 retries, 200 ms apart (or the + // server's Retry-After, if it sends one), so at least 400 ms before the result. + http.SetRateLimitRetry(2, std::chrono::milliseconds(200)); + auto start = std::chrono::steady_clock::now(); + HttpResponse resp = http.GetWait("https://httpbin.org/status/429", std::chrono::seconds(30)); + auto elapsed = std::chrono::steady_clock::now() - start; + + // Back to the default (3 retries, 1 s apart) for the remaining tests + http.SetRateLimitRetry(3); + + DMQ_ASSERT_TRUE(resp.statusCode == 429); + DMQ_ASSERT_TRUE(resp.error.empty()); + DMQ_ASSERT_TRUE(elapsed >= std::chrono::milliseconds(400)); + + // Retries off: the 429 comes back at once + http.SetRateLimitRetry(0); + resp = http.GetWait("https://httpbin.org/status/429", std::chrono::seconds(30)); + http.SetRateLimitRetry(3); + DMQ_ASSERT_TRUE(resp.statusCode == 429); + + std::cout << " GetWait 429 retried, then returned (" + << std::chrono::duration_cast(elapsed).count() + << " ms)" << std::endl; +} + // ----------------------------------------------------------------------------- // Main entry point // ----------------------------------------------------------------------------- @@ -108,6 +138,7 @@ void Blocking_UT(AsyncHttp& http) Test_PostWait_Success(http); Test_PostWait_StatusError(http); Test_SequentialRequests(http); + Test_RateLimitRetry(http); std::cout << "HTTP Blocking API Tests Passed!" << std::endl; } diff --git a/UnitTest/Callback.cpp b/UnitTest/Callback.cpp index 7bcaa4c..c4a3902 100644 --- a/UnitTest/Callback.cpp +++ b/UnitTest/Callback.cpp @@ -81,13 +81,13 @@ static void Test_Get_AsyncCallback(AsyncHttp& http) static void Test_Post_SyncCallback(AsyncHttp& http) { std::atomic fired{false}; - std::string receivedBody; + HttpResponse received; std::mutex bodyMutex; std::function fn = [&](HttpResponse resp) { { std::lock_guard lock(bodyMutex); - receivedBody = resp.body; + received = resp; } fired.store(true); }; @@ -101,7 +101,11 @@ static void Test_Post_SyncCallback(AsyncHttp& http) DMQ_ASSERT_TRUE(ok); { std::lock_guard lock(bodyMutex); - DMQ_ASSERT_TRUE(receivedBody.find("sensor") != std::string::npos); + if (received.body.find("sensor") == std::string::npos) + std::cout << " Post() failed: status=" << received.statusCode + << " error=\"" << received.error << "\" body=\"" + << received.body.substr(0, 200) << "\"" << std::endl; + DMQ_ASSERT_TRUE(received.body.find("sensor") != std::string::npos); } std::cout << " Post() sync callback fired, body contains posted data" << std::endl; }