1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
// paho-mqtt/src/topic.rs
//
// This file is part of the Eclipse Paho MQTT Rust Client library.
//
/*******************************************************************************
* Copyright (c) 2017-2021 Frank Pagliughi <fpagliughi@mindspring.com>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v20.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Frank Pagliughi - initial implementation and documentation
*******************************************************************************/
//! Objects for manipulating and checking message topics.
//!
use crate::{
async_client::AsyncClient,
client::Client,
errors::{Error, Result},
message::{Message, MessageBuilder},
properties::{Properties, PropertyCode},
subscribe_options::SubscribeOptions,
token::{DeliveryToken, Token},
ServerResponse,
};
use std::fmt;
/////////////////////////////////////////////////////////////////////////////
// Topic
/////////////////////////////////////////////////////////////////////////////
/// A topic destination for messages.
///
/// This keeps message parameters for repeatedly publishing to the same
/// topic on a server.
pub struct Topic<'a> {
/// Reference to the broker that will receive the messages.
cli: &'a AsyncClient,
/// The topic on which to publish the messages.
topic: String,
/// The QoS level to publish the messages.
qos: i32,
/// Whether the last message should be retained by the broker.
retained: bool,
/// The topic alias.
/// If this is non-zero is it sent in place of the string topic name.
alias: u16,
}
impl<'a> Topic<'a> {
/// Creates a new topic object for publishing messages.
///
/// # Arguments
///
/// `cli` The client used to publish the messages.
/// `topic` The topic on which to publish the messages
/// `qos` The quality of service for messages
///
pub fn new<T>(cli: &'a AsyncClient, topic: T, qos: i32) -> Self
where
T: Into<String>,
{
Topic {
cli,
topic: topic.into(),
qos,
retained: false,
alias: 0,
}
}
/// Creates a new topic object for publishing retain messages.
///
/// # Arguments
///
/// `cli` The client used to publish the messages.
/// `topic` The topic on which to publish the messages
/// `qos` The quality of service for messages
///
pub fn new_retained<T>(cli: &'a AsyncClient, topic: T, qos: i32) -> Self
where
T: Into<String>,
{
Topic {
cli,
topic: topic.into(),
qos,
retained: true,
alias: 0,
}
}
/// Create a message for the topic using the supplied payload.
///
/// If `inc_topic` is true, this will create a message containing the
/// string topic whether or not the alias is set. This would be done
/// to set the topic alias on the server.
///
/// If `inc_topic` is false, then the topic will be left blank if the
/// alias is set, and the topic alias property will be added to the
/// message.
pub fn create_message_with_topic<V>(&self, payload: V, inc_topic: bool) -> Message
where
V: Into<Vec<u8>>,
{
let mut bld = MessageBuilder::new()
.payload(payload)
.qos(self.qos)
.retained(self.retained);
if self.alias == 0 || inc_topic {
bld = bld.topic(&self.topic);
}
if self.alias != 0 {
bld = bld.properties(properties! { PropertyCode::TopicAlias => self.alias });
}
bld.finalize()
}
/// Create a message for the topic using the supplied payload
///
pub fn create_message<V>(&self, payload: V) -> Message
where
V: Into<Vec<u8>>,
{
self.create_message_with_topic(payload, false)
}
/// Subscribe to the topic.
pub fn subscribe(&self) -> Token {
self.cli.subscribe(self.topic.clone(), self.qos)
}
/// Subscribe to the topic with subscription options.
pub fn subscribe_with_options<T, P>(&self, opts: T, props: P) -> Token
where
T: Into<SubscribeOptions>,
P: Into<Option<Properties>>,
{
self.cli
.subscribe_with_options(self.topic.clone(), self.qos, opts, props)
}
/// Publish a message on the topic.
///
/// If a topic alias was previously sent, this will use the integer alias
/// property instead of sending the topic string.
/// Topic aliases are only applicable for MQTT v5 connections.
///
/// # Arguments
///
/// `payload` The payload of the message
///
pub fn publish<V>(&self, payload: V) -> DeliveryToken
where
V: Into<Vec<u8>>,
{
let msg = self.create_message(payload);
self.cli.publish(msg)
}
/// Attempts to publish a message on the topic, but returns an error
/// immediately if there's a problem creating or queuing the message for
/// transmission.
///
/// If a topic alias was previously sent, this will use the integer alias
/// property instead of sending the topic string.
/// Topic aliases are only applicable for MQTT v5 connections.
///
/// # Arguments
///
/// `payload` The payload of the message
///
/// Returns a Publish Error containing the complete message on failure.
pub fn try_publish<V>(&self, payload: V) -> Result<DeliveryToken>
where
V: Into<Vec<u8>>,
{
let msg = self.create_message(payload);
self.cli.try_publish(msg)
}
/// Publish a message with a topic alias.
///
/// This publishes the message with a topic alias property to set the
/// alias at the broker. After calling this, the object keeps the
/// alias and uses it for subsequent publishes instead of sending the
/// full topic string.
///
/// Note that using an alias is only valid with an MQTT v5 connection,
/// and the value must be in the range of 1 - TopicAliasMaximum as the
/// broker reported in the CONNACK packet. The alias is only valid
/// for a single connection. It should be reset on a reconnect.
///
/// This can be called a second time to change the alias setting.
/// Using an alias of zero on a subsequent call instructs this object to
/// stop using the alias and publish with the topic name.
///
/// # Arguments
///
/// `alias` The integer alias to use for subsequent message publishing.
/// This must be in the range 1 - `TopicAliasMaximum` as reported by
/// the server in the CONNACK package. Using a value of zero
/// instructs this object to stop using the alias and go back to
/// publishing with the string topic name.
/// `payload` The payload of the message
///
pub fn publish_with_alias<V>(&mut self, alias: u16, payload: V) -> DeliveryToken
where
V: Into<Vec<u8>>,
{
self.alias = alias;
let msg = self.create_message_with_topic(payload, true);
self.cli.publish(msg)
}
/// Attempts to publish a message on the topic using and setting a new topic
/// alias, but returns an error immediately if there's a problem creating or
/// queuing the message for transmission.
///
/// See [`publish_with_alias()`](Self::publish_with_alias) for more information.
///
/// Returns a Publish Error containing the complete message on failure.
pub fn try_publish_with_alias<V>(&mut self, alias: u16, payload: V) -> Result<DeliveryToken>
where
V: Into<Vec<u8>>,
{
self.alias = alias;
let msg = self.create_message_with_topic(payload, true);
self.cli.try_publish(msg)
}
/// Gets the alias for the topic, if any.
pub fn alias(&self) -> Option<u16> {
match self.alias {
0 => None,
val => Some(val),
}
}
/// Removes the alias, if any, from the topic.
///
/// After removing the alias, publshed messages contain the full string
/// topic. The alias mapping remains on the server though. The alias
/// number cann be reused by assigning to a different topic, but the
/// only way to remove it is to disconnect the client.
pub fn remove_alias(&mut self) {
self.alias = 0;
}
}
/////////////////////////////////////////////////////////////////////////////
// SyncTopic
/////////////////////////////////////////////////////////////////////////////
/// A topic destination for messages.
///
/// This keeps message parameters for repeatedly publishing to the same
/// topic on a server.
pub struct SyncTopic<'a> {
cli: &'a Client,
topic: Topic<'a>,
}
impl<'a> SyncTopic<'a> {
/// Creates a new topic object for publishing messages.
///
/// # Arguments
///
/// `cli` The client used to publish the messages.
/// `topic` The topic on which to publish the messages
/// `qos` The quality of service for messages
///
pub fn new<T>(cli: &'a Client, topic: T, qos: i32) -> Self
where
T: Into<String>,
{
Self {
cli,
topic: Topic::new(&cli.cli, topic, qos),
}
}
/// Creates a new topic object for publishing messages.
///
/// # Arguments
///
/// `cli` The client used to publish the messages.
/// `topic` The topic on which to publish the messages
/// `qos` The quality of service for messages
///
pub fn new_retained<T: Into<String>>(cli: &'a Client, topic: T, qos: i32) -> Self
where
T: Into<String>,
{
Self {
cli,
topic: Topic::new_retained(&cli.cli, topic, qos),
}
}
/// Create a message for the topic using the supplied payload
pub fn create_message<V>(&self, payload: V) -> Message
where
V: Into<Vec<u8>>,
{
self.topic.create_message(payload)
}
/// Subscribe to the topic.
pub fn subscribe(&self) -> Result<ServerResponse> {
self.cli.subscribe(&self.topic.topic, self.topic.qos)
}
/// Subscribe to the topic with subscription options.
pub fn subscribe_with_options<T, P>(&self, opts: T, props: P) -> Result<ServerResponse>
where
T: Into<SubscribeOptions>,
P: Into<Option<Properties>>,
{
self.cli
.subscribe_with_options(&self.topic.topic, self.topic.qos, opts, props)
}
/// Publish a message on the topic.
///
/// If a topic alias was previously sent, this will use the integer alias
/// property instead of sending the topic string.
/// Topic aliases are only applicable for MQTT v5 connections.
///
/// # Arguments
///
/// `payload` The payload of the message
///
pub fn publish<V>(&self, payload: V) -> Result<()>
where
V: Into<Vec<u8>>,
{
let msg = self.create_message(payload);
self.cli.publish(msg)
}
/// Publish a message with a topic alias.
///
/// This publishes the message with a topic alias property to set the
/// alias at the broker. After calling this, the object keeps the
/// alias and uses it for subsequent publishes instead of sending the
/// full topic string.
///
/// Note that using an alias is only valid with an MQTT v5 connection,
/// and the value must be in the range of 1 - TopicAliasMaximum as the
/// broker reported in the CONNACK packet. The alias is only valid
/// for a single connection. It should be reset on a reconnect.
///
/// This can be called a second time to change the alias setting.
/// Using an alias of zero on a subsequent call instructs this object to
/// stop using the alias and publish with the topic name.
///
/// # Arguments
///
/// `alias` The integer alias to use for subsequent message publishing.
/// This must be in the range 1 - `TopicAliasMaximum` as reported by
/// the server in the CONNACK package. Using a value of zero
/// instructs this object to stop using the alias and go back to
/// publishing with the string topic name.
/// `payload` The payload of the message
///
pub fn publish_with_alias<V>(&mut self, alias: u16, payload: V) -> Result<()>
where
V: Into<Vec<u8>>,
{
self.topic.alias = alias;
let msg = self.topic.create_message_with_topic(payload, true);
self.cli.publish(msg)
}
/// Gets the alias for the topic, if any.
pub fn alias(&self) -> Option<u16> {
self.topic.alias()
}
/// Removes the alias, if any, from the topic.
///
/// After removing the alias, publshed messages contain the full string
/// topic. The alias mapping remains on the server though. The alias
/// number cann be reused by assigning to a different topic, but the
/// only way to remove it is to disconnect the client.
pub fn remove_alias(&mut self) {
self.topic.remove_alias();
}
}
/////////////////////////////////////////////////////////////////////////////
// TopicFilter
/////////////////////////////////////////////////////////////////////////////
/// A topic filter.
///
/// An MQTT topic filter is a multi-field string, delimited by forward
/// slashes, '/', in which fields can contain the wildcards:
/// '+' - Matches a single field
/// '#' - Matches all subsequent fields (must be last field in filter)
///
/// It can be used to match against topics.
#[derive(Debug)]
pub enum TopicFilter {
/// If there are no wildcards, the filter is a straight topic string
Topic(String),
/// If there are wildcards, the filter is split by fields.
Fields(Vec<String>),
}
impl TopicFilter {
/// Creates a new topic filter from the string.
/// This can fail if the filter is not correct, such as having a '#'
/// wildcard in anyplace other than the last field, or if
pub fn new<S>(filter: S) -> Result<Self>
where
S: Into<String>,
{
let filter = filter.into();
let n = filter.len();
if n == 0 {
return Err(Error::BadTopicFilter);
}
// If the topic contains any wildcards.
let wild = match filter.find('#') {
Some(i) if i < n - 1 => return Err(Error::BadTopicFilter),
Some(_) => true,
None => filter.contains('+'),
};
let v = if wild {
let fields = filter.split('/').map(|s| s.to_string()).collect();
Self::Fields(fields)
}
else {
Self::Topic(filter)
};
Ok(v)
}
/// Creates a new topic filter from the string without checking it.
pub fn new_unchecked<S>(filter: S) -> Self
where
S: Into<String>,
{
let filter = filter.into();
if filter.contains('+') || filter.ends_with('#') {
Self::Fields(filter.split('/').map(|s| s.to_string()).collect())
}
else {
Self::Topic(filter)
}
}
/// Determines if the topic matches the filter.
///
/// This is the same as [`is_match`](Self::is_match), but uses a more
/// consistent function name with other topic matchers.
pub fn matches(&self, topic: &str) -> bool {
use crate::topic_matcher::topic_matches_iter;
match self {
Self::Topic(filter) => topic == filter,
Self::Fields(fields) => {
topic_matches_iter(fields.iter().map(|s| s.as_str()), topic.split('/'))
}
}
}
/// Determines if the topic matches the filter.
pub fn is_match(&self, topic: &str) -> bool {
self.matches(topic)
}
}
impl fmt::Display for TopicFilter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Topic(filter) => write!(f, "{}", filter),
Self::Fields(fields) => write!(f, "{}", fields.join("/")),
}
}
}
/////////////////////////////////////////////////////////////////////////////
// Unit Tests
/////////////////////////////////////////////////////////////////////////////
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_nonwild_topic_filter() {
const FILTER: &str = "some/topic";
let filter = TopicFilter::new(FILTER).unwrap();
assert!(filter.is_match(FILTER));
let s = format!("{}", filter);
assert_eq!(s, FILTER);
}
#[test]
fn test_basic_topic_filter() {
const FILTER1: &str = "some/topic/#";
let filter = TopicFilter::new(FILTER1).unwrap();
assert!(filter.is_match("some/topic/thing"));
let s = format!("{}", filter);
assert_eq!(s, FILTER1);
const FILTER2: &str = "some/+/thing";
let filter = TopicFilter::new(FILTER2).unwrap();
assert!(filter.is_match("some/topic/thing"));
assert!(!filter.is_match("some/topic/plus/thing"));
let s = format!("{}", filter);
assert_eq!(s, FILTER2);
const FILTER3: &str = "some/+";
let filter = TopicFilter::new(FILTER3).unwrap();
assert!(filter.is_match("some/thing"));
assert!(!filter.is_match("some/thing/plus"));
}
#[test]
fn test_topic_filter() {
// Should match
assert!(TopicFilter::new_unchecked("foo/bar").matches("foo/bar"));
assert!(TopicFilter::new_unchecked("foo/+").matches("foo/bar"));
assert!(TopicFilter::new_unchecked("foo/+/baz").matches("foo/bar/baz"));
assert!(TopicFilter::new_unchecked("foo/+/#").matches("foo/bar/baz"));
assert!(TopicFilter::new_unchecked("A/B/+/#").matches("A/B/B/C"));
assert!(TopicFilter::new_unchecked("#").matches("foo/bar/baz"));
assert!(TopicFilter::new_unchecked("#").matches("/foo/bar"));
assert!(TopicFilter::new_unchecked("/#").matches("/foo/bar"));
assert!(TopicFilter::new_unchecked("$SYS/bar").matches("$SYS/bar"));
assert!(TopicFilter::new_unchecked("foo/#").matches("foo/$bar"));
assert!(TopicFilter::new_unchecked("foo/+/baz").matches("foo/$bar/baz"));
// Should not match
assert!(!TopicFilter::new_unchecked("test/6/#").matches("test/3"));
assert!(!TopicFilter::new_unchecked("foo/bar").matches("foo"));
assert!(!TopicFilter::new_unchecked("foo/+").matches("foo/bar/baz"));
assert!(!TopicFilter::new_unchecked("foo/+/baz").matches("foo/bar/bar"));
assert!(!TopicFilter::new_unchecked("foo/+/#").matches("fo2/bar/baz"));
assert!(!TopicFilter::new_unchecked("/#").matches("foo/bar"));
assert!(!TopicFilter::new_unchecked("#").matches("$SYS/bar"));
assert!(!TopicFilter::new_unchecked("$BOB/bar").matches("$SYS/bar"));
assert!(!TopicFilter::new_unchecked("+/bar").matches("$SYS/bar"));
}
}