Upgrade ccapi to v6.12.0
This commit is contained in:
1 parent
8069cc893f
commit
90492733fd
109 files changed
+4172
-8930
No files matched your search
@@ -31,7 +31,7 @@
|
||||
#include "rapidjson/stringbuffer.h"
|
||||
#include "rapidjson/writer.h"
|
||||
// clang-format off
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
|
||||
#include "websocketpp/config/boost_config.hpp"
|
||||
#include "websocketpp/client.hpp"
|
||||
#include "websocketpp/common/connection_hdl.hpp"
|
||||
@@ -41,7 +41,7 @@
|
||||
#endif
|
||||
// clang-format on
|
||||
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
|
||||
#if defined(CCAPI_ENABLE_SERVICE_MARKET_DATA) && \
|
||||
(defined(CCAPI_ENABLE_EXCHANGE_HUOBI) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP)) || \
|
||||
defined(CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT) && \
|
||||
@@ -69,9 +69,9 @@
|
||||
namespace beast = boost::beast;
|
||||
namespace http = beast::http;
|
||||
namespace net = boost::asio;
|
||||
namespace ssl = boost::asio::ssl;
|
||||
using tcp = boost::asio::ip::tcp;
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
namespace ssl = net::ssl;
|
||||
using tcp = net::ip::tcp;
|
||||
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
|
||||
namespace wspp = websocketpp;
|
||||
#endif
|
||||
namespace rj = rapidjson;
|
||||
@@ -82,8 +82,8 @@ namespace ccapi {
|
||||
*/
|
||||
class Service : public std::enable_shared_from_this<Service> {
|
||||
public:
|
||||
typedef std::shared_ptr<ServiceContext> ServiceContextPtr;
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
typedef ServiceContext* ServiceContextPtr;
|
||||
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
|
||||
typedef wspp::lib::error_code ErrorCode;
|
||||
#else
|
||||
typedef boost::system::error_code ErrorCode; // a.k.a. beast::error_code
|
||||
@@ -117,16 +117,15 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
sessionConfigs(sessionConfigs),
|
||||
serviceContextPtr(serviceContextPtr),
|
||||
resolver(*serviceContextPtr->ioContextPtr),
|
||||
resolverWs(*serviceContextPtr->ioContextPtr),
|
||||
httpConnectionPool(sessionOptions.httpConnectionPoolMaxSize) {
|
||||
resolverWs(*serviceContextPtr->ioContextPtr) {
|
||||
this->enableCheckPingPongWebsocketProtocolLevel = this->sessionOptions.enableCheckPingPongWebsocketProtocolLevel;
|
||||
this->enableCheckPingPongWebsocketApplicationLevel = this->sessionOptions.enableCheckPingPongWebsocketApplicationLevel;
|
||||
// this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL] = sessionOptions.pingWebsocketProtocolLevelIntervalMilliSeconds;
|
||||
// this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL] = sessionOptions.pongWebsocketProtocolLevelTimeoutMilliSeconds;
|
||||
this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = sessionOptions.pingWebsocketApplicationLevelIntervalMilliSeconds;
|
||||
this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = sessionOptions.pongWebsocketApplicationLevelTimeoutMilliSeconds;
|
||||
this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::FIX_PROTOCOL_LEVEL] = sessionOptions.heartbeatFixIntervalMilliSeconds;
|
||||
this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::FIX_PROTOCOL_LEVEL] = sessionOptions.heartbeatFixTimeoutMilliSeconds;
|
||||
// this->pingIntervalMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL] = sessionOptions.pingWebsocketProtocolLevelIntervalMilliseconds;
|
||||
// this->pongTimeoutMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL] = sessionOptions.pongWebsocketProtocolLevelTimeoutMilliseconds;
|
||||
this->pingIntervalMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = sessionOptions.pingWebsocketApplicationLevelIntervalMilliseconds;
|
||||
this->pongTimeoutMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = sessionOptions.pongWebsocketApplicationLevelTimeoutMilliseconds;
|
||||
this->pingIntervalMillisecondsByMethodMap[PingPongMethod::FIX_PROTOCOL_LEVEL] = sessionOptions.heartbeatFixIntervalMilliseconds;
|
||||
this->pongTimeoutMillisecondsByMethodMap[PingPongMethod::FIX_PROTOCOL_LEVEL] = sessionOptions.heartbeatFixTimeoutMilliseconds;
|
||||
}
|
||||
virtual ~Service() {
|
||||
for (const auto& x : this->pingTimerByMethodByConnectionIdMap) {
|
||||
@@ -142,11 +141,20 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
for (const auto& x : this->connectRetryOnFailTimerByConnectionIdMap) {
|
||||
x.second->cancel();
|
||||
}
|
||||
if (this->httpConnectionPoolPurgeTimer) {
|
||||
this->httpConnectionPoolPurgeTimer->cancel();
|
||||
}
|
||||
void purgeHttpConnectionPool() { this->httpConnectionPool.clear(); }
|
||||
void purgeHttpConnectionPool(const std::string& localIpAddress) { this->httpConnectionPool.erase(localIpAddress); }
|
||||
void purgeHttpConnectionPool(const std::string& localIpAddress, const std::string& baseUrl) { this->httpConnectionPool[localIpAddress].erase(baseUrl); }
|
||||
void forceCloseWebsocketConnections() {
|
||||
for (const auto& x : this->wsConnectionByIdMap) {
|
||||
ErrorCode ec;
|
||||
auto wsConnectionPtr = x.second;
|
||||
this->close(wsConnectionPtr, beast::websocket::close_code::normal, beast::websocket::close_reason("force close"), ec);
|
||||
if (ec) {
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "shutdown");
|
||||
}
|
||||
}
|
||||
}
|
||||
void purgeHttpConnectionPool() { this->httpConnectionPool.purge(); }
|
||||
void stop() {
|
||||
for (const auto& x : this->sendRequestDelayTimerByCorrelationIdMap) {
|
||||
x.second->cancel();
|
||||
@@ -155,21 +163,12 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
this->shouldContinue = false;
|
||||
for (const auto& x : this->wsConnectionByIdMap) {
|
||||
ErrorCode ec;
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
auto wsConnection = x.second;
|
||||
this->close(wsConnection, wsConnection.hdl, websocketpp::close::status::normal, "stop", ec);
|
||||
#else
|
||||
auto wsConnectionPtr = x.second;
|
||||
this->close(wsConnectionPtr, beast::websocket::close_code::normal, beast::websocket::close_reason("stop"), ec);
|
||||
#endif
|
||||
if (ec) {
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "shutdown");
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnection.id] = false;
|
||||
#else
|
||||
this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnectionPtr->id] = false;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
virtual void convertRequestForRestCustom(http::request<http::string_body>& req, const Request& request, const TimePoint& now, const std::string& symbolId,
|
||||
@@ -182,14 +181,14 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
const std::map<std::string, std::string>& credential) {}
|
||||
virtual void processSuccessfulTextMessageRest(int statusCode, const Request& request, const std::string& textMessage, const TimePoint& timeReceived,
|
||||
Queue<Event>* eventQueuePtr) {}
|
||||
std::shared_ptr<std::future<void>> sendRequest(Request& request, const bool useFuture, const TimePoint& now, long delayMilliSeconds,
|
||||
std::shared_ptr<std::future<void>> sendRequest(Request& request, const bool useFuture, const TimePoint& now, long delayMilliseconds,
|
||||
Queue<Event>* eventQueuePtr) {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
CCAPI_LOGGER_DEBUG("request = " + toString(request));
|
||||
CCAPI_LOGGER_DEBUG("useFuture = " + toString(useFuture));
|
||||
TimePoint then;
|
||||
if (delayMilliSeconds > 0) {
|
||||
then = now + std::chrono::milliseconds(delayMilliSeconds);
|
||||
if (delayMilliseconds > 0) {
|
||||
then = now + std::chrono::milliseconds(delayMilliseconds);
|
||||
} else {
|
||||
then = now;
|
||||
}
|
||||
@@ -217,24 +216,24 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
}
|
||||
std::shared_ptr<std::promise<void>> promisePtr(promisePtrRaw);
|
||||
HttpRetry retry(0, 0, "", promisePtr);
|
||||
if (delayMilliSeconds > 0) {
|
||||
TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(delayMilliSeconds)));
|
||||
if (delayMilliseconds > 0) {
|
||||
TimerPtr timerPtr(new net::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(delayMilliseconds)));
|
||||
timerPtr->async_wait([that = shared_from_this(), request, req, retry, eventQueuePtr](ErrorCode const& ec) mutable {
|
||||
if (ec) {
|
||||
CCAPI_LOGGER_ERROR("request = " + toString(request) + ", sendRequest timer error: " + ec.message());
|
||||
that->onError(Event::Type::REQUEST_STATUS, Message::Type::GENERIC_ERROR, ec, "timer", {request.getCorrelationId()}, eventQueuePtr);
|
||||
} else {
|
||||
auto thatReq = req;
|
||||
auto now = UtilTime::now();
|
||||
request.setTimeSent(now);
|
||||
that->tryRequest(request, thatReq, retry, eventQueuePtr);
|
||||
that->tryRequest(request, req, retry, eventQueuePtr);
|
||||
}
|
||||
that->sendRequestDelayTimerByCorrelationIdMap.erase(request.getCorrelationId());
|
||||
});
|
||||
this->sendRequestDelayTimerByCorrelationIdMap[request.getCorrelationId()] = timerPtr;
|
||||
} else {
|
||||
request.setTimeSent(now);
|
||||
this->tryRequest(request, req, retry, eventQueuePtr);
|
||||
net::post(*this->serviceContextPtr->ioContextPtr,
|
||||
[that = shared_from_this(), request, req, retry, eventQueuePtr]() mutable { that->tryRequest(request, req, retry, eventQueuePtr); });
|
||||
}
|
||||
std::shared_ptr<std::future<void>> futurePtr(nullptr);
|
||||
if (useFuture) {
|
||||
@@ -303,10 +302,10 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
// return output;
|
||||
// }
|
||||
typedef ServiceContext::SslContextPtr SslContextPtr;
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
|
||||
typedef ServiceContext::TlsClient TlsClient;
|
||||
#endif
|
||||
typedef std::shared_ptr<boost::asio::steady_timer> TimerPtr;
|
||||
typedef std::shared_ptr<net::steady_timer> TimerPtr;
|
||||
void setHostRestFromUrlRest(std::string baseUrlRest) {
|
||||
auto hostPort = this->extractHostFromUrl(baseUrlRest);
|
||||
this->hostRest = hostPort.first;
|
||||
@@ -341,7 +340,7 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
return std::static_pointer_cast<Derived>(shared_from_this());
|
||||
}
|
||||
void sendRequest(const http::request<http::string_body>& req, std::function<void(const beast::error_code&)> errorHandler,
|
||||
std::function<void(const http::response<http::string_body>&)> responseHandler, long timeoutMilliSeconds) {
|
||||
std::function<void(const http::response<http::string_body>&)> responseHandler, long timeoutMilliseconds) {
|
||||
#if defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE)
|
||||
std::ostringstream oss;
|
||||
oss << req;
|
||||
@@ -358,11 +357,17 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
}
|
||||
std::shared_ptr<HttpConnection> httpConnectionPtr(new HttpConnection(this->hostRest, this->portRest, streamPtr));
|
||||
CCAPI_LOGGER_DEBUG("httpConnection = " + toString(*httpConnectionPtr));
|
||||
this->startConnect(httpConnectionPtr, req, errorHandler, responseHandler, timeoutMilliSeconds, this->tcpResolverResultsRest);
|
||||
std::shared_ptr<tcp::resolver> newResolverPtr(new tcp::resolver(*this->serviceContextPtr->ioContextPtr));
|
||||
CCAPI_LOGGER_TRACE("this->hostRest = " + this->hostRest);
|
||||
CCAPI_LOGGER_TRACE("this->portRest = " + this->portRest);
|
||||
newResolverPtr->async_resolve(this->hostRest, this->portRest,
|
||||
beast::bind_front_handler(&Service::onResolve, shared_from_this(), httpConnectionPtr, newResolverPtr, req, errorHandler,
|
||||
responseHandler, timeoutMilliseconds));
|
||||
// this->startConnect(httpConnectionPtr, req, errorHandler, responseHandler, timeoutMilliseconds, this->tcpResolverResultsRest);
|
||||
}
|
||||
void sendRequest(const std::string& host, const std::string& port, const http::request<http::string_body>& req,
|
||||
std::function<void(const beast::error_code&)> errorHandler, std::function<void(const http::response<http::string_body>&)> responseHandler,
|
||||
long timeoutMilliSeconds) {
|
||||
long timeoutMilliseconds) {
|
||||
#if defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE)
|
||||
std::ostringstream oss;
|
||||
oss << req;
|
||||
@@ -379,26 +384,28 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
std::shared_ptr<HttpConnection> httpConnectionPtr(new HttpConnection(host, port, streamPtr));
|
||||
CCAPI_LOGGER_DEBUG("httpConnection = " + toString(*httpConnectionPtr));
|
||||
std::shared_ptr<tcp::resolver> newResolverPtr(new tcp::resolver(*this->serviceContextPtr->ioContextPtr));
|
||||
CCAPI_LOGGER_TRACE("host = " + host);
|
||||
CCAPI_LOGGER_TRACE("port = " + port);
|
||||
newResolverPtr->async_resolve(host, port,
|
||||
beast::bind_front_handler(&Service::onResolve, shared_from_this(), httpConnectionPtr, newResolverPtr, req, errorHandler,
|
||||
responseHandler, timeoutMilliSeconds));
|
||||
responseHandler, timeoutMilliseconds));
|
||||
}
|
||||
void onResolve(std::shared_ptr<HttpConnection> httpConnectionPtr, std::shared_ptr<tcp::resolver> newResolverPtr, http::request<http::string_body> req,
|
||||
std::function<void(const beast::error_code&)> errorHandler, std::function<void(const http::response<http::string_body>&)> responseHandler,
|
||||
long timeoutMilliSeconds, beast::error_code ec, tcp::resolver::results_type tcpNewResolverResults) {
|
||||
long timeoutMilliseconds, beast::error_code ec, tcp::resolver::results_type tcpNewResolverResults) {
|
||||
if (ec) {
|
||||
CCAPI_LOGGER_TRACE("fail");
|
||||
errorHandler(ec);
|
||||
return;
|
||||
}
|
||||
this->startConnect(httpConnectionPtr, req, errorHandler, responseHandler, timeoutMilliSeconds, tcpNewResolverResults);
|
||||
this->startConnect(httpConnectionPtr, req, errorHandler, responseHandler, timeoutMilliseconds, tcpNewResolverResults);
|
||||
}
|
||||
void startConnect(std::shared_ptr<HttpConnection> httpConnectionPtr, http::request<http::string_body> req,
|
||||
std::function<void(const beast::error_code&)> errorHandler, std::function<void(const http::response<http::string_body>&)> responseHandler,
|
||||
long timeoutMilliSeconds, tcp::resolver::results_type tcpNewResolverResults) {
|
||||
long timeoutMilliseconds, tcp::resolver::results_type tcpNewResolverResults) {
|
||||
beast::ssl_stream<beast::tcp_stream>& stream = *httpConnectionPtr->streamPtr;
|
||||
if (timeoutMilliSeconds > 0) {
|
||||
beast::get_lowest_layer(stream).expires_after(std::chrono::milliseconds(timeoutMilliSeconds));
|
||||
if (timeoutMilliseconds > 0) {
|
||||
beast::get_lowest_layer(stream).expires_after(std::chrono::milliseconds(timeoutMilliseconds));
|
||||
}
|
||||
CCAPI_LOGGER_TRACE("before async_connect");
|
||||
beast::get_lowest_layer(stream).async_connect(
|
||||
@@ -488,7 +495,7 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
responseHandler(*resPtr);
|
||||
}
|
||||
template <class T>
|
||||
std::shared_ptr<T> createStream(std::shared_ptr<net::io_context> iocPtr, std::shared_ptr<net::ssl::context> ctxPtr, const std::string& host) {
|
||||
std::shared_ptr<T> createStream(net::io_context* iocPtr, net::ssl::context* ctxPtr, const std::string& host) {
|
||||
std::shared_ptr<T> streamPtr(new T(*iocPtr, *ctxPtr));
|
||||
// Set SNI Hostname (many hosts need this to handshake successfully)
|
||||
if (!SSL_set_tlsext_host_name(streamPtr->native_handle(), host.c_str())) {
|
||||
@@ -498,25 +505,15 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
}
|
||||
return streamPtr;
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
|
||||
#else
|
||||
template <>
|
||||
std::shared_ptr<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>> createStream(std::shared_ptr<net::io_context> iocPtr,
|
||||
std::shared_ptr<net::ssl::context> ctxPtr,
|
||||
const std::string& host) {
|
||||
CCAPI_LOGGER_TRACE("host = " + host)
|
||||
std::shared_ptr<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>> createWsStream(net::io_context* iocPtr, net::ssl::context* ctxPtr) {
|
||||
std::shared_ptr<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>> streamPtr(
|
||||
new beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>(*iocPtr, *ctxPtr));
|
||||
// Set SNI Hostname (many hosts need this to handshake successfully)
|
||||
if (!SSL_set_tlsext_host_name(streamPtr->next_layer().native_handle(), host.c_str())) {
|
||||
beast::error_code ec{static_cast<int>(::ERR_get_error()), net::error::get_ssl_category()};
|
||||
CCAPI_LOGGER_DEBUG("error SSL_set_tlsext_host_name: " + ec.message());
|
||||
throw ec;
|
||||
}
|
||||
return streamPtr;
|
||||
}
|
||||
#endif
|
||||
// std::shared_ptr<beast::ssl_stream<beast::tcp_stream>> createStream(std::shared_ptr<net::io_context> iocPtr, std::shared_ptr<net::ssl::context> ctxPtr,
|
||||
// std::shared_ptr<beast::ssl_stream<beast::tcp_stream>> createStream(net::io_context* iocPtr, net::ssl::context* ctxPtr,
|
||||
// const std::string& host) {
|
||||
// std::shared_ptr<beast::ssl_stream<beast::tcp_stream>> streamPtr(new beast::ssl_stream<beast::tcp_stream>(*iocPtr, *ctxPtr));
|
||||
// // Set SNI Hostname (many hosts need this to handshake successfully)
|
||||
@@ -527,31 +524,120 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
// }
|
||||
// return streamPtr;
|
||||
// }
|
||||
void performRequest(std::shared_ptr<HttpConnection> httpConnectionPtr, const Request& request, http::request<http::string_body>& req, const HttpRetry& retry,
|
||||
Queue<Event>* eventQueuePtr) {
|
||||
void performRequestWithNewHttpConnection(std::shared_ptr<HttpConnection> httpConnectionPtr, const Request& request, http::request<http::string_body>& req,
|
||||
const HttpRetry& retry, Queue<Event>* eventQueuePtr) {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
CCAPI_LOGGER_DEBUG("httpConnection = " + toString(*httpConnectionPtr));
|
||||
CCAPI_LOGGER_DEBUG("request = " + toString(request));
|
||||
CCAPI_LOGGER_DEBUG("retry = " + toString(retry));
|
||||
beast::ssl_stream<beast::tcp_stream>& stream = *httpConnectionPtr->streamPtr;
|
||||
CCAPI_LOGGER_DEBUG("this->sessionOptions.httpRequestTimeoutMilliSeconds = " + toString(this->sessionOptions.httpRequestTimeoutMilliSeconds));
|
||||
if (this->sessionOptions.httpRequestTimeoutMilliSeconds > 0) {
|
||||
beast::get_lowest_layer(stream).expires_after(std::chrono::milliseconds(this->sessionOptions.httpRequestTimeoutMilliSeconds));
|
||||
CCAPI_LOGGER_DEBUG("this->sessionOptions.httpRequestTimeoutMilliseconds = " + toString(this->sessionOptions.httpRequestTimeoutMilliseconds));
|
||||
if (this->sessionOptions.httpRequestTimeoutMilliseconds > 0) {
|
||||
beast::get_lowest_layer(stream).expires_after(std::chrono::milliseconds(this->sessionOptions.httpRequestTimeoutMilliseconds));
|
||||
}
|
||||
CCAPI_LOGGER_TRACE("before async_connect");
|
||||
beast::get_lowest_layer(stream).async_connect(
|
||||
this->tcpResolverResultsRest,
|
||||
beast::bind_front_handler(&Service::onConnect_2, shared_from_this(), httpConnectionPtr, request, req, retry, eventQueuePtr));
|
||||
CCAPI_LOGGER_TRACE("after async_connect");
|
||||
const auto& localIpAddress = request.getLocalIpAddress();
|
||||
CCAPI_LOGGER_TRACE("localIpAddress = " + localIpAddress);
|
||||
if (!localIpAddress.empty()) {
|
||||
if (!beast::get_lowest_layer(stream).socket().is_open()) {
|
||||
ErrorCode ec;
|
||||
CCAPI_LOGGER_TRACE("before socket open");
|
||||
beast::get_lowest_layer(stream).socket().open(net::ip::tcp::v4(), ec);
|
||||
if (ec) {
|
||||
CCAPI_LOGGER_TRACE("fail");
|
||||
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "socket open", {request.getCorrelationId()}, eventQueuePtr);
|
||||
return;
|
||||
}
|
||||
}
|
||||
ErrorCode ec;
|
||||
tcp::endpoint existingLocalEndpoint = beast::get_lowest_layer(stream).socket().local_endpoint(ec);
|
||||
if (ec) {
|
||||
CCAPI_LOGGER_TRACE("fail");
|
||||
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "socket get local endpoint", {request.getCorrelationId()},
|
||||
eventQueuePtr);
|
||||
return;
|
||||
}
|
||||
tcp::endpoint localEndpoint(net::ip::address::from_string(localIpAddress),
|
||||
0); // Note: Setting the port to 0 means the OS will select a free port for you
|
||||
if (localEndpoint != existingLocalEndpoint) {
|
||||
ErrorCode ec;
|
||||
CCAPI_LOGGER_TRACE("before socket bind");
|
||||
beast::get_lowest_layer(stream).socket().bind(localEndpoint, ec);
|
||||
if (ec) {
|
||||
CCAPI_LOGGER_TRACE("fail");
|
||||
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "socket bind", {request.getCorrelationId()}, eventQueuePtr);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
std::shared_ptr<tcp::resolver> newResolverPtr(new tcp::resolver(*this->serviceContextPtr->ioContextPtr));
|
||||
CCAPI_LOGGER_TRACE("httpConnectionPtr->host = " + httpConnectionPtr->host);
|
||||
CCAPI_LOGGER_TRACE("httpConnectionPtr->port = " + httpConnectionPtr->port);
|
||||
newResolverPtr->async_resolve(
|
||||
httpConnectionPtr->host, httpConnectionPtr->port,
|
||||
beast::bind_front_handler(&Service::onResolveWorkaround, shared_from_this(), httpConnectionPtr, newResolverPtr, request, req, retry, eventQueuePtr));
|
||||
CCAPI_LOGGER_FUNCTION_EXIT;
|
||||
}
|
||||
void onConnect_2(std::shared_ptr<HttpConnection> httpConnectionPtr, Request request, http::request<http::string_body> req, HttpRetry retry,
|
||||
Queue<Event>* eventQueuePtr, beast::error_code ec, tcp::resolver::results_type::endpoint_type) {
|
||||
CCAPI_LOGGER_TRACE("async_connect callback start");
|
||||
void onResolveWorkaround(std::shared_ptr<HttpConnection> httpConnectionPtr, std::shared_ptr<tcp::resolver> newResolverPtr, Request request,
|
||||
http::request<http::string_body> req, HttpRetry retry, Queue<Event>* eventQueuePtr, beast::error_code ec,
|
||||
tcp::resolver::results_type tcpNewResolverResults) {
|
||||
if (ec) {
|
||||
CCAPI_LOGGER_TRACE("fail");
|
||||
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "DNS resolve", {request.getCorrelationId()}, eventQueuePtr);
|
||||
return;
|
||||
}
|
||||
CCAPI_LOGGER_TRACE("before asyncConnectWorkaround");
|
||||
TimerPtr timerPtr{nullptr};
|
||||
if (this->sessionOptions.httpRequestTimeoutMilliseconds > 0) {
|
||||
timerPtr = std::make_shared<boost::asio::steady_timer>(*this->serviceContextPtr->ioContextPtr,
|
||||
std::chrono::milliseconds(this->sessionOptions.httpRequestTimeoutMilliseconds));
|
||||
timerPtr->async_wait([httpConnectionPtr](ErrorCode const& ec) {
|
||||
if (ec) {
|
||||
if (ec != net::error::make_error_code(net::error::basic_errors::operation_aborted)) {
|
||||
CCAPI_LOGGER_ERROR("httpConnectionPtr = " + toString(*httpConnectionPtr) + ", connect timeout timer error: " + ec.message());
|
||||
}
|
||||
} else {
|
||||
CCAPI_LOGGER_TRACE("httpConnectionPtr = " + toString(*httpConnectionPtr) + ", connect timeout timer triggered");
|
||||
beast::ssl_stream<beast::tcp_stream>& stream = *httpConnectionPtr->streamPtr;
|
||||
beast::get_lowest_layer(stream).socket().cancel();
|
||||
}
|
||||
});
|
||||
}
|
||||
this->asyncConnectWorkaround(httpConnectionPtr, timerPtr, request, req, retry, eventQueuePtr, tcpNewResolverResults, 0);
|
||||
CCAPI_LOGGER_TRACE("after asyncConnectWorkaround");
|
||||
}
|
||||
// used to avoid asio close and reopen the socket and therefore losing the bound local ip address
|
||||
void asyncConnectWorkaround(std::shared_ptr<HttpConnection> httpConnectionPtr, TimerPtr timerPtr, Request request, http::request<http::string_body> req,
|
||||
HttpRetry retry, Queue<Event>* eventQueuePtr, tcp::resolver::results_type tcpNewResolverResults,
|
||||
size_t tcpNewResolverResultsIndex) {
|
||||
auto it = tcpNewResolverResults.begin();
|
||||
std::advance(it, tcpNewResolverResultsIndex);
|
||||
if (it == tcpNewResolverResults.end()) {
|
||||
ErrorCode ec = net::error::make_error_code(net::error::misc_errors::not_found);
|
||||
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "connect", {request.getCorrelationId()}, eventQueuePtr);
|
||||
return;
|
||||
}
|
||||
CCAPI_LOGGER_TRACE("before async_connect");
|
||||
beast::ssl_stream<beast::tcp_stream>& stream = *httpConnectionPtr->streamPtr;
|
||||
beast::get_lowest_layer(stream).socket().async_connect(
|
||||
*it, beast::bind_front_handler(&Service::onConnect_2, shared_from_this(), httpConnectionPtr, timerPtr, request, req, retry, eventQueuePtr,
|
||||
tcpNewResolverResults, tcpNewResolverResultsIndex));
|
||||
CCAPI_LOGGER_TRACE("after async_connect");
|
||||
}
|
||||
void onConnect_2(std::shared_ptr<HttpConnection> httpConnectionPtr, TimerPtr timerPtr, Request request, http::request<http::string_body> req, HttpRetry retry,
|
||||
Queue<Event>* eventQueuePtr, tcp::resolver::results_type tcpNewResolverResults, size_t tcpNewResolverResultsIndex, beast::error_code ec) {
|
||||
CCAPI_LOGGER_TRACE("async_connect callback start");
|
||||
CCAPI_LOGGER_TRACE("local endpoint has address " + beast::get_lowest_layer(*httpConnectionPtr->streamPtr).socket().local_endpoint().address().to_string());
|
||||
if (ec) {
|
||||
CCAPI_LOGGER_TRACE("fail");
|
||||
if (ec == net::error::make_error_code(net::error::basic_errors::operation_aborted)) {
|
||||
CCAPI_LOGGER_TRACE("fail");
|
||||
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "connect attempt timeout", {request.getCorrelationId()}, eventQueuePtr);
|
||||
return;
|
||||
}
|
||||
this->asyncConnectWorkaround(httpConnectionPtr, timerPtr, request, req, retry, eventQueuePtr, tcpNewResolverResults, tcpNewResolverResultsIndex + 1);
|
||||
return;
|
||||
}
|
||||
timerPtr->cancel();
|
||||
CCAPI_LOGGER_TRACE("connected");
|
||||
beast::ssl_stream<beast::tcp_stream>& stream = *httpConnectionPtr->streamPtr;
|
||||
// #ifdef CCAPI_DISABLE_NAGLE_ALGORITHM
|
||||
@@ -576,8 +662,8 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
void startWrite_2(std::shared_ptr<HttpConnection> httpConnectionPtr, Request request, http::request<http::string_body> req, HttpRetry retry,
|
||||
Queue<Event>* eventQueuePtr) {
|
||||
beast::ssl_stream<beast::tcp_stream>& stream = *httpConnectionPtr->streamPtr;
|
||||
if (this->sessionOptions.httpRequestTimeoutMilliSeconds > 0) {
|
||||
beast::get_lowest_layer(stream).expires_after(std::chrono::milliseconds(this->sessionOptions.httpRequestTimeoutMilliSeconds));
|
||||
if (this->sessionOptions.httpRequestTimeoutMilliseconds > 0) {
|
||||
beast::get_lowest_layer(stream).expires_after(std::chrono::milliseconds(this->sessionOptions.httpRequestTimeoutMilliseconds));
|
||||
}
|
||||
std::shared_ptr<http::request<http::string_body>> reqPtr(new http::request<http::string_body>(std::move(req)));
|
||||
CCAPI_LOGGER_TRACE("before async_write");
|
||||
@@ -592,7 +678,7 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
if (ec) {
|
||||
CCAPI_LOGGER_TRACE("fail");
|
||||
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "write", {request.getCorrelationId()}, eventQueuePtr);
|
||||
this->httpConnectionPool.purge();
|
||||
this->httpConnectionPool[request.getLocalIpAddress()][request.getBaseUrl()].clear();
|
||||
auto now = UtilTime::now();
|
||||
auto req = this->convertRequest(request, now);
|
||||
retry.numRetry += 1;
|
||||
@@ -609,32 +695,17 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
beast::bind_front_handler(&Service::onRead_2, shared_from_this(), httpConnectionPtr, request, reqPtr, retry, bufferPtr, resPtr, eventQueuePtr));
|
||||
CCAPI_LOGGER_TRACE("after async_read");
|
||||
}
|
||||
void setHttpConnectionPoolPurgeTimer() {
|
||||
TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(5000)));
|
||||
timerPtr->async_wait([that = shared_from_this()](ErrorCode const& ec) {
|
||||
auto now = UtilTime::now();
|
||||
if (ec) {
|
||||
that->onError(Event::Type::SESSION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer");
|
||||
} else {
|
||||
if (std::chrono::duration_cast<std::chrono::milliseconds>(now - that->lastHttpConnectionPoolPushBackTp).count() >
|
||||
that->sessionOptions.httpConnectionPoolIdleTimeoutMilliSeconds) {
|
||||
that->httpConnectionPool.purge();
|
||||
}
|
||||
that->setHttpConnectionPoolPurgeTimer();
|
||||
}
|
||||
});
|
||||
this->httpConnectionPoolPurgeTimer = timerPtr;
|
||||
}
|
||||
void onRead_2(std::shared_ptr<HttpConnection> httpConnectionPtr, Request request, std::shared_ptr<http::request<http::string_body>> reqPtr, HttpRetry retry,
|
||||
std::shared_ptr<beast::flat_buffer> bufferPtr, std::shared_ptr<http::response<http::string_body>> resPtr, Queue<Event>* eventQueuePtr,
|
||||
beast::error_code ec, std::size_t bytes_transferred) {
|
||||
CCAPI_LOGGER_TRACE("async_read callback start");
|
||||
CCAPI_LOGGER_TRACE("local endpoint has address " + beast::get_lowest_layer(*httpConnectionPtr->streamPtr).socket().local_endpoint().address().to_string());
|
||||
auto now = UtilTime::now();
|
||||
boost::ignore_unused(bytes_transferred);
|
||||
if (ec) {
|
||||
CCAPI_LOGGER_TRACE("fail");
|
||||
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "read", {request.getCorrelationId()}, eventQueuePtr);
|
||||
this->httpConnectionPool.purge();
|
||||
this->httpConnectionPool[request.getLocalIpAddress()][request.getBaseUrl()].clear();
|
||||
auto now = UtilTime::now();
|
||||
auto req = this->convertRequest(request, now);
|
||||
retry.numRetry += 1;
|
||||
@@ -642,19 +713,17 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
return;
|
||||
}
|
||||
if (!this->sessionOptions.enableOneHttpConnectionPerRequest) {
|
||||
try {
|
||||
if (std::chrono::duration_cast<std::chrono::seconds>(this->lastHttpConnectionPoolPushBackTp.time_since_epoch()).count() == 0 &&
|
||||
this->sessionOptions.httpConnectionPoolIdleTimeoutMilliSeconds > 0) {
|
||||
this->setHttpConnectionPoolPurgeTimer();
|
||||
}
|
||||
this->httpConnectionPool.pushBack(std::move(httpConnectionPtr));
|
||||
this->lastHttpConnectionPoolPushBackTp = now;
|
||||
CCAPI_LOGGER_TRACE("pushed back httpConnectionPtr " + toString(*httpConnectionPtr) + " to pool");
|
||||
} catch (const std::runtime_error& e) {
|
||||
if (e.what() != this->httpConnectionPool.EXCEPTION_QUEUE_FULL) {
|
||||
CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
httpConnectionPtr->lastReceiveDataTp = now;
|
||||
const auto& localIpAddress = request.getLocalIpAddress();
|
||||
const auto& requestBaseUrl = request.getBaseUrl();
|
||||
if (this->sessionOptions.httpConnectionPoolMaxSize > 0 &&
|
||||
this->httpConnectionPool[localIpAddress][requestBaseUrl].size() >= this->sessionOptions.httpConnectionPoolMaxSize) {
|
||||
CCAPI_LOGGER_TRACE("httpConnectionPool is full for localIpAddress = " + localIpAddress + ", requestBaseUrl = " + toString(requestBaseUrl));
|
||||
this->httpConnectionPool[localIpAddress][requestBaseUrl].pop_front();
|
||||
}
|
||||
this->httpConnectionPool[localIpAddress][requestBaseUrl].push_back(httpConnectionPtr);
|
||||
CCAPI_LOGGER_TRACE("pushed back httpConnectionPtr " + toString(*httpConnectionPtr) + " to httpConnectionPool for localIpAddress = " + localIpAddress +
|
||||
", requestBaseUrl = " + toString(requestBaseUrl));
|
||||
}
|
||||
#if defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE)
|
||||
{
|
||||
@@ -737,7 +806,13 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
CCAPI_LOGGER_TRACE("retry = " + toString(retry));
|
||||
if (retry.numRetry <= this->sessionOptions.httpMaxNumRetry && retry.numRedirect <= this->sessionOptions.httpMaxNumRedirect) {
|
||||
try {
|
||||
if (this->sessionOptions.enableOneHttpConnectionPerRequest || this->httpConnectionPool.empty()) {
|
||||
const auto& localIpAddress = request.getLocalIpAddress();
|
||||
const auto& requestBaseUrl = request.getBaseUrl();
|
||||
if (this->sessionOptions.enableOneHttpConnectionPerRequest || this->httpConnectionPool[localIpAddress][requestBaseUrl].empty() ||
|
||||
std::chrono::duration_cast<std::chrono::seconds>(request.getTimeSent() -
|
||||
this->httpConnectionPool[localIpAddress][requestBaseUrl].back()->lastReceiveDataTp)
|
||||
.count() >= this->sessionOptions.httpConnectionKeepAliveTimeoutSeconds) {
|
||||
this->httpConnectionPool[localIpAddress][requestBaseUrl].clear();
|
||||
std::shared_ptr<beast::ssl_stream<beast::tcp_stream>> streamPtr(nullptr);
|
||||
try {
|
||||
streamPtr = this->createStream<beast::ssl_stream<beast::tcp_stream>>(this->serviceContextPtr->ioContextPtr, this->serviceContextPtr->sslContextPtr,
|
||||
@@ -747,32 +822,24 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "create stream", {request.getCorrelationId()}, eventQueuePtr);
|
||||
return;
|
||||
}
|
||||
std::shared_ptr<HttpConnection> httpConnectionPtr(new HttpConnection(this->hostRest, this->portRest, streamPtr));
|
||||
CCAPI_LOGGER_WARN("about to perform request with new httpConnectionPtr " + toString(*httpConnectionPtr));
|
||||
this->performRequest(httpConnectionPtr, request, req, retry, eventQueuePtr);
|
||||
} else {
|
||||
std::shared_ptr<HttpConnection> httpConnectionPtr(nullptr);
|
||||
try {
|
||||
httpConnectionPtr = std::move(this->httpConnectionPool.popBack());
|
||||
CCAPI_LOGGER_TRACE("about to perform request with existing httpConnectionPtr " + toString(*httpConnectionPtr));
|
||||
this->startWrite_2(httpConnectionPtr, request, req, retry, eventQueuePtr);
|
||||
} catch (const std::runtime_error& e) {
|
||||
if (e.what() != this->httpConnectionPool.EXCEPTION_QUEUE_EMPTY) {
|
||||
CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
std::shared_ptr<beast::ssl_stream<beast::tcp_stream>> streamPtr(nullptr);
|
||||
try {
|
||||
streamPtr = this->createStream<beast::ssl_stream<beast::tcp_stream>>(this->serviceContextPtr->ioContextPtr,
|
||||
this->serviceContextPtr->sslContextPtr, this->hostRest);
|
||||
} catch (const beast::error_code& ec) {
|
||||
CCAPI_LOGGER_TRACE("fail");
|
||||
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "create stream", {request.getCorrelationId()}, eventQueuePtr);
|
||||
return;
|
||||
}
|
||||
httpConnectionPtr = std::make_shared<HttpConnection>(this->hostRest, this->portRest, streamPtr);
|
||||
CCAPI_LOGGER_WARN("about to perform request with new httpConnectionPtr " + toString(*httpConnectionPtr));
|
||||
this->performRequest(httpConnectionPtr, request, req, retry, eventQueuePtr);
|
||||
std::string host, port;
|
||||
if (requestBaseUrl.empty()) {
|
||||
host = this->hostRest;
|
||||
port = this->portRest;
|
||||
} else {
|
||||
host = request.getHost();
|
||||
port = request.getPort();
|
||||
}
|
||||
std::shared_ptr<HttpConnection> httpConnectionPtr(new HttpConnection(host, port, streamPtr));
|
||||
CCAPI_LOGGER_WARN("about to perform request with new httpConnectionPtr " + toString(*httpConnectionPtr) + " for localIpAddress = " + localIpAddress +
|
||||
", requestBaseUrl = " + toString(requestBaseUrl));
|
||||
this->performRequestWithNewHttpConnection(httpConnectionPtr, request, req, retry, eventQueuePtr);
|
||||
} else {
|
||||
std::shared_ptr<HttpConnection> httpConnectionPtr = this->httpConnectionPool[localIpAddress][requestBaseUrl].back();
|
||||
this->httpConnectionPool[localIpAddress][requestBaseUrl].pop_back();
|
||||
CCAPI_LOGGER_TRACE("about to perform request with existing httpConnectionPtr " + toString(*httpConnectionPtr) +
|
||||
" for localIpAddress = " + localIpAddress + ", requestBaseUrl = " + toString(requestBaseUrl));
|
||||
this->startWrite_2(httpConnectionPtr, request, req, retry, eventQueuePtr);
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what());
|
||||
@@ -805,7 +872,7 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
} else {
|
||||
req.keep_alive(true);
|
||||
}
|
||||
req.set(http::field::host, this->hostRest);
|
||||
req.set(http::field::host, request.getBaseUrl().empty() ? this->hostRest : request.getHost());
|
||||
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
|
||||
this->convertRequestForRest(req, request, now, symbolId, credential);
|
||||
CCAPI_LOGGER_FUNCTION_EXIT;
|
||||
@@ -821,14 +888,15 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
}
|
||||
}
|
||||
}
|
||||
void appendParam(std::string& queryString, const std::map<std::string, std::string>& param,
|
||||
const std::map<std::string, std::string> standardizationMap = {}) {
|
||||
void appendParam(std::string& queryString, const std::map<std::string, std::string>& param, const std::map<std::string, std::string> standardizationMap = {},
|
||||
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) {
|
||||
int i = 0;
|
||||
for (const auto& kv : param) {
|
||||
std::string key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
|
||||
queryString += key;
|
||||
queryString += "=";
|
||||
queryString += Url::urlEncode(kv.second);
|
||||
std::string value = conversionMap.find(kv.first) != conversionMap.end() ? conversionMap.at(kv.first)(kv.second) : kv.second;
|
||||
queryString += Url::urlEncode(value);
|
||||
queryString += "&";
|
||||
++i;
|
||||
}
|
||||
@@ -857,7 +925,7 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
std::string methodStringUpper = UtilString::toUpper(methodString);
|
||||
return http::string_to_verb(methodStringUpper);
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
|
||||
SslContextPtr onTlsInit(wspp::connection_hdl hdl) { return this->serviceContextPtr->sslContextPtr; }
|
||||
WsConnection& getWsConnectionFromConnectionPtr(TlsClient::connection_ptr connectionPtr) {
|
||||
return this->wsConnectionByIdMap.at(this->connectionAddressToString(connectionPtr));
|
||||
@@ -954,7 +1022,7 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
if (this->connectRetryOnFailTimerByConnectionIdMap.find(thisWsConnection.id) != this->connectRetryOnFailTimerByConnectionIdMap.end()) {
|
||||
this->connectRetryOnFailTimerByConnectionIdMap.at(thisWsConnection.id)->cancel();
|
||||
}
|
||||
TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(seconds * 1000)));
|
||||
TimerPtr timerPtr(new net::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(seconds * 1000)));
|
||||
timerPtr->async_wait([thisWsConnection, that = shared_from_this(), urlBase](ErrorCode const& ec) {
|
||||
if (that->wsConnectionByIdMap.find(thisWsConnection.id) == that->wsConnectionByIdMap.end()) {
|
||||
if (ec) {
|
||||
@@ -1120,11 +1188,11 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
std::function<void(wspp::connection_hdl, ErrorCode&)> pingMethod) {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
CCAPI_LOGGER_TRACE("method = " + pingPongMethodToString(method));
|
||||
auto pingIntervalMilliSeconds = this->pingIntervalMilliSecondsByMethodMap[method];
|
||||
auto pongTimeoutMilliSeconds = this->pongTimeoutMilliSecondsByMethodMap[method];
|
||||
CCAPI_LOGGER_TRACE("pingIntervalMilliSeconds = " + toString(pingIntervalMilliSeconds));
|
||||
CCAPI_LOGGER_TRACE("pongTimeoutMilliSeconds = " + toString(pongTimeoutMilliSeconds));
|
||||
if (pingIntervalMilliSeconds <= pongTimeoutMilliSeconds) {
|
||||
auto pingIntervalMilliseconds = this->pingIntervalMillisecondsByMethodMap[method];
|
||||
auto pongTimeoutMilliseconds = this->pongTimeoutMillisecondsByMethodMap[method];
|
||||
CCAPI_LOGGER_TRACE("pingIntervalMilliseconds = " + toString(pingIntervalMilliseconds));
|
||||
CCAPI_LOGGER_TRACE("pongTimeoutMilliseconds = " + toString(pongTimeoutMilliseconds));
|
||||
if (pingIntervalMilliseconds <= pongTimeoutMilliseconds) {
|
||||
return;
|
||||
}
|
||||
if (wsConnection.status == WsConnection::Status::OPEN) {
|
||||
@@ -1133,8 +1201,8 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
this->pingTimerByMethodByConnectionIdMap.at(wsConnection.id).at(method)->cancel();
|
||||
}
|
||||
TimerPtr timerPtr(
|
||||
new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pingIntervalMilliSeconds - pongTimeoutMilliSeconds)));
|
||||
timerPtr->async_wait([wsConnection, that = shared_from_this(), hdl, pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) {
|
||||
new net::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pingIntervalMilliseconds - pongTimeoutMilliseconds)));
|
||||
timerPtr->async_wait([wsConnection, that = shared_from_this(), hdl, pingMethod, pongTimeoutMilliseconds, method](ErrorCode const& ec) {
|
||||
if (that->wsConnectionByIdMap.find(wsConnection.id) != that->wsConnectionByIdMap.end()) {
|
||||
if (ec) {
|
||||
CCAPI_LOGGER_ERROR("wsConnection = " + toString(wsConnection) + ", ping timer error: " + ec.message());
|
||||
@@ -1146,7 +1214,7 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
if (ec) {
|
||||
that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "ping");
|
||||
}
|
||||
if (pongTimeoutMilliSeconds <= 0) {
|
||||
if (pongTimeoutMilliseconds <= 0) {
|
||||
return;
|
||||
}
|
||||
if (that->pongTimeOutTimerByMethodByConnectionIdMap.find(wsConnection.id) != that->pongTimeOutTimerByMethodByConnectionIdMap.end() &&
|
||||
@@ -1154,8 +1222,8 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
that->pongTimeOutTimerByMethodByConnectionIdMap.at(wsConnection.id).end()) {
|
||||
that->pongTimeOutTimerByMethodByConnectionIdMap.at(wsConnection.id).at(method)->cancel();
|
||||
}
|
||||
TimerPtr timerPtr(new boost::asio::steady_timer(*that->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pongTimeoutMilliSeconds)));
|
||||
timerPtr->async_wait([wsConnection, that, hdl, pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) {
|
||||
TimerPtr timerPtr(new net::steady_timer(*that->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pongTimeoutMilliseconds)));
|
||||
timerPtr->async_wait([wsConnection, that, hdl, pingMethod, pongTimeoutMilliseconds, method](ErrorCode const& ec) {
|
||||
if (that->wsConnectionByIdMap.find(wsConnection.id) != that->wsConnectionByIdMap.end()) {
|
||||
if (ec) {
|
||||
CCAPI_LOGGER_ERROR("wsConnection = " + toString(wsConnection) + ", pong time out timer error: " + ec.message());
|
||||
@@ -1167,7 +1235,7 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).find(method) !=
|
||||
that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).end() &&
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(now - that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).at(method))
|
||||
.count() >= pongTimeoutMilliSeconds) {
|
||||
.count() >= pongTimeoutMilliseconds) {
|
||||
auto thisWsConnection = wsConnection;
|
||||
ErrorCode ec;
|
||||
that->close(thisWsConnection, hdl, websocketpp::close::status::normal, "pong timeout", ec);
|
||||
@@ -1213,29 +1281,40 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
WsConnection& wsConnection = *wsConnectionPtr;
|
||||
wsConnection.status = WsConnection::Status::CONNECTING;
|
||||
CCAPI_LOGGER_DEBUG("connection initialization on id " + wsConnection.id);
|
||||
std::string url = wsConnection.url;
|
||||
std::string url = wsConnection.getUrl();
|
||||
CCAPI_LOGGER_DEBUG("url = " + url);
|
||||
this->startResolveWs(wsConnectionPtr);
|
||||
CCAPI_LOGGER_FUNCTION_EXIT;
|
||||
}
|
||||
void startResolveWs(std::shared_ptr<WsConnection> wsConnectionPtr) {
|
||||
std::shared_ptr<tcp::resolver> newResolverPtr(new tcp::resolver(*this->serviceContextPtr->ioContextPtr));
|
||||
CCAPI_LOGGER_TRACE("wsConnectionPtr = " + wsConnectionPtr->toString());
|
||||
CCAPI_LOGGER_TRACE("wsConnectionPtr->host = " + wsConnectionPtr->host);
|
||||
CCAPI_LOGGER_TRACE("wsConnectionPtr->port = " + wsConnectionPtr->port);
|
||||
newResolverPtr->async_resolve(wsConnectionPtr->host, wsConnectionPtr->port,
|
||||
beast::bind_front_handler(&Service::onResolveWs, shared_from_this(), wsConnectionPtr, newResolverPtr));
|
||||
}
|
||||
void onResolveWs(std::shared_ptr<WsConnection> wsConnectionPtr, std::shared_ptr<tcp::resolver> newResolverPtr, beast::error_code ec,
|
||||
tcp::resolver::results_type tcpNewResolverResultsWs) {
|
||||
if (ec) {
|
||||
CCAPI_LOGGER_TRACE("fail");
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "dns resolve", wsConnectionPtr->correlationIdList);
|
||||
CCAPI_LOGGER_TRACE("dns resolve fail");
|
||||
this->onFail(wsConnectionPtr);
|
||||
return;
|
||||
}
|
||||
this->startConnectWs(wsConnectionPtr, this->sessionOptions.websocketConnectTimeoutMilliSeconds, tcpNewResolverResultsWs);
|
||||
this->startConnectWs(wsConnectionPtr, this->sessionOptions.websocketConnectTimeoutMilliseconds, tcpNewResolverResultsWs);
|
||||
}
|
||||
void startConnectWs(std::shared_ptr<WsConnection> wsConnectionPtr, long timeoutMilliSeconds, tcp::resolver::results_type tcpResolverResults) {
|
||||
void startConnectWs(std::shared_ptr<WsConnection> wsConnectionPtr, long timeoutMilliseconds, tcp::resolver::results_type tcpResolverResults) {
|
||||
beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>& stream = *wsConnectionPtr->streamPtr;
|
||||
if (timeoutMilliSeconds > 0) {
|
||||
beast::get_lowest_layer(stream).expires_after(std::chrono::milliseconds(timeoutMilliSeconds));
|
||||
if (timeoutMilliseconds > 0) {
|
||||
beast::get_lowest_layer(stream).expires_after(std::chrono::milliseconds(timeoutMilliseconds));
|
||||
}
|
||||
// Set SNI Hostname (many hosts need this to handshake successfully)
|
||||
CCAPI_LOGGER_TRACE("wsConnectionPtr->host = " + wsConnectionPtr->host)
|
||||
if (!SSL_set_tlsext_host_name(stream.next_layer().native_handle(), wsConnectionPtr->host.c_str())) {
|
||||
beast::error_code ec{static_cast<int>(::ERR_get_error()), net::error::get_ssl_category()};
|
||||
CCAPI_LOGGER_DEBUG("error SSL_set_tlsext_host_name: " + ec.message());
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "set SNI Hostname", wsConnectionPtr->correlationIdList);
|
||||
return;
|
||||
}
|
||||
CCAPI_LOGGER_TRACE("before async_connect");
|
||||
beast::get_lowest_layer(stream).async_connect(tcpResolverResults, beast::bind_front_handler(&Service::onConnectWs, shared_from_this(), wsConnectionPtr));
|
||||
@@ -1250,7 +1329,9 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
}
|
||||
CCAPI_LOGGER_TRACE("connected");
|
||||
CCAPI_LOGGER_TRACE("ep.port() = " + std::to_string(ep.port()));
|
||||
wsConnectionPtr->hostHttpHeaderValue = this->hostWs + ':' + std::to_string(ep.port());
|
||||
wsConnectionPtr->hostHttpHeaderValue =
|
||||
this->hostHttpHeaderValueIgnorePort ? wsConnectionPtr->host : wsConnectionPtr->host + ':' + std::to_string(ep.port());
|
||||
CCAPI_LOGGER_TRACE("wsConnectionPtr->hostHttpHeaderValue = " + wsConnectionPtr->hostHttpHeaderValue);
|
||||
beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>& stream = *wsConnectionPtr->streamPtr;
|
||||
beast::get_lowest_layer(stream).socket().set_option(tcp::no_delay(true));
|
||||
CCAPI_LOGGER_TRACE("before ssl async_handshake");
|
||||
@@ -1260,15 +1341,15 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
void onSslHandshakeWs(std::shared_ptr<WsConnection> wsConnectionPtr, beast::error_code ec) {
|
||||
CCAPI_LOGGER_TRACE("ssl async_handshake callback start");
|
||||
if (ec) {
|
||||
CCAPI_LOGGER_TRACE("fail");
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "ssl handshake", wsConnectionPtr->correlationIdList);
|
||||
CCAPI_LOGGER_TRACE("ssl handshake fail");
|
||||
this->onFail(wsConnectionPtr);
|
||||
return;
|
||||
}
|
||||
CCAPI_LOGGER_TRACE("ssl handshaked");
|
||||
beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>& stream = *wsConnectionPtr->streamPtr;
|
||||
beast::get_lowest_layer(stream).expires_never();
|
||||
beast::websocket::stream_base::timeout opt{std::chrono::milliseconds(this->sessionOptions.websocketConnectTimeoutMilliSeconds),
|
||||
std::chrono::milliseconds(this->sessionOptions.pongWebsocketProtocolLevelTimeoutMilliSeconds), true};
|
||||
beast::websocket::stream_base::timeout opt{std::chrono::milliseconds(this->sessionOptions.websocketConnectTimeoutMilliseconds),
|
||||
std::chrono::milliseconds(this->sessionOptions.pongWebsocketProtocolLevelTimeoutMilliseconds), true};
|
||||
|
||||
stream.set_option(opt);
|
||||
stream.set_option(beast::websocket::stream_base::decorator([wsConnectionPtr](beast::websocket::request_type& req) {
|
||||
@@ -1285,8 +1366,8 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
void onWsHandshakeWs(std::shared_ptr<WsConnection> wsConnectionPtr, beast::error_code ec) {
|
||||
CCAPI_LOGGER_TRACE("ws async_handshake callback start");
|
||||
if (ec) {
|
||||
CCAPI_LOGGER_TRACE("fail");
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "ws handshake", wsConnectionPtr->correlationIdList);
|
||||
CCAPI_LOGGER_TRACE("ws handshake fail");
|
||||
this->onFail(wsConnectionPtr);
|
||||
return;
|
||||
}
|
||||
CCAPI_LOGGER_TRACE("ws handshaked");
|
||||
@@ -1295,7 +1376,9 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
CCAPI_LOGGER_TRACE("about to start read");
|
||||
this->startReadWs(wsConnectionPtr);
|
||||
auto& stream = *wsConnectionPtr->streamPtr;
|
||||
stream.control_callback(beast::bind_front_handler(&Service::onControlCallback, shared_from_this(), wsConnectionPtr));
|
||||
stream.control_callback([wsConnectionPtr, that = shared_from_this()](boost::beast::websocket::frame_type kind, boost::beast::string_view payload) {
|
||||
that->onControlCallback(wsConnectionPtr, kind, payload);
|
||||
});
|
||||
}
|
||||
void startReadWs(std::shared_ptr<WsConnection> wsConnectionPtr) {
|
||||
auto& stream = *wsConnectionPtr->streamPtr;
|
||||
@@ -1305,7 +1388,7 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
stream.async_read(readMessageBuffer, beast::bind_front_handler(&Service::onReadWs, shared_from_this(), wsConnectionPtr));
|
||||
CCAPI_LOGGER_TRACE("after async_read");
|
||||
}
|
||||
void onReadWs(std::shared_ptr<WsConnection> wsConnectionPtr, const boost::system::error_code& ec, std::size_t n) {
|
||||
void onReadWs(std::shared_ptr<WsConnection> wsConnectionPtr, const ErrorCode& ec, std::size_t n) {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
CCAPI_LOGGER_TRACE("n = " + toString(n));
|
||||
auto now = UtilTime::now();
|
||||
@@ -1339,7 +1422,7 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
this->onMessage(wsConnectionPtr, (const char*)readMessageBuffer.data().data(), readMessageBuffer.size());
|
||||
readMessageBuffer.consume(readMessageBuffer.size());
|
||||
this->startReadWs(wsConnectionPtr);
|
||||
this->onPongByMethod(PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL, wsConnectionPtr, now);
|
||||
this->onPongByMethod(PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL, wsConnectionPtr, now, false);
|
||||
CCAPI_LOGGER_FUNCTION_EXIT;
|
||||
}
|
||||
virtual void onOpen(std::shared_ptr<WsConnection> wsConnectionPtr) {
|
||||
@@ -1348,7 +1431,7 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
WsConnection& wsConnection = *wsConnectionPtr;
|
||||
wsConnection.status = WsConnection::Status::OPEN;
|
||||
CCAPI_LOGGER_INFO("connection " + toString(wsConnection) + " established");
|
||||
auto urlBase = UtilString::split(wsConnection.url, "?").at(0);
|
||||
auto urlBase = UtilString::split(wsConnection.getUrl(), "?").at(0);
|
||||
this->connectNumRetryOnFailByConnectionUrlMap[urlBase] = 0;
|
||||
Event event;
|
||||
event.setType(Event::Type::SESSION_STATUS);
|
||||
@@ -1360,7 +1443,7 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
message.setCorrelationIdList(correlationIdList);
|
||||
Element element;
|
||||
element.insert(CCAPI_CONNECTION_ID, wsConnection.id);
|
||||
element.insert(CCAPI_CONNECTION_URL, wsConnection.url);
|
||||
element.insert(CCAPI_CONNECTION_URL, wsConnection.getUrl());
|
||||
message.setElementList({element});
|
||||
event.setMessageList({message});
|
||||
this->eventHandler(event, nullptr);
|
||||
@@ -1386,6 +1469,7 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
memcpy(writeMessageBuffer.data() + n, data, dataSize);
|
||||
writeMessageBufferBoundary.push_back(dataSize);
|
||||
n += dataSize;
|
||||
CCAPI_LOGGER_TRACE("connectionId = " + connectionId);
|
||||
CCAPI_LOGGER_DEBUG("about to send " + std::string(data, dataSize));
|
||||
CCAPI_LOGGER_TRACE("writeMessageBufferWrittenLength = " + toString(writeMessageBufferWrittenLength));
|
||||
if (writeMessageBufferWrittenLength == 0) {
|
||||
@@ -1401,10 +1485,10 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
CCAPI_LOGGER_TRACE("before async_write");
|
||||
CCAPI_LOGGER_TRACE("numBytesToWrite = " + toString(numBytesToWrite));
|
||||
stream.binary(false);
|
||||
stream.async_write(boost::asio::buffer(data, numBytesToWrite), beast::bind_front_handler(&Service::onWriteWs, shared_from_this(), wsConnectionPtr));
|
||||
stream.async_write(net::buffer(data, numBytesToWrite), beast::bind_front_handler(&Service::onWriteWs, shared_from_this(), wsConnectionPtr));
|
||||
CCAPI_LOGGER_TRACE("after async_write");
|
||||
}
|
||||
void onWriteWs(std::shared_ptr<WsConnection> wsConnectionPtr, const boost::system::error_code& ec, std::size_t n) {
|
||||
void onWriteWs(std::shared_ptr<WsConnection> wsConnectionPtr, const ErrorCode& ec, std::size_t n) {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
auto& connectionId = wsConnectionPtr->id;
|
||||
auto& writeMessageBuffer = this->writeMessageBufferByConnectionIdMap[connectionId];
|
||||
@@ -1427,13 +1511,13 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, "connection " + toString(wsConnection) + " has failed before opening");
|
||||
WsConnection thisWsConnection = wsConnection;
|
||||
this->wsConnectionByIdMap.erase(thisWsConnection.id);
|
||||
auto urlBase = UtilString::split(thisWsConnection.url, "?").at(0);
|
||||
auto urlBase = UtilString::split(thisWsConnection.getUrl(), "?").at(0);
|
||||
long seconds = std::round(UtilAlgorithm::exponentialBackoff(1, 1, 2, std::min(this->connectNumRetryOnFailByConnectionUrlMap[urlBase], 6)));
|
||||
CCAPI_LOGGER_INFO("about to set timer for " + toString(seconds) + " seconds");
|
||||
if (this->connectRetryOnFailTimerByConnectionIdMap.find(thisWsConnection.id) != this->connectRetryOnFailTimerByConnectionIdMap.end()) {
|
||||
this->connectRetryOnFailTimerByConnectionIdMap.at(thisWsConnection.id)->cancel();
|
||||
}
|
||||
TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(seconds * 1000)));
|
||||
TimerPtr timerPtr(new net::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(seconds * 1000)));
|
||||
timerPtr->async_wait([wsConnectionPtr, that = shared_from_this(), urlBase](ErrorCode const& ec) {
|
||||
WsConnection& thisWsConnection = *wsConnectionPtr;
|
||||
if (that->wsConnectionByIdMap.find(thisWsConnection.id) == that->wsConnectionByIdMap.end()) {
|
||||
@@ -1460,8 +1544,7 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
std::shared_ptr<WsConnection> thatWsConnectionPtr = wsConnectionPtr;
|
||||
std::shared_ptr<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>> streamPtr(nullptr);
|
||||
try {
|
||||
streamPtr = this->createStream<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>>(this->serviceContextPtr->ioContextPtr,
|
||||
this->serviceContextPtr->sslContextPtr, this->hostWs);
|
||||
streamPtr = this->createWsStream(this->serviceContextPtr->ioContextPtr, this->serviceContextPtr->sslContextPtr);
|
||||
} catch (const beast::error_code& ec) {
|
||||
throw ec;
|
||||
}
|
||||
@@ -1520,7 +1603,7 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
message.setType(Message::Type::SESSION_CONNECTION_DOWN);
|
||||
Element element;
|
||||
element.insert(CCAPI_CONNECTION_ID, wsConnection.id);
|
||||
element.insert(CCAPI_CONNECTION_URL, wsConnection.url);
|
||||
element.insert(CCAPI_CONNECTION_URL, wsConnection.getUrl());
|
||||
element.insert(CCAPI_REASON, reason);
|
||||
message.setElementList({element});
|
||||
std::vector<std::string> correlationIdList;
|
||||
@@ -1602,38 +1685,42 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
}
|
||||
void onPong(std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view payload) {
|
||||
auto now = UtilTime::now();
|
||||
this->onPongByMethod(PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL, wsConnectionPtr, now);
|
||||
this->onPongByMethod(PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL, wsConnectionPtr, now, true);
|
||||
}
|
||||
void onPongByMethod(PingPongMethod method, std::shared_ptr<WsConnection> wsConnectionPtr, const TimePoint& timeReceived) {
|
||||
void onPongByMethod(PingPongMethod method, std::shared_ptr<WsConnection> wsConnectionPtr, const TimePoint& timeReceived, bool truePong) {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
CCAPI_LOGGER_TRACE(pingPongMethodToString(method) + ": received a pong from " + toString(*wsConnectionPtr));
|
||||
CCAPI_LOGGER_TRACE(pingPongMethodToString(method) + ": received a " + (truePong ? "websocket protocol pong" : "data message") + " from " +
|
||||
toString(*wsConnectionPtr));
|
||||
this->lastPongTpByMethodByConnectionIdMap[wsConnectionPtr->id][method] = timeReceived;
|
||||
CCAPI_LOGGER_FUNCTION_EXIT;
|
||||
}
|
||||
void onPing(std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view payload) {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
auto now = UtilTime::now();
|
||||
CCAPI_LOGGER_TRACE("received a ping from " + toString(*wsConnectionPtr));
|
||||
this->lastPongTpByMethodByConnectionIdMap[wsConnectionPtr->id][PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL] = now;
|
||||
CCAPI_LOGGER_FUNCTION_EXIT;
|
||||
}
|
||||
void send(std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view payload, ErrorCode& ec) {
|
||||
this->writeMessage(wsConnectionPtr, payload.data(), payload.length());
|
||||
}
|
||||
void ping(std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view payload, ErrorCode& ec) {
|
||||
if (!this->wsConnectionPendingPingingByIdMap[wsConnectionPtr->id]) {
|
||||
if (!this->wsConnectionPendingPingingByConnectionIdMap[wsConnectionPtr->id]) {
|
||||
auto& stream = *wsConnectionPtr->streamPtr;
|
||||
stream.async_ping("", [that = this, wsConnectionPtr](ErrorCode const& ec) { that->wsConnectionPendingPingingByIdMap[wsConnectionPtr->id] = false; });
|
||||
this->wsConnectionPendingPingingByIdMap[wsConnectionPtr->id] = true;
|
||||
stream.async_ping(
|
||||
"", [that = this, wsConnectionPtr](ErrorCode const& ec) { that->wsConnectionPendingPingingByConnectionIdMap[wsConnectionPtr->id] = false; });
|
||||
this->wsConnectionPendingPingingByConnectionIdMap[wsConnectionPtr->id] = true;
|
||||
}
|
||||
}
|
||||
virtual void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) {}
|
||||
void setPingPongTimer(PingPongMethod method, std::shared_ptr<WsConnection> wsConnectionPtr, std::function<void(ErrorCode&)> pingMethod) {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
CCAPI_LOGGER_TRACE("method = " + pingPongMethodToString(method));
|
||||
auto pingIntervalMilliSeconds = this->pingIntervalMilliSecondsByMethodMap[method];
|
||||
auto pongTimeoutMilliSeconds = this->pongTimeoutMilliSecondsByMethodMap[method];
|
||||
CCAPI_LOGGER_TRACE("pingIntervalMilliSeconds = " + toString(pingIntervalMilliSeconds));
|
||||
CCAPI_LOGGER_TRACE("pongTimeoutMilliSeconds = " + toString(pongTimeoutMilliSeconds));
|
||||
if (pingIntervalMilliSeconds <= pongTimeoutMilliSeconds) {
|
||||
auto pingIntervalMilliseconds = this->pingIntervalMillisecondsByMethodMap[method];
|
||||
auto pongTimeoutMilliseconds = this->pongTimeoutMillisecondsByMethodMap[method];
|
||||
CCAPI_LOGGER_TRACE("pingIntervalMilliseconds = " + toString(pingIntervalMilliseconds));
|
||||
CCAPI_LOGGER_TRACE("pongTimeoutMilliseconds = " + toString(pongTimeoutMilliseconds));
|
||||
if (pingIntervalMilliseconds <= pongTimeoutMilliseconds) {
|
||||
return;
|
||||
}
|
||||
WsConnection& wsConnection = *wsConnectionPtr;
|
||||
@@ -1643,8 +1730,8 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
this->pingTimerByMethodByConnectionIdMap.at(wsConnection.id).at(method)->cancel();
|
||||
}
|
||||
TimerPtr timerPtr(
|
||||
new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pingIntervalMilliSeconds - pongTimeoutMilliSeconds)));
|
||||
timerPtr->async_wait([wsConnectionPtr, that = shared_from_this(), pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) {
|
||||
new net::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pingIntervalMilliseconds - pongTimeoutMilliseconds)));
|
||||
timerPtr->async_wait([wsConnectionPtr, that = shared_from_this(), pingMethod, pongTimeoutMilliseconds, method](ErrorCode const& ec) {
|
||||
WsConnection& wsConnection = *wsConnectionPtr;
|
||||
if (that->wsConnectionByIdMap.find(wsConnection.id) != that->wsConnectionByIdMap.end()) {
|
||||
if (ec) {
|
||||
@@ -1657,7 +1744,7 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
if (ec) {
|
||||
that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "ping");
|
||||
}
|
||||
if (pongTimeoutMilliSeconds <= 0) {
|
||||
if (pongTimeoutMilliseconds <= 0) {
|
||||
return;
|
||||
}
|
||||
if (that->pongTimeOutTimerByMethodByConnectionIdMap.find(wsConnection.id) != that->pongTimeOutTimerByMethodByConnectionIdMap.end() &&
|
||||
@@ -1665,8 +1752,8 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
that->pongTimeOutTimerByMethodByConnectionIdMap.at(wsConnection.id).end()) {
|
||||
that->pongTimeOutTimerByMethodByConnectionIdMap.at(wsConnection.id).at(method)->cancel();
|
||||
}
|
||||
TimerPtr timerPtr(new boost::asio::steady_timer(*that->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pongTimeoutMilliSeconds)));
|
||||
timerPtr->async_wait([wsConnectionPtr, that, pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) {
|
||||
TimerPtr timerPtr(new net::steady_timer(*that->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pongTimeoutMilliseconds)));
|
||||
timerPtr->async_wait([wsConnectionPtr, that, pingMethod, pongTimeoutMilliseconds, method](ErrorCode const& ec) {
|
||||
WsConnection& wsConnection = *wsConnectionPtr;
|
||||
if (that->wsConnectionByIdMap.find(wsConnection.id) != that->wsConnectionByIdMap.end()) {
|
||||
if (ec) {
|
||||
@@ -1679,7 +1766,7 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).find(method) !=
|
||||
that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).end() &&
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(now - that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).at(method))
|
||||
.count() >= pongTimeoutMilliSeconds) {
|
||||
.count() >= pongTimeoutMilliseconds) {
|
||||
auto thisWsConnectionPtr = wsConnectionPtr;
|
||||
ErrorCode ec;
|
||||
that->close(thisWsConnectionPtr, beast::websocket::close_code::normal,
|
||||
@@ -1705,8 +1792,17 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
}
|
||||
CCAPI_LOGGER_FUNCTION_EXIT;
|
||||
}
|
||||
std::string convertParamTimeSecondsToTimeMilliseconds(const std::string& input) {
|
||||
auto dotPosition = input.find('.');
|
||||
if (dotPosition == std::string::npos) {
|
||||
return std::to_string(std::stoll(input) * 1000);
|
||||
} else {
|
||||
}
|
||||
return std::to_string(std::stoll(input.substr(0, dotPosition)) * 1000 + std::stoll(UtilString::rightPadTo(input.substr(dotPosition + 1, 3), 3, '0')));
|
||||
}
|
||||
virtual void onTextMessage(std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessage, const TimePoint& timeReceived) {}
|
||||
#endif
|
||||
bool hostHttpHeaderValueIgnorePort{};
|
||||
std::string apiKeyName;
|
||||
std::string apiSecretName;
|
||||
std::string exchangeName;
|
||||
@@ -1721,13 +1817,11 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
std::string portRest;
|
||||
std::string hostWs;
|
||||
std::string portWs;
|
||||
tcp::resolver::results_type tcpResolverResultsRest, tcpResolverResultsWs;
|
||||
Queue<std::shared_ptr<HttpConnection>> httpConnectionPool;
|
||||
TimePoint lastHttpConnectionPoolPushBackTp{std::chrono::seconds{0}};
|
||||
TimerPtr httpConnectionPoolPurgeTimer;
|
||||
// tcp::resolver::results_type tcpResolverResultsRest, tcpResolverResultsWs;
|
||||
std::map<std::string, std::map<std::string, std::deque<std::shared_ptr<HttpConnection>>>> httpConnectionPool;
|
||||
std::map<std::string, std::string> credentialDefault;
|
||||
std::map<std::string, TimerPtr> sendRequestDelayTimerByCorrelationIdMap;
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
|
||||
std::map<std::string, WsConnection> wsConnectionByIdMap;
|
||||
#else
|
||||
std::map<std::string, std::shared_ptr<WsConnection>> wsConnectionByIdMap; // TODO(cryptochassis): for consistency, to be renamed to wsConnectionPtrByIdMap
|
||||
@@ -1736,15 +1830,15 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
std::map<std::string, size_t> writeMessageBufferWrittenLengthByConnectionIdMap;
|
||||
std::map<std::string, std::vector<size_t>> writeMessageBufferBoundaryByConnectionIdMap;
|
||||
#endif
|
||||
std::map<std::string, bool> wsConnectionPendingPingingByIdMap;
|
||||
std::map<std::string, bool> wsConnectionPendingPingingByConnectionIdMap;
|
||||
std::map<std::string, bool> shouldProcessRemainingMessageOnClosingByConnectionIdMap;
|
||||
std::map<std::string, int> connectNumRetryOnFailByConnectionUrlMap;
|
||||
std::map<std::string, TimerPtr> connectRetryOnFailTimerByConnectionIdMap;
|
||||
std::map<std::string, std::map<PingPongMethod, TimePoint>> lastPongTpByMethodByConnectionIdMap;
|
||||
std::map<std::string, std::map<PingPongMethod, TimerPtr>> pingTimerByMethodByConnectionIdMap;
|
||||
std::map<std::string, std::map<PingPongMethod, TimerPtr>> pongTimeOutTimerByMethodByConnectionIdMap;
|
||||
std::map<PingPongMethod, long> pingIntervalMilliSecondsByMethodMap;
|
||||
std::map<PingPongMethod, long> pongTimeoutMilliSecondsByMethodMap;
|
||||
std::map<PingPongMethod, long> pingIntervalMillisecondsByMethodMap;
|
||||
std::map<PingPongMethod, long> pongTimeoutMillisecondsByMethodMap;
|
||||
std::atomic<bool> shouldContinue{true};
|
||||
std::map<std::string, std::map<std::string, std::string>> extraPropertyByConnectionIdMap;
|
||||
bool enableCheckPingPongWebsocketProtocolLevel{};
|
||||
@@ -1757,7 +1851,7 @@ class Service : public std::enable_shared_from_this<Service> {
|
||||
(defined(CCAPI_ENABLE_EXCHANGE_HUOBI) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP)) || \
|
||||
defined(CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT) && \
|
||||
(defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_BITMART))
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
|
||||
struct monostate {};
|
||||
websocketpp::extensions_workaround::permessage_deflate::enabled<monostate> inflater;
|
||||
#else
|
||||
|
||||
Reference in new issue
Block a user