mqtt-topic-engine 0.1.1

High-performance MQTT topic pattern matching and routing engine
Documentation
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
//! Tests for TopicPatternPath functionality

use std::collections::HashMap;

use arcstr::ArcStr;

use crate::CacheStrategy;
use crate::{TopicPatternError, TopicPatternPath};

fn create_pattern(pattern: &str) -> TopicPatternPath {
	TopicPatternPath::new_from_string(pattern, CacheStrategy::NoCache)
		.expect("Pattern should be valid")
}

trait TopicPatternPathTestExt {
	fn with_parameters<I, K, V>(
		self,
		params: I,
	) -> Result<Self, TopicPatternError>
	where
		Self: Sized,
		I: IntoIterator<Item = (K, V)>,
		K: Into<ArcStr>,
		V: Into<ArcStr>;
}

impl TopicPatternPathTestExt for TopicPatternPath {
	fn with_parameters<I, K, V>(
		mut self,
		params: I,
	) -> Result<Self, TopicPatternError>
	where
		I: IntoIterator<Item = (K, V)>,
		K: Into<ArcStr>,
		V: Into<ArcStr>,
	{
		for (key, value) in params {
			self = self.bind_parameter(key, value)?;
		}
		Ok(self)
	}
}

/// Test with_parameters() functionality
mod with_parameters_tests {
	use arcstr::Substr;

	use super::*;
	use crate::TopicPatternItem;

	#[test]
	fn test_single_parameter_substitution() {
		let pattern = create_pattern("sensors/{sensor_id}/data");
		let result = pattern.with_parameters([("sensor_id", "123")]).unwrap();

		// topic_pattern() preserves original template
		assert_eq!(result.topic_pattern(), "sensors/{sensor_id}/data");
		// mqtt_pattern() shows substituted result
		assert_eq!(result.mqtt_pattern(), "sensors/123/data");
	}

	#[test]
	fn test_multiple_parameter_substitution() {
		let pattern =
			create_pattern("buildings/{building}/floors/{floor}/rooms/{room}");
		let params = [("building", "A"), ("floor", "2"), ("room", "kitchen")];
		let result = pattern.with_parameters(params).unwrap();

		// All parameters substituted in mqtt_pattern
		assert_eq!(result.mqtt_pattern(), "buildings/A/floors/2/rooms/kitchen");
	}

	#[test]
	fn test_partial_parameter_substitution() {
		let pattern =
			create_pattern("sensors/{sensor_id}/data/{measurement_type}");
		let result = pattern
			.with_parameters([("sensor_id", "floor_sensor")])
			.unwrap();

		// topic_pattern() preserves original template
		assert_eq!(
			result.topic_pattern(),
			"sensors/{sensor_id}/data/{measurement_type}"
		);
		// mqtt_pattern() shows partial substitution (unbound params become +)
		assert_eq!(result.mqtt_pattern(), "sensors/floor_sensor/data/+");
	}

	#[test]
	fn test_with_hashmap() {
		let pattern =
			create_pattern("devices/{device_type}/{device_id}/status");
		let mut params = HashMap::new();
		params.insert("device_type", "sensor");
		params.insert("device_id", "temp_01");

		let result = pattern.with_parameters(params).unwrap();
		assert_eq!(result.mqtt_pattern(), "devices/sensor/temp_01/status");
	}

	#[test]
	fn test_with_vector_of_tuples() {
		let pattern = create_pattern("home/{room}/device/{device}");
		let params = vec![("room", "kitchen"), ("device", "thermometer")];

		let result = pattern.with_parameters(params).unwrap();
		assert_eq!(result.mqtt_pattern(), "home/kitchen/device/thermometer");
	}

	#[test]
	fn test_with_slice() {
		let pattern = create_pattern("mqtt/{topic}/{subtopic}");
		let params = [("topic", "sensors"), ("subtopic", "temperature")];

		let result = pattern.with_parameters(params).unwrap();
		assert_eq!(result.mqtt_pattern(), "mqtt/sensors/temperature");
	}

	#[test]
	fn test_empty_parameters_returns_clone() {
		let pattern = create_pattern("sensors/{sensor_id}/data");
		let empty_params: Vec<(String, String)> = vec![];
		let topic_pattern = pattern.topic_pattern();
		let mqtt_pattern = pattern.mqtt_pattern();
		let result = pattern.with_parameters(empty_params).unwrap();
		assert_eq!(result.topic_pattern(), topic_pattern);
		assert_eq!(result.mqtt_pattern(), mqtt_pattern);
	}

	#[test]
	fn test_empty_iterator_returns_clone() {
		let pattern = create_pattern("devices/{id}/status");
		let topic_pattern = pattern.topic_pattern();
		let result = pattern
			.with_parameters(std::iter::empty::<(String, String)>())
			.unwrap();

		assert_eq!(result.topic_pattern(), topic_pattern);
	}

	#[test]
	fn test_empty_hashmap_returns_clone() {
		let pattern = create_pattern("sensors/{sensor_id}/data");
		let empty_map: HashMap<String, String> = HashMap::new();
		let topic_pattern = pattern.topic_pattern();
		let result = pattern.with_parameters(&empty_map).unwrap();
		assert_eq!(result.topic_pattern(), topic_pattern);
	}

	#[test]
	fn test_parameter_not_found_error() {
		let pattern = create_pattern("sensors/{sensor_id}/data");
		let result = pattern.with_parameters([("nonexistent", "value")]);

		assert!(result.is_err());
		if let Err(TopicPatternError::WildcardUsage { usage }) = result {
			assert!(
				usage.contains("Parameter 'nonexistent' not found in pattern")
			);
		} else {
			panic!("Expected WildcardUsage error");
		}
	}

	#[test]
	fn test_mixed_valid_and_invalid_parameters() {
		let pattern = create_pattern("sensors/{sensor_id}/data/{type}");
		let params = [
			("sensor_id", "123"),
			("invalid_param", "value"), // This will cause error
		];

		let result = pattern.with_parameters(params);
		assert!(result.is_err());

		// Should fail on first invalid parameter
		if let Err(TopicPatternError::WildcardUsage { usage }) = result {
			assert!(
				usage
					.contains("Parameter 'invalid_param' not found in pattern")
			);
		}
	}

	#[test]
	fn test_anonymous_wildcards_are_not_substituted() {
		let pattern = create_pattern("sensors/+/data/{measurement}");
		let result = pattern
			.with_parameters([("measurement", "temperature")])
			.unwrap();

		// topic_pattern() preserves original template including anonymous wildcards
		assert_eq!(result.topic_pattern(), "sensors/+/data/{measurement}");
		// mqtt_pattern() substitutes named params, leaves anonymous wildcards
		assert_eq!(result.mqtt_pattern(), "sensors/+/data/temperature");
	}

	#[test]
	fn test_mixed_named_and_anonymous_wildcards() {
		let pattern =
			create_pattern("devices/{device_type}/+/status/{status_type}");
		let params = [("device_type", "sensor"), ("status_type", "online")];
		let result = pattern.with_parameters(params).unwrap();

		// topic_pattern() preserves original template
		assert_eq!(
			result.topic_pattern(),
			"devices/{device_type}/+/status/{status_type}"
		);
		// mqtt_pattern() substitutes named params, preserves anonymous wildcards
		assert_eq!(result.mqtt_pattern(), "devices/sensor/+/status/online");
	}

	#[test]
	fn test_hash_wildcard_preservation() {
		let pattern = create_pattern("logs/{service}/#");
		let result = pattern.with_parameters([("service", "auth")]).unwrap();

		// topic_pattern() preserves original template
		assert_eq!(result.topic_pattern(), "logs/{service}/#");
		// mqtt_pattern() substitutes named params, preserves # wildcard
		assert_eq!(result.mqtt_pattern(), "logs/auth/#");
	}

	#[test]
	fn test_named_hash_wildcard_substitution() {
		let pattern = create_pattern("events/{category}/{details:#}");
		let result = pattern.with_parameters([("category", "alerts")]).unwrap();

		// topic_pattern() preserves original template including named hash wildcard
		assert_eq!(result.topic_pattern(), "events/{category}/{details:#}");
		// mqtt_pattern() substitutes named params, converts named hash to #
		assert_eq!(result.mqtt_pattern(), "events/alerts/#");
	}

	#[test]
	#[cfg(feature = "lru-cache")]
	fn test_cache_strategy_preservation() {
		let pattern = TopicPatternPath::new_from_string(
			"sensors/{id}/data",
			CacheStrategy::Lru(std::num::NonZeroUsize::new(50).unwrap()),
		)
		.unwrap();

		let result = pattern.with_parameters([("id", "123")]).unwrap();

		// Cache strategy should be preserved
		match result.cache_strategy() {
			| CacheStrategy::Lru(size) => assert_eq!(size.get(), 50),
			| CacheStrategy::NoCache => panic!("Expected LRU cache strategy"),
		}
	}

	#[test]
	fn test_unicode_parameters() {
		let pattern = create_pattern("пристрої/{тип}/статус");
		let result = pattern.with_parameters([("тип", "сенсор")]).unwrap();

		assert_eq!(result.mqtt_pattern(), "пристрої/сенсор/статус");
	}

	#[test]
	fn test_special_characters_in_values() {
		let pattern = create_pattern("devices/{device_id}/data");
		let result = pattern
			.with_parameters([("device_id", "temp-sensor@home.local")])
			.unwrap();

		assert_eq!(
			result.mqtt_pattern(),
			"devices/temp-sensor@home.local/data"
		);
	}

	#[test]
	fn test_empty_string_parameter_value() {
		let pattern = create_pattern("prefix/{param}/suffix");
		let result = pattern.with_parameters([("param", "")]).unwrap();

		assert_eq!(result.mqtt_pattern(), "prefix//suffix");
	}

	#[test]
	fn test_pattern_with_no_wildcards() {
		let pattern = create_pattern("static/topic/path");
		let result = pattern.with_parameters([("nonexistent", "value")]);

		assert!(result.is_err());
		if let Err(TopicPatternError::WildcardUsage { usage }) = result {
			assert!(
				usage.contains("Parameter 'nonexistent' not found in pattern")
			);
		}
	}

	#[test]
	fn test_single_wildcard_pattern() {
		let pattern = create_pattern("{param}");
		let result = pattern.with_parameters([("param", "value")]).unwrap();

		// topic_pattern() preserves original template
		assert_eq!(result.topic_pattern(), "{param}");
		// mqtt_pattern() shows substituted result
		assert_eq!(result.mqtt_pattern(), "value");
	}

	#[test]
	fn test_parameter_order_independence() {
		let pattern = create_pattern("a/{first}/b/{second}/c");

		// Test different parameter orders
		let result1 = pattern
			.clone()
			.with_parameters([("first", "1"), ("second", "2")])
			.unwrap();
		let result2 = pattern
			.with_parameters([("second", "2"), ("first", "1")])
			.unwrap();

		// Both should produce the same MQTT pattern regardless of parameter order
		assert_eq!(result1.mqtt_pattern(), "a/1/b/2/c");
		assert_eq!(result2.mqtt_pattern(), "a/1/b/2/c");
		assert_eq!(result1.mqtt_pattern(), result2.mqtt_pattern());
	}

	fn str_to_topic_pattern_path(
		topic: &str,
	) -> Result<TopicPatternPath, TopicPatternError> {
		TopicPatternPath::new_from_string(topic, CacheStrategy::NoCache)
	}

	#[test]
	fn test_simple_string_pattern() {
		let result = str_to_topic_pattern_path("simple/path").unwrap();
		assert_eq!(
			result.segments(),
			&vec![
				TopicPatternItem::Str(Substr::from("simple")),
				TopicPatternItem::Str(Substr::from("path"))
			]
		);
	}

	#[test]
	fn test_pattern_with_star() {
		let result = str_to_topic_pattern_path("devices/+/status").unwrap();
		assert_eq!(
			result.segments(),
			&vec![
				TopicPatternItem::Str(Substr::from("devices")),
				TopicPatternItem::Plus(None),
				TopicPatternItem::Str(Substr::from("status"))
			]
		);
	}

	#[test]
	fn test_pattern_with_hash() {
		let result = str_to_topic_pattern_path("sensors/#").unwrap();
		assert_eq!(
			result.segments(),
			&vec![
				TopicPatternItem::Str(Substr::from("sensors")),
				TopicPatternItem::Hash(None)
			]
		);
	}

	#[test]
	fn test_pattern_with_both_wildcards() {
		let result = str_to_topic_pattern_path("home/+/device/#").unwrap();
		assert_eq!(
			result.segments(),
			&vec![
				TopicPatternItem::Str(Substr::from("home")),
				TopicPatternItem::Plus(None),
				TopicPatternItem::Str(Substr::from("device")),
				TopicPatternItem::Hash(None)
			]
		);
	}

	#[test]
	fn test_empty_string() {
		let result = str_to_topic_pattern_path("");
		assert!(result.is_err());
		assert_eq!(result.unwrap_err(), TopicPatternError::EmptyTopic);
	}

	#[test]
	fn test_only_wildcards() {
		let result_star = str_to_topic_pattern_path("+").unwrap();
		assert_eq!(result_star.segments(), &vec![TopicPatternItem::Plus(None)]);

		let result_hash = str_to_topic_pattern_path("#").unwrap();
		assert_eq!(result_hash.segments(), &vec![TopicPatternItem::Hash(None)]);
	}

	#[test]
	fn test_consecutive_separators() {
		let result = str_to_topic_pattern_path("topic//subtopic");
		assert!(result.is_ok());
		assert_eq!(
			result.unwrap().segments(),
			&vec![
				TopicPatternItem::Str(Substr::from("topic")),
				TopicPatternItem::Str(Substr::from("")),
				TopicPatternItem::Str(Substr::from("subtopic"))
			]
		);
	}

	#[test]
	fn test_starting_with_separator() {
		let result = str_to_topic_pattern_path("/start");
		assert!(result.is_ok());
		assert_eq!(
			result.unwrap().segments(),
			&vec![
				TopicPatternItem::Str(Substr::from("")),
				TopicPatternItem::Str(Substr::from("start"))
			]
		);
	}

	#[test]
	fn test_ending_with_separator() {
		let result = str_to_topic_pattern_path("end/");
		assert!(result.is_ok());
		assert_eq!(
			result.unwrap().segments(),
			&vec![
				TopicPatternItem::Str(Substr::from("end")),
				TopicPatternItem::Str(Substr::from(""))
			]
		);
	}

	#[test]
	fn test_invalid_hash_wildcard_position() {
		let result = str_to_topic_pattern_path("invalid/#/pattern");
		assert!(result.is_err());
		assert_eq!(
			result.unwrap_err(),
			TopicPatternError::HashPosition {
				pattern: "invalid/#/pattern".to_string()
			}
		);
	}

	#[test]
	fn test_very_long_pattern() {
		let long_pattern = "segment1/segment2/segment3/segment4/segment5/\
		                    segment6/segment7/segment8/segment9/segment10";
		let result = str_to_topic_pattern_path(long_pattern).unwrap();
		assert_eq!(result.segments().len(), 10);
	}

	#[test]
	fn test_unicode_characters() {
		let result = str_to_topic_pattern_path("пристрої/+/статус").unwrap();
		assert_eq!(
			result.segments(),
			&vec![
				TopicPatternItem::Str(Substr::from("пристрої")),
				TopicPatternItem::Plus(None),
				TopicPatternItem::Str(Substr::from("статус"))
			]
		);
	}

	#[test]
	fn test_special_characters() {
		let result =
			str_to_topic_pattern_path("device-123/status@home").unwrap();
		assert_eq!(
			result.segments(),
			&vec![
				TopicPatternItem::Str(Substr::from("device-123")),
				TopicPatternItem::Str(Substr::from("status@home"))
			]
		);
	}

	#[test]
	fn test_display_implementation() {
		// Test simple string pattern
		let path = str_to_topic_pattern_path("simple/path").unwrap();
		assert_eq!(path.to_string(), "simple/path");

		// Test with wildcards
		let path = str_to_topic_pattern_path("devices/+/status").unwrap();
		assert_eq!(path.to_string(), "devices/+/status");

		// Test with hash wildcard
		let path = str_to_topic_pattern_path("sensors/#").unwrap();
		assert_eq!(path.to_string(), "sensors/#");

		// Test empty path
		if let Err(err) = str_to_topic_pattern_path("") {
			assert_eq!(err, TopicPatternError::EmptyTopic);
		} else {
			panic!("Expected error for empty topic pattern");
		}

		// Test / path
		let path = str_to_topic_pattern_path("/").unwrap();
		assert_eq!(path.to_string(), "/");

		// Test finish / path
		let path = str_to_topic_pattern_path("device/").unwrap();
		assert_eq!(path.to_string(), "device/");

		// Test with consecutive separators
		let path = str_to_topic_pattern_path("topic//subtopic").unwrap();
		assert_eq!(path.to_string(), "topic//subtopic");
	}

	#[test]
	fn test_invalid_wildcards_format() {
		let result_double_star = str_to_topic_pattern_path("topic/++/subtopic");
		assert!(result_double_star.is_err());
		assert!(matches!(
			result_double_star.unwrap_err(),
			TopicPatternError::WildcardUsage { .. }
		));

		let result_double_hash = str_to_topic_pattern_path("topic/##");
		assert!(result_double_hash.is_err());
		assert!(matches!(
			result_double_hash.unwrap_err(),
			TopicPatternError::WildcardUsage { .. }
		));
	}

	#[test]
	fn test_wildcards_with_other_characters() {
		let result_star = str_to_topic_pattern_path("topic/a+b/subtopic");
		assert!(result_star.is_err());
		assert!(matches!(
			result_star.unwrap_err(),
			TopicPatternError::WildcardUsage { .. }
		));

		let result_hash = str_to_topic_pattern_path("topic/a#b");
		assert!(result_hash.is_err());
		assert!(matches!(
			result_hash.unwrap_err(),
			TopicPatternError::WildcardUsage { .. }
		));
	}
}

/// Integration tests with real-world patterns
mod integration_tests {
	use super::*;

	#[test]
	fn test_mqtt_sensor_reading_pattern() {
		let pattern = create_pattern("typed/{room}/pl/{sensor_id}/some/{temp}");
		let params = [
			("room", "kitchen"),
			("sensor_id", "floor_sensor"),
			("temp", "23.5"),
		];

		let result = pattern.with_parameters(params).unwrap();
		assert_eq!(
			result.mqtt_pattern(),
			"typed/kitchen/pl/floor_sensor/some/23.5"
		);
	}

	#[test]
	fn test_iot_device_telemetry_pattern() {
		let pattern = create_pattern(
			"iot/{building}/{floor}/devices/{device_type}/{device_id}/\
			 telemetry/{metric}",
		);
		let params = [
			("building", "office-a"),
			("floor", "3"),
			("device_type", "temperature"),
			("device_id", "temp-001"),
			("metric", "celsius"),
		];

		let result = pattern.with_parameters(params).unwrap();
		let expected =
			"iot/office-a/3/devices/temperature/temp-001/telemetry/celsius";
		assert_eq!(result.mqtt_pattern(), expected);
	}

	#[test]
	fn test_selective_filtering() {
		// Test case where we only want to filter specific sensors
		let pattern =
			create_pattern("sensors/{location}/{sensor_type}/{sensor_id}/data");

		// Filter only by sensor_type, leave others as wildcards
		let result = pattern
			.with_parameters([("sensor_type", "temperature")])
			.unwrap();

		// topic_pattern() preserves original template
		assert_eq!(
			result.topic_pattern(),
			"sensors/{location}/{sensor_type}/{sensor_id}/data"
		);
		// mqtt_pattern() shows partial substitution with + for unbound params
		assert_eq!(result.mqtt_pattern(), "sensors/+/temperature/+/data");
	}

	#[test]
	fn test_log_aggregation_pattern() {
		let pattern = create_pattern("logs/{service}/{level}/{details:#}");

		// Filter for specific service and log level
		let result = pattern
			.with_parameters([("service", "auth-service"), ("level", "error")])
			.unwrap();

		// topic_pattern() preserves original template
		assert_eq!(
			result.topic_pattern(),
			"logs/{service}/{level}/{details:#}"
		);
		// mqtt_pattern() substitutes bound params, converts named hash to #
		assert_eq!(result.mqtt_pattern(), "logs/auth-service/error/#");
	}
}