From 3a2ccb55c6fd84f4d184299ff157d825d459f019 Mon Sep 17 00:00:00 2001 From: snider Date: Wed, 15 Oct 2025 20:58:57 +0100 Subject: [PATCH] Refactor ApiServer to manage server lifecycle with start, stop, and wait methods --- src/api/ApiServer.cpp | 26 +++++++++++++++++++++----- src/api/ApiServer.hpp | 12 +++++++++++- src/api/main.cpp | 9 ++++++++- 3 files changed, 40 insertions(+), 7 deletions(-) diff --git a/src/api/ApiServer.cpp b/src/api/ApiServer.cpp index 09aadf50..726a3469 100644 --- a/src/api/ApiServer.cpp +++ b/src/api/ApiServer.cpp @@ -21,11 +21,11 @@ void ApiServer::run() { auto infoController = std::make_shared(); docEndpoints->append(infoController->getEndpoints()); - auto blockController = std::make_shared(); - docEndpoints->append(blockController->getEndpoints()); + // auto blockController = std::make_shared(); + // docEndpoints->append(blockController->getEndpoints()); router->addController(infoController); - router->addController(blockController); + // router->addController(blockController); OATPP_CREATE_COMPONENT(std::shared_ptr, swaggerDocumentInfo) ([] @@ -55,12 +55,28 @@ void ApiServer::run() { OATPP_COMPONENT(std::shared_ptr, connectionProvider); /* Create a server which takes provided TCP connections and passes them to the HTTP connection handler */ - oatpp::network::Server server(connectionProvider, connectionHandler); + m_server = std::make_shared(connectionProvider, connectionHandler); /* Print server port */ OATPP_LOGI("lethean-api", "Server running, API Docs: http://127.0.0.1:%s/swagger/ui", static_cast(connectionProvider->getProperty("port").getData())); /* Run server */ - server.run(); + m_server->run(); } + +void ApiServer::start() { + m_server_thread = std::thread(&ApiServer::run, this); +} + +void ApiServer::stop() { + if (m_server) { + m_server->stop(); + } +} + +void ApiServer::wait() { + if (m_server_thread.joinable()) { + m_server_thread.join(); + } +} diff --git a/src/api/ApiServer.hpp b/src/api/ApiServer.hpp index 582561c1..3adc6513 100644 --- a/src/api/ApiServer.hpp +++ b/src/api/ApiServer.hpp @@ -10,7 +10,15 @@ #include "oatpp/core/macro/component.hpp" #include "oatpp-swagger/Resources.hpp" +#include "oatpp/network/Server.hpp" +#include + class ApiServer { +private: + std::thread m_server_thread; + std::shared_ptr m_server; + + void run(); public: @@ -44,7 +52,9 @@ public: }; - void run(); + void start(); + void stop(); + void wait(); }; diff --git a/src/api/main.cpp b/src/api/main.cpp index eecb3004..91023d82 100644 --- a/src/api/main.cpp +++ b/src/api/main.cpp @@ -1,12 +1,19 @@ #include "ApiServer.hpp" #include "oatpp/core/base/Environment.hpp" +#include "common/util.h" int main(int argc, const char * argv[]) { oatpp::base::Environment::init(); ApiServer server; - server.run(); + + tools::signal_handler::install([&server] { + server.stop(); + }); + + server.start(); + server.wait(); /* Destroy oatpp Environment */ oatpp::base::Environment::destroy();