xrpld
Loading...
Searching...
No Matches
JSONRPCClient.cpp
1#include <test/jtx/JSONRPCClient.h>
2
3#include <test/jtx/AbstractClient.h>
4
5#include <xrpld/core/Config.h>
6
7#include <xrpl/basics/contract.h>
8#include <xrpl/config/BasicConfig.h>
9#include <xrpl/config/Constants.h>
10#include <xrpl/json/json_reader.h>
11#include <xrpl/json/json_value.h>
12#include <xrpl/json/to_string.h>
13#include <xrpl/protocol/ApiVersion.h>
14#include <xrpl/protocol/JsonRpc.h>
15#include <xrpl/protocol/jss.h>
16#include <xrpl/server/Port.h>
17
18#include <boost/asio/buffer.hpp>
19#include <boost/asio/error.hpp>
20#include <boost/asio/io_context.hpp>
21#include <boost/asio/ip/address_v4.hpp>
22#include <boost/asio/ip/address_v6.hpp>
23#include <boost/asio/ip/tcp.hpp>
24#include <boost/beast/core/multi_buffer.hpp>
25#include <boost/beast/http/dynamic_body.hpp>
26#include <boost/beast/http/error.hpp>
27#include <boost/beast/http/message.hpp>
28#include <boost/beast/http/read.hpp>
29#include <boost/beast/http/string_body.hpp>
30#include <boost/beast/http/verb.hpp>
31#include <boost/beast/http/write.hpp>
32#include <boost/system/system_error.hpp>
33
34#include <algorithm>
35#include <array>
36#include <iostream>
37#include <memory>
38#include <sstream>
39#include <stdexcept>
40#include <string>
41
42namespace xrpl::test {
43
45{
46 static boost::asio::ip::tcp::endpoint
48 {
49 auto& log = std::cerr;
50 ParsedPort common;
51 parsePort(common, cfg[Sections::kServer], log);
52 for (auto const& name : cfg.section(Sections::kServer).values())
53 {
54 if (!cfg.exists(name))
55 continue;
56 ParsedPort pp;
57 parsePort(pp, cfg[name], log);
58 if (not pp.protocol.contains("http"))
59 continue;
60 using namespace boost::asio::ip;
61 if (pp.ip && pp.ip->is_unspecified())
62 {
63 *pp.ip = pp.ip->is_v6() ? address{address_v6::loopback()}
64 : address{address_v4::loopback()};
65 }
66
67 if (!pp.port)
68 Throw<std::runtime_error>("Use fixConfigPorts with auto ports");
69
70 return {*pp.ip, *pp.port}; // NOLINT(bugprone-unchecked-optional-access)
71 }
72 Throw<std::runtime_error>("Missing HTTP port");
73 return {}; // Silence compiler control paths return value warning
74 }
75
76 template <class ConstBufferSequence>
77 static std::string
78 bufferString(ConstBufferSequence const& b)
79 {
80 using namespace boost::asio;
82 s.resize(buffer_size(b));
83 buffer_copy(buffer(&s[0], s.size()), b);
84 return s;
85 }
86
87 boost::asio::ip::tcp::endpoint ep_;
88 boost::asio::io_context ios_;
89 boost::asio::ip::tcp::socket stream_;
90 boost::beast::multi_buffer bin_;
91 boost::beast::multi_buffer bout_;
92 unsigned rpcVersion_;
93
94 bool disconnected_ = false;
95
96 // Errors that mean the persistent keep-alive connection was dropped by the
97 // server (rather than a genuine protocol failure), so the request can be
98 // safely retried on a fresh connection.
99 static bool
100 droppedConnection(boost::system::error_code const& ec)
101 {
102 namespace error = boost::asio::error;
103 static auto const kDroppedConnectionErrors = std::to_array<boost::system::error_code>({
104 boost::beast::http::error::end_of_stream,
105 error::eof,
106 error::connection_reset,
107 error::connection_aborted,
108 error::broken_pipe,
109 error::not_connected,
110 });
111
112 return std::ranges::any_of(
113 kDroppedConnectionErrors,
114 [&ec](boost::system::error_code const& e) { return ec == e; });
115 }
116
117 // Tear down and re-establish the socket to ep_, discarding any buffered
118 // bytes left over from the dropped connection.
119 void
121 {
122 boost::system::error_code ec;
123 stream_.close(ec);
124 bin_.clear();
125 stream_.connect(ep_);
126 }
127
128public:
129 explicit JSONRPCClient(Config const& cfg, unsigned rpcVersion)
130 : ep_(getEndpoint(cfg)), stream_(ios_), rpcVersion_(rpcVersion)
131 {
132 stream_.connect(ep_);
133 }
134
135 // Return value is an Object type with up to three keys:
136 // status
137 // error
138 // result
140 invoke(std::string const& cmd, json::Value const& params) override
141 {
142 using namespace boost::beast::http;
143 using namespace boost::asio;
144 using namespace std::string_literals;
145
146 // Once disconnect() has released the slot, the client must not be
147 // reused (see AbstractClient::disconnect). Refuse rather than let the
148 // failed write/read below trip the reconnect path and silently
149 // re-consume a connection slot, which would defeat disconnectClient().
150 if (disconnected_)
151 Throw<std::logic_error>("JSONRPCClient::invoke called after disconnect()");
152
153 request<string_body> req;
154 req.method(boost::beast::http::verb::post);
155 req.target("/");
156 req.version(11);
157 req.insert("Content-Type", "application/json; charset=UTF-8");
158 {
160 ostr << ep_;
161 req.insert("Host", ostr.str());
162 }
163 {
164 json::Value jr;
165 jr[jss::method] = cmd;
166 if (rpcVersion_ == 2)
167 {
168 jr[jss::jsonrpc] = rpc::kJsonRpcVersion;
169 jr[jss::ripplerpc] = rpc::kRippleRpcVersion2;
170 jr[jss::id] = 5;
171 }
172 if (params)
173 {
174 json::Value& ja = jr[jss::params] = json::ValueType::Array;
175 ja.append(params);
176 }
177 req.body() = to_string(jr);
178 }
179 req.prepare_payload();
180
181 // The client keeps a single keep-alive connection for its whole
182 // lifetime, but the server drops idle localhost connections after a few
183 // seconds (BaseHTTPPeer::kTimeoutSecondsLocal). If a slow gap between
184 // requests let the server close the socket, the write/read here fails
185 // with end_of_stream; reconnect and retry the request exactly once.
186 response<dynamic_body> res;
187 auto const writeAndRead = [&] {
188 write(stream_, req);
189 read(stream_, bin_, res);
190 };
191 try
192 {
193 writeAndRead();
194 }
195 catch (boost::system::system_error const& e)
196 {
197 if (!droppedConnection(e.code()))
198 throw;
199 reconnect();
200 res = {};
201 writeAndRead();
202 }
203
204 json::Reader jr;
205 json::Value jv;
206 jr.parse(bufferString(res.body().data()), jv);
207 if (jv["result"].isMember("error"))
208 jv["error"] = jv["result"]["error"];
209 if (jv["result"].isMember("status"))
210 jv["status"] = jv["result"]["status"];
211 return jv;
212 }
213
214 [[nodiscard]] unsigned
215 version() const override
216 {
217 return rpcVersion_;
218 }
219
220 void
221 disconnect() override
222 {
223 if (disconnected_)
224 return;
225
226 disconnected_ = true;
227
228 boost::system::error_code ec;
229 stream_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
230 stream_.close(ec);
231 }
232};
233
235makeJSONRPCClient(Config const& cfg, unsigned rpcVersion)
236{
237 return std::make_unique<JSONRPCClient>(cfg, rpcVersion);
238}
239
240} // namespace xrpl::test
T any_of(T... args)
Unserialize a JSON document into a Value.
Definition json_reader.h:20
bool parse(std::string const &document, Value &root)
Read a Value from a JSON document.
Represents a JSON value.
Definition json_value.h:121
Value & append(Value const &value)
Append value to array at the end.
Holds unparsed configuration information.
bool exists(std::string const &name) const
Returns true if a section with the given name exists.
Section & section(std::string const &name)
Returns the section with the given name.
std::vector< std::string > const & values() const
Returns all the values in the section.
Definition BasicConfig.h:68
JSONRPCClient(Config const &cfg, unsigned rpcVersion)
static std::string bufferString(ConstBufferSequence const &b)
unsigned version() const override
Get RPC 1.0 or RPC 2.0.
static bool droppedConnection(boost::system::error_code const &ec)
boost::asio::ip::tcp::endpoint ep_
boost::asio::ip::tcp::socket stream_
boost::beast::multi_buffer bout_
boost::beast::multi_buffer bin_
boost::asio::io_context ios_
static boost::asio::ip::tcp::endpoint getEndpoint(BasicConfig const &cfg)
void disconnect() override
Close the client's connection to the server.
json::Value invoke(std::string const &cmd, json::Value const &params) override
Submit a command synchronously.
T contains(T... args)
T make_unique(T... args)
@ Array
array value (ordered list)
Definition json_value.h:32
constexpr std::string_view kRippleRpcVersion2
Definition ApiVersion.h:57
constexpr std::string_view kJsonRpcVersion
Value of the jsonrpc member of a request and of its reply, fixed at "2.0" by the JSON-RPC specificati...
Definition JsonRpc.h:16
std::unique_ptr< AbstractClient > makeJSONRPCClient(Config const &cfg, unsigned rpcVersion)
Returns a client using JSON-RPC over HTTP/S.
void parsePort(ParsedPort &port, Section const &section, std::ostream &log)
Definition Port.cpp:195
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
XRPL_NO_SANITIZE_ADDRESS void Throw(Args &&... args)
Definition contract.h:52
T resize(T... args)
T size(T... args)
T str(T... args)
std::set< std::string, boost::beast::iless > protocol
Definition Port.h:81
std::optional< boost::asio::ip::address > ip
Definition Port.h:94
std::optional< std::uint16_t > port
Definition Port.h:95
static constexpr auto kServer
Definition Constants.h:56