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/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"
23
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>
35
36#include <chrono>
37#include <exception>
38#include <functional>
39#include <memory>
40#include <optional>
41#include <ratio>
42#include <string>
43#include <utility>
44
45namespace web::ng {
46
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_;
60 util::TagDecoratorFactory const tagFactory_;
61 rpc::impl::ProductionAPIVersionParser apiVersionParser_; // can be injected if needed
62
63 util::Logger log_{"RPC"};
64 util::Logger perfLog_{"Performance"};
65
66public:
78 std::shared_ptr<BackendInterface const> const& backend,
79 std::shared_ptr<RPCEngineType> const& rpcEngine,
80 std::shared_ptr<etl::ETLServiceInterface const> const& etl,
82 )
83 : backend_(backend)
84 , rpcEngine_(rpcEngine)
85 , etl_(etl)
86 , dosguard_(dosguard)
87 , tagFactory_(config)
88 , apiVersionParser_(config.getObject("api_version"))
89 {
90 }
91
101 [[nodiscard]] Response
103 Request const& request,
104 ConnectionMetadata const& connectionMetadata,
105 SubscriptionContextPtr subscriptionContext,
106 boost::asio::yield_context yield
107 )
108 {
109 if (not dosguard_.get().isOk(connectionMetadata.ip())) {
110 return makeSlowDownResponse(request, std::nullopt);
111 }
112
113 std::optional<Response> response;
114 util::CoroutineGroup coroutineGroup{yield, 1};
115 auto const onTaskComplete = coroutineGroup.registerForeign(yield);
116 ASSERT(onTaskComplete.has_value(), "Coroutine group can't be full");
117
118 bool const postSuccessful = rpcEngine_->post(
119 [this,
120 &request,
121 &response,
122 &onTaskComplete = *onTaskComplete, // NOLINT(bugprone-unchecked-optional-access)
123 &connectionMetadata,
124 subscriptionContext =
125 std::move(subscriptionContext)](boost::asio::yield_context innerYield) mutable {
126 try {
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();
131 response = impl::ErrorHelper{request}.makeJsonParsingError();
132 if (ec.failed()) {
133 LOG(log_.warn()) << "Error parsing JSON: " << ec.message()
134 << ". For request: " << request.message();
135 } else {
136 LOG(log_.warn())
137 << "Received not a JSON object. For request: " << request.message();
138 }
139 } else {
140 auto parsedObject = std::move(parsedRequest).as_object();
141
142 if (not dosguard_.get().request(connectionMetadata.ip(), parsedObject)) {
143 response = makeSlowDownResponse(request, parsedObject);
144 } else {
145 LOG(perfLog_.debug())
146 << connectionMetadata.tag() << "Adding to work queue";
147
148 if (not connectionMetadata.wasUpgraded() and
149 shouldReplaceParams(parsedObject)) {
150 parsedObject[JS(params)] =
151 boost::json::array({boost::json::object{}});
152 }
153
154 response = handleRequest(
155 innerYield,
156 request,
157 std::move(parsedObject),
158 connectionMetadata,
159 std::move(subscriptionContext)
160 );
161 }
162 }
163 } catch (std::exception const& ex) {
164 LOG(perfLog_.error())
165 << connectionMetadata.tag() << "Caught exception: " << ex.what();
166 rpcEngine_->notifyInternalError();
167 response = impl::ErrorHelper{request}.makeInternalError();
168 }
169
170 // notify the coroutine group that the foreign task is done
171 onTaskComplete();
172 },
173 connectionMetadata.ip()
174 );
175
176 if (not postSuccessful) {
177 // onTaskComplete must be called to notify coroutineGroup that the foreign task is done
178 (*onTaskComplete)(); // NOLINT(bugprone-unchecked-optional-access)
179 rpcEngine_->notifyTooBusy();
180 return impl::ErrorHelper{request}.makeTooBusyError();
181 }
182
183 // Put the coroutine to sleep until the foreign task is done
184 coroutineGroup.asyncWait(yield);
185 ASSERT(response.has_value(), "Woke up coroutine without setting response");
186
187 // NOLINTBEGIN(bugprone-unchecked-optional-access)
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);
191 } else {
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";
195 }
196 }
197
198 return *std::move(response);
199 // NOLINTEND(bugprone-unchecked-optional-access)
200 }
201
202private:
204 handleRequest(
205 boost::asio::yield_context yield,
206 Request const& rawRequest,
207 boost::json::object&& request,
208 ConnectionMetadata const& connectionMetadata,
209 SubscriptionContextPtr subscriptionContext
210 )
211 {
212 LOG(log_.info()) << connectionMetadata.tag()
213 << (connectionMetadata.wasUpgraded() ? "ws" : "http")
214 << " received request from work queue: " << util::removeSecret(request)
215 << " ip = " << connectionMetadata.ip();
216
217 try {
218 auto const range = backend_->fetchLedgerRange();
219 if (!range) {
220 // for error that happened before the handler, we don't attach any warnings
221 rpcEngine_->notifyNotReady();
222 return impl::ErrorHelper{rawRequest, std::move(request)}.makeNotReadyError();
223 }
224
225 auto const context = [&] {
226 if (connectionMetadata.wasUpgraded()) {
227 ASSERT(
228 subscriptionContext != nullptr,
229 "Subscription context must exist for a WS connection"
230 );
231 return rpc::makeWsContext(
232 yield,
233 request,
234 std::move(subscriptionContext),
235 tagFactory_.with(connectionMetadata.tag()),
236 *range,
237 connectionMetadata.ip(),
238 std::cref(apiVersionParser_),
239 connectionMetadata.isAdmin()
240 );
241 }
243 yield,
244 request,
245 tagFactory_.with(connectionMetadata.tag()),
246 *range,
247 connectionMetadata.ip(),
248 std::cref(apiVersionParser_),
249 connectionMetadata.isAdmin()
250 );
251 }();
252
253 if (!context) {
254 auto const err = context.error();
255 LOG(perfLog_.warn())
256 << connectionMetadata.tag() << "Could not create Web context: " << err;
257 LOG(log_.warn()) << connectionMetadata.tag()
258 << "Could not create Web context: " << err;
259
260 // we count all those as BadSyntax - as the WS path would.
261 // Although over HTTP these will yield a 400 status with a plain text response (for
262 // most).
263 rpcEngine_->notifyBadSyntax();
264 return impl::ErrorHelper(rawRequest, std::move(request)).makeError(err);
265 }
266
267 auto [result, timeDiff] =
268 util::timed([&] { return rpcEngine_->buildResponse(*context); });
269
270 auto const us = std::chrono::duration<int, std::milli>(timeDiff);
271 rpc::logDuration(request, context->tag(), us);
272
273 boost::json::object response;
274
275 if (!result.response.has_value()) {
276 // note: error statuses are counted/notified in buildResponse itself
277 response =
278 impl::ErrorHelper(rawRequest, request).composeError(result.response.error());
279 auto const responseStr = boost::json::serialize(response);
280
281 LOG(perfLog_.debug()) << context->tag() << "Encountered error: " << responseStr;
282 LOG(log_.debug()) << context->tag() << "Encountered error: " << responseStr;
283 } else {
284 auto& json = result.response.value();
285 auto const isForwarded = json.contains("forwarded") &&
286 json.at("forwarded").is_bool() && json.at("forwarded").as_bool();
287
288 // This can still technically be an error. Clio counts forwarded requests
289 // as successful.
290 rpcEngine_->notifyComplete(*context, us, isForwarded);
291
292 if (isForwarded)
293 json.erase("forwarded");
294
295 // if the result is forwarded - just use it as is
296 // if forwarded request has error, for http, error should be in "result"; for ws,
297 // error should be at top
298 if (isForwarded &&
299 (json.contains(JS(result)) || connectionMetadata.wasUpgraded())) {
300 for (auto const& [k, v] : json)
301 response.insert_or_assign(k, v);
302 } else {
303 response[JS(result)] = json;
304 }
305
306 if (isForwarded)
307 response["forwarded"] = true;
308
309 // for ws there is an additional field "status" in the response,
310 // otherwise the "status" is in the "result" field
311 if (connectionMetadata.wasUpgraded()) {
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);
315 };
316
317 appendFieldIfExist(JS(id));
318 appendFieldIfExist(JS(api_version));
319
320 if (!response.contains(JS(error)))
321 response[JS(status)] = JS(success);
322
323 response[JS(type)] = JS(response);
324 } else {
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);
328 }
329 }
330
331 boost::json::array warnings = std::move(result.warnings);
332 warnings.emplace_back(rpc::makeWarning(rpc::WarningCode::WarnRpcClio));
333
334 if (etl_->lastCloseAgeSeconds() >= 60)
335 warnings.emplace_back(rpc::makeWarning(rpc::WarningCode::WarnRpcOutdated));
336
337 response["warnings"] = warnings;
338 return Response{boost::beast::http::status::ok, response, rawRequest};
339 } catch (std::exception const& ex) {
340 // note: while we are catching this in buildResponse too, this is here to make sure
341 // that any other code that may throw is outside of buildResponse is also worked around.
342 LOG(perfLog_.error()) << connectionMetadata.tag() << "Caught exception: " << ex.what();
343 LOG(log_.error()) << connectionMetadata.tag() << "Caught exception: " << ex.what();
344
345 rpcEngine_->notifyInternalError();
346 return impl::ErrorHelper(rawRequest, std::move(request)).makeInternalError();
347 }
348 }
349
350 static Response
351 makeSlowDownResponse(Request const& request, std::optional<boost::json::value> requestJson)
352 {
353 auto error = rpc::makeError(rpc::XrpldError::RpcSlowDown);
354
355 if (not request.isHttp()) {
356 try {
357 if (not requestJson.has_value()) {
358 requestJson = boost::json::parse(request.message());
359 }
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();
365 }
366 }
367 return web::ng::Response{boost::beast::http::status::service_unavailable, error, request};
368 }
369
370 [[nodiscard]] bool
371 shouldReplaceParams(boost::json::object const& req) const
372 {
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();
387
388 // Note: all this compatibility dance is to match `rippled` as close as possible
389 return not hasParams or paramsIsEmptyString or paramsIsNull or paramsIsEmptyObject or
390 arrayIsEmpty or firstArgIsEmptyString or firstArgIsNull;
391 }
392};
393
394} // namespace web::ng
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
An interface for a connection metadata class.
Definition Connection.hpp:28
std::string const & ip() const
Get the ip of the client.
Definition Connection.cpp:21
virtual bool wasUpgraded() const =0
Whether the connection was upgraded. Upgraded connections are websocket connections.
bool isAdmin() const
Get whether the client is an admin.
Definition Connection.cpp: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