Clio  develop
The XRP Ledger API server.
Loading...
Searching...
No Matches
RPCEngine.hpp
1#pragma once
2
3#include "data/BackendInterface.hpp"
5#include "rpc/Errors.hpp"
6#include "rpc/RPCHelpers.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"
15
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>
22
23#include <chrono>
24#include <cstdint>
25#include <exception>
26#include <functional>
27#include <memory>
28#include <optional>
29#include <string>
30#include <unordered_set>
31#include <utility>
32
36namespace rpc {
37
43template <typename CountersType>
44class RPCEngine {
45 util::Logger perfLog_{"Performance"};
46 util::Logger log_{"RPC"};
47
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_;
52
53 std::shared_ptr<HandlerProvider const> handlerProvider_;
54
56
57 std::optional<util::ResponseExpirationCache> responseCache_;
58
59public:
73 std::shared_ptr<BackendInterface> backend,
74 std::shared_ptr<etl::LoadBalancerInterface> const& balancer,
76 WorkQueue& workQueue,
77 CountersType& counters,
78 std::shared_ptr<HandlerProvider const> const& handlerProvider
79 )
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}
86 {
87 // Let main thread catch the exception if config type is wrong
88 auto const cacheTimeout = config.get<float>("rpc.cache_timeout");
89
90 if (cacheTimeout > 0.f) {
91 LOG(log_.info()) << fmt::format("Init RPC Cache, timeout: {} seconds", cacheTimeout);
92
93 responseCache_.emplace(
95 std::unordered_set<std::string>{"server_info"}
96 );
97 }
98 }
99
112 static std::shared_ptr<RPCEngine>
115 std::shared_ptr<BackendInterface> const& backend,
116 std::shared_ptr<etl::LoadBalancerInterface> const& balancer,
117 web::dosguard::DOSGuardInterface const& dosGuard,
118 WorkQueue& workQueue,
119 CountersType& counters,
120 std::shared_ptr<HandlerProvider const> const& handlerProvider
121 )
122 {
123 return std::make_shared<RPCEngine>(
124 config, backend, balancer, dosGuard, workQueue, counters, handlerProvider
125 );
126 }
127
134 Result
136 {
137 if (forwardingProxy_.shouldForward(ctx)) {
138 // Disallow forwarding of the admin api, only user api is allowed for security reasons.
139 if (isAdminCmd(ctx.method, ctx.params))
140 return Result{Status{XrpldError::RpcNoPermission}};
141
142 return forwardingProxy_.forward(ctx);
143 }
144
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)};
148 }
149
150 if (backend_->isTooBusy()) {
151 LOG(log_.error()) << "Database is too busy. Rejecting request";
152 notifyTooBusy(); // TODO: should we add ctx.method if we have it?
153 return Result{Status{XrpldError::RpcTooBusy}};
154 }
155
156 auto const method = handlerProvider_->getHandler(ctx.method);
157 if (!method) {
159 return Result{Status{XrpldError::RpcUnknownCommand}};
160 }
161
162 try {
163 LOG(perfLog_.debug()) << ctx.tag() << " start executing rpc `" << ctx.method << '`';
164
165 auto const context = Context{
166 .yield = ctx.yield,
167 .session = ctx.session,
168 .isAdmin = ctx.isAdmin,
169 .clientIp = ctx.clientIp,
170 .apiVersion = ctx.apiVersion,
171 };
172 auto v = method->process(ctx.params, context);
173
174 LOG(perfLog_.debug()) << ctx.tag() << " finish executing rpc `" << ctx.method << '`';
175
176 if (not v) {
178 } else if (not ctx.isAdmin and responseCache_) {
179 responseCache_->put(ctx.method, ctx.params, v.result->as_object());
180 }
181
182 return Result{std::move(v)};
183 } catch (data::DatabaseError const& t) {
184 LOG(log_.error()) << "Database error: " << t.what();
186
187 return Result{Status{XrpldError::RpcTooBusy}};
188 } catch (std::exception const& ex) {
189 LOG(log_.error()) << ctx.tag() << "Caught exception: " << ex.what();
191
192 return Result{Status{XrpldError::RpcInternal}};
193 }
194 }
195
204 template <typename FnType>
205 bool
206 post(FnType&& func, std::string const& ip)
207 {
208 return workQueue_.get().postCoro(
209 std::forward<FnType>(func), dosGuard_.get().isWhiteListed(ip)
210 );
211 }
212
220 void
222 web::Context const& context,
223 std::chrono::microseconds const& duration,
224 bool isForwarded
225 )
226 {
227 if (validHandler(context.method)) {
228 counters_.get().rpcComplete(context.method, duration);
229 if (not isForwarded) {
230 counters_.get().recordLedgerRequest(context.params, context.range.maxSequence);
231 }
232 }
233 }
234
241 void
242 recordLedgerMetrics(boost::json::object const& params, std::uint32_t currentLedgerSequence)
243 {
244 counters_.get().recordLedgerRequest(params, currentLedgerSequence);
245 }
246
255 void
256 notifyFailed(std::string const& method)
257 {
258 // FIXME: seems like this is not used?
259 if (validHandler(method))
260 counters_.get().rpcFailed(method);
261 }
262
270 void
271 notifyErrored(std::string const& method)
272 {
273 if (validHandler(method))
274 counters_.get().rpcErrored(method);
275 }
276
280 void
282 {
283 counters_.get().onTooBusy();
284 }
285
291 void
293 {
294 counters_.get().onNotReady();
295 }
296
300 void
302 {
303 counters_.get().onBadSyntax();
304 }
305
310 void
312 {
313 counters_.get().onUnknownCommand();
314 }
315
319 void
321 {
322 counters_.get().onInternalError();
323 }
324
325private:
326 [[nodiscard]] bool
327 validHandler(std::string const& method) const
328 {
329 return handlerProvider_->contains(method) || forwardingProxy_.isProxied(method);
330 }
331
332 Result
333 buildResponseImpl(web::Context const& ctx)
334 {
335 if (backend_->isTooBusy()) {
336 LOG(log_.error()) << "Database is too busy. Rejecting request";
337 notifyTooBusy(); // TODO: should we add ctx.method if we have it?
338 return Result{Status{XrpldError::RpcTooBusy}};
339 }
340
341 auto const method = handlerProvider_->getHandler(ctx.method);
342 if (!method) {
344 return Result{Status{XrpldError::RpcUnknownCommand}};
345 }
346
347 try {
348 LOG(perfLog_.debug()) << ctx.tag() << " start executing rpc `" << ctx.method << '`';
349
350 auto const context = Context{
351 .yield = ctx.yield,
352 .session = ctx.session,
353 .isAdmin = ctx.isAdmin,
354 .clientIp = ctx.clientIp,
355 .apiVersion = ctx.apiVersion,
356 };
357 auto v = method->process(ctx.params, context);
358
359 LOG(perfLog_.debug()) << ctx.tag() << " finish executing rpc `" << ctx.method << '`';
360
361 if (not v) {
363 }
364
365 return Result{std::move(v)};
366 } catch (data::DatabaseError const& t) {
367 LOG(log_.error()) << "Database error: " << t.what();
369
370 return Result{Status{XrpldError::RpcTooBusy}};
371 } catch (std::exception const& ex) {
372 LOG(log_.error()) << ctx.tag() << "Caught exception: " << ex.what();
374
375 return Result{Status{XrpldError::RpcInternal}};
376 }
377 }
378};
379
380} // namespace rpc
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 &params, 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