Skip to main content

tightbeam_pubsub/
topic.rs

1//! Topic names and their validation. The page `docs/pubsub.md` (Topics)
2//! states the rules.
3
4use core::error::Error;
5use core::fmt;
6use core::str::{from_utf8, FromStr, Utf8Error};
7use std::sync::Arc;
8
9/// The prefix a client subscribes with: `sub/<topic>`.
10pub const SUB_PREFIX: &str = "sub/";
11
12/// The prefix a client unsubscribes with: `unsub/<topic>`.
13pub const UNSUB_PREFIX: &str = "unsub/";
14
15/// The prefix a client publishes with: `pub/<topic>`.
16pub const PUB_PREFIX: &str = "pub/";
17
18/// The prefix the registry completes a topic with: `end/<topic>`.
19pub const END_PREFIX: &str = "end/";
20
21/// A command verb, named by the prefix of the frame id that carries it.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub(crate) enum Verb {
24	/// A client subscribes: `sub/<topic>`.
25	Subscribe,
26	/// A client unsubscribes: `unsub/<topic>`.
27	Unsubscribe,
28	/// A client publishes: `pub/<topic>`.
29	Publish,
30	/// The registry completes a topic: `end/<topic>`.
31	End,
32}
33
34impl Verb {
35	/// Every verb, each of whose prefixes a topic name may not start with.
36	pub(crate) const ALL: [Self; 4] = [Self::Subscribe, Self::Unsubscribe, Self::Publish, Self::End];
37
38	/// The prefix of the frame id of this verb.
39	pub(crate) const fn prefix(self) -> &'static str {
40		match self {
41			Self::Subscribe => SUB_PREFIX,
42			Self::Unsubscribe => UNSUB_PREFIX,
43			Self::Publish => PUB_PREFIX,
44			Self::End => END_PREFIX,
45		}
46	}
47
48	/// The name of this verb in an audit record: its prefix without the `/`.
49	pub(crate) fn tag(self) -> &'static str {
50		let prefix = self.prefix();
51		prefix.trim_end_matches('/')
52	}
53}
54
55/// A validated topic name: non-empty UTF-8 of at most [`Topic::MAX_LEN`]
56/// octets that starts outside every command prefix, matched exactly.
57///
58/// The name sits behind an `Arc`, so a clone shares it.
59///
60/// # Sources
61///
62/// - MQTT 5.0 ยง 4.7, Topic Names and Topic Filters:
63///   <https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html>
64#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
65pub struct Topic(Arc<str>);
66
67impl Topic {
68	/// The longest topic name, in octets of UTF-8.
69	///
70	/// The registry keeps each subscribed name, and the backplane keeps a
71	/// counter for each published name, so this ceiling bounds the memory
72	/// one name can hold.
73	pub const MAX_LEN: usize = 256;
74
75	/// The name, as the frame id of each update carries it.
76	#[must_use]
77	pub fn as_str(&self) -> &str {
78		&self.0
79	}
80}
81
82impl fmt::Display for Topic {
83	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84		f.write_str(&self.0)
85	}
86}
87
88impl FromStr for Topic {
89	type Err = TopicError;
90
91	/// Parse a topic name from a UTF-8 string.
92	///
93	/// # Errors
94	///
95	/// - [`TopicError::Empty`] -- the name has zero length.
96	/// - [`TopicError::TooLong`] -- the name holds more than [`Topic::MAX_LEN`] octets.
97	/// - [`TopicError::ReservedPrefix`] -- the name starts with a command prefix.
98	fn from_str(name: &str) -> Result<Self, Self::Err> {
99		if name.is_empty() {
100			return Err(TopicError::Empty);
101		}
102		if name.len() > Self::MAX_LEN {
103			return Err(TopicError::TooLong(name.len()));
104		}
105
106		let reserved = Verb::ALL.into_iter().find(|verb| name.starts_with(verb.prefix()));
107		if let Some(verb) = reserved {
108			return Err(TopicError::ReservedPrefix(verb.prefix()));
109		}
110
111		Ok(Self(Arc::from(name)))
112	}
113}
114
115impl TryFrom<&str> for Topic {
116	type Error = TopicError;
117
118	fn try_from(name: &str) -> Result<Self, Self::Error> {
119		name.parse()
120	}
121}
122
123impl TryFrom<&[u8]> for Topic {
124	type Error = TopicError;
125
126	/// Parse a topic name from raw octets.
127	///
128	/// # Errors
129	///
130	/// - [`TopicError::NotUtf8`] -- the octets are not valid UTF-8.
131	/// - The errors of [`from_str`](FromStr::from_str).
132	fn try_from(name: &[u8]) -> Result<Self, Self::Error> {
133		let text = from_utf8(name)?;
134		text.parse()
135	}
136}
137
138impl From<Utf8Error> for TopicError {
139	fn from(cause: Utf8Error) -> Self {
140		Self::NotUtf8(cause)
141	}
142}
143
144/// Why a topic name failed validation.
145#[derive(Debug, Clone, PartialEq, Eq)]
146pub enum TopicError {
147	/// The name is empty.
148	Empty,
149	/// The name holds more than [`Topic::MAX_LEN`] octets. The field is its
150	/// length in octets.
151	TooLong(usize),
152	/// The name starts with a reserved command prefix.
153	ReservedPrefix(&'static str),
154	/// The name bytes are not valid UTF-8.
155	NotUtf8(Utf8Error),
156}
157
158impl fmt::Display for TopicError {
159	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160		match self {
161			Self::Empty => f.write_str("a topic name must be non-empty"),
162			Self::TooLong(len) => {
163				let max = Topic::MAX_LEN;
164				write!(f, "a topic name must fit in {max} octets, and this one holds {len}")
165			}
166			Self::NotUtf8(cause) => write!(f, "a topic name must be UTF-8: {cause}"),
167			Self::ReservedPrefix(prefix) => {
168				write!(f, "a topic name must not start with the reserved prefix {prefix}")
169			}
170		}
171	}
172}
173
174impl Error for TopicError {
175	fn source(&self) -> Option<&(dyn Error + 'static)> {
176		match self {
177			Self::NotUtf8(cause) => Some(cause),
178			_ => None,
179		}
180	}
181}
182
183#[cfg(test)]
184mod tests {
185	use super::*;
186
187	/// Parse `name`, expecting a valid topic.
188	fn parsed(name: &str) -> Topic {
189		name.parse().expect("the name should parse as a topic")
190	}
191
192	#[test]
193	fn accepts_hierarchical_names() {
194		let topic = parsed("prices/spot/BTC");
195		assert_eq!(topic.as_str(), "prices/spot/BTC");
196		assert_eq!(topic.to_string(), "prices/spot/BTC");
197	}
198
199	#[test]
200	fn accepts_names_containing_reserved_words_after_the_start() {
201		let topic = parsed("orders/sub/updates");
202		assert_eq!(topic.as_str(), "orders/sub/updates");
203	}
204
205	#[test]
206	fn rejects_an_empty_name() {
207		let outcome: Result<Topic, TopicError> = "".parse();
208		assert!(matches!(outcome, Err(TopicError::Empty)));
209	}
210
211	/// Parse `name`, expecting the reserved prefix that refuses it.
212	fn refused_prefix(name: &str) -> Option<&'static str> {
213		let outcome: Result<Topic, TopicError> = name.parse();
214		match outcome {
215			Err(TopicError::ReservedPrefix(prefix)) => Some(prefix),
216			_ => None,
217		}
218	}
219
220	#[test]
221	fn rejects_the_subscribe_prefix() {
222		assert_eq!(refused_prefix("sub/prices"), Some(SUB_PREFIX));
223	}
224
225	#[test]
226	fn rejects_the_unsubscribe_prefix() {
227		assert_eq!(refused_prefix("unsub/prices"), Some(UNSUB_PREFIX));
228	}
229
230	#[test]
231	fn rejects_the_publish_prefix() {
232		assert_eq!(refused_prefix("pub/prices"), Some(PUB_PREFIX));
233	}
234
235	#[test]
236	fn rejects_the_end_prefix() {
237		assert_eq!(refused_prefix("end/prices"), Some(END_PREFIX));
238	}
239
240	#[test]
241	fn a_verb_tags_audit_records_with_its_prefix() {
242		assert_eq!(Verb::Unsubscribe.tag(), "unsub");
243	}
244
245	#[test]
246	fn rejects_non_utf8_bytes() {
247		let outcome = Topic::try_from([0xff, 0xfe].as_slice());
248		assert!(matches!(outcome, Err(TopicError::NotUtf8(_))));
249	}
250
251	#[test]
252	fn accepts_a_name_at_the_length_ceiling() {
253		let name = "x".repeat(Topic::MAX_LEN);
254		let outcome: Result<Topic, TopicError> = name.parse();
255		assert!(outcome.is_ok());
256	}
257
258	#[test]
259	fn rejects_a_name_past_the_length_ceiling() {
260		let name = "x".repeat(Topic::MAX_LEN + 1);
261		let outcome: Result<Topic, TopicError> = name.parse();
262		assert!(matches!(outcome, Err(TopicError::TooLong(_))));
263	}
264
265	#[test]
266	fn parses_from_frame_id_octets() {
267		let parsed = Topic::try_from(b"chat/lobby".as_slice());
268		assert!(matches!(parsed, Ok(topic) if topic.as_str() == "chat/lobby"));
269	}
270}