Malloy
Loading...
Searching...
No Matches
connection.hpp
1#pragma once
2
3#include "../type_traits.hpp"
4#include "../../core/type_traits.hpp"
5#include "../../core/http/request.hpp"
6#include "../../core/http/response.hpp"
7#include "../../core/http/type_traits.hpp"
8
9#include <boost/asio/strand.hpp>
10#include <boost/beast/core.hpp>
11#include <spdlog/logger.h>
12
13#include <future>
14#include <optional>
15
16namespace malloy::client::http
17{
18
24 template<class Derived, malloy::http::concepts::body ReqBody, concepts::response_filter Filter, typename Callback>
26 {
27 public:
28 using resp_t = typename Filter::response_type;
29 using callback_t = Callback;
30
31 connection(std::shared_ptr<spdlog::logger> logger, boost::asio::io_context& io_ctx, const std::uint64_t body_limit) :
32 m_logger(std::move(logger)),
33 m_resolver(boost::asio::make_strand(io_ctx))
34 {
35 // Sanity check
36 if (!m_logger)
37 throw std::invalid_argument("no valid logger provided.");
38
39 // Set body limit
40 m_parser.body_limit(body_limit);
41 }
42
43 // Start the asynchronous operation
44 void
45 run(
46 char const* port,
48 std::promise<malloy::error_code> err_channel,
49 callback_t&& cb,
50 Filter&& filter
51 )
52 {
53 m_req_filter = std::move(filter);
54 m_req = std::move(req);
55 m_err_channel = std::move(err_channel);
56 m_cb.emplace(std::move(cb));
57
58 // Look up the domain name
59 m_resolver.async_resolve(
60 m_req.base()[malloy::http::field::host],
61 port,
62 boost::beast::bind_front_handler(
63 &connection::on_resolve,
64 derived().shared_from_this()
65 )
66 );
67 }
68
69 protected:
70 std::shared_ptr<spdlog::logger> m_logger;
71
72 void
73 send_request()
74 {
75 // Send the HTTP request to the remote host
76 boost::beast::http::async_write(
77 derived().stream(),
78 m_req,
79 boost::beast::bind_front_handler(
80 &connection::on_write,
81 derived().shared_from_this()
82 )
83 );
84 }
85
86 private:
87 boost::asio::ip::tcp::resolver m_resolver;
88 boost::beast::flat_buffer m_buffer; // (Must persist between reads)
89 boost::beast::http::response_parser<boost::beast::http::empty_body> m_parser;
91 std::promise<malloy::error_code> m_err_channel;
92 std::optional<callback_t> m_cb;
93 Filter m_req_filter;
94
95 [[nodiscard]]
96 Derived&
97 derived()
98 {
99 return static_cast<Derived&>(*this);
100 }
101
102 void
103 on_resolve(const boost::beast::error_code& ec, boost::asio::ip::tcp::resolver::results_type results)
104 {
105 if (ec) {
106 m_logger->error("on_resolve: {}", ec.message());
107 m_err_channel.set_value(ec);
108 return;
109 }
110
111 // Set a timeout on the operation
112 boost::beast::get_lowest_layer(derived().stream()).expires_after(std::chrono::seconds(30));
113
114 // Make the connection on the IP address we get from a lookup
115 boost::beast::get_lowest_layer(derived().stream()).async_connect(
116 results,
117 boost::beast::bind_front_handler(
118 &connection::on_connect,
119 derived().shared_from_this()
120 )
121 );
122 }
123
124 void
125 on_connect(const boost::beast::error_code& ec, boost::asio::ip::tcp::resolver::results_type::endpoint_type)
126 {
127 if (ec) {
128 m_logger->error("on_connect: {}", ec.message());
129 m_err_channel.set_value(ec);
130 return;
131 }
132
133 // Set a timeout on the operation
134 boost::beast::get_lowest_layer(derived().stream()).expires_after(std::chrono::seconds(30));
135
136 // Call hook
137 derived().hook_connected();
138 }
139
140 void
141 on_write(const boost::beast::error_code& ec, [[maybe_unused]] const std::size_t bytes_transferred)
142 {
143 if (ec) {
144 m_logger->error("on_write: {}", ec.message());
145 m_err_channel.set_value(ec);
146 return;
147 }
148
149 // Receive the HTTP response
150 boost::beast::http::async_read_header(
151 derived().stream(),
152 m_buffer,
153 m_parser,
154 malloy::bind_front_handler(
155 &connection::on_read_header,
156 derived().shared_from_this()
157 )
158 );
159
160 }
161
162 void
163 on_read_header(malloy::error_code ec, std::size_t)
164 {
165 if (ec) {
166 m_logger->error("on_read_header: '{}'", ec.message());
167 m_err_channel.set_value(ec);
168 return;
169 }
170
171 // Pick a body and parse it from the stream
172 auto bodies = m_req_filter.body_for(m_parser.get().base());
173 std::visit([this](auto&& body) {
174 using body_t = std::decay_t<decltype(body)>;
175
176 auto parser = std::make_shared<boost::beast::http::response_parser<body_t>>(std::move(m_parser));
177 m_req_filter.setup_body(parser->get().base(), parser->get().body());
178
179 boost::beast::http::async_read(
180 derived().stream(),
181 m_buffer,
182 *parser,
183 [this, parser, me = derived().shared_from_this()](auto ec, auto) {
184 if (ec) {
185 m_logger->error("on_read(): {}", ec.message());
186 m_err_channel.set_value(ec);
187 return;
188 }
189
190 // Notify via callback
191 (*m_cb)(malloy::http::response<body_t>{parser->release()});
192 on_read();
193 });
194 },
195 std::move(bodies)
196 );
197 }
198
199 void
200 on_read()
201 {
202 // Gracefully close the socket
204 boost::beast::get_lowest_layer(derived().stream()).socket().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
205
206 // not_connected happens sometimes so don't bother reporting it.
207 if (ec && ec != boost::beast::errc::not_connected) {
208 m_logger->error("shutdown: {}", ec.message());
209 }
210 m_err_channel.set_value(ec); // Set it even if its not an error, to signify that we are done
211
212 }
213 };
214
215}
Definition: connection.hpp:26
Definition: request.hpp:19
Definition: response.hpp:22
boost::beast::error_code error_code
Error code used to signify errors without throwing. Truthy means it holds an error.
Definition: error.hpp:9