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