3#include "data/BackendInterface.hpp"
7#include "rpc/WorkQueue.hpp"
8#include "rpc/common/HandlerProvider.hpp"
9#include "rpc/common/Types.hpp"
10#include "rpc/common/impl/ForwardingProxy.hpp"
11#include "util/ResponseExpirationCache.hpp"
12#include "util/log/Logger.hpp"
13#include "web/Context.hpp"
14#include "web/dosguard/DOSGuardInterface.hpp"
16#include <boost/asio/spawn.hpp>
17#include <boost/iterator/transform_iterator.hpp>
18#include <boost/json.hpp>
19#include <boost/json/object.hpp>
20#include <fmt/format.h>
21#include <xrpl/protocol/ErrorCodes.h>
30#include <unordered_set>
43template <
typename CountersType>
48 std::shared_ptr<BackendInterface> backend_;
49 std::reference_wrapper<web::dosguard::DOSGuardInterface const> dosGuard_;
50 std::reference_wrapper<WorkQueue> workQueue_;
51 std::reference_wrapper<CountersType> counters_;
53 std::shared_ptr<HandlerProvider const> handlerProvider_;
57 std::optional<util::ResponseExpirationCache> responseCache_;
73 std::shared_ptr<BackendInterface> backend,
74 std::shared_ptr<etl::LoadBalancerInterface>
const& balancer,
77 CountersType& counters,
78 std::shared_ptr<HandlerProvider const>
const& handlerProvider
80 : backend_{std::move(backend)}
81 , dosGuard_{std::cref(dosGuard)}
82 , workQueue_{std::ref(workQueue)}
83 , counters_{std::ref(counters)}
84 , handlerProvider_{handlerProvider}
85 , forwardingProxy_{balancer, counters, handlerProvider}
88 auto const cacheTimeout = config.
get<
float>(
"rpc.cache_timeout");
90 if (cacheTimeout > 0.f) {
91 LOG(log_.info()) << fmt::format(
"Init RPC Cache, timeout: {} seconds", cacheTimeout);
93 responseCache_.emplace(
95 std::unordered_set<std::string>{
"server_info"}
112 static std::shared_ptr<RPCEngine>
115 std::shared_ptr<BackendInterface>
const& backend,
116 std::shared_ptr<etl::LoadBalancerInterface>
const& balancer,
119 CountersType& counters,
120 std::shared_ptr<HandlerProvider const>
const& handlerProvider
123 return std::make_shared<RPCEngine>(
124 config, backend, balancer, dosGuard, workQueue, counters, handlerProvider
137 if (forwardingProxy_.shouldForward(ctx)) {
140 return Result{Status{XrpldError::RpcNoPermission}};
142 return forwardingProxy_.forward(ctx);
145 if (not ctx.
isAdmin and responseCache_) {
146 if (
auto res = responseCache_->get(ctx.
method, ctx.
params); res.has_value())
147 return Result{*std::move(res)};
150 if (backend_->isTooBusy()) {
151 LOG(log_.error()) <<
"Database is too busy. Rejecting request";
153 return Result{Status{XrpldError::RpcTooBusy}};
156 auto const method = handlerProvider_->getHandler(ctx.
method);
159 return Result{Status{XrpldError::RpcUnknownCommand}};
163 LOG(perfLog_.debug()) << ctx.
tag() <<
" start executing rpc `" << ctx.
method <<
'`';
172 auto v = method->process(ctx.
params, context);
174 LOG(perfLog_.debug()) << ctx.
tag() <<
" finish executing rpc `" << ctx.
method <<
'`';
178 }
else if (not ctx.
isAdmin and responseCache_) {
179 responseCache_->put(ctx.
method, ctx.
params, v.result->as_object());
182 return Result{std::move(v)};
184 LOG(log_.error()) <<
"Database error: " << t.
what();
187 return Result{Status{XrpldError::RpcTooBusy}};
188 }
catch (std::exception
const& ex) {
189 LOG(log_.error()) << ctx.
tag() <<
"Caught exception: " << ex.what();
192 return Result{Status{XrpldError::RpcInternal}};
204 template <
typename FnType>
206 post(FnType&& func, std::string
const& ip)
208 return workQueue_.get().postCoro(
209 std::forward<FnType>(func), dosGuard_.get().isWhiteListed(ip)
223 std::chrono::microseconds
const& duration,
227 if (validHandler(context.
method)) {
228 counters_.get().rpcComplete(context.
method, duration);
229 if (not isForwarded) {
244 counters_.get().recordLedgerRequest(params, currentLedgerSequence);
259 if (validHandler(method))
260 counters_.get().rpcFailed(method);
273 if (validHandler(method))
274 counters_.get().rpcErrored(method);
283 counters_.get().onTooBusy();
294 counters_.get().onNotReady();
303 counters_.get().onBadSyntax();
313 counters_.get().onUnknownCommand();
322 counters_.get().onInternalError();
327 validHandler(std::string
const& method)
const
329 return handlerProvider_->contains(method) || forwardingProxy_.isProxied(method);
335 if (backend_->isTooBusy()) {
336 LOG(log_.
error()) <<
"Database is too busy. Rejecting request";
338 return Result{Status{XrpldError::RpcTooBusy}};
341 auto const method = handlerProvider_->getHandler(ctx.
method);
344 return Result{Status{XrpldError::RpcUnknownCommand}};
348 LOG(perfLog_.debug()) << ctx.
tag() <<
" start executing rpc `" << ctx.
method <<
'`';
350 auto const context = Context{
357 auto v = method->process(ctx.
params, context);
359 LOG(perfLog_.debug()) << ctx.
tag() <<
" finish executing rpc `" << ctx.
method <<
'`';
365 return Result{std::move(v)};
366 }
catch (data::DatabaseError
const& t) {
367 LOG(log_.error()) <<
"Database error: " << t.
what();
370 return Result{Status{XrpldError::RpcTooBusy}};
371 }
catch (std::exception
const& ex) {
372 LOG(log_.error()) << ctx.
tag() <<
"Caught exception: " << ex.what();
375 return Result{Status{XrpldError::RpcInternal}};
Represents a transient database error that the caller should retry.
Definition BackendInterface.hpp:41
char const * what() const noexcept override
Definition BackendInterface.hpp:60
void notifyNotReady()
Notify the system that the RPC system was not ready to handle an incoming request.
Definition RPCEngine.hpp:292
void notifyInternalError()
Notify the system that the incoming request lead to an internal error (unrecoverable).
Definition RPCEngine.hpp:320
void notifyErrored(std::string const &method)
Notify the system that specified method failed due to some unrecoverable error.
Definition RPCEngine.hpp:271
void notifyUnknownCommand()
Notify the system that the incoming request specified an unknown/unsupported method/command.
Definition RPCEngine.hpp:311
static std::shared_ptr< RPCEngine > makeRPCEngine(util::config::ClioConfigDefinition const &config, std::shared_ptr< BackendInterface > const &backend, std::shared_ptr< etl::LoadBalancerInterface > const &balancer, web::dosguard::DOSGuardInterface const &dosGuard, WorkQueue &workQueue, CountersType &counters, std::shared_ptr< HandlerProvider const > const &handlerProvider)
Factory function to create a new instance of the RPC engine.
Definition RPCEngine.hpp:113
RPCEngine(util::config::ClioConfigDefinition const &config, std::shared_ptr< BackendInterface > backend, std::shared_ptr< etl::LoadBalancerInterface > const &balancer, web::dosguard::DOSGuardInterface const &dosGuard, WorkQueue &workQueue, CountersType &counters, std::shared_ptr< HandlerProvider const > const &handlerProvider)
Construct a new RPCEngine object.
Definition RPCEngine.hpp:71
void notifyBadSyntax()
Notify the system that the incoming request did not specify the RPC method/command.
Definition RPCEngine.hpp:301
void recordLedgerMetrics(boost::json::object const ¶ms, std::uint32_t currentLedgerSequence)
Record ledger request metrics.
Definition RPCEngine.hpp:242
void notifyFailed(std::string const &method)
Notify the system that specified method failed to execute due to a recoverable user error.
Definition RPCEngine.hpp:256
void notifyComplete(web::Context const &context, std::chrono::microseconds const &duration, bool isForwarded)
Notify the system that specified method was executed and record ledger metrics.
Definition RPCEngine.hpp:221
void notifyTooBusy()
Notify the system that the RPC system is too busy to handle an incoming request.
Definition RPCEngine.hpp:281
Result buildResponse(web::Context const &ctx)
Main request processor routine.
Definition RPCEngine.hpp:135
bool post(FnType &&func, std::string const &ip)
Used to schedule request processing onto the work queue.
Definition RPCEngine.hpp:206
An asynchronous, thread-safe queue for RPC requests.
Definition WorkQueue.hpp:43
Definition ForwardingProxy.hpp:22
A simple thread-safe logger for the channel specified in the constructor.
Definition Logger.hpp:110
Pump error(std::source_location const &loc=std::source_location::current()) const
Interface for logging at Severity::ERR severity.
Definition Logger.cpp:509
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
static std::chrono::milliseconds toMilliseconds(float value)
Method to convert a float seconds value to milliseconds.
Definition ConfigDefinition.cpp:109
T get(std::string_view fullKey) const
Returns the specified value of given string if value exists.
Definition ConfigDefinition.hpp:88
The interface of a denial of service guard.
Definition DOSGuardInterface.hpp:27
impl::Result Result
Result of a query.
Definition Types.hpp:26
This namespace contains all the RPC logic and handlers.
Definition AMMHelpers.cpp:17
bool isAdminCmd(std::string const &method, boost::json::object const &request)
Check whether a request requires administrative privileges on rippled side.
Definition RPCHelpers.cpp:1734
std::uint32_t maxSequence
Highest ledger sequence in the range (inclusive).
Definition Types.hpp:248
Context of an RPC call.
Definition Types.hpp:102
Result type used to return responses or error statuses to the Webserver subsystem.
Definition Types.hpp:132
Context that is used by the Webserver to pass around information about an incoming request.
Definition Context.hpp:22
SubscriptionContextPtr session
The subscription context of the connection.
Definition Context.hpp:27
std::string clientIp
IP of the peer.
Definition Context.hpp:29
data::LedgerRange range
The ledger range available at the time of the request.
Definition Context.hpp:28
std::uint32_t apiVersion
The api_version parsed from the request.
Definition Context.hpp:25
boost::asio::yield_context yield
The coroutine context the request is handled in.
Definition Context.hpp:23
boost::json::object params
Request's parameters/data as a JSON object.
Definition Context.hpp:26
std::string method
The method/command requested.
Definition Context.hpp:24
bool isAdmin
Whether the peer has admin privileges.
Definition Context.hpp:30