#include "echoion/core/RpcServer.hpp" #include "echoion/core/Logger.hpp" #include #include #include namespace Echoion::Core { RpcServer::RpcServer() = default; RpcServer::~RpcServer() { stop(); } Api::Result RpcServer::start(uint16_t port) { if (running_.exchange(true)) { return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists, "RPC server already running")); } port_ = port; try { asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), port); acceptor_.emplace(ioContext_); acceptor_->open(endpoint.protocol()); acceptor_->set_option(asio::ip::tcp::acceptor::reuse_address(true)); acceptor_->bind(endpoint); acceptor_->listen(); serverThread_ = std::thread(&RpcServer::acceptLoop, this); ECHOION_LOG_INFO(std::format("RPC server started on port {}", port)); return {}; } catch (const std::exception& e) { running_ = false; return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, std::format("Failed to start RPC server: {}", e.what()))); } } void RpcServer::stop() { if (!running_.exchange(false)) { return; } try { // Cancel any pending async operations if (acceptor_.has_value()) { boost::system::error_code ec; acceptor_->cancel(ec); } ioContext_.stop(); // Close all client connections { std::lock_guard lock(clientsMutex_); for (auto& [id, ws] : clients_) { if (ws->is_open()) { beast::error_code ec; ws->close(websocket::close_code::normal, ec); } } clients_.clear(); } // Wait for all client threads to finish (with timeout) { std::lock_guard lock(clientThreadsMutex_); for (auto& thread : clientThreads_) { if (thread.joinable()) { thread.detach(); // Don't wait, just detach } } clientThreads_.clear(); } // Wait for server thread with timeout if (serverThread_.joinable()) { // Give it a moment to clean up auto start = std::chrono::steady_clock::now(); while (serverThread_.joinable() && std::chrono::steady_clock::now() - start < std::chrono::seconds(2)) { std::this_thread::sleep_for(std::chrono::milliseconds(50)); } if (serverThread_.joinable()) { serverThread_.detach(); // Force detach if still running } } if (acceptor_.has_value()) { boost::system::error_code ec; acceptor_->close(ec); } ECHOION_LOG_INFO("RPC server stopped"); } catch (const std::exception& e) { ECHOION_LOG_ERROR(std::format("Error stopping RPC server: {}", e.what())); } } void RpcServer::acceptLoop() { ECHOION_LOG_INFO("RPC server accept loop started"); while (running_.load()) { try { asio::ip::tcp::socket socket(ioContext_); ECHOION_LOG_DEBUG("RPC server waiting for connection..."); // Use async accept with cancellation support std::atomic acceptComplete{false}; boost::system::error_code acceptEc; acceptor_->async_accept(socket, [&](const boost::system::error_code& ec) { acceptEc = ec; acceptComplete = true; }); // Poll until accept completes or we're stopped while (!acceptComplete.load() && running_.load()) { ioContext_.poll_one(); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } // Cancel pending operation if we're stopping if (!running_.load()) { acceptor_->cancel(); break; } if (acceptEc) { throw std::runtime_error(acceptEc.message()); } ECHOION_LOG_DEBUG(std::format("RPC server accepted TCP connection from {}:{}", socket.remote_endpoint().address().to_string(), socket.remote_endpoint().port())); if (!running_.load()) break; auto ws = std::make_shared>(std::move(socket)); ws->accept(); ECHOION_LOG_DEBUG("RPC server WebSocket handshake completed"); uint64_t clientId = nextClientId_++; { std::lock_guard lock(clientsMutex_); clients_[clientId] = ws; } ECHOION_LOG_DEBUG(std::format("RPC client {} connected", clientId)); // Handle client in separate thread std::thread clientThread([this, clientId, ws]() { handleClient(ws); // Cleanup { std::lock_guard lock(clientsMutex_); clients_.erase(clientId); } { std::lock_guard lock(authMutex_); authenticatedClients_.erase(clientId); } ECHOION_LOG_DEBUG(std::format("RPC client {} disconnected", clientId)); }); // Track the thread for proper cleanup { std::lock_guard lock(clientThreadsMutex_); // Clean up any finished threads first clientThreads_.erase( std::remove_if(clientThreads_.begin(), clientThreads_.end(), [](std::thread& t) { if (!t.joinable()) return true; return false; }), clientThreads_.end() ); clientThreads_.push_back(std::move(clientThread)); } } catch (const std::exception& e) { // If we're shutting down, exit gracefully if (!running_.load()) { break; } ECHOION_LOG_ERROR(std::format("RPC accept error: {}", e.what())); } } ECHOION_LOG_INFO("RPC server accept loop stopped"); } void RpcServer::handleClient(std::shared_ptr> ws) { beast::flat_buffer buffer; while (running_.load() && ws->is_open()) { try { beast::error_code ec; ws->read(buffer, ec); if (ec == websocket::error::closed) { break; } if (ec) { ECHOION_LOG_ERROR(std::format("WebSocket read error: {}", ec.message())); break; } std::string message = beast::buffers_to_string(buffer.data()); buffer.consume(buffer.size()); // Find client ID uint64_t clientId = 0; { std::lock_guard lock(clientsMutex_); for (const auto& [id, clientWs] : clients_) { if (clientWs.get() == ws.get()) { clientId = id; break; } } } if (clientId != 0) { processMessage(clientId, message); } } catch (const std::exception& e) { ECHOION_LOG_ERROR(std::format("Client handling error: {}", e.what())); break; } } } void RpcServer::processMessage(uint64_t clientId, const std::string& message) { try { Api::RpcRequest request; auto ec = glz::read_json(request, message); if (ec) { Api::RpcResponse response; response.requestId = 0; response.success = false; response.error = "{\"code\":5,\"message\":\"Invalid JSON\",\"source\":\"RpcServer\"}"; response.success = false; sendResponse(clientId, response); return; } // Check authentication (except for Authenticate method) if (request.method != Api::RpcMethod::Authenticate) { if (!isClientAuthenticated(clientId)) { Api::RpcResponse response; response.requestId = request.id; response.success = false; response.error = "{\"code\":10,\"message\":\"Not authenticated\",\"source\":\"RpcServer\"}"; response.success = false; sendResponse(clientId, response); return; } } // Find handler std::string methodName = std::to_string(static_cast(request.method)); CommandHandler handler; { std::lock_guard lock(handlersMutex_); auto it = handlers_.find(methodName); if (it != handlers_.end()) { handler = it->second; } } Api::RpcResponse response; response.requestId = request.id; response.timestamp = std::chrono::system_clock::now(); if (handler) { auto result = handler(request.params.value_or(""), clientId); if (result) { response.success = true; response.result = *result; } else { response.success = false; response.error = std::format("{{\"code\":{},\"message\":\"{}\",\"source\":\"{}\"}}", static_cast(result.error().code), result.error().message, result.error().source); } } else { response.success = false; response.error = "{\"code\":2,\"message\":\"Unknown method\",\"source\":\"RpcServer\"}"; } sendResponse(clientId, response); } catch (const std::exception& e) { ECHOION_LOG_ERROR(std::format("Message processing error: {}", e.what())); } } void RpcServer::sendResponse(uint64_t clientId, const Api::RpcResponse& response) { std::lock_guard lock(clientsMutex_); auto it = clients_.find(clientId); if (it == clients_.end() || !it->second->is_open()) { return; } try { auto json = glz::write_json(response); if (json) { it->second->write(asio::buffer(*json)); } } catch (const std::exception& e) { ECHOION_LOG_ERROR(std::format("Send response error: {}", e.what())); } } void RpcServer::sendNotification(uint64_t clientId, const Api::RpcNotification& notification) { std::lock_guard lock(clientsMutex_); auto it = clients_.find(clientId); if (it == clients_.end() || !it->second->is_open()) { return; } try { auto json = glz::write_json(notification); if (json) { it->second->write(asio::buffer(*json)); } } catch (const std::exception& e) { ECHOION_LOG_ERROR(std::format("Send notification error: {}", e.what())); } } void RpcServer::broadcastEvent(const std::string& event, const std::string& data) { Api::RpcNotification notification; notification.event = event; notification.data = data; notification.timestamp = std::chrono::system_clock::now(); std::lock_guard lock(clientsMutex_); for (const auto& [clientId, ws] : clients_) { if (ws->is_open() && isClientAuthenticated(clientId)) { try { auto json = glz::write_json(notification); if (json) { ws->write(asio::buffer(*json)); } } catch (const std::exception& e) { ECHOION_LOG_ERROR(std::format("Broadcast error: {}", e.what())); } } } } void RpcServer::sendEvent(uint64_t clientId, const std::string& event, const std::string& data) { Api::RpcNotification notification; notification.event = event; notification.data = data; notification.timestamp = std::chrono::system_clock::now(); sendNotification(clientId, notification); } void RpcServer::registerHandler(const std::string& method, CommandHandler handler) { std::lock_guard lock(handlersMutex_); handlers_[method] = std::move(handler); } void RpcServer::unregisterHandler(const std::string& method) { std::lock_guard lock(handlersMutex_); handlers_.erase(method); } void RpcServer::setAuthToken(const std::string& token) { std::lock_guard lock(authMutex_); authToken_ = token; } bool RpcServer::authenticate(const std::string& token) { std::lock_guard lock(authMutex_); return authToken_.empty() || token == authToken_; } void RpcServer::addAuthenticatedClient(uint64_t clientId) { std::lock_guard lock(authMutex_); authenticatedClients_.insert(clientId); } void RpcServer::removeAuthenticatedClient(uint64_t clientId) { std::lock_guard lock(authMutex_); authenticatedClients_.erase(clientId); } bool RpcServer::isClientAuthenticated(uint64_t clientId) { std::lock_guard lock(authMutex_); return authenticatedClients_.contains(clientId); } } // namespace Echoion::Core