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
//! Aggregated Topics - Multi-topic subscription with pattern matching
//!
//! This module provides functionality for subscribing to multiple topics simultaneously
//! using glob patterns. Messages from all matching topics are multiplexed into a single
//! stream, with each message tagged by its source topic path.
//!
//! # Use Cases
//!
//! - Dashboard monitoring (subscribe to all cameras at once)
//! - Data recording (capture all sensors)
//! - Multi-sensor fusion (combine multiple IMU sources)
//! - Telemetry aggregation (all system metrics)
//!
//! # Example
//!
//! ```rust,no_run
//! use mecha10_core::prelude::*;
//! use mecha10_core::messages::Image;
//!
//! # async fn example(ctx: &Context) -> Result<()> {
//! // Subscribe to all camera topics
//! let mut cameras = ctx.subscribe_aggregated::<Image>("/sensor/camera/*").await?;
//!
//! while let Some((topic, image)) = cameras.recv().await {
//! println!("Received from {}: {}x{}", topic, image.width, image.height);
//! }
//! # Ok(())
//! # }
//! ```
use crate::messages::Message;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
pub enum ReceiverType<T> {
Unbounded(mpsc::UnboundedReceiver<T>),
Bounded(mpsc::Receiver<T>),
}
pub struct AggregatedReceiver<T: Message> {
pattern: String,
topics: Vec<String>,
rx: mpsc::UnboundedReceiver<(String, T)>,
_tasks: Vec<JoinHandle<()>>,
}
impl<T: Message> AggregatedReceiver<T> {
/// Create a new aggregated receiver
///
/// # Arguments
///
/// * `pattern` - The glob pattern used to match topics
/// * `receivers` - List of (topic_path, receiver) tuples for each matching topic
///
/// # Returns
///
/// A new `AggregatedReceiver` that multiplexes all input receivers
pub fn new(pattern: String, receivers: Vec<(String, mpsc::UnboundedReceiver<T>)>) -> Self {
let receivers = receivers
.into_iter()
.map(|(topic_path, receiver)| (topic_path, ReceiverType::Unbounded(receiver)))
.collect();
Self::new_mixed(pattern, receivers)
}
/// Create a new aggregated receiver supporting both bounded and unbounded channels
///
/// This version spawns one task per receiver, naturally providing fair scheduling
/// without busy-waiting. Each task forwards messages with topic tags to the
/// aggregated channel.
///
/// # Arguments
///
/// * `pattern` - The glob pattern used to match topics
/// * `receivers` - List of (topic_path, receiver) tuples for each matching topic
///
/// # Returns
///
/// A new `AggregatedReceiver` that multiplexes all input receivers with backpressure support
///
/// # Performance
///
/// Spawns one task per receiver. Each task efficiently waits on its receiver using
/// async `.recv()`, providing optimal performance without polling or busy-waiting.
/// Tokio's scheduler ensures fair multiplexing across all tasks.
pub fn new_mixed(pattern: String, receivers: Vec<(String, ReceiverType<T>)>) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
let mut tasks = Vec::new();
let mut topics = Vec::new();
for (topic_path, mut receiver) in receivers {
topics.push(topic_path.clone());
let tx = tx.clone();
let topic_path_clone = topic_path.clone();
let task = tokio::spawn(async move {
loop {
let msg_opt = match &mut receiver {
ReceiverType::Unbounded(rx) => rx.recv().await,
ReceiverType::Bounded(rx) => rx.recv().await,
};
match msg_opt {
Some(message) => {
if tx.send((topic_path_clone.clone(), message)).is_err() {
break;
}
}
None => {
break;
}
}
}
});
tasks.push(task);
}
Self {
pattern,
topics,
rx,
_tasks: tasks,
}
}
/// Receive the next message from any subscribed topic
///
/// Returns a tuple of `(topic_path, message)`.
/// Returns `None` when all senders are closed.
///
/// # Returns
///
/// * `Some((topic, message))` - Next message with its source topic
/// * `None` - All subscriptions have been closed
///
/// # Examples
///
/// ```rust,no_run
/// # use mecha10_core::prelude::*;
/// # use mecha10_core::aggregated::AggregatedReceiver;
/// # use mecha10_core::messages::Image;
/// # async fn example(mut cameras: AggregatedReceiver<Image>) -> Result<()> {
/// while let Some((topic, image)) = cameras.recv().await {
/// println!("Received from {}: {}x{}", topic, image.width, image.height);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn recv(&mut self) -> Option<(String, T)> {
self.rx.recv().await
}
/// Get the glob pattern for this aggregated receiver
///
/// # Returns
///
/// The pattern string used to match topics
///
/// # Examples
///
/// ```rust,no_run
/// # use mecha10_core::aggregated::AggregatedReceiver;
/// # use mecha10_core::messages::Message;
/// # fn example<T: Message>(receiver: &AggregatedReceiver<T>) {
/// let pattern = receiver.pattern();
/// println!("Monitoring pattern: {}", pattern);
/// # }
/// ```
pub fn pattern(&self) -> &str {
&self.pattern
}
/// Get list of currently subscribed topics
///
/// # Returns
///
/// A vector of topic paths that match the pattern
///
/// # Examples
///
/// ```rust,no_run
/// # use mecha10_core::aggregated::AggregatedReceiver;
/// # use mecha10_core::messages::Message;
/// # fn example<T: Message>(receiver: &AggregatedReceiver<T>) {
/// let topics = receiver.topics();
/// println!("Subscribed to {} topics: {:?}", topics.len(), topics);
/// # }
/// ```
pub fn topics(&self) -> &[String] {
&self.topics
}
/// Get the number of subscribed topics
///
/// # Returns
///
/// The count of topics currently being aggregated
pub fn topic_count(&self) -> usize {
self.topics.len()
}
}
impl<T: Message> Unpin for AggregatedReceiver<T> {}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn new_forwards_messages_from_unbounded_receivers() {
let (tx_a, rx_a) = mpsc::unbounded_channel::<i32>();
let (tx_b, rx_b) = mpsc::unbounded_channel::<i32>();
let mut aggregated = AggregatedReceiver::new(
"topic/*".to_string(),
vec![("topic/a".to_string(), rx_a), ("topic/b".to_string(), rx_b)],
);
assert_eq!(aggregated.pattern(), "topic/*");
assert_eq!(aggregated.topic_count(), 2);
tx_a.send(1).unwrap();
tx_b.send(2).unwrap();
drop(tx_a);
drop(tx_b);
let mut received = vec![aggregated.recv().await.unwrap(), aggregated.recv().await.unwrap()];
received.sort();
assert_eq!(received, vec![("topic/a".to_string(), 1), ("topic/b".to_string(), 2)]);
assert_eq!(aggregated.recv().await, None);
}
}
pub mod pattern {
/// Check if a topic path matches a glob pattern
///
/// Supports full glob syntax via the `globset` crate:
/// - `*` matches any sequence of characters within a path segment
/// - `**` matches any sequence of path segments (including none)
/// - `{a,b}` matches either a or b
/// - `?` matches any single character
/// - `[abc]` matches any character in the set
/// - `[!abc]` matches any character not in the set
///
/// # Arguments
///
/// * `path` - The topic path to test
/// * `pattern` - The glob pattern to match against
///
/// # Returns
///
/// `true` if the path matches the pattern, `false` otherwise
///
/// # Examples
///
/// ```rust
/// use mecha10_core::aggregated::pattern::matches_pattern;
///
/// assert!(matches_pattern("/sensor/camera/rgb", "/sensor/camera/*"));
/// assert!(matches_pattern("/sensor/camera/depth", "/sensor/camera/*"));
/// assert!(!matches_pattern("/sensor/lidar/scan", "/sensor/camera/*"));
///
/// assert!(matches_pattern("/sensor/camera/rgb", "/sensor/**"));
/// assert!(matches_pattern("/sensor/lidar/scan", "/sensor/**"));
///
/// // Advanced patterns
/// assert!(matches_pattern("/sensor/camera1/rgb", "/sensor/camera?/rgb"));
/// assert!(matches_pattern("/sensor/camera/left", "/sensor/camera/{left,right}"));
/// assert!(matches_pattern("/sensor/imu0/data", "/sensor/imu[0-9]/data"));
/// ```
pub fn matches_pattern(path: &str, pattern: &str) -> bool {
use globset::GlobBuilder;
let glob = GlobBuilder::new(pattern)
.literal_separator(false)
.backslash_escape(true)
.build();
match glob {
Ok(glob_pattern) => {
let matcher = glob_pattern.compile_matcher();
matcher.is_match(path)
}
Err(_) => path == pattern,
}
}
/// Convert a glob pattern to a Redis KEYS pattern
///
/// # Arguments
///
/// * `pattern` - The glob pattern
///
/// # Returns
///
/// A Redis-compatible KEYS pattern
///
/// # Examples
///
/// ```rust
/// use mecha10_core::aggregated::pattern::convert_glob_to_redis;
///
/// assert_eq!(
/// convert_glob_to_redis("/sensor/camera/*"),
/// "mecha10:/sensor/camera/*"
/// );
/// ```
pub fn convert_glob_to_redis(pattern: &str) -> String {
format!("mecha10:{}", pattern)
}
}