reinhardt-core 0.1.0

Core components for Reinhardt framework
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
//! Signal visualization for graphical representation of signal connections
//!
//! Generates visual representations of signal flows and connections using
//! various formats like DOT (Graphviz), Mermaid, and ASCII diagrams.
//!
//! # Examples
//!
//! ```
//! use reinhardt_core::signals::visualization::{SignalGraph, SignalNode, SignalEdge};
//!
//! let mut graph = SignalGraph::new();
//!
//! // Add signal node
//! graph.add_signal_node("user_created", "Sent when user is created");
//!
//! // Add receiver node
//! graph.add_receiver_node("send_email", "Sends welcome email", 10);
//!
//! // Connect signal to receiver
//! graph.add_edge("user_created", "send_email", None);
//!
//! // Generate DOT format
//! let dot = graph.to_dot();
//! assert!(dot.contains("user_created"));
//! ```

use std::collections::{HashMap, HashSet};

/// Node type in the signal graph
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NodeType {
	/// A signal that can be sent
	Signal,
	/// A receiver that handles signals
	Receiver,
	/// A middleware that intercepts signals
	Middleware,
}

/// A node in the signal graph
#[derive(Debug, Clone)]
pub struct SignalNode {
	/// Node identifier
	pub id: String,
	/// Node type
	pub node_type: NodeType,
	/// Description of the node
	pub description: String,
	/// Priority (for receivers)
	pub priority: Option<i32>,
	/// Whether this node is critical
	pub is_critical: bool,
}

/// An edge connecting two nodes in the signal graph
#[derive(Debug, Clone)]
pub struct SignalEdge {
	/// Source node ID
	pub from: String,
	/// Target node ID
	pub to: String,
	/// Optional label for the edge
	pub label: Option<String>,
	/// Whether this connection is conditional
	pub is_conditional: bool,
}

/// Graph representation of signal connections
pub struct SignalGraph {
	nodes: HashMap<String, SignalNode>,
	edges: Vec<SignalEdge>,
}

impl SignalGraph {
	/// Create a new empty signal graph
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::signals::visualization::SignalGraph;
	///
	/// let graph = SignalGraph::new();
	/// ```
	pub fn new() -> Self {
		Self {
			nodes: HashMap::new(),
			edges: Vec::new(),
		}
	}

	/// Add a signal node to the graph
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::signals::visualization::SignalGraph;
	///
	/// let mut graph = SignalGraph::new();
	/// graph.add_signal_node("user_created", "Sent when user is created");
	/// ```
	pub fn add_signal_node(&mut self, id: &str, description: &str) {
		self.nodes.insert(
			id.to_string(),
			SignalNode {
				id: id.to_string(),
				node_type: NodeType::Signal,
				description: description.to_string(),
				priority: None,
				is_critical: false,
			},
		);
	}

	/// Add a receiver node to the graph
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::signals::visualization::SignalGraph;
	///
	/// let mut graph = SignalGraph::new();
	/// graph.add_receiver_node("send_email", "Sends welcome email", 10);
	/// ```
	pub fn add_receiver_node(&mut self, id: &str, description: &str, priority: i32) {
		self.nodes.insert(
			id.to_string(),
			SignalNode {
				id: id.to_string(),
				node_type: NodeType::Receiver,
				description: description.to_string(),
				priority: Some(priority),
				is_critical: false,
			},
		);
	}

	/// Add a middleware node to the graph
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::signals::visualization::SignalGraph;
	///
	/// let mut graph = SignalGraph::new();
	/// graph.add_middleware_node("logger", "Logs all signals");
	/// ```
	pub fn add_middleware_node(&mut self, id: &str, description: &str) {
		self.nodes.insert(
			id.to_string(),
			SignalNode {
				id: id.to_string(),
				node_type: NodeType::Middleware,
				description: description.to_string(),
				priority: None,
				is_critical: false,
			},
		);
	}

	/// Mark a node as critical
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::signals::visualization::SignalGraph;
	///
	/// let mut graph = SignalGraph::new();
	/// graph.add_receiver_node("payment_processor", "Process payment", 10);
	/// graph.mark_as_critical("payment_processor");
	/// ```
	pub fn mark_as_critical(&mut self, node_id: &str) {
		if let Some(node) = self.nodes.get_mut(node_id) {
			node.is_critical = true;
		}
	}

	/// Add an edge between two nodes
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::signals::visualization::SignalGraph;
	///
	/// let mut graph = SignalGraph::new();
	/// graph.add_signal_node("user_created", "User created signal");
	/// graph.add_receiver_node("send_email", "Send email", 0);
	/// graph.add_edge("user_created", "send_email", Some("on_create".to_string()));
	/// ```
	pub fn add_edge(&mut self, from: &str, to: &str, label: Option<String>) {
		self.edges.push(SignalEdge {
			from: from.to_string(),
			to: to.to_string(),
			label,
			is_conditional: false,
		});
	}

	/// Add a conditional edge (e.g., filtered signal)
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::signals::visualization::SignalGraph;
	///
	/// let mut graph = SignalGraph::new();
	/// graph.add_signal_node("user_action", "User action signal");
	/// graph.add_receiver_node("admin_handler", "Admin handler", 0);
	/// graph.add_conditional_edge("user_action", "admin_handler", "if admin");
	/// ```
	pub fn add_conditional_edge(&mut self, from: &str, to: &str, condition: &str) {
		self.edges.push(SignalEdge {
			from: from.to_string(),
			to: to.to_string(),
			label: Some(condition.to_string()),
			is_conditional: true,
		});
	}

	/// Generate DOT (Graphviz) format representation
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::signals::visualization::SignalGraph;
	///
	/// let mut graph = SignalGraph::new();
	/// graph.add_signal_node("signal1", "First signal");
	/// graph.add_receiver_node("receiver1", "First receiver", 0);
	/// graph.add_edge("signal1", "receiver1", None);
	///
	/// let dot = graph.to_dot();
	/// assert!(dot.contains("digraph SignalGraph"));
	/// ```
	pub fn to_dot(&self) -> String {
		let mut output = String::from("digraph SignalGraph {\n");
		output.push_str("  rankdir=LR;\n");
		output.push_str("  node [shape=box, style=rounded];\n\n");

		// Define nodes (escape labels to prevent DOT injection)
		for (id, node) in &self.nodes {
			let (shape, color) = match node.node_type {
				NodeType::Signal => ("ellipse", "lightblue"),
				NodeType::Receiver => ("box", "lightgreen"),
				NodeType::Middleware => ("diamond", "lightyellow"),
			};

			let border_color = if node.is_critical { "red" } else { "black" };
			let priority_label = node
				.priority
				.map(|p| format!("\\nPriority: {}", p))
				.unwrap_or_default();

			let escaped_id = escape_dot_label(id);
			let escaped_desc = escape_dot_label(&node.description);

			output.push_str(&format!(
				"  \"{}\" [shape={}, fillcolor={}, style=\"filled,rounded\", color={}, label=\"{}{}\\n{}\"];\n",
				escaped_id, shape, color, border_color, escaped_id, priority_label, escaped_desc
			));
		}

		output.push('\n');

		// Define edges (escape labels to prevent DOT injection)
		for edge in &self.edges {
			let style = if edge.is_conditional {
				"style=dashed"
			} else {
				"style=solid"
			};

			let label = edge
				.label
				.as_ref()
				.map(|l| format!("label=\"{}\"", escape_dot_label(l)))
				.unwrap_or_default();

			output.push_str(&format!(
				"  \"{}\" -> \"{}\" [{}{}{}];\n",
				escape_dot_label(&edge.from),
				escape_dot_label(&edge.to),
				style,
				if label.is_empty() { "" } else { ", " },
				label
			));
		}

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

	/// Generate Mermaid diagram format
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::signals::visualization::SignalGraph;
	///
	/// let mut graph = SignalGraph::new();
	/// graph.add_signal_node("signal1", "First signal");
	/// graph.add_receiver_node("receiver1", "First receiver", 0);
	/// graph.add_edge("signal1", "receiver1", None);
	///
	/// let mermaid = graph.to_mermaid();
	/// assert!(mermaid.contains("graph LR"));
	/// ```
	pub fn to_mermaid(&self) -> String {
		let mut output = String::from("graph LR\n");

		// Define nodes
		for (id, node) in &self.nodes {
			let (shape_start, shape_end) = match node.node_type {
				NodeType::Signal => ("([", "])"),
				NodeType::Receiver => ("[", "]"),
				NodeType::Middleware => ("{", "}"),
			};

			let critical_marker = if node.is_critical { "âš  " } else { "" };
			let priority_label = node
				.priority
				.map(|p| format!(" P{}", p))
				.unwrap_or_default();

			output.push_str(&format!(
				"  {}{}{}{}{}{}\n",
				id, shape_start, critical_marker, node.description, priority_label, shape_end
			));
		}

		output.push('\n');

		// Define edges
		for edge in &self.edges {
			let arrow = if edge.is_conditional { "-.->" } else { "-->" };
			let label = edge
				.label
				.as_ref()
				.map(|l| format!("|{}|", l))
				.unwrap_or_default();

			output.push_str(&format!("  {} {}{} {}\n", edge.from, arrow, label, edge.to));
		}

		output
	}

	/// Generate ASCII art diagram
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::signals::visualization::SignalGraph;
	///
	/// let mut graph = SignalGraph::new();
	/// graph.add_signal_node("signal1", "Signal");
	/// graph.add_receiver_node("receiver1", "Receiver", 0);
	/// graph.add_edge("signal1", "receiver1", None);
	///
	/// let ascii = graph.to_ascii();
	/// assert!(ascii.contains("signal1"));
	/// ```
	pub fn to_ascii(&self) -> String {
		let mut output = String::from("Signal Flow Diagram\n");
		output.push_str("===================\n\n");

		// Group receivers by signal
		let mut signal_to_receivers: HashMap<String, Vec<String>> = HashMap::new();

		for edge in &self.edges {
			if let Some(from_node) = self.nodes.get(&edge.from)
				&& from_node.node_type == NodeType::Signal
			{
				signal_to_receivers
					.entry(edge.from.clone())
					.or_default()
					.push(edge.to.clone());
			}
		}

		// Generate ASCII representation
		for (signal_id, receivers) in signal_to_receivers {
			if let Some(signal_node) = self.nodes.get(&signal_id) {
				output.push_str(&format!("({}) {}\n", signal_id, signal_node.description));
				output.push_str("  |\n");

				for (i, receiver_id) in receivers.iter().enumerate() {
					if let Some(receiver_node) = self.nodes.get(receiver_id) {
						let is_last = i == receivers.len() - 1;
						let connector = if is_last {
							"  └──>"
						} else {
							"  ├──>"
						};
						let critical = if receiver_node.is_critical {
							" âš "
						} else {
							""
						};
						let priority = receiver_node
							.priority
							.map(|p| format!(" [P{}]", p))
							.unwrap_or_default();

						output.push_str(&format!(
							"{} [{}] {}{}{}\n",
							connector, receiver_id, receiver_node.description, priority, critical
						));
					}
				}

				output.push('\n');
			}
		}

		output
	}

	/// Get list of all nodes
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::signals::visualization::SignalGraph;
	///
	/// let mut graph = SignalGraph::new();
	/// graph.add_signal_node("signal1", "Signal 1");
	/// graph.add_receiver_node("receiver1", "Receiver 1", 0);
	///
	/// let nodes = graph.nodes();
	/// assert_eq!(nodes.len(), 2);
	/// ```
	pub fn nodes(&self) -> Vec<&SignalNode> {
		self.nodes.values().collect()
	}

	/// Get list of all edges
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::signals::visualization::SignalGraph;
	///
	/// let mut graph = SignalGraph::new();
	/// graph.add_signal_node("signal1", "Signal 1");
	/// graph.add_receiver_node("receiver1", "Receiver 1", 0);
	/// graph.add_edge("signal1", "receiver1", None);
	///
	/// let edges = graph.edges();
	/// assert_eq!(edges.len(), 1);
	/// ```
	pub fn edges(&self) -> &[SignalEdge] {
		&self.edges
	}

	/// Find all receivers connected to a signal
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::signals::visualization::SignalGraph;
	///
	/// let mut graph = SignalGraph::new();
	/// graph.add_signal_node("signal1", "Signal 1");
	/// graph.add_receiver_node("receiver1", "Receiver 1", 0);
	/// graph.add_edge("signal1", "receiver1", None);
	///
	/// let receivers = graph.find_receivers("signal1");
	/// assert_eq!(receivers.len(), 1);
	/// ```
	pub fn find_receivers(&self, signal_id: &str) -> Vec<&SignalNode> {
		let receiver_ids: HashSet<_> = self
			.edges
			.iter()
			.filter(|e| e.from == signal_id)
			.map(|e| e.to.as_str())
			.collect();

		receiver_ids
			.into_iter()
			.filter_map(|id| self.nodes.get(id))
			.collect()
	}

	/// Find all signals that trigger a receiver
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::signals::visualization::SignalGraph;
	///
	/// let mut graph = SignalGraph::new();
	/// graph.add_signal_node("signal1", "Signal 1");
	/// graph.add_receiver_node("receiver1", "Receiver 1", 0);
	/// graph.add_edge("signal1", "receiver1", None);
	///
	/// let signals = graph.find_signals_for_receiver("receiver1");
	/// assert_eq!(signals.len(), 1);
	/// ```
	pub fn find_signals_for_receiver(&self, receiver_id: &str) -> Vec<&SignalNode> {
		let signal_ids: HashSet<_> = self
			.edges
			.iter()
			.filter(|e| e.to == receiver_id)
			.map(|e| e.from.as_str())
			.collect();

		signal_ids
			.into_iter()
			.filter_map(|id| self.nodes.get(id))
			.collect()
	}
}

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

/// Escape special characters for DOT format labels.
///
/// Prevents content injection by escaping backslash, double-quote,
/// and newline characters that have special meaning in DOT syntax.
fn escape_dot_label(s: &str) -> String {
	s.replace('\\', "\\\\")
		.replace('"', "\\\"")
		.replace('\n', "\\n")
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn test_add_nodes() {
		let mut graph = SignalGraph::new();

		graph.add_signal_node("user_created", "User created signal");
		graph.add_receiver_node("send_email", "Send welcome email", 10);

		assert_eq!(graph.nodes.len(), 2);
	}

	#[test]
	fn test_add_edges() {
		let mut graph = SignalGraph::new();

		graph.add_signal_node("signal1", "Signal 1");
		graph.add_receiver_node("receiver1", "Receiver 1", 0);
		graph.add_edge("signal1", "receiver1", None);

		assert_eq!(graph.edges.len(), 1);
	}

	#[test]
	fn test_to_dot() {
		let mut graph = SignalGraph::new();

		graph.add_signal_node("user_created", "User created");
		graph.add_receiver_node("send_email", "Send email", 10);
		graph.add_edge("user_created", "send_email", Some("notify".to_string()));

		let dot = graph.to_dot();
		assert!(dot.contains("digraph SignalGraph"));
		assert!(dot.contains("user_created"));
		assert!(dot.contains("send_email"));
		assert!(dot.contains("notify"));
	}

	#[test]
	fn test_to_mermaid() {
		let mut graph = SignalGraph::new();

		graph.add_signal_node("signal1", "Signal");
		graph.add_receiver_node("receiver1", "Receiver", 0);
		graph.add_edge("signal1", "receiver1", None);

		let mermaid = graph.to_mermaid();
		assert!(mermaid.contains("graph LR"));
		assert!(mermaid.contains("signal1"));
	}

	#[test]
	fn test_to_ascii() {
		let mut graph = SignalGraph::new();

		graph.add_signal_node("signal1", "Test signal");
		graph.add_receiver_node("receiver1", "Test receiver", 0);
		graph.add_edge("signal1", "receiver1", None);

		let ascii = graph.to_ascii();
		assert!(ascii.contains("signal1"));
		assert!(ascii.contains("receiver1"));
	}

	#[test]
	fn test_mark_as_critical() {
		let mut graph = SignalGraph::new();

		graph.add_receiver_node("payment", "Payment processor", 10);
		graph.mark_as_critical("payment");

		let node = graph.nodes.get("payment").unwrap();
		assert!(node.is_critical);
	}

	#[test]
	fn test_find_receivers() {
		let mut graph = SignalGraph::new();

		graph.add_signal_node("signal1", "Signal");
		graph.add_receiver_node("receiver1", "Receiver 1", 0);
		graph.add_receiver_node("receiver2", "Receiver 2", 0);
		graph.add_edge("signal1", "receiver1", None);
		graph.add_edge("signal1", "receiver2", None);

		let receivers = graph.find_receivers("signal1");
		assert_eq!(receivers.len(), 2);
	}

	#[test]
	fn test_conditional_edge() {
		let mut graph = SignalGraph::new();

		graph.add_signal_node("user_action", "User action");
		graph.add_receiver_node("admin_handler", "Admin handler", 0);
		graph.add_conditional_edge("user_action", "admin_handler", "if admin");

		let edge = &graph.edges[0];
		assert!(edge.is_conditional);
	}
}