writer_fsm.hpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. //
  2. // Copyright (c) 2025 Marcelo Zimbres Silva (mzimbres@gmail.com),
  3. // Ruben Perez Hidalgo (rubenperez038 at gmail dot com)
  4. //
  5. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  6. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  7. //
  8. #ifndef BOOST_REDIS_WRITER_FSM_HPP
  9. #define BOOST_REDIS_WRITER_FSM_HPP
  10. #include <boost/asio/cancellation_type.hpp>
  11. #include <boost/assert.hpp>
  12. #include <boost/system/error_code.hpp>
  13. #include <chrono>
  14. #include <cstddef>
  15. // Sans-io algorithm for the writer task, as a finite state machine
  16. namespace boost::redis::detail {
  17. // Forward decls
  18. struct connection_state;
  19. // What should we do next?
  20. enum class writer_action_type
  21. {
  22. done, // Call the final handler
  23. write_some, // Issue a write on the stream
  24. wait, // Wait until there is data to be written
  25. };
  26. class writer_action {
  27. writer_action_type type_;
  28. union {
  29. system::error_code ec_;
  30. std::chrono::steady_clock::duration timeout_;
  31. };
  32. writer_action(writer_action_type type, std::chrono::steady_clock::duration t) noexcept
  33. : type_{type}
  34. , timeout_{t}
  35. { }
  36. public:
  37. writer_action_type type() const { return type_; }
  38. writer_action(system::error_code ec) noexcept
  39. : type_{writer_action_type::done}
  40. , ec_{ec}
  41. { }
  42. static writer_action write_some(std::chrono::steady_clock::duration timeout)
  43. {
  44. return {writer_action_type::write_some, timeout};
  45. }
  46. static writer_action wait(std::chrono::steady_clock::duration timeout)
  47. {
  48. return {writer_action_type::wait, timeout};
  49. }
  50. system::error_code error() const
  51. {
  52. BOOST_ASSERT(type_ == writer_action_type::done);
  53. return ec_;
  54. }
  55. std::chrono::steady_clock::duration timeout() const
  56. {
  57. BOOST_ASSERT(type_ == writer_action_type::write_some || type_ == writer_action_type::wait);
  58. return timeout_;
  59. }
  60. };
  61. class writer_fsm {
  62. int resume_point_{0};
  63. public:
  64. writer_fsm() = default;
  65. writer_action resume(
  66. connection_state& st,
  67. system::error_code ec,
  68. std::size_t bytes_written,
  69. asio::cancellation_type_t cancel_state);
  70. };
  71. } // namespace boost::redis::detail
  72. #endif // BOOST_REDIS_CONNECTOR_HPP