diff options
| author | Rutger Broekhoff | 2026-11-30 21:27:55 +0100 |
|---|---|---|
| committer | Rutger Broekhoff | 2026-11-30 21:27:55 +0100 |
| commit | 7bba7176194c4d1d9c7066f8eda7a94491d924e6 (patch) | |
| tree | a9a171e8608786e09d6342729ee13b8471c0c9c2 /server/src/http/core | |
| parent | 02475e05ccd1aa15c6a6163834f28bfebbef796f (diff) | |
| download | routemon-7bba7176194c4d1d9c7066f8eda7a94491d924e6.tar.gz routemon-7bba7176194c4d1d9c7066f8eda7a94491d924e6.zip | |
Cleanups and updates
Diffstat (limited to 'server/src/http/core')
| -rw-r--r-- | server/src/http/core/client.cpp | 20 | ||||
| -rw-r--r-- | server/src/http/core/client.cppm | 65 | ||||
| -rw-r--r-- | server/src/http/core/common.cpp | 108 | ||||
| -rw-r--r-- | server/src/http/core/common.cppm | 79 | ||||
| -rw-r--r-- | server/src/http/core/server.cpp | 209 | ||||
| -rw-r--r-- | server/src/http/core/server.cppm | 799 |
6 files changed, 1280 insertions, 0 deletions
diff --git a/server/src/http/core/client.cpp b/server/src/http/core/client.cpp new file mode 100644 index 0000000..c0143b0 --- /dev/null +++ b/server/src/http/core/client.cpp | |||
| @@ -0,0 +1,20 @@ | |||
| 1 | module; | ||
| 2 | |||
| 3 | #include <boost/asio/ssl.hpp> | ||
| 4 | #include <boost/beast/core.hpp> | ||
| 5 | #include <boost/beast/http.hpp> | ||
| 6 | |||
| 7 | module routemon:http.core.client$impl; | ||
| 8 | |||
| 9 | import :http.core.client; | ||
| 10 | |||
| 11 | namespace routemon::http::core { | ||
| 12 | |||
| 13 | client::client(net::io_context& ioc) : ioc_{ioc}, resolver_{ioc} | ||
| 14 | { | ||
| 15 | sslc_.set_default_verify_paths(); | ||
| 16 | sslc_.set_verify_mode( | ||
| 17 | net::ssl::verify_peer | net::ssl::verify_fail_if_no_peer_cert); | ||
| 18 | } | ||
| 19 | |||
| 20 | } // namespace routemon::http::core | ||
diff --git a/server/src/http/core/client.cppm b/server/src/http/core/client.cppm new file mode 100644 index 0000000..ada4f03 --- /dev/null +++ b/server/src/http/core/client.cppm | |||
| @@ -0,0 +1,65 @@ | |||
| 1 | module; | ||
| 2 | |||
| 3 | #include <boost/asio/connect.hpp> | ||
| 4 | #include <boost/asio/ip/tcp.hpp> | ||
| 5 | #include <boost/asio/ssl.hpp> | ||
| 6 | #include <boost/beast/core.hpp> | ||
| 7 | #include <boost/beast/http.hpp> | ||
| 8 | |||
| 9 | export module routemon:http.core.client; | ||
| 10 | |||
| 11 | export import :http.core.common; | ||
| 12 | |||
| 13 | namespace net = boost::asio; | ||
| 14 | namespace ssl = net::ssl; | ||
| 15 | using tcp = net::ip::tcp; | ||
| 16 | |||
| 17 | namespace routemon::http::core { | ||
| 18 | |||
| 19 | export class client | ||
| 20 | { | ||
| 21 | net::io_context& ioc_; | ||
| 22 | ssl::context sslc_{ssl::context::tlsv12_client}; | ||
| 23 | tcp::resolver resolver_; | ||
| 24 | |||
| 25 | public: | ||
| 26 | explicit client(net::io_context& ioc); | ||
| 27 | |||
| 28 | template <class ReqBody> | ||
| 29 | auto do_request(bhttp::request<ReqBody>& req) | ||
| 30 | -> bhttp::response<bhttp::dynamic_body> | ||
| 31 | { | ||
| 32 | // TODO: call into non-template member ASAP. | ||
| 33 | // Consider using beast::message_generator. | ||
| 34 | |||
| 35 | auto stream = ssl::stream<beast::tcp_stream>{ioc_, sslc_}; | ||
| 36 | |||
| 37 | auto host = std::string{req.at(bhttp::field::host)}; | ||
| 38 | if (!SSL_set_tlsext_host_name(stream.native_handle(), host.c_str())) | ||
| 39 | { | ||
| 40 | throw beast::system_error{ | ||
| 41 | static_cast<int>(::ERR_get_error()), net::error::get_ssl_category() | ||
| 42 | }; | ||
| 43 | } | ||
| 44 | stream.set_verify_callback(ssl::host_name_verification(host)); | ||
| 45 | auto const results = resolver_.resolve(host, "443"); | ||
| 46 | beast::get_lowest_layer(stream).connect(results); | ||
| 47 | stream.handshake(ssl::stream_base::client); | ||
| 48 | |||
| 49 | req.set(bhttp::field::user_agent, "routemon/1.0"); | ||
| 50 | bhttp::write(stream, req); | ||
| 51 | |||
| 52 | auto buffer = beast::flat_buffer{}; | ||
| 53 | auto res = bhttp::response<bhttp::dynamic_body>{}; | ||
| 54 | bhttp::read(stream, buffer, res); | ||
| 55 | |||
| 56 | auto ec = beast::error_code{}; | ||
| 57 | stream.shutdown(ec); | ||
| 58 | if (ec != net::ssl::error::stream_truncated) | ||
| 59 | throw beast::system_error{ec}; | ||
| 60 | |||
| 61 | return res; | ||
| 62 | } | ||
| 63 | }; | ||
| 64 | |||
| 65 | } // namespace routemon::http::core | ||
diff --git a/server/src/http/core/common.cpp b/server/src/http/core/common.cpp new file mode 100644 index 0000000..bc3ef31 --- /dev/null +++ b/server/src/http/core/common.cpp | |||
| @@ -0,0 +1,108 @@ | |||
| 1 | module; | ||
| 2 | |||
| 3 | #include <boost/beast/core.hpp> | ||
| 4 | #include <boost/beast/http.hpp> | ||
| 5 | |||
| 6 | module routemon:http.core.common$impl; | ||
| 7 | |||
| 8 | import :http.core.common; | ||
| 9 | |||
| 10 | namespace routemon::http::core { | ||
| 11 | |||
| 12 | supported_verb::supported_verb(supported_verb_t value) : value{value} {} | ||
| 13 | |||
| 14 | auto supported_verb::from(bhttp::verb v) -> std::optional<supported_verb> | ||
| 15 | { | ||
| 16 | switch (v) | ||
| 17 | { | ||
| 18 | case bhttp::verb::options: | ||
| 19 | return supported_verb::options; | ||
| 20 | case bhttp::verb::delete_: | ||
| 21 | return supported_verb::delete_; | ||
| 22 | case bhttp::verb::get: | ||
| 23 | return supported_verb::get; | ||
| 24 | case bhttp::verb::head: | ||
| 25 | return supported_verb::head; | ||
| 26 | case bhttp::verb::post: | ||
| 27 | return supported_verb::post; | ||
| 28 | case bhttp::verb::put: | ||
| 29 | return supported_verb::put; | ||
| 30 | default: | ||
| 31 | return std::nullopt; | ||
| 32 | } | ||
| 33 | } | ||
| 34 | |||
| 35 | supported_verb::operator bhttp::verb() const | ||
| 36 | { | ||
| 37 | switch (value) | ||
| 38 | { | ||
| 39 | case supported_verb::options: | ||
| 40 | return bhttp::verb::options; | ||
| 41 | case supported_verb::delete_: | ||
| 42 | return bhttp::verb::delete_; | ||
| 43 | case supported_verb::get: | ||
| 44 | return bhttp::verb::get; | ||
| 45 | case supported_verb::head: | ||
| 46 | return bhttp::verb::head; | ||
| 47 | case supported_verb::post: | ||
| 48 | return bhttp::verb::post; | ||
| 49 | case supported_verb::put: | ||
| 50 | return bhttp::verb::put; | ||
| 51 | } | ||
| 52 | } | ||
| 53 | |||
| 54 | auto verb_set::with(supported_verb v) const noexcept -> verb_set | ||
| 55 | { | ||
| 56 | auto set = verb_set{*this}; | ||
| 57 | switch (v.value) | ||
| 58 | { | ||
| 59 | case supported_verb::delete_: | ||
| 60 | set.delete_ = true; | ||
| 61 | return set; | ||
| 62 | case supported_verb::get: | ||
| 63 | set.get = true; | ||
| 64 | return set; | ||
| 65 | case supported_verb::head: | ||
| 66 | set.head = true; | ||
| 67 | return set; | ||
| 68 | case supported_verb::post: | ||
| 69 | set.post = true; | ||
| 70 | return set; | ||
| 71 | case supported_verb::put: | ||
| 72 | set.put = true; | ||
| 73 | return set; | ||
| 74 | case supported_verb::options: | ||
| 75 | set.options = true; | ||
| 76 | return set; | ||
| 77 | } | ||
| 78 | } | ||
| 79 | |||
| 80 | auto verb_set::empty() const noexcept -> bool { return *this == verb_set{}; } | ||
| 81 | |||
| 82 | auto verb_set::to_string() const -> std::string | ||
| 83 | { | ||
| 84 | std::ostringstream ss; | ||
| 85 | bool wrote = false; | ||
| 86 | auto write = [&](bhttp::verb v) | ||
| 87 | { | ||
| 88 | if (wrote) | ||
| 89 | ss << ", "; | ||
| 90 | ss << v; | ||
| 91 | wrote = true; | ||
| 92 | }; | ||
| 93 | if (delete_) | ||
| 94 | write(bhttp::verb::delete_); | ||
| 95 | if (get) | ||
| 96 | write(bhttp::verb::get); | ||
| 97 | if (head) | ||
| 98 | write(bhttp::verb::head); | ||
| 99 | if (post) | ||
| 100 | write(bhttp::verb::post); | ||
| 101 | if (put) | ||
| 102 | write(bhttp::verb::put); | ||
| 103 | if (options) | ||
| 104 | write(bhttp::verb::options); | ||
| 105 | return ss.str(); | ||
| 106 | } | ||
| 107 | |||
| 108 | } // namespace routemon::http::core | ||
diff --git a/server/src/http/core/common.cppm b/server/src/http/core/common.cppm new file mode 100644 index 0000000..e8fbe42 --- /dev/null +++ b/server/src/http/core/common.cppm | |||
| @@ -0,0 +1,79 @@ | |||
| 1 | module; | ||
| 2 | |||
| 3 | #include <boost/beast/core.hpp> | ||
| 4 | #include <boost/beast/http.hpp> | ||
| 5 | |||
| 6 | export module routemon:http.core.common; | ||
| 7 | |||
| 8 | namespace beast = boost::beast; | ||
| 9 | export namespace bhttp = beast::http; | ||
| 10 | |||
| 11 | namespace boost::beast { | ||
| 12 | |||
| 13 | namespace concepts { | ||
| 14 | |||
| 15 | template <class T> | ||
| 16 | concept buffers_generator = beast::is_buffers_generator<T>::value; | ||
| 17 | |||
| 18 | template <class T> | ||
| 19 | concept const_buffer_sequence = beast::is_const_buffer_sequence<T>::value; | ||
| 20 | |||
| 21 | } // namespace concepts | ||
| 22 | |||
| 23 | namespace http::concepts { | ||
| 24 | |||
| 25 | template <class T> | ||
| 26 | concept fields = is_fields<T>::value; | ||
| 27 | |||
| 28 | template <class T> | ||
| 29 | concept body = is_body<T>::value; | ||
| 30 | |||
| 31 | template <class T> | ||
| 32 | concept body_reader = is_body_reader<T>::value; | ||
| 33 | |||
| 34 | } // namespace http::concepts | ||
| 35 | |||
| 36 | } // namespace boost::beast | ||
| 37 | |||
| 38 | namespace routemon::http::core { | ||
| 39 | |||
| 40 | struct supported_verb | ||
| 41 | { | ||
| 42 | enum supported_verb_t : std::uint8_t | ||
| 43 | { | ||
| 44 | options, | ||
| 45 | delete_, | ||
| 46 | get, | ||
| 47 | head, | ||
| 48 | post, | ||
| 49 | put, | ||
| 50 | }; | ||
| 51 | |||
| 52 | supported_verb_t value; | ||
| 53 | |||
| 54 | supported_verb(supported_verb_t value); | ||
| 55 | |||
| 56 | static auto from(bhttp::verb v) -> std::optional<supported_verb>; | ||
| 57 | |||
| 58 | operator bhttp::verb() const; | ||
| 59 | }; | ||
| 60 | |||
| 61 | export struct verb_set | ||
| 62 | { | ||
| 63 | bool options : 1 = false; | ||
| 64 | bool delete_ : 1 = false; | ||
| 65 | bool get : 1 = false; | ||
| 66 | bool head : 1 = false; | ||
| 67 | bool post : 1 = false; | ||
| 68 | bool put : 1 = false; | ||
| 69 | |||
| 70 | [[nodiscard]] auto with(supported_verb v) const noexcept -> verb_set; | ||
| 71 | [[nodiscard]] auto empty() const noexcept -> bool; | ||
| 72 | [[nodiscard]] auto to_string() const -> std::string; | ||
| 73 | |||
| 74 | auto operator==(verb_set const& rhs) const noexcept -> bool = default; | ||
| 75 | }; | ||
| 76 | static_assert(sizeof(verb_set) == 1); | ||
| 77 | static_assert(alignof(verb_set) == 1); | ||
| 78 | |||
| 79 | } // namespace routemon::http::core | ||
diff --git a/server/src/http/core/server.cpp b/server/src/http/core/server.cpp new file mode 100644 index 0000000..f204dfb --- /dev/null +++ b/server/src/http/core/server.cpp | |||
| @@ -0,0 +1,209 @@ | |||
| 1 | module; | ||
| 2 | |||
| 3 | #include <boost/asio/as_tuple.hpp> | ||
| 4 | #include <boost/asio/awaitable.hpp> | ||
| 5 | #include <boost/asio/co_spawn.hpp> | ||
| 6 | #include <boost/asio/ip/tcp.hpp> | ||
| 7 | #include <boost/beast/core.hpp> | ||
| 8 | #include <boost/beast/http.hpp> | ||
| 9 | #include <boost/config.hpp> | ||
| 10 | #include <boost/json/serialize.hpp> | ||
| 11 | #include <boost/url.hpp> | ||
| 12 | |||
| 13 | module routemon:http.core.server$impl; | ||
| 14 | |||
| 15 | import :http.core.server; | ||
| 16 | import :trace; | ||
| 17 | |||
| 18 | namespace chrono = std::chrono; | ||
| 19 | |||
| 20 | namespace routemon::http::core { | ||
| 21 | |||
| 22 | auto presponse::header() -> bhttp::response_header<bhttp::fields>& | ||
| 23 | { | ||
| 24 | return impl_->header(); | ||
| 25 | } | ||
| 26 | |||
| 27 | auto presponse::header() const -> bhttp::response_header<bhttp::fields> const& | ||
| 28 | { | ||
| 29 | return impl_->header(); | ||
| 30 | } | ||
| 31 | |||
| 32 | auto presponse::is_done() const -> bool { return impl_->is_done(); } | ||
| 33 | |||
| 34 | auto presponse::prepare(beast::error_code& ec) -> const_buffers_type | ||
| 35 | { | ||
| 36 | return impl_->prepare(ec); | ||
| 37 | } | ||
| 38 | |||
| 39 | auto presponse::consume(std::size_t n) -> void { return impl_->consume(n); } | ||
| 40 | |||
| 41 | auto presponse::keep_alive() const noexcept -> bool | ||
| 42 | { | ||
| 43 | return impl_->keep_alive(); | ||
| 44 | } | ||
| 45 | |||
| 46 | keep_alive::keep_alive(bool value) : value{value} {} | ||
| 47 | |||
| 48 | auto problem_rsp( | ||
| 49 | base_ctx const& ctx, problem::details const& problem, keep_alive ka) | ||
| 50 | -> presponse | ||
| 51 | { | ||
| 52 | auto rsp = make_rsp<bhttp::string_body>(problem.status, ka); | ||
| 53 | rsp.set(bhttp::field::content_type, "application/problem+json"); | ||
| 54 | rsp.body() = json::serialize(json::value_from(problem, ctx.locale)); | ||
| 55 | rsp.prepare_payload(); | ||
| 56 | return presponse{std::move(rsp)}; | ||
| 57 | } | ||
| 58 | |||
| 59 | auto make_preflight_rsp(preflight_response res, keep_alive ka) | ||
| 60 | -> bhttp::response<bhttp::empty_body> | ||
| 61 | { | ||
| 62 | auto rsp = make_rsp<bhttp::empty_body>(bhttp::status::no_content, ka); | ||
| 63 | auto allow_headers_str = res.allow_headers | ||
| 64 | | std::views::transform( | ||
| 65 | [](auto const& field) -> std::string_view | ||
| 66 | { return bhttp::to_string(field); }) | ||
| 67 | | std::views::join_with(std::string_view{", "}) | ||
| 68 | | std::ranges::to<std::string>(); | ||
| 69 | rsp.set( | ||
| 70 | bhttp::field::access_control_allow_methods, | ||
| 71 | res.allow_methods.to_string()); | ||
| 72 | rsp.set(bhttp::field::access_control_allow_headers, allow_headers_str); | ||
| 73 | rsp.prepare_payload(); | ||
| 74 | return rsp; | ||
| 75 | } | ||
| 76 | |||
| 77 | auto global_options_handler(base_ctx const& ctx, readable_request r) | ||
| 78 | -> net::awaitable<presponse> | ||
| 79 | { | ||
| 80 | // TODO: switch to "small (4KB) discarded" body type, similar to what Go | ||
| 81 | // does? Same goes for default_options_handler? Not sure. | ||
| 82 | if (auto res = co_await read_empty_request(ctx, std::move(r)); !res) | ||
| 83 | co_return std::move(res.error()); | ||
| 84 | auto req = r.p->release(); | ||
| 85 | auto rsp = make_rsp<bhttp::empty_body>( | ||
| 86 | bhttp::status::no_content, keep_alive{req.keep_alive()}); | ||
| 87 | rsp.prepare_payload(); | ||
| 88 | co_return std::move(rsp); | ||
| 89 | } | ||
| 90 | |||
| 91 | auto router::handle_request(trace::id trace_id, readable_request r) const | ||
| 92 | -> net::awaitable<presponse> | ||
| 93 | { | ||
| 94 | return impl_->handle_request(trace_id, r); | ||
| 95 | } | ||
| 96 | |||
| 97 | server::server(log::logger const& l, router&& r) | ||
| 98 | : l_{l.sub("http_server")}, r_{std::move(r)} | ||
| 99 | { | ||
| 100 | } | ||
| 101 | |||
| 102 | auto server::do_session(beast::tcp_stream strm) -> net::awaitable<void> | ||
| 103 | { | ||
| 104 | auto buf = beast::flat_buffer{}; | ||
| 105 | |||
| 106 | while (true) | ||
| 107 | { | ||
| 108 | auto p0 = bhttp::request_parser<bhttp::empty_body>{}; | ||
| 109 | p0.body_limit(boost::none); | ||
| 110 | auto [ec, _] = | ||
| 111 | co_await bhttp::async_read_header(strm, buf, p0, net::as_tuple); | ||
| 112 | if (ec == bhttp::error::end_of_stream) | ||
| 113 | break; | ||
| 114 | else if (ec) | ||
| 115 | throw boost::system::system_error{ec}; | ||
| 116 | |||
| 117 | auto trace_id = trace::id{}; | ||
| 118 | auto l = l_.sub("do_session").with("trace_id", trace_id.as_string()); | ||
| 119 | l.debug("Read header, invoking request handler"); | ||
| 120 | auto const before_hdl = chrono::steady_clock::now(); | ||
| 121 | |||
| 122 | auto http_version = p0.get().version(); | ||
| 123 | auto&& rsp = co_await r_.handle_request( | ||
| 124 | trace_id, readable_request{ | ||
| 125 | .p = util::not_null{&p0}, | ||
| 126 | .strm = util::not_null{&strm}, | ||
| 127 | .buf = util::not_null{&buf}, | ||
| 128 | }); | ||
| 129 | |||
| 130 | l.debug( | ||
| 131 | "Request handler returned after {}, writing response", | ||
| 132 | chrono::duration<double, std::milli>{ | ||
| 133 | chrono::steady_clock::now() - before_hdl | ||
| 134 | }); | ||
| 135 | auto before_write_rsp = chrono::steady_clock::now(); | ||
| 136 | |||
| 137 | rsp.header().version(http_version); | ||
| 138 | bool keep_alive = rsp.keep_alive(); | ||
| 139 | co_await beast::async_write(strm, std::move(rsp)); | ||
| 140 | |||
| 141 | l.debug( | ||
| 142 | "Wrote response in {}", chrono::duration<double, std::milli>{ | ||
| 143 | chrono::steady_clock::now() - before_write_rsp | ||
| 144 | }); | ||
| 145 | |||
| 146 | if (!keep_alive) | ||
| 147 | { | ||
| 148 | break; | ||
| 149 | } | ||
| 150 | } | ||
| 151 | |||
| 152 | strm.socket().shutdown(tcp::socket::shutdown_send); | ||
| 153 | } | ||
| 154 | |||
| 155 | auto server::do_listen(tcp::endpoint endpoint) -> net::awaitable<void> | ||
| 156 | { | ||
| 157 | auto executor = co_await net::this_coro::executor; | ||
| 158 | auto acceptor = tcp::acceptor{executor, endpoint}; | ||
| 159 | |||
| 160 | l_.with("endpoint", endpoint.address().to_string()) | ||
| 161 | .with("port", std::to_string(endpoint.port())) | ||
| 162 | .info("Serving"); | ||
| 163 | while (true) | ||
| 164 | { | ||
| 165 | net::co_spawn( | ||
| 166 | executor, | ||
| 167 | do_session(beast::tcp_stream{co_await acceptor.async_accept()}), | ||
| 168 | [this](std::exception_ptr e) | ||
| 169 | { | ||
| 170 | if (e) | ||
| 171 | { | ||
| 172 | try | ||
| 173 | { | ||
| 174 | std::rethrow_exception(e); | ||
| 175 | } | ||
| 176 | catch (std::exception const& e) | ||
| 177 | { | ||
| 178 | l_.error("Error in session: {}", e.what()); | ||
| 179 | } | ||
| 180 | } | ||
| 181 | }); | ||
| 182 | } | ||
| 183 | } | ||
| 184 | |||
| 185 | auto server::spawn(net::io_context& ioc) -> void | ||
| 186 | { | ||
| 187 | auto const addr = net::ip::make_address("0.0.0.0"); | ||
| 188 | auto const endpoint = tcp::endpoint{addr, 8284}; | ||
| 189 | |||
| 190 | // TODO: make exception handling as nice as in srv.cpp | ||
| 191 | net::co_spawn( | ||
| 192 | ioc, do_listen(endpoint), | ||
| 193 | [this](std::exception_ptr e) | ||
| 194 | { | ||
| 195 | if (e) | ||
| 196 | { | ||
| 197 | try | ||
| 198 | { | ||
| 199 | std::rethrow_exception(e); | ||
| 200 | } | ||
| 201 | catch (std::exception const& e) | ||
| 202 | { | ||
| 203 | l_.error("Error: {}", e.what()); | ||
| 204 | } | ||
| 205 | } | ||
| 206 | }); | ||
| 207 | } | ||
| 208 | |||
| 209 | } // namespace routemon::http::core | ||
diff --git a/server/src/http/core/server.cppm b/server/src/http/core/server.cppm new file mode 100644 index 0000000..dbef975 --- /dev/null +++ b/server/src/http/core/server.cppm | |||
| @@ -0,0 +1,799 @@ | |||
| 1 | module; | ||
| 2 | |||
| 3 | #include <boost/asio/as_tuple.hpp> | ||
| 4 | #include <boost/asio/awaitable.hpp> | ||
| 5 | #include <boost/asio/co_spawn.hpp> | ||
| 6 | #include <boost/asio/ip/tcp.hpp> | ||
| 7 | #include <boost/beast/core.hpp> | ||
| 8 | #include <boost/beast/http.hpp> | ||
| 9 | #include <boost/config.hpp> | ||
| 10 | #include <boost/json/serialize.hpp> | ||
| 11 | #include <boost/url.hpp> | ||
| 12 | |||
| 13 | export module routemon:http.core.server; | ||
| 14 | |||
| 15 | import std; | ||
| 16 | import :config; | ||
| 17 | import :trace; | ||
| 18 | import :http.core.common; | ||
| 19 | import :problem; | ||
| 20 | |||
| 21 | namespace net = boost::asio; | ||
| 22 | using tcp = net::ip::tcp; | ||
| 23 | |||
| 24 | namespace routemon::http::core { | ||
| 25 | |||
| 26 | struct readable_request | ||
| 27 | { | ||
| 28 | util::not_null<bhttp::request_parser<bhttp::empty_body>*> p; | ||
| 29 | util::not_null<beast::tcp_stream*> strm; | ||
| 30 | util::not_null<beast::flat_buffer*> buf; | ||
| 31 | }; | ||
| 32 | |||
| 33 | class presponse | ||
| 34 | { | ||
| 35 | public: | ||
| 36 | using const_buffers_type = beast::span<net::const_buffer>; | ||
| 37 | |||
| 38 | private: | ||
| 39 | struct impl_base | ||
| 40 | { | ||
| 41 | virtual ~impl_base() = default; | ||
| 42 | virtual auto header() -> bhttp::response_header<bhttp::fields>& = 0; | ||
| 43 | virtual auto header() const | ||
| 44 | -> bhttp::response_header<bhttp::fields> const& = 0; | ||
| 45 | virtual auto is_done() const -> bool = 0; | ||
| 46 | virtual auto prepare(beast::error_code&) -> const_buffers_type = 0; | ||
| 47 | virtual auto consume(std::size_t n) -> void = 0; | ||
| 48 | virtual auto keep_alive() const -> bool = 0; | ||
| 49 | }; | ||
| 50 | std::unique_ptr<impl_base> impl_; | ||
| 51 | |||
| 52 | template <bhttp::concepts::body Body> | ||
| 53 | class impl : public impl_base | ||
| 54 | { | ||
| 55 | // Initializes in the response state. | ||
| 56 | // At the first call to prepare, we switch to the message generator | ||
| 57 | // state. After that point, header may not be called anymore (it will | ||
| 58 | // throw). | ||
| 59 | std::variant<bhttp::response<Body>, bhttp::message_generator> state_; | ||
| 60 | |||
| 61 | auto ensure_message_generator() -> bhttp::message_generator& | ||
| 62 | { | ||
| 63 | if (auto prsp = std::get_if<bhttp::response<Body>>(&state_)) | ||
| 64 | { | ||
| 65 | auto rsp = bhttp::response<Body>{std::move(*prsp)}; | ||
| 66 | state_.template emplace<bhttp::message_generator>(std::move(rsp)); | ||
| 67 | } | ||
| 68 | return std::get<bhttp::message_generator>(state_); | ||
| 69 | } | ||
| 70 | |||
| 71 | public: | ||
| 72 | explicit impl(bhttp::response<Body>&& rsp) : state_{std::move(rsp)} {} | ||
| 73 | |||
| 74 | auto header() -> bhttp::response_header<bhttp::fields>& override | ||
| 75 | { | ||
| 76 | if (auto prsp = std::get_if<bhttp::response<Body>>(&state_)) | ||
| 77 | { | ||
| 78 | return prsp->base(); | ||
| 79 | } | ||
| 80 | else | ||
| 81 | { | ||
| 82 | // TODO: define custom exception type | ||
| 83 | // presponse::bad_header_access | ||
| 84 | throw std::logic_error{"header() may not be called after prepare()"}; | ||
| 85 | } | ||
| 86 | } | ||
| 87 | auto header() const -> bhttp::response_header<bhttp::fields> const& override | ||
| 88 | { | ||
| 89 | if (auto prsp = std::get_if<bhttp::response<Body>>(&state_)) | ||
| 90 | { | ||
| 91 | return prsp->base(); | ||
| 92 | } | ||
| 93 | else | ||
| 94 | { | ||
| 95 | throw std::logic_error{"header() may not be called after prepare()"}; | ||
| 96 | } | ||
| 97 | } | ||
| 98 | |||
| 99 | auto is_done() const -> bool override | ||
| 100 | { | ||
| 101 | if (auto pgen = std::get_if<bhttp::message_generator>(&state_)) | ||
| 102 | { | ||
| 103 | return pgen->is_done(); | ||
| 104 | } | ||
| 105 | else /* still in the response state */ | ||
| 106 | { | ||
| 107 | return false; | ||
| 108 | } | ||
| 109 | } | ||
| 110 | |||
| 111 | auto prepare(beast::error_code& ec) -> const_buffers_type override | ||
| 112 | { | ||
| 113 | return ensure_message_generator().prepare(ec); | ||
| 114 | } | ||
| 115 | |||
| 116 | auto consume(std::size_t n) -> void override | ||
| 117 | { | ||
| 118 | ensure_message_generator().consume(n); | ||
| 119 | } | ||
| 120 | |||
| 121 | auto keep_alive() const noexcept -> bool override | ||
| 122 | { | ||
| 123 | return state_.visit( | ||
| 124 | util::overloaded{ | ||
| 125 | [](bhttp::response<Body> const& rsp) -> bool | ||
| 126 | { return rsp.keep_alive(); }, | ||
| 127 | [](bhttp::message_generator const& gen) -> bool | ||
| 128 | { return gen.keep_alive(); }, | ||
| 129 | }); | ||
| 130 | } | ||
| 131 | }; | ||
| 132 | |||
| 133 | public: | ||
| 134 | template <bhttp::concepts::body Body> | ||
| 135 | explicit presponse(bhttp::response<Body>&& rsp) | ||
| 136 | : impl_{new impl{std::move(rsp)}} | ||
| 137 | { | ||
| 138 | } | ||
| 139 | |||
| 140 | auto header() -> bhttp::response_header<bhttp::fields>&; | ||
| 141 | auto header() const -> bhttp::response_header<bhttp::fields> const&; | ||
| 142 | auto is_done() const -> bool; | ||
| 143 | auto prepare(beast::error_code& ec) -> const_buffers_type; | ||
| 144 | auto consume(std::size_t n) -> void; | ||
| 145 | auto keep_alive() const noexcept -> bool; | ||
| 146 | }; | ||
| 147 | static_assert(beast::concepts::buffers_generator<presponse>); | ||
| 148 | |||
| 149 | template <class Ctx> | ||
| 150 | using next_handler_t = std::function<auto(Ctx)->net::awaitable<presponse>>; | ||
| 151 | |||
| 152 | template <class OuterCtx, class InnerCtx> | ||
| 153 | using middleware_t = | ||
| 154 | std::function<auto( | ||
| 155 | OuterCtx, bhttp::request_header<bhttp::fields>&, | ||
| 156 | next_handler_t<InnerCtx>) | ||
| 157 | ->net::awaitable<presponse>>; | ||
| 158 | |||
| 159 | template <class Ctx> | ||
| 160 | auto id_middleware( | ||
| 161 | Ctx ctx, bhttp::request_header<bhttp::fields>&, next_handler_t<Ctx> next) | ||
| 162 | -> net::awaitable<presponse> | ||
| 163 | { | ||
| 164 | co_return co_await next(std::move(ctx)); | ||
| 165 | } | ||
| 166 | |||
| 167 | struct base_ctx | ||
| 168 | { | ||
| 169 | std::locale locale; | ||
| 170 | trace::id trace_id; | ||
| 171 | }; | ||
| 172 | |||
| 173 | template <class Ctx> | ||
| 174 | using basic_route_handler_fn_t = | ||
| 175 | std::function<auto( | ||
| 176 | Ctx, readable_request, | ||
| 177 | std::vector<std::string> const& matches) | ||
| 178 | ->net::awaitable<presponse>>; | ||
| 179 | |||
| 180 | template <class Ctx> | ||
| 181 | auto cors_middleware(std::vector<std::string> const& allow_origins) | ||
| 182 | -> middleware_t<Ctx, Ctx> | ||
| 183 | { | ||
| 184 | if (allow_origins.empty()) | ||
| 185 | return id_middleware<Ctx>; | ||
| 186 | |||
| 187 | auto header_str = allow_origins | ||
| 188 | | std::views::join_with(std::string_view{", "}) | ||
| 189 | | std::ranges::to<std::string>(); | ||
| 190 | |||
| 191 | return [header_str = std::move(header_str)]( | ||
| 192 | Ctx ctx, bhttp::request_header<bhttp::fields>& req_hdr, | ||
| 193 | next_handler_t<Ctx> next) -> net::awaitable<presponse> | ||
| 194 | { | ||
| 195 | std::ignore = req_hdr; | ||
| 196 | auto prersp = co_await next(ctx); | ||
| 197 | prersp.header().set(bhttp::field::access_control_allow_origin, header_str); | ||
| 198 | co_return std::move(prersp); | ||
| 199 | }; | ||
| 200 | } | ||
| 201 | |||
| 202 | template <class Ctx> | ||
| 203 | auto expose_trace_id_middleware( | ||
| 204 | Ctx ctx, bhttp::request_header<bhttp::fields>& req_hdr, | ||
| 205 | next_handler_t<Ctx> next) -> net::awaitable<presponse> | ||
| 206 | { | ||
| 207 | std::ignore = req_hdr; | ||
| 208 | auto prersp = co_await next(std::move(ctx)); | ||
| 209 | prersp.header().set( | ||
| 210 | "X-Routemon-Trace-Id", | ||
| 211 | std::string_view{static_cast<base_ctx const&>(ctx).trace_id.as_string()}); | ||
| 212 | prersp.header().insert( | ||
| 213 | bhttp::field::access_control_expose_headers, "X-Routemon-Trace-Id"); | ||
| 214 | co_return std::move(prersp); | ||
| 215 | } | ||
| 216 | |||
| 217 | template <class Ctx> | ||
| 218 | auto expose_content_language_middleware( | ||
| 219 | Ctx ctx, bhttp::request_header<bhttp::fields>& req_hdr, | ||
| 220 | next_handler_t<Ctx> next) -> net::awaitable<presponse> | ||
| 221 | { | ||
| 222 | std::ignore = req_hdr; | ||
| 223 | auto prersp = co_await next(std::move(ctx)); | ||
| 224 | if (prersp.header().find(bhttp::field::content_language) | ||
| 225 | == prersp.header().end() | ||
| 226 | && std::has_facet<locale::bcp47_tag>(ctx.locale)) | ||
| 227 | { | ||
| 228 | prersp.header().set( | ||
| 229 | bhttp::field::content_language, | ||
| 230 | std::use_facet<locale::bcp47_tag>(ctx.locale).tag()); | ||
| 231 | } | ||
| 232 | co_return std::move(prersp); | ||
| 233 | } | ||
| 234 | |||
| 235 | struct keep_alive | ||
| 236 | { | ||
| 237 | bool value; | ||
| 238 | |||
| 239 | explicit keep_alive(bool value); | ||
| 240 | }; | ||
| 241 | |||
| 242 | template <bhttp::concepts::body Body> | ||
| 243 | auto make_rsp(bhttp::status status, keep_alive ka) -> bhttp::response<Body> | ||
| 244 | { | ||
| 245 | auto rsp = bhttp::response<Body>{}; // HTTP version gets set later | ||
| 246 | rsp.result(status); | ||
| 247 | rsp.keep_alive(ka.value); | ||
| 248 | return rsp; | ||
| 249 | } | ||
| 250 | |||
| 251 | auto problem_rsp( | ||
| 252 | base_ctx const& ctx, problem::details const& problem, keep_alive ka) | ||
| 253 | -> presponse; | ||
| 254 | |||
| 255 | struct preflight_response | ||
| 256 | { | ||
| 257 | verb_set allow_methods; | ||
| 258 | std::vector<bhttp::field> allow_headers; | ||
| 259 | }; | ||
| 260 | |||
| 261 | auto make_preflight_rsp(preflight_response res, keep_alive ka) | ||
| 262 | -> bhttp::response<bhttp::empty_body>; | ||
| 263 | |||
| 264 | // Using base_ctx instead of a template here since that saves you | ||
| 265 | // typing on invocation (and we do not care about the context type | ||
| 266 | // anyway, but all context types should derive from base_ctx). | ||
| 267 | template <bhttp::concepts::body_reader Body, typename... Args> | ||
| 268 | auto read_request(base_ctx const& ctx, readable_request&& r, Args&&... args) | ||
| 269 | -> net::awaitable<bhttp::request<Body>> | ||
| 270 | { | ||
| 271 | std::ignore = ctx; | ||
| 272 | auto p = | ||
| 273 | bhttp::request_parser<Body>{std::move(*r.p), std::forward<Args>(args)...}; | ||
| 274 | co_await bhttp::async_read(*r.strm, *r.buf, p); | ||
| 275 | co_return std::move(p.release()); | ||
| 276 | } | ||
| 277 | |||
| 278 | auto read_empty_request(base_ctx const& ctx, readable_request&& r) -> net:: | ||
| 279 | awaitable<std::expected<bhttp::request<bhttp::empty_body>, presponse>> | ||
| 280 | { | ||
| 281 | auto [ec, _] = | ||
| 282 | co_await bhttp::async_read(*r.strm, *r.buf, *r.p, net::as_tuple); | ||
| 283 | if (ec == bhttp::error::unexpected_body) | ||
| 284 | { | ||
| 285 | auto tpl = problem::tpl{ | ||
| 286 | .status = bhttp::status::bad_request, | ||
| 287 | .title = translate("No body expected for this request"), | ||
| 288 | .type_uri = "https://routemon.fautchen.eu/problems/unexpected-body", | ||
| 289 | }; | ||
| 290 | co_return std::unexpected{problem_rsp( | ||
| 291 | ctx, tpl.instantiate(), keep_alive{false})}; | ||
| 292 | } | ||
| 293 | else if (ec) | ||
| 294 | { | ||
| 295 | throw boost::system::system_error{ec}; | ||
| 296 | } | ||
| 297 | co_return r.p->release(); | ||
| 298 | } | ||
| 299 | |||
| 300 | template <class InnerCtx> | ||
| 301 | struct routed_ctx : InnerCtx | ||
| 302 | { | ||
| 303 | verb_set route_methods; | ||
| 304 | boost::urls::url target; | ||
| 305 | }; | ||
| 306 | |||
| 307 | template <class Ctx> | ||
| 308 | requires requires(Ctx ctx) { | ||
| 309 | // Ctx must be derived from an instantiation of routed_ctx | ||
| 310 | []<class InnerCtx>(routed_ctx<InnerCtx> const&) {}(ctx); | ||
| 311 | } | ||
| 312 | auto default_options_handler( | ||
| 313 | Ctx const& ctx, readable_request r, std::vector<std::string> const&) | ||
| 314 | -> net::awaitable<presponse> | ||
| 315 | { | ||
| 316 | auto mreq = co_await read_empty_request(ctx, std::move(r)); | ||
| 317 | if (!mreq) | ||
| 318 | co_return std::move(mreq.error()); | ||
| 319 | |||
| 320 | if (mreq->find(bhttp::field::access_control_request_method) != mreq->end()) | ||
| 321 | { | ||
| 322 | // CORS preflight request | ||
| 323 | co_return make_preflight_rsp( | ||
| 324 | preflight_response{ | ||
| 325 | // TODO: should access-control-allow-methods contain OPTIONS? | ||
| 326 | .allow_methods = ctx.route_methods, | ||
| 327 | .allow_headers = | ||
| 328 | {bhttp::field::content_type, bhttp::field::content_encoding}, | ||
| 329 | }, | ||
| 330 | keep_alive{mreq->keep_alive()}); | ||
| 331 | } | ||
| 332 | else | ||
| 333 | { | ||
| 334 | // Normal OPTIONS request | ||
| 335 | auto rsp = make_rsp<bhttp::empty_body>( | ||
| 336 | bhttp::status::no_content, keep_alive{mreq->keep_alive()}); | ||
| 337 | rsp.set(bhttp::field::allow, ctx.route_methods.to_string()); | ||
| 338 | rsp.prepare_payload(); | ||
| 339 | co_return std::move(rsp); | ||
| 340 | } | ||
| 341 | } | ||
| 342 | |||
| 343 | auto global_options_handler(base_ctx const& ctx, readable_request r) | ||
| 344 | -> net::awaitable<presponse>; | ||
| 345 | |||
| 346 | template <class A, class B, class C> | ||
| 347 | auto middleware_compose(middleware_t<A, B> ab, middleware_t<B, C> bc) | ||
| 348 | -> middleware_t<A, C> | ||
| 349 | { | ||
| 350 | return [ab = std::move(ab), bc = std::move(bc)]( | ||
| 351 | A a, bhttp::request_header<bhttp::fields>& header, | ||
| 352 | next_handler_t<C> next) -> net::awaitable<presponse> | ||
| 353 | { | ||
| 354 | co_return co_await ab( | ||
| 355 | std::move(a), header, [&](B b) -> net::awaitable<presponse> | ||
| 356 | { co_return co_await bc(std::move(b), header, next); }); | ||
| 357 | }; | ||
| 358 | } | ||
| 359 | |||
| 360 | template <class A, class B> | ||
| 361 | auto middleware_wrap_fn(middleware_t<A, B> ab, basic_route_handler_fn_t<B> fn) | ||
| 362 | -> basic_route_handler_fn_t<A> | ||
| 363 | { | ||
| 364 | return | ||
| 365 | [ab = std::move(ab), fn = std::move(fn)]( | ||
| 366 | A a_ctx, readable_request r, | ||
| 367 | std::vector<std::string> const& matches) -> net::awaitable<presponse> | ||
| 368 | { | ||
| 369 | co_return co_await ab( | ||
| 370 | std::move(a_ctx), r.p->get().base(), | ||
| 371 | [&](B b_ctx) -> net::awaitable<presponse> | ||
| 372 | { co_return co_await fn(std::move(b_ctx), r, matches); }); | ||
| 373 | }; | ||
| 374 | } | ||
| 375 | |||
| 376 | template <std::default_initializable V> | ||
| 377 | requires requires(V v) { | ||
| 378 | { static_cast<bool>(v) }; | ||
| 379 | } | ||
| 380 | struct handler_map | ||
| 381 | { | ||
| 382 | V options = {}; | ||
| 383 | V delete_ = {}; | ||
| 384 | V get = {}; | ||
| 385 | V head = {}; | ||
| 386 | V post = {}; | ||
| 387 | V put = {}; | ||
| 388 | |||
| 389 | template <class Self> | ||
| 390 | auto lookup(this Self&& self, supported_verb v) -> auto&& | ||
| 391 | { | ||
| 392 | switch (v.value) | ||
| 393 | { | ||
| 394 | case supported_verb::options: | ||
| 395 | return std::forward<Self>(self).options; | ||
| 396 | case supported_verb::delete_: | ||
| 397 | return std::forward<Self>(self).delete_; | ||
| 398 | case supported_verb::get: | ||
| 399 | return std::forward<Self>(self).get; | ||
| 400 | case supported_verb::head: | ||
| 401 | return std::forward<Self>(self).head; | ||
| 402 | case supported_verb::post: | ||
| 403 | return std::forward<Self>(self).post; | ||
| 404 | case supported_verb::put: | ||
| 405 | return std::forward<Self>(self).put; | ||
| 406 | } | ||
| 407 | } | ||
| 408 | |||
| 409 | auto verbs() const -> verb_set | ||
| 410 | { | ||
| 411 | return verb_set{ | ||
| 412 | .options = static_cast<bool>(options), | ||
| 413 | .delete_ = static_cast<bool>(delete_), | ||
| 414 | .get = static_cast<bool>(get), | ||
| 415 | .head = static_cast<bool>(head), | ||
| 416 | .post = static_cast<bool>(post), | ||
| 417 | .put = static_cast<bool>(put), | ||
| 418 | }; | ||
| 419 | } | ||
| 420 | |||
| 421 | auto empty() const -> bool { return verbs().empty(); } | ||
| 422 | |||
| 423 | template <std::default_initializable U> | ||
| 424 | auto map(std::invocable<V const&> auto f) const -> handler_map<U> | ||
| 425 | requires std:: | ||
| 426 | assignable_from<U&, std::invoke_result_t<decltype(f), V const&>> | ||
| 427 | { | ||
| 428 | return { | ||
| 429 | .options = static_cast<bool>(options) ? f(options) : U{}, | ||
| 430 | .delete_ = static_cast<bool>(delete_) ? f(delete_) : U{}, | ||
| 431 | .get = static_cast<bool>(get) ? f(get) : U{}, | ||
| 432 | .head = static_cast<bool>(head) ? f(head) : U{}, | ||
| 433 | .post = static_cast<bool>(post) ? f(post) : U{}, | ||
| 434 | .put = static_cast<bool>(put) ? f(put) : U{}, | ||
| 435 | }; | ||
| 436 | } | ||
| 437 | }; | ||
| 438 | |||
| 439 | template <class Ctx> | ||
| 440 | struct route_tree | ||
| 441 | { | ||
| 442 | using leaves = handler_map<basic_route_handler_fn_t<Ctx>>; | ||
| 443 | using named_subtrees = std::unordered_map<std::string, route_tree>; | ||
| 444 | using wildcard_subtree = std::indirect<route_tree>; | ||
| 445 | |||
| 446 | leaves here; | ||
| 447 | // TODO: consider making the first alternative a radix tree | ||
| 448 | // Note: the map is the first variant here; the variant will be | ||
| 449 | // default-constructed with the default-constructed first | ||
| 450 | // alternative. The empty map denotes a lack of subtrees. | ||
| 451 | std::variant<named_subtrees, wildcard_subtree> sub; | ||
| 452 | }; | ||
| 453 | |||
| 454 | template <class OuterCtx, class InnerCtx> | ||
| 455 | auto middleware_wrap_tree( | ||
| 456 | middleware_t<OuterCtx, InnerCtx> mw, route_tree<InnerCtx> const& tree) | ||
| 457 | -> route_tree<OuterCtx> | ||
| 458 | { | ||
| 459 | auto new_leaves = tree.here.template map<basic_route_handler_fn_t<OuterCtx>>( | ||
| 460 | std::bind_front(middleware_wrap_fn<OuterCtx, InnerCtx>, mw)); | ||
| 461 | auto new_sub = tree.sub.visit( | ||
| 462 | util::overloaded{ | ||
| 463 | [&mw](route_tree<InnerCtx>::named_subtrees const& subtrees) | ||
| 464 | -> decltype(route_tree<OuterCtx>::sub) | ||
| 465 | { | ||
| 466 | auto new_subtrees = typename route_tree<OuterCtx>::named_subtrees{}; | ||
| 467 | for (auto [seg, subtree] : subtrees) | ||
| 468 | new_subtrees[seg] = middleware_wrap_tree(mw, subtree); | ||
| 469 | return new_subtrees; | ||
| 470 | }, | ||
| 471 | [&mw](route_tree<InnerCtx>::wildcard_subtree const& subtree) | ||
| 472 | -> decltype(route_tree<OuterCtx>::sub) | ||
| 473 | { | ||
| 474 | return typename route_tree<OuterCtx>::wildcard_subtree{ | ||
| 475 | middleware_wrap_tree(mw, *subtree) | ||
| 476 | }; | ||
| 477 | }, | ||
| 478 | }); | ||
| 479 | return {.here = new_leaves, .sub = new_sub}; | ||
| 480 | } | ||
| 481 | |||
| 482 | template <class T> | ||
| 483 | concept match_arg = std::constructible_from<T, std::string const&>; | ||
| 484 | |||
| 485 | template <class Ctx, match_arg... MatchArgs> | ||
| 486 | using route_handler_fn_t = | ||
| 487 | std::function<auto(Ctx, readable_request, MatchArgs...) | ||
| 488 | ->net::awaitable<presponse>>; | ||
| 489 | |||
| 490 | template <class Ctx, match_arg... MatchArgs> | ||
| 491 | auto degen_route_handler(route_handler_fn_t<Ctx, MatchArgs...> fn) | ||
| 492 | -> basic_route_handler_fn_t<Ctx> | ||
| 493 | { | ||
| 494 | return | ||
| 495 | [fn = std::move(fn)]( | ||
| 496 | Ctx ctx, readable_request r, | ||
| 497 | std::vector<std::string> const& matches) -> net::awaitable<presponse> | ||
| 498 | { | ||
| 499 | if (sizeof...(MatchArgs) != matches.size()) | ||
| 500 | throw std::runtime_error{"got unexpected amount of matches"}; | ||
| 501 | auto it = matches.begin(); | ||
| 502 | co_return co_await fn( | ||
| 503 | std::move(ctx), r, | ||
| 504 | MatchArgs{static_cast<std::string const&>(*it++)}...); | ||
| 505 | }; | ||
| 506 | } | ||
| 507 | |||
| 508 | template <class Ctx, match_arg... MatchArgs> | ||
| 509 | struct ctree : route_tree<Ctx> | ||
| 510 | { | ||
| 511 | template <class OuterCtx> | ||
| 512 | auto wrap(middleware_t<OuterCtx, Ctx> mw) const | ||
| 513 | -> ctree<OuterCtx, MatchArgs...> | ||
| 514 | { | ||
| 515 | return {middleware_wrap_tree(std::move(mw), *this)}; | ||
| 516 | } | ||
| 517 | }; | ||
| 518 | |||
| 519 | template <class Ctx, match_arg... MatchArgs> | ||
| 520 | struct dtree : handler_map<route_handler_fn_t<Ctx, MatchArgs...>> | ||
| 521 | { | ||
| 522 | [[nodiscard]] auto to_leaves() const -> typename route_tree<Ctx>::leaves | ||
| 523 | { | ||
| 524 | auto here = this->template map<basic_route_handler_fn_t<Ctx>>( | ||
| 525 | degen_route_handler<Ctx, MatchArgs...>); | ||
| 526 | if (!here.verbs().empty() && !static_cast<bool>(this->options)) | ||
| 527 | here.options = default_options_handler<Ctx>; | ||
| 528 | return here; | ||
| 529 | } | ||
| 530 | |||
| 531 | [[nodiscard]] auto named_subtrees( | ||
| 532 | std::initializer_list<std::pair<std::string, ctree<Ctx, MatchArgs...>>> | ||
| 533 | subtrees) const -> ctree<Ctx, MatchArgs...> | ||
| 534 | { | ||
| 535 | auto sub = typename route_tree<Ctx>::named_subtrees{ | ||
| 536 | std::from_range, subtrees | ||
| 537 | | std::views::transform( | ||
| 538 | [](auto const& p) | ||
| 539 | { | ||
| 540 | return std::make_pair( | ||
| 541 | p.first, | ||
| 542 | static_cast<route_tree<Ctx>>(p.second)); | ||
| 543 | }) | ||
| 544 | }; | ||
| 545 | return {route_tree<Ctx>{.here = to_leaves(), .sub = sub}}; | ||
| 546 | } | ||
| 547 | |||
| 548 | template <match_arg MatchArg> | ||
| 549 | [[nodiscard]] auto | ||
| 550 | wildcard_subtree(ctree<Ctx, MatchArgs..., MatchArg> subtree) | ||
| 551 | -> ctree<Ctx, MatchArgs...> | ||
| 552 | { | ||
| 553 | return {route_tree<Ctx>{ | ||
| 554 | .here = to_leaves(), | ||
| 555 | .sub = typename route_tree<Ctx>::wildcard_subtree{ | ||
| 556 | static_cast<route_tree<Ctx>>(subtree) | ||
| 557 | } | ||
| 558 | }}; | ||
| 559 | } | ||
| 560 | |||
| 561 | [[nodiscard]] auto no_subtrees() const -> ctree<Ctx, MatchArgs...> | ||
| 562 | { | ||
| 563 | return {route_tree<Ctx>{.here = to_leaves(), .sub = {}}}; | ||
| 564 | } | ||
| 565 | }; | ||
| 566 | |||
| 567 | class router | ||
| 568 | { | ||
| 569 | struct impl_base | ||
| 570 | { | ||
| 571 | virtual ~impl_base() = default; | ||
| 572 | virtual auto handle_request(trace::id trace_id, readable_request r) const | ||
| 573 | -> net::awaitable<presponse> = 0; | ||
| 574 | }; | ||
| 575 | |||
| 576 | std::unique_ptr<impl_base> impl_; | ||
| 577 | |||
| 578 | template <std::derived_from<base_ctx> PreRouteCtx> | ||
| 579 | class impl : public impl_base | ||
| 580 | { | ||
| 581 | log::logger l_; | ||
| 582 | locale::selector lsel_; | ||
| 583 | middleware_t<base_ctx, PreRouteCtx> global_middleware_; | ||
| 584 | route_tree<routed_ctx<PreRouteCtx>> routes_; | ||
| 585 | |||
| 586 | public: | ||
| 587 | explicit impl( | ||
| 588 | log::logger const& l, locale::selector&& lsel, | ||
| 589 | middleware_t<base_ctx, PreRouteCtx> global_middleware, | ||
| 590 | route_tree<routed_ctx<PreRouteCtx>> routes) | ||
| 591 | : l_{l.sub("router")}, lsel_{std::move(lsel)}, | ||
| 592 | global_middleware_{std::move(global_middleware)}, | ||
| 593 | routes_{std::move(routes)} | ||
| 594 | { | ||
| 595 | } | ||
| 596 | |||
| 597 | struct match_result | ||
| 598 | { | ||
| 599 | util::not_null< | ||
| 600 | handler_map<basic_route_handler_fn_t<routed_ctx<PreRouteCtx>>> const* | ||
| 601 | > | ||
| 602 | route_handlers; | ||
| 603 | std::vector<std::string> wildcard_matches; | ||
| 604 | |||
| 605 | auto allowed_methods() const -> verb_set | ||
| 606 | { | ||
| 607 | return route_handlers->verbs(); | ||
| 608 | } | ||
| 609 | }; | ||
| 610 | |||
| 611 | auto match(boost::urls::segments_view segments) const | ||
| 612 | -> std::optional<match_result> | ||
| 613 | { | ||
| 614 | auto const* tree = &routes_; | ||
| 615 | auto wildcard_matches = std::vector<std::string>{}; | ||
| 616 | for (auto const& seg : segments) | ||
| 617 | { | ||
| 618 | tree->sub.visit( | ||
| 619 | util::overloaded{ | ||
| 620 | [&](route_tree<routed_ctx<PreRouteCtx>>::named_subtrees const& | ||
| 621 | subtrees) | ||
| 622 | { | ||
| 623 | auto it = subtrees.find(seg); | ||
| 624 | tree = it == subtrees.end() ? nullptr : &it->second; | ||
| 625 | }, | ||
| 626 | [&](route_tree<routed_ctx<PreRouteCtx>>::wildcard_subtree const& | ||
| 627 | wildcard_subtree) | ||
| 628 | { | ||
| 629 | wildcard_matches.push_back(seg); | ||
| 630 | tree = &*wildcard_subtree; | ||
| 631 | }, | ||
| 632 | }); | ||
| 633 | if (!tree) | ||
| 634 | return std::nullopt; | ||
| 635 | } | ||
| 636 | if (tree->here.empty()) | ||
| 637 | return std::nullopt; | ||
| 638 | return match_result{ | ||
| 639 | .route_handlers = util::not_null{&tree->here}, | ||
| 640 | .wildcard_matches = wildcard_matches, | ||
| 641 | }; | ||
| 642 | } | ||
| 643 | |||
| 644 | auto route_request(PreRouteCtx ctx, readable_request r) const | ||
| 645 | -> net::awaitable<presponse> | ||
| 646 | { | ||
| 647 | auto req_base = r.p->get().base(); | ||
| 648 | |||
| 649 | auto const bad_request_tpl = problem::tpl{ | ||
| 650 | .status = bhttp::status::bad_request, | ||
| 651 | .title = translate("Bad request"), | ||
| 652 | .type_uri = "https://routemon.fautchen.eu/problems/bad-request", | ||
| 653 | }; | ||
| 654 | |||
| 655 | if (req_base.target() == "*") | ||
| 656 | { | ||
| 657 | // request-target is in asterisk-form (RFC 9112, § 3.2.4), | ||
| 658 | // so the request must be a server-wide OPTIONS request. | ||
| 659 | |||
| 660 | if (req_base.method() != bhttp::verb::options) | ||
| 661 | { | ||
| 662 | auto tpl = problem::tpl{ | ||
| 663 | .status = bhttp::status::method_not_allowed, | ||
| 664 | .title = translate("Method not allowed"), | ||
| 665 | .type_uri = "https://routemon.fautchen.eu/problems/" | ||
| 666 | "method-not-allowed", | ||
| 667 | }; | ||
| 668 | co_return problem_rsp(ctx, tpl.instantiate(), keep_alive{false}); | ||
| 669 | } | ||
| 670 | |||
| 671 | co_return co_await global_options_handler(ctx, r); | ||
| 672 | } | ||
| 673 | else if (auto mreq_url0 = | ||
| 674 | boost::urls::parse_origin_form(req_base.target())) | ||
| 675 | { | ||
| 676 | // request-target is in origin-form (RFC 9112, § 3.2.1), | ||
| 677 | // so it must be a normal request (not a CONNECT or | ||
| 678 | // server-wide OPTIONS request). | ||
| 679 | |||
| 680 | auto req_url = boost::urls::url{*mreq_url0}; | ||
| 681 | req_url.normalize(); | ||
| 682 | if (!req_url.is_path_absolute()) | ||
| 683 | { | ||
| 684 | auto problem = bad_request_tpl.instantiate().set_detail(translate( | ||
| 685 | "Path of normalized (RFC 3986, § 6) " | ||
| 686 | "origin-form request-target (RFC " | ||
| 687 | "9112, § 3.2.1) should be " | ||
| 688 | "absolute")); | ||
| 689 | co_return problem_rsp(ctx, problem, keep_alive{false}); | ||
| 690 | } | ||
| 691 | |||
| 692 | // l_.with( | ||
| 693 | // "trace_id", | ||
| 694 | // static_cast<base_ctx const&>(ctx).trace_id.as_string()) | ||
| 695 | // .debug( | ||
| 696 | // "Request targets {} {}", req_base.method_string(), | ||
| 697 | // req_url.path()); | ||
| 698 | |||
| 699 | auto mres = match(req_url.segments()); | ||
| 700 | if (!mres) | ||
| 701 | { | ||
| 702 | auto tpl = problem::tpl{ | ||
| 703 | .status = bhttp::status::not_found, | ||
| 704 | .title = translate("Not found"), | ||
| 705 | .type_uri = "https://routemon.fautchen.eu/problems/not-found", | ||
| 706 | }; | ||
| 707 | co_return problem_rsp(ctx, tpl.instantiate(), keep_alive{false}); | ||
| 708 | } | ||
| 709 | |||
| 710 | auto mverb = supported_verb::from(req_base.method()); | ||
| 711 | if (!mverb) | ||
| 712 | { | ||
| 713 | // Method not implemented. | ||
| 714 | auto tpl = problem::tpl{ | ||
| 715 | .status = bhttp::status::not_implemented, | ||
| 716 | .title = translate("Method not implemented"), | ||
| 717 | .type_uri = "https://routemon.fautchen.eu/problems/" | ||
| 718 | "method-not-implemented", | ||
| 719 | }; | ||
| 720 | co_return problem_rsp(ctx, tpl.instantiate(), keep_alive{false}); | ||
| 721 | } | ||
| 722 | |||
| 723 | if (auto mhdl = mres->route_handlers->lookup(*mverb)) | ||
| 724 | { | ||
| 725 | auto new_ctx = routed_ctx<PreRouteCtx>{ | ||
| 726 | std::move(ctx), mres->allowed_methods(), std::move(req_url) | ||
| 727 | }; | ||
| 728 | co_return co_await mhdl( | ||
| 729 | std::move(new_ctx), r, mres->wildcard_matches); | ||
| 730 | } | ||
| 731 | else | ||
| 732 | { | ||
| 733 | // Path recognized, but method not allowed. | ||
| 734 | auto tpl = problem::tpl{ | ||
| 735 | .status = bhttp::status::method_not_allowed, | ||
| 736 | .title = translate("Method not allowed"), | ||
| 737 | .type_uri = "https://routemon.fautchen.eu/problems/" | ||
| 738 | "method-not-allowed", | ||
| 739 | }; | ||
| 740 | auto rsp = problem_rsp(ctx, tpl.instantiate(), keep_alive{false}); | ||
| 741 | rsp.header().set( | ||
| 742 | bhttp::field::allow, mres->allowed_methods().to_string()); | ||
| 743 | co_return std::move(rsp); | ||
| 744 | } | ||
| 745 | } | ||
| 746 | else | ||
| 747 | { | ||
| 748 | // We do not accept any other request-target forms. | ||
| 749 | |||
| 750 | auto problem = bad_request_tpl.instantiate().set_detail(translate( | ||
| 751 | "Invalid request-target, expected " | ||
| 752 | "asterisk-form or origin-form " | ||
| 753 | "(see RFC 9112, § 3.2)")); | ||
| 754 | co_return problem_rsp(ctx, problem, keep_alive{false}); | ||
| 755 | } | ||
| 756 | } | ||
| 757 | |||
| 758 | auto handle_request(trace::id trace_id, readable_request r) const | ||
| 759 | -> net::awaitable<presponse> override | ||
| 760 | { | ||
| 761 | auto header = r.p->get().base(); | ||
| 762 | auto locale = lsel_.select(header[bhttp::field::accept_language]); | ||
| 763 | co_return co_await global_middleware_( | ||
| 764 | base_ctx{.locale = locale, .trace_id = trace_id}, header, | ||
| 765 | [&](PreRouteCtx ctx) -> net::awaitable<presponse> | ||
| 766 | { co_return co_await route_request(std::move(ctx), std::move(r)); }); | ||
| 767 | } | ||
| 768 | }; | ||
| 769 | |||
| 770 | public: | ||
| 771 | template <std::derived_from<base_ctx> PreRouteCtx> | ||
| 772 | explicit router( | ||
| 773 | log::logger const& l, locale::selector&& lsel, | ||
| 774 | middleware_t<base_ctx, PreRouteCtx> global_middleware, | ||
| 775 | route_tree<routed_ctx<PreRouteCtx>> routes) | ||
| 776 | : impl_{std::make_unique<impl<PreRouteCtx>>( | ||
| 777 | l, std::move(lsel), std::move(global_middleware), std::move(routes))} | ||
| 778 | { | ||
| 779 | } | ||
| 780 | |||
| 781 | auto handle_request(trace::id trace_id, readable_request r) const | ||
| 782 | -> net::awaitable<presponse>; | ||
| 783 | }; | ||
| 784 | |||
| 785 | class server | ||
| 786 | { | ||
| 787 | log::logger l_; | ||
| 788 | router r_; | ||
| 789 | |||
| 790 | auto do_session(beast::tcp_stream strm) -> net::awaitable<void>; | ||
| 791 | auto do_listen(tcp::endpoint endpoint) -> net::awaitable<void>; | ||
| 792 | |||
| 793 | public: | ||
| 794 | explicit server(log::logger const& l, router&& r); | ||
| 795 | |||
| 796 | auto spawn(net::io_context& ioc) -> void; | ||
| 797 | }; | ||
| 798 | |||
| 799 | } // namespace routemon::http::core | ||