Files
EchoionCore/src/RpcServer.cpp
T
faumarayandClaude Opus 4.8 3af9aecbec Phase C: run RPC per-client handlers on a Void ThreadPool
Replace the one-detached-std::thread-per-client model and its manual
bookkeeping (the clientThreads_ vector, finished-thread sweep, and
detach-after-timeout shutdown) with a Void::Concurrency::ThreadPool:

- start() builds clientPool_ (CLIENT_POOL_SIZE workers); the accept loop
  submits each accepted connection's handleClient + cleanup as a task.
- stop() closes the client sockets (so each handler's read() returns) then
  resets the pool, whose destructor drains and joins every handler.

The accept loop stays on its own dedicated thread — a long-lived listen
loop is not pool work, and its cancellable/timeout-guarded shutdown is
unchanged. CLIENT_POOL_SIZE (64) caps concurrent long-lived client handlers
far above any realistic count for this bot's RPC surface.

Build green. Runtime behavior (live RPC sessions) is unverified here.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 13:26:16 +03:00

436 lines
11 KiB
C++

#include "echoion/core/Logger.hpp"
#include "echoion/core/RpcServer.hpp"
#include <Void/Data/Json.hpp>
#include <Void/Data/Reflect.hpp>
#include <algorithm>
#include <format>
namespace Echoion::Core
{
RpcServer::RpcServer() = default;
RpcServer::~RpcServer() { stop(); }
Api::Result<void> RpcServer::start(uint16_t port)
{
if (running_.exchange(true)) {
return Api::fail(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();
clientPool_ = std::make_unique<Void::Concurrency::ThreadPool>(
CLIENT_POOL_SIZE);
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 Api::fail(
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<std::mutex> lock(clientsMutex_);
for (auto& [id, ws] : clients_) {
if (ws->is_open()) {
beast::error_code ec;
ws->close(websocket::close_code::normal, ec);
}
}
clients_.clear();
}
// Drain and join the client handlers. Their sockets were just
// closed, so each handleClient read() fails and the task returns;
// ~ThreadPool then joins every worker.
clientPool_.reset();
// 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<bool> 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<websocket::stream<asio::ip::tcp::socket>>(
std::move(socket));
ws->accept();
ECHOION_LOG_DEBUG("RPC server WebSocket handshake completed");
uint64_t clientId = nextClientId_++;
{
std::lock_guard<std::mutex> lock(clientsMutex_);
clients_[clientId] = ws;
}
ECHOION_LOG_DEBUG(
std::format("RPC client {} connected", clientId));
// Handle the client on the worker pool (drained/joined by
// ~ThreadPool on stop).
if (clientPool_) {
clientPool_->submit([this, clientId, ws]() {
handleClient(ws);
// Cleanup
{
std::lock_guard<std::mutex> lock(clientsMutex_);
clients_.erase(clientId);
}
{
std::lock_guard<std::mutex> lock(authMutex_);
authenticatedClients_.erase(clientId);
}
ECHOION_LOG_DEBUG(std::format(
"RPC client {} disconnected", clientId));
});
}
} 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<websocket::stream<asio::ip::tcp::socket>> 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<std::mutex> 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;
bool decoded = false;
if (auto parsed = Void::Json::parse(message)) {
if (auto req = Void::Json::from_json<Api::RpcRequest>(*parsed)) {
request = std::move(*req);
decoded = true;
}
}
if (!decoded) {
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<int>(request.method));
CommandHandler handler;
{
std::lock_guard<std::mutex> 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<uint32_t>(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<std::mutex> lock(clientsMutex_);
auto it = clients_.find(clientId);
if (it == clients_.end() || !it->second->is_open()) {
return;
}
try {
const std::string json =
Void::Json::serialize(Void::Json::to_json(response));
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<std::mutex> lock(clientsMutex_);
auto it = clients_.find(clientId);
if (it == clients_.end() || !it->second->is_open()) {
return;
}
try {
const std::string json =
Void::Json::serialize(Void::Json::to_json(notification));
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<std::mutex> lock(clientsMutex_);
for (const auto& [clientId, ws] : clients_) {
if (ws->is_open() && isClientAuthenticated(clientId)) {
try {
const std::string json = Void::Json::serialize(
Void::Json::to_json(notification));
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<std::mutex> lock(handlersMutex_);
handlers_[method] = std::move(handler);
}
void RpcServer::unregisterHandler(const std::string& method)
{
std::lock_guard<std::mutex> lock(handlersMutex_);
handlers_.erase(method);
}
void RpcServer::setAuthToken(const std::string& token)
{
std::lock_guard<std::mutex> lock(authMutex_);
authToken_ = token;
}
bool RpcServer::authenticate(const std::string& token)
{
std::lock_guard<std::mutex> lock(authMutex_);
return authToken_.empty() || token == authToken_;
}
void RpcServer::addAuthenticatedClient(uint64_t clientId)
{
std::lock_guard<std::mutex> lock(authMutex_);
authenticatedClients_.insert(clientId);
}
void RpcServer::removeAuthenticatedClient(uint64_t clientId)
{
std::lock_guard<std::mutex> lock(authMutex_);
authenticatedClients_.erase(clientId);
}
bool RpcServer::isClientAuthenticated(uint64_t clientId)
{
std::lock_guard<std::mutex> lock(authMutex_);
return authenticatedClients_.contains(clientId);
}
} // namespace Echoion::Core