multiplexer.ipp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. /* Copyright (c) 2018-2025 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. #include <boost/redis/detail/multiplexer.hpp>
  7. #include <boost/redis/ignore.hpp>
  8. #include <boost/redis/request.hpp>
  9. #include <boost/asio/error.hpp>
  10. #include <boost/assert.hpp>
  11. #include <cstddef>
  12. #include <memory>
  13. namespace boost::redis::detail {
  14. multiplexer::elem::elem(request const& req, any_adapter adapter)
  15. : req_{&req}
  16. , adapter_{std::move(adapter)}
  17. , remaining_responses_{req.get_expected_responses()}
  18. , status_{status::waiting}
  19. , ec_{}
  20. , read_size_{0}
  21. { }
  22. auto multiplexer::elem::notify_error(system::error_code ec) noexcept -> void
  23. {
  24. if (!ec_) {
  25. ec_ = ec;
  26. }
  27. notify_done();
  28. }
  29. auto multiplexer::elem::commit_response(std::size_t read_size) -> void
  30. {
  31. read_size_ += read_size;
  32. --remaining_responses_;
  33. }
  34. void multiplexer::elem::mark_abandoned()
  35. {
  36. req_ = nullptr;
  37. adapter_ = any_adapter(); // A default-constructed any_adapter ignores all nodes
  38. set_done_callback([] { });
  39. }
  40. multiplexer::multiplexer()
  41. {
  42. // Reserve some memory to avoid excessive memory allocations in
  43. // the first reads.
  44. read_buffer_.reserve(4096u);
  45. }
  46. void multiplexer::cancel(std::shared_ptr<elem> const& ptr)
  47. {
  48. if (ptr->is_waiting()) {
  49. // We can safely remove it from the queue, since it hasn't been sent yet
  50. reqs_.erase(std::remove(std::begin(reqs_), std::end(reqs_), ptr));
  51. } else {
  52. // Removing the request would cause trouble when the response arrived.
  53. // Mark it as abandoned, so the response is discarded when it arrives
  54. ptr->mark_abandoned();
  55. }
  56. }
  57. bool multiplexer::commit_write(std::size_t bytes_written)
  58. {
  59. BOOST_ASSERT(!cancel_run_called_);
  60. BOOST_ASSERT(bytes_written + write_offset_ <= write_buffer_.size());
  61. usage_.bytes_sent += bytes_written;
  62. write_offset_ += bytes_written;
  63. // Are there still more bytes to write?
  64. if (write_offset_ < write_buffer_.size())
  65. return false;
  66. // We've written all the bytes in the write buffer.
  67. write_buffer_.clear();
  68. // There is small optimization possible here: traverse only the
  69. // partition of unwritten requests instead of them all.
  70. std::for_each(std::begin(reqs_), std::end(reqs_), [](auto const& ptr) {
  71. BOOST_ASSERT_MSG(ptr != nullptr, "Expects non-null pointer.");
  72. if (ptr->is_staged()) {
  73. ptr->mark_written();
  74. }
  75. });
  76. release_push_requests();
  77. return true;
  78. }
  79. void multiplexer::add(std::shared_ptr<elem> const& info)
  80. {
  81. BOOST_ASSERT(!info->is_abandoned());
  82. reqs_.push_back(info);
  83. if (request_access::has_priority(info->get_request())) {
  84. auto rend = std::partition_point(std::rbegin(reqs_), std::rend(reqs_), [](auto const& e) {
  85. return e->is_waiting();
  86. });
  87. std::rotate(std::rbegin(reqs_), std::rbegin(reqs_) + 1, rend);
  88. }
  89. }
  90. consume_result multiplexer::consume_impl(system::error_code& ec)
  91. {
  92. // We arrive here in two states:
  93. //
  94. // 1. While we are parsing a message. In this case we
  95. // don't want to determine the type of the message in the
  96. // buffer (i.e. response vs push) but leave it untouched
  97. // until the parsing of a complete message ends.
  98. //
  99. // 2. On a new message, in which case we have to determine
  100. // whether the next message is a push or a response.
  101. //
  102. auto const data = read_buffer_.get_commited();
  103. BOOST_ASSERT(!data.empty());
  104. if (!on_push_) // Prepare for new message.
  105. on_push_ = is_next_push(data);
  106. if (on_push_) {
  107. if (!resp3::parse(parser_, data, receive_adapter_, ec))
  108. return consume_result::needs_more;
  109. return consume_result::got_push;
  110. }
  111. BOOST_ASSERT(!reqs_.empty());
  112. BOOST_ASSERT(reqs_.front() != nullptr);
  113. BOOST_ASSERT(reqs_.front()->get_remaining_responses() != 0);
  114. BOOST_ASSERT(!reqs_.front()->is_waiting());
  115. if (!resp3::parse(parser_, data, reqs_.front()->get_adapter(), ec))
  116. return consume_result::needs_more;
  117. if (ec) {
  118. reqs_.front()->notify_error(ec);
  119. reqs_.pop_front();
  120. return consume_result::got_response;
  121. }
  122. reqs_.front()->commit_response(parser_.get_consumed());
  123. if (reqs_.front()->get_remaining_responses() == 0) {
  124. // Done with this request.
  125. reqs_.front()->notify_done();
  126. reqs_.pop_front();
  127. }
  128. return consume_result::got_response;
  129. }
  130. std::pair<consume_result, std::size_t> multiplexer::consume(system::error_code& ec)
  131. {
  132. BOOST_ASSERT(!cancel_run_called_);
  133. auto const ret = consume_impl(ec);
  134. auto const consumed = parser_.get_consumed();
  135. if (ec) {
  136. return std::make_pair(ret, consumed);
  137. }
  138. if (ret != consume_result::needs_more) {
  139. parser_.reset();
  140. auto const res = read_buffer_.consume(consumed);
  141. commit_usage(ret == consume_result::got_push, res);
  142. return std::make_pair(ret, res.consumed);
  143. }
  144. return std::make_pair(consume_result::needs_more, consumed);
  145. }
  146. auto multiplexer::prepare_read() noexcept -> system::error_code { return read_buffer_.prepare(); }
  147. auto multiplexer::get_prepared_read_buffer() noexcept -> read_buffer::span_type
  148. {
  149. return read_buffer_.get_prepared();
  150. }
  151. void multiplexer::commit_read(std::size_t bytes_read) { read_buffer_.commit(bytes_read); }
  152. auto multiplexer::get_read_buffer_size() const noexcept -> std::size_t
  153. {
  154. return read_buffer_.get_commited().size();
  155. }
  156. void multiplexer::reset()
  157. {
  158. read_buffer_.clear();
  159. write_buffer_.clear();
  160. write_offset_ = 0u;
  161. parser_.reset();
  162. on_push_ = false;
  163. cancel_run_called_ = false;
  164. }
  165. std::size_t multiplexer::prepare_write()
  166. {
  167. BOOST_ASSERT(!cancel_run_called_);
  168. // Coalesces the requests and marks them staged. After a
  169. // successful write staged requests will be marked as written.
  170. auto const point = std::partition_point(
  171. std::cbegin(reqs_),
  172. std::cend(reqs_),
  173. [](auto const& ri) {
  174. return !ri->is_waiting();
  175. });
  176. std::for_each(point, std::cend(reqs_), [this](const std::shared_ptr<elem>& ri) {
  177. // Stage the request.
  178. BOOST_ASSERT(!ri->is_abandoned());
  179. write_buffer_ += ri->get_request().payload();
  180. ri->mark_staged();
  181. usage_.commands_sent += ri->get_request().get_commands();
  182. });
  183. write_offset_ = 0u;
  184. auto const d = std::distance(point, std::cend(reqs_));
  185. return static_cast<std::size_t>(d);
  186. }
  187. std::size_t multiplexer::cancel_waiting()
  188. {
  189. auto f = [](auto const& ptr) {
  190. BOOST_ASSERT(ptr != nullptr);
  191. return !ptr->is_waiting();
  192. };
  193. auto point = std::stable_partition(std::begin(reqs_), std::end(reqs_), f);
  194. auto const ret = std::distance(point, std::end(reqs_));
  195. std::for_each(point, std::end(reqs_), [](auto const& ptr) {
  196. ptr->notify_error({asio::error::operation_aborted});
  197. });
  198. reqs_.erase(point, std::end(reqs_));
  199. return ret;
  200. }
  201. void multiplexer::cancel_on_conn_lost()
  202. {
  203. // Should only be called once per reconnection.
  204. // See https://github.com/boostorg/redis/issues/181
  205. BOOST_ASSERT(!cancel_run_called_);
  206. cancel_run_called_ = true;
  207. // Must return false if the request should be removed.
  208. auto cond = [](const std::shared_ptr<elem>& ptr) {
  209. BOOST_ASSERT(ptr != nullptr);
  210. // Abandoned requests only make sense because a response for them might arrive.
  211. // They should be discarded after the connection is lost
  212. if (ptr->is_abandoned())
  213. return false;
  214. if (ptr->is_waiting()) {
  215. return !ptr->get_request().get_config().cancel_on_connection_lost;
  216. } else {
  217. return !ptr->get_request().get_config().cancel_if_unresponded;
  218. }
  219. };
  220. auto point = std::stable_partition(std::begin(reqs_), std::end(reqs_), cond);
  221. std::for_each(point, std::end(reqs_), [](auto const& ptr) {
  222. ptr->notify_error({asio::error::operation_aborted});
  223. });
  224. reqs_.erase(point, std::end(reqs_));
  225. std::for_each(std::begin(reqs_), std::end(reqs_), [](auto const& ptr) {
  226. return ptr->mark_waiting();
  227. });
  228. }
  229. void multiplexer::commit_usage(bool is_push, read_buffer::consume_result res)
  230. {
  231. if (is_push) {
  232. usage_.pushes_received += 1;
  233. usage_.push_bytes_received += res.consumed;
  234. on_push_ = false;
  235. } else {
  236. usage_.responses_received += 1;
  237. usage_.response_bytes_received += res.consumed;
  238. }
  239. usage_.bytes_rotated += res.rotated;
  240. }
  241. bool multiplexer::is_next_push(std::string_view data) const noexcept
  242. {
  243. // Useful links to understand the heuristics below.
  244. //
  245. // - https://github.com/redis/redis/issues/11784
  246. // - https://github.com/redis/redis/issues/6426
  247. // - https://github.com/boostorg/redis/issues/170
  248. // Test if the message resp3 type is a push.
  249. BOOST_ASSERT(!data.empty());
  250. if (resp3::to_type(data.front()) == resp3::type::push)
  251. return true;
  252. // This is non-push type and the requests queue is empty. I have
  253. // noticed this is possible, for example with -MISCONF. I don't
  254. // know why they are not sent with a push type so we can
  255. // distinguish them from responses to commands. If we are lucky
  256. // enough to receive them when the command queue is empty they
  257. // can be treated as server pushes, otherwise it is impossible
  258. // to handle them properly
  259. if (reqs_.empty())
  260. return true;
  261. // The request does not expect any response but we got one. This
  262. // may happen if for example, subscribe with wrong syntax.
  263. if (reqs_.front()->get_remaining_responses() == 0)
  264. return true;
  265. // Added to deal with MONITOR and also to fix PR170 which
  266. // happens under load and on low-latency networks, where we
  267. // might start receiving responses before the write operation
  268. // completed and the request is still marked as staged and not
  269. // written.
  270. return reqs_.front()->is_waiting();
  271. }
  272. void multiplexer::release_push_requests()
  273. {
  274. auto point = std::stable_partition(
  275. std::begin(reqs_),
  276. std::end(reqs_),
  277. [](const std::shared_ptr<elem>& ptr) {
  278. return !(ptr->is_written() && ptr->get_remaining_responses() == 0u);
  279. });
  280. std::for_each(point, std::end(reqs_), [](auto const& ptr) {
  281. ptr->notify_done();
  282. });
  283. reqs_.erase(point, std::end(reqs_));
  284. }
  285. void multiplexer::set_receive_adapter(any_adapter adapter)
  286. {
  287. receive_adapter_ = std::move(adapter);
  288. }
  289. void multiplexer::set_config(config const& cfg)
  290. {
  291. read_buffer_.set_config({cfg.read_buffer_append_size, cfg.max_read_size});
  292. }
  293. auto make_elem(request const& req, any_adapter adapter) -> std::shared_ptr<multiplexer::elem>
  294. {
  295. return std::make_shared<multiplexer::elem>(req, std::move(adapter));
  296. }
  297. } // namespace boost::redis::detail