mecha10-core 0.8.0

Mecha10 core runtime and foundational types
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
//! Topic Registry for Runtime Introspection and Validation
//!
//! Provides a central registry for tracking all active topics, their publishers,
//! subscribers, and message types. Enables runtime discovery, monitoring, and
//! debugging of the pub/sub system.
//!
//! # Use Cases
//!
//! - Discover what topics exist at runtime
//! - Find which nodes publish/subscribe to a topic
//! - Validate topic usage (orphaned topics, missing publishers/subscribers)
//! - Monitor topic activity (message rates, last activity)
//! - Debug communication issues
//! - Generate system topology diagrams
//!
//! # Example
//!
//! ```rust
//! use mecha10_core::prelude::*;
//! use mecha10_core::topic_registry::{TopicRegistry, TopicInfo};
//!
//! # async fn example() -> Result<()> {
//! let registry = TopicRegistry::new();
//!
//! // Register a publisher
//! registry.register_publisher("/sensor/camera/rgb", "camera_node", "Image").await;
//!
//! // Register a subscriber
//! registry.register_subscriber("/sensor/camera/rgb", "vision_node", "Image").await;
//!
//! // Query topic info
//! if let Some(info) = registry.get_topic("/sensor/camera/rgb").await {
//!     println!("Topic: {}", info.topic);
//!     println!("Publishers: {:?}", info.publishers);
//!     println!("Subscribers: {:?}", info.subscribers);
//!     println!("Message type: {}", info.message_type);
//! }
//!
//! // List all topics
//! let topics = registry.list_topics().await;
//! for topic in topics {
//!     println!("- {}", topic);
//! }
//!
//! // Validate topology
//! let issues = registry.validate().await;
//! for issue in issues {
//!     println!("Warning: {}", issue);
//! }
//! # Ok(())
//! # }
//! ```

use crate::prelude::now_micros;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{debug, info, warn};

use crate::rwlock_collections::RwLockMapExt;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TopicInfo {
    pub topic: String,

    pub message_type: String,

    pub publishers: Vec<String>,

    pub subscribers: Vec<String>,

    pub created_at: u64,

    pub last_publisher_added: Option<u64>,

    pub last_subscriber_added: Option<u64>,

    pub description: Option<String>,

    pub metadata: HashMap<String, String>,
}

impl TopicInfo {
    /// Create new topic info
    pub fn new(topic: &str, message_type: &str) -> Self {
        Self {
            topic: topic.to_string(),
            message_type: message_type.to_string(),
            publishers: Vec::new(),
            subscribers: Vec::new(),
            created_at: now_micros(),
            last_publisher_added: None,
            last_subscriber_added: None,
            description: None,
            metadata: HashMap::new(),
        }
    }

    /// Add a publisher
    pub fn add_publisher(&mut self, node_id: &str) {
        Self::add_node(&mut self.publishers, &mut self.last_publisher_added, node_id);
    }

    /// Add a subscriber
    pub fn add_subscriber(&mut self, node_id: &str) {
        Self::add_node(&mut self.subscribers, &mut self.last_subscriber_added, node_id);
    }

    /// Remove a publisher
    pub fn remove_publisher(&mut self, node_id: &str) {
        Self::remove_node(&mut self.publishers, node_id);
    }

    /// Remove a subscriber
    pub fn remove_subscriber(&mut self, node_id: &str) {
        Self::remove_node(&mut self.subscribers, node_id);
    }

    /// Shared body behind `add_publisher`/`add_subscriber`, which differ only in which
    /// side's node list and "last added" timestamp they update.
    fn add_node(list: &mut Vec<String>, last_added: &mut Option<u64>, node_id: &str) {
        if !list.contains(&node_id.to_string()) {
            list.push(node_id.to_string());
            *last_added = Some(now_micros());
        }
    }

    /// Shared body behind `remove_publisher`/`remove_subscriber`.
    fn remove_node(list: &mut Vec<String>, node_id: &str) {
        list.retain(|n| n != node_id);
    }

    /// Check if topic is orphaned (no publishers or no subscribers)
    pub fn is_orphaned(&self) -> bool {
        self.publishers.is_empty() || self.subscribers.is_empty()
    }

    /// Get the number of publishers
    pub fn publisher_count(&self) -> usize {
        self.publishers.len()
    }

    /// Get the number of subscribers
    pub fn subscriber_count(&self) -> usize {
        self.subscribers.len()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Role {
    Publisher,
    Subscriber,
}

impl Role {
    /// Human-readable label used in log messages.
    fn label(&self) -> &'static str {
        match self {
            Role::Publisher => "publisher",
            Role::Subscriber => "subscriber",
        }
    }
}

#[derive(Clone)]
pub struct TopicRegistry {
    topics: Arc<RwLock<HashMap<String, TopicInfo>>>,

    node_publishers: Arc<RwLock<HashMap<String, HashSet<String>>>>,

    node_subscribers: Arc<RwLock<HashMap<String, HashSet<String>>>>,
}

impl TopicRegistry {
    /// Create a new topic registry
    pub fn new() -> Self {
        info!("Creating new topic registry");
        Self {
            topics: Arc::new(RwLock::new(HashMap::new())),
            node_publishers: Arc::new(RwLock::new(HashMap::new())),
            node_subscribers: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    pub async fn register_publisher(&self, topic: &str, node_id: &str, message_type: &str) {
        self.register(Role::Publisher, topic, node_id, message_type).await;
    }

    /// Register a subscriber for a topic
    ///
    /// # Arguments
    ///
    /// * `topic` - Topic path
    /// * `node_id` - Subscribing node identifier
    /// * `message_type` - Message type name
    pub async fn register_subscriber(&self, topic: &str, node_id: &str, message_type: &str) {
        self.register(Role::Subscriber, topic, node_id, message_type).await;
    }

    /// Unregister a publisher
    pub async fn unregister_publisher(&self, topic: &str, node_id: &str) {
        self.unregister(Role::Publisher, topic, node_id).await;
    }

    /// Unregister a subscriber
    pub async fn unregister_subscriber(&self, topic: &str, node_id: &str) {
        self.unregister(Role::Subscriber, topic, node_id).await;
    }

    /// Node->topics reverse-mapping table for the given role.
    fn node_map(&self, role: Role) -> &Arc<RwLock<HashMap<String, HashSet<String>>>> {
        match role {
            Role::Publisher => &self.node_publishers,
            Role::Subscriber => &self.node_subscribers,
        }
    }

    /// Shared implementation behind `register_publisher`/`register_subscriber`.
    ///
    /// Looks up (or creates) the topic's `TopicInfo`, records the node on the
    /// side of the entry indicated by `role`, and updates the corresponding
    /// node->topics reverse mapping.
    async fn register(&self, role: Role, topic: &str, node_id: &str, message_type: &str) {
        let mut topics = self.topics.write().await;

        let topic_info = topics
            .entry(topic.to_string())
            .or_insert_with(|| TopicInfo::new(topic, message_type));

        match role {
            Role::Publisher => topic_info.add_publisher(node_id),
            Role::Subscriber => topic_info.add_subscriber(node_id),
        }

        let mut node_entries = self.node_map(role).write().await;
        node_entries
            .entry(node_id.to_string())
            .or_default()
            .insert(topic.to_string());

        debug!(
            "Registered {}: node='{}', topic='{}', type='{}'",
            role.label(),
            node_id,
            topic,
            message_type
        );
    }

    /// Shared implementation behind `unregister_publisher`/`unregister_subscriber`.
    ///
    /// Removes the node from the side of the topic's `TopicInfo` indicated by
    /// `role`, drops the topic entirely if it has no publishers or
    /// subscribers left, and updates the corresponding node->topics reverse
    /// mapping.
    async fn unregister(&self, role: Role, topic: &str, node_id: &str) {
        let mut topics = self.topics.write().await;

        if let Some(info) = topics.get_mut(topic) {
            match role {
                Role::Publisher => info.remove_publisher(node_id),
                Role::Subscriber => info.remove_subscriber(node_id),
            }

            if info.publishers.is_empty() && info.subscribers.is_empty() {
                topics.remove(topic);
                debug!("Removed topic '{}' (no publishers or subscribers)", topic);
            }
        }

        let mut node_entries = self.node_map(role).write().await;
        if let Some(topics_set) = node_entries.get_mut(node_id) {
            topics_set.remove(topic);
            if topics_set.is_empty() {
                node_entries.remove(node_id);
            }
        }

        debug!("Unregistered {}: node='{}', topic='{}'", role.label(), node_id, topic);
    }

    /// Unregister all topics for a node (when node stops)
    pub async fn unregister_node(&self, node_id: &str) {
        let topics_published = {
            let node_pubs = self.node_publishers.read().await;
            node_pubs.get(node_id).cloned().unwrap_or_default()
        };

        for topic in topics_published {
            self.unregister_publisher(&topic, node_id).await;
        }

        let topics_subscribed = {
            let node_subs = self.node_subscribers.read().await;
            node_subs.get(node_id).cloned().unwrap_or_default()
        };

        for topic in topics_subscribed {
            self.unregister_subscriber(&topic, node_id).await;
        }

        info!("Unregistered all topics for node '{}'", node_id);
    }

    /// Get information about a specific topic
    pub async fn get_topic(&self, topic: &str) -> Option<TopicInfo> {
        self.topics.cloned_get(&topic.to_string()).await
    }

    /// List all registered topics
    pub async fn list_topics(&self) -> Vec<String> {
        self.topics.cloned_keys().await
    }

    /// Get all topic information
    pub async fn get_all_topics(&self) -> Vec<TopicInfo> {
        self.topics.cloned_values().await
    }

    /// Find topics by message type
    pub async fn find_by_message_type(&self, message_type: &str) -> Vec<TopicInfo> {
        let topics = self.topics.read().await;
        topics
            .values()
            .filter(|info| info.message_type == message_type)
            .cloned()
            .collect()
    }

    /// Find topics published by a node
    pub async fn topics_published_by(&self, node_id: &str) -> Vec<String> {
        self.topics_for_role(Role::Publisher, node_id).await
    }

    /// Find topics subscribed to by a node
    pub async fn topics_subscribed_by(&self, node_id: &str) -> Vec<String> {
        self.topics_for_role(Role::Subscriber, node_id).await
    }

    /// Shared implementation behind `topics_published_by`/`topics_subscribed_by`.
    async fn topics_for_role(&self, role: Role, node_id: &str) -> Vec<String> {
        let node_entries = self.node_map(role).read().await;
        node_entries
            .get(node_id)
            .cloned()
            .unwrap_or_default()
            .into_iter()
            .collect()
    }

    /// Get total number of topics
    pub async fn topic_count(&self) -> usize {
        let topics = self.topics.read().await;
        topics.len()
    }

    /// Validate the topic topology
    ///
    /// Returns a list of validation issues:
    /// - Topics with no publishers
    /// - Topics with no subscribers
    /// - Type mismatches
    pub async fn validate(&self) -> Vec<String> {
        let mut issues = Vec::new();
        let topics = self.topics.read().await;

        for (topic, info) in topics.iter() {
            if info.publishers.is_empty() {
                issues.push(format!(
                    "Topic '{}' has no publishers (subscribed by: {:?})",
                    topic, info.subscribers
                ));
            }

            if info.subscribers.is_empty() {
                issues.push(format!(
                    "Topic '{}' has no subscribers (published by: {:?})",
                    topic, info.publishers
                ));
            }
        }

        if !issues.is_empty() {
            warn!("Found {} topology issues", issues.len());
        }

        issues
    }

    /// Get topology statistics
    pub async fn stats(&self) -> TopologyStats {
        let topics = self.topics.read().await;

        let total_topics = topics.len();
        let total_publishers: usize = topics.values().map(|t| t.publishers.len()).sum();
        let total_subscribers: usize = topics.values().map(|t| t.subscribers.len()).sum();

        let orphaned_topics = topics.values().filter(|t| t.is_orphaned()).count();

        let topics_without_publishers = topics.values().filter(|t| t.publishers.is_empty()).count();

        let topics_without_subscribers = topics.values().filter(|t| t.subscribers.is_empty()).count();

        TopologyStats {
            total_topics,
            total_publishers,
            total_subscribers,
            orphaned_topics,
            topics_without_publishers,
            topics_without_subscribers,
        }
    }

    /// Export topology as DOT graph (for Graphviz visualization)
    pub async fn export_dot(&self) -> String {
        let mut dot = String::from("digraph TopicTopology {\n");
        dot.push_str("  rankdir=LR;\n");
        dot.push_str("  node [shape=box];\n\n");

        let topics = self.topics.read().await;

        for (topic, info) in topics.iter() {
            let label = format!("{}\\n({})", topic, info.message_type);
            dot.push_str(&format!(
                "  \"{}\" [label=\"{}\", shape=ellipse, style=filled, fillcolor=lightblue];\n",
                topic, label
            ));
        }

        dot.push('\n');

        for (topic, info) in topics.iter() {
            for pub_node in &info.publishers {
                dot.push_str(&format!(
                    "  \"{}\" -> \"{}\" [label=\"pub\", color=green];\n",
                    pub_node, topic
                ));
            }

            for sub_node in &info.subscribers {
                dot.push_str(&format!(
                    "  \"{}\" -> \"{}\" [label=\"sub\", color=blue];\n",
                    topic, sub_node
                ));
            }
        }

        dot.push_str("}\n");
        dot
    }

    /// Clear all registered topics (for testing)
    pub async fn clear(&self) {
        let mut topics = self.topics.write().await;
        topics.clear();

        let mut node_pubs = self.node_publishers.write().await;
        node_pubs.clear();

        let mut node_subs = self.node_subscribers.write().await;
        node_subs.clear();

        info!("Cleared topic registry");
    }
}

impl Default for TopicRegistry {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TopologyStats {
    pub total_topics: usize,

    pub total_publishers: usize,

    pub total_subscribers: usize,

    pub orphaned_topics: usize,

    pub topics_without_publishers: usize,

    pub topics_without_subscribers: usize,
}