xrpld
Loading...
Searching...
No Matches
WSClient.cpp
1#include <test/jtx/WSClient.h>
2
3#include <xrpld/core/Config.h>
4
5#include <xrpl/basics/Mutex.hpp>
6#include <xrpl/basics/contract.h>
7#include <xrpl/config/BasicConfig.h>
8#include <xrpl/config/Constants.h>
9#include <xrpl/json/json_reader.h>
10#include <xrpl/json/json_value.h>
11#include <xrpl/json/to_string.h>
12#include <xrpl/protocol/ApiVersion.h>
13#include <xrpl/protocol/JsonRpc.h>
14#include <xrpl/protocol/jss.h>
15#include <xrpl/server/Port.h>
16
17#include <boost/asio/bind_executor.hpp>
18#include <boost/asio/buffer.hpp>
19#include <boost/asio/executor_work_guard.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/asio/post.hpp>
25#include <boost/asio/strand.hpp>
26#include <boost/beast/core/multi_buffer.hpp>
27#include <boost/beast/websocket/error.hpp>
28#include <boost/beast/websocket/rfc6455.hpp>
29#include <boost/beast/websocket/stream.hpp>
30#include <boost/beast/websocket/stream_base.hpp>
31#include <boost/system/detail/error_code.hpp>
32#include <boost/system/system_error.hpp>
33
34#include <chrono>
35#include <condition_variable>
36#include <cstddef>
37#include <exception>
38#include <functional>
39#include <iostream>
40#include <list>
41#include <memory>
42#include <mutex>
43#include <optional>
44#include <stdexcept>
45#include <string>
46#include <thread>
47#include <unordered_map>
48#include <utility>
49
50namespace xrpl::test {
51
52class WSClientImpl : public WSClient
53{
54 using ErrorCode = boost::system::error_code;
55
56 struct Msg
57 {
59
60 explicit Msg(json::Value&& jv) : jv(std::move(jv))
61 {
62 }
63 };
64
65 static boost::asio::ip::tcp::endpoint
66 getEndpoint(BasicConfig const& cfg, bool v2)
67 {
68 auto& log = std::cerr;
69 ParsedPort common;
70 parsePort(common, cfg[Sections::kServer], log);
71 auto const ps = v2 ? "ws2" : "ws";
72 for (auto const& name : cfg.section(Sections::kServer).values())
73 {
74 if (!cfg.exists(name))
75 continue;
76 ParsedPort pp;
77 parsePort(pp, cfg[name], log);
78 if (!pp.protocol.contains(ps))
79 continue;
80 using namespace boost::asio::ip;
81 if (pp.ip && pp.ip->is_unspecified())
82 {
83 *pp.ip = pp.ip->is_v6() ? address{address_v6::loopback()}
84 : address{address_v4::loopback()};
85 }
86
87 if (!pp.port)
88 Throw<std::runtime_error>("Use fixConfigPorts with auto ports");
89
90 return {*pp.ip, *pp.port}; // NOLINT(bugprone-unchecked-optional-access)
91 }
92 Throw<std::runtime_error>("Missing WebSocket port");
93 return {}; // Silence compiler control paths return value warning
94 }
95
96 template <class ConstBuffers>
97 static std::string
98 bufferString(ConstBuffers const& b)
99 {
100 using boost::asio::buffer;
101 using boost::asio::buffer_size;
102 std::string s;
103 s.resize(buffer_size(b));
104 buffer_copy(buffer(&s[0], s.size()), b);
105 return s;
106 }
107
108 boost::asio::io_context ios_;
110 boost::asio::strand<boost::asio::io_context::executor_type> strand_;
112 boost::asio::ip::tcp::socket stream_;
113 boost::beast::websocket::stream<boost::asio::ip::tcp::socket&> ws_;
114 boost::beast::multi_buffer rb_;
115
116 bool peerClosed_ = false;
117
118 // disconnect() waits on this until the read loop ends (for any reason:
119 // the server acknowledged our close, or a timeout force-closed the socket).
120 static constexpr auto kDisconnectTimeout = std::chrono::seconds{1};
121 xrpl::Mutex<bool> readEnded_;
123
124 // synchronize message queue
128
129 unsigned rpcVersion_;
130
131 void
133 {
134 boost::asio::post(
135 ios_, //
136 boost::asio::bind_executor(strand_, [this] {
137 if (!peerClosed_)
138 {
139 ws_.async_close(
140 {}, //
141 boost::asio::bind_executor(strand_, [&](ErrorCode) {
142 try
143 {
144 stream_.cancel();
145 }
146 // NOLINTNEXTLINE(bugprone-empty-catch)
147 catch (boost::system::system_error const&)
148 {
149 // ignored
150 }
151 }));
152 }
153 }));
154 work_ = std::nullopt;
155 thread_.join();
156 }
157
158public:
160 Config const& cfg,
161 bool v2,
162 unsigned rpcVersion,
164 : work_(std::in_place, boost::asio::make_work_guard(ios_))
165 , strand_(boost::asio::make_strand(ios_))
166 , thread_([&] { ios_.run(); })
167 , stream_(ios_)
168 , ws_(stream_)
169 , rpcVersion_(rpcVersion)
170 {
171 try
172 {
173 auto const ep = getEndpoint(cfg, v2);
174 stream_.connect(ep);
175 ws_.set_option(
176 boost::beast::websocket::stream_base::decorator(
177 [&](boost::beast::websocket::request_type& req) {
178 for (auto const& h : headers)
179 req.set(h.first, h.second);
180 }));
181 ws_.handshake(ep.address().to_string() + ":" + std::to_string(ep.port()), "/");
182 ws_.async_read(
183 rb_, boost::asio::bind_executor(strand_, [this](ErrorCode const& ec, std::size_t) {
184 onReadMsg(ec);
185 }));
186 }
187 catch (std::exception&)
188 {
189 cleanup();
190 rethrow();
191 }
192 }
193
194 ~WSClientImpl() override
195 {
196 cleanup();
197 }
198
200 invoke(std::string const& cmd, json::Value const& params) override
201 {
202 using boost::asio::buffer;
203 using namespace std::chrono_literals;
204
205 {
206 json::Value jp;
207 if (params)
208 jp = params;
209 if (rpcVersion_ == 2)
210 {
211 jp[jss::method] = cmd;
212 jp[jss::jsonrpc] = rpc::kJsonRpcVersion;
213 jp[jss::ripplerpc] = rpc::kRippleRpcVersion2;
214 jp[jss::id] = 5;
215 }
216 else
217 {
218 jp[jss::command] = cmd;
219 }
220 auto const s = to_string(jp);
221
222 // Use the error_code overload to avoid an unhandled exception
223 // when the server closes the WebSocket connection (e.g. after
224 // booting a client that exceeded resource thresholds).
225 ErrorCode ec;
226 ws_.write_some(true, buffer(s), ec);
227 if (ec)
228 return {};
229 }
230
231 auto jv =
232 findMsg(5s, [&](json::Value const& jval) { return jval[jss::type] == jss::response; });
233 if (jv)
234 {
235 // Normalize JSON output
236 jv->removeMember(jss::type);
237 if ((*jv).isMember(jss::status) && (*jv)[jss::status] == jss::error)
238 {
239 json::Value ret;
240 ret[jss::result] = *jv;
241 if ((*jv).isMember(jss::error))
242 ret[jss::error] = (*jv)[jss::error];
243 ret[jss::status] = jss::error;
244 return ret;
245 }
246 if ((*jv).isMember(jss::status) && (*jv).isMember(jss::result))
247 (*jv)[jss::result][jss::status] = (*jv)[jss::status];
248 return *jv;
249 }
250 return {};
251 }
252
254 getMsg(std::chrono::milliseconds const& timeout) override
255 {
257 {
259 if (!cv_.wait_for(lock, timeout, [&] { return !msgs_.empty(); }))
260 return std::nullopt;
261 m = std::move(msgs_.back());
262 msgs_.pop_back();
263 }
264 return std::move(m->jv);
265 }
266
268 findMsg(std::chrono::milliseconds const& timeout, std::function<bool(json::Value const&)> pred)
269 override
270 {
272 {
274 if (!cv_.wait_for(lock, timeout, [&] {
275 for (auto it = msgs_.begin(); it != msgs_.end(); ++it)
276 {
277 if (pred((*it)->jv))
278 {
279 m = std::move(*it);
280 msgs_.erase(it);
281 return true;
282 }
283 }
284 return false;
285 }))
286 {
287 return std::nullopt;
288 }
289 }
290 return std::move(m->jv);
291 }
292
293 [[nodiscard]] unsigned
294 version() const override
295 {
296 return rpcVersion_;
297 }
298
299 void
300 disconnect() override
301 {
302 // Perform a graceful WebSocket closing handshake and block until the
303 // read loop ends, so the server observes a clean close (not a RST) and
304 // has finished tearing the connection down by the time we return.
305 // If the server already closed, the wait below returns immediately.
306 boost::asio::post(
307 ios_,
308 boost::asio::bind_executor(
309 strand_, //
310 [this] {
311 if (!peerClosed_)
312 {
313 ws_.async_close(
314 boost::beast::websocket::close_code::normal,
315 boost::asio::bind_executor(strand_, [](ErrorCode) {}));
316 }
317 }));
318
319 auto lock = readEnded_.lock<std::unique_lock>();
320 readEndCv_.wait_for(lock, kDisconnectTimeout, [&lock] { return *lock; });
321
322 // On timeout (server gone or not replying) force the socket closed so
323 // the outstanding read ends and the worker thread can later be joined.
324 if (!*lock)
325 {
326 boost::asio::post(
327 ios_,
328 boost::asio::bind_executor(
329 strand_, //
330 [this] {
331 boost::system::error_code ec;
332 stream_.close(ec);
333 }));
334 }
335 }
336
337private:
338 void
340 {
341 if (ec)
342 {
343 if (ec == boost::beast::websocket::error::closed)
344 peerClosed_ = true;
345
346 *readEnded_.lock() = true;
347 readEndCv_.notify_all();
348
349 return;
350 }
351
352 json::Value jv;
353 json::Reader jr;
354
355 jr.parse(bufferString(rb_.data()), jv);
356 rb_.consume(rb_.size());
357
358 auto const m = std::make_shared<Msg>(std::move(jv));
359 {
360 std::scoped_lock const lock(m_);
361 msgs_.push_front(m);
362 cv_.notify_all();
363 }
364
365 ws_.async_read(
366 rb_, boost::asio::bind_executor(strand_, [this](ErrorCode const& ec, std::size_t) {
367 onReadMsg(ec);
368 }));
369 }
370};
371
374 Config const& cfg,
375 bool v2,
376 unsigned rpcVersion,
378{
379 return std::make_unique<WSClientImpl>(cfg, v2, rpcVersion, headers);
380}
381
382} // namespace xrpl::test
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
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
std::list< std::shared_ptr< Msg > > msgs_
Definition WSClient.cpp:127
xrpl::Mutex< bool > readEnded_
Definition WSClient.cpp:121
void disconnect() override
Close the client's connection to the server.
Definition WSClient.cpp:300
void onReadMsg(ErrorCode const &ec)
Definition WSClient.cpp:339
boost::beast::multi_buffer rb_
Definition WSClient.cpp:114
boost::asio::io_context ios_
Definition WSClient.cpp:108
unsigned version() const override
Get RPC 1.0 or RPC 2.0.
Definition WSClient.cpp:294
std::optional< boost::asio::executor_work_guard< boost::asio::io_context::executor_type > > work_
Definition WSClient.cpp:109
boost::asio::ip::tcp::socket stream_
Definition WSClient.cpp:112
std::optional< json::Value > getMsg(std::chrono::milliseconds const &timeout) override
Retrieve a message.
Definition WSClient.cpp:254
boost::beast::websocket::stream< boost::asio::ip::tcp::socket & > ws_
Definition WSClient.cpp:113
json::Value invoke(std::string const &cmd, json::Value const &params) override
Submit a command synchronously.
Definition WSClient.cpp:200
std::optional< json::Value > findMsg(std::chrono::milliseconds const &timeout, std::function< bool(json::Value const &)> pred) override
Retrieve a message that meets the predicate criteria.
Definition WSClient.cpp:268
WSClientImpl(Config const &cfg, bool v2, unsigned rpcVersion, std::unordered_map< std::string, std::string > const &headers={})
Definition WSClient.cpp:159
std::condition_variable cv_
Definition WSClient.cpp:126
static constexpr auto kDisconnectTimeout
Definition WSClient.cpp:120
static std::string bufferString(ConstBuffers const &b)
Definition WSClient.cpp:98
static boost::asio::ip::tcp::endpoint getEndpoint(BasicConfig const &cfg, bool v2)
Definition WSClient.cpp:66
boost::system::error_code ErrorCode
Definition WSClient.cpp:54
boost::asio::strand< boost::asio::io_context::executor_type > strand_
Definition WSClient.cpp:110
std::condition_variable readEndCv_
Definition WSClient.cpp:122
T contains(T... args)
T make_shared(T... args)
T make_unique(T... args)
STL namespace.
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< WSClient > makeWSClient(Config const &cfg, bool v2, unsigned rpcVersion, std::unordered_map< std::string, std::string > const &headers)
Returns a client operating through WebSockets/S.
Definition WSClient.cpp:373
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 rethrow()
Rethrow the exception currently being handled.
Definition contract.h:36
XRPL_NO_SANITIZE_ADDRESS void Throw(Args &&... args)
Definition contract.h:52
T resize(T... args)
T size(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
T to_string(T... args)