#pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace Echoion::Core { namespace asio = boost::asio; namespace beast = boost::beast; namespace websocket = beast::websocket; class RpcServer : public std::enable_shared_from_this { public: using CommandHandler = std::function( const std::string& params, uint64_t clientId)>; RpcServer(); ~RpcServer(); // Initialize and start the server Api::Result start(uint16_t port = 8765); void stop(); [[nodiscard]] bool isRunning() const { return running_; } [[nodiscard]] uint16_t getPort() const { return port_; } // Register command handlers void registerHandler(const std::string& method, CommandHandler handler); void unregisterHandler(const std::string& method); // Authentication void setAuthToken(const std::string& token); [[nodiscard]] bool authenticate(const std::string& token); void addAuthenticatedClient(uint64_t clientId); void removeAuthenticatedClient(uint64_t clientId); [[nodiscard]] bool isClientAuthenticated(uint64_t clientId); // Broadcast events to all connected clients void broadcastEvent(const std::string& event, const std::string& data); // Send event to specific client void sendEvent(uint64_t clientId, const std::string& event, const std::string& data); private: void acceptLoop(); void handleClient( std::shared_ptr> ws); void processMessage(uint64_t clientId, const std::string& message); void sendResponse(uint64_t clientId, const Api::RpcResponse& response); void sendNotification(uint64_t clientId, const Api::RpcNotification& notification); asio::io_context ioContext_; std::optional acceptor_; std::thread serverThread_; std::atomic running_{false}; uint16_t port_ = 8765; // Connected clients std::unordered_map< uint64_t, std::shared_ptr>> clients_; std::mutex clientsMutex_; std::atomic nextClientId_{1}; // Per-client handlers run on a Void worker pool instead of one // detached std::thread each; ~ThreadPool drains and joins them on // stop. Sized well above any realistic concurrent-client count // (each long-lived handler holds a worker for the connection's // lifetime). static constexpr std::size_t CLIENT_POOL_SIZE = 64; std::unique_ptr clientPool_; // Authenticated clients std::set authenticatedClients_; std::mutex authMutex_; std::string authToken_; // Command handlers std::unordered_map handlers_; std::mutex handlersMutex_; }; } // namespace Echoion::Core