request.hpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. /* Copyright (c) 2018-2023 Marcelo Zimbres Silva ([email protected])
  2. *
  3. * Distributed under the Boost Software License, Version 1.0. (See
  4. * accompanying file LICENSE.txt)
  5. */
  6. #ifndef BOOST_REDIS_REQUEST_HPP
  7. #define BOOST_REDIS_REQUEST_HPP
  8. #include <boost/redis/resp3/type.hpp>
  9. #include <boost/redis/resp3/serialization.hpp>
  10. #include <string>
  11. #include <tuple>
  12. #include <algorithm>
  13. // NOTE: For some commands like hset it would be a good idea to assert
  14. // the value type is a pair.
  15. namespace boost::redis {
  16. namespace detail{
  17. auto has_response(std::string_view cmd) -> bool;
  18. }
  19. /** \brief Creates Redis requests.
  20. * \ingroup high-level-api
  21. *
  22. * A request is composed of one or more Redis commands and is
  23. * referred to in the redis documentation as a pipeline, see
  24. * https://redis.io/topics/pipelining. For example
  25. *
  26. * @code
  27. * request r;
  28. * r.push("HELLO", 3);
  29. * r.push("FLUSHALL");
  30. * r.push("PING");
  31. * r.push("PING", "key");
  32. * r.push("QUIT");
  33. * @endcode
  34. *
  35. * \remarks
  36. *
  37. * Uses a std::string for internal storage.
  38. */
  39. class request {
  40. public:
  41. /// Request configuration options.
  42. struct config {
  43. /** \brief If `true` calls to `connection::async_exec` will
  44. * complete with error if the connection is lost while the
  45. * request hasn't been sent yet.
  46. */
  47. bool cancel_on_connection_lost = true;
  48. /** \brief If `true` `connection::async_exec` will complete with
  49. * `boost::redis::error::not_connected` if the call happens
  50. * before the connection with Redis was established.
  51. */
  52. bool cancel_if_not_connected = false;
  53. /** \brief If `false` `connection::async_exec` will not
  54. * automatically cancel this request if the connection is lost.
  55. * Affects only requests that have been written to the socket
  56. * but remained unresponded when
  57. * `boost::redis::connection::async_run` completed.
  58. */
  59. bool cancel_if_unresponded = true;
  60. /** \brief If this request has a `HELLO` command and this flag
  61. * is `true`, the `boost::redis::connection` will move it to the
  62. * front of the queue of awaiting requests. This makes it
  63. * possible to send `HELLO` and authenticate before other
  64. * commands are sent.
  65. */
  66. bool hello_with_priority = true;
  67. };
  68. /** \brief Constructor
  69. *
  70. * \param cfg Configuration options.
  71. */
  72. explicit
  73. request(config cfg = config{true, false, true, true})
  74. : cfg_{cfg} {}
  75. //// Returns the number of responses expected for this request.
  76. [[nodiscard]] auto get_expected_responses() const noexcept -> std::size_t
  77. { return expected_responses_;};
  78. //// Returns the number of commands contained in this request.
  79. [[nodiscard]] auto get_commands() const noexcept -> std::size_t
  80. { return commands_;};
  81. [[nodiscard]] auto payload() const noexcept -> std::string_view
  82. { return payload_;}
  83. [[nodiscard]] auto has_hello_priority() const noexcept -> auto const&
  84. { return has_hello_priority_;}
  85. /// Clears the request preserving allocated memory.
  86. void clear()
  87. {
  88. payload_.clear();
  89. commands_ = 0;
  90. expected_responses_ = 0;
  91. has_hello_priority_ = false;
  92. }
  93. /// Calls std::string::reserve on the internal storage.
  94. void reserve(std::size_t new_cap = 0)
  95. { payload_.reserve(new_cap); }
  96. /// Returns a const reference to the config object.
  97. [[nodiscard]] auto get_config() const noexcept -> auto const& {return cfg_; }
  98. /// Returns a reference to the config object.
  99. [[nodiscard]] auto get_config() noexcept -> auto& {return cfg_; }
  100. /** @brief Appends a new command to the end of the request.
  101. *
  102. * For example
  103. *
  104. * \code
  105. * request req;
  106. * req.push("SET", "key", "some string", "EX", "2");
  107. * \endcode
  108. *
  109. * will add the `set` command with value "some string" and an
  110. * expiration of 2 seconds.
  111. *
  112. * \param cmd The command e.g redis or sentinel command.
  113. * \param args Command arguments.
  114. * \tparam Ts Non-string types will be converted to string by calling `boost_redis_to_bulk` on each argument. This function must be made available over ADL and must have the following signature
  115. *
  116. * @code
  117. * void boost_redis_to_bulk(std::string& to, T const& t);
  118. * {
  119. * boost::redis::resp3::boost_redis_to_bulk(to, serialize(t));
  120. * }
  121. * @endcode
  122. *
  123. * See cpp20_serialization.cpp
  124. */
  125. template <class... Ts>
  126. void push(std::string_view cmd, Ts const&... args)
  127. {
  128. auto constexpr pack_size = sizeof...(Ts);
  129. resp3::add_header(payload_, resp3::type::array, 1 + pack_size);
  130. resp3::add_bulk(payload_, cmd);
  131. resp3::add_bulk(payload_, std::tie(std::forward<Ts const&>(args)...));
  132. check_cmd(cmd);
  133. }
  134. /** @brief Appends a new command to the end of the request.
  135. *
  136. * This overload is useful for commands that have a key and have a
  137. * dynamic range of arguments. For example
  138. *
  139. * @code
  140. * std::map<std::string, std::string> map
  141. * { {"key1", "value1"}
  142. * , {"key2", "value2"}
  143. * , {"key3", "value3"}
  144. * };
  145. *
  146. * request req;
  147. * req.push_range("HSET", "key", std::cbegin(map), std::cend(map));
  148. * @endcode
  149. *
  150. * \param cmd The command e.g. Redis or Sentinel command.
  151. * \param key The command key.
  152. * \param begin Iterator to the begin of the range.
  153. * \param end Iterator to the end of the range.
  154. * \tparam Ts Non-string types will be converted to string by calling `boost_redis_to_bulk` on each argument. This function must be made available over ADL and must have the following signature
  155. *
  156. * @code
  157. * void boost_redis_to_bulk(std::string& to, T const& t);
  158. * {
  159. * boost::redis::resp3::boost_redis_to_bulk(to, serialize(t));
  160. * }
  161. * @endcode
  162. *
  163. * See cpp20_serialization.cpp
  164. */
  165. template <class ForwardIterator>
  166. void
  167. push_range(
  168. std::string_view const& cmd,
  169. std::string_view const& key,
  170. ForwardIterator begin,
  171. ForwardIterator end,
  172. typename std::iterator_traits<ForwardIterator>::value_type * = nullptr)
  173. {
  174. using value_type = typename std::iterator_traits<ForwardIterator>::value_type;
  175. if (begin == end)
  176. return;
  177. auto constexpr size = resp3::bulk_counter<value_type>::size;
  178. auto const distance = std::distance(begin, end);
  179. resp3::add_header(payload_, resp3::type::array, 2 + size * distance);
  180. resp3::add_bulk(payload_, cmd);
  181. resp3::add_bulk(payload_, key);
  182. for (; begin != end; ++begin)
  183. resp3::add_bulk(payload_, *begin);
  184. check_cmd(cmd);
  185. }
  186. /** @brief Appends a new command to the end of the request.
  187. *
  188. * This overload is useful for commands that have a dynamic number
  189. * of arguments and don't have a key. For example
  190. *
  191. * \code
  192. * std::set<std::string> channels
  193. * { "channel1" , "channel2" , "channel3" }
  194. *
  195. * request req;
  196. * req.push("SUBSCRIBE", std::cbegin(channels), std::cend(channels));
  197. * \endcode
  198. *
  199. * \param cmd The Redis command
  200. * \param begin Iterator to the begin of the range.
  201. * \param end Iterator to the end of the range.
  202. * \tparam ForwardIterator If the value type is not a std::string it will be converted to a string by calling `boost_redis_to_bulk`. This function must be made available over ADL and must have the following signature
  203. *
  204. * @code
  205. * void boost_redis_to_bulk(std::string& to, T const& t);
  206. * {
  207. * boost::redis::resp3::boost_redis_to_bulk(to, serialize(t));
  208. * }
  209. * @endcode
  210. *
  211. * See cpp20_serialization.cpp
  212. */
  213. template <class ForwardIterator>
  214. void
  215. push_range(
  216. std::string_view const& cmd,
  217. ForwardIterator begin,
  218. ForwardIterator end,
  219. typename std::iterator_traits<ForwardIterator>::value_type * = nullptr)
  220. {
  221. using value_type = typename std::iterator_traits<ForwardIterator>::value_type;
  222. if (begin == end)
  223. return;
  224. auto constexpr size = resp3::bulk_counter<value_type>::size;
  225. auto const distance = std::distance(begin, end);
  226. resp3::add_header(payload_, resp3::type::array, 1 + size * distance);
  227. resp3::add_bulk(payload_, cmd);
  228. for (; begin != end; ++begin)
  229. resp3::add_bulk(payload_, *begin);
  230. check_cmd(cmd);
  231. }
  232. /** @brief Appends a new command to the end of the request.
  233. *
  234. * Equivalent to the overload taking a range of begin and end
  235. * iterators.
  236. *
  237. * \param cmd Redis command.
  238. * \param key Redis key.
  239. * \param range Range to send e.g. `std::map`.
  240. * \tparam A type that can be passed to `std::cbegin()` and `std::cend()`.
  241. */
  242. template <class Range>
  243. void
  244. push_range(
  245. std::string_view const& cmd,
  246. std::string_view const& key,
  247. Range const& range,
  248. decltype(std::begin(range)) * = nullptr)
  249. {
  250. using std::begin;
  251. using std::end;
  252. push_range(cmd, key, begin(range), end(range));
  253. }
  254. /** @brief Appends a new command to the end of the request.
  255. *
  256. * Equivalent to the overload taking a range of begin and end
  257. * iterators.
  258. *
  259. * \param cmd Redis command.
  260. * \param range Range to send e.g. `std::map`.
  261. * \tparam A type that can be passed to `std::cbegin()` and `std::cend()`.
  262. */
  263. template <class Range>
  264. void
  265. push_range(
  266. std::string_view cmd,
  267. Range const& range,
  268. decltype(std::cbegin(range)) * = nullptr)
  269. {
  270. using std::cbegin;
  271. using std::cend;
  272. push_range(cmd, cbegin(range), cend(range));
  273. }
  274. private:
  275. void check_cmd(std::string_view cmd)
  276. {
  277. ++commands_;
  278. if (!detail::has_response(cmd))
  279. ++expected_responses_;
  280. if (cmd == "HELLO")
  281. has_hello_priority_ = cfg_.hello_with_priority;
  282. }
  283. config cfg_;
  284. std::string payload_;
  285. std::size_t commands_ = 0;
  286. std::size_t expected_responses_ = 0;
  287. bool has_hello_priority_ = false;
  288. };
  289. } // boost::redis::resp3
  290. #endif // BOOST_REDIS_REQUEST_HPP