Clio  develop
The XRP Ledger API server.
Loading...
Searching...
No Matches
RPCServerHandler.hpp
1#pragma once
2
3#include "data/BackendInterface.hpp"
4#include "etl/ETLServiceInterface.hpp"
5#include "rpc/Errors.hpp"
6#include "rpc/Factories.hpp"
7#include "rpc/JS.hpp"
8#include "rpc/RPCHelpers.hpp"
9#include "rpc/common/impl/APIVersionParser.hpp"
10#include "util/JsonUtils.hpp"
11#include "util/Profiler.hpp"
12#include "util/Taggable.hpp"
13#include "util/config/ConfigDefinition.hpp"
14#include "util/log/Logger.hpp"
15#include "web/dosguard/DOSGuardInterface.hpp"
16#include "web/impl/ErrorHandling.hpp"
17#include "web/interface/ConnectionBase.hpp"
18
19#include <boost/asio/spawn.hpp>
20#include <boost/beast/core/error.hpp>
21#include <boost/json/array.hpp>
22#include <boost/json/object.hpp>
23#include <boost/json/parse.hpp>
24#include <boost/json/serialize.hpp>
25#include <boost/system/system_error.hpp>
26#include <rpcspec/backends/BoostJson.hpp>
27#include <xrpl/protocol/jss.h>
28
29#include <chrono>
30#include <exception>
31#include <functional>
32#include <memory>
33#include <ratio>
34#include <stdexcept>
35#include <string>
36#include <utility>
37
38namespace web {
39
47template <typename RPCEngineType>
49 std::shared_ptr<BackendInterface const> const backend_;
50 std::shared_ptr<RPCEngineType> const rpcEngine_;
51 std::shared_ptr<etl::ETLServiceInterface const> const etl_;
52 util::TagDecoratorFactory const tagFactory_;
53 rpc::impl::ProductionAPIVersionParser apiVersionParser_; // can be injected if needed
54 std::reference_wrapper<web::dosguard::DOSGuardInterface> dosguard_;
55
56 util::Logger log_{"RPC"};
57 util::Logger perfLog_{"Performance"};
58
59public:
71 std::shared_ptr<BackendInterface const> const& backend,
72 std::shared_ptr<RPCEngineType> const& rpcEngine,
73 std::shared_ptr<etl::ETLServiceInterface const> const& etl,
75 )
76 : backend_(backend)
77 , rpcEngine_(rpcEngine)
78 , etl_(etl)
79 , tagFactory_(config)
80 , apiVersionParser_(config.getObject("api_version"))
81 , dosguard_(dosguard)
82 {
83 }
84
91 void
92 operator()(std::string const& request, std::shared_ptr<web::ConnectionBase> const& connection)
93 {
94 if (not dosguard_.get().isOk(connection->clientIp())) {
95 connection->sendSlowDown(request);
96 return;
97 }
98
99 try {
100 auto req = boost::json::parse(request).as_object();
101 LOG(perfLog_.debug()) << connection->tag() << "Adding to work queue";
102
103 if (not connection->upgraded and shouldReplaceParams(req))
104 req[JS(params)] = boost::json::array({boost::json::object{}});
105
106 if (not dosguard_.get().request(connection->clientIp(), req)) {
107 connection->sendSlowDown(request);
108 return;
109 }
110
111 if (!rpcEngine_->post(
112 [this, request = std::move(req), connection](
113 boost::asio::yield_context yield
114 ) mutable { handleRequest(yield, std::move(request), connection); },
115 connection->clientIp()
116 )) {
117 rpcEngine_->notifyTooBusy();
118 web::impl::ErrorHelper(connection).sendTooBusyError();
119 }
120 } catch (boost::system::system_error const& ex) {
121 // system_error thrown when json parsing failed
122 rpcEngine_->notifyBadSyntax();
123 web::impl::ErrorHelper(connection).sendJsonParsingError();
124 LOG(log_.warn()) << "Error parsing JSON: " << ex.what() << ". For request: " << request;
125 } catch (std::invalid_argument const& ex) {
126 // thrown when json parses something that is not an object at top level
127 rpcEngine_->notifyBadSyntax();
128 LOG(log_.warn()) << "Invalid argument error: " << ex.what()
129 << ". For request: " << request;
130 web::impl::ErrorHelper(connection).sendJsonParsingError();
131 } catch (std::exception const& ex) {
132 LOG(perfLog_.error()) << connection->tag() << "Caught exception: " << ex.what();
133 rpcEngine_->notifyInternalError();
134 throw;
135 }
136 }
137
138private:
139 void
140 handleRequest(
141 boost::asio::yield_context yield,
142 boost::json::object&& request,
143 std::shared_ptr<web::ConnectionBase> const& connection
144 )
145 {
146 LOG(log_.info()) << connection->tag() << (connection->upgraded ? "ws" : "http")
147 << " received request from work queue: " << util::removeSecret(request)
148 << " ip = " << connection->clientIp();
149
150 try {
151 auto const range = backend_->fetchLedgerRange();
152 if (!range) {
153 // for error that happened before the handler, we don't attach any warnings
154 rpcEngine_->notifyNotReady();
155 web::impl::ErrorHelper(connection, std::move(request)).sendNotReadyError();
156
157 return;
158 }
159
160 auto const context = [&] {
161 if (connection->upgraded) {
162 return rpc::makeWsContext(
163 yield,
164 request,
165 connection->makeSubscriptionContext(tagFactory_),
166 tagFactory_.with(connection->tag()),
167 *range,
168 connection->clientIp(),
169 std::cref(apiVersionParser_),
170 connection->isAdmin()
171 );
172 }
174 yield,
175 request,
176 tagFactory_.with(connection->tag()),
177 *range,
178 connection->clientIp(),
179 std::cref(apiVersionParser_),
180 connection->isAdmin()
181 );
182 }();
183
184 if (!context) {
185 auto const err = context.error();
186 LOG(perfLog_.warn())
187 << connection->tag() << "Could not create Web context: " << err;
188 LOG(log_.warn()) << connection->tag() << "Could not create Web context: " << err;
189
190 // we count all those as BadSyntax - as the WS path would.
191 // Although over HTTP these will yield a 400 status with a plain text response (for
192 // most).
193 rpcEngine_->notifyBadSyntax();
194 web::impl::ErrorHelper(connection, std::move(request)).sendError(err);
195
196 return;
197 }
198
199 auto [result, timeDiff] =
200 util::timed([&] { return rpcEngine_->buildResponse(*context); });
201
202 auto const us = std::chrono::duration<int, std::milli>(timeDiff);
203 rpc::logDuration(request, context->tag(), us);
204
205 boost::json::object response;
206
207 if (!result.response.has_value()) {
208 // note: error statuses are counted/notified in buildResponse itself
209 response = web::impl::ErrorHelper(connection, request)
210 .composeError(result.response.error());
211 auto const responseStr = boost::json::serialize(response);
212
213 LOG(perfLog_.debug()) << context->tag() << "Encountered error: " << responseStr;
214 LOG(log_.debug()) << context->tag() << "Encountered error: " << responseStr;
215 } else {
216 auto& json = result.response.value();
217 auto const isForwarded = json.contains("forwarded") &&
218 json.at("forwarded").is_bool() && json.at("forwarded").as_bool();
219
220 // This can still technically be an error. Clio counts forwarded requests
221 // as successful.
222 rpcEngine_->notifyComplete(*context, us, isForwarded);
223
224 if (isForwarded)
225 json.erase("forwarded");
226
227 // if the result is forwarded - just use it as is
228 // if forwarded request has error, for http, error should be in "result"; for ws,
229 // error should be at top
230 if (isForwarded && (json.contains(JS(result)) || connection->upgraded)) {
231 for (auto const& [k, v] : json)
232 response.insert_or_assign(k, v);
233 } else {
234 response[JS(result)] = json;
235 }
236
237 if (isForwarded)
238 response["forwarded"] = true;
239
240 // for ws there is an additional field "status" in the response,
241 // otherwise the "status" is in the "result" field
242 if (connection->upgraded) {
243 auto const appendFieldIfExist = [&](auto const& field) {
244 if (request.contains(field) and not request.at(field).is_null())
245 response[field] = request.at(field);
246 };
247
248 appendFieldIfExist(JS(id));
249 appendFieldIfExist(JS(api_version));
250
251 if (!response.contains(JS(error)))
252 response[JS(status)] = JS(success);
253
254 response[JS(type)] = JS(response);
255 } else {
256 if (response.contains(JS(result)) &&
257 !response[JS(result)].as_object().contains(JS(error)))
258 response[JS(result)].as_object()[JS(status)] = JS(success);
259 }
260 }
261
262 boost::json::array warnings = std::move(result.warnings);
263 warnings.emplace_back(rpc::makeWarning(rpc::WarningCode::WarnRpcClio));
264
265 if (etl_->lastCloseAgeSeconds() >= 60)
266 warnings.emplace_back(rpc::makeWarning(rpc::WarningCode::WarnRpcOutdated));
267
268 response["warnings"] = warnings;
269 connection->send(boost::json::serialize(response));
270 } catch (std::exception const& ex) {
271 // note: while we are catching this in buildResponse too, this is here to make sure
272 // that any other code that may throw is outside of buildResponse is also worked around.
273 LOG(perfLog_.error()) << connection->tag() << "Caught exception: " << ex.what();
274 LOG(log_.error()) << connection->tag() << "Caught exception: " << ex.what();
275
276 rpcEngine_->notifyInternalError();
277 web::impl::ErrorHelper(connection, std::move(request)).sendInternalError();
278
279 return;
280 }
281 }
282
283 [[nodiscard]] bool
284 shouldReplaceParams(boost::json::object const& req) const
285 {
286 auto const hasParams = req.contains(JS(params));
287 auto const paramsIsArray = hasParams and req.at(JS(params)).is_array();
288 auto const paramsIsEmptyString =
289 hasParams and req.at(JS(params)).is_string() and req.at(JS(params)).as_string().empty();
290 auto const paramsIsEmptyObject =
291 hasParams and req.at(JS(params)).is_object() and req.at(JS(params)).as_object().empty();
292 auto const paramsIsNull = hasParams and req.at(JS(params)).is_null();
293 auto const arrayIsEmpty = paramsIsArray and req.at(JS(params)).as_array().empty();
294 auto const arrayIsNotEmpty = paramsIsArray and not req.at(JS(params)).as_array().empty();
295 auto const firstArgIsNull =
296 arrayIsNotEmpty and req.at(JS(params)).as_array().at(0).is_null();
297 auto const firstArgIsEmptyString = arrayIsNotEmpty and
298 req.at(JS(params)).as_array().at(0).is_string() and
299 req.at(JS(params)).as_array().at(0).as_string().empty();
300
301 // Note: all this compatibility dance is to match `rippled` as close as possible
302 return not hasParams or paramsIsEmptyString or paramsIsNull or paramsIsEmptyObject or
303 arrayIsEmpty or firstArgIsEmptyString or firstArgIsNull;
304 }
305};
306
307} // namespace web
Definition APIVersionParser.hpp:15
A simple thread-safe logger for the channel specified in the constructor.
Definition Logger.hpp:110
Pump info(std::source_location const &loc=std::source_location::current()) const
Interface for logging at Severity::NFO severity.
Definition Logger.cpp:499
A factory for TagDecorator instantiation.
Definition Taggable.hpp:165
TagDecoratorFactory with(ParentType parent) const noexcept
Creates a new tag decorator factory with a bound parent tag decorator.
Definition Taggable.cpp:47
All the config data will be stored and extracted from this class.
Definition ConfigDefinition.hpp:31
RPCServerHandler(util::config::ClioConfigDefinition const &config, std::shared_ptr< BackendInterface const > const &backend, std::shared_ptr< RPCEngineType > const &rpcEngine, std::shared_ptr< etl::ETLServiceInterface const > const &etl, web::dosguard::DOSGuardInterface &dosguard)
Create a new server handler.
Definition RPCServerHandler.hpp:69
void operator()(std::string const &request, std::shared_ptr< web::ConnectionBase > const &connection)
The callback when server receives a request.
Definition RPCServerHandler.hpp:92
The interface of a denial of service guard.
Definition DOSGuardInterface.hpp:27
A helper that attempts to match rippled reporting mode HTTP errors as close as possible.
Definition ErrorHandling.hpp:26
This namespace contains everything to do with the ETL and ETL sources.
Definition AmendmentBlockHandlerInterface.hpp:6
std::expected< web::Context, Status > makeWsContext(boost::asio::yield_context yc, boost::json::object const &request, web::SubscriptionContextPtr session, util::TagDecoratorFactory const &tagFactory, data::LedgerRange const &range, std::string const &clientIp, std::reference_wrapper< APIVersionParser const > apiVersionParser, bool isAdmin)
A factory function that creates a Websocket context.
Definition Factories.cpp:28
void logDuration(boost::json::object const &request, util::BaseTagDecorator const &tag, DurationType const &dur)
Log the duration of the request processing.
Definition RPCHelpers.hpp:844
std::expected< web::Context, Status > makeHttpContext(boost::asio::yield_context yc, boost::json::object const &request, util::TagDecoratorFactory const &tagFactory, data::LedgerRange const &range, std::string const &clientIp, std::reference_wrapper< APIVersionParser const > apiVersionParser, bool const isAdmin)
A factory function that creates a HTTP context.
Definition Factories.cpp:63
boost::json::object removeSecret(boost::json::object const &object)
Removes any detected secret information from a response JSON object.
Definition JsonUtils.hpp:55
auto timed(FnType &&func)
Profiler function to measure the time a function execution consumes.
Definition Profiler.hpp:21
Denial of service protection: rate limiting, IP whitelisting and request weighting.
Definition DOSGuard.cpp:22
This namespace implements the web server and related components.
Definition Types.hpp:23