mqtt_retained_message.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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. * refrenced from : mqtt_cpp/include/mqtt/broker/retained_messages.hpp
  11. */
  12. #ifndef __ASIO2_MQTT_RETAINED_MESSAGES_HPP__
  13. #define __ASIO2_MQTT_RETAINED_MESSAGES_HPP__
  14. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #pragma once
  16. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  17. #include <cstdint>
  18. #include <string>
  19. #include <string_view>
  20. #include <type_traits>
  21. #include <unordered_map>
  22. #include <algorithm>
  23. #include <optional>
  24. #include <deque>
  25. #include <asio2/base/detail/shared_mutex.hpp>
  26. #include <asio2/mqtt/message.hpp>
  27. #include <asio2/mqtt/detail/mqtt_topic_util.hpp>
  28. namespace asio2::mqtt
  29. {
  30. template<typename Value>
  31. class retained_messages
  32. {
  33. public:
  34. using key_type = std::pair<std::size_t, std::string_view>;
  35. struct hasher
  36. {
  37. inline std::size_t operator()(key_type const& pair) const noexcept
  38. {
  39. std::size_t v = asio2::detail::fnv1a_hash<std::size_t>(
  40. (const unsigned char*)(std::addressof(pair.first)), sizeof(std::size_t));
  41. return asio2::detail::fnv1a_hash<std::size_t>(v,
  42. (const unsigned char*)(pair.second.data()), pair.second.size());
  43. }
  44. };
  45. protected:
  46. // Exceptions used
  47. static void throw_max_stored_topics()
  48. {
  49. throw std::overflow_error("Retained map maximum number of topics reached");
  50. }
  51. static void throw_no_wildcards_allowed()
  52. {
  53. throw std::runtime_error("Retained map no wildcards allowed in retained topic name");
  54. }
  55. static constexpr std::size_t root_parent_id = 0;
  56. static constexpr std::size_t root_node_id = 1;
  57. static constexpr std::size_t max_node_id = (std::numeric_limits<std::size_t>::max)();
  58. struct path_entry
  59. {
  60. std::size_t parent_id;
  61. std::string_view name;
  62. std::size_t id;
  63. std::size_t count = 1;
  64. static constexpr std::size_t max_count = (std::numeric_limits<std::size_t>::max)();
  65. // Increase the count for this node
  66. inline void increase_count()
  67. {
  68. if (count == max_count)
  69. {
  70. throw_max_stored_topics();
  71. }
  72. ++count;
  73. }
  74. // Decrease the count for this node
  75. inline void decrease_count()
  76. {
  77. ASIO2_ASSERT(count >= 1);
  78. --count;
  79. }
  80. std::optional<Value> value;
  81. path_entry(std::size_t parent_id, std::string_view name, std::size_t id)
  82. : parent_id(parent_id)
  83. , name(name)
  84. , id(id)
  85. { }
  86. };
  87. using map_type = std::unordered_map<key_type, path_entry, hasher>;
  88. using map_iterator = typename map_type::iterator;
  89. using map_const_iterator = typename map_type::const_iterator;
  90. /// use rwlock to make thread safe
  91. mutable asio2::shared_mutexer retained_mutex_;
  92. std::unordered_map <key_type, path_entry, hasher> map_ ASIO2_GUARDED_BY(retained_mutex_);
  93. std::unordered_multimap<std::size_t, path_entry* > wildcard_map_ ASIO2_GUARDED_BY(retained_mutex_);
  94. std::size_t map_size ASIO2_GUARDED_BY(retained_mutex_);
  95. std::size_t next_node_id ASIO2_GUARDED_BY(retained_mutex_);
  96. inline map_iterator create_topic(std::string_view topic_name) ASIO2_NO_THREAD_SAFETY_ANALYSIS
  97. {
  98. map_iterator parent = get_root();
  99. topic_filter_tokenizer(topic_name, [this, &parent](std::string_view t) mutable
  100. {
  101. return this->create_topic_subfun(parent, t);
  102. });
  103. return parent;
  104. }
  105. inline bool create_topic_subfun(map_iterator& parent, std::string_view t) ASIO2_NO_THREAD_SAFETY_ANALYSIS
  106. {
  107. if (t == "+" || t == "#")
  108. {
  109. throw_no_wildcards_allowed();
  110. }
  111. std::size_t parent_id = parent->second.id;
  112. map_iterator it = map_.find(key_type(parent_id, t));
  113. if (it == map_.end())
  114. {
  115. it = map_.emplace(
  116. key_type(parent_id, t),
  117. path_entry(parent_id, t, next_node_id++)
  118. ).first;
  119. wildcard_map_.emplace(parent_id, std::addressof(it->second));
  120. if (next_node_id == max_node_id)
  121. {
  122. throw_max_stored_topics();
  123. }
  124. }
  125. else
  126. {
  127. it->second.increase_count();
  128. }
  129. parent = it;
  130. return true;
  131. }
  132. inline std::vector<map_iterator> find_topic(std::string_view topic_name) ASIO2_NO_THREAD_SAFETY_ANALYSIS
  133. {
  134. std::vector<map_iterator> path;
  135. map_iterator parent = get_root();
  136. topic_filter_tokenizer(topic_name, [this, &path, &parent](std::string_view t) mutable
  137. {
  138. return this->find_topic_subfun(path, parent, t);
  139. });
  140. return path;
  141. }
  142. inline bool find_topic_subfun(std::vector<map_iterator>& path, map_iterator& parent, std::string_view t)
  143. ASIO2_NO_THREAD_SAFETY_ANALYSIS
  144. {
  145. auto it = map_.find(key_type(parent->second.id, t));
  146. if (it == map_.end())
  147. {
  148. path.clear();
  149. return false;
  150. }
  151. path.push_back(it);
  152. parent = it;
  153. return true;
  154. }
  155. // Match all underlying topics when a hash entry is matched
  156. // perform a breadth-first iteration over all items in the tree below
  157. template<typename Output>
  158. inline void match_hash_entries(std::size_t parent_id, Output&& callback, bool ignore_system)
  159. ASIO2_NO_THREAD_SAFETY_ANALYSIS
  160. {
  161. std::deque<std::size_t> ids;
  162. ids.push_back(parent_id);
  163. std::deque<std::size_t> new_ids;
  164. while (!ids.empty())
  165. {
  166. new_ids.resize(0);
  167. for (auto it : ids)
  168. {
  169. auto range = wildcard_map_.equal_range(it);
  170. for (auto i = range.first; i != range.second && i->second->parent_id == it; ++i)
  171. {
  172. // Should we ignore system matches
  173. if (!ignore_system || i->second->name.empty() || i->second->name[0] != '$')
  174. {
  175. if (i->second->value)
  176. {
  177. callback(i->second->value.value());
  178. }
  179. new_ids.push_back(i->second->id);
  180. }
  181. }
  182. }
  183. // Ignore system only on first level
  184. ignore_system = false;
  185. std::swap(ids, new_ids);
  186. }
  187. }
  188. // Find all topics that match the specified topic filter
  189. template<typename Output>
  190. inline void find_match(std::string_view topic_filter, Output&& callback) ASIO2_NO_THREAD_SAFETY_ANALYSIS
  191. {
  192. std::deque<map_iterator> iters;
  193. iters.push_back(get_root());
  194. std::deque<map_iterator> new_iters;
  195. topic_filter_tokenizer(topic_filter,
  196. [this, &iters, &new_iters, &callback](std::string_view t) mutable
  197. {
  198. return this->find_match_subfun(iters, new_iters, callback, t);
  199. });
  200. for (auto& it : iters)
  201. {
  202. if (it->second.value)
  203. {
  204. callback(it->second.value.value());
  205. }
  206. }
  207. }
  208. template<typename Output>
  209. inline bool find_match_subfun(
  210. std::deque<map_iterator>& iters, std::deque<map_iterator>& new_iters, Output& callback, std::string_view t)
  211. ASIO2_NO_THREAD_SAFETY_ANALYSIS
  212. {
  213. new_iters.resize(0);
  214. for (auto& it : iters)
  215. {
  216. std::size_t parent_id = it->second.id;
  217. if (t == std::string_view("+"))
  218. {
  219. auto range = wildcard_map_.equal_range(parent_id);
  220. for (auto i = range.first; i != range.second && i->second->parent_id == parent_id; ++i)
  221. {
  222. if (parent_id != root_node_id || i->second->name.empty() || i->second->name[0] != '$')
  223. {
  224. auto j = map_.find(key_type(i->second->parent_id, i->second->name));
  225. ASIO2_ASSERT(j != map_.end());
  226. new_iters.push_back(j);
  227. }
  228. else
  229. {
  230. break;
  231. }
  232. }
  233. }
  234. else if (t == std::string_view("#"))
  235. {
  236. match_hash_entries(parent_id, callback, parent_id == root_node_id);
  237. return false;
  238. }
  239. else
  240. {
  241. map_iterator i = map_.find(key_type(parent_id, t));
  242. if (i != map_.end())
  243. {
  244. new_iters.push_back(i);
  245. }
  246. }
  247. }
  248. std::swap(new_iters, iters);
  249. return !iters.empty();
  250. }
  251. // Remove a value at the specified topic name
  252. inline std::size_t erase_topic(std::string_view topic_name) ASIO2_NO_THREAD_SAFETY_ANALYSIS
  253. {
  254. auto path = find_topic(topic_name);
  255. // Reset the value if there is actually something stored
  256. if (!path.empty() && path.back()->second.value)
  257. {
  258. path.back()->second.value = std::nullopt;
  259. // Do iterators stay valid when erasing ? I think they do ?
  260. for (auto iter : path)
  261. {
  262. iter->second.decrease_count();
  263. if (iter->second.count == 0)
  264. {
  265. auto range = wildcard_map_.equal_range(std::get<0>(iter->first));
  266. for (auto it = range.first; it != range.second; ++it)
  267. {
  268. if (std::addressof(iter->second) == it->second)
  269. {
  270. wildcard_map_.erase(it);
  271. break;
  272. }
  273. }
  274. map_.erase(iter);
  275. }
  276. }
  277. return 1;
  278. }
  279. return 0;
  280. }
  281. // Increase the number of topics for this path
  282. inline void increase_topics(std::vector<map_iterator> const &path) ASIO2_NO_THREAD_SAFETY_ANALYSIS
  283. {
  284. for (auto& it : path)
  285. {
  286. it->second.increase_count();
  287. }
  288. }
  289. // Increase the map size (total number of topics stored)
  290. inline void increase_map_size() ASIO2_NO_THREAD_SAFETY_ANALYSIS
  291. {
  292. if (map_size == (std::numeric_limits<decltype(map_size)>::max)())
  293. {
  294. throw_max_stored_topics();
  295. }
  296. ++map_size;
  297. }
  298. // Decrease the map size (total number of topics stored)
  299. inline void decrease_map_size(std::size_t count) ASIO2_NO_THREAD_SAFETY_ANALYSIS
  300. {
  301. ASIO2_ASSERT(map_size >= count);
  302. map_size -= count;
  303. }
  304. inline void init_map() ASIO2_NO_THREAD_SAFETY_ANALYSIS
  305. {
  306. map_size = 0;
  307. // Create the root node
  308. auto it = map_.emplace(key_type(root_parent_id, ""),
  309. path_entry(root_parent_id, "", root_node_id)).first;
  310. next_node_id = root_node_id + 1;
  311. //
  312. wildcard_map_.emplace(root_parent_id, std::addressof(it->second));
  313. }
  314. inline map_iterator get_root() ASIO2_NO_THREAD_SAFETY_ANALYSIS
  315. {
  316. return map_.find(key_type(root_parent_id, ""));
  317. }
  318. public:
  319. retained_messages()
  320. {
  321. init_map();
  322. }
  323. // Insert a value at the specified topic name
  324. template<typename V>
  325. inline std::size_t insert_or_assign(std::string_view topic_name, V&& value)
  326. {
  327. asio2::unique_locker g(this->retained_mutex_);
  328. auto path = this->find_topic(topic_name);
  329. if (path.empty())
  330. {
  331. auto new_topic = this->create_topic(topic_name);
  332. new_topic->second.value.emplace(std::forward<V>(value));
  333. increase_map_size();
  334. return 1;
  335. }
  336. if (!path.back()->second.value)
  337. {
  338. this->increase_topics(path);
  339. path.back()->second.value.emplace(std::forward<V>(value));
  340. increase_map_size();
  341. return 1;
  342. }
  343. // replace the value
  344. path.back()->second.value.emplace(std::forward<V>(value));
  345. return 0;
  346. }
  347. // Find all stored topics that math the specified topic_filter
  348. template<typename Output>
  349. inline void find(std::string_view topic_filter, Output&& callback)
  350. {
  351. asio2::shared_locker g(this->retained_mutex_);
  352. find_match(topic_filter, std::forward<Output>(callback));
  353. }
  354. // Remove a stored value at the specified topic name
  355. inline std::size_t erase(std::string_view topic_name)
  356. {
  357. asio2::unique_locker g(this->retained_mutex_);
  358. auto result = erase_topic(topic_name);
  359. decrease_map_size(result);
  360. return result;
  361. }
  362. inline std::size_t size() const
  363. {
  364. asio2::shared_locker g(this->retained_mutex_);
  365. return map_size;
  366. }
  367. inline std::size_t internal_size() const
  368. {
  369. asio2::shared_locker g(this->retained_mutex_);
  370. return map_.size();
  371. }
  372. // Clear all topics
  373. inline void clear()
  374. {
  375. asio2::unique_locker g(this->retained_mutex_);
  376. map_.clear();
  377. wildcard_map_.clear();
  378. init_map();
  379. }
  380. // Dump debug information
  381. template<typename Output>
  382. inline void dump(Output &out)
  383. {
  384. asio2::shared_locker g(this->retained_mutex_);
  385. for (auto const&[k, v] : map_)
  386. {
  387. std::ignore = k;
  388. out << v.parent_id << " " << v.name << " " << (v.value ? "init" : "-")
  389. << " " << v.count << std::endl;
  390. }
  391. }
  392. };
  393. // A collection of messages that have been retained in
  394. // case clients add a new subscription to the associated topics.
  395. struct rmnode
  396. {
  397. template<class Message>
  398. explicit rmnode(Message&& msg, std::shared_ptr<asio::steady_timer> expiry_timer)
  399. : message(std::forward<Message>(msg))
  400. , message_expiry_timer(std::move(expiry_timer))
  401. {
  402. }
  403. mqtt::message message;
  404. std::shared_ptr<asio::steady_timer> message_expiry_timer;
  405. };
  406. }
  407. #endif // !__ASIO2_MQTT_RETAINED_MESSAGES_HPP__