algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
ws_session_base.hpp
1#pragma once
2
8#define ATL_TRANSPORT_LAYER_PRESENT 1
9
10#include <boost/asio/ip/tcp.hpp>
11#include <boost/asio/post.hpp>
12#include <boost/asio/steady_timer.hpp>
13#include <boost/asio/strand.hpp>
14#include <boost/beast/core.hpp>
15#include <boost/beast/websocket.hpp>
16
17#include <algorithm>
18#include <chrono>
19#include <cstdint>
20#include <deque>
21#include <map>
22#include <memory>
23#include <random>
24#include <string>
25#include <string_view>
26#include <utility>
27
28namespace algotradelib {
29
30namespace beast = boost::beast;
31namespace http = beast::http;
32namespace websocket = beast::websocket;
33namespace net = boost::asio;
35using tcp = net::ip::tcp;
36
37namespace network {
38
42 std::string target_{"/"};
44 std::map<std::string, std::string> headers_;
51 std::chrono::seconds operation_timeout_{30};
55 std::chrono::seconds reconnect_initial_{1};
57 std::chrono::seconds reconnect_max_{30};
58};
59
71template <typename Derived, typename Stream>
72class WebSocketSessionBase : public std::enable_shared_from_this<Derived> {
73public:
78 void connect() {
79 net::post(strand_, [self = shared_derived()] {
80 self->stop_requested_ = false;
81 self->do_connect();
82 });
83 }
84
93 void send(std::string message) {
94 net::post(strand_, [self = shared_derived(), message = std::move(message)]() mutable {
95 self->write_queue_.push_back(std::move(message));
96 if (self->connected_ && !self->closing_ && !self->writing_) {
97 self->do_write();
98 }
99 });
100 }
101
106 void close() {
107 net::post(strand_, [self = shared_derived()] {
108 self->stop_requested_ = true;
109 self->reconnect_timer_.cancel();
110 if (self->closing_) {
111 return;
112 }
113 self->closing_ = true;
114 if (self->connecting_ && !self->connected_) {
115 self->resolver_.cancel();
116 if (self->ws_) {
117 beast::error_code ignored;
118 beast::get_lowest_layer(*self->ws_).socket().cancel(ignored);
119 }
120 return;
121 }
122 if (self->connected_ && !self->writing_) {
123 self->do_close();
124 } else if (!self->connected_) {
125 self->closing_ = false;
126 self->on_closed();
127 }
128 });
129 }
130
131protected:
139 WebSocketSessionBase(net::io_context& ioc, std::string host, std::string port, WebSocketSessionOptions options)
140 : strand_(net::make_strand(ioc)),
143 host_(std::move(host)),
144 port_(std::move(port)),
145 options_(std::move(options)),
146 reconnect_rng_(std::random_device{}()) {}
147
149 virtual ~WebSocketSessionBase() = default;
150
155 virtual void on_message(std::string_view message) = 0;
156
158 virtual void on_open() {}
159
166 virtual void on_error(std::string_view stage, beast::error_code error) {
167 boost::ignore_unused(stage, error);
168 }
169
171 virtual void on_closed() {}
172
174 net::strand<net::io_context::executor_type> strand_;
176 tcp::resolver resolver_;
178 net::steady_timer reconnect_timer_;
180 std::unique_ptr<Stream> ws_;
182 beast::flat_buffer buffer_;
184 std::deque<std::string> write_queue_;
186 std::string host_;
188 std::string port_;
190 std::string host_header_;
194 bool connected_{false};
196 bool connecting_{false};
198 bool closing_{false};
200 bool writing_{false};
202 bool stop_requested_{false};
204 unsigned int reconnect_attempt_{0};
206 std::minstd_rand reconnect_rng_;
207
212 std::shared_ptr<Derived> shared_derived() {
213 return std::static_pointer_cast<Derived>(this->shared_from_this());
214 }
215
218 connecting_ = true;
219 resolver_.async_resolve(
220 host_, port_, beast::bind_front_handler(&WebSocketSessionBase::on_resolve, shared_derived())
221 );
222 }
223
229 beast::get_lowest_layer(*ws_).expires_never();
230 ws_->set_option(websocket::stream_base::timeout::suggested(beast::role_type::client));
231 ws_->set_option(websocket::stream_base::decorator([this](websocket::request_type& request) {
232 request.set(http::field::user_agent, "algotradelib");
233 for (const auto& header : options_.headers_) {
234 request.set(header.first, header.second);
235 }
236 }));
237 ws_->async_handshake(
238 host_header_, options_.target_, beast::bind_front_handler(&WebSocketSessionBase::on_handshake, shared_derived())
239 );
240 }
241
253 if (!closing_) {
254 return false;
255 }
256 connecting_ = false;
257 closing_ = false;
258 if (ws_) {
259 beast::error_code ignored;
260 beast::get_lowest_layer(*ws_).socket().close(ignored);
261 }
262 on_closed();
263 return true;
264 }
265
272 void fail(std::string_view stage, beast::error_code error) {
273 connected_ = false;
274 connecting_ = false;
275 writing_ = false;
276 const bool closing = closing_;
277 closing_ = false;
278 if (ws_) {
279 beast::error_code ignored;
280 beast::get_lowest_layer(*ws_).socket().close(ignored);
281 }
282 on_error(stage, error);
283 if (closing) {
284 on_closed();
285 }
286 schedule_reconnect();
287 }
288
289private:
290 friend struct WebSocketSessionTestAccess;
291
292 void on_resolve(beast::error_code error, tcp::resolver::results_type endpoints) {
293 if (error) {
294 fail("resolve", error);
295 return;
296 }
297 if (abandon_if_closing()) {
298 return;
299 }
300 beast::get_lowest_layer(*ws_).expires_after(options_.operation_timeout_);
301 beast::get_lowest_layer(*ws_).async_connect(
302 endpoints, beast::bind_front_handler(&Derived::on_connect, shared_derived())
303 );
304 }
305
306 void on_handshake(beast::error_code error) {
307 if (error) {
308 fail("handshake", error);
309 return;
310 }
311 if (abandon_if_closing()) {
312 return;
313 }
314 connecting_ = false;
315 connected_ = true;
317 on_open();
318 do_read();
319 if (!write_queue_.empty()) {
320 do_write();
321 }
322 }
323
324 void do_write() {
325 writing_ = true;
326 ws_->async_write(
327 net::buffer(write_queue_.front()), beast::bind_front_handler(&WebSocketSessionBase::on_write, shared_derived())
328 );
329 }
330
331 void on_write(beast::error_code error, std::size_t bytes_transferred) {
332 boost::ignore_unused(bytes_transferred);
333 writing_ = false;
334 if (error) {
335 fail("write", error);
336 return;
337 }
338 write_queue_.pop_front();
339 if (closing_) {
340 do_close();
341 } else if (!write_queue_.empty()) {
342 do_write();
343 }
344 }
345
346 void do_read() {
347 ws_->async_read(buffer_, beast::bind_front_handler(&WebSocketSessionBase::on_read, shared_derived()));
348 }
349
350 void on_read(beast::error_code error, std::size_t bytes_transferred) {
351 boost::ignore_unused(bytes_transferred);
352 if (error == websocket::error::closed) {
353 connected_ = false;
354 connecting_ = false;
355 closing_ = false;
356 on_closed();
357 schedule_reconnect();
358 return;
359 }
360 if (error) {
361 fail("read", error);
362 return;
363 }
364 const auto message = beast::buffers_to_string(buffer_.data());
365 buffer_.consume(buffer_.size());
366 on_message(message);
367 do_read();
368 }
369
370 void do_close() {
371 ws_->async_close(
372 websocket::close_code::normal, beast::bind_front_handler(&WebSocketSessionBase::on_close, shared_derived())
373 );
374 }
375
376 void on_close(beast::error_code error) {
377 connected_ = false;
378 connecting_ = false;
379 closing_ = false;
380 if (error) {
381 on_error("close", error);
382 }
383 on_closed();
384 if (!stop_requested_) {
385 schedule_reconnect();
386 }
387 }
388
389 void schedule_reconnect() {
391 return;
392 }
393 const auto shift = std::min(reconnect_attempt_, 16U);
394 const auto multiplier = static_cast<std::int64_t>(1ULL << shift);
395 const auto delay = std::min(options_.reconnect_initial_ * multiplier, options_.reconnect_max_);
397 const auto base_delay = std::chrono::duration_cast<std::chrono::milliseconds>(delay);
398 const auto jitter_window = base_delay / 5;
399 const auto jitter = jitter_window.count() <= 0 ?
400 std::chrono::milliseconds(0) :
401 std::chrono::milliseconds(std::uniform_int_distribution<std::int64_t>(0, jitter_window.count())(reconnect_rng_));
402 reconnect_timer_.expires_after(base_delay + jitter);
403 reconnect_timer_.async_wait([self = shared_derived()](beast::error_code error) {
404 if (!error) {
405 self->do_connect();
406 }
407 });
408 }
409};
410
411} // namespace network
412} // namespace algotradelib
virtual ~WebSocketSessionBase()=default
Destroys the session.
unsigned int reconnect_attempt_
Reconnect attempts since the last successful connect.
bool abandon_if_closing()
Ends a connect that close() interrupted, if it did; called first by each connect stage that completed...
virtual void on_closed()
Called when the session has closed (by close() or by the server).
virtual void on_open()
Called when the session is connected (after each successful upgrade, reconnects included).
void start_ws_handshake()
Sends the upgrade request; called once connected (WsSession) or after the TLS handshake (WssSession).
WebSocketSessionOptions options_
The options.
void fail(std::string_view stage, beast::error_code error)
Tears the session down after a failure, calls on_error (and on_closed if closing),...
net::steady_timer reconnect_timer_
The reconnect timer.
bool stop_requested_
Whether close() was called (no reconnection).
std::string host_header_
The Host header value (host:port), set on connect.
bool writing_
Whether a write is in progress.
bool connected_
Whether the session is connected.
WebSocketSessionBase(net::io_context &ioc, std::string host, std::string port, WebSocketSessionOptions options)
Constructs the session; nothing connects until connect().
void start_resolve()
Starts the DNS lookup; called by the transport class's do_connect() once ws_ is ready.
bool connecting_
Whether a connect is in progress.
beast::flat_buffer buffer_
The read buffer.
void send(std::string message)
Queues a message; messages are sent in order once connected.
bool closing_
Whether a close is in progress.
void connect()
Connects asynchronously (does nothing if connected, connecting or closing), and re-enables reconnecti...
std::unique_ptr< Stream > ws_
The stream, created by the transport class on each connect.
std::shared_ptr< Derived > shared_derived()
Returns a shared pointer to this session as the transport type.
virtual void on_message(std::string_view message)=0
Called with each complete message received.
void close()
Closes the session asynchronously after any write in progress, and disables reconnection; on_closed i...
net::strand< net::io_context::executor_type > strand_
The strand every handler runs on.
virtual void on_error(std::string_view stage, beast::error_code error)
Called after a failed stage has torn the session down; it then reconnects if automatic_reconnect_ is ...
std::deque< std::string > write_queue_
Messages waiting to be sent; the front one may be being written.
std::minstd_rand reconnect_rng_
The random source for reconnect jitter.
HTTP and WebSocket transport, OAuth tokens, and request pacing.
The library: broker-neutral types (core), and the modules below.
net::ip::tcp tcp
Short for boost::asio::ip::tcp.
Options for a WebSocket session (WsSession, WssSession).
std::map< std::string, std::string > headers_
Extra headers sent with the upgrade request.
std::chrono::seconds operation_timeout_
The deadline for the TCP connect and (for WssSession) the TLS handshake. The DNS lookup has no deadli...
std::chrono::seconds reconnect_max_
The longest reconnect delay (before jitter).
bool automatic_reconnect_
Whether to reconnect after a failure or a close not requested with close().
std::string target_
The path of the upgrade request.
std::chrono::seconds reconnect_initial_
The first reconnect delay; it doubles on each attempt, plus up to 20% random jitter.