Files
EchoionCore/include/echoion/core/RpcServer.hpp
T

99 lines
2.7 KiB
C++

#pragma once
#include <PluginTypes.hpp>
#include <RpcTypes.hpp>
#include <TrackTypes.hpp>
#include <Types.hpp>
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include <boost/beast/websocket.hpp>
#include <functional>
#include <mutex>
#include <set>
#include <thread>
#include <unordered_map>
namespace Echoion::Core
{
namespace asio = boost::asio;
namespace beast = boost::beast;
namespace websocket = beast::websocket;
class RpcServer : public std::enable_shared_from_this<RpcServer>
{
public:
using CommandHandler = std::function<Api::Result<std::string>(
const std::string& params, uint64_t clientId)>;
RpcServer();
~RpcServer();
// Initialize and start the server
Api::Result<void> 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<websocket::stream<asio::ip::tcp::socket>> 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<asio::ip::tcp::acceptor> acceptor_;
std::thread serverThread_;
std::atomic<bool> running_{false};
uint16_t port_ = 8765;
// Connected clients
std::unordered_map<
uint64_t,
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>>>
clients_;
std::mutex clientsMutex_;
std::atomic<uint64_t> nextClientId_{1};
// Client threads (for proper cleanup)
std::vector<std::thread> clientThreads_;
std::mutex clientThreadsMutex_;
// Authenticated clients
std::set<uint64_t> authenticatedClients_;
std::mutex authMutex_;
std::string authToken_;
// Command handlers
std::unordered_map<std::string, CommandHandler> handlers_;
std::mutex handlersMutex_;
};
} // namespace Echoion::Core