virthttp  0.0
libvirt http interface
async_handler.hpp
Go to the documentation of this file.
1 #pragma once
2 #include <string_view>
3 #include <boost/beast/http.hpp>
4 #include <ctre.hpp>
7 
8 using namespace std::literals;
9 
14 constexpr static ctll::fixed_string numeric_id_pattern = "[0-9A-Fa-f]{1,8}";
22 constexpr auto numeric_id_match(std::string_view id) noexcept { return ctre::match<numeric_id_pattern>(id); }
23 
24 // Contract: sv matches `numeric_id_pattern`
32 constexpr std::uint32_t hex_decode_id(std::string_view sv) noexcept {
33  std::uint32_t ret = 0;
34  for (char c : sv) {
35  ret <<= 4u;
36 
37  if (c >= '0' && '9' >= c)
38  ret += c - '0';
39  else if (c >= 'A' && 'F' >= c)
40  ret += c - 'A' + 10;
41  else if (c >= 'a' && 'f' >= c)
42  ret += c - 'a' + 10;
43  }
44  return ret;
45 }
46 
54 constexpr std::array<char, sizeof(std::uint32_t) * 2> hex_encode_id(std::uint32_t id) noexcept {
55  constexpr auto hex = "0123456789abcdef"sv;
56  std::array<char, sizeof(std::uint32_t)* 2> ret = {};
57  for (auto it = ret.rbegin(); it < ret.rend(); ++it) {
58  *it = hex[id & 0xfu];
59  id >>= 16u;
60  }
61  return ret;
62 }
63 
72 template <TransportProto proto> auto handle_async_retrieve(GeneralStore& gstore, std::string_view str_id) {
73  if constexpr (proto == TransportProto::HTTP1) {
74  using Ret = std::pair<boost::beast::http::status, std::string>;
75 
76  if (!numeric_id_match(str_id))
77  return Ret{boost::beast::http::status::not_found, {}};
78 
79  auto [status, val] = gstore.async_store.value_if_ready(hex_decode_id(str_id));
80  switch (status) {
82  return Ret{boost::beast::http::status::not_found, {}};
84  return Ret{boost::beast::http::status::processing, {}};
86  return Ret{boost::beast::http::status::found, val};
87  }
88  }
90 }
std::pair< TaskStatus, std::string > value_if_ready(IndexType id)
Definition: async_store.hpp:83
#define UNREACHABLE
Definition: utility.hpp:19
task is done and its buffers are ready to be sent back
AsyncStore async_store
Definition: general_store.hpp:10
constexpr auto numeric_id_match(std::string_view id) noexcept
Definition: async_handler.hpp:22
static constexpr ctll::fixed_string numeric_id_pattern
Definition: async_handler.hpp:14
constexpr std::uint32_t hex_decode_id(std::string_view sv) noexcept
Definition: async_handler.hpp:32
constexpr std::array< char, sizeof(std::uint32_t)*2 > hex_encode_id(std::uint32_t id) noexcept
Definition: async_handler.hpp:54
task is currently being executed
Definition: general_store.hpp:5
auto handle_async_retrieve(GeneralStore &gstore, std::string_view str_id)
Definition: async_handler.hpp:72