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 m_logger->trace("on_resolve()");
106
107 if (ec) {
108 m_logger->error("on_resolve: {}", ec.message());
109 m_err_channel.set_value(ec);
110 return;
111 }
112
113 // Set a timeout on the operation
114 boost::beast::get_lowest_layer(derived().stream()).expires_after(std::chrono::seconds(30));
115
116 // Make the connection on the IP address we get from a lookup
117 boost::beast::get_lowest_layer(derived().stream()).async_connect(
118 results,
119 boost::beast::bind_front_handler(
120 &connection::on_connect,
121 derived().shared_from_this()
122 )
123 );
124 }
125
126 void
127 on_connect(const boost::beast::error_code& ec, boost::asio::ip::tcp::resolver::results_type::endpoint_type)
128 {
129 m_logger->trace("on_connect()");
130
131 if (ec) {
132 m_logger->error("on_connect: {}", ec.message());
133 m_err_channel.set_value(ec);
134 return;
135 }
136
137 // Set a timeout on the operation
138 boost::beast::get_lowest_layer(derived().stream()).expires_after(std::chrono::seconds(30));
139
140 // Call hook
141 derived().hook_connected();
142 }
143
144 void
145 on_write(const boost::beast::error_code& ec, [[maybe_unused]] const std::size_t bytes_transferred)
146 {
147 if (ec) {
148 m_logger->error("on_write: {}", ec.message());
149 m_err_channel.set_value(ec);
150 return;
151 }
152
153 // Receive the HTTP response
154 boost::beast::http::async_read_header(
155 derived().stream(),
156 m_buffer,
157 m_parser,
158 malloy::bind_front_handler(
159 &connection::on_read_header,
160 derived().shared_from_this()
161 )
162 );
163 }
164
165 void
166 on_read_header(malloy::error_code ec, std::size_t)
167 {
168 if (ec) {
169 m_logger->error("on_read_header: '{}'", ec.message());
170 m_err_channel.set_value(ec);
171 return;
172 }
173
174 // Pick a body and parse it from the stream
175 auto bodies = m_req_filter.body_for(m_parser.get().base());
176 std::visit([this](auto&& body) {
177 using body_t = std::decay_t<decltype(body)>;
178
179 auto parser = std::make_shared<boost::beast::http::response_parser<body_t>>(std::move(m_parser));
180 m_req_filter.setup_body(parser->get().base(), parser->get().body());
181
182 boost::beast::http::async_read(
183 derived().stream(),
184 m_buffer,
185 *parser,
186 [this, parser, me = derived().shared_from_this()](auto ec, auto) {
187 if (ec) {
188 m_logger->error("on_read(): {}", ec.message());
189 m_err_channel.set_value(ec);
190 return;
191 }
192
193 // Notify via callback
194 (*m_cb)(malloy::http::response<body_t>{parser->release()});
195 on_read();
196 });
197 },
198 std::move(bodies)
199 );
200 }
201
202 void
203 on_read()
204 {
205 // Gracefully close the socket
207 boost::beast::get_lowest_layer(derived().stream()).socket().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
208
209 // not_connected happens sometimes so don't bother reporting it.
210 if (ec && ec != boost::beast::errc::not_connected)
211 m_logger->error("shutdown: {}", ec.message());
212
213 m_err_channel.set_value(ec); // Set it even if its not an error, to signify that we are done
214 }
215 };
216
217}
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