score-back/src/rpc_server.cpp
amukhamadiev ece26e7b1f [jsonrpccxx] moved to external rpc impl
Detailed:
      As base used jsonrpccxx implementation paired with TCP socket
      TCP socket updated to handle dynamic sized buffers
      TCP communication protocol changed to serialized packet size after
      which json string is presented
2026-02-20 17:51:14 +03:00

60 lines
1.8 KiB
C++

#include "cloud_point_rpc/rpc_server.hpp"
#include <glog/logging.h>
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);
}
std::string RpcServer::process(const std::string &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