algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
http_client.hpp
1#pragma once
2
8#define ATL_TRANSPORT_LAYER_PRESENT 1
9
10#include "./rate_limit.hpp"
11
12#include <algotradelib/core>
13
14#include <boost/asio/any_completion_handler.hpp>
15#include <boost/asio/associated_executor.hpp>
16#include <boost/asio/async_result.hpp>
17#include <boost/asio/dispatch.hpp>
18#include <boost/asio/ip/tcp.hpp>
19#include <boost/asio/post.hpp>
20#include <boost/asio/ssl.hpp>
21#include <boost/asio/strand.hpp>
22#include <boost/beast/core.hpp>
23#include <boost/beast/http.hpp>
24#include <boost/beast/ssl.hpp>
25
26#include <chrono>
27#include <cstdint>
28#include <deque>
29#include <map>
30#include <memory>
31#include <optional>
32#include <string>
33#include <utility>
34#include <vector>
35
36namespace algotradelib {
37
38namespace beast = boost::beast;
39namespace http = boost::beast::http;
40namespace net = boost::asio;
41namespace ssl = net::ssl;
43using tcp = net::ip::tcp;
44
45namespace network {
46
48using HttpResponse = http::response<http::string_body>;
49
58 http::verb method_{http::verb::get};
60 std::string target_{"/"};
62 std::string body_;
64 std::vector<std::pair<std::string, std::string>> headers_;
66 int version_{11};
74};
75
82 std::chrono::seconds timeout_{30};
84 std::size_t body_limit_{8 * 1024 * 1024};
89 std::size_t queue_limit_{1024};
90
96 std::optional<RateLimitBudget> rate_limit_;
97
108 std::chrono::milliseconds unreplayed_idle_limit_{1000};
109
121 std::optional<bool> fresh_connection_for_orders_;
122};
123
131inline BrokerError transport_error(std::string stage, beast::error_code ec) {
132 BrokerError error;
133 error.category_ = ec == net::error::operation_aborted ? ErrorCategory::CANCELLED : ErrorCategory::TRANSPORT;
134 error.broker_code_ = std::move(stage);
135 error.message_ = ec.message();
136 return error;
137}
138
145inline std::string make_host_header(const std::string& host, const std::string& port) {
146 return port == "443" ? host : host + ":" + port;
147}
148
158inline void shutdown_ssl_stream(beast::ssl_stream<beast::tcp_stream>& stream, std::chrono::seconds timeout) noexcept {
159 beast::error_code ignored;
160 beast::get_lowest_layer(stream).expires_after(timeout);
161 stream.shutdown(ignored);
162 beast::get_lowest_layer(stream).socket().shutdown(tcp::socket::shutdown_both, ignored);
163 beast::get_lowest_layer(stream).socket().close(ignored);
164}
165
171inline void close_ssl_stream(beast::ssl_stream<beast::tcp_stream>& stream) noexcept {
172 beast::error_code ignored;
173 beast::get_lowest_layer(stream).cancel();
174 beast::get_lowest_layer(stream).socket().shutdown(tcp::socket::shutdown_both, ignored);
175 beast::get_lowest_layer(stream).socket().close(ignored);
176}
177
185public:
197 net::io_context& ioc, ssl::context& context, std::string host, std::string port, HttpClientOptions options = {}
198 )
199 : resolver_(ioc), context_(context), host_(std::move(host)), port_(std::move(port)), options_(options) {}
200
208 HttpResponse get(const std::string& target, const std::map<std::string, std::string>& headers = {}) {
209 return request(http::verb::get, target, "", headers);
210 }
211
221 const std::string& target, const std::string& body, const std::map<std::string, std::string>& headers = {}
222 ) {
223 return request(http::verb::post, target, body, headers);
224 }
225
236 http::verb method, const std::string& target, const std::string& body = {},
237 const std::map<std::string, std::string>& headers = {}
238 ) {
239 for (int attempt = 0;; ++attempt) {
240 beast::error_code error;
241 // Never replayed, so never written into a connection the server may have closed while it was
242 // idle; see `HttpClientOptions::unreplayed_idle_limit_`.
243 if (
244 method != http::verb::get && idle_since_ &&
245 std::chrono::steady_clock::now() - *idle_since_ > options_.unreplayed_idle_limit_
246 ) {
247 // Dropped without waiting for the peer's close notification: a synchronous TLS shutdown is not
248 // bounded by the stream's deadline, and a live server may never answer one.
249 close_ssl_stream(*stream_);
250 stream_.reset();
251 buffer_.consume(buffer_.size());
252 idle_since_.reset();
253 }
254 ensure_connected(error);
255 if (!error) {
256 http::request<http::string_body> request_value{method, target, 11};
257 request_value.set(http::field::host, host_header());
258 request_value.set(http::field::user_agent, "algotradelib");
259 request_value.keep_alive(true);
260 for (const auto& header : headers) {
261 request_value.set(header.first, header.second);
262 }
263 request_value.body() = body;
264 if (!body.empty()) {
265 request_value.prepare_payload();
266 }
267
268 beast::get_lowest_layer(*stream_).expires_after(options_.timeout_);
269 http::write(*stream_, request_value, error);
270 }
271
272 http::response_parser<http::string_body> parser;
273 if (!error) {
274 parser.body_limit(options_.body_limit_);
275 http::read(*stream_, buffer_, parser, error);
276 }
277
278 if (!error) {
279 auto response = parser.release();
280 if (!response.keep_alive() || response.need_eof()) {
281 disconnect();
282 } else {
283 idle_since_ = std::chrono::steady_clock::now();
284 }
285 return response;
286 }
287
288 disconnect();
289 if (method != http::verb::get || attempt > 0) {
290 throw beast::system_error(error);
291 }
292 }
293 }
294
296 void close() {
297 disconnect();
298 }
299
300private:
301 tcp::resolver resolver_;
302 ssl::context& context_;
303 std::string host_;
304 std::string port_;
305 HttpClientOptions options_;
306 std::unique_ptr<beast::ssl_stream<beast::tcp_stream>> stream_;
307 beast::flat_buffer buffer_;
308 // When the connection last finished a response and was kept alive; empty while there is none.
309 std::optional<std::chrono::steady_clock::time_point> idle_since_;
310
311 void ensure_connected(beast::error_code& error) {
312 if (stream_ && beast::get_lowest_layer(*stream_).socket().is_open()) {
313 return;
314 }
315 stream_ = std::make_unique<beast::ssl_stream<beast::tcp_stream>>(resolver_.get_executor(), context_);
316 if (!SSL_set_tlsext_host_name(stream_->native_handle(), host_.c_str())) {
317 error = beast::error_code(static_cast<int>(::ERR_get_error()), net::error::get_ssl_category());
318 return;
319 }
320 stream_->set_verify_callback(ssl::host_name_verification(host_));
321 const auto endpoints = resolver_.resolve(host_, port_, error);
322 if (error) {
323 return;
324 }
325 beast::get_lowest_layer(*stream_).expires_after(options_.timeout_);
326 beast::get_lowest_layer(*stream_).connect(endpoints, error);
327 if (error) {
328 return;
329 }
330 beast::get_lowest_layer(*stream_).expires_after(options_.timeout_);
331 stream_->handshake(ssl::stream_base::client, error);
332 }
333
334 std::string host_header() const {
335 return make_host_header(host_, port_);
336 }
337
338 void disconnect() noexcept {
339 if (!stream_) {
340 return;
341 }
342 shutdown_ssl_stream(*stream_, std::chrono::seconds(1));
343 stream_.reset();
344 buffer_.consume(buffer_.size());
345 idle_since_.reset();
346 }
347};
348
374class AsyncHttpClient : public std::enable_shared_from_this<AsyncHttpClient> {
375public:
377 using CompletionHandler = net::any_completion_handler<void(Result<HttpResponse>)>;
378
391 net::any_io_executor executor, ssl::context& context, std::string host, std::string port,
392 HttpClientOptions options = {}
393 )
394 : strand_(net::make_strand(std::move(executor))),
395 resolver_(strand_),
396 resolve_timer_(strand_),
397 admission_timer_(strand_),
398 context_(context),
399 host_(std::move(host)),
400 port_(std::move(port)),
401 options_(options),
402 fresh_orders_(options.fresh_connection_for_orders_.value_or(false)) {
403 if (options_.rate_limit_) {
404 limiter_.emplace(*options_.rate_limit_);
405 }
406 }
407
417 return limiter_ ? &*limiter_ : nullptr;
418 }
419
427 const RateLimitController* rate_limits() const noexcept {
428 return limiter_ ? &*limiter_ : nullptr;
429 }
430
440 std::uint64_t admission_waits() const noexcept {
441 return admission_timer_.arms();
442 }
443
457 template <typename CompletionToken>
458 auto async_request(HttpRequest request_value, CompletionToken&& token) {
459 return net::async_initiate<CompletionToken, void(Result<HttpResponse>)>(
460 [self = shared_from_this(), request_value = std::move(request_value)](auto&& handler) mutable {
461 Pending pending(std::move(request_value), CompletionHandler(std::forward<decltype(handler)>(handler)));
462 net::post(self->strand_, [self, pending = std::move(pending)]() mutable {
463 self->enqueue(std::move(pending));
464 });
465 },
466 token
467 );
468 }
469
474 void close() {
475 net::post(strand_, [self = shared_from_this()] {
476 self->stopped_ = true;
477 self->resolver_.cancel();
478 self->resolve_timer_.cancel();
479 self->admission_timer_.cancel();
480 self->disconnect();
481 BrokerError error;
483 error.broker_code_ = "close";
484 error.message_ = "HTTP client closed";
485 // Each entry answers for itself, which is why `sent_` lives on the request rather than being
486 // inferred from the connection: a caller has to be able to tell an order that provably does
487 // not exist -- no reconciliation owed, no request spent -- from one that may be on the wire.
488 // Reading the client's state here would answer for none of them, since `disconnect()` has
489 // just cleared it.
490 while (!self->queue_.empty()) {
491 auto pending = std::move(self->queue_.front());
492 self->queue_.pop_front();
493 BrokerError reported = error;
494 reported.reached_broker_ = pending.sent_;
495 self->complete(std::move(pending.handler_), Result<HttpResponse>(std::move(reported)));
496 }
497 });
498 }
499
500private:
501 enum class State {
502 DISCONNECTED,
503 RESOLVING,
504 CONNECTING,
505 HANDSHAKING,
506 READY,
507 WRITING,
508 READING,
509 };
510
511 struct Pending {
512 HttpRequest request_;
513 CompletionHandler handler_;
514 bool retried_{false};
515 // Whether this request already went to a fresh connection because the last one sat idle. Once is
516 // enough, and it bounds the rule: a fresh connection starts its own idle clock, which with a limit
517 // of zero or below would otherwise send it straight back for another.
518 bool refreshed_{false};
519 // Whether any attempt at this request has begun writing it to the socket.
520 //
521 // The honest record of what a caller may be told about the broker having seen it, and
522 // deliberately not `retried_`, which counts a replay rather than a send: a GET that fails to
523 // *connect* is retried without a byte having left, and reading the retry as evidence would
524 // report an unsent request as one the broker may hold. Sticky once set, because a second
525 // attempt cannot unsend the first.
526 bool sent_{false};
527 // When this request began waiting for rate-limit admission; empty while it is not waiting. Kept
528 // on the request, not the client: a request inserted ahead of a waiting one is admitted on its
529 // own terms, and must neither be charged the other's wait nor restart it.
530 std::optional<std::chrono::steady_clock::time_point> waiting_since_;
531
532 Pending(HttpRequest request_value, CompletionHandler completion)
533 : request_(std::move(request_value)), handler_(std::move(completion)) {}
534 };
535
536 net::strand<net::any_io_executor> strand_;
537 tcp::resolver resolver_;
538 net::steady_timer resolve_timer_;
539 // The admission timer, wrapped so that arming it is counted by construction.
540 //
541 // **A counter beside the timer is not enough, and that is not hypothetical.** The first version of
542 // this observable incremented a member at the one call site that armed the timer, on the paced
543 // branch. `pump()` returns before that site when there is no budget, so a regression arming this
544 // timer on the *unpaced* branch would have delayed every request on an unmetered API while the
545 // counter still read zero -- and the test asserting zero would have passed.
546 //
547 // Making the count a property of the timer removes the bypass rather than documenting it: there
548 // is no way to arm *this* timer without `expires_after`, so there is no way to wait on it without
549 // saying so. What that does not cover is a delay built on some other timer; see
550 // `admission_waits()`.
551 //
552 // **A narrow wrapper for two call sites, not a general Asio timer substitute.** It discards the
553 // completion-token return values its callers do not use, and it counts an expiry reset even when
554 // no wait follows -- which is exact for the one place that arms this timer and immediately waits,
555 // and would need revisiting for any other use. Changing an expiry cancels a pending wait, whose
556 // handler then receives `operation_aborted`; this client's handler already returns on any error.
557 class CountedTimer {
558 public:
559 explicit CountedTimer(net::strand<net::any_io_executor>& strand) : timer_(strand) {}
560
561 // Arms the timer for `delay`, and counts the arm.
562 template <typename Rep, typename Period>
563 void expires_after(const std::chrono::duration<Rep, Period>& delay) {
564 timer_.expires_after(delay);
565 // Counted after the call, so this records an arm that happened rather than one attempted.
566 ++arms_;
567 }
568
569 // Waits, forwarding to the underlying timer.
570 template <typename Handler>
571 void async_wait(Handler&& handler) {
572 timer_.async_wait(std::forward<Handler>(handler));
573 }
574
575 // Cancels any outstanding wait. Not counted: a cancellation is not an admission wait.
576 std::size_t cancel() {
577 return timer_.cancel();
578 }
579
580 // Returns how many times this timer has been armed.
581 std::uint64_t arms() const noexcept {
582 return arms_;
583 }
584
585 private:
586 net::steady_timer timer_;
587 std::uint64_t arms_{0};
588 };
589
590 CountedTimer admission_timer_;
591 ssl::context& context_;
592 std::unique_ptr<beast::ssl_stream<beast::tcp_stream>> stream_;
593 beast::flat_buffer buffer_;
594 std::string host_;
595 std::string port_;
596 HttpClientOptions options_;
597 State state_{State::DISCONNECTED};
598 bool stopped_{false};
599 bool resolve_timed_out_{false};
600 std::deque<Pending> queue_;
601 std::optional<RateLimitController> limiter_;
602 std::optional<http::request<http::string_body>> active_request_;
603 std::optional<http::response_parser<http::string_body>> parser_;
604 // When the connection last finished a response and was kept alive, or finished its handshake; empty while there is none.
605 std::optional<std::chrono::steady_clock::time_point> idle_since_;
606 // Whether any request has begun writing on the current connection.
607 // Kept on the connection, not on a request: a request that outranks an order can be written on the connection opened for it.
608 bool connection_used_{false};
609 // `HttpClientOptions::fresh_connection_for_orders_`, resolved once.
610 bool fresh_orders_{false};
611
612 void enqueue(Pending pending) {
613 if (stopped_) {
614 BrokerError error;
615 error.category_ = ErrorCategory::CANCELLED;
616 // Never queued, let alone sent: the instruction reached nobody.
617 error.reached_broker_ = false;
618 error.broker_code_ = "enqueue";
619 error.message_ = "HTTP client is closed";
620 complete(std::move(pending.handler_), Result<HttpResponse>(std::move(error)));
621 return;
622 }
623 if (queue_.size() >= options_.queue_limit_) {
624 if (limiter_) {
625 limiter_->record_shed(pending.request_.group_);
626 }
627 BrokerError error;
628 error.category_ = ErrorCategory::TRANSPORT;
629 // Refused at admission, so nothing was sent. `TRANSPORT` would otherwise read as a request
630 // that may be on the wire, and a runner would withhold the instrument to reconcile an order
631 // that was never built.
632 error.reached_broker_ = false;
633 error.broker_code_ = "queue_full";
634 error.message_ = "HTTP request queue limit exceeded";
635 complete(std::move(pending.handler_), Result<HttpResponse>(std::move(error)));
636 return;
637 }
638 queue_.insert(insertion_point(pending.request_.group_), std::move(pending));
639 pump();
640 }
641
642 // Returns where a request of `group` belongs in the pending queue.
643 //
644 // Higher priority is served first, and equal priority keeps arrival order, so
645 // a queue carrying one traffic class behaves exactly as a FIFO queue does.
646 //
647 // The front request is skipped while it is on the wire. Reordering around an
648 // in-flight request would detach it from the response being read for it, which
649 // is the one thing priority must never be allowed to do.
650 std::deque<Pending>::iterator insertion_point(RateLimitGroup group) {
651 auto position = queue_.begin();
652 if (front_in_flight() && position != queue_.end()) {
653 ++position;
654 }
655 const int priority = rate_limit_priority(group);
656 while (position != queue_.end() && rate_limit_priority(position->request_.group_) >= priority) {
657 ++position;
658 }
659 return position;
660 }
661
662 // Returns whether the front request has already been committed to the wire.
663 bool front_in_flight() const noexcept {
664 switch (state_) {
665 case State::WRITING:
666 case State::READING:
667 return true;
668 case State::DISCONNECTED:
669 case State::RESOLVING:
670 case State::CONNECTING:
671 case State::HANDSHAKING:
672 case State::READY:
673 return false;
674 }
675 return true;
676 }
677
678 void pump() {
679 if (stopped_ || queue_.empty()) {
680 return;
681 }
682 if (state_ == State::DISCONNECTED) {
683 start_resolve();
684 return;
685 }
686 if (state_ != State::READY) {
687 return;
688 }
689 // A request that is never replayed is not written into a connection the server may have closed
690 // while it sat idle; see `HttpClientOptions::unreplayed_idle_limit_`. Before admission, so the
691 // reconnect spends no rate-limit slot of its own.
692 // With `fresh_orders_` on, an order has its own rule, applied just before it is written (`refresh_for_order`).
693 if (
694 !(fresh_orders_ && queue_.front().request_.group_ == RateLimitGroup::TRADING) &&
695 queue_.front().request_.method_ != http::verb::get && !queue_.front().refreshed_ && idle_since_ &&
696 std::chrono::steady_clock::now() - *idle_since_ > options_.unreplayed_idle_limit_
697 ) {
698 queue_.front().refreshed_ = true;
699 disconnect();
700 // The handshake is not admission delay; the wait, if any, is measured again from here.
701 queue_.front().waiting_since_.reset();
702 start_resolve();
703 return;
704 }
705 if (!limiter_) {
706 if (!refresh_for_order()) {
707 start_write();
708 }
709 return;
710 }
711
712 // Admission is evaluated for whichever request is at the front *now*, so a
713 // trading request that arrives while a polling request is waiting is
714 // reconsidered immediately rather than inheriting the wait it did not earn.
715 const auto group = queue_.front().request_.group_;
716 const auto delay = limiter_->delay_until(group);
717 if (delay > RateLimitController::Duration::zero()) {
718 // Waiting longer than the operation's own deadline would queue a request
719 // only to time it out on the wire. Failing now says the same thing sooner,
720 // and says it before the request is sent rather than after.
721 if (delay > std::chrono::duration_cast<RateLimitController::Duration>(options_.timeout_)) {
722 limiter_->record_shed(group);
723 auto pending = std::move(queue_.front());
724 queue_.pop_front();
725 BrokerError error;
726 error.category_ = ErrorCategory::CANCELLED;
727 // Ordinarily nothing was sent -- admission is evaluated only while the connection is
728 // `READY`, never while the front request is in flight. A GET being replayed is the
729 // exception: it is admitted again, and its first attempt did reach the wire.
730 error.reached_broker_ = pending.sent_;
731 error.broker_code_ = "admission_deadline";
732 error.message_ = "request would wait for rate-limit admission beyond its deadline";
733 complete(std::move(pending.handler_), Result<HttpResponse>(std::move(error)));
734 pump();
735 return;
736 }
737 if (!queue_.front().waiting_since_) {
738 queue_.front().waiting_since_ = std::chrono::steady_clock::now();
739 }
740 admission_timer_.expires_after(delay);
741 admission_timer_.async_wait([self = shared_from_this()](beast::error_code ec) {
742 if (ec) {
743 return;
744 }
745 self->pump();
746 });
747 return;
748 }
749
750 // Admitted.
751 // An order still goes to a fresh connection first if this one cannot carry it; the admission is evaluated again after the handshake, and its wait is recorded then, handshake included.
752 if (refresh_for_order()) {
753 return;
754 }
755 if (auto& waiting_since = queue_.front().waiting_since_) {
756 limiter_->record_delay(
757 group,
758 std::chrono::duration_cast<RateLimitController::Duration>(std::chrono::steady_clock::now() - *waiting_since)
759 );
760 waiting_since.reset();
761 }
762 admission_timer_.cancel();
763 limiter_->acquire(group);
764 start_write();
765 }
766
767 // With `fresh_orders_` on, replaces the connection if the front request is an order (`RateLimitGroup::TRADING`) and the connection cannot carry it; returns whether it did.
768 //
769 // An order is never replayed, so one written into a connection the server has closed is an order of unknown outcome.
770 // Servers close a connection that has carried requests on their own schedule (KIS has closed one under a second after an order's reply), so an order is written only on a connection no request has begun writing on.
771 // Checked just before the write, after any admission wait, so that a request written in between (a token request outranks an order and can overtake it) is seen.
772 // A used connection is always replaced; an unused one only when it has sat longer than `HttpClientOptions::unreplayed_idle_limit_` and this request has not been given a fresh connection yet, which bounds the rule for a limit of zero.
773 bool refresh_for_order() {
774 if (!fresh_orders_) {
775 return false;
776 }
777 auto& front = queue_.front();
778 if (front.request_.group_ != RateLimitGroup::TRADING) {
779 return false;
780 }
781 const bool aged = idle_since_ && std::chrono::steady_clock::now() - *idle_since_ > options_.unreplayed_idle_limit_;
782 if (!connection_used_ && (!aged || front.refreshed_)) {
783 return false;
784 }
785 front.refreshed_ = true;
786 disconnect();
787 start_resolve();
788 return true;
789 }
790
791 void start_resolve() {
792 stream_ = std::make_unique<beast::ssl_stream<beast::tcp_stream>>(strand_, context_);
793 state_ = State::RESOLVING;
794 resolve_timed_out_ = false;
795 resolve_timer_.expires_after(options_.timeout_);
796 resolve_timer_.async_wait([self = shared_from_this()](beast::error_code ec) {
797 if (!ec && self->state_ == State::RESOLVING) {
798 self->resolve_timed_out_ = true;
799 self->resolver_.cancel();
800 }
801 });
802 resolver_.async_resolve(
803 host_, port_, [self = shared_from_this()](beast::error_code ec, tcp::resolver::results_type endpoints) {
804 self->resolve_timer_.cancel();
805 // `close()` completes every queued request and releases the stream, so a
806 // continuation that arrives afterwards has nothing left to advance.
807 if (self->stopped_ || !self->stream_) {
808 return;
809 }
810 if (ec) {
811 if (self->resolve_timed_out_) {
812 ec = beast::error_code(net::error::timed_out);
813 }
814 self->fail("resolve", ec);
815 return;
816 }
817 self->state_ = State::CONNECTING;
818 beast::get_lowest_layer(*self->stream_).expires_after(self->options_.timeout_);
819 beast::get_lowest_layer(*self->stream_)
820 .async_connect(endpoints, [self](beast::error_code connect_ec, tcp::resolver::results_type::endpoint_type) {
821 if (self->stopped_ || !self->stream_) {
822 return;
823 }
824 if (connect_ec) {
825 self->fail("connect", connect_ec);
826 return;
827 }
828 self->start_handshake();
829 });
830 }
831 );
832 }
833
834 void start_handshake() {
835 if (!SSL_set_tlsext_host_name(stream_->native_handle(), host_.c_str())) {
836 fail("sni", beast::error_code(static_cast<int>(::ERR_get_error()), net::error::get_ssl_category()));
837 return;
838 }
839 stream_->set_verify_callback(ssl::host_name_verification(host_));
840 state_ = State::HANDSHAKING;
841 beast::get_lowest_layer(*stream_).expires_after(options_.timeout_);
842 stream_->async_handshake(ssl::stream_base::client, [self = shared_from_this()](beast::error_code ec) {
843 if (self->stopped_ || !self->stream_) {
844 return;
845 }
846 if (ec) {
847 self->fail("tls_handshake", ec);
848 return;
849 }
850 self->state_ = State::READY;
851 // The idle clock starts here too: a request can wait for admission on a connection that has
852 // carried nothing yet, and the server's idle timeout runs all the same.
853 self->idle_since_ = std::chrono::steady_clock::now();
854 self->connection_used_ = false;
855 self->pump();
856 });
857 }
858
859 void start_write() {
860 // Marked here, which is the only moment this can be said truthfully: everything before is
861 // resolving, connecting and handshaking, none of which puts the request anywhere.
862 queue_.front().sent_ = true;
863 connection_used_ = true;
864 const auto& request_value = queue_.front().request_;
865 active_request_.emplace(request_value.method_, request_value.target_, request_value.version_);
866 active_request_->set(http::field::host, host_header());
867 active_request_->set(http::field::user_agent, "algotradelib");
868 active_request_->keep_alive(true);
869 for (const auto& header : request_value.headers_) {
870 active_request_->set(header.first, header.second);
871 }
872 active_request_->body() = request_value.body_;
873 if (!request_value.body_.empty()) {
874 active_request_->prepare_payload();
875 }
876
877 state_ = State::WRITING;
878 beast::get_lowest_layer(*stream_).expires_after(options_.timeout_);
879 http::async_write(*stream_, *active_request_, [self = shared_from_this()](beast::error_code ec, std::size_t) {
880 if (self->stopped_ || self->queue_.empty()) {
881 return;
882 }
883 if (ec) {
884 self->fail("write", ec);
885 return;
886 }
887 self->start_read();
888 });
889 }
890
891 void start_read() {
892 parser_.emplace();
893 parser_->body_limit(options_.body_limit_);
894 state_ = State::READING;
895 beast::get_lowest_layer(*stream_).expires_after(options_.timeout_);
896 http::async_read(*stream_, buffer_, *parser_, [self = shared_from_this()](beast::error_code ec, std::size_t) {
897 if (self->stopped_ || self->queue_.empty()) {
898 return;
899 }
900 if (ec) {
901 self->fail("read", ec);
902 return;
903 }
904 auto response = self->parser_->release();
905 const bool keep_alive = response.keep_alive() && !response.need_eof();
906 self->parser_.reset();
907 self->active_request_.reset();
908 auto pending = std::move(self->queue_.front());
909 self->queue_.pop_front();
910 if (keep_alive) {
911 self->state_ = State::READY;
912 self->idle_since_ = std::chrono::steady_clock::now();
913 } else {
914 self->disconnect();
915 }
916 self->complete(std::move(pending.handler_), Result<HttpResponse>(std::move(response)));
917 self->pump();
918 });
919 }
920
921 void fail(const char* stage, beast::error_code ec) {
922 // **Asked of the request, not of the connection** (`sent_` is kept on each pending request), for
923 // the reason `close()` gives: `disconnect()` resets the connection's state, and asking it afterwards
924 // would answer "not in flight" for every failure -- including one that happened halfway through
925 // writing an order. This is the same question from the other
926 // side: a resolve, connect, or handshake failure happens *before* `start_write()`, so an order
927 // has certainly not been sent, and reporting it as indeterminate spends a rate-limit slot and
928 // withholds the instrument to reconcile an order that does not exist.
929 disconnect();
930 if (queue_.empty()) {
931 return;
932 }
933 auto& pending = queue_.front();
934 if (pending.request_.method_ == http::verb::get && !pending.retried_ && ec != net::error::operation_aborted) {
935 pending.retried_ = true;
936 pump();
937 return;
938 }
939 auto completed = std::move(pending);
940 queue_.pop_front();
941 auto error = transport_error(stage, ec);
942 error.reached_broker_ = completed.sent_;
943 complete(std::move(completed.handler_), Result<HttpResponse>(std::move(error)));
944 pump();
945 }
946
947 void disconnect() noexcept {
948 resolve_timer_.cancel();
949 if (stream_) {
950 close_ssl_stream(*stream_);
951 stream_.reset();
952 }
953 buffer_.consume(buffer_.size());
954 parser_.reset();
955 active_request_.reset();
956 state_ = State::DISCONNECTED;
957 idle_since_.reset();
958 connection_used_ = false;
959 }
960
961 std::string host_header() const {
962 return make_host_header(host_, port_);
963 }
964
965 void complete(CompletionHandler handler, Result<HttpResponse> result) {
966 auto executor = net::get_associated_executor(handler, strand_);
967 net::dispatch(executor, [handler = std::move(handler), result = std::move(result)]() mutable {
968 std::move(handler)(std::move(result));
969 });
970 }
971};
972
973} // namespace network
974} // namespace algotradelib
Either a value or a BrokerError.
Definition types.hpp:1058
auto async_request(HttpRequest request_value, CompletionToken &&token)
Queues a request; completes with the response (any status) or an error.
AsyncHttpClient(net::any_io_executor executor, ssl::context &context, std::string host, std::string port, HttpClientOptions options={})
Constructs a client; it connects on the first request.
RateLimitController * rate_limits() noexcept
Returns the connection's rate limiter.
net::any_completion_handler< void(Result< HttpResponse >)> CompletionHandler
The completion handler type: called once with the response or an error.
void close()
Closes the client: cancels the connection and completes every queued request with CANCELLED....
std::uint64_t admission_waits() const noexcept
Returns how many times the client started a rate-limit admission wait.
const RateLimitController * rate_limits() const noexcept
Returns the connection's rate limiter (read-only).
HttpResponse get(const std::string &target, const std::map< std::string, std::string > &headers={})
Sends a GET request and waits for the response.
HttpClient(net::io_context &ioc, ssl::context &context, std::string host, std::string port, HttpClientOptions options={})
Constructs a client; it connects on the first request.
void close()
Closes the connection; the next request opens a new one.
HttpResponse post(const std::string &target, const std::string &body, const std::map< std::string, std::string > &headers={})
Sends a POST request and waits for the response; never retried.
HttpResponse request(http::verb method, const std::string &target, const std::string &body={}, const std::map< std::string, std::string > &headers={})
Sends a request and waits for the response; a GET that fails is sent once more.
The rate limiter of one connection (one app key): a RateLimitBucket on the steady clock,...
HTTP and WebSocket transport, OAuth tokens, and request pacing.
RateLimitGroup
The traffic class of a request, for rate limiting and queue priority. The broker adapter that builds ...
@ TRADING
Order placement, amendment and cancellation. HttpClientOptions::fresh_connection_for_orders_ applies ...
@ REFERENCE
Instrument reference data and trading calendars.
constexpr int rate_limit_priority(RateLimitGroup group) noexcept
Returns a traffic class's queue priority.
BrokerError transport_error(std::string stage, beast::error_code ec)
Converts a transport error into a BrokerError.
void shutdown_ssl_stream(beast::ssl_stream< beast::tcp_stream > &stream, std::chrono::seconds timeout) noexcept
Shuts a TLS stream down (best effort) and closes its socket.
void close_ssl_stream(beast::ssl_stream< beast::tcp_stream > &stream) noexcept
Cancels a TLS stream's operations and closes its socket, without waiting for the TLS shutdown.
std::string make_host_header(const std::string &host, const std::string &port)
Builds an HTTP Host header value.
http::response< http::string_body > HttpResponse
The HTTP response type the transport clients return.
The library: broker-neutral types (core), and the modules below.
@ CANCELLED
The operation was cancelled, such as by closing the client or a local deadline.
Definition types.hpp:950
@ TRANSPORT
The connection failed (DNS, connect, TLS, write or read).
Definition types.hpp:952
net::ip::tcp tcp
Short for boost::asio::ip::tcp.
The error a broker or transport operation returns.
Definition types.hpp:1003
std::string message_
A human-readable description, for logs; do not parse it.
Definition types.hpp:1033
ErrorCategory category_
The kind of failure; the field to branch on.
Definition types.hpp:1005
std::string broker_code_
The broker's own error code, verbatim (for example KIS's EGW00201).
Definition types.hpp:1022
bool reached_broker_
Whether a request was sent before this error.
Definition types.hpp:1014
Deadlines, size limits and pacing for an HTTP client.
std::optional< RateLimitBudget > rate_limit_
The rate-limit budget that paces this connection's requests, or empty (the default) for no pacing (As...
std::chrono::seconds timeout_
The deadline for each of DNS lookup, connect, TLS handshake, write and read, in AsyncHttpClient; Http...
std::chrono::milliseconds unreplayed_idle_limit_
How long a kept-alive connection may sit idle and still carry a request other than a GET (one second ...
std::size_t body_limit_
The largest response body accepted, in bytes.
std::optional< bool > fresh_connection_for_orders_
Whether AsyncHttpClient writes every order (RateLimitGroup::TRADING) on a connection no request has u...
std::size_t queue_limit_
How many requests the queue may hold, the one being sent included (AsyncHttpClient); one more fails w...
An HTTP request for AsyncHttpClient.
RateLimitGroup group_
The traffic class, for rate limiting and queue priority.
std::string target_
The request target: path and query.
std::vector< std::pair< std::string, std::string > > headers_
Additional headers, in the order they are sent.
std::string body_
The request body, empty for a GET.
http::verb method_
The HTTP method. A GET may be sent again once after a connection failure; nothing else is.
int version_
The HTTP version, 11 for HTTP/1.1.