Migrate core infrastructure to VoidLibrary
This commit is contained in:
1 parent
53801f2b53
commit
2bdb63766d
65 files changed
+16109
-12011
No files matched your search
+410
-347
@@ -1,400 +1,463 @@
|
||||
#include "echoion/core/RpcServer.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <glaze/glaze.hpp>
|
||||
#include <format>
|
||||
#include "echoion/core/RpcServer.hpp"
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Data/Reflect.hpp>
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
RpcServer::RpcServer() = default;
|
||||
RpcServer::RpcServer() = default;
|
||||
|
||||
RpcServer::~RpcServer() {
|
||||
stop();
|
||||
}
|
||||
RpcServer::~RpcServer() { stop(); }
|
||||
|
||||
Api::Result<void> RpcServer::start(uint16_t port) {
|
||||
if (running_.exchange(true)) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists, "RPC server already running"));
|
||||
}
|
||||
Api::Result<void> RpcServer::start(uint16_t port)
|
||||
{
|
||||
if (running_.exchange(true)) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists,
|
||||
"RPC server already running"));
|
||||
}
|
||||
|
||||
port_ = port;
|
||||
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();
|
||||
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);
|
||||
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())));
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
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();
|
||||
try {
|
||||
// Cancel any pending async operations
|
||||
if (acceptor_.has_value()) {
|
||||
boost::system::error_code ec;
|
||||
acceptor_->cancel(ec);
|
||||
}
|
||||
|
||||
// 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();
|
||||
}
|
||||
ioContext_.stop();
|
||||
|
||||
// Wait for all client threads to finish (with timeout)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientThreadsMutex_);
|
||||
for (auto& thread : clientThreads_) {
|
||||
if (thread.joinable()) {
|
||||
thread.detach(); // Don't wait, just detach
|
||||
}
|
||||
}
|
||||
clientThreads_.clear();
|
||||
}
|
||||
// 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();
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
// Wait for all client threads to finish (with timeout)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientThreadsMutex_);
|
||||
for (auto& thread : clientThreads_) {
|
||||
if (thread.joinable()) {
|
||||
// Give each thread a short time to finish
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
while (thread.joinable() &&
|
||||
std::chrono::steady_clock::now() - start <
|
||||
std::chrono::milliseconds(100)) {
|
||||
std::this_thread::sleep_for(
|
||||
std::chrono::milliseconds(10));
|
||||
}
|
||||
if (thread.joinable()) {
|
||||
thread.detach(); // Only detach if still running
|
||||
// after timeout
|
||||
}
|
||||
}
|
||||
}
|
||||
clientThreads_.clear();
|
||||
}
|
||||
|
||||
ECHOION_LOG_INFO("RPC server stopped");
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Error stopping RPC server: {}", e.what()));
|
||||
}
|
||||
}
|
||||
// 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
|
||||
}
|
||||
}
|
||||
|
||||
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 (acceptor_.has_value()) {
|
||||
boost::system::error_code ec;
|
||||
acceptor_->close(ec);
|
||||
}
|
||||
|
||||
if (!running_.load()) break;
|
||||
ECHOION_LOG_INFO("RPC server stopped");
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Error stopping RPC server: {}", e.what()));
|
||||
}
|
||||
}
|
||||
|
||||
auto ws = std::make_shared<websocket::stream<asio::ip::tcp::socket>>(std::move(socket));
|
||||
ws->accept();
|
||||
ECHOION_LOG_DEBUG("RPC server WebSocket handshake completed");
|
||||
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...");
|
||||
|
||||
uint64_t clientId = nextClientId_++;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
clients_[clientId] = ws;
|
||||
}
|
||||
// Use async accept with cancellation support
|
||||
std::atomic<bool> acceptComplete{false};
|
||||
boost::system::error_code acceptEc;
|
||||
|
||||
ECHOION_LOG_DEBUG(std::format("RPC client {} connected", clientId));
|
||||
acceptor_->async_accept(
|
||||
socket, [&](const boost::system::error_code& ec) {
|
||||
acceptEc = ec;
|
||||
acceptComplete = true;
|
||||
});
|
||||
|
||||
// Handle client in separate thread
|
||||
std::thread clientThread([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));
|
||||
});
|
||||
|
||||
// Track the thread for proper cleanup
|
||||
{
|
||||
std::lock_guard<std::mutex> 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));
|
||||
}
|
||||
// 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));
|
||||
}
|
||||
|
||||
} 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");
|
||||
}
|
||||
// Cancel pending operation if we're stopping
|
||||
if (!running_.load()) {
|
||||
acceptor_->cancel();
|
||||
break;
|
||||
}
|
||||
|
||||
void RpcServer::handleClient(std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws) {
|
||||
beast::flat_buffer buffer;
|
||||
if (acceptEc) {
|
||||
throw std::runtime_error(acceptEc.message());
|
||||
}
|
||||
|
||||
while (running_.load() && ws->is_open()) {
|
||||
try {
|
||||
beast::error_code ec;
|
||||
ws->read(buffer, ec);
|
||||
ECHOION_LOG_DEBUG(
|
||||
std::format("RPC server accepted TCP connection from {}:{}",
|
||||
socket.remote_endpoint().address().to_string(),
|
||||
socket.remote_endpoint().port()));
|
||||
|
||||
if (ec == websocket::error::closed) {
|
||||
break;
|
||||
}
|
||||
if (ec) {
|
||||
ECHOION_LOG_ERROR(std::format("WebSocket read error: {}", ec.message()));
|
||||
break;
|
||||
}
|
||||
if (!running_.load()) {
|
||||
break;
|
||||
}
|
||||
|
||||
std::string message = beast::buffers_to_string(buffer.data());
|
||||
buffer.consume(buffer.size());
|
||||
auto ws =
|
||||
std::make_shared<websocket::stream<asio::ip::tcp::socket>>(
|
||||
std::move(socket));
|
||||
ws->accept();
|
||||
ECHOION_LOG_DEBUG("RPC server WebSocket handshake completed");
|
||||
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
uint64_t clientId = nextClientId_++;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
clients_[clientId] = ws;
|
||||
}
|
||||
|
||||
if (clientId != 0) {
|
||||
processMessage(clientId, message);
|
||||
}
|
||||
ECHOION_LOG_DEBUG(
|
||||
std::format("RPC client {} connected", clientId));
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Client handling error: {}", e.what()));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Handle client in separate thread
|
||||
std::thread clientThread([this, clientId, ws]() {
|
||||
handleClient(ws);
|
||||
|
||||
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;
|
||||
}
|
||||
// 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));
|
||||
});
|
||||
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
// Track the thread for proper cleanup
|
||||
{
|
||||
std::lock_guard<std::mutex> 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));
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
} 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");
|
||||
}
|
||||
|
||||
Api::RpcResponse response;
|
||||
response.requestId = request.id;
|
||||
response.timestamp = std::chrono::system_clock::now();
|
||||
void RpcServer::handleClient(
|
||||
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws)
|
||||
{
|
||||
beast::flat_buffer buffer;
|
||||
|
||||
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\"}";
|
||||
}
|
||||
while (running_.load() && ws->is_open()) {
|
||||
try {
|
||||
beast::error_code ec;
|
||||
ws->read(buffer, ec);
|
||||
|
||||
sendResponse(clientId, response);
|
||||
if (ec == websocket::error::closed) {
|
||||
break;
|
||||
}
|
||||
if (ec) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("WebSocket read error: {}", ec.message()));
|
||||
break;
|
||||
}
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Message processing error: {}", e.what()));
|
||||
}
|
||||
}
|
||||
std::string message = beast::buffers_to_string(buffer.data());
|
||||
buffer.consume(buffer.size());
|
||||
|
||||
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;
|
||||
}
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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()));
|
||||
}
|
||||
}
|
||||
if (clientId != 0) {
|
||||
processMessage(clientId, message);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Client handling error: {}", e.what()));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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::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;
|
||||
}
|
||||
|
||||
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();
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> 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()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
Api::RpcResponse response;
|
||||
response.requestId = request.id;
|
||||
response.timestamp = std::chrono::system_clock::now();
|
||||
|
||||
void RpcServer::registerHandler(const std::string& method, CommandHandler handler) {
|
||||
std::lock_guard<std::mutex> lock(handlersMutex_);
|
||||
handlers_[method] = std::move(handler);
|
||||
}
|
||||
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\"}";
|
||||
}
|
||||
|
||||
void RpcServer::unregisterHandler(const std::string& method) {
|
||||
std::lock_guard<std::mutex> lock(handlersMutex_);
|
||||
handlers_.erase(method);
|
||||
}
|
||||
sendResponse(clientId, response);
|
||||
|
||||
void RpcServer::setAuthToken(const std::string& token) {
|
||||
std::lock_guard<std::mutex> lock(authMutex_);
|
||||
authToken_ = token;
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Message processing error: {}", e.what()));
|
||||
}
|
||||
}
|
||||
|
||||
bool RpcServer::authenticate(const std::string& token) {
|
||||
std::lock_guard<std::mutex> lock(authMutex_);
|
||||
return authToken_.empty() || token == authToken_;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
void RpcServer::addAuthenticatedClient(uint64_t clientId) {
|
||||
std::lock_guard<std::mutex> lock(authMutex_);
|
||||
authenticatedClients_.insert(clientId);
|
||||
}
|
||||
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::removeAuthenticatedClient(uint64_t clientId) {
|
||||
std::lock_guard<std::mutex> lock(authMutex_);
|
||||
authenticatedClients_.erase(clientId);
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
bool RpcServer::isClientAuthenticated(uint64_t clientId) {
|
||||
std::lock_guard<std::mutex> lock(authMutex_);
|
||||
return authenticatedClients_.contains(clientId);
|
||||
}
|
||||
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
|
||||
Reference in new issue
Block a user