mqtt_message_router.hpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. /*
  2. * Copyright (c) 2017-2023 zhllxt
  3. *
  4. * author : zhllxt
  5. * email : 37792738@qq.com
  6. *
  7. * Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. */
  10. #ifndef __ASIO2_MQTT_MESSAGE_ROUTER_HPP__
  11. #define __ASIO2_MQTT_MESSAGE_ROUTER_HPP__
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. #pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include <optional>
  16. #include <asio2/base/iopool.hpp>
  17. #include <asio2/base/define.hpp>
  18. #include <asio2/base/detail/function_traits.hpp>
  19. #include <asio2/base/detail/util.hpp>
  20. #include <asio2/base/detail/shared_mutex.hpp>
  21. #include <asio2/mqtt/detail/mqtt_topic_util.hpp>
  22. #include <asio2/mqtt/message.hpp>
  23. namespace asio2::detail
  24. {
  25. ASIO2_CLASS_FORWARD_DECLARE_BASE;
  26. ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
  27. ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
  28. ASIO2_CLASS_FORWARD_DECLARE_TCP_SESSION;
  29. ASIO2_CLASS_FORWARD_DECLARE_TCP_CLIENT;
  30. /**
  31. * used for:
  32. *
  33. * bool ret = client.subscribe("/usr/topic1", 0, [](mqtt::message& msg){});
  34. * util recvd the suback message, then the ret is true.
  35. *
  36. * bool ret = client.publish("/usr/topic1", "...payload...", 0);
  37. * util recvd the puback message, then the ret is true.
  38. *
  39. * and so on...
  40. */
  41. template<class derived_t, class args_t>
  42. class mqtt_message_router_t
  43. {
  44. friend derived_t;
  45. ASIO2_CLASS_FRIEND_DECLARE_BASE;
  46. ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
  47. ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
  48. ASIO2_CLASS_FRIEND_DECLARE_TCP_SESSION;
  49. ASIO2_CLASS_FRIEND_DECLARE_TCP_CLIENT;
  50. public:
  51. using self = mqtt_message_router_t<derived_t, args_t>;
  52. using args_type = args_t;
  53. using subnode_type = typename args_type::template subnode<derived_t>;
  54. using key_type = std::pair<mqtt::control_packet_type, mqtt::two_byte_integer::value_type>;
  55. using val_type = detail::function<void(mqtt::message&)>;
  56. struct hasher
  57. {
  58. inline std::size_t operator()(key_type const& pair) const noexcept
  59. {
  60. std::size_t v = detail::fnv1a_hash<std::size_t>(
  61. (const unsigned char*)(std::addressof(pair.first)), sizeof(pair.first));
  62. return detail::fnv1a_hash<std::size_t>(v,
  63. (const unsigned char*)(std::addressof(pair.second)), sizeof(pair.second));
  64. }
  65. };
  66. /**
  67. * @brief constructor
  68. */
  69. mqtt_message_router_t() = default;
  70. /**
  71. * @brief destructor
  72. */
  73. ~mqtt_message_router_t() = default;
  74. protected:
  75. template<class FunctionT>
  76. inline bool _add_router(mqtt::message& msg, FunctionT&& callback)
  77. {
  78. derived_t& derive = static_cast<derived_t&>(*this);
  79. bool r = false;
  80. std::visit([&derive, &callback, &r](auto& m) mutable
  81. {
  82. r = derive._add_router(m, std::forward<FunctionT>(callback));
  83. }, msg.base());
  84. return r;
  85. }
  86. template<class Message, class FunctionT>
  87. typename std::enable_if_t<mqtt::is_rawmsg<Message>(), bool>
  88. inline _add_router(Message& msg, FunctionT&& callback)
  89. {
  90. derived_t& derive = static_cast<derived_t&>(*this);
  91. using message_type = typename detail::remove_cvref_t<Message>;
  92. if constexpr (!mqtt::has_packet_id<message_type>::value)
  93. {
  94. static_assert(detail::always_false_v<Message> && "This mqtt message don't has Packet Identifier");
  95. return false;
  96. }
  97. else
  98. {
  99. ASIO2_ASSERT(
  100. msg.packet_type() >= mqtt::control_packet_type::connect &&
  101. msg.packet_type() <= mqtt::control_packet_type::auth);
  102. if (!(
  103. msg.packet_type() >= mqtt::control_packet_type::connect &&
  104. msg.packet_type() <= mqtt::control_packet_type::auth))
  105. {
  106. return false;
  107. }
  108. key_type key = { msg.packet_type(), msg.packet_id() };
  109. return derive._add_router(std::move(key), std::forward<FunctionT>(callback));
  110. }
  111. }
  112. template<class FunctionT>
  113. inline bool _add_router(key_type key, FunctionT&& callback)
  114. {
  115. derived_t& derive = static_cast<derived_t&>(*this);
  116. derive.dispatch([&derive, key, cb = std::forward<FunctionT>(callback)]() mutable
  117. {
  118. derive._do_add_router(std::move(key), std::move(cb));
  119. });
  120. return true;
  121. }
  122. template<class FunctionT>
  123. inline bool _do_add_router(key_type key, FunctionT&& callback)
  124. {
  125. using fun_traits_type = function_traits<FunctionT>;
  126. using arg0_type = typename std::remove_cv_t<std::remove_reference_t<
  127. typename fun_traits_type::template args<0>::type>>;
  128. asio2::unique_locker g(this->message_router_mutex_);
  129. if constexpr (std::is_same_v<arg0_type, mqtt::message>)
  130. {
  131. auto[_1, inserted] = this->message_router_.insert_or_assign(std::move(key),
  132. std::forward<FunctionT>(callback));
  133. ASIO2_ASSERT(inserted);
  134. asio2::ignore_unused(_1, inserted);
  135. }
  136. else
  137. {
  138. auto[_1, inserted] = this->message_router_.insert_or_assign(std::move(key),
  139. [cb = std::forward<FunctionT>(callback)](mqtt::message& msg) mutable
  140. {
  141. arg0_type* p = std::get_if<arg0_type>(std::addressof(msg.base()));
  142. if (p)
  143. {
  144. cb(*p);
  145. }
  146. });
  147. ASIO2_ASSERT(inserted);
  148. asio2::ignore_unused(_1, inserted);
  149. }
  150. return true;
  151. }
  152. inline void _del_router(mqtt::message& msg)
  153. {
  154. derived_t& derive = static_cast<derived_t&>(*this);
  155. std::visit([&derive](auto& m) mutable
  156. {
  157. derive._del_router(m);
  158. }, msg.base());
  159. }
  160. template<class Message>
  161. typename std::enable_if_t<mqtt::is_rawmsg<Message>(), void>
  162. inline _del_router(Message& msg)
  163. {
  164. derived_t& derive = static_cast<derived_t&>(*this);
  165. using message_type = typename detail::remove_cvref_t<Message>;
  166. if constexpr (!mqtt::has_packet_id<message_type>::value)
  167. {
  168. static_assert(detail::always_false_v<Message> && "This mqtt message don't has Packet Identifier");
  169. return;
  170. }
  171. else
  172. {
  173. ASIO2_ASSERT(
  174. msg.packet_type() >= mqtt::control_packet_type::connect &&
  175. msg.packet_type() <= mqtt::control_packet_type::auth);
  176. if (!(
  177. msg.packet_type() >= mqtt::control_packet_type::connect &&
  178. msg.packet_type() <= mqtt::control_packet_type::auth))
  179. {
  180. return;
  181. }
  182. key_type key = { msg.packet_type(), msg.packet_id() };
  183. derive._del_router(std::move(key));
  184. }
  185. }
  186. inline void _del_router(key_type key)
  187. {
  188. derived_t& derive = static_cast<derived_t&>(*this);
  189. derive.dispatch([this, key = std::move(key)]() mutable
  190. {
  191. asio2::unique_locker g(this->message_router_mutex_);
  192. this->message_router_.erase(key);
  193. });
  194. }
  195. inline bool _match_router(mqtt::message& msg)
  196. {
  197. derived_t& derive = static_cast<derived_t&>(*this);
  198. std::optional<key_type> key = derive._generate_key(msg);
  199. if (!key.has_value())
  200. return false;
  201. return derive._call_router(key.value(), msg);
  202. }
  203. inline bool _call_router(key_type key, mqtt::message& msg)
  204. {
  205. derived_t& derive = static_cast<derived_t&>(*this);
  206. derive.dispatch([this, msg, key = std::move(key)]() mutable
  207. {
  208. asio2::unique_locker g(this->message_router_mutex_);
  209. auto it = this->message_router_.find(key);
  210. if (it == this->message_router_.end())
  211. return;
  212. (it->second)(msg);
  213. this->message_router_.erase(it);
  214. });
  215. return true;
  216. }
  217. inline std::optional<key_type> _generate_key(mqtt::message& msg)
  218. {
  219. derived_t& derive = static_cast<derived_t&>(*this);
  220. std::optional<key_type> r;
  221. std::visit([&derive, &r](auto& m) mutable
  222. {
  223. r = derive._generate_key(m);
  224. }, msg.base());
  225. return r;
  226. }
  227. template<class Message>
  228. typename std::enable_if_t<mqtt::is_rawmsg<Message>(), std::optional<key_type>>
  229. inline _generate_key(Message& msg)
  230. {
  231. using message_type = typename detail::remove_cvref_t<Message>;
  232. if constexpr (!mqtt::has_packet_id<message_type>::value)
  233. {
  234. return std::nullopt;
  235. }
  236. else
  237. {
  238. ASIO2_ASSERT(
  239. msg.packet_type() >= mqtt::control_packet_type::connect &&
  240. msg.packet_type() <= mqtt::control_packet_type::auth);
  241. if (!(
  242. msg.packet_type() >= mqtt::control_packet_type::connect &&
  243. msg.packet_type() <= mqtt::control_packet_type::auth))
  244. {
  245. return std::nullopt;
  246. }
  247. std::optional<key_type> key;
  248. if /**/ constexpr (mqtt::is_puback_message<message_type>())
  249. {
  250. key = { mqtt::control_packet_type::publish, msg.packet_id() };
  251. }
  252. else if constexpr (mqtt::is_pubcomp_message<message_type>())
  253. {
  254. key = { mqtt::control_packet_type::publish, msg.packet_id() };
  255. }
  256. else if constexpr (mqtt::is_suback_message<message_type>())
  257. {
  258. key = { mqtt::control_packet_type::subscribe, msg.packet_id() };
  259. }
  260. else if constexpr (mqtt::is_unsuback_message<message_type>())
  261. {
  262. key = { mqtt::control_packet_type::unsubscribe, msg.packet_id() };
  263. }
  264. else
  265. {
  266. return std::nullopt;
  267. }
  268. return key;
  269. }
  270. }
  271. protected:
  272. /// use rwlock to make thread safe
  273. mutable asio2::shared_mutexer message_router_mutex_;
  274. /// router map, key - pair<mqtt::control_packet_type, packet id>
  275. std::unordered_map<key_type, val_type, hasher> message_router_ ASIO2_GUARDED_BY(message_router_mutex_);
  276. };
  277. }
  278. #endif // !__ASIO2_MQTT_MESSAGE_ROUTER_HPP__