summaryrefslogtreecommitdiffstats
path: root/server/src/http_server.cpp
blob: c3a9ed7f516a18e3960dadabca857713cfb7cade (about) (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
module;

#include <boost/asio/as_tuple.hpp>
#include <boost/asio/awaitable.hpp>
#include <boost/asio/co_spawn.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/config.hpp>
#include <boost/json/serialize.hpp>
#include <boost/url.hpp>

module routemon:http.server$impl;

import :http.server;
import :trace;

namespace chrono = std::chrono;

namespace routemon::http {

auto presponse::header() -> bhttp::response_header<bhttp::fields>&
{
  return impl_->header();
}

auto presponse::header() const -> bhttp::response_header<bhttp::fields> const&
{
  return impl_->header();
}

auto presponse::is_done() const -> bool { return impl_->is_done(); }

auto presponse::prepare(beast::error_code& ec) -> const_buffers_type
{
  return impl_->prepare(ec);
}

auto presponse::consume(std::size_t n) -> void { return impl_->consume(n); }

auto presponse::keep_alive() const noexcept -> bool
{
  return impl_->keep_alive();
}

keep_alive::keep_alive(bool value) : value{value} {}

auto problem_rsp(
    base_ctx const& ctx, problem::details const& problem, keep_alive ka)
    -> presponse
{
  auto rsp = make_rsp<bhttp::string_body>(problem.status, ka);
  rsp.set(bhttp::field::content_type, "application/problem+json");
  rsp.body() = json::serialize(json::value_from(problem, ctx.locale));
  rsp.prepare_payload();
  return presponse{std::move(rsp)};
}

auto make_preflight_rsp(preflight_response res, keep_alive ka)
    -> bhttp::response<bhttp::empty_body>
{
  auto rsp = make_rsp<bhttp::empty_body>(bhttp::status::no_content, ka);
  auto allow_headers_str = res.allow_headers
                           | std::views::transform(
                               [](auto const& field) -> std::string_view
                               { return bhttp::to_string(field); })
                           | std::views::join_with(std::string_view{", "})
                           | std::ranges::to<std::string>();
  rsp.set(
      bhttp::field::access_control_allow_methods,
      res.allow_methods.to_string());
  rsp.set(bhttp::field::access_control_allow_headers, allow_headers_str);
  rsp.prepare_payload();
  return rsp;
}

auto global_options_handler(base_ctx const& ctx, readable_request r)
    -> net::awaitable<presponse>
{
  // TODO: switch to "small (4KB) discarded" body type, similar to what Go
  // does? Same goes for default_options_handler? Not sure.
  if (auto res = co_await read_request<bhttp::empty_body>(ctx, std::move(r));
      !res)
    co_return std::move(res.error());
  auto req = r.p->release();
  auto rsp = make_rsp<bhttp::empty_body>(
      bhttp::status::no_content, keep_alive{req.keep_alive()});
  rsp.prepare_payload();
  co_return std::move(rsp);
}

auto router::handle_request(trace::id trace_id, readable_request r) const
    -> net::awaitable<presponse>
{
  return impl_->handle_request(trace_id, r);
}

server::server(log::logger const& l, router&& r)
  : l_{l.sub("http_server")}, r_{std::move(r)}
{
}

auto server::do_session(beast::tcp_stream strm) -> net::awaitable<void>
{
  auto buf = beast::flat_buffer{};

  while (true)
  {
    auto p0 = bhttp::request_parser<bhttp::empty_body>{};
    p0.body_limit(boost::none);
    auto [ec, _] =
        co_await bhttp::async_read_header(strm, buf, p0, net::as_tuple);
    if (ec == bhttp::error::end_of_stream)
      break;
    else if (ec)
      throw boost::system::system_error{ec};

    auto trace_id = trace::id{};
    auto l = l_.sub("do_session").with("trace_id", trace_id.as_string());
    l.debug("Read header, invoking request handler");
    auto const before_hdl = chrono::steady_clock::now();

    auto http_version = p0.get().version();
    auto&& rsp = co_await r_.handle_request(
        trace_id, readable_request{
                    .p = util::not_null{&p0},
                    .strm = util::not_null{&strm},
                    .buf = util::not_null{&buf},
                  });

    l.debug(
        "Request handler returned after {}, writing response",
        chrono::duration<double, std::milli>{
          chrono::steady_clock::now() - before_hdl
        });
    auto before_write_rsp = chrono::steady_clock::now();

    rsp.header().version(http_version);
    bool keep_alive = rsp.keep_alive();
    co_await beast::async_write(strm, std::move(rsp));

    l.debug(
        "Wrote response in {}", chrono::duration<double, std::milli>{
                                  chrono::steady_clock::now() - before_write_rsp
                                });

    if (!keep_alive)
    {
      break;
    }
  }

  strm.socket().shutdown(tcp::socket::shutdown_send);
}

auto server::do_listen(tcp::endpoint endpoint) -> net::awaitable<void>
{
  auto executor = co_await net::this_coro::executor;
  auto acceptor = tcp::acceptor{executor, endpoint};

  l_.with("endpoint", endpoint.address().to_string())
      .with("port", std::to_string(endpoint.port()))
      .info("Serving");
  while (true)
  {
    net::co_spawn(
        executor,
        do_session(beast::tcp_stream{co_await acceptor.async_accept()}),
        [this](std::exception_ptr e)
        {
          if (e)
          {
            try
            {
              std::rethrow_exception(e);
            }
            catch (std::exception const& e)
            {
              l_.error("Error in session: {}", e.what());
            }
          }
        });
  }
}

auto server::spawn(net::io_context& ioc) -> void
{
  auto const addr = net::ip::make_address("0.0.0.0");
  auto const endpoint = tcp::endpoint{addr, 8284};

  // TODO: make exception handling as nice as in srv.cpp
  net::co_spawn(
      ioc, do_listen(endpoint),
      [this](std::exception_ptr e)
      {
        if (e)
        {
          try
          {
            std::rethrow_exception(e);
          }
          catch (std::exception const& e)
          {
            l_.error("Error: {}", e.what());
          }
        }
      });
}

} // namespace routemon::http