mqtt_subscribe_router.hpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  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_SUBSCRIBE_ROUTER_HPP__
  11. #define __ASIO2_MQTT_SUBSCRIBE_ROUTER_HPP__
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. #pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include <asio2/mqtt/detail/mqtt_message_router.hpp>
  16. namespace asio2::detail
  17. {
  18. ASIO2_CLASS_FORWARD_DECLARE_BASE;
  19. ASIO2_CLASS_FORWARD_DECLARE_TCP_BASE;
  20. ASIO2_CLASS_FORWARD_DECLARE_TCP_SERVER;
  21. ASIO2_CLASS_FORWARD_DECLARE_TCP_SESSION;
  22. ASIO2_CLASS_FORWARD_DECLARE_TCP_CLIENT;
  23. template<class derived_t, class args_t>
  24. class mqtt_subscribe_router_t
  25. {
  26. friend derived_t;
  27. ASIO2_CLASS_FRIEND_DECLARE_BASE;
  28. ASIO2_CLASS_FRIEND_DECLARE_TCP_BASE;
  29. ASIO2_CLASS_FRIEND_DECLARE_TCP_SERVER;
  30. ASIO2_CLASS_FRIEND_DECLARE_TCP_SESSION;
  31. ASIO2_CLASS_FRIEND_DECLARE_TCP_CLIENT;
  32. public:
  33. using self = mqtt_subscribe_router_t<derived_t, args_t>;
  34. using args_type = args_t;
  35. using subnode_type = typename args_type::template subnode<derived_t>;
  36. using key_type = typename mqtt_message_router_t<derived_t, args_t>::key_type;
  37. struct hasher
  38. {
  39. inline std::size_t operator()(key_type const& pair) const noexcept
  40. {
  41. std::size_t v = asio2::detail::fnv1a_hash<std::size_t>(
  42. (const unsigned char*)(std::addressof(pair.first)), sizeof(pair.first));
  43. return asio2::detail::fnv1a_hash<std::size_t>(v,
  44. (const unsigned char*)(std::addressof(pair.second)), sizeof(pair.second));
  45. }
  46. };
  47. /**
  48. * @brief constructor
  49. */
  50. mqtt_subscribe_router_t() = default;
  51. /**
  52. * @brief destructor
  53. */
  54. ~mqtt_subscribe_router_t() = default;
  55. template<class ReturnT = void, class QosOrInt, class FunctionT>
  56. typename std::enable_if_t<
  57. std::is_same_v<detail::remove_cvref_t<QosOrInt>, mqtt::qos_type> ||
  58. std::is_integral_v<detail::remove_cvref_t<QosOrInt>>, ReturnT>
  59. subscribe(std::string topic_filter, QosOrInt qos, FunctionT&& callback)
  60. {
  61. derived_t& derive = static_cast<derived_t&>(*this);
  62. mqtt::version ver = derive.version();
  63. auto pid = derive.idmgr_.get();
  64. if /**/ (ver == mqtt::version::v3)
  65. {
  66. mqtt::v3::subscribe msg;
  67. msg.packet_id(pid);
  68. msg.add_subscriptions(mqtt::subscription(std::move(topic_filter), qos));
  69. return this->subscribe<ReturnT>(std::move(msg), std::forward<FunctionT>(callback));
  70. }
  71. else if (ver == mqtt::version::v4)
  72. {
  73. mqtt::v4::subscribe msg;
  74. msg.packet_id(pid);
  75. msg.add_subscriptions(mqtt::subscription(std::move(topic_filter), qos));
  76. return this->subscribe<ReturnT>(std::move(msg), std::forward<FunctionT>(callback));
  77. }
  78. else if (ver == mqtt::version::v5)
  79. {
  80. mqtt::v5::subscribe msg;
  81. msg.packet_id(pid);
  82. msg.add_subscriptions(mqtt::subscription(std::move(topic_filter), qos));
  83. return this->subscribe<ReturnT>(std::move(msg), std::forward<FunctionT>(callback));
  84. }
  85. else
  86. {
  87. derive.idmgr_.release(pid);
  88. set_last_error(asio::error::invalid_argument);
  89. ASIO2_ASSERT(false);
  90. return derive.template _empty_result<ReturnT>();
  91. }
  92. }
  93. template<class ReturnT = void, class Message, class FunctionT>
  94. typename std::enable_if_t<
  95. std::is_same_v<detail::remove_cvref_t<Message>, mqtt::v3::subscribe> ||
  96. std::is_same_v<detail::remove_cvref_t<Message>, mqtt::v4::subscribe> ||
  97. std::is_same_v<detail::remove_cvref_t<Message>, mqtt::v5::subscribe>, ReturnT>
  98. subscribe(Message&& msg, FunctionT&& callback)
  99. {
  100. derived_t& derive = static_cast<derived_t&>(*this);
  101. if (!derive.is_started())
  102. {
  103. set_last_error(asio::error::not_connected);
  104. ASIO2_ASSERT(false);
  105. return derive.template _empty_result<ReturnT>();
  106. }
  107. if (msg.subscriptions().data().empty())
  108. {
  109. set_last_error(asio::error::invalid_argument);
  110. ASIO2_ASSERT(false);
  111. return derive.template _empty_result<ReturnT>();
  112. }
  113. for (mqtt::subscription& sub : msg.subscriptions().data())
  114. {
  115. if (!mqtt::is_valid_qos(sub.qos()))
  116. {
  117. set_last_error(asio::error::invalid_argument);
  118. ASIO2_ASSERT(false);
  119. return derive.template _empty_result<ReturnT>();
  120. }
  121. }
  122. clear_last_error();
  123. [[maybe_unused]] key_type key = { msg.packet_type(), msg.packet_id() };
  124. derive._dispatch_subscribe(std::forward<Message>(msg), std::forward<FunctionT>(callback));
  125. if (derive.io_->running_in_this_thread())
  126. {
  127. return derive.template _in_progress<ReturnT>();
  128. }
  129. ASIO2_ASSERT(!derive.io_->running_in_this_thread());
  130. if /**/ constexpr (std::is_same_v<ReturnT, void>)
  131. {
  132. return;
  133. }
  134. else if constexpr (std::is_same_v<ReturnT, bool>)
  135. {
  136. return derive._do_router(key, [](auto& msg) mutable
  137. {
  138. if constexpr (mqtt::is_suback_message<decltype(msg)>())
  139. {
  140. for (auto&& reason : msg.reason_codes().data())
  141. {
  142. if (!mqtt::is_valid_qos(reason.value()))
  143. {
  144. return false;
  145. }
  146. }
  147. return true;
  148. }
  149. else
  150. {
  151. return false;
  152. }
  153. });
  154. }
  155. else if constexpr (std::is_same_v<ReturnT, mqtt::message>)
  156. {
  157. return derive._do_router(key);
  158. }
  159. else
  160. {
  161. static_assert(detail::always_false_v<ReturnT>);
  162. }
  163. }
  164. template<class ReturnT = void>
  165. ReturnT unsubscribe(std::string topic_filter)
  166. {
  167. derived_t& derive = static_cast<derived_t&>(*this);
  168. mqtt::version ver = derive.version();
  169. auto pid = derive.idmgr_.get();
  170. if /**/ (ver == mqtt::version::v3)
  171. {
  172. return this->unsubscribe<ReturnT>(mqtt::v3::unsubscribe(pid, std::move(topic_filter)));
  173. }
  174. else if (ver == mqtt::version::v4)
  175. {
  176. return this->unsubscribe<ReturnT>(mqtt::v4::unsubscribe(pid, std::move(topic_filter)));
  177. }
  178. else if (ver == mqtt::version::v5)
  179. {
  180. return this->unsubscribe<ReturnT>(mqtt::v5::unsubscribe(pid, std::move(topic_filter)));
  181. }
  182. else
  183. {
  184. derive.idmgr_.release(pid);
  185. set_last_error(asio::error::invalid_argument);
  186. ASIO2_ASSERT(false);
  187. return derive.template _empty_result<ReturnT>();
  188. }
  189. }
  190. template<class ReturnT = void, class Message>
  191. typename std::enable_if_t<
  192. std::is_same_v<detail::remove_cvref_t<Message>, mqtt::v3::unsubscribe> ||
  193. std::is_same_v<detail::remove_cvref_t<Message>, mqtt::v4::unsubscribe> ||
  194. std::is_same_v<detail::remove_cvref_t<Message>, mqtt::v5::unsubscribe>, ReturnT>
  195. unsubscribe(Message&& msg)
  196. {
  197. derived_t& derive = static_cast<derived_t&>(*this);
  198. if (!derive.is_started())
  199. {
  200. set_last_error(asio::error::not_connected);
  201. ASIO2_ASSERT(false);
  202. return derive.template _empty_result<ReturnT>();
  203. }
  204. if (msg.topic_filters().data().empty())
  205. {
  206. set_last_error(asio::error::invalid_argument);
  207. ASIO2_ASSERT(false);
  208. return derive.template _empty_result<ReturnT>();
  209. }
  210. clear_last_error();
  211. [[maybe_unused]] key_type key = { msg.packet_type(), msg.packet_id() };
  212. // must ensure the member variable is read write in the io_context thread.
  213. // save the subscribed key and topic filters, beacuse if the unsubscribed
  214. // is sucussed, we need remove the topics from the sub map.
  215. derive.dispatch([&derive, key, topics = msg.topic_filters()]() mutable
  216. {
  217. if (derive.subs_map().get_subscribe_count() > 0)
  218. derive.unsubscribed_topics_.emplace(key, std::move(topics));
  219. });
  220. derive.async_send(std::forward<Message>(msg), [&derive, key]() mutable
  221. {
  222. // if send data failed, we need remove the added key and topics from the map.
  223. if (asio2::get_last_error())
  224. {
  225. derive.unsubscribed_topics_.erase(key);
  226. }
  227. });
  228. if (derive.io_->running_in_this_thread())
  229. {
  230. return derive.template _in_progress<ReturnT>();
  231. }
  232. ASIO2_ASSERT(!derive.io_->running_in_this_thread());
  233. if /**/ constexpr (std::is_same_v<ReturnT, void>)
  234. {
  235. return;
  236. }
  237. else if constexpr (std::is_same_v<ReturnT, bool>)
  238. {
  239. return derive._do_router(key, [](auto& msg) mutable
  240. {
  241. if constexpr (mqtt::is_unsuback_message<decltype(msg)>())
  242. {
  243. // UNSUBACK Payload : The Payload contains a list of Reason Codes.
  244. // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901194
  245. if constexpr (std::is_same_v<detail::remove_cvref_t<decltype(msg)>, mqtt::v5::unsuback>)
  246. {
  247. for (auto&& reason : msg.reason_codes().data())
  248. {
  249. mqtt::error e = static_cast<mqtt::error>(reason.value());
  250. if (!(e == mqtt::error::success || e == mqtt::error::no_subscription_existed))
  251. {
  252. return false;
  253. }
  254. }
  255. return true;
  256. }
  257. else
  258. {
  259. return true;
  260. }
  261. }
  262. else
  263. {
  264. return false;
  265. }
  266. });
  267. }
  268. else if constexpr (std::is_same_v<ReturnT, mqtt::message>)
  269. {
  270. return derive._do_router(key);
  271. }
  272. else
  273. {
  274. static_assert(detail::always_false_v<ReturnT>);
  275. }
  276. }
  277. template<class ReturnT = void, class QosOrInt>
  278. ReturnT publish(std::string topic_name, std::string payload, QosOrInt qos)
  279. {
  280. derived_t& derive = static_cast<derived_t&>(*this);
  281. mqtt::version ver = derive.version();
  282. if /**/ (ver == mqtt::version::v3)
  283. {
  284. return this->publish<ReturnT>(mqtt::v3::publish(std::move(topic_name), std::move(payload), qos));
  285. }
  286. else if (ver == mqtt::version::v4)
  287. {
  288. return this->publish<ReturnT>(mqtt::v4::publish(std::move(topic_name), std::move(payload), qos));
  289. }
  290. else if (ver == mqtt::version::v5)
  291. {
  292. return this->publish<ReturnT>(mqtt::v5::publish(std::move(topic_name), std::move(payload), qos));
  293. }
  294. else
  295. {
  296. set_last_error(asio::error::invalid_argument);
  297. ASIO2_ASSERT(false);
  298. return derive.template _empty_result<ReturnT>();
  299. }
  300. }
  301. template<class ReturnT = void, class Message>
  302. typename std::enable_if_t<
  303. std::is_same_v<detail::remove_cvref_t<Message>, mqtt::v3::publish> ||
  304. std::is_same_v<detail::remove_cvref_t<Message>, mqtt::v4::publish> ||
  305. std::is_same_v<detail::remove_cvref_t<Message>, mqtt::v5::publish>, ReturnT>
  306. publish(Message&& msg)
  307. {
  308. derived_t& derive = static_cast<derived_t&>(*this);
  309. if (!derive.is_started())
  310. {
  311. set_last_error(asio::error::not_connected);
  312. ASIO2_ASSERT(false);
  313. return derive.template _empty_result<ReturnT>();
  314. }
  315. if (msg.qos() > mqtt::qos_type::at_most_once && !msg.has_packet_id())
  316. {
  317. msg.packet_id(derive.idmgr_.get());
  318. }
  319. clear_last_error();
  320. [[maybe_unused]] std::optional<key_type> key{};
  321. if (msg.qos() > mqtt::qos_type::at_most_once && msg.has_packet_id())
  322. key = { msg.packet_type(), msg.packet_id() };
  323. derive.async_send(std::forward<Message>(msg));
  324. // qos 0 don't need a response
  325. if (!key.has_value())
  326. {
  327. return derive.template _empty_result<ReturnT>();
  328. }
  329. if (derive.io_->running_in_this_thread())
  330. {
  331. return derive.template _in_progress<ReturnT>();
  332. }
  333. ASIO2_ASSERT(!derive.io_->running_in_this_thread());
  334. if /**/ constexpr (std::is_same_v<ReturnT, void>)
  335. {
  336. return;
  337. }
  338. else if constexpr (std::is_same_v<ReturnT, bool>)
  339. {
  340. return derive._do_bool_publish(key);
  341. }
  342. else if constexpr (std::is_same_v<ReturnT, mqtt::message>)
  343. {
  344. return derive._do_router(key.value());
  345. }
  346. else
  347. {
  348. static_assert(detail::always_false_v<ReturnT>);
  349. }
  350. }
  351. protected:
  352. template<class K>
  353. bool _do_bool_publish(std::optional<K>& key)
  354. {
  355. derived_t& derive = static_cast<derived_t&>(*this);
  356. return derive._do_router(key.value(), [](auto& msg) mutable
  357. {
  358. // qos 1 response
  359. if constexpr (mqtt::is_puback_message<decltype(msg)>())
  360. {
  361. if constexpr (std::is_same_v<detail::remove_cvref_t<decltype(msg)>, mqtt::v5::puback>)
  362. {
  363. mqtt::error e = static_cast<mqtt::error>(msg.reason_code());
  364. if (!(e == mqtt::error::success))
  365. {
  366. return false;
  367. }
  368. return true;
  369. }
  370. else
  371. {
  372. return true;
  373. }
  374. }
  375. else if constexpr (mqtt::is_pubcomp_message<decltype(msg)>())
  376. {
  377. if constexpr (std::is_same_v<detail::remove_cvref_t<decltype(msg)>, mqtt::v5::pubcomp>)
  378. {
  379. mqtt::error e = static_cast<mqtt::error>(msg.reason_code());
  380. if (!(e == mqtt::error::success))
  381. {
  382. return false;
  383. }
  384. return true;
  385. }
  386. else
  387. {
  388. return true;
  389. }
  390. }
  391. else
  392. {
  393. return false;
  394. }
  395. });
  396. }
  397. template<class ReturnT>
  398. inline ReturnT _empty_result()
  399. {
  400. if constexpr (std::is_same_v<ReturnT, void>)
  401. {
  402. return;
  403. }
  404. else
  405. {
  406. return ReturnT{};
  407. }
  408. }
  409. template<class ReturnT>
  410. inline ReturnT _in_progress()
  411. {
  412. if /**/ constexpr (std::is_same_v<ReturnT, void>)
  413. {
  414. set_last_error(asio::error::in_progress);
  415. return;
  416. }
  417. else if constexpr (std::is_same_v<ReturnT, bool>)
  418. {
  419. set_last_error(asio::error::in_progress);
  420. return true;
  421. }
  422. else if constexpr (std::is_same_v<ReturnT, mqtt::message>)
  423. {
  424. set_last_error(asio::error::in_progress);
  425. return mqtt::message{};
  426. }
  427. else
  428. {
  429. static_assert(detail::always_false_v<ReturnT>);
  430. }
  431. }
  432. /**
  433. * callback signature : bool (auto& msg)
  434. */
  435. template<class KeyT, class FunctionT>
  436. bool _do_router(KeyT key, FunctionT&& callback)
  437. {
  438. derived_t& derive = static_cast<derived_t&>(*this);
  439. std::promise<bool> p;
  440. std::future<bool> f = p.get_future();
  441. derive._add_router(key, [&callback, p = std::move(p)](mqtt::message& m) mutable
  442. {
  443. std::visit([&callback, &p](auto& msg) mutable
  444. {
  445. p.set_value(callback(msg));
  446. }, m.base());
  447. });
  448. std::future_status status = f.wait_for(derive.get_default_timeout());
  449. if (status == std::future_status::ready)
  450. {
  451. derive._del_router(key);
  452. return true;
  453. }
  454. set_last_error(asio::error::timed_out);
  455. derive._del_router(key);
  456. return false;
  457. }
  458. template<class KeyT>
  459. mqtt::message _do_router(KeyT key)
  460. {
  461. derived_t& derive = static_cast<derived_t&>(*this);
  462. std::shared_ptr<mqtt::message> r = std::make_shared<mqtt::message>();
  463. std::promise<void> p;
  464. std::future<void> f = p.get_future();
  465. derive._add_router(key, [r, p = std::move(p)](mqtt::message& m) mutable
  466. {
  467. *r = m;
  468. p.set_value();
  469. });
  470. std::future_status status = f.wait_for(derive.get_default_timeout());
  471. if (status == std::future_status::ready)
  472. {
  473. derive._del_router(key);
  474. return std::move(*r);
  475. }
  476. set_last_error(asio::error::timed_out);
  477. derive._del_router(key);
  478. return mqtt::message{};
  479. }
  480. template<class Message, class FunctionT>
  481. inline void _dispatch_subscribe(Message&& msg, FunctionT&& callback)
  482. {
  483. derived_t& derive = static_cast<derived_t&>(*this);
  484. derive.dispatch(
  485. [&derive, msg = std::forward<Message>(msg), cb = std::forward<FunctionT>(callback)]() mutable
  486. {
  487. derive._do_subscribe(std::move(msg), std::move(cb));
  488. });
  489. }
  490. template<class Message, class FunctionT>
  491. void _do_subscribe(Message&& msg, FunctionT&& callback)
  492. {
  493. using message_type = typename detail::remove_cvref_t<Message>;
  494. using fun_traits_type = function_traits<FunctionT>;
  495. using arg0_type = typename std::remove_cv_t<std::remove_reference_t<
  496. typename fun_traits_type::template args<0>::type>>;
  497. derived_t& derive = static_cast<derived_t&>(*this);
  498. ASIO2_ASSERT(derive.io_->running_in_this_thread());
  499. mqtt::v5::properties_set props;
  500. if constexpr (std::is_same_v<message_type, mqtt::v5::subscribe>)
  501. {
  502. props = msg.properties();
  503. }
  504. else
  505. {
  506. std::ignore = true;
  507. }
  508. std::vector<mqtt::subscription>& subs = msg.subscriptions().data();
  509. for (std::size_t i = 0; i < subs.size(); ++i)
  510. {
  511. mqtt::subscription& sub = subs[i];
  512. bool end = (i + 1 == subs.size());
  513. subnode_type node{ derive.selfptr(), sub, end ? std::move(props) : props };
  514. if constexpr (std::is_same_v<arg0_type, mqtt::message>)
  515. {
  516. node.callback = end ? std::forward<FunctionT>(callback) : callback;
  517. }
  518. else
  519. {
  520. node.callback = [cb = end ? std::forward<FunctionT>(callback) : callback]
  521. (mqtt::message& msg) mutable
  522. {
  523. arg0_type* p = std::get_if<arg0_type>(std::addressof(msg.base()));
  524. if (p)
  525. {
  526. cb(*p);
  527. }
  528. };
  529. }
  530. std::string_view share_name = node.share_name();
  531. std::string_view topic_filter = node.topic_filter();
  532. auto[_1, inserted] = this->subs_map().insert_or_assign(topic_filter, "", std::move(node));
  533. asio2::ignore_unused(share_name, topic_filter, _1, inserted);
  534. }
  535. derive.async_send(std::forward<Message>(msg));
  536. }
  537. inline mqtt::subscription_map<std::string_view, subnode_type>& subs_map() { return subs_map_; }
  538. protected:
  539. /// subscription information map
  540. mqtt::subscription_map<std::string_view, subnode_type> subs_map_;
  541. /// don't need mutex, beacuse client only has one thread, we use post to ensure this
  542. /// variable was read write in the client io_context thread.
  543. std::unordered_map<key_type, mqtt::utf8_string_set, hasher> unsubscribed_topics_;
  544. };
  545. }
  546. #endif // !__ASIO2_MQTT_SUBSCRIBE_ROUTER_HPP__