Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 39 additions & 21 deletions HTTP/async_http.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include "async_http.h"
#include "DelegateMQ.h"
#include <curl/curl.h>
#include <algorithm>
#include <any>
#include <functional>
#include <future>
Expand Down Expand Up @@ -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<int>(code);
resp.body = std::move(body);
}
return resp;
return Perform();
}

HttpResponse AsyncHttp::HttpPost(const std::string& url,
Expand All @@ -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());
Expand All @@ -152,22 +140,52 @@ namespace async {
curl_easy_setopt(m_curl, CURLOPT_POSTFIELDSIZE, static_cast<long>(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<int>(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::milliseconds>(
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<std::chrono::milliseconds>(retryDelay).count();
m_retryDelayMs.store(ms < 0 ? 0 : static_cast<long long>(ms));
}

// Runs on m_thread: execute GET then invoke callback
Expand Down
19 changes: 19 additions & 0 deletions HTTP/async_http.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@

#include "DelegateMQ.h"
#include <curl/curl.h>
#include <atomic>
#include <future>
#include <string>
#include <chrono>
Expand Down Expand Up @@ -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
// -------------------------------------------------------------------------
Expand Down Expand Up @@ -126,9 +140,14 @@ namespace async {
dmq::os::Thread m_thread;
CURL* m_curl = nullptr;
bool m_running = false;
std::atomic<int> m_maxRetries{3};
std::atomic<long long> 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,
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
31 changes: 31 additions & 0 deletions UnitTest/Blocking.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::chrono::milliseconds>(elapsed).count()
<< " ms)" << std::endl;
}

// -----------------------------------------------------------------------------
// Main entry point
// -----------------------------------------------------------------------------
Expand All @@ -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;
}
10 changes: 7 additions & 3 deletions UnitTest/Callback.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,13 @@ static void Test_Get_AsyncCallback(AsyncHttp& http)
static void Test_Post_SyncCallback(AsyncHttp& http)
{
std::atomic<bool> fired{false};
std::string receivedBody;
HttpResponse received;
std::mutex bodyMutex;

std::function<void(HttpResponse)> fn = [&](HttpResponse resp) {
{
std::lock_guard<std::mutex> lock(bodyMutex);
receivedBody = resp.body;
received = resp;
}
fired.store(true);
};
Expand All @@ -101,7 +101,11 @@ static void Test_Post_SyncCallback(AsyncHttp& http)
DMQ_ASSERT_TRUE(ok);
{
std::lock_guard<std::mutex> 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;
}
Expand Down