From a9a80c956a7ae74db74a14654806e7c2dcdb956e Mon Sep 17 00:00:00 2001 From: Zephyron Date: Fri, 21 Nov 2025 17:32:27 +1000 Subject: [PATCH] Improve web service thread safety by creating client per request - Change GenericRequest() to create a new httplib::Client for each request instead of reusing a single instance - Remove shared client instance and mutex to avoid thread safety issues - This is the safest approach in a multi-threaded environment and prevents potential race conditions Signed-off-by: Zephyron --- src/web_service/web_backend.cpp | 21 ++++++++------------- 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/src/web_service/web_backend.cpp b/src/web_service/web_backend.cpp index 710fe09ba..b41b42f34 100644 --- a/src/web_service/web_backend.cpp +++ b/src/web_service/web_backend.cpp @@ -77,17 +77,14 @@ struct Client::Impl { const std::string& jwt_ = "", const std::string& username_ = "", const std::string& token_ = "") { - { - std::scoped_lock lock{cli_mutex}; - if (cli == nullptr) { - cli = std::make_unique(host.c_str()); - cli->set_connection_timeout(TIMEOUT_SECONDS); - cli->set_read_timeout(TIMEOUT_SECONDS); - cli->set_write_timeout(TIMEOUT_SECONDS); - } - } + // Create a new client for each request. This is the safest approach in a + // multi-threaded environment as it avoids sharing a single client instance. + httplib::Client cli(host.c_str()); + cli.set_connection_timeout(TIMEOUT_SECONDS); + cli.set_read_timeout(TIMEOUT_SECONDS); + cli.set_write_timeout(TIMEOUT_SECONDS); - if (!cli->is_valid()) { + if (!cli.is_valid()) { LOG_ERROR(WebService, "Invalid URL {}", host + path); return WebResult{WebResult::Code::InvalidURL, "Invalid URL", ""}; } @@ -116,7 +113,7 @@ struct Client::Impl { request.headers = params; request.body = data; - httplib::Result result = cli->send(request); + httplib::Result result = cli.send(request); if (!result) { LOG_ERROR(WebService, "{} to {} returned null", method, host + path); @@ -175,8 +172,6 @@ struct Client::Impl { std::string username; std::string token; std::string jwt; - std::unique_ptr cli; - std::mutex cli_mutex; struct JWTCache { std::mutex mutex;