summaryrefslogtreecommitdiffstats
path: root/server/src/http_server.cppm
blob: 12c83dbf7bb64672fc70616ce998a0872a3cb450 (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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
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>

export module routemon:http.server;

import std;
import :config;
import :trace;
import :http.common;
import :problem;

namespace net = boost::asio;
using tcp = net::ip::tcp;

namespace routemon::http {

struct readable_request
{
  util::not_null<bhttp::request_parser<bhttp::empty_body>*> p;
  util::not_null<beast::tcp_stream*> strm;
  util::not_null<beast::flat_buffer*> buf;
};

class presponse
{
public:
  using const_buffers_type = beast::span<net::const_buffer>;

private:
  struct impl_base
  {
    virtual ~impl_base() = default;
    virtual auto header() -> bhttp::response_header<bhttp::fields>& = 0;
    virtual auto header() const
        -> bhttp::response_header<bhttp::fields> const& = 0;
    virtual auto is_done() const -> bool = 0;
    virtual auto prepare(beast::error_code&) -> const_buffers_type = 0;
    virtual auto consume(std::size_t n) -> void = 0;
    virtual auto keep_alive() const -> bool = 0;
  };
  std::unique_ptr<impl_base> impl_;

  template <bhttp::concepts::body Body>
  class impl : public impl_base
  {
    // Initializes in the response state.
    // At the first call to prepare, we switch to the message generator
    // state. After that point, header may not be called anymore (it will
    // throw).
    std::variant<bhttp::response<Body>, bhttp::message_generator> state_;

    auto ensure_message_generator() -> bhttp::message_generator&
    {
      if (auto prsp = std::get_if<bhttp::response<Body>>(&state_))
      {
        auto rsp = bhttp::response<Body>{std::move(*prsp)};
        state_.template emplace<bhttp::message_generator>(std::move(rsp));
      }
      return std::get<bhttp::message_generator>(state_);
    }

  public:
    explicit impl(bhttp::response<Body>&& rsp) : state_{std::move(rsp)} {}

    auto header() -> bhttp::response_header<bhttp::fields>& override
    {
      if (auto prsp = std::get_if<bhttp::response<Body>>(&state_))
      {
        return prsp->base();
      }
      else
      {
        // TODO: define custom exception type
        // presponse::bad_header_access
        throw std::logic_error{"header() may not be called after prepare()"};
      }
    }
    auto header() const -> bhttp::response_header<bhttp::fields> const& override
    {
      if (auto prsp = std::get_if<bhttp::response<Body>>(&state_))
      {
        return prsp->base();
      }
      else
      {
        throw std::logic_error{"header() may not be called after prepare()"};
      }
    }

    auto is_done() const -> bool override
    {
      if (auto pgen = std::get_if<bhttp::message_generator>(&state_))
      {
        return pgen->is_done();
      }
      else /* still in the response state */
      {
        return false;
      }
    }

    auto prepare(beast::error_code& ec) -> const_buffers_type override
    {
      return ensure_message_generator().prepare(ec);
    }

    auto consume(std::size_t n) -> void override
    {
      ensure_message_generator().consume(n);
    }

    auto keep_alive() const noexcept -> bool override
    {
      return state_.visit(
          util::overloaded{
            [](bhttp::response<Body> const& rsp) -> bool
            { return rsp.keep_alive(); },
            [](bhttp::message_generator const& gen) -> bool
            { return gen.keep_alive(); },
          });
    }
  };

public:
  template <bhttp::concepts::body Body>
  explicit presponse(bhttp::response<Body>&& rsp)
    : impl_{new impl{std::move(rsp)}}
  {
  }

  auto header() -> bhttp::response_header<bhttp::fields>&;
  auto header() const -> bhttp::response_header<bhttp::fields> const&;
  auto is_done() const -> bool;
  auto prepare(beast::error_code& ec) -> const_buffers_type;
  auto consume(std::size_t n) -> void;
  auto keep_alive() const noexcept -> bool;
};
static_assert(beast::concepts::buffers_generator<presponse>);

template <class Ctx>
using next_handler_t = std::function<auto(Ctx)->net::awaitable<presponse>>;

template <class OuterCtx, class InnerCtx>
using middleware_t =
    std::function<auto(
                      OuterCtx, bhttp::request_header<bhttp::fields>&,
                      next_handler_t<InnerCtx>)
                      ->net::awaitable<presponse>>;

template <class Ctx>
auto id_middleware(
    Ctx ctx, bhttp::request_header<bhttp::fields>&, next_handler_t<Ctx> next)
    -> net::awaitable<presponse>
{
  co_return co_await next(std::move(ctx));
}

struct base_ctx
{
  std::locale locale;
  trace::id trace_id;
};

template <class Ctx>
using basic_route_handler_fn_t =
    std::function<auto(
                      Ctx, readable_request,
                      std::vector<std::string> const& matches)
                      ->net::awaitable<presponse>>;

template <class Ctx>
auto cors_middleware(std::vector<std::string> const& allow_origins)
    -> middleware_t<Ctx, Ctx>
{
  if (allow_origins.empty())
    return id_middleware<Ctx>;

  auto header_str = allow_origins
                    | std::views::join_with(std::string_view{", "})
                    | std::ranges::to<std::string>();

  return [header_str = std::move(header_str)](
             Ctx ctx, bhttp::request_header<bhttp::fields>& req_hdr,
             next_handler_t<Ctx> next) -> net::awaitable<presponse>
  {
    std::ignore = req_hdr;
    auto prersp = co_await next(ctx);
    prersp.header().set(bhttp::field::access_control_allow_origin, header_str);
    co_return std::move(prersp);
  };
}

template <class Ctx>
auto trace_id_middleware(
    Ctx ctx, bhttp::request_header<bhttp::fields>& req_hdr,
    next_handler_t<Ctx> next) -> net::awaitable<presponse>
{
  std::ignore = req_hdr;
  auto prersp = co_await next(std::move(ctx));
  prersp.header().set(
      "X-Routemon-Trace-Id",
      std::string_view{static_cast<base_ctx const&>(ctx).trace_id.as_string()});
  prersp.header().insert(
      bhttp::field::access_control_expose_headers, "X-Routemon-Trace-Id");
  co_return std::move(prersp);
}

struct keep_alive
{
  bool value;

  explicit keep_alive(bool value);
};

template <bhttp::concepts::body Body>
auto make_rsp(bhttp::status status, keep_alive ka) -> bhttp::response<Body>
{
  auto rsp = bhttp::response<Body>{}; // HTTP version gets set later
  rsp.result(status);
  rsp.keep_alive(ka.value);
  return rsp;
}

auto problem_rsp(
    base_ctx const& ctx, problem::details const& problem, keep_alive ka)
    -> presponse;

struct preflight_response
{
  verb_set allow_methods;
  std::vector<bhttp::field> allow_headers;
};

auto make_preflight_rsp(preflight_response res, keep_alive ka)
    -> bhttp::response<bhttp::empty_body>;

// Using base_ctx instead of a template here since that saves you
// typing on invocation (and we do not care about the context type
// anyway, but all context types should derive from base_ctx).
template <bhttp::concepts::body_reader Body>
auto read_request(base_ctx const& ctx, readable_request&& r)
    -> net::awaitable<std::expected<bhttp::request<Body>, presponse>>
{
  std::ignore = ctx;
  auto p = bhttp::request_parser<Body>{std::move(*r.p)};
  co_await bhttp::async_read(*r.strm, *r.buf, p);
  co_return std::move(p.release());
}

template <>
auto read_request<bhttp::empty_body>(base_ctx const& ctx, readable_request&& r)
    -> net::
        awaitable<std::expected<bhttp::request<bhttp::empty_body>, presponse>>
{
  auto [ec, _] =
      co_await bhttp::async_read(*r.strm, *r.buf, *r.p, net::as_tuple);
  if (ec == bhttp::error::unexpected_body)
  {
    auto tpl = problem::tpl{
      .status = bhttp::status::bad_request,
      .title = translate("No body expected for this request"),
      .type_uri = "https://routemon.fautchen.eu/problems/unexpected-body",
    };
    co_return std::unexpected{problem_rsp(
        ctx, tpl.instantiate(), keep_alive{false})};
  }
  else if (ec)
  {
    throw boost::system::system_error{ec};
  }
  co_return r.p->release();
}

template <class InnerCtx>
struct routed_ctx : InnerCtx
{
  verb_set route_methods;
};

template <class Ctx>
  requires requires(Ctx ctx) {
    // Ctx must be derived from an instantiation of routed_ctx
    []<class InnerCtx>(routed_ctx<InnerCtx> const&) {}(ctx);
  }
auto default_options_handler(
    Ctx const& ctx, readable_request r, std::vector<std::string> const&)
    -> net::awaitable<presponse>
{
  auto mreq = co_await read_request<bhttp::empty_body>(ctx, std::move(r));
  if (!mreq)
    co_return std::move(mreq.error());

  if (mreq->find(bhttp::field::access_control_request_method) != mreq->end())
  {
    // CORS preflight request
    co_return make_preflight_rsp(
        preflight_response{
          // TODO: should access-control-allow-methods contain OPTIONS?
          .allow_methods = ctx.route_methods,
          .allow_headers = {bhttp::field::content_type},
        },
        keep_alive{mreq->keep_alive()});
  }
  else
  {
    // Normal OPTIONS request
    auto rsp = make_rsp<bhttp::empty_body>(
        bhttp::status::no_content, keep_alive{mreq->keep_alive()});
    rsp.set(bhttp::field::allow, ctx.route_methods.to_string());
    rsp.prepare_payload();
    co_return std::move(rsp);
  }
}

auto global_options_handler(base_ctx const& ctx, readable_request r)
    -> net::awaitable<presponse>;

template <class A, class B, class C>
auto middleware_compose(middleware_t<A, B> ab, middleware_t<B, C> bc)
    -> middleware_t<A, C>
{
  return [ab = std::move(ab), bc = std::move(bc)](
             A a, bhttp::request_header<bhttp::fields>& header,
             next_handler_t<C> next) -> net::awaitable<presponse>
  {
    co_return co_await ab(
        std::move(a), header, [&](B b) -> net::awaitable<presponse>
        { co_return co_await bc(std::move(b), header, next); });
  };
}

template <class A, class B>
auto middleware_wrap_fn(middleware_t<A, B> ab, basic_route_handler_fn_t<B> fn)
    -> basic_route_handler_fn_t<A>
{
  return
      [ab = std::move(ab), fn = std::move(fn)](
          A a_ctx, readable_request r,
          std::vector<std::string> const& matches) -> net::awaitable<presponse>
  {
    co_return co_await ab(
        std::move(a_ctx), r.p->get().base(),
        [&](B b_ctx) -> net::awaitable<presponse>
        { co_return co_await fn(std::move(b_ctx), r, matches); });
  };
}

template <std::default_initializable V>
  requires requires(V v) {
    { static_cast<bool>(v) };
  }
struct handler_map
{
  V options = {};
  V delete_ = {};
  V get = {};
  V head = {};
  V post = {};
  V put = {};

  template <class Self>
  auto lookup(this Self&& self, supported_verb v) -> auto&&
  {
    switch (v.value)
    {
    case supported_verb::options:
      return std::forward<Self>(self).options;
    case supported_verb::delete_:
      return std::forward<Self>(self).delete_;
    case supported_verb::get:
      return std::forward<Self>(self).get;
    case supported_verb::head:
      return std::forward<Self>(self).head;
    case supported_verb::post:
      return std::forward<Self>(self).post;
    case supported_verb::put:
      return std::forward<Self>(self).put;
    }
  }

  auto verbs() const -> verb_set
  {
    return verb_set{
      .options = static_cast<bool>(options),
      .delete_ = static_cast<bool>(delete_),
      .get = static_cast<bool>(get),
      .head = static_cast<bool>(head),
      .post = static_cast<bool>(post),
      .put = static_cast<bool>(put),
    };
  }

  auto empty() const -> bool { return verbs().empty(); }

  template <std::default_initializable U>
  auto map(std::invocable<V const&> auto f) const -> handler_map<U>
    requires std::
        assignable_from<U&, std::invoke_result_t<decltype(f), V const&>>
  {
    return {
      .options = static_cast<bool>(options) ? f(options) : U{},
      .delete_ = static_cast<bool>(delete_) ? f(delete_) : U{},
      .get = static_cast<bool>(get) ? f(get) : U{},
      .head = static_cast<bool>(head) ? f(head) : U{},
      .post = static_cast<bool>(post) ? f(post) : U{},
      .put = static_cast<bool>(put) ? f(put) : U{},
    };
  }
};

template <class Ctx>
struct route_tree
{
  using leaves = handler_map<basic_route_handler_fn_t<Ctx>>;
  using named_subtrees = std::unordered_map<std::string, route_tree>;
  using wildcard_subtree = std::indirect<route_tree>;

  leaves here;
  // TODO: consider making the first alternative a radix tree
  // Note: the map is the first variant here; the variant will be
  // default-constructed with the default-constructed first
  // alternative. The empty map denotes a lack of subtrees.
  std::variant<named_subtrees, wildcard_subtree> sub;
};

template <class OuterCtx, class InnerCtx>
auto middleware_wrap_tree(
    middleware_t<OuterCtx, InnerCtx> mw, route_tree<InnerCtx> const& tree)
    -> route_tree<OuterCtx>
{
  auto new_leaves = tree.here.template map<basic_route_handler_fn_t<OuterCtx>>(
      std::bind_front(middleware_wrap_fn<OuterCtx, InnerCtx>, mw));
  auto new_sub = tree.sub.visit(
      util::overloaded{
        [&mw](route_tree<InnerCtx>::named_subtrees const& subtrees)
            -> decltype(route_tree<OuterCtx>::sub)
        {
          auto new_subtrees = typename route_tree<OuterCtx>::named_subtrees{};
          for (auto [seg, subtree] : subtrees)
            new_subtrees[seg] = middleware_wrap_tree(mw, subtree);
          return new_subtrees;
        },
        [&mw](route_tree<InnerCtx>::wildcard_subtree const& subtree)
            -> decltype(route_tree<OuterCtx>::sub)
        {
          return typename route_tree<OuterCtx>::wildcard_subtree{
            middleware_wrap_tree(mw, *subtree)
          };
        },
      });
  return {.here = new_leaves, .sub = new_sub};
}

template <class T>
concept match_arg = std::constructible_from<T, std::string const&>;

template <class Ctx, match_arg... MatchArgs>
using route_handler_fn_t =
    std::function<auto(Ctx, readable_request, MatchArgs...)
                      ->net::awaitable<presponse>>;

template <class Ctx, match_arg... MatchArgs>
auto degen_route_handler(route_handler_fn_t<Ctx, MatchArgs...> fn)
    -> basic_route_handler_fn_t<Ctx>
{
  return
      [fn = std::move(fn)](
          Ctx ctx, readable_request r,
          std::vector<std::string> const& matches) -> net::awaitable<presponse>
  {
    if (sizeof...(MatchArgs) != matches.size())
      throw std::runtime_error{"got unexpected amount of matches"};
    auto it = matches.begin();
    co_return co_await fn(
        std::move(ctx), r,
        MatchArgs{static_cast<std::string const&>(*it++)}...);
  };
}

template <class Ctx, match_arg... MatchArgs>
struct ctree : route_tree<Ctx>
{
  template <class OuterCtx>
  auto wrap(middleware_t<OuterCtx, Ctx> mw) const
      -> ctree<OuterCtx, MatchArgs...>
  {
    return {middleware_wrap_tree(std::move(mw), *this)};
  }
};

template <class Ctx, match_arg... MatchArgs>
struct dtree : handler_map<route_handler_fn_t<Ctx, MatchArgs...>>
{
  [[nodiscard]] auto to_leaves() const -> typename route_tree<Ctx>::leaves
  {
    auto here = this->template map<basic_route_handler_fn_t<Ctx>>(
        degen_route_handler<Ctx, MatchArgs...>);
    if (!here.verbs().empty() && !static_cast<bool>(this->options))
      here.options = default_options_handler<Ctx>;
    return here;
  }

  [[nodiscard]] auto named_subtrees(
      std::initializer_list<std::pair<std::string, ctree<Ctx, MatchArgs...>>>
          subtrees) const -> ctree<Ctx, MatchArgs...>
  {
    auto sub = typename route_tree<Ctx>::named_subtrees{
      std::from_range, subtrees
                           | std::views::transform(
                               [](auto const& p)
                               {
                                 return std::make_pair(
                                     p.first,
                                     static_cast<route_tree<Ctx>>(p.second));
                               })
    };
    return {route_tree<Ctx>{.here = to_leaves(), .sub = sub}};
  }

  template <match_arg MatchArg>
  [[nodiscard]] auto
  wildcard_subtree(ctree<Ctx, MatchArgs..., MatchArg> subtree)
      -> ctree<Ctx, MatchArgs...>
  {
    return {route_tree<Ctx>{
      .here = to_leaves(),
      .sub = typename route_tree<Ctx>::wildcard_subtree{
        static_cast<route_tree<Ctx>>(subtree)
      }
    }};
  }

  [[nodiscard]] auto no_subtrees() const -> ctree<Ctx, MatchArgs...>
  {
    return {route_tree<Ctx>{.here = to_leaves(), .sub = {}}};
  }
};

class router
{
  struct impl_base
  {
    virtual ~impl_base() = default;
    virtual auto handle_request(trace::id trace_id, readable_request r) const
        -> net::awaitable<presponse> = 0;
  };

  std::unique_ptr<impl_base> impl_;

  template <std::derived_from<base_ctx> PreRouteCtx>
  class impl : public impl_base
  {
    log::logger l_;
    locale::selector lsel_;
    middleware_t<base_ctx, PreRouteCtx> global_middleware_;
    route_tree<routed_ctx<PreRouteCtx>> routes_;

  public:
    explicit impl(
        log::logger const& l, locale::selector&& lsel,
        middleware_t<base_ctx, PreRouteCtx> global_middleware,
        route_tree<routed_ctx<PreRouteCtx>> routes)
      : l_{l.sub("router")}, lsel_{std::move(lsel)},
        global_middleware_{std::move(global_middleware)},
        routes_{std::move(routes)}
    {
    }

    struct match_result
    {
      util::not_null<
          handler_map<basic_route_handler_fn_t<routed_ctx<PreRouteCtx>>> const*
      >
          route_handlers;
      std::vector<std::string> wildcard_matches;

      auto allowed_methods() const -> verb_set
      {
        return route_handlers->verbs();
      }
    };

    auto match(boost::urls::segments_view segments) const
        -> std::optional<match_result>
    {
      auto const* tree = &routes_;
      auto wildcard_matches = std::vector<std::string>{};
      for (auto const& seg : segments)
      {
        tree->sub.visit(
            util::overloaded{
              [&](route_tree<routed_ctx<PreRouteCtx>>::named_subtrees const&
                      subtrees)
              {
                auto it = subtrees.find(seg);
                tree = it == subtrees.end() ? nullptr : &it->second;
              },
              [&](route_tree<routed_ctx<PreRouteCtx>>::wildcard_subtree const&
                      wildcard_subtree)
              {
                wildcard_matches.push_back(seg);
                tree = &*wildcard_subtree;
              },
            });
        if (!tree)
          return std::nullopt;
      }
      if (tree->here.empty())
        return std::nullopt;
      return match_result{
        .route_handlers = util::not_null{&tree->here},
        .wildcard_matches = wildcard_matches,
      };
    }

    auto route_request(PreRouteCtx ctx, readable_request r) const
        -> net::awaitable<presponse>
    {
      auto req_base = r.p->get().base();

      auto const bad_request_tpl = problem::tpl{
        .status = bhttp::status::bad_request,
        .title = translate("Bad request"),
        .type_uri = "https://routemon.fautchen.eu/problems/bad-request",
      };

      if (req_base.target() == "*")
      {
        // request-target is in asterisk-form (RFC 9112, § 3.2.4),
        // so the request must be a server-wide OPTIONS request.

        if (req_base.method() != bhttp::verb::options)
        {
          auto tpl = problem::tpl{
            .status = bhttp::status::method_not_allowed,
            .title = translate("Method not allowed"),
            .type_uri = "https://routemon.fautchen.eu/problems/"
                        "method-not-allowed",
          };
          co_return problem_rsp(ctx, tpl.instantiate(), keep_alive{false});
        }

        co_return co_await global_options_handler(ctx, r);
      }
      else if (auto mreq_url0 =
                   boost::urls::parse_origin_form(req_base.target()))
      {
        // request-target is in origin-form (RFC 9112, § 3.2.1),
        // so it must be a normal request (not a CONNECT or
        // server-wide OPTIONS request).

        auto req_url = boost::urls::url{*mreq_url0};
        req_url.normalize();
        if (!req_url.is_path_absolute())
        {
          auto problem = bad_request_tpl.instantiate().set_detail(translate(
              "Path of normalized (RFC 3986, § 6) "
              "origin-form request-target (RFC "
              "9112, § 3.2.1) should be "
              "absolute"));
          co_return problem_rsp(ctx, problem, keep_alive{false});
        }

        l_.with(
              "trace_id",
              static_cast<base_ctx const&>(ctx).trace_id.as_string())
            .debug(
                "Request targets {} {}", req_base.method_string(),
                req_url.path());

        auto mres = match(req_url.segments());
        if (!mres)
        {
          auto tpl = problem::tpl{
            .status = bhttp::status::not_found,
            .title = translate("Not found"),
            .type_uri = "https://routemon.fautchen.eu/problems/not-found",
          };
          co_return problem_rsp(ctx, tpl.instantiate(), keep_alive{false});
        }

        auto mverb = supported_verb::from(req_base.method());
        if (!mverb)
        {
          // Method not implemented.
          auto tpl = problem::tpl{
            .status = bhttp::status::not_implemented,
            .title = translate("Method not implemented"),
            .type_uri = "https://routemon.fautchen.eu/problems/"
                        "method-not-implemented",
          };
          co_return problem_rsp(ctx, tpl.instantiate(), keep_alive{false});
        }

        if (auto mhdl = mres->route_handlers->lookup(*mverb))
        {
          auto new_ctx =
              routed_ctx<PreRouteCtx>{std::move(ctx), mres->allowed_methods()};
          co_return co_await mhdl(
              std::move(new_ctx), r, mres->wildcard_matches);
        }
        else
        {
          // Path recognized, but method not allowed.
          auto tpl = problem::tpl{
            .status = bhttp::status::method_not_allowed,
            .title = translate("Method not allowed"),
            .type_uri = "https://routemon.fautchen.eu/problems/"
                        "method-not-allowed",
          };
          auto rsp = problem_rsp(ctx, tpl.instantiate(), keep_alive{false});
          rsp.header().set(
              bhttp::field::allow, mres->allowed_methods().to_string());
          co_return std::move(rsp);
        }
      }
      else
      {
        // We do not accept any other request-target forms.

        auto problem = bad_request_tpl.instantiate().set_detail(translate(
            "Invalid request-target, expected "
            "asterisk-form or origin-form "
            "(see RFC 9112, § 3.2)"));
        co_return problem_rsp(ctx, problem, keep_alive{false});
      }
    }

    auto handle_request(trace::id trace_id, readable_request r) const
        -> net::awaitable<presponse> override
    {
      auto header = r.p->get().base();
      auto locale = lsel_.select(header[bhttp::field::accept_language]);
      co_return co_await global_middleware_(
          base_ctx{.locale = locale, .trace_id = trace_id}, header,
          [&](PreRouteCtx ctx) -> net::awaitable<presponse>
          { co_return co_await route_request(std::move(ctx), std::move(r)); });
    }
  };

public:
  template <std::derived_from<base_ctx> PreRouteCtx>
  explicit router(
      log::logger const& l, locale::selector&& lsel,
      middleware_t<base_ctx, PreRouteCtx> global_middleware,
      route_tree<routed_ctx<PreRouteCtx>> routes)
    : impl_{std::make_unique<impl<PreRouteCtx>>(
          l, std::move(lsel), std::move(global_middleware), std::move(routes))}
  {
  }

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

class server
{
  log::logger l_;
  router r_;

  auto do_session(beast::tcp_stream strm) -> net::awaitable<void>;
  auto do_listen(tcp::endpoint endpoint) -> net::awaitable<void>;

public:
  explicit server(log::logger const& l, router&& r);

  auto spawn(net::io_context& ioc) -> void;
};

} // namespace routemon::http