diff --git a/CMakeLists.txt b/CMakeLists.txt index 99844c2e6..d88aa4c1b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -21,10 +21,12 @@ if (WIN32) set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} \ /MP \ /WX /wd4251 /wd4250 /wd4251 /wd4244 /wd4267 /wd4355 /wd4275 /wd4345 \ + /bigobj \ /DCURL_STATICLIB \ /D_WINSOCK_DEPRECATED_NO_WARNINGS \ /D__TBB_NO_IMPLICIT_LINKAGE \ /DBOOST_ALL_NO_LIB \ + /std:c++17 \ /D_SCL_SECURE_NO_WARNINGS /D_CRT_SECURE_NO_WARNINGS /D_WIN32_WINNT=0x0600") set (CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MTd") diff --git a/externals b/externals index 7bcc559c1..788caab49 160000 --- a/externals +++ b/externals @@ -1 +1 @@ -Subproject commit 7bcc559c1a5262f924d65e4cacec190ffc1fe8e0 +Subproject commit 788caab497ed38504fa9062e96e812ad9dc0d78f diff --git a/requirements39.txt b/requirements.txt similarity index 82% rename from requirements39.txt rename to requirements.txt index bd0a2b7b5..51c22aa07 100644 --- a/requirements39.txt +++ b/requirements.txt @@ -6,9 +6,12 @@ isort==5.9.3 lazy-object-proxy==1.6.0 mccabe==0.6.1 platformdirs==2.3.0 +protobuf==3.19.1 +pybars3==0.9.7 pycodestyle==2.7.0 pycparser==2.20 pylint==2.10.2 +PyMeta3==0.5.1 toml==0.10.2 wrapt==1.12.1 yapf==0.31.0 diff --git a/requirements27.txt b/requirements27.txt deleted file mode 100644 index 3d7ffdc1e..000000000 --- a/requirements27.txt +++ /dev/null @@ -1,12 +0,0 @@ -bcrypt==3.1.7 -cffi==1.14.3 -cryptography==3.1.1 -enum34==1.1.10 -ipaddress==1.0.23 -paramiko==2.7.2 -protobuf==3.13.0 -pybars3==0.9.7 -pycparser==2.20 -PyMeta3==0.5.1 -PyNaCl==1.4.0 -six==1.15.0 diff --git a/src/lib/CMakeLists.txt b/src/lib/CMakeLists.txt index 47117d545..c371b83f0 100644 --- a/src/lib/CMakeLists.txt +++ b/src/lib/CMakeLists.txt @@ -18,6 +18,7 @@ if (WIN32) domain_model/*.cpp expression/*.cpp logging/*.cpp + io/*.cpp md/*.cpp os/*.cpp quickbus/*.cpp @@ -110,7 +111,11 @@ if (WIN32) libboost_date_time libboost_atomic libprotobuf - ) + libprotoc + libssl + libcrypto + crypt32 + ) else () target_link_libraries( libspark protobuf @@ -148,5 +153,3 @@ endif() if (WIN32) include(${CMAKE_SOURCE_DIR}/tools/vs_filters.cmake) endif() - - diff --git a/src/lib/api/public/ApiServer.h b/src/lib/api/public/ApiServer.h index 853004dc4..d2b87f5ee 100644 --- a/src/lib/api/public/ApiServer.h +++ b/src/lib/api/public/ApiServer.h @@ -41,8 +41,8 @@ class BTS_EXPORT ApiServer { ResponseHeader header; header.set_code(ApiError::SUCCESS); header.set_request_id(request_id); - int header_size = header.ByteSize() + 1; - int body_size = response.ByteSize(); + int header_size = header.ByteSizeLong() + 1; + int body_size = response.ByteSizeLong(); int total_size = header_size + body_size; if (total_size <= 1024) { uint8_t buffer[1024]; diff --git a/src/lib/api/public/ClientChannel.h b/src/lib/api/public/ClientChannel.h index e48736d82..32b0dca27 100644 --- a/src/lib/api/public/ClientChannel.h +++ b/src/lib/api/public/ClientChannel.h @@ -45,11 +45,11 @@ class ClientChannel { auto ptoken = _context.token(); if (ptoken) header.mutable_token()->CopyFrom(*ptoken); - int header_size = header.ByteSize() + 1; + int header_size = header.ByteSizeLong() + 1; assert(header_size < 128); std::string request_buffer; - request_buffer.reserve(header_size + request.ByteSize()); + request_buffer.reserve(header_size + request.ByteSizeLong()); request_buffer += (char)(header_size); bool success = header.AppendToString(&request_buffer); success = success && request.AppendToString(&request_buffer); @@ -85,10 +85,10 @@ class ClientChannel { } template - rxcpp::observable>> + rxcpp::observable>> subscribe(int method_id, const char *method, const std::string &qualifier) { - return rxcpp::observable<>::create>>( - [=](rxcpp::subscriber>> observer) { + return rxcpp::observable<>::create>>( + [=](rxcpp::subscriber>> observer) { StreamAccessRequest request; request.set_qualifier(qualifier); send( @@ -109,7 +109,7 @@ class ClientChannel { const StreamUpdate *changes, int change_count) mutable { if (event_type == EventType::TABLE_UPDATED) { - std::vector> added_items, + std::vector> added_items, changed_items; std::vector added_keys, changed_keys, removed_keys; @@ -132,14 +132,14 @@ class ClientChannel { } } observer.on_next( - RawUpdate>( + RawUpdate>( added_items, added_keys, changed_items, changed_keys, removed_keys)); } else if (event_type == EventType::TABLE_CREATED) { if (!first_update) { observer.on_next( RawUpdate< - std::shared_ptr>::Reset()); + std::shared_ptr>::Reset()); } first_update = false; } diff --git a/src/lib/api/public/Update.h b/src/lib/api/public/Update.h index 49e4677bf..aa4c1ba3c 100644 --- a/src/lib/api/public/Update.h +++ b/src/lib/api/public/Update.h @@ -57,9 +57,13 @@ template std::function>( const rxcpp::observable> &)> reconstitute() { - return [](const rxcpp::observable> &input) { + return [](const rxcpp::observable> &inputi) { + auto *input_ptr = const_cast>*>(&inputi); + auto &input = *input_ptr; auto state = std::make_shared>(); - return input.map([state](RawUpdate &raw) { + return input.map([state](const RawUpdate &craw) { + auto *raw_ptr = const_cast*>(&craw); + RawUpdate &raw = *raw_ptr; if (raw.is_reset) { std::vector removed; removed.reserve(state->size()); diff --git a/src/lib/api/service_compiler/plugin.py b/src/lib/api/service_compiler/plugin.py index 9dc8c39db..fa28e92e4 100755 --- a/src/lib/api/service_compiler/plugin.py +++ b/src/lib/api/service_compiler/plugin.py @@ -30,8 +30,7 @@ import apioptions_pb2 def loadTemplate(lang, name): path = os.path.join("templates", lang, name) text = open(path).read() - utext = unicode(text, "utf-8") - return compiler.compile(utext) + return compiler.compile(text) def option(options, key, default=None): if options.HasExtension(key): @@ -306,10 +305,9 @@ def generate_code(request, response): #### MAIN ######### if __name__ == "__main__": - if DEBUG: - data = open("data", mode='rb').read() - else: - data = sys.stdin.read() + data_in = open(0, mode='rb') + data = data_in.read() + data_in.close() request = plugin.CodeGeneratorRequest() # open("data", 'wb').write(data) request.ParseFromString(data) @@ -321,5 +319,5 @@ if __name__ == "__main__": print (f.content) else: output = response.SerializeToString() - sys.stdout.write(output) + sys.stdout.buffer.write(output) diff --git a/src/lib/api/service_compiler/templates/cpp/client.pb.cc b/src/lib/api/service_compiler/templates/cpp/client.pb.cc index 629c29178..e7c8c9154 100644 --- a/src/lib/api/service_compiler/templates/cpp/client.pb.cc +++ b/src/lib/api/service_compiler/templates/cpp/client.pb.cc @@ -19,12 +19,12 @@ using namespace rxcpp::operators; rxcpp::observable<{{cap name}}Update> {{../name}}::subscribe_{{name}}(std::string const&qualifier) { return _pchannel->subscribe<{{output_type_cpp}}>({{@index}}, "{{name}}", qualifier) - | (bts::api::reconstitute,const {{key_type.cpptype}}, {{../name}}>()); + | (bts::api::reconstitute,const {{key_type.cpptype}}, {{../name}}>()); } rxcpp::observable<{{cap name}}Update> {{../name}}::subscribe_{{name}}() { return _pchannel->subscribe<{{output_type_cpp}}>({{@index}}, "{{name}}", "") - | (bts::api::reconstitute,const {{key_type.cpptype}}, {{../name}}>()); + | (bts::api::reconstitute,const {{key_type.cpptype}}, {{../name}}>()); } {{#if key_type.natural_key}} diff --git a/src/lib/api/service_compiler/templates/cpp/client.pb.h b/src/lib/api/service_compiler/templates/cpp/client.pb.h index 338462bd1..d8b8d5f7b 100644 --- a/src/lib/api/service_compiler/templates/cpp/client.pb.h +++ b/src/lib/api/service_compiler/templates/cpp/client.pb.h @@ -6,11 +6,12 @@ #include "lib/api/public/Update.h" #include "lib/utils/bts_export.h" -#include -#include +#include #include #include #include +#include +#include {{ns-open package}} @@ -22,7 +23,7 @@ class {{name}}; {{#each service}} {{#each method}}{{#if server_streaming}} class {{../name}}; -typedef bts::api::Update, const {{key_type.cpptype}}, {{../name}}> {{cap name}}Update; +typedef bts::api::Update, const {{key_type.cpptype}}, {{../name}}> {{cap name}}Update; {{/if}}{{/each}} // {{comment}} diff --git a/src/lib/api/service_compiler/templates/cpp/server.pb.cc b/src/lib/api/service_compiler/templates/cpp/server.pb.cc index 4635e7803..6265c10f7 100644 --- a/src/lib/api/service_compiler/templates/cpp/server.pb.cc +++ b/src/lib/api/service_compiler/templates/cpp/server.pb.cc @@ -63,7 +63,7 @@ void Authenticated{{name}}Base::dispatch(const bts::api::RequestHeader& header, response.set_request_id(header.request_id()); response.set_code(bts::api::ApiError::MISSING_METHOD); uint8_t buffer[64]; - int header_size = response.ByteSize() + 1; + int header_size = response.ByteSizeLong() + 1; serialize(header_size, response, buffer); on_response(buffer, header_size); } break; @@ -128,7 +128,7 @@ void Authenticated{{name}}Base::dispatch(const bts::api::RequestHeader& header, {{else}} update.key = get_key({{name}}_key(item)); {{/if}} - update.buffer_len = item.ByteSize(); + update.buffer_len = item.ByteSizeLong(); char* buffer = new char[update.buffer_len]; item.SerializePartialToArray(buffer, update.buffer_len); update.buffer =buffer; @@ -143,7 +143,7 @@ void Authenticated{{name}}Base::dispatch(const bts::api::RequestHeader& header, {{else}} update.key = get_key({{name}}_key(item)); {{/if}} - update.buffer_len = item.ByteSize(); + update.buffer_len = item.ByteSizeLong(); char* buffer = new char[update.buffer_len]; item.SerializePartialToArray(buffer, update.buffer_len); update.buffer =buffer; diff --git a/src/lib/core/HashPhaser.h b/src/lib/core/HashPhaser.h index dbbc34c37..7d0fd56ef 100644 --- a/src/lib/core/HashPhaser.h +++ b/src/lib/core/HashPhaser.h @@ -6,6 +6,10 @@ namespace bts::core { +#ifndef __CHAR_BIT__ +#define __CHAR_BIT__ 8 +#endif + /** * Provides facilities to combine multiple hash codes into a single hash code. * @@ -126,7 +130,7 @@ std::size_t HashPhaser::auto_phase_range(Iter first, Iter last) { const std::uint16_t max_els = 8; auto num_vals = std::distance(first, last); std::uint16_t el_count = - num_vals > std::numeric_limits::max() + num_vals > (std::numeric_limits::max)() ? max_els : std::max(static_cast(num_vals), max_els); auto bits_per_hash = (sizeof(std::size_t) * __CHAR_BIT__) / el_count; @@ -151,7 +155,7 @@ std::size_t HashPhaser::auto_phase_range(Iter first, Iter last, Hash hash) { const std::uint16_t max_els = 8; auto num_vals = std::distance(first, last); std::uint16_t el_count = - num_vals > std::numeric_limits::max() + num_vals > (std::numeric_limits::max)() ? max_els : std::max(static_cast(num_vals), max_els); auto bits_per_hash = (sizeof(std::size_t) * __CHAR_BIT__) / el_count; @@ -174,8 +178,8 @@ void HashPhaser::_auto_phase( auto m_depth = depth++; _auto_phase(composite_hash, depth, next...); auto val_hash = std::hash()(value); - auto bits_per_hash = (sizeof(std::size_t) * __CHAR_BIT__) / depth; - std::size_t phase = 1U << (bits_per_hash - 1); + std::size_t bits_per_hash = (sizeof(std::size_t) * __CHAR_BIT__) / depth; + std::size_t phase = std::size_t(1) << static_cast(bits_per_hash - 1); composite_hash |= (val_hash % phase) << (m_depth * bits_per_hash); } @@ -184,8 +188,8 @@ void HashPhaser::_auto_phase( std::size_t &composite_hash, std::uint16_t &depth, T value) { depth++; std::size_t val_hash = std::hash()(value); - auto bits_per_hash = (sizeof(std::size_t) * __CHAR_BIT__) / depth; - std::size_t phase = 1U << (bits_per_hash - 1); + std::size_t bits_per_hash = (sizeof(std::size_t) * __CHAR_BIT__) / depth; + std::size_t phase = std::size_t(1) << static_cast(bits_per_hash - 1); composite_hash |= (val_hash % phase) << ((depth - 1) * bits_per_hash); } diff --git a/src/lib/domain/Price.h b/src/lib/domain/Price.h index 50d2e348c..867dbdfaf 100644 --- a/src/lib/domain/Price.h +++ b/src/lib/domain/Price.h @@ -7,9 +7,9 @@ #include #if bts_assert_msg -#define _ASSERT_MSG(EXP, msg) bts_assert_msg(EXP, msg) +#define __ASSERT_MSG(EXP, msg) bts_assert_msg(EXP, msg) #else -#define _ASSERT_MSG(EXP, msg) \ +#define __ASSERT_MSG(EXP, msg) \ do { \ if (!(EXP)) { \ std::cerr << "Assert failure: " << std::string(#EXP) << " " << msg \ @@ -21,7 +21,9 @@ } while (0) #endif -#define _ASSERT(EXP) _ASSERT_MSG(EXP, "") +#define __ASSERT(EXP) __ASSERT_MSG(EXP, "") + +#define IS_NAND(x) (x == std::numeric_limits::quiet_NaN()) namespace bts::domain { @@ -162,7 +164,7 @@ namespace bts::domain { constexpr Price::Price(std::int64_t mantissa, std::int8_t exponent) noexcept : _mantissa(mantissa) { - _ASSERT(exponent == Price::exponent()); + __ASSERT(exponent == Price::exponent()); } template @@ -177,7 +179,7 @@ constexpr float Price::to_float() const noexcept { template inline Price Price::from_double(double price) noexcept { static_assert(PRECISION == -exponent()); - if (std::isnan(price)) { + if (IS_NAND(price)) { return nan(); } double temp; // NOLINT @@ -242,10 +244,10 @@ constexpr bool Price::is_better(Side s, Price p2) const noexcept { } constexpr bool Price::is_better(Side s, double p1, double p2) noexcept { - if (std::isnan(p1)) { + if (IS_NAND(p1)) { return false; } - if (std::isnan(p2)) { + if (IS_NAND(p2)) { return true; } if (s == Side::Buy) { @@ -278,11 +280,11 @@ constexpr bool Price::is_better_or_equal(Side s, Price p2) const noexcept { constexpr bool Price::is_better_or_equal( Side s, double p1, double p2) noexcept { - if (std::isnan(p1)) { + if (IS_NAND(p1)) { // This case is always false (even if p2 is nan), because nan != nan. return false; } - if (std::isnan(p2)) { + if (IS_NAND(p2)) { return true; } if (s == Side::Buy) { @@ -497,5 +499,6 @@ constexpr size_t hash::operator()( } // namespace std -#undef _ASSERT -#undef _ASSERT_MSG +#undef IS_NAND +#undef __ASSERT +#undef __ASSERT_MSG diff --git a/src/lib/io/websocket/WebsocketClient.cpp b/src/lib/io/websocket/WebsocketClient.cpp index 4270376f6..0718db93c 100644 --- a/src/lib/io/websocket/WebsocketClient.cpp +++ b/src/lib/io/websocket/WebsocketClient.cpp @@ -1,12 +1,15 @@ #include "WebsocketClient.h" +#include "WebsocketSSLClientInternal.h" #include "WebsocketClientConfiguration.h" #include "WebsocketError.h" #include "WebsocketMessage.h" #include "lib/logging/logging.h" #include "lib/utils/bts_assert.h" #include +#ifndef _WIN32 #include #include +#endif #include #include #include @@ -43,23 +46,8 @@ #include #include -namespace beast = boost::beast; // from -namespace http_core = beast::http; // from -namespace websocket_core = beast::websocket; // from -namespace net = boost::asio; // from -namespace ssl = boost::asio::ssl; // from -using tcp = boost::asio::ip::tcp; // from - namespace bts::io::websocket { -std::string get_thread_string() { - auto core_id = sched_getcpu(); - std::thread::id thread_id = std::this_thread::get_id(); - std::stringstream ss; - ss << "{thread_id:" << thread_id << " core:" << core_id << "}"; - return ss.str(); -} - // class WebsocketClientInternal // : public std::enable_shared_from_this { // private: @@ -323,285 +311,6 @@ std::string get_thread_string() { // } // }; -class WebsocketSSLClientInternal - : public std::enable_shared_from_this { - private: - using WSCI = WebsocketSSLClientInternal; - const WebsocketClientConfiguration _conf; - tcp::resolver _resolver; - websocket_core::stream> _ws; - beast::flat_buffer _read_buffer; - boost::asio::deadline_timer _timer; - IWebsocketListener *_listener; - std::string ip_port = {}; - // can't call async_read until the completion call - bool _pending_read = false; - // same for write - bool _pending_write = false; - // for send_message calls when there is_pending_write is true - std::queue _send_queue = {}; - // this is just incremented and every read message is tagged with it - uint64_t _read_msg_id = 0; - // since there can only be one pending write at a time (ie we cant send an - // aysnc write until the last write's completion has been called) - uint64_t _pending_write_msg_id = 0; - // if any of the async call completion result in an error, this is set. - // this allows the timer - bool _encountered_error = false; - // oneway switch thats turned on once async_close is called - bool _close_attempted = false; - - public: - // Resolver and socket require an io_context - explicit WebsocketSSLClientInternal( - const WebsocketClientConfiguration &conf, - net::io_context &ioc, - ssl::context &ctx, - IWebsocketListener *listener) - : _conf(conf), _resolver(net::make_strand(ioc)), - _ws(net::make_strand(ioc), ctx), - _timer(ioc, boost::posix_time::milliseconds(conf.timer_ms)), - _listener(listener) {} - - // user facing function - void start() { _resolve(); } - - void send_message(const WebsocketMessage &msg) { - _send_queue.push(msg); - _write_data(); - } - - void close_connection() { - if (!_close_attempted) { - _close_attempted = true; - _ws.async_close( - websocket_core::close_code::normal, - beast::bind_front_handler(&WSCI::_on_close, shared_from_this())); - } - } - - private: - static void _fail(beast::error_code ec, char const *what) { - std::cerr << what << ": " << ec.message() << std::endl; - } - - void _handle_error( - beast::error_code error_code, - std::string &&err_msg, - WebsocketError::ErrorType err_type) { - _encountered_error = true; - std::stringstream str; - str << "Error_code:" << error_code << " Text:" << err_msg; - LOG(OrderMan, Info, - "WebsocketSSLClientInternal::_handle_error error_code:{} err_msg:{}", - error_code, err_msg); - _listener->on_error({err_type, str.str()}); - close_connection(); - } - - // Start the asynchronous operation - void _resolve() { - _resolver.async_resolve( - _conf.ip, _conf.port, - beast::bind_front_handler(&WSCI::_on_resolve, shared_from_this())); - } - - void _on_resolve( - beast::error_code ec, const tcp::resolver::results_type &results) { - if (ec) { - _fail(ec, "resolve"); - _handle_error( - ec, "Address resoloution failed", - WebsocketError::ErrorType::SETUP); - return; - } - LOG(OrderMan, Info, - "WebsocketSSLClientInternal::_on_resolve successfull results:{}", - results.size()); - // Set the timeout for the operation - beast::get_lowest_layer(_ws).expires_after(std::chrono::seconds(30)); - // Make the connection on the IP address we get from a lookup - beast::get_lowest_layer(_ws).async_connect( - results, - beast::bind_front_handler(&WSCI::_on_connect, shared_from_this())); - } - - void _on_connect( - beast::error_code ec, - const tcp::resolver::results_type::endpoint_type &ep) { - if (ec) { - _fail(ec, "connect"); - _handle_error( - ec, "Connection failed", WebsocketError::ErrorType::SETUP); - return; - } - LOG(OrderMan, Info, - "WebsocketSSLClientInternal::_on_connect successfull ep:{}", ep); - ip_port = _conf.ip + ':' + std::to_string(ep.port()); - // Set a timeout on the operation - beast::get_lowest_layer(_ws).expires_after(std::chrono::seconds(30)); - - // Set SNI Hostname (many hosts need this to handshake successfully) - if (!SSL_set_tlsext_host_name( - _ws.next_layer().native_handle(), ip_port.c_str())) { - ec = beast::error_code( - static_cast(::ERR_get_error()), - net::error::get_ssl_category()); - _fail(ec, "connect"); - _handle_error( - ec, "Connection failed", WebsocketError::ErrorType::SETUP); - return; - } - - // Perform the SSL handshake - _ws.next_layer().async_handshake( - ssl::stream_base::client, - beast::bind_front_handler( - &WSCI::_on_ssl_handshake, shared_from_this())); - } - - void _on_ssl_handshake(beast::error_code ec) { - if (ec) { - _fail(ec, "ssl_handshake"); - _handle_error( - ec, "SSL Handshake failed", WebsocketError::ErrorType::SETUP); - return; - } - LOG(OrderMan, Info, - "WebsocketSSLClientInternal::_on_ssl_handshake successful"); - // Turn off the timeout on the tcp_stream, because - // the websocket stream has its own timeout system. - beast::get_lowest_layer(_ws).expires_never(); - - // Set suggested timeout settings for the websocket - _ws.set_option(websocket_core::stream_base::timeout::suggested( - beast::role_type::client)); - - // Set a decorator to change the User-Agent of the handshake - _ws.set_option(websocket_core::stream_base::decorator( - [](websocket_core::request_type &req) { - req.set( - http_core::field::user_agent, - std::string(BOOST_BEAST_VERSION_STRING) + - " websocket-client-async-ssl"); - })); - - // Perform the websocket handshake - _ws.async_handshake( - ip_port, _conf.host_name, - beast::bind_front_handler(&WSCI::_on_handshake, shared_from_this())); - } - - void _on_handshake(beast::error_code ec) { - if (ec) { - _fail(ec, "handshake"); - _handle_error( - ec, "Handshake failed", WebsocketError::ErrorType::SETUP); - return; - } - LOG(OrderMan, Info, - "WebsocketSSLClientInternal::_on_handshake successfull"); - // this is when the connection is really established - _listener->on_connection_established(); - _read_data(); - _write_data(); - _reinit_timer(); - } - - void _on_timer(beast::error_code ec) { - if (ec) { - _fail(ec, "timer"); - _handle_error(ec, "Timer failed", WebsocketError::ErrorType::MISC); - return; - } - _listener->on_timer(); - if (_is_active()) { - _reinit_timer(); - } - } - - void _reinit_timer() { - _timer.expires_at( - _timer.expires_at() + - boost::posix_time::milliseconds(_conf.timer_ms)); - _timer.async_wait( - beast::bind_front_handler(&WSCI::_on_timer, shared_from_this())); - } - - void _write_data() { - if (!_pending_write) { - if (!_send_queue.empty()) { - WebsocketMessage msg = _send_queue.front(); - _pending_write_msg_id = msg.message_id; - _send_queue.pop(); - _pending_write = true; - _ws.async_write( - net::buffer(msg.data, msg.data_size), - beast::bind_front_handler( - &WSCI::_on_write, shared_from_this())); - } - } - } - - void _read_data() { - if (!_pending_read) { - _pending_read = true; - _ws.async_read( - _read_buffer, - beast::bind_front_handler(&WSCI::_on_read, shared_from_this())); - } - } - - void _on_write(beast::error_code ec, std::size_t bytes_transferred) { - boost::ignore_unused(bytes_transferred); - if (ec) { - _fail(ec, "write"); - _handle_error( - ec, "Write failed", WebsocketError::ErrorType::WRITE_FAILED); - return; - } - _pending_write = false; - // Read a message into our buffer - _listener->on_write_complete(_pending_write_msg_id); - _read_data(); - _write_data(); - } - - void _on_read(beast::error_code ec, std::size_t bytes_transferred) { - boost::ignore_unused(bytes_transferred); - if (ec) { - _fail(ec, "read"); - _handle_error( - ec, "Read failed", WebsocketError::ErrorType::READ_FAILED); - return; - } - _pending_read = false; - WebsocketMessage msg = { - _read_msg_id++, - static_cast(_read_buffer.cdata().data()), - _read_buffer.data().size()}; - _listener->on_data(msg); - _read_buffer.clear(); - _read_data(); - _write_data(); - } - - void _on_close(beast::error_code ec) { - if (ec) { - _fail(ec, "close"); - _listener->on_connection_closed(false); - return; - } - _listener->on_connection_closed(true); - // If we get here then the connection is closed gracefully - // The make_printable() function helps print a ConstBufferSequence - std::cout << "on_close" - << " last data:" << beast::make_printable(_read_buffer.data()) - << std::endl; - } - - bool _is_active() const { return !_encountered_error && !_close_attempted; } -}; extern "C" { struct WebsocketMessageWrapper { std::uint64_t message_id; @@ -641,9 +350,9 @@ WebsocketClient::WebsocketClient( void WebsocketClient::start() { for (size_t i = 0; i <= me->conf.n_reconnection_attempts; i++) { - net::io_context ioc; + boost::asio::io_context ioc; // The SSL context is required, and holds certificates - ssl::context ctx{ssl::context::tlsv12_client}; + boost::asio::ssl::context ctx{boost::asio::ssl::context::tlsv12_client}; // This holds the root certificate used for verification // load_root_certificates(ctx); std::shared_ptr wsci = diff --git a/src/lib/io/websocket/WebsocketSSLClientInternal.cpp b/src/lib/io/websocket/WebsocketSSLClientInternal.cpp new file mode 100644 index 000000000..06ba75093 --- /dev/null +++ b/src/lib/io/websocket/WebsocketSSLClientInternal.cpp @@ -0,0 +1,300 @@ +#include "WebsocketSSLClientInternal.h" +#include "WebsocketError.h" +#include "WebsocketMessage.h" +#include "lib/logging/logging.h" +#include "lib/utils/bts_assert.h" +#include +#ifndef _WIN32 +#include +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace bts::io::websocket { + +// Resolver and socket require an io_context +WebsocketSSLClientInternal::WebsocketSSLClientInternal( + const WebsocketClientConfiguration &conf, + boost::asio::io_context &ioc, + boost::asio::ssl::context &ctx, + IWebsocketListener *listener) + : _conf(conf), _resolver(boost::asio::make_strand(ioc)), + _ws(boost::asio::make_strand(ioc), ctx), + _timer(ioc, boost::posix_time::milliseconds(conf.timer_ms)), + _listener(listener) {} + +// user facing function +void WebsocketSSLClientInternal::start() { _resolve(); } + +void WebsocketSSLClientInternal::send_message(const WebsocketMessage &msg) { + _send_queue.push(msg); + _write_data(); +} + +void WebsocketSSLClientInternal::close_connection() { + if (!_close_attempted) { + _close_attempted = true; + _ws.async_close( + boost::beast::websocket::close_code::normal, + boost::beast::bind_front_handler( + &WSCI::_on_close, shared_from_this())); + } +} + +void WebsocketSSLClientInternal::_fail( + boost::beast::error_code ec, char const *what) { + std::cerr << what << ": " << ec.message() << std::endl; +} + +void WebsocketSSLClientInternal::_handle_error( + boost::beast::error_code error_code, + std::string &&err_msg, + WebsocketError::ErrorType err_type) { + _encountered_error = true; + std::stringstream str; + str << "Error_code:" << error_code << " Text:" << err_msg; + LOG(OrderMan, Info, + "WebsocketSSLClientInternal::_handle_error error_code:{} err_msg:{}", + error_code, err_msg); + _listener->on_error({err_type, str.str()}); + close_connection(); +} + +// Start the asynchronous operation +void WebsocketSSLClientInternal::_resolve() { + _resolver.async_resolve( + _conf.ip, _conf.port, + boost::beast::bind_front_handler( + &WSCI::_on_resolve, shared_from_this())); +} + +void WebsocketSSLClientInternal::_on_resolve( + boost::beast::error_code ec, + const boost::asio::ip::tcp::resolver::results_type &results) { + if (ec) { + _fail(ec, "resolve"); + _handle_error( + ec, "Address resoloution failed", WebsocketError::ErrorType::SETUP); + return; + } + LOG(OrderMan, Info, + "WebsocketSSLClientInternal::_on_resolve successfull results:{}", + results.size()); + // Set the timeout for the operation + boost::beast::get_lowest_layer(_ws).expires_after(std::chrono::seconds(30)); + // Make the connection on the IP address we get from a lookup + boost::beast::get_lowest_layer(_ws).async_connect( + results, boost::beast::bind_front_handler( + &WSCI::_on_connect, shared_from_this())); +} + +void WebsocketSSLClientInternal::_on_connect( + boost::beast::error_code ec, + const boost::asio::ip::tcp::resolver::results_type::endpoint_type &ep) { + if (ec) { + _fail(ec, "connect"); + _handle_error(ec, "Connection failed", WebsocketError::ErrorType::SETUP); + return; + } + LOG(OrderMan, Info, + "WebsocketSSLClientInternal::_on_connect successfull ep:{}", ep); + ip_port = _conf.ip + ':' + std::to_string(ep.port()); + // Set a timeout on the operation + boost::beast::get_lowest_layer(_ws).expires_after(std::chrono::seconds(30)); + + // Set SNI Hostname (many hosts need this to handshake successfully) + if (!SSL_set_tlsext_host_name( + _ws.next_layer().native_handle(), ip_port.c_str())) { + ec = boost::beast::error_code( + static_cast(::ERR_get_error()), + boost::asio::error::get_ssl_category()); + _fail(ec, "connect"); + _handle_error(ec, "Connection failed", WebsocketError::ErrorType::SETUP); + return; + } + + // Perform the SSL handshake + _ws.next_layer().async_handshake( + boost::asio::ssl::stream_base::client, + boost::beast::bind_front_handler( + &WSCI::_on_ssl_handshake, shared_from_this())); +} + +void WebsocketSSLClientInternal::_on_ssl_handshake( + boost::beast::error_code ec) { + if (ec) { + _fail(ec, "ssl_handshake"); + _handle_error( + ec, "SSL Handshake failed", WebsocketError::ErrorType::SETUP); + return; + } + LOG(OrderMan, Info, + "WebsocketSSLClientInternal::_on_ssl_handshake successful"); + // Turn off the timeout on the tcp_stream, because + // the websocket stream has its own timeout system. + boost::beast::get_lowest_layer(_ws).expires_never(); + + // Set suggested timeout settings for the websocket + _ws.set_option(boost::beast::websocket::stream_base::timeout::suggested( + boost::beast::role_type::client)); + + // Set a decorator to change the User-Agent of the handshake + _ws.set_option(boost::beast::websocket::stream_base::decorator( + [](boost::beast::websocket::request_type &req) { + req.set( + boost::beast::http::field::user_agent, + std::string(BOOST_BEAST_VERSION_STRING) + + " websocket-client-async-ssl"); + })); + + // Perform the websocket handshake + _ws.async_handshake( + ip_port, _conf.host_name, + boost::beast::bind_front_handler( + &WSCI::_on_handshake, shared_from_this())); +} + +void WebsocketSSLClientInternal::_on_handshake(boost::beast::error_code ec) { + if (ec) { + _fail(ec, "handshake"); + _handle_error(ec, "Handshake failed", WebsocketError::ErrorType::SETUP); + return; + } + LOG(OrderMan, Info, "WebsocketSSLClientInternal::_on_handshake successfull"); + // this is when the connection is really established + _listener->on_connection_established(); + _read_data(); + _write_data(); + _reinit_timer(); +} + +void WebsocketSSLClientInternal::_on_timer(boost::beast::error_code ec) { + if (ec) { + _fail(ec, "timer"); + _handle_error(ec, "Timer failed", WebsocketError::ErrorType::MISC); + return; + } + _listener->on_timer(); + if (_is_active()) { + _reinit_timer(); + } +} + +void WebsocketSSLClientInternal::_reinit_timer() { + _timer.expires_at( + _timer.expires_at() + boost::posix_time::milliseconds(_conf.timer_ms)); + _timer.async_wait( + boost::beast::bind_front_handler(&WSCI::_on_timer, shared_from_this())); +} + +void WebsocketSSLClientInternal::_write_data() { + if (!_pending_write) { + if (!_send_queue.empty()) { + WebsocketMessage msg = _send_queue.front(); + _pending_write_msg_id = msg.message_id; + _send_queue.pop(); + _pending_write = true; + _ws.async_write( + boost::asio::buffer(msg.data, msg.data_size), + boost::beast::bind_front_handler( + &WSCI::_on_write, shared_from_this())); + } + } +} + +void WebsocketSSLClientInternal::_read_data() { + if (!_pending_read) { + _pending_read = true; + _ws.async_read( + _read_buffer, boost::beast::bind_front_handler( + &WSCI::_on_read, shared_from_this())); + } +} + +void WebsocketSSLClientInternal::_on_write( + boost::beast::error_code ec, std::size_t bytes_transferred) { + boost::ignore_unused(bytes_transferred); + if (ec) { + _fail(ec, "write"); + _handle_error( + ec, "Write failed", WebsocketError::ErrorType::WRITE_FAILED); + return; + } + _pending_write = false; + // Read a message into our buffer + _listener->on_write_complete(_pending_write_msg_id); + _read_data(); + _write_data(); +} + +void WebsocketSSLClientInternal::_on_read( + boost::beast::error_code ec, std::size_t bytes_transferred) { + boost::ignore_unused(bytes_transferred); + if (ec) { + _fail(ec, "read"); + _handle_error(ec, "Read failed", WebsocketError::ErrorType::READ_FAILED); + return; + } + _pending_read = false; + WebsocketMessage msg = { + _read_msg_id++, static_cast(_read_buffer.cdata().data()), + _read_buffer.data().size()}; + _listener->on_data(msg); + _read_buffer.clear(); + _read_data(); + _write_data(); +} + +void WebsocketSSLClientInternal::_on_close(boost::beast::error_code ec) { + if (ec) { + _fail(ec, "close"); + _listener->on_connection_closed(false); + return; + } + _listener->on_connection_closed(true); + // If we get here then the connection is closed gracefully + // The make_printable() function helps print a ConstBufferSequence + std::cout << "on_close" + << " last data:" + << boost::beast::make_printable(_read_buffer.data()) << std::endl; +} + +bool WebsocketSSLClientInternal::_is_active() const { + return !_encountered_error && !_close_attempted; +} + +} // namespace bts::io::websocket diff --git a/src/lib/io/websocket/WebsocketSSLClientInternal.h b/src/lib/io/websocket/WebsocketSSLClientInternal.h new file mode 100644 index 000000000..c5c09f4b1 --- /dev/null +++ b/src/lib/io/websocket/WebsocketSSLClientInternal.h @@ -0,0 +1,137 @@ +#pragma once +#include "WebsocketClientConfiguration.h" +#include "WebsocketError.h" +#include "WebsocketMessage.h" +#include "lib/io/websocket/IWebsocketListener.h" +#include +#ifndef _WIN32 +#include +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace bts::io::websocket { + +class WebsocketSSLClientInternal + : public std::enable_shared_from_this { + private: + using WSCI = WebsocketSSLClientInternal; + const WebsocketClientConfiguration _conf; + boost::asio::ip::tcp::resolver _resolver; + boost::beast::websocket::stream> + _ws; + boost::beast::flat_buffer _read_buffer; + boost::asio::deadline_timer _timer; + IWebsocketListener *_listener; + std::string ip_port = {}; + // can't call async_read until the completion call + bool _pending_read = false; + // same for write + bool _pending_write = false; + // for send_message calls when there is_pending_write is true + std::queue _send_queue = {}; + // this is just incremented and every read message is tagged with it + uint64_t _read_msg_id = 0; + // since there can only be one pending write at a time (ie we cant send an + // aysnc write until the last write's completion has been called) + uint64_t _pending_write_msg_id = 0; + // if any of the async call completion result in an error, this is set. + // this allows the timer + bool _encountered_error = false; + // oneway switch thats turned on once async_close is called + bool _close_attempted = false; + + public: + // Resolver and socket require an io_context + explicit WebsocketSSLClientInternal( + const WebsocketClientConfiguration &conf, + boost::asio::io_context &ioc, + boost::asio::ssl::context &ctx, + IWebsocketListener *listener); + + // user facing function + void start(); + + void send_message(const WebsocketMessage &msg); + + void close_connection(); + + private: + static void _fail(boost::beast::error_code ec, char const *what); + + void _handle_error( + boost::beast::error_code error_code, + std::string &&err_msg, + WebsocketError::ErrorType err_type); + + // Start the asynchronous operation + void _resolve(); + + void _on_resolve( + boost::beast::error_code ec, const boost::asio::ip::tcp::resolver::results_type &results); + + void _on_connect( + boost::beast::error_code ec, + const boost::asio::ip::tcp::resolver::results_type::endpoint_type &ep); + + void _on_ssl_handshake(boost::beast::error_code ec); + + void _on_handshake(boost::beast::error_code ec); + + void _on_timer(boost::beast::error_code ec); + + void _reinit_timer(); + + void _write_data(); + + void _read_data(); + + void _on_write(boost::beast::error_code ec, std::size_t bytes_transferred); + + void _on_read(boost::beast::error_code ec, std::size_t bytes_transferred); + + void _on_close(boost::beast::error_code ec); + + bool _is_active() const; +}; + +#undef beast +#undef websocket +#undef net +#undef ssl +#undef tcp + +} // namespace bts::io::websocket diff --git a/src/lib/io/websocket/tests/WebsocketClientTests.cpp b/src/lib/io/websocket/tests/WebsocketClientTests.cpp index a0f912666..3f21cc62e 100644 --- a/src/lib/io/websocket/tests/WebsocketClientTests.cpp +++ b/src/lib/io/websocket/tests/WebsocketClientTests.cpp @@ -1,3 +1,4 @@ +#ifndef _WIN32 #include "lib/io/websocket/IWebsocketListener.h" #include "lib/io/websocket/WebsocketClient.h" #include "lib/io/websocket/WebsocketClientConfiguration.h" @@ -357,3 +358,4 @@ TEST_CASE("WebsocketClientTest", "[bin_conn]") { } } // namespace bts::io::websocket +#endif diff --git a/src/lib/logging/Common.h b/src/lib/logging/Common.h index 6804a4ed5..5b4856a1d 100644 --- a/src/lib/logging/Common.h +++ b/src/lib/logging/Common.h @@ -12,14 +12,14 @@ namespace log { struct Level { using Rep = uint8_t; - constexpr static auto Max = std::numeric_limits::max(); + constexpr static auto Max = (std::numeric_limits::max)(); Rep ordinal; bool operator<(const Level &rhs) const { return ordinal < rhs.ordinal; } }; struct Subsystem { using Rep = uint8_t; - constexpr static auto Max = std::numeric_limits::max(); + constexpr static auto Max = (std::numeric_limits::max)(); Rep ordinal; bool operator<(const Subsystem &rhs) const { return ordinal < rhs.ordinal; } }; diff --git a/src/lib/logging/Logger.h b/src/lib/logging/Logger.h index 5cdf65366..edbb57b79 100644 --- a/src/lib/logging/Logger.h +++ b/src/lib/logging/Logger.h @@ -4,6 +4,7 @@ #include "MsgPacking.h" #include "lib/os/os.h" +#include #include #include #include diff --git a/src/lib/logging/MsgPacking.h b/src/lib/logging/MsgPacking.h index 6cbe4d7dd..cec7ae865 100644 --- a/src/lib/logging/MsgPacking.h +++ b/src/lib/logging/MsgPacking.h @@ -13,7 +13,7 @@ std::string format_tuple( const char *msg_template, Tuple const &t, std::index_sequence) { try { return fmt::format(msg_template, std::get(t)...); - } catch (fmt::FormatError const &e) { + } catch (fmt::format_error const &e) { return fmt::format( "Bad log message template: '{}' Error: '{}'", msg_template, e.what()); } diff --git a/src/lib/md/Shm/FixedSecurity.h b/src/lib/md/Shm/FixedSecurity.h index fff8d22f1..b3f157d87 100644 --- a/src/lib/md/Shm/FixedSecurity.h +++ b/src/lib/md/Shm/FixedSecurity.h @@ -162,7 +162,7 @@ template class FixedSpreadSecurity : public FixedSecurity { class FixedSyntheticSecurity : public FixedSecurity { public: FixedSyntheticSecurity(const api::Security &sec) - : _leg_count(sec.synthetic().legs_size()), _buffer_size(sec.ByteSize()) { + : _leg_count(sec.synthetic().legs_size()), _buffer_size(static_cast(sec.ByteSizeLong())) { type = api::SECURITYTYPE_SYNTHETIC; sec.SerializeToArray(buffer(), _buffer_size); size = sizeof(FixedSyntheticSecurity) + _buffer_size; @@ -263,7 +263,7 @@ void with_security( // buffer and only heap allocating if we exceed that but in general // FixedSynthetic is not performance sensitive std::vector buffer; - buffer.resize(psynthetic->ByteSize() + sizeof(FixedSyntheticSecurity)); + buffer.resize(psynthetic->ByteSizeLong() + sizeof(FixedSyntheticSecurity)); auto *psec = new (&buffer[0]) FixedSyntheticSecurity(*psynthetic); cb(*psec); return; diff --git a/src/lib/md/binance/BinanceDepthStreamParams.cpp b/src/lib/md/binance/BinanceDepthStreamParams.cpp index a9a11b93c..6d63a04a0 100644 --- a/src/lib/md/binance/BinanceDepthStreamParams.cpp +++ b/src/lib/md/binance/BinanceDepthStreamParams.cpp @@ -5,6 +5,7 @@ #include #include #include +#include namespace bts::md::binance { diff --git a/src/lib/md/relay/RelayRecorder.cpp b/src/lib/md/relay/RelayRecorder.cpp index 5be30acb3..89c64a919 100644 --- a/src/lib/md/relay/RelayRecorder.cpp +++ b/src/lib/md/relay/RelayRecorder.cpp @@ -30,7 +30,7 @@ const char *magic = "Co2"; const uint32_t recorder_version = 3; template void writebuf(ofstream &out, const T &pb) { - uint32_t size = pb.ByteSize(); + auto size = static_cast(pb.ByteSizeLong()); out.write(reinterpret_cast(&size), sizeof(size)); bts_assert(pb.SerializeToOstream(&out)); } diff --git a/src/lib/utils/overloaded.h b/src/lib/utils/overloaded.h index 85d2143a9..11e7d1255 100644 --- a/src/lib/utils/overloaded.h +++ b/src/lib/utils/overloaded.h @@ -1,6 +1,6 @@ #pragma once -#if __cplusplus >= 201703L +// #if __cplusplus >= 201703L #include // Helper to visit std::variant namespace bts { @@ -8,4 +8,4 @@ template struct overloaded : Ts... { using Ts::operator()...; }; template overloaded(Ts...) -> overloaded; // not needed as of C++20 } // namespace bts -#endif +// #endif diff --git a/tools/buildspark.cmd b/tools/buildspark.cmd index 635358465..c15211712 100644 --- a/tools/buildspark.cmd +++ b/tools/buildspark.cmd @@ -1,31 +1,19 @@ @echo off -if not exist %~dp0\..\.venv27 ( - CALL :create_venv27 -) - -if not exist %~dp0\..\.venv39 ( - CALL :create_venv39 +if not exist %~dp0\..\.venv ( + CALL :create_venv ) touch %~dp0\..\src\lib\CMakeLists.txt -@call %~dp0\..\.venv39\Scripts\activate.bat +@call %~dp0\..\.venv\Scripts\activate.bat @call python %~dp0\..\tools\buildspark.py %* EXIT /B %ERRORLEVEL% -:create_venv27 - echo Creating python27 virtual environment - @call C:\Python27\Scripts\virtualenv %~dp0\..\.venv27 - @call %~dp0\..\.venv27\Scripts\activate.bat - @call %~dp0\..\.venv27\Scripts\pip install -r %~dp0\..\requirements27.txt - @call deactivate - EXIT /B 0 - -:create_venv39 - echo Creating python39 virtual environment - @call python -m venv %~dp0\..\.venv39 - @call %~dp0\..\.venv39\Scripts\activate.bat - @call %~dp0\..\.venv39\Scripts\pip install -r %~dp0\..\requirements39.txt +:create_venv + echo Creating python virtual environment + @call python -m venv %~dp0\..\.venv + @call %~dp0\..\.venv\Scripts\activate.bat + @call %~dp0\..\.venv\Scripts\pip install -r %~dp0\..\requirements.txt @call deactivate EXIT /B 0 diff --git a/tools/buildspark.py b/tools/buildspark.py index 74ed88459..d2f27edec 100644 --- a/tools/buildspark.py +++ b/tools/buildspark.py @@ -40,14 +40,6 @@ class SparkPaths: def externals(): return fr'{_workspace_root()}\externals' - @staticmethod - def venv27(): - return fr'{_workspace_root()}\.venv27' - - @staticmethod - def venv27_prompt(): - return fr'{_workspace_root()}\.venv27\Scripts\activate.bat' - @staticmethod def msbuild(): # Wrap in quotes so spaces don't need to be escaped @@ -151,9 +143,6 @@ if __name__ == "__main__": parser = _get_arg_parser() args = parser.parse_args() - os.environ[ - 'spark_build_python_path'] = fr'{SparkPaths.tools()}\..\externals\windows\bin\python' - args_dict = vars(args) build_dir = _get_arg(args_dict, 'output_dir') or SparkPaths.default_build() clean = args.clean @@ -169,7 +158,7 @@ if __name__ == "__main__": except Exception as e: _exit(e) - build_cmd_steps = [SparkPaths.vs_prompt(), SparkPaths.venv27_prompt()] + build_cmd_steps = [SparkPaths.vs_prompt()] base_output_path_arg = _msbuild_prop_arg( 'BaseOutputPath', f'{build_dir}\\{args.configuration}')