#include "cloud_point_rpc/rpc_server.hpp" #include using json = nlohmann::json; namespace cloud_point_rpc { namespace { json create_error(int code, const std::string &message, const json &id = nullptr) { return {{"jsonrpc", "2.0"}, {"error", {{"code", code}, {"message", message}}}, {"id", id}}; } json create_success(const json &result, const json &id) { return {{"jsonrpc", "2.0"}, {"result", result}, {"id", id}}; } } // namespace void RpcServer::register_method(const std::string &name, Handler handler) { handlers_[name] = std::move(handler); } void RpcServer::register_method(const std::string& name, callback_t handler) { handlers_[name] = [handler](const nlohmann::json& j) -> nlohmann::json { rpc_string tmp; tmp.s = j.dump(); rpc_string* res = handler(&tmp); return {res->s}; }; } std::string RpcServer::process(const std::string &request_str) { LOG(INFO) << request_str; json request; try { request = json::parse(request_str); } catch (const json::parse_error &) { LOG(ERROR) << "json parse error; " << __func__; return create_error(-32700, "Parse error").dump(); } // Batch requests are not supported in this minimal version, assume single // object if (!request.contains("jsonrpc") || request["jsonrpc"] != "2.0" || !request.contains("method") || !request.contains("id")) { return create_error(-32600, "Invalid Request", request.value("id", json(nullptr))) .dump(); } std::string method = request["method"]; json id = request["id"]; json params = request.value("params", json::object()); auto it = handlers_.find(method); if (it == handlers_.end()) { return create_error(-32601, "Method not found", id).dump(); } try { json result = it->second(params); return create_success(result, id).dump(); } catch (const std::exception &e) { return create_error(-32000, e.what(), id).dump(); // Server error } } } // namespace cloud_point_rpc