request.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. /* Copyright (c) 2018-2024 Marcelo Zimbres Silva (mzimbres@gmail.com)
  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/serialization.hpp>
  9. #include <boost/redis/resp3/type.hpp>
  10. #include <algorithm>
  11. #include <string>
  12. #include <tuple>
  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. struct request_access;
  19. } // namespace detail
  20. /** @brief Represents a Redis request.
  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. * <a href="https://redis.io/topics/pipelining"></a> for more info.
  25. *
  26. * For example:
  27. *
  28. * @code
  29. * request r;
  30. * r.push("HELLO", 3);
  31. * r.push("FLUSHALL");
  32. * r.push("PING");
  33. * r.push("PING", "key");
  34. * r.push("QUIT");
  35. * @endcode
  36. *
  37. * Uses a `std::string` for internal storage.
  38. */
  39. class request {
  40. public:
  41. /// Request configuration options.
  42. struct config {
  43. /** @brief (Deprecated) If `true`, calls to @ref basic_connection::async_exec will
  44. * complete with error if the connection is lost while the
  45. * request hasn't been sent yet.
  46. *
  47. * @par Deprecated
  48. * This setting is deprecated and should be always left out as the default
  49. * (waiting for a connection to be established again).
  50. * If you need to limit how much time a @ref basic_connection::async_exec
  51. * operation is allowed to take, use `asio::cancel_after`, instead.
  52. */
  53. bool cancel_on_connection_lost = false;
  54. /** @brief (Deprecated) If `true`, @ref basic_connection::async_exec will complete with
  55. * @ref boost::redis::error::not_connected if the call happens
  56. * before the connection with Redis was established.
  57. *
  58. * @par Deprecated
  59. * This setting is deprecated and should be always left out as the default
  60. * (waiting for a connection to be established).
  61. * If you need to limit how much time a @ref basic_connection::async_exec
  62. * operation is allowed to take, use `asio::cancel_after`, instead.
  63. */
  64. bool cancel_if_not_connected = false;
  65. /** @brief If `false`, @ref basic_connection::async_exec will not
  66. * automatically cancel this request if the connection is lost.
  67. * Affects only requests that have been written to the server
  68. * but have not been responded when
  69. * the connection is lost.
  70. */
  71. bool cancel_if_unresponded = true;
  72. /** @brief (Deprecated) If this request has a `HELLO` command and this flag
  73. * is `true`, it will be moved to the
  74. * front of the queue of awaiting requests. This makes it
  75. * possible to send `HELLO` commands and authenticate before other
  76. * commands are sent.
  77. *
  78. * @par Deprecated
  79. * This field has been superseded by @ref config::setup.
  80. * This setup request will always be run first on connection establishment.
  81. * Please use it to run any required setup commands.
  82. * This field will be removed in subsequent releases.
  83. */
  84. bool hello_with_priority = true;
  85. };
  86. /** @brief Constructor
  87. *
  88. * @param cfg Configuration options.
  89. */
  90. explicit request(config cfg = config{false, false, true, true})
  91. : cfg_{cfg}
  92. { }
  93. /// Returns the number of responses expected for this request.
  94. [[nodiscard]] auto get_expected_responses() const noexcept -> std::size_t
  95. {
  96. return expected_responses_;
  97. };
  98. /// Returns the number of commands contained in this request.
  99. [[nodiscard]] auto get_commands() const noexcept -> std::size_t { return commands_; };
  100. [[nodiscard]] auto payload() const noexcept -> std::string_view { return payload_; }
  101. [[nodiscard]]
  102. BOOST_DEPRECATED(
  103. "The hello_with_priority attribute and related functions are deprecated. "
  104. "Use config::setup to run setup commands, instead.") auto has_hello_priority() const noexcept
  105. -> auto const&
  106. {
  107. return has_hello_priority_;
  108. }
  109. /// Clears the request preserving allocated memory.
  110. void clear()
  111. {
  112. payload_.clear();
  113. commands_ = 0;
  114. expected_responses_ = 0;
  115. has_hello_priority_ = false;
  116. }
  117. /// Calls `std::string::reserve` on the internal storage.
  118. void reserve(std::size_t new_cap = 0) { payload_.reserve(new_cap); }
  119. /// Returns a reference to the config object.
  120. [[nodiscard]] auto get_config() const noexcept -> config const& { return cfg_; }
  121. /// Returns a reference to the config object.
  122. [[nodiscard]] auto get_config() noexcept -> config& { return cfg_; }
  123. /** @brief Appends a new command to the end of the request.
  124. *
  125. * For example:
  126. *
  127. * @code
  128. * request req;
  129. * req.push("SET", "key", "some string", "EX", "2");
  130. * @endcode
  131. *
  132. * This will add a `SET` command with value `"some string"` and an
  133. * expiration of 2 seconds.
  134. *
  135. * Command arguments should either be convertible to `std::string_view`
  136. * or support the `boost_redis_to_bulk` function.
  137. * This function is a customization point that must be made available
  138. * using ADL and must have the following signature:
  139. *
  140. * @code
  141. * void boost_redis_to_bulk(std::string& to, T const& t);
  142. * @endcode
  143. *
  144. *
  145. * See cpp20_serialization.cpp
  146. *
  147. * @param cmd The command to execute. It should be a redis or sentinel command, like `"SET"`.
  148. * @param args Command arguments. Non-string types will be converted to string by calling `boost_redis_to_bulk` on each argument.
  149. * @tparam Ts Types of the command arguments.
  150. *
  151. */
  152. template <class... Ts>
  153. void push(std::string_view cmd, Ts const&... args)
  154. {
  155. auto constexpr pack_size = sizeof...(Ts);
  156. resp3::add_header(payload_, resp3::type::array, 1 + pack_size);
  157. resp3::add_bulk(payload_, cmd);
  158. resp3::add_bulk(payload_, std::tie(std::forward<Ts const&>(args)...));
  159. check_cmd(cmd);
  160. }
  161. /** @brief Appends a new command to the end of the request.
  162. *
  163. * This overload is useful for commands that have a key and have a
  164. * dynamic range of arguments. For example:
  165. *
  166. * @code
  167. * std::map<std::string, std::string> map
  168. * { {"key1", "value1"}
  169. * , {"key2", "value2"}
  170. * , {"key3", "value3"}
  171. * };
  172. *
  173. * request req;
  174. * req.push_range("HSET", "key", map.cbegin(), map.cend());
  175. * @endcode
  176. *
  177. * Command arguments should either be convertible to `std::string_view`
  178. * or support the `boost_redis_to_bulk` function.
  179. * This function is a customization point that must be made available
  180. * using ADL and must have the following signature:
  181. *
  182. * @code
  183. * void boost_redis_to_bulk(std::string& to, T const& t);
  184. * @endcode
  185. *
  186. * @param cmd The command to execute. It should be a redis or sentinel command, like `"SET"`.
  187. * @param key The command key. It will be added as the first argument to the command.
  188. * @param begin Iterator to the begin of the range.
  189. * @param end Iterator to the end of the range.
  190. * @tparam ForwardIterator A forward iterator with an element type that is convertible to `std::string_view`
  191. * or supports `boost_redis_to_bulk`.
  192. *
  193. * See cpp20_serialization.cpp
  194. */
  195. template <class ForwardIterator>
  196. void push_range(
  197. std::string_view cmd,
  198. std::string_view key,
  199. ForwardIterator begin,
  200. ForwardIterator end,
  201. typename std::iterator_traits<ForwardIterator>::value_type* = nullptr)
  202. {
  203. using value_type = typename std::iterator_traits<ForwardIterator>::value_type;
  204. if (begin == end)
  205. return;
  206. auto constexpr size = resp3::bulk_counter<value_type>::size;
  207. auto const distance = std::distance(begin, end);
  208. resp3::add_header(payload_, resp3::type::array, 2 + size * distance);
  209. resp3::add_bulk(payload_, cmd);
  210. resp3::add_bulk(payload_, key);
  211. for (; begin != end; ++begin)
  212. resp3::add_bulk(payload_, *begin);
  213. check_cmd(cmd);
  214. }
  215. /** @brief Appends a new command to the end of the request.
  216. *
  217. * This overload is useful for commands that have a dynamic number
  218. * of arguments and don't have a key. For example:
  219. *
  220. * @code
  221. * std::set<std::string> channels
  222. * { "channel1" , "channel2" , "channel3" };
  223. *
  224. * request req;
  225. * req.push("SUBSCRIBE", std::cbegin(channels), std::cend(channels));
  226. * @endcode
  227. *
  228. * Command arguments should either be convertible to `std::string_view`
  229. * or support the `boost_redis_to_bulk` function.
  230. * This function is a customization point that must be made available
  231. * using ADL and must have the following signature:
  232. *
  233. * @code
  234. * void boost_redis_to_bulk(std::string& to, T const& t);
  235. * @endcode
  236. *
  237. * @param cmd The command to execute. It should be a redis or sentinel command, like `"SET"`.
  238. * @param begin Iterator to the begin of the range.
  239. * @param end Iterator to the end of the range.
  240. * @tparam ForwardIterator A forward iterator with an element type that is convertible to `std::string_view`
  241. * or supports `boost_redis_to_bulk`.
  242. *
  243. * See cpp20_serialization.cpp
  244. */
  245. template <class ForwardIterator>
  246. void push_range(
  247. std::string_view cmd,
  248. ForwardIterator begin,
  249. ForwardIterator end,
  250. typename std::iterator_traits<ForwardIterator>::value_type* = nullptr)
  251. {
  252. using value_type = typename std::iterator_traits<ForwardIterator>::value_type;
  253. if (begin == end)
  254. return;
  255. auto constexpr size = resp3::bulk_counter<value_type>::size;
  256. auto const distance = std::distance(begin, end);
  257. resp3::add_header(payload_, resp3::type::array, 1 + size * distance);
  258. resp3::add_bulk(payload_, cmd);
  259. for (; begin != end; ++begin)
  260. resp3::add_bulk(payload_, *begin);
  261. check_cmd(cmd);
  262. }
  263. /** @brief Appends a new command to the end of the request.
  264. *
  265. * Equivalent to the overload taking a range of begin and end
  266. * iterators.
  267. *
  268. * @param cmd The command to execute. It should be a redis or sentinel command, like `"SET"`.
  269. * @param key The command key. It will be added as the first argument to the command.
  270. * @param range Range containing the command arguments.
  271. * @tparam Range A type that can be passed to `std::begin()` and `std::end()` to obtain
  272. * iterators. The range elements should be convertible to `std::string_view`
  273. * or support `boost_redis_to_bulk`.
  274. */
  275. template <class Range>
  276. void push_range(
  277. std::string_view cmd,
  278. std::string_view key,
  279. Range const& range,
  280. decltype(std::begin(range))* = nullptr)
  281. {
  282. using std::begin;
  283. using std::end;
  284. push_range(cmd, key, begin(range), end(range));
  285. }
  286. /** @brief Appends a new command to the end of the request.
  287. *
  288. * Equivalent to the overload taking a range of begin and end
  289. * iterators.
  290. *
  291. * @param cmd The command to execute. It should be a redis or sentinel command, like `"SET"`.
  292. * @param range Range containing the command arguments.
  293. * @tparam Range A type that can be passed to `std::begin()` and `std::end()` to obtain
  294. * iterators. The range elements should be convertible to `std::string_view`
  295. * or support `boost_redis_to_bulk`.
  296. */
  297. template <class Range>
  298. void push_range(
  299. std::string_view cmd,
  300. Range const& range,
  301. decltype(std::cbegin(range))* = nullptr)
  302. {
  303. using std::cbegin;
  304. using std::cend;
  305. push_range(cmd, cbegin(range), cend(range));
  306. }
  307. /** @brief Appends the commands in another request to the end of the request.
  308. *
  309. * Appends all the commands contained in `other` to the end of
  310. * this request. Configuration flags in `*this`,
  311. * like @ref config::cancel_if_unresponded, are *not* modified,
  312. * even if `other` has a different config than `*this`.
  313. *
  314. * @param other The request containing the commands to append.
  315. */
  316. void append(const request& other);
  317. private:
  318. void check_cmd(std::string_view cmd)
  319. {
  320. ++commands_;
  321. if (!detail::has_response(cmd))
  322. ++expected_responses_;
  323. if (cmd == "HELLO")
  324. has_hello_priority_ = cfg_.hello_with_priority;
  325. }
  326. config cfg_;
  327. std::string payload_;
  328. std::size_t commands_ = 0;
  329. std::size_t expected_responses_ = 0;
  330. bool has_hello_priority_ = false;
  331. friend struct detail::request_access;
  332. };
  333. namespace detail {
  334. struct request_access {
  335. inline static void set_priority(request& r, bool value) { r.has_hello_priority_ = value; }
  336. inline static bool has_priority(const request& r) { return r.has_hello_priority_; }
  337. };
  338. // Creates a HELLO 3 request
  339. request make_hello_request();
  340. } // namespace detail
  341. } // namespace boost::redis
  342. #endif // BOOST_REDIS_REQUEST_HPP