mqtt_cpp
|
#include <subscription_map.hpp>
In MQTT we have: Clients subscribed with certain topic filters, topic filters are path with may contain wildcards such as
Topics being published, a topic is a sort of path and does not contain wildcards · $SYS/ has been widely adopted as a prefix to topics that contain Server-specific information or control APIs · Applications cannot use a topic with a leading $ character for their own purposes Check whether a string is a valid topic using 'mqtt_valid_topic'
We introduce two data structures: . A subscription map, storing a topic_filter -> data Using a published topic, we can find all topic filters which match the specified topic . A stored topic map, storing topic -> data Using a new topic filter, we can find all stored topics which match the specified topic filter
Subscription map stores all entries in a tree the tree starts from a root node, and topic filters are tokenized and stored in the tree
For example if the topic_filter example/monitor/Clients is stored, the following nodes are created: root -> example -> monitor -> Clients
Every node in the tree may store one or multiple subscribers. Nodes store a reference count to the number of subscribers so for example, if we store the following topic_filters: example/ example/monitor/Clients
the subscription map looks as follows: root(2) -> example(2) -> monitor(1) -> Clients (1)
hash and + are stored as normal nodes within the tree, but the parent node knows if a hash child is available. This improves the matching, no extra lookup is required to see if a # or + child is available in a child node:
example/#
stores the following tree: root -> example (hash: yes) -> #
and
example/+
stores the following tree: root -> example (plus: yes) -> #
all node entries are stored in a single hash map. The key for every node is: (parent node id, path)
so if we store: root/example/test root (id:1) -> example (id:2, key:1,example) -> test (id:3, key:2,test)
also, every node stores the key of its parent, allowing quick traversing from leaf to root of the tree