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 <rpcspec/backends/BoostJson.hpp>
34#include <xrpl/protocol/jss.h>
54template <
typename RPCEngineType>
56 std::shared_ptr<BackendInterface const>
const backend_;
57 std::shared_ptr<RPCEngineType>
const rpcEngine_;
58 std::shared_ptr<etl::ETLServiceInterface const>
const etl_;
59 std::reference_wrapper<dosguard::DOSGuardInterface> dosguard_;
78 std::shared_ptr<BackendInterface const>
const& backend,
79 std::shared_ptr<RPCEngineType>
const& rpcEngine,
80 std::shared_ptr<etl::ETLServiceInterface const>
const&
etl,
84 , rpcEngine_(rpcEngine)
88 , apiVersionParser_(config.getObject(
"api_version"))
106 boost::asio::yield_context yield
109 if (not dosguard_.get().isOk(connectionMetadata.
ip())) {
110 return makeSlowDownResponse(request, std::nullopt);
113 std::optional<Response> response;
116 ASSERT(onTaskComplete.has_value(),
"Coroutine group can't be full");
118 bool const postSuccessful = rpcEngine_->post(
122 &onTaskComplete = *onTaskComplete,
124 subscriptionContext =
125 std::move(subscriptionContext)](boost::asio::yield_context innerYield)
mutable {
127 boost::system::error_code ec;
128 auto parsedRequest = boost::json::parse(request.
message(), ec);
129 if (ec.failed() or not parsedRequest.is_object()) {
130 rpcEngine_->notifyBadSyntax();
133 LOG(log_.warn()) <<
"Error parsing JSON: " << ec.message()
134 <<
". For request: " << request.
message();
137 <<
"Received not a JSON object. For request: " << request.
message();
140 auto parsedObject = std::move(parsedRequest).as_object();
142 if (not dosguard_.get().request(connectionMetadata.
ip(), parsedObject)) {
143 response = makeSlowDownResponse(request, parsedObject);
145 LOG(perfLog_.debug())
146 << connectionMetadata.
tag() <<
"Adding to work queue";
149 shouldReplaceParams(parsedObject)) {
150 parsedObject[JS(params)] =
151 boost::json::array({boost::json::object{}});
154 response = handleRequest(
157 std::move(parsedObject),
159 std::move(subscriptionContext)
163 }
catch (std::exception
const& ex) {
164 LOG(perfLog_.error())
165 << connectionMetadata.
tag() <<
"Caught exception: " << ex.what();
166 rpcEngine_->notifyInternalError();
173 connectionMetadata.
ip()
176 if (not postSuccessful) {
179 rpcEngine_->notifyTooBusy();
185 ASSERT(response.has_value(),
"Woke up coroutine without setting response");
188 if (not dosguard_.get().add(connectionMetadata.
ip(), response->message().size())) {
189 if (
auto const warned =
withLoadWarning(response->message()); warned.has_value()) {
190 response->setMessage(*warned);
192 LOG(log_.debug()) << connectionMetadata.
tag()
193 <<
"Rate limit reached but the response body is not a JSON "
194 "object; sending it without a load warning";
198 return *std::move(response);
205 boost::asio::yield_context yield,
207 boost::json::object&& request,
212 LOG(log_.
info()) << connectionMetadata.
tag()
213 << (connectionMetadata.
wasUpgraded() ?
"ws" :
"http")
215 <<
" ip = " << connectionMetadata.
ip();
218 auto const range = backend_->fetchLedgerRange();
221 rpcEngine_->notifyNotReady();
225 auto const context = [&] {
228 subscriptionContext !=
nullptr,
229 "Subscription context must exist for a WS connection"
234 std::move(subscriptionContext),
235 tagFactory_.
with(connectionMetadata.
tag()),
237 connectionMetadata.
ip(),
238 std::cref(apiVersionParser_),
245 tagFactory_.with(connectionMetadata.
tag()),
247 connectionMetadata.
ip(),
248 std::cref(apiVersionParser_),
254 auto const err = context.error();
256 << connectionMetadata.
tag() <<
"Could not create Web context: " << err;
257 LOG(log_.warn()) << connectionMetadata.
tag()
258 <<
"Could not create Web context: " << err;
263 rpcEngine_->notifyBadSyntax();
264 return impl::ErrorHelper(rawRequest, std::move(request)).makeError(err);
267 auto [result, timeDiff] =
268 util::timed([&] {
return rpcEngine_->buildResponse(*context); });
270 auto const us = std::chrono::duration<int, std::milli>(timeDiff);
273 boost::json::object response;
275 if (!result.response.has_value()) {
278 impl::ErrorHelper(rawRequest, request).composeError(result.response.error());
279 auto const responseStr = boost::json::serialize(response);
281 LOG(perfLog_.debug()) << context->tag() <<
"Encountered error: " << responseStr;
282 LOG(log_.debug()) << context->tag() <<
"Encountered error: " << responseStr;
284 auto& json = result.response.value();
285 auto const isForwarded = json.contains(
"forwarded") &&
286 json.at(
"forwarded").is_bool() && json.at(
"forwarded").as_bool();
290 rpcEngine_->notifyComplete(*context, us, isForwarded);
293 json.erase(
"forwarded");
299 (json.contains(JS(result)) || connectionMetadata.
wasUpgraded())) {
300 for (
auto const& [k, v] : json)
301 response.insert_or_assign(k, v);
303 response[JS(result)] = json;
307 response[
"forwarded"] =
true;
312 auto const appendFieldIfExist = [&](
auto const& field) {
313 if (request.contains(field) and not request.at(field).is_null())
314 response[field] = request.at(field);
317 appendFieldIfExist(JS(
id));
318 appendFieldIfExist(JS(api_version));
320 if (!response.contains(JS(error)))
321 response[JS(status)] = JS(success);
323 response[JS(type)] = JS(response);
325 if (response.contains(JS(result)) &&
326 !response[JS(result)].as_object().contains(JS(error)))
327 response[JS(result)].as_object()[JS(status)] = JS(success);
331 boost::json::array warnings = std::move(result.warnings);
332 warnings.emplace_back(rpc::makeWarning(rpc::WarningCode::WarnRpcClio));
334 if (etl_->lastCloseAgeSeconds() >= 60)
335 warnings.emplace_back(rpc::makeWarning(rpc::WarningCode::WarnRpcOutdated));
337 response[
"warnings"] = warnings;
338 return Response{boost::beast::http::status::ok, response, rawRequest};
339 }
catch (std::exception
const& ex) {
342 LOG(perfLog_.error()) << connectionMetadata.
tag() <<
"Caught exception: " << ex.what();
343 LOG(log_.error()) << connectionMetadata.
tag() <<
"Caught exception: " << ex.what();
345 rpcEngine_->notifyInternalError();
346 return impl::ErrorHelper(rawRequest, std::move(request)).makeInternalError();
351 makeSlowDownResponse(Request
const& request, std::optional<boost::json::value> requestJson)
355 if (not request.isHttp()) {
357 if (not requestJson.has_value()) {
358 requestJson = boost::json::parse(request.message());
360 if (requestJson->is_object() && requestJson->as_object().contains(
"id"))
361 error[
"id"] = requestJson->as_object().at(
"id");
362 error[
"request"] = request.message();
363 }
catch (std::exception
const&) {
364 error[
"request"] = request.message();
367 return web::ng::Response{boost::beast::http::status::service_unavailable, error, request};
371 shouldReplaceParams(boost::json::object
const& req)
const
373 auto const hasParams = req.contains(JS(params));
374 auto const paramsIsArray = hasParams and req.at(JS(params)).is_array();
375 auto const paramsIsEmptyString =
376 hasParams and req.at(JS(params)).is_string() and req.at(JS(params)).as_string().empty();
377 auto const paramsIsEmptyObject =
378 hasParams and req.at(JS(params)).is_object() and req.at(JS(params)).as_object().empty();
379 auto const paramsIsNull = hasParams and req.at(JS(params)).is_null();
380 auto const arrayIsEmpty = paramsIsArray and req.at(JS(params)).as_array().empty();
381 auto const arrayIsNotEmpty = paramsIsArray and not req.at(JS(params)).as_array().empty();
382 auto const firstArgIsNull =
383 arrayIsNotEmpty and req.at(JS(params)).as_array().at(0).is_null();
384 auto const firstArgIsEmptyString = arrayIsNotEmpty and
385 req.at(JS(params)).as_array().at(0).is_string() and
386 req.at(JS(params)).as_array().at(0).as_string().empty();
389 return not hasParams or paramsIsEmptyString or paramsIsNull or paramsIsEmptyObject or
390 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: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
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:76
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:102
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:125
Response makeJsonParsingError() const
Make a response when json parsing fails.
Definition ErrorHandling.cpp:141
Response makeNotReadyError() const
Make a response for when the server is not ready.
Definition ErrorHandling.cpp:119
Response makeInternalError() const
Make an internal error response.
Definition ErrorHandling.cpp:111
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
boost::json::object makeError(XrpldError err, std::optional< std::string_view > customError, std::optional< std::string_view > customMessage)
Generate JSON from a rpc::XrpldError.
Definition Errors.cpp:185
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
The next generation web server implementation.
Definition Connection.cpp:10
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:33