3#include "data/BackendInterface.hpp"
4#include "etl/ETLServiceInterface.hpp"
6#include "rpc/Factories.hpp"
9#include "rpc/common/impl/APIVersionParser.hpp"
10#include "util/Assert.hpp"
11#include "util/CoroutineGroup.hpp"
12#include "util/JsonUtils.hpp"
13#include "util/Profiler.hpp"
14#include "util/Taggable.hpp"
15#include "util/log/Logger.hpp"
16#include "web/LoadWarning.hpp"
17#include "web/SubscriptionContextInterface.hpp"
18#include "web/dosguard/DOSGuardInterface.hpp"
19#include "web/ng/Connection.hpp"
20#include "web/ng/Request.hpp"
21#include "web/ng/Response.hpp"
22#include "web/ng/impl/ErrorHandling.hpp"
24#include <boost/asio/spawn.hpp>
25#include <boost/asio/steady_timer.hpp>
26#include <boost/beast/core/error.hpp>
27#include <boost/beast/http/status.hpp>
28#include <boost/json/array.hpp>
29#include <boost/json/object.hpp>
30#include <boost/json/parse.hpp>
31#include <boost/json/serialize.hpp>
32#include <boost/system/system_error.hpp>
33#include <xrpl/protocol/jss.h>
51template <
typename RPCEngineType>
53 std::shared_ptr<BackendInterface const>
const backend_;
54 std::shared_ptr<RPCEngineType>
const rpcEngine_;
55 std::shared_ptr<etl::ETLServiceInterface const>
const etl_;
56 std::reference_wrapper<dosguard::DOSGuardInterface> dosguard_;
75 std::shared_ptr<BackendInterface const>
const& backend,
76 std::shared_ptr<RPCEngineType>
const& rpcEngine,
77 std::shared_ptr<etl::ETLServiceInterface const>
const& etl,
81 , rpcEngine_(rpcEngine)
85 , apiVersionParser_(config.getObject(
"api_version"))
103 boost::asio::yield_context yield
106 if (not dosguard_.get().isOk(connectionMetadata.
ip())) {
107 return makeSlowDownResponse(request, std::nullopt);
110 std::optional<Response> response;
113 ASSERT(onTaskComplete.has_value(),
"Coroutine group can't be full");
115 bool const postSuccessful = rpcEngine_->post(
119 &onTaskComplete = *onTaskComplete,
121 subscriptionContext =
122 std::move(subscriptionContext)](boost::asio::yield_context innerYield)
mutable {
124 boost::system::error_code ec;
125 auto parsedRequest = boost::json::parse(request.
message(), ec);
126 if (ec.failed() or not parsedRequest.is_object()) {
127 rpcEngine_->notifyBadSyntax();
130 LOG(log_.warn()) <<
"Error parsing JSON: " << ec.message()
131 <<
". For request: " << request.
message();
134 <<
"Received not a JSON object. For request: " << request.
message();
137 auto parsedObject = std::move(parsedRequest).as_object();
139 if (not dosguard_.get().request(connectionMetadata.
ip(), parsedObject)) {
140 response = makeSlowDownResponse(request, parsedObject);
142 LOG(perfLog_.debug())
143 << connectionMetadata.
tag() <<
"Adding to work queue";
146 shouldReplaceParams(parsedObject)) {
147 parsedObject[JS(params)] =
148 boost::json::array({boost::json::object{}});
151 response = handleRequest(
154 std::move(parsedObject),
156 std::move(subscriptionContext)
160 }
catch (std::exception
const& ex) {
161 LOG(perfLog_.error())
162 << connectionMetadata.
tag() <<
"Caught exception: " << ex.what();
163 rpcEngine_->notifyInternalError();
170 connectionMetadata.
ip()
173 if (not postSuccessful) {
176 rpcEngine_->notifyTooBusy();
182 ASSERT(response.has_value(),
"Woke up coroutine without setting response");
185 if (not dosguard_.get().add(connectionMetadata.
ip(), response->message().size())) {
186 if (
auto const warned =
withLoadWarning(response->message()); warned.has_value()) {
187 response->setMessage(*warned);
189 LOG(log_.debug()) << connectionMetadata.
tag()
190 <<
"Rate limit reached but the response body is not a JSON "
191 "object; sending it without a load warning";
195 return *std::move(response);
202 boost::asio::yield_context yield,
204 boost::json::object&& request,
209 LOG(log_.
info()) << connectionMetadata.
tag()
210 << (connectionMetadata.
wasUpgraded() ?
"ws" :
"http")
212 <<
" ip = " << connectionMetadata.
ip();
215 auto const range = backend_->fetchLedgerRange();
218 rpcEngine_->notifyNotReady();
222 auto const context = [&] {
225 subscriptionContext !=
nullptr,
226 "Subscription context must exist for a WS connection"
231 std::move(subscriptionContext),
232 tagFactory_.
with(connectionMetadata.
tag()),
234 connectionMetadata.
ip(),
235 std::cref(apiVersionParser_),
242 tagFactory_.with(connectionMetadata.
tag()),
244 connectionMetadata.
ip(),
245 std::cref(apiVersionParser_),
251 auto const err = context.error();
253 << connectionMetadata.
tag() <<
"Could not create Web context: " << err;
254 LOG(log_.warn()) << connectionMetadata.
tag()
255 <<
"Could not create Web context: " << err;
260 rpcEngine_->notifyBadSyntax();
261 return impl::ErrorHelper(rawRequest, std::move(request)).makeError(err);
264 auto [result, timeDiff] =
265 util::timed([&]() {
return rpcEngine_->buildResponse(*context); });
267 auto us = std::chrono::duration<int, std::milli>(timeDiff);
270 boost::json::object response;
272 if (!result.response.has_value()) {
275 impl::ErrorHelper(rawRequest, request).composeError(result.response.error());
276 auto const responseStr = boost::json::serialize(response);
278 LOG(perfLog_.debug()) << context->tag() <<
"Encountered error: " << responseStr;
279 LOG(log_.debug()) << context->tag() <<
"Encountered error: " << responseStr;
281 auto& json = result.response.value();
282 auto const isForwarded = json.contains(
"forwarded") &&
283 json.at(
"forwarded").is_bool() && json.at(
"forwarded").as_bool();
287 rpcEngine_->notifyComplete(*context, us, isForwarded);
290 json.erase(
"forwarded");
296 (json.contains(JS(result)) || connectionMetadata.
wasUpgraded())) {
297 for (
auto const& [k, v] : json)
298 response.insert_or_assign(k, v);
300 response[JS(result)] = json;
304 response[
"forwarded"] =
true;
309 auto const appendFieldIfExist = [&](
auto const& field) {
310 if (request.contains(field) and not request.at(field).is_null())
311 response[field] = request.at(field);
314 appendFieldIfExist(JS(
id));
315 appendFieldIfExist(JS(api_version));
317 if (!response.contains(JS(error)))
318 response[JS(status)] = JS(success);
320 response[JS(type)] = JS(response);
322 if (response.contains(JS(result)) &&
323 !response[JS(result)].as_object().contains(JS(error)))
324 response[JS(result)].as_object()[JS(status)] = JS(success);
328 boost::json::array warnings = std::move(result.warnings);
329 warnings.emplace_back(rpc::makeWarning(rpc::WarningCode::WarnRpcClio));
331 if (etl_->lastCloseAgeSeconds() >= 60)
332 warnings.emplace_back(rpc::makeWarning(rpc::WarningCode::WarnRpcOutdated));
334 response[
"warnings"] = warnings;
335 return Response{boost::beast::http::status::ok, response, rawRequest};
336 }
catch (std::exception
const& ex) {
339 LOG(perfLog_.error()) << connectionMetadata.
tag() <<
"Caught exception: " << ex.what();
340 LOG(log_.error()) << connectionMetadata.
tag() <<
"Caught exception: " << ex.what();
342 rpcEngine_->notifyInternalError();
343 return impl::ErrorHelper(rawRequest, std::move(request)).makeInternalError();
348 makeSlowDownResponse(Request
const& request, std::optional<boost::json::value> requestJson)
352 if (not request.isHttp()) {
354 if (not requestJson.has_value()) {
355 requestJson = boost::json::parse(request.message());
357 if (requestJson->is_object() && requestJson->as_object().contains(
"id"))
358 error[
"id"] = requestJson->as_object().at(
"id");
359 error[
"request"] = request.message();
360 }
catch (std::exception
const&) {
361 error[
"request"] = request.message();
364 return web::ng::Response{boost::beast::http::status::service_unavailable, error, request};
368 shouldReplaceParams(boost::json::object
const& req)
const
370 auto const hasParams = req.contains(JS(params));
371 auto const paramsIsArray = hasParams and req.at(JS(params)).is_array();
372 auto const paramsIsEmptyString =
373 hasParams and req.at(JS(params)).is_string() and req.at(JS(params)).as_string().empty();
374 auto const paramsIsEmptyObject =
375 hasParams and req.at(JS(params)).is_object() and req.at(JS(params)).as_object().empty();
376 auto const paramsIsNull = hasParams and req.at(JS(params)).is_null();
377 auto const arrayIsEmpty = paramsIsArray and req.at(JS(params)).as_array().empty();
378 auto const arrayIsNotEmpty = paramsIsArray and not req.at(JS(params)).as_array().empty();
379 auto const firstArgIsNull =
380 arrayIsNotEmpty and req.at(JS(params)).as_array().at(0).is_null();
381 auto const firstArgIsEmptyString = arrayIsNotEmpty and
382 req.at(JS(params)).as_array().at(0).is_string() and
383 req.at(JS(params)).as_array().at(0).as_string().empty();
386 return not hasParams or paramsIsEmptyString or paramsIsNull or paramsIsEmptyObject or
387 arrayIsEmpty or firstArgIsEmptyString or firstArgIsNull;
Definition APIVersionParser.hpp:15
CoroutineGroup is a helper class to manage a group of coroutines. It allows to spawn multiple corouti...
Definition CoroutineGroup.hpp:18
std::optional< std::function< void()> > registerForeign(boost::asio::yield_context yield)
Register a foreign coroutine this group should wait for.
Definition CoroutineGroup.cpp:48
void asyncWait(boost::asio::yield_context yield)
Wait for all the coroutines in the group to finish.
Definition CoroutineGroup.cpp:60
A simple thread-safe logger for the channel specified in the constructor.
Definition Logger.hpp:78
Pump info(std::source_location const &loc=std::source_location::current()) const
Interface for logging at Severity::NFO severity.
Definition Logger.cpp:502
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
BaseTagDecorator const & tag() const
Getter for tag decorator.
Definition Taggable.hpp:264
All the config data will be stored and extracted from this class.
Definition ConfigDefinition.hpp:31
The interface of a denial of service guard.
Definition DOSGuardInterface.hpp:27
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, dosguard::DOSGuardInterface &dosguard)
Create a new server handler.
Definition RPCServerHandler.hpp:73
Response operator()(Request const &request, ConnectionMetadata const &connectionMetadata, SubscriptionContextPtr subscriptionContext, boost::asio::yield_context yield)
The callback when server receives a request.
Definition RPCServerHandler.hpp:99
Represents an HTTP or WebSocket request.
Definition Request.hpp:18
std::string_view message() const
Get the body (in case of an HTTP request) or the message (in case of a WebSocket request).
Definition Request.cpp:74
Represents an HTTP or Websocket response.
Definition Response.hpp:21
A helper that attempts to match rippled reporting mode HTTP errors as close as possible.
Definition ErrorHandling.hpp:22
Response makeTooBusyError() const
Make a response for when the server is too busy.
Definition ErrorHandling.cpp:127
Response makeJsonParsingError() const
Make a response when json parsing fails.
Definition ErrorHandling.cpp:145
Response makeNotReadyError() const
Make a response for when the server is not ready.
Definition ErrorHandling.cpp:121
Response makeInternalError() const
Make an internal error response.
Definition ErrorHandling.cpp:111
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:838
boost::json::object makeError(RippledError err, std::optional< std::string_view > customError, std::optional< std::string_view > customMessage)
Generate JSON from a rpc::RippledError.
Definition Errors.cpp:172
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
std::shared_ptr< SubscriptionContextInterface > SubscriptionContextPtr
An alias for shared pointer to a SubscriptionContextInterface.
Definition SubscriptionContextInterface.hpp:64
std::optional< boost::json::object > withLoadWarning(std::string_view message)
Parse a serialized response body and attach the DOSGuard "load" warning to it.
Definition LoadWarning.hpp:32