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 <zephyron@citron-emu.org>
This commit is contained in:
Zephyron
2025-11-21 17:32:27 +10:00
parent 188e2a8489
commit a9a80c956a

View File

@@ -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<httplib::Client>(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<httplib::Client> cli;
std::mutex cli_mutex;
struct JWTCache {
std::mutex mutex;