Skip to content

Commit

Permalink
rev
Browse files Browse the repository at this point in the history
  • Loading branch information
dr3mro committed Jan 2, 2025
1 parent 311e3fe commit 00ba9b0
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 42 deletions.
68 changes: 33 additions & 35 deletions src/database/databaseconnectionpool.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#include <string>
#include <thread>
#include <utility>
#include <vector>

#include "configurator/configurator.hpp"
#include "database.hpp"
Expand All @@ -38,7 +39,7 @@ std::shared_ptr<Database> DatabaseConnectionPool::createDatabaseConnection(const
}
catch (const std::exception& e)
{
Message::CriticalMessage(fmt::format("Database connection initialization failure : {}", e.what()));
Message::CriticalMessage(fmt::format("Failed to create a Database connection: {}", e.what()));
}
return nullptr;
}
Expand All @@ -49,53 +50,50 @@ DatabaseConnectionPool::DatabaseConnectionPool() : configurator_(Store::getObjec
{
const Configurator::DatabaseConfig& config = configurator_->get<Configurator::DatabaseConfig>();

std::vector<std::future<std::shared_ptr<Database>>> futures;

futures.reserve(config.max_conn);
for (uint16_t i = 0; i < config.max_conn; ++i)
{
unsigned int retryCount = 0;
bool connectionEstablished = false;

while (retryCount < MAX_RETRIES && !connectionEstablished)
{
auto future = std::async(std::launch::async, [this, &config]() { return this->createDatabaseConnection(config); });
auto status = future.wait_for(std::chrono::seconds(TIMEOUT + 1));

if (status == std::future_status::ready)
futures.push_back(std::async(std::launch::async,
[this, config]() -> std::shared_ptr<Database>
{
auto conn = future.get();
if (conn != nullptr)
unsigned int retryCount = 0;
while (retryCount < MAX_RETRIES)
{
databaseConnections_.push_back(conn);
Message::InitMessage(fmt::format("Connection {}/{} created successfully.", i + 1, config.max_conn));
connectionEstablished = true;
break;
auto conn = createDatabaseConnection(config);
if (conn)
{
return conn;
}
std::this_thread::sleep_for(std::chrono::seconds(1U << retryCount));
Message::WarningMessage(fmt::format("Retrying connection to database {}/{} retries.", ++retryCount, MAX_RETRIES));
}
}

retryCount++;

Message::WarningMessage(fmt::format("Connection attempt {} timed out, retrying... ({}/{})", i + 1, retryCount, MAX_RETRIES));
return nullptr;
}));
}

if (retryCount < MAX_RETRIES)
{
std::this_thread::sleep_for(std::chrono::seconds(1U << retryCount));
}
// Wait for all futures
for (auto& future : futures)
{
auto conn = future.get(); // Blocks only on completion of the individual task
if (conn != nullptr)
{
std::lock_guard<std::mutex> lock(mutex_);
databaseConnections_.push_back(conn);
Message::InitMessage(fmt::format("Connection {}/{} created successfully.", databaseConnections_.size(), config.max_conn));
}

if (!connectionEstablished)
else
{
while (!databaseConnections_.empty())
{
databaseConnections_.pop_front();
}

Message::ErrorMessage(fmt::format("Failed to establish connection {} after {} attempts.", i + 1, MAX_RETRIES));
Message::ErrorMessage("Failed to establish one or more connections after maximum retries.");
throw std::runtime_error("Database connection pool initialization failure.");
}
}
}
catch (const std::exception& e)
{
Message::CriticalMessage(fmt::format("Failed to initialize database connection pool: {}", e.what()));
std::string what = e.what();
Message::CriticalMessage(fmt::format("Failed to initialize database connection pool: {}", what.substr(0, -4)));
Message::ErrorMessage("Exiting...");
exit(EXIT_FAILURE); /*NOLINT*/
}
Expand Down Expand Up @@ -152,4 +150,4 @@ void DatabaseConnectionPool::reconnect_all()

connection++;
}
}
}
18 changes: 13 additions & 5 deletions src/utils/message/message.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include <fmt/format.h>
#include <trantor/utils/Logger.h>

#include <algorithm>
#include <string>
#include <unordered_map>

Expand All @@ -30,18 +31,25 @@ std::string Message::get_color(trantor::Logger::LogLevel level)
return color_map.at(level);
}

void Message::MessageImpl(const std::string& status_message, trantor::Logger::LogLevel level)
void Message::MessageImpl(const std::string& _status_message, trantor::Logger::LogLevel _level)
{
trantor::Logger(level).stream() << fmt::format("{}{}{}", get_color(level), status_message, "\033[0m");
trantor::Logger(_level).stream() << fmt::format("{}{}{}", get_color(_level), removeNewLine(_status_message), "\033[0m");
}
void Message::MessageImpl(const std::string& status_message, const std::string& type)
void Message::MessageImpl(const std::string& _status_message, const std::string& _type) /*NOLINT */
{
fmt::print("{}{}{}{}{}\n",
fmt::format(fg(fmt::color::indian_red),
"[Project Valhalla]"), // The server name in red
fmt::format(fg(fmt::color::white), " ["), // the left square bracket
fmt::format("{}", fmt::format(fg(fmt::color::green), "{}",
type)), // The message type in green
_type)), // The message type in green
fmt::format(fg(fmt::color::white), "] "), // the right square bracket
status_message); // the message
removeNewLine(_status_message)); // The message
}

std::string Message::removeNewLine(const std::string& _str)
{
std::string status_message = _str;
std::ranges::replace(status_message, '\n', ' ');
return status_message;
}
5 changes: 3 additions & 2 deletions src/utils/message/message.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class Message
static std::string get_color(trantor::Logger::LogLevel level);

private:
static void MessageImpl(const std::string& status_message, trantor::Logger::LogLevel level);
static void MessageImpl(const std::string& status_messageconst, const std::string& type);
static void MessageImpl(const std::string& _status_message, trantor::Logger::LogLevel _level);
static void MessageImpl(const std::string& _status_message, const std::string& _type);
static std::string removeNewLine(const std::string& _str);
};

0 comments on commit 00ba9b0

Please sign in to comment.