-
Notifications
You must be signed in to change notification settings - Fork 233
Expand file tree
/
Copy pathccapi_service.h
More file actions
1680 lines (1541 loc) · 83.4 KB
/
ccapi_service.h
File metadata and controls
1680 lines (1541 loc) · 83.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_SERVICE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_SERVICE_H_
#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) && \
(defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_BITMART)))
#define CCAPI_REQUIRES_INFLATE_STREAM 1
#else
#define CCAPI_REQUIRES_INFLATE_STREAM 0
#endif
#ifndef CCAPI_HTTP_RESPONSE_PARSER_BODY_LIMIT
#define CCAPI_HTTP_RESPONSE_PARSER_BODY_LIMIT (8 * 1024 * 1024)
#endif
#ifndef CCAPI_JSON_PARSE_BUFFER_SIZE
#define CCAPI_JSON_PARSE_BUFFER_SIZE (8 * 1024 * 1024)
#endif
#include "ccapi_cpp/ccapi_logger.h"
#ifndef RAPIDJSON_HAS_CXX11_NOEXCEPT
#define RAPIDJSON_HAS_CXX11_NOEXCEPT 0
#endif
#ifndef RAPIDJSON_ASSERT
#define RAPIDJSON_ASSERT(x) \
if (!(x)) { \
throw std::runtime_error("rapidjson internal assertion failure"); \
}
#endif
#ifndef RAPIDJSON_PARSE_ERROR_NORETURN
#define RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode, offset) throw std::runtime_error(#parseErrorCode)
#endif
#ifndef CCAPI_WEBSOCKET_WRITE_BUFFER_SIZE
#define CCAPI_WEBSOCKET_WRITE_BUFFER_SIZE (1 << 20)
#endif
#include <regex>
#include "boost/asio/strand.hpp"
#include "boost/beast/core.hpp"
#include "boost/beast/http.hpp"
#include "boost/beast/ssl.hpp"
#include "boost/beast/version.hpp"
#include "ccapi_cpp/ccapi_event.h"
#include "ccapi_cpp/ccapi_macro.h"
#include "ccapi_cpp/ccapi_market_data_message.h"
#include "ccapi_cpp/ccapi_util_private.h"
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
// clang-format off
#include "boost/beast/websocket.hpp"
// clang-format on
#include "ccapi_cpp/ccapi_fix_connection.h"
#include "ccapi_cpp/ccapi_http_connection.h"
#include "ccapi_cpp/ccapi_http_retry.h"
#if CCAPI_REQUIRES_INFLATE_STREAM
#include "ccapi_cpp/ccapi_inflate_stream.h"
#endif
#include "ccapi_cpp/ccapi_queue.h"
#include "ccapi_cpp/ccapi_request.h"
#include "ccapi_cpp/ccapi_session_configs.h"
#include "ccapi_cpp/ccapi_session_options.h"
#include "ccapi_cpp/ccapi_subscription.h"
#include "ccapi_cpp/ccapi_url.h"
#include "ccapi_cpp/ccapi_ws_connection.h"
#include "ccapi_cpp/service/ccapi_service_context.h"
namespace beast = boost::beast;
namespace http = beast::http;
namespace net = boost::asio;
namespace ssl = net::ssl;
using tcp = net::ip::tcp;
namespace rj = rapidjson;
namespace ccapi {
/**
* Defines a service which provides access to exchange API and normalizes them. This is a base class that implements generic functionalities for dealing with
* exchange REST and Websocket APIs. The Session object is responsible for routing requests and subscriptions to the desired concrete service.
*/
class Service : public std::enable_shared_from_this<Service> {
public:
typedef ServiceContext* ServiceContextPtr;
typedef boost::system::error_code ErrorCode; // a.k.a. beast::error_code
enum class PingPongMethod {
WEBSOCKET_PROTOCOL_LEVEL,
WEBSOCKET_APPLICATION_LEVEL,
FIX_PROTOCOL_LEVEL,
};
static std::string pingPongMethodToString(PingPongMethod pingPongMethod) {
std::string output;
switch (pingPongMethod) {
case PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL:
output = "WEBSOCKET_PROTOCOL_LEVEL";
break;
case PingPongMethod::WEBSOCKET_APPLICATION_LEVEL:
output = "WEBSOCKET_APPLICATION_LEVEL";
break;
case PingPongMethod::FIX_PROTOCOL_LEVEL:
output = "FIX_PROTOCOL_LEVEL";
break;
default:
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
return output;
}
Service(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: eventHandler(eventHandler),
sessionOptions(sessionOptions),
sessionConfigs(sessionConfigs),
serviceContextPtr(serviceContextPtr),
resolver(*serviceContextPtr->ioContextPtr),
resolverWs(*serviceContextPtr->ioContextPtr),
jsonDocumentAllocator(jsonParseBuffer.data(), jsonParseBuffer.size()) {
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;
}
virtual ~Service() {
for (const auto& x : this->pingTimerByMethodByConnectionIdMap) {
for (const auto& y : x.second) {
y.second->cancel();
}
}
for (const auto& x : this->pongTimeOutTimerByMethodByConnectionIdMap) {
for (const auto& y : x.second) {
y.second->cancel();
}
}
for (const auto& x : this->connectRetryOnFailTimerByConnectionIdMap) {
x.second->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->wsConnectionPtrByIdMap) {
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 stop() {
for (const auto& x : this->sendRequestDelayTimerByCorrelationIdMap) {
x.second->cancel();
}
sendRequestDelayTimerByCorrelationIdMap.clear();
this->shouldContinue = false;
for (const auto& x : this->wsConnectionPtrByIdMap) {
ErrorCode ec;
auto wsConnectionPtr = x.second;
this->close(wsConnectionPtr, beast::websocket::close_code::normal, beast::websocket::close_reason("stop"), ec);
if (ec) {
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "shutdown");
}
this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnectionPtr->id] = false;
}
}
virtual void convertRequestForRestCustom(http::request<http::string_body>& req, const Request& request, const TimePoint& now, const std::string& symbolId,
const std::map<std::string, std::string>& credential) {
auto errorMessage = "REST unimplemented operation " + Request::operationToString(request.getOperation()) + " for exchange " + request.getExchange();
throw std::runtime_error(errorMessage);
}
virtual void subscribe(std::vector<Subscription>& subscriptionList) {}
virtual void convertRequestForRest(http::request<http::string_body>& req, const Request& request, const TimePoint& now, const std::string& symbolId,
const std::map<std::string, std::string>& credential) {}
virtual void processSuccessfulTextMessageRest(int statusCode, const Request& request, boost::beast::string_view textMessageView,
const TimePoint& timeReceived, Queue<Event>* eventQueuePtr) {}
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);
} else {
then = now;
}
http::request<http::string_body> req;
try {
req = this->convertRequest(request, then);
} catch (const std::runtime_error& e) {
CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what());
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, e, {request.getCorrelationId()}, eventQueuePtr);
std::promise<void>* promisePtrRaw = nullptr;
if (useFuture) {
promisePtrRaw = new std::promise<void>();
}
std::shared_ptr<std::promise<void>> promisePtr(promisePtrRaw);
std::shared_ptr<std::future<void>> futurePtr(nullptr);
if (useFuture) {
futurePtr = std::make_shared<std::future<void>>(std::move(promisePtr->get_future()));
promisePtr->set_value();
}
return futurePtr;
}
std::promise<void>* promisePtrRaw = nullptr;
if (useFuture) {
promisePtrRaw = new std::promise<void>();
}
std::shared_ptr<std::promise<void>> promisePtr(promisePtrRaw);
HttpRetry retry(0, 0, "", promisePtr);
if (delayMilliseconds > 0) {
auto timerPtr = std::make_shared<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) {
if (ec != boost::asio::error::operation_aborted) {
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 now = UtilTime::now();
request.setTimeSent(now);
that->tryRequest(request, req, retry, eventQueuePtr);
}
that->sendRequestDelayTimerByCorrelationIdMap.erase(request.getCorrelationId());
});
this->sendRequestDelayTimerByCorrelationIdMap[request.getCorrelationId()] = timerPtr;
} else {
request.setTimeSent(now);
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) {
futurePtr = std::make_shared<std::future<void>>(std::move(promisePtr->get_future()));
}
CCAPI_LOGGER_FUNCTION_EXIT;
return futurePtr;
}
virtual void sendRequestByWebsocket(const std::string& websocketOrderEntrySubscriptionCorrelationId, Request& request, const TimePoint& now) {}
virtual void sendRequestByFix(const std::string& fixOrderEntrySubscriptionCorrelationId, Request& request, const TimePoint& now) {}
virtual void subscribe(Subscription& subscription) {}
void onError(const Event::Type eventType, const Message::Type messageType, const std::string& errorMessage,
const std::vector<std::string> correlationIdList = {}, Queue<Event>* eventQueuePtr = nullptr) {
CCAPI_LOGGER_ERROR("errorMessage = " + errorMessage);
CCAPI_LOGGER_ERROR("correlationIdList = " + toString(correlationIdList));
Event event;
event.setType(eventType);
Message message;
auto now = UtilTime::now();
message.setTimeReceived(now);
message.setType(messageType);
message.setCorrelationIdList(correlationIdList);
Element element;
element.insert(CCAPI_ERROR_MESSAGE, errorMessage);
message.setElementList({element});
event.setMessageList({message});
this->eventHandler(event, eventQueuePtr);
}
void onError(const Event::Type eventType, const Message::Type messageType, const ErrorCode& ec, const std::string& what,
const std::vector<std::string> correlationIdList = {}, Queue<Event>* eventQueuePtr = nullptr) {
this->onError(eventType, messageType, what + ": " + ec.message() + ", category: " + ec.category().name(), correlationIdList, eventQueuePtr);
}
void onError(const Event::Type eventType, const Message::Type messageType, const std::exception& e, const std::vector<std::string> correlationIdList = {},
Queue<Event>* eventQueuePtr = nullptr) {
this->onError(eventType, messageType, e.what(), correlationIdList, eventQueuePtr);
}
void onResponseError(const Request& request, int statusCode, boost::beast::string_view errorMessageView, Queue<Event>* eventQueuePtr) {
std::string statusCodeStr = std::to_string(statusCode);
CCAPI_LOGGER_ERROR("request = " + toString(request) + ", statusCode = " + statusCodeStr + ", errorMessage = " + std::string(errorMessageView));
Event event;
event.setType(Event::Type::RESPONSE);
Message message;
auto now = UtilTime::now();
message.setTimeReceived(now);
message.setType(Message::Type::RESPONSE_ERROR);
message.setCorrelationIdList({request.getCorrelationId()});
Element element;
element.insert(CCAPI_HTTP_STATUS_CODE, statusCodeStr);
element.insert(CCAPI_ERROR_MESSAGE, UtilString::trim(std::string(errorMessageView)));
message.setElementList({element});
event.setMessageList({message});
this->eventHandler(event, eventQueuePtr);
}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
typedef ServiceContext::SslContextPtr SslContextPtr;
typedef std::shared_ptr<net::steady_timer> TimerPtr;
void setHostRestFromUrlRest(std::string baseUrlRest) {
auto hostPort = this->extractHostFromUrl(baseUrlRest);
this->hostRest = hostPort.first;
this->portRest = hostPort.second;
}
// void setHostWsFromUrlWs(std::string baseUrlWs) {
// auto hostPort = this->extractHostFromUrl(baseUrlWs);
// this->hostWs = hostPort.first;
// this->portWs = hostPort.second;
// }
// void setHostWsFromUrlWsOrderEntry(std::string baseUrlWsOrderEntry) {
// auto hostPort = this->extractHostFromUrl(baseUrlWs);
// this->hostWsOrderEntry = hostPort.first;
// this->portWsOrderEntry = hostPort.second;
// }
std::pair<std::string, std::string> extractHostFromUrl(std::string baseUrl) {
std::string host;
std::string port;
if (!baseUrl.empty()) {
auto splitted1 = UtilString::split(baseUrl, "://");
auto splitted2 = UtilString::split(UtilString::split(splitted1.at(1), "/").at(0), ":");
host = splitted2.at(0);
if (splitted2.size() == 2) {
port = splitted2.at(1);
} else {
if (splitted1.at(0) == "https" || splitted1.at(0) == "wss") {
port = CCAPI_HTTPS_PORT_DEFAULT;
} else {
port = CCAPI_HTTP_PORT_DEFAULT;
}
}
}
return std::make_pair(host, port);
}
template <typename Derived>
std::shared_ptr<Derived> shared_from_base() {
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) {
#if defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE)
std::ostringstream oss;
oss << req;
CCAPI_LOGGER_DEBUG("req = \n" + oss.str());
#endif
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");
errorHandler(ec);
return;
}
auto httpConnectionPtr = std::make_shared<HttpConnection>(this->hostRest, this->portRest, streamPtr);
CCAPI_LOGGER_DEBUG("httpConnection = " + toString(*httpConnectionPtr));
auto newResolverPtr = std::make_shared<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) {
#if defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE)
std::ostringstream oss;
oss << req;
CCAPI_LOGGER_DEBUG("req = \n" + oss.str());
#endif
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, host);
} catch (const beast::error_code& ec) {
CCAPI_LOGGER_TRACE("fail");
errorHandler(ec);
return;
}
auto httpConnectionPtr = std::make_shared<HttpConnection>(host, port, streamPtr);
CCAPI_LOGGER_DEBUG("httpConnection = " + toString(*httpConnectionPtr));
auto newResolverPtr = std::make_shared<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));
}
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) {
if (ec) {
CCAPI_LOGGER_TRACE("fail");
errorHandler(ec);
return;
}
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) {
beast::ssl_stream<beast::tcp_stream>& stream = *httpConnectionPtr->streamPtr;
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(
tcpNewResolverResults, beast::bind_front_handler(&Service::onConnect, shared_from_this(), httpConnectionPtr, req, errorHandler, responseHandler));
CCAPI_LOGGER_TRACE("after async_connect");
}
void onConnect(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,
beast::error_code ec, tcp::resolver::results_type::endpoint_type) {
CCAPI_LOGGER_TRACE("async_connect callback start");
if (ec) {
CCAPI_LOGGER_TRACE("fail");
errorHandler(ec);
return;
}
CCAPI_LOGGER_TRACE("connected");
beast::ssl_stream<beast::tcp_stream>& stream = *httpConnectionPtr->streamPtr;
// #ifdef CCAPI_DISABLE_NAGLE_ALGORITHM
beast::get_lowest_layer(stream).socket().set_option(tcp::no_delay(true));
// #endif
CCAPI_LOGGER_TRACE("before ssl async_handshake");
stream.async_handshake(ssl::stream_base::client,
beast::bind_front_handler(&Service::onSslHandshake, shared_from_this(), httpConnectionPtr, req, errorHandler, responseHandler));
CCAPI_LOGGER_TRACE("after ssl async_handshake");
}
void onSslHandshake(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,
beast::error_code ec) {
CCAPI_LOGGER_TRACE("ssl async_handshake callback start");
if (ec) {
CCAPI_LOGGER_TRACE("fail");
errorHandler(ec);
return;
}
CCAPI_LOGGER_TRACE("ssl handshaked");
beast::ssl_stream<beast::tcp_stream>& stream = *httpConnectionPtr->streamPtr;
auto reqPtr = std::make_shared<http::request<http::string_body>>(std::move(req));
CCAPI_LOGGER_TRACE("before async_write");
http::async_write(stream, *reqPtr,
beast::bind_front_handler(&Service::onWrite, shared_from_this(), httpConnectionPtr, reqPtr, errorHandler, responseHandler));
CCAPI_LOGGER_TRACE("after async_write");
}
void onWrite(std::shared_ptr<HttpConnection> httpConnectionPtr, std::shared_ptr<http::request<http::string_body>> reqPtr,
std::function<void(const beast::error_code&)> errorHandler, std::function<void(const http::response<http::string_body>&)> responseHandler,
beast::error_code ec, std::size_t bytes_transferred) {
CCAPI_LOGGER_TRACE("async_write callback start");
boost::ignore_unused(bytes_transferred);
if (ec) {
CCAPI_LOGGER_TRACE("fail");
errorHandler(ec);
return;
}
CCAPI_LOGGER_TRACE("written");
httpConnectionPtr->clearBuffer();
beast::ssl_stream<beast::tcp_stream>& stream = *httpConnectionPtr->streamPtr;
CCAPI_LOGGER_TRACE("before async_read");
std::shared_ptr<http::response_parser<http::string_body>> resParserPtr = std::make_shared<http::response_parser<http::string_body>>();
resParserPtr->body_limit(CCAPI_HTTP_RESPONSE_PARSER_BODY_LIMIT);
http::async_read(stream, httpConnectionPtr->buffer, *resParserPtr,
beast::bind_front_handler(&Service::onRead, shared_from_this(), httpConnectionPtr, reqPtr, resParserPtr, errorHandler, responseHandler));
CCAPI_LOGGER_TRACE("after async_read");
}
void onRead(std::shared_ptr<HttpConnection> httpConnectionPtr, std::shared_ptr<http::request<http::string_body>> reqPtr,
std::shared_ptr<http::response_parser<http::string_body>> resParserPtr, std::function<void(const beast::error_code&)> errorHandler,
std::function<void(const http::response<http::string_body>&)> responseHandler, beast::error_code ec, std::size_t bytes_transferred) {
CCAPI_LOGGER_TRACE("async_read callback start");
auto resPtr = &resParserPtr->get();
boost::ignore_unused(bytes_transferred);
if (ec) {
CCAPI_LOGGER_TRACE("fail");
errorHandler(ec);
return;
}
#if defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE)
{
std::ostringstream oss;
oss << *reqPtr;
CCAPI_LOGGER_DEBUG("req = \n" + oss.str());
}
{
std::ostringstream oss;
oss << *resPtr;
CCAPI_LOGGER_DEBUG("res = \n" + oss.str());
}
#endif
responseHandler(*resPtr);
}
template <class T>
std::shared_ptr<T> createStream(net::io_context* iocPtr, net::ssl::context* ctxPtr, const std::string& host) {
auto streamPtr = std::make_shared<T>(*iocPtr, *ctxPtr);
// Set SNI hostname (important for TLS handshakes)
if (!SSL_set_tlsext_host_name(streamPtr->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;
}
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));
}
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::make_address(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;
}
}
}
auto newResolverPtr = std::make_shared<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 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 != boost::asio::error::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
beast::get_lowest_layer(stream).socket().set_option(tcp::no_delay(true));
// #endif
CCAPI_LOGGER_TRACE("before ssl async_handshake");
stream.async_handshake(ssl::stream_base::client,
beast::bind_front_handler(&Service::onSslHandshake_2, shared_from_this(), httpConnectionPtr, request, req, retry, eventQueuePtr));
CCAPI_LOGGER_TRACE("after ssl async_handshake");
}
void onSslHandshake_2(std::shared_ptr<HttpConnection> httpConnectionPtr, Request request, http::request<http::string_body> req, HttpRetry retry,
Queue<Event>* eventQueuePtr, beast::error_code ec) {
CCAPI_LOGGER_TRACE("ssl async_handshake callback start");
if (ec) {
CCAPI_LOGGER_TRACE("fail");
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "ssl handshake", {request.getCorrelationId()}, eventQueuePtr);
return;
}
CCAPI_LOGGER_TRACE("ssl handshaked");
this->startWrite_2(httpConnectionPtr, request, req, retry, eventQueuePtr);
}
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));
}
auto reqPtr = std::make_shared<http::request<http::string_body>>(std::move(req));
CCAPI_LOGGER_TRACE("before async_write");
http::async_write(stream, *reqPtr,
beast::bind_front_handler(&Service::onWrite_2, shared_from_this(), httpConnectionPtr, request, reqPtr, retry, eventQueuePtr));
CCAPI_LOGGER_TRACE("after async_write");
}
void onWrite_2(std::shared_ptr<HttpConnection> httpConnectionPtr, Request request, std::shared_ptr<http::request<http::string_body>> reqPtr, HttpRetry retry,
Queue<Event>* eventQueuePtr, beast::error_code ec, std::size_t bytes_transferred) {
CCAPI_LOGGER_TRACE("async_write callback start");
boost::ignore_unused(bytes_transferred);
if (ec) {
CCAPI_LOGGER_TRACE("fail");
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "write", {request.getCorrelationId()}, eventQueuePtr);
this->httpConnectionPool[request.getLocalIpAddress()][request.getBaseUrl()].clear();
auto now = UtilTime::now();
auto req = this->convertRequest(request, now);
retry.numRetry += 1;
this->tryRequest(request, req, retry, eventQueuePtr);
return;
}
CCAPI_LOGGER_TRACE("written");
httpConnectionPtr->clearBuffer();
beast::ssl_stream<beast::tcp_stream>& stream = *httpConnectionPtr->streamPtr;
CCAPI_LOGGER_TRACE("before async_read");
std::shared_ptr<http::response_parser<http::string_body>> resParserPtr = std::make_shared<http::response_parser<http::string_body>>();
resParserPtr->body_limit(CCAPI_HTTP_RESPONSE_PARSER_BODY_LIMIT);
http::async_read(stream, httpConnectionPtr->buffer, *resParserPtr,
beast::bind_front_handler(&Service::onRead_2, shared_from_this(), httpConnectionPtr, request, reqPtr, resParserPtr, retry, eventQueuePtr));
CCAPI_LOGGER_TRACE("after async_read");
}
void onRead_2(std::shared_ptr<HttpConnection> httpConnectionPtr, Request request, std::shared_ptr<http::request<http::string_body>> reqPtr,
std::shared_ptr<http::response_parser<http::string_body>> resParserPtr, HttpRetry retry, 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 resPtr = &resParserPtr->get();
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[request.getLocalIpAddress()][request.getBaseUrl()].clear();
auto now = UtilTime::now();
auto req = this->convertRequest(request, now);
retry.numRetry += 1;
this->tryRequest(request, req, retry, eventQueuePtr);
return;
}
#if defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE)
{
std::ostringstream oss;
oss << *reqPtr;
CCAPI_LOGGER_DEBUG("req = \n" + oss.str());
}
{
std::ostringstream oss;
oss << *resPtr;
CCAPI_LOGGER_DEBUG("res = \n" + oss.str());
}
#endif
int statusCode = resPtr->result_int();
boost::beast::string_view bodyView(resPtr->body());
try {
if (statusCode / 100 == 2) {
this->processSuccessfulTextMessageRest(statusCode, request, bodyView, now, eventQueuePtr);
} else if (statusCode / 100 == 3) {
if (resPtr->base().find("Location") != resPtr->base().end()) {
Url url(resPtr->base()
.at("Location")
#if BOOST_VERSION < 108100
// Boost Beast 1.81 uses boost::core::string_view which doesn't contain to_string() method
.to_string()
#endif
);
std::string host(url.host);
if (!url.port.empty()) {
host += ":";
host += url.port;
}
auto now = UtilTime::now();
auto req = this->convertRequest(request, now);
req.set(http::field::host, host);
req.target(url.target);
retry.numRedirect += 1;
CCAPI_LOGGER_WARN("redirect from request " + request.toString() + " to url " + url.toString());
this->tryRequest(request, req, retry, eventQueuePtr);
}
this->onResponseError(request, statusCode, bodyView, eventQueuePtr);
return;
} else if (statusCode / 100 == 4) {
this->onResponseError(request, statusCode, bodyView, eventQueuePtr);
} else if (statusCode / 100 == 5) {
this->onResponseError(request, statusCode, bodyView, eventQueuePtr);
retry.numRetry += 1;
this->tryRequest(request, *reqPtr, retry, eventQueuePtr);
return;
} else {
this->onResponseError(request, statusCode, "unhandled response", eventQueuePtr);
}
} catch (const std::exception& e) {
CCAPI_LOGGER_ERROR(e.what());
{
std::ostringstream oss;
oss << *reqPtr;
CCAPI_LOGGER_ERROR("req = \n" + oss.str());
}
{
std::ostringstream oss;
oss << *resPtr;
CCAPI_LOGGER_ERROR("res = " + oss.str());
}
this->onError(Event::Type::REQUEST_STATUS, Message::Type::GENERIC_ERROR, e, {request.getCorrelationId()}, eventQueuePtr);
}
if (!this->sessionOptions.enableOneHttpConnectionPerRequest) {
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));
}
CCAPI_LOGGER_DEBUG("retry = " + toString(retry));
if (retry.promisePtr) {
retry.promisePtr->set_value();
}
}
virtual bool doesHttpBodyContainError(boost::beast::string_view bodyView) { return false; }
void tryRequest(const Request& request, http::request<http::string_body>& req, const HttpRetry& retry, Queue<Event>* eventQueuePtr) {
CCAPI_LOGGER_FUNCTION_ENTER;
#if defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE)
std::ostringstream oss;
oss << req;
CCAPI_LOGGER_DEBUG("req = \n" + oss.str());
#endif
CCAPI_LOGGER_TRACE("retry = " + toString(retry));
if (retry.numRetry <= this->sessionOptions.httpMaxNumRetry && retry.numRedirect <= this->sessionOptions.httpMaxNumRedirect) {
try {
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,
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;
}
std::string host, port;
if (requestBaseUrl.empty()) {
host = this->hostRest;
port = this->portRest;
} else {
host = request.getHost();
port = request.getPort();
}
auto httpConnectionPtr = std::make_shared<HttpConnection>(host, port, streamPtr);
CCAPI_LOGGER_WARN("about to perform request with new httpConnectionPtr " + toString(*httpConnectionPtr) + " for request = " + toString(request) +
", 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());
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, e, {request.getCorrelationId()}, eventQueuePtr);
}
} else {
std::string errorMessage = retry.numRetry > this->sessionOptions.httpMaxNumRetry ? "max retry exceeded" : "max redirect exceeded";
CCAPI_LOGGER_ERROR(errorMessage);
CCAPI_LOGGER_DEBUG("retry = " + toString(retry));
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, std::runtime_error(errorMessage), {request.getCorrelationId()}, eventQueuePtr);
if (retry.promisePtr) {
retry.promisePtr->set_value();
}
}
CCAPI_LOGGER_FUNCTION_EXIT;
}
http::request<http::string_body> convertRequest(const Request& request, const TimePoint& now) {
CCAPI_LOGGER_FUNCTION_ENTER;
auto credential = request.getCredential();
if (credential.empty()) {
credential = this->credentialDefault;
}
auto instrument = request.getInstrument();
auto symbolId = instrument;
CCAPI_LOGGER_TRACE("symbolId = " + symbolId);
http::request<http::string_body> req;
req.version(11);
if (this->sessionOptions.enableOneHttpConnectionPerRequest) {
req.keep_alive(false);
} else {
req.keep_alive(true);
}
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;
return req;
}
void substituteParam(std::string& target, const std::map<std::string, std::string>& param, const std::map<std::string, std::string> standardizationMap = {}) {
for (const auto& kv : param) {
auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
auto value = kv.second;
auto it = target.find(key);
if (it != std::string::npos) {
target = target.replace(it, key.length(), value);
}
}
}
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_view, 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 += "=";
std::string value = conversionMap.find(kv.first) != conversionMap.end() ? conversionMap.at(kv.first)(kv.second) : kv.second;
queryString += Url::urlEncode(value);
queryString += "&";
++i;
}
}
void appendSymbolId(rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::string& symbolId, const std::string& symbolIdCalled) {
rjValue.AddMember(rj::Value(symbolIdCalled.c_str(), allocator).Move(), rj::Value(symbolId.c_str(), allocator).Move(), allocator);
}
void appendSymbolId(std::string& queryString, const std::string& symbolId, const std::string& symbolIdCalled) {
if (!symbolId.empty()) {
queryString += symbolIdCalled;
queryString += "=";
queryString += Url::urlEncode(symbolId);
queryString += "&";
}
}
void setupCredential(std::vector<std::string> nameList) {
for (const auto& x : nameList) {
if (this->sessionConfigs.getCredential().find(x) != this->sessionConfigs.getCredential().end()) {
this->credentialDefault.insert(std::make_pair(x, this->sessionConfigs.getCredential().at(x)));
} else if (!UtilSystem::getEnvAsString(x).empty()) {
this->credentialDefault.insert(std::make_pair(x, UtilSystem::getEnvAsString(x)));
}
}
}
http::verb convertHttpMethodStringToMethod(const std::string& methodString) {
std::string methodStringUpper = UtilString::toUpper(methodString);
return http::string_to_verb(methodStringUpper);
}
void close(std::shared_ptr<WsConnection> wsConnectionPtr, beast::websocket::close_code const code, beast::websocket::close_reason reason, ErrorCode& ec) {
if (wsConnectionPtr->status == WsConnection::Status::CLOSING) {
CCAPI_LOGGER_WARN("websocket connection is already in the state of closing");
return;
}
wsConnectionPtr->status = WsConnection::Status::CLOSING;
wsConnectionPtr->remoteCloseCode = code;
wsConnectionPtr->remoteCloseReason = reason;
std::visit([&](auto& streamPtr) { streamPtr->async_close(code, beast::bind_front_handler(&Service::onClose, shared_from_this(), wsConnectionPtr)); },
wsConnectionPtr->streamPtr);
}
virtual void prepareConnect(std::shared_ptr<WsConnection> wsConnectionPtr) { this->connect(wsConnectionPtr); }
virtual void connect(std::shared_ptr<WsConnection> wsConnectionPtr) {
CCAPI_LOGGER_FUNCTION_ENTER;
wsConnectionPtr->status = WsConnection::Status::CONNECTING;
CCAPI_LOGGER_DEBUG("wsConnectionPtr = " + wsConnectionPtr->toString());
this->startResolveWs(wsConnectionPtr);
CCAPI_LOGGER_FUNCTION_EXIT;
}
void startResolveWs(std::shared_ptr<WsConnection> wsConnectionPtr) {
auto newResolverPtr = std::make_shared<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);
CCAPI_LOGGER_TRACE("wsConnectionPtr->proxyUrl = " + wsConnectionPtr->proxyUrl);
std::string host;
std::string port;
if (wsConnectionPtr->proxyUrl.empty()) {
host = wsConnectionPtr->host;
port = wsConnectionPtr->port;
} else {
const auto& splitted = UtilString::split(wsConnectionPtr->proxyUrl, ':');
host = splitted.at(0);
port = splitted.size() > 1 ? splitted.at(1) : CCAPI_HTTP_PORT_DEFAULT;
}