Skip to main content

oxirs_stream/
visual_designer_engine.rs

1//! # Visual Designer — Engine
2//!
3//! Core engine components: `VisualStreamDesigner`, `PipelineValidator`,
4//! and `PipelineOptimizer` with SVG/DOT/Mermaid export, validation logic,
5//! and automatic pipeline optimization.
6
7use anyhow::{anyhow, Result};
8use chrono::Utc;
9use std::collections::{HashMap, HashSet};
10use std::sync::Arc;
11use tokio::sync::RwLock;
12use tracing::{debug, info};
13use uuid::Uuid;
14
15use crate::visual_designer_types::{
16    BackpressureStrategy, Breakpoint, DataType, DebugMetrics, DebuggerConfig, DebuggerState,
17    EdgeConfig, EdgeMetadata, EdgeStyle, EdgeType, ErrorHandling, ExportFormat, ImpactLevel,
18    LineType, NodeConfig, NodeMetadata, NodeStatus, NodeType, OptimizationResult,
19    OptimizationSuggestion, OptimizationType, PipelineDebugger, PipelineEdge, PipelineInfo,
20    PipelineMetadata, PipelineMetrics, PipelineNode, PipelineOptimizer, PipelineValidator, Port,
21    PortType, Position, ResourceLimits, ValidationError, ValidationErrorType, ValidationResult,
22    ValidationWarning, ValidationWarningType, VisualDesignerConfig, VisualPipeline,
23};
24
25/// Visual designer main struct
26pub struct VisualStreamDesigner {
27    config: VisualDesignerConfig,
28    pipelines: Arc<RwLock<HashMap<String, VisualPipeline>>>,
29    debuggers: Arc<RwLock<HashMap<String, PipelineDebugger>>>,
30    validator: Arc<PipelineValidator>,
31    optimizer: Arc<PipelineOptimizer>,
32}
33
34impl VisualStreamDesigner {
35    /// Create a new visual stream designer
36    pub fn new(config: VisualDesignerConfig) -> Self {
37        Self {
38            config: config.clone(),
39            pipelines: Arc::new(RwLock::new(HashMap::new())),
40            debuggers: Arc::new(RwLock::new(HashMap::new())),
41            validator: Arc::new(PipelineValidator::new(config.clone())),
42            optimizer: Arc::new(PipelineOptimizer::new(config)),
43        }
44    }
45
46    /// Create a new empty pipeline
47    pub async fn create_pipeline(
48        &self,
49        name: String,
50        description: Option<String>,
51    ) -> Result<String> {
52        let pipeline = VisualPipeline {
53            id: Uuid::new_v4().to_string(),
54            name,
55            description,
56            version: "1.0.0".to_string(),
57            nodes: HashMap::new(),
58            edges: HashMap::new(),
59            metadata: PipelineMetadata {
60                created_at: Utc::now(),
61                updated_at: Utc::now(),
62                author: None,
63                tags: Vec::new(),
64                properties: HashMap::new(),
65            },
66            validation_result: None,
67        };
68
69        let id = pipeline.id.clone();
70        self.pipelines.write().await.insert(id.clone(), pipeline);
71
72        info!("Created new pipeline: {}", id);
73        Ok(id)
74    }
75
76    /// Add a node to the pipeline
77    pub async fn add_node(
78        &self,
79        pipeline_id: &str,
80        name: String,
81        node_type: NodeType,
82        position: Position,
83    ) -> Result<String> {
84        let mut pipelines = self.pipelines.write().await;
85        let pipeline = pipelines
86            .get_mut(pipeline_id)
87            .ok_or_else(|| anyhow!("Pipeline not found"))?;
88
89        let node = PipelineNode {
90            id: Uuid::new_v4().to_string(),
91            name,
92            node_type: node_type.clone(),
93            position,
94            config: Self::default_node_config(&node_type),
95            metadata: NodeMetadata {
96                created_at: Utc::now(),
97                updated_at: Utc::now(),
98                version: "1.0.0".to_string(),
99                author: None,
100                description: None,
101                tags: Vec::new(),
102            },
103            status: NodeStatus::Idle,
104        };
105
106        let node_id = node.id.clone();
107        pipeline.nodes.insert(node_id.clone(), node);
108        pipeline.metadata.updated_at = Utc::now();
109
110        debug!("Added node {} to pipeline {}", node_id, pipeline_id);
111        Ok(node_id)
112    }
113
114    /// Add an edge connecting two nodes
115    pub async fn add_edge(
116        &self,
117        pipeline_id: &str,
118        source_node_id: String,
119        source_port_id: String,
120        target_node_id: String,
121        target_port_id: String,
122    ) -> Result<String> {
123        let mut pipelines = self.pipelines.write().await;
124        let pipeline = pipelines
125            .get_mut(pipeline_id)
126            .ok_or_else(|| anyhow!("Pipeline not found"))?;
127
128        // Validate nodes exist
129        if !pipeline.nodes.contains_key(&source_node_id) {
130            return Err(anyhow!("Source node not found"));
131        }
132        if !pipeline.nodes.contains_key(&target_node_id) {
133            return Err(anyhow!("Target node not found"));
134        }
135
136        let edge = PipelineEdge {
137            id: Uuid::new_v4().to_string(),
138            source_node_id,
139            source_port_id,
140            target_node_id,
141            target_port_id,
142            edge_type: EdgeType::DataFlow,
143            config: EdgeConfig {
144                buffer_size: 1000,
145                backpressure_strategy: BackpressureStrategy::Block,
146                error_handling: ErrorHandling::Propagate,
147            },
148            metadata: EdgeMetadata {
149                created_at: Utc::now(),
150                label: None,
151                style: EdgeStyle {
152                    color: "#000000".to_string(),
153                    thickness: 2.0,
154                    line_type: LineType::Solid,
155                },
156            },
157        };
158
159        let edge_id = edge.id.clone();
160        pipeline.edges.insert(edge_id.clone(), edge);
161        pipeline.metadata.updated_at = Utc::now();
162
163        debug!("Added edge {} to pipeline {}", edge_id, pipeline_id);
164        Ok(edge_id)
165    }
166
167    /// Validate a pipeline
168    pub async fn validate_pipeline(&self, pipeline_id: &str) -> Result<ValidationResult> {
169        let pipelines = self.pipelines.read().await;
170        let pipeline = pipelines
171            .get(pipeline_id)
172            .ok_or_else(|| anyhow!("Pipeline not found"))?;
173
174        self.validator.validate(pipeline).await
175    }
176
177    /// Optimize a pipeline
178    pub async fn optimize_pipeline(&self, pipeline_id: &str) -> Result<OptimizationResult> {
179        let pipelines = self.pipelines.read().await;
180        let pipeline = pipelines
181            .get(pipeline_id)
182            .ok_or_else(|| anyhow!("Pipeline not found"))?;
183
184        self.optimizer.optimize(pipeline).await
185    }
186
187    /// Export pipeline to specified format
188    pub async fn export_pipeline(&self, pipeline_id: &str, format: ExportFormat) -> Result<String> {
189        let pipelines = self.pipelines.read().await;
190        let pipeline = pipelines
191            .get(pipeline_id)
192            .ok_or_else(|| anyhow!("Pipeline not found"))?;
193
194        match format {
195            ExportFormat::Json => serde_json::to_string_pretty(pipeline)
196                .map_err(|e| anyhow!("JSON export failed: {}", e)),
197            ExportFormat::Yaml => {
198                serde_yaml::to_string(pipeline).map_err(|e| anyhow!("YAML export failed: {}", e))
199            }
200            ExportFormat::Dot => export_dot(pipeline),
201            ExportFormat::Mermaid => export_mermaid(pipeline),
202            ExportFormat::Svg => export_svg(pipeline),
203            ExportFormat::Png => Err(anyhow!(
204                "PNG export requires SVG rasterization; use ExportFormat::Svg and convert with \
205                 resvg/tiny-skia externally (these crates depend on miniz_oxide which is \
206                 prohibited by COOLJAPAN Pure Rust Policy)"
207            )),
208        }
209    }
210
211    /// Import pipeline from string
212    pub async fn import_pipeline(&self, data: &str, format: ExportFormat) -> Result<String> {
213        let pipeline: VisualPipeline = match format {
214            ExportFormat::Json => {
215                serde_json::from_str(data).map_err(|e| anyhow!("JSON import failed: {}", e))?
216            }
217            ExportFormat::Yaml => {
218                serde_yaml::from_str(data).map_err(|e| anyhow!("YAML import failed: {}", e))?
219            }
220            _ => return Err(anyhow!("Import format not supported")),
221        };
222
223        let id = pipeline.id.clone();
224        self.pipelines.write().await.insert(id.clone(), pipeline);
225
226        info!("Imported pipeline: {}", id);
227        Ok(id)
228    }
229
230    /// Create a debugger for a pipeline
231    pub async fn create_debugger(
232        &self,
233        pipeline_id: &str,
234        config: DebuggerConfig,
235    ) -> Result<String> {
236        let pipelines = self.pipelines.read().await;
237        let pipeline = pipelines
238            .get(pipeline_id)
239            .ok_or_else(|| anyhow!("Pipeline not found"))?;
240
241        let max_event_history = config.max_event_history;
242        let debugger = PipelineDebugger {
243            pipeline: pipeline.clone(),
244            config,
245            state: Arc::new(RwLock::new(DebuggerState {
246                is_running: false,
247                is_paused: false,
248                current_node_id: None,
249                execution_stack: Vec::new(),
250                variables: HashMap::new(),
251                metrics: DebugMetrics::default(),
252            })),
253            breakpoints: Arc::new(RwLock::new(HashMap::new())),
254            event_history: Arc::new(RwLock::new(std::collections::VecDeque::with_capacity(
255                max_event_history,
256            ))),
257        };
258
259        let debugger_id = Uuid::new_v4().to_string();
260        self.debuggers
261            .write()
262            .await
263            .insert(debugger_id.clone(), debugger);
264
265        info!(
266            "Created debugger {} for pipeline {}",
267            debugger_id, pipeline_id
268        );
269        Ok(debugger_id)
270    }
271
272    /// Add a breakpoint to a debugger
273    pub async fn add_breakpoint(
274        &self,
275        debugger_id: &str,
276        node_id: String,
277        condition: Option<String>,
278    ) -> Result<String> {
279        let debuggers = self.debuggers.read().await;
280        let debugger = debuggers
281            .get(debugger_id)
282            .ok_or_else(|| anyhow!("Debugger not found"))?;
283
284        let breakpoint = Breakpoint {
285            id: Uuid::new_v4().to_string(),
286            node_id,
287            condition,
288            enabled: true,
289            hit_count: 0,
290            max_hits: None,
291        };
292
293        let breakpoint_id = breakpoint.id.clone();
294        debugger
295            .breakpoints
296            .write()
297            .await
298            .insert(breakpoint_id.clone(), breakpoint);
299
300        debug!(
301            "Added breakpoint {} to debugger {}",
302            breakpoint_id, debugger_id
303        );
304        Ok(breakpoint_id)
305    }
306
307    /// Get debugger state
308    pub async fn get_debugger_state(&self, debugger_id: &str) -> Result<DebuggerState> {
309        let debuggers = self.debuggers.read().await;
310        let debugger = debuggers
311            .get(debugger_id)
312            .ok_or_else(|| anyhow!("Debugger not found"))?;
313
314        let state = debugger.state.read().await.clone();
315        drop(debuggers); // Explicitly drop to avoid borrow issues
316        Ok(state)
317    }
318
319    /// Get event history from debugger
320    pub async fn get_event_history(
321        &self,
322        debugger_id: &str,
323        limit: Option<usize>,
324    ) -> Result<Vec<crate::visual_designer_types::DebugEvent>> {
325        let debuggers = self.debuggers.read().await;
326        let debugger = debuggers
327            .get(debugger_id)
328            .ok_or_else(|| anyhow!("Debugger not found"))?;
329
330        let history = debugger.event_history.read().await;
331        let limit = limit.unwrap_or(history.len());
332
333        Ok(history.iter().rev().take(limit).cloned().collect())
334    }
335
336    /// Get default node configuration based on type
337    fn default_node_config(_node_type: &NodeType) -> NodeConfig {
338        NodeConfig {
339            parameters: HashMap::new(),
340            input_ports: vec![Port {
341                id: "input".to_string(),
342                name: "Input".to_string(),
343                port_type: PortType::Input,
344                data_type: DataType::StreamEvent,
345                required: true,
346            }],
347            output_ports: vec![Port {
348                id: "output".to_string(),
349                name: "Output".to_string(),
350                port_type: PortType::Output,
351                data_type: DataType::StreamEvent,
352                required: false,
353            }],
354            resource_limits: ResourceLimits {
355                max_memory_mb: Some(1024),
356                max_cpu_percent: Some(50.0),
357                max_execution_time_ms: Some(5000),
358                max_events_per_second: Some(10000),
359            },
360        }
361    }
362
363    /// List all pipelines
364    pub async fn list_pipelines(&self) -> Vec<PipelineInfo> {
365        let pipelines = self.pipelines.read().await;
366        pipelines
367            .values()
368            .map(|p| PipelineInfo {
369                id: p.id.clone(),
370                name: p.name.clone(),
371                version: p.version.clone(),
372                node_count: p.nodes.len(),
373                edge_count: p.edges.len(),
374                created_at: p.metadata.created_at,
375                updated_at: p.metadata.updated_at,
376            })
377            .collect()
378    }
379
380    /// Get pipeline details
381    pub async fn get_pipeline(&self, pipeline_id: &str) -> Result<VisualPipeline> {
382        let pipelines = self.pipelines.read().await;
383        pipelines
384            .get(pipeline_id)
385            .cloned()
386            .ok_or_else(|| anyhow!("Pipeline not found"))
387    }
388
389    /// Delete a pipeline
390    pub async fn delete_pipeline(&self, pipeline_id: &str) -> Result<()> {
391        let mut pipelines = self.pipelines.write().await;
392        pipelines
393            .remove(pipeline_id)
394            .ok_or_else(|| anyhow!("Pipeline not found"))?;
395
396        info!("Deleted pipeline: {}", pipeline_id);
397        Ok(())
398    }
399}
400
401// ---------------------------------------------------------------------------
402// Pipeline validator
403// ---------------------------------------------------------------------------
404
405impl PipelineValidator {
406    pub fn new(config: VisualDesignerConfig) -> Self {
407        Self { config }
408    }
409
410    pub async fn validate(&self, pipeline: &VisualPipeline) -> Result<ValidationResult> {
411        let mut errors = Vec::new();
412        let mut warnings = Vec::new();
413
414        // Check for cyclic dependencies
415        if self.has_cycle(pipeline) {
416            errors.push(ValidationError {
417                error_type: ValidationErrorType::CyclicDependency,
418                message: "Pipeline contains cyclic dependencies".to_string(),
419                node_id: None,
420                edge_id: None,
421            });
422        }
423
424        // Check for disconnected nodes
425        let disconnected = self.find_disconnected_nodes(pipeline);
426        for node_id in disconnected {
427            warnings.push(ValidationWarning {
428                warning_type: ValidationWarningType::UnusedPort,
429                message: format!("Node {} is disconnected", node_id),
430                node_id: Some(node_id),
431                suggestion: Some("Connect this node to the pipeline".to_string()),
432            });
433        }
434
435        // Check data type compatibility
436        for edge in pipeline.edges.values() {
437            if let Err(e) = self.check_data_type_compatibility(pipeline, edge) {
438                errors.push(ValidationError {
439                    error_type: ValidationErrorType::IncompatibleDataTypes,
440                    message: e.to_string(),
441                    node_id: None,
442                    edge_id: Some(edge.id.clone()),
443                });
444            }
445        }
446
447        // Check resource limits
448        if pipeline.nodes.len() > self.config.max_nodes {
449            errors.push(ValidationError {
450                error_type: ValidationErrorType::ResourceLimitExceeded,
451                message: format!(
452                    "Pipeline exceeds maximum node count: {} > {}",
453                    pipeline.nodes.len(),
454                    self.config.max_nodes
455                ),
456                node_id: None,
457                edge_id: None,
458            });
459        }
460
461        Ok(ValidationResult {
462            is_valid: errors.is_empty(),
463            errors,
464            warnings,
465            validated_at: Utc::now(),
466        })
467    }
468
469    fn has_cycle(&self, pipeline: &VisualPipeline) -> bool {
470        let mut visited = HashSet::new();
471        let mut rec_stack = HashSet::new();
472
473        for node_id in pipeline.nodes.keys() {
474            if Self::detect_cycle_util(pipeline, node_id, &mut visited, &mut rec_stack) {
475                return true;
476            }
477        }
478
479        false
480    }
481
482    fn detect_cycle_util(
483        pipeline: &VisualPipeline,
484        node_id: &str,
485        visited: &mut HashSet<String>,
486        rec_stack: &mut HashSet<String>,
487    ) -> bool {
488        if !visited.contains(node_id) {
489            visited.insert(node_id.to_string());
490            rec_stack.insert(node_id.to_string());
491
492            // Get all neighbors
493            let neighbors: Vec<String> = pipeline
494                .edges
495                .values()
496                .filter(|e| e.source_node_id == node_id)
497                .map(|e| e.target_node_id.clone())
498                .collect();
499
500            for neighbor in neighbors {
501                if !visited.contains(&neighbor)
502                    && Self::detect_cycle_util(pipeline, &neighbor, visited, rec_stack)
503                {
504                    return true;
505                }
506                if rec_stack.contains(&neighbor) {
507                    return true;
508                }
509            }
510        }
511
512        rec_stack.remove(node_id);
513        false
514    }
515
516    fn find_disconnected_nodes(&self, pipeline: &VisualPipeline) -> Vec<String> {
517        let mut connected = HashSet::new();
518
519        for edge in pipeline.edges.values() {
520            connected.insert(edge.source_node_id.clone());
521            connected.insert(edge.target_node_id.clone());
522        }
523
524        pipeline
525            .nodes
526            .keys()
527            .filter(|id| !connected.contains(*id))
528            .cloned()
529            .collect()
530    }
531
532    fn check_data_type_compatibility(
533        &self,
534        _pipeline: &VisualPipeline,
535        _edge: &PipelineEdge,
536    ) -> Result<()> {
537        // Simplified check - in real implementation, would verify port data types match
538        Ok(())
539    }
540}
541
542// ---------------------------------------------------------------------------
543// Pipeline optimizer
544// ---------------------------------------------------------------------------
545
546impl PipelineOptimizer {
547    pub fn new(config: VisualDesignerConfig) -> Self {
548        Self { config }
549    }
550
551    pub async fn optimize(&self, pipeline: &VisualPipeline) -> Result<OptimizationResult> {
552        let mut suggestions = Vec::new();
553
554        // Analyze pipeline structure
555        let metrics = self.analyze_structure(pipeline);
556
557        // Generate optimization suggestions — trigger when either the longest path exceeds
558        // 10 hops (max_chain_length) or the average depth across all nodes exceeds 10.
559        if metrics.max_chain_length > 10 || metrics.avg_chain_length > 10.0 {
560            suggestions.push(OptimizationSuggestion {
561                suggestion_type: OptimizationType::ReduceChainLength,
562                impact: ImpactLevel::High,
563                description: "Consider breaking long chains into parallel branches".to_string(),
564                estimated_improvement: 30.0,
565            });
566        }
567
568        if metrics.parallel_opportunities > 0 {
569            suggestions.push(OptimizationSuggestion {
570                suggestion_type: OptimizationType::IncreaseParallelism,
571                impact: ImpactLevel::Medium,
572                description: format!(
573                    "Found {} opportunities for parallel processing",
574                    metrics.parallel_opportunities
575                ),
576                estimated_improvement: 15.0 * metrics.parallel_opportunities as f64,
577            });
578        }
579
580        Ok(OptimizationResult {
581            original_metrics: metrics,
582            suggestions,
583            optimized_at: Utc::now(),
584        })
585    }
586
587    fn analyze_structure(&self, pipeline: &VisualPipeline) -> PipelineMetrics {
588        let mut total_chain_length = 0usize;
589        let mut max_depth = 0usize;
590        let chain_count = pipeline.nodes.len();
591
592        // Simple chain length calculation
593        for node_id in pipeline.nodes.keys() {
594            let depth = self.calculate_depth(pipeline, node_id);
595            total_chain_length += depth;
596            if depth > max_depth {
597                max_depth = depth;
598            }
599        }
600
601        PipelineMetrics {
602            node_count: pipeline.nodes.len(),
603            edge_count: pipeline.edges.len(),
604            avg_chain_length: if chain_count > 0 {
605                total_chain_length as f64 / chain_count as f64
606            } else {
607                0.0
608            },
609            max_chain_length: max_depth,
610            parallel_opportunities: self.count_parallel_opportunities(pipeline),
611            bottleneck_nodes: Vec::new(),
612        }
613    }
614
615    fn calculate_depth(&self, pipeline: &VisualPipeline, node_id: &str) -> usize {
616        let mut depth = 0;
617        let mut current = node_id.to_string();
618
619        while let Some(edge) = pipeline
620            .edges
621            .values()
622            .find(|e| e.target_node_id == current)
623        {
624            depth += 1;
625            current = edge.source_node_id.clone();
626        }
627
628        depth
629    }
630
631    fn count_parallel_opportunities(&self, pipeline: &VisualPipeline) -> usize {
632        let mut count = 0;
633
634        for node_id in pipeline.nodes.keys() {
635            let outgoing: Vec<_> = pipeline
636                .edges
637                .values()
638                .filter(|e| e.source_node_id == *node_id)
639                .collect();
640
641            if outgoing.len() > 1 {
642                count += 1;
643            }
644        }
645
646        count
647    }
648}
649
650// ---------------------------------------------------------------------------
651// Export helpers (free functions)
652// ---------------------------------------------------------------------------
653
654/// Export pipeline to SVG format
655pub fn export_svg(pipeline: &VisualPipeline) -> Result<String> {
656    // Layout constants
657    const NODE_W: f64 = 140.0;
658    const NODE_H: f64 = 44.0;
659    const H_GAP: f64 = 60.0;
660    const V_GAP: f64 = 70.0;
661    const MARGIN: f64 = 30.0;
662
663    // Collect nodes sorted deterministically so layout is stable.
664    let mut nodes: Vec<(&String, &PipelineNode)> = pipeline.nodes.iter().collect();
665    nodes.sort_by_key(|(id, _)| id.as_str());
666
667    // Assign positions: use stored position when non-zero, otherwise fall back to
668    // a simple grid layout so the SVG is always valid even for freshly created pipelines.
669    let cols = ((nodes.len() as f64).sqrt().ceil() as usize).max(1);
670    let mut node_positions: HashMap<&str, (f64, f64)> = HashMap::new();
671
672    for (idx, (id, node)) in nodes.iter().enumerate() {
673        let (cx, cy) = if node.position.x.abs() > 1e-9 || node.position.y.abs() > 1e-9 {
674            (node.position.x, node.position.y)
675        } else {
676            let col = idx % cols;
677            let row = idx / cols;
678            (
679                MARGIN + col as f64 * (NODE_W + H_GAP),
680                MARGIN + row as f64 * (NODE_H + V_GAP),
681            )
682        };
683        node_positions.insert(id.as_str(), (cx, cy));
684    }
685
686    // Canvas size
687    let total_w = if node_positions.is_empty() {
688        200.0
689    } else {
690        node_positions
691            .values()
692            .map(|(x, _)| *x)
693            .fold(f64::NEG_INFINITY, f64::max)
694            + NODE_W
695            + MARGIN
696    };
697    let total_h = if node_positions.is_empty() {
698        100.0
699    } else {
700        node_positions
701            .values()
702            .map(|(_, y)| *y)
703            .fold(f64::NEG_INFINITY, f64::max)
704            + NODE_H
705            + MARGIN
706    };
707
708    let mut svg = String::new();
709    svg.push_str(&format!(
710        r#"<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="{h}">"#,
711        w = total_w,
712        h = total_h
713    ));
714    svg.push('\n');
715
716    // Styles embedded inline for portability
717    svg.push_str(
718        r##"<defs><style>
719  .node-rect{fill:#4a90d9;stroke:#2c5f8a;stroke-width:1.5;rx:6;ry:6;}
720  .node-label{fill:#fff;font-family:sans-serif;font-size:12px;text-anchor:middle;dominant-baseline:middle;}
721  .edge-line{stroke:#888;stroke-width:1.5;marker-end:url(#arrow);}
722</style>
723<marker id="arrow" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto">
724  <path d="M0,0 L0,6 L8,3 z" fill="#888"/>
725</marker></defs>
726"##,
727    );
728
729    // Draw edges first (behind nodes)
730    for edge in pipeline.edges.values() {
731        if let (Some(&(sx, sy)), Some(&(tx, ty))) = (
732            node_positions.get(edge.source_node_id.as_str()),
733            node_positions.get(edge.target_node_id.as_str()),
734        ) {
735            let x1 = sx + NODE_W;
736            let y1 = sy + NODE_H / 2.0;
737            let x2 = tx;
738            let y2 = ty + NODE_H / 2.0;
739            svg.push_str(&format!(
740                r#"<line class="edge-line" x1="{x1:.1}" y1="{y1:.1}" x2="{x2:.1}" y2="{y2:.1}"/>"#
741            ));
742            svg.push('\n');
743        }
744    }
745
746    // Draw nodes
747    for (id, node) in &nodes {
748        if let Some(&(x, y)) = node_positions.get(id.as_str()) {
749            let label = xml_escape(&node.name);
750            svg.push_str(&format!(
751                r#"<rect class="node-rect" x="{x:.1}" y="{y:.1}" width="{w}" height="{h}" rx="6" ry="6"/>"#,
752                w = NODE_W,
753                h = NODE_H
754            ));
755            svg.push('\n');
756            svg.push_str(&format!(
757                r#"<text class="node-label" x="{cx:.1}" y="{cy:.1}">{label}</text>"#,
758                cx = x + NODE_W / 2.0,
759                cy = y + NODE_H / 2.0,
760            ));
761            svg.push('\n');
762        }
763    }
764
765    // Pipeline name as title
766    let title = xml_escape(&pipeline.name);
767    svg.push_str(&format!(
768        r##"<text x="{x}" y="16" font-family="sans-serif" font-size="14" fill="#333">{title}</text>"##,
769        x = MARGIN
770    ));
771    svg.push('\n');
772
773    svg.push_str("</svg>\n");
774    Ok(svg)
775}
776
777/// Export pipeline to DOT format (GraphViz)
778pub fn export_dot(pipeline: &VisualPipeline) -> Result<String> {
779    let mut dot = String::new();
780    dot.push_str(&format!("digraph \"{}\" {{\n", pipeline.name));
781    dot.push_str("  rankdir=LR;\n");
782    dot.push_str("  node [shape=box];\n\n");
783
784    // Add nodes
785    for (id, node) in &pipeline.nodes {
786        let label = format!("{}\\n{:?}", node.name, node.node_type);
787        dot.push_str(&format!("  \"{}\" [label=\"{}\"];\n", id, label));
788    }
789
790    dot.push('\n');
791
792    // Add edges
793    for edge in pipeline.edges.values() {
794        dot.push_str(&format!(
795            "  \"{}\" -> \"{}\";\n",
796            edge.source_node_id, edge.target_node_id
797        ));
798    }
799
800    dot.push_str("}\n");
801    Ok(dot)
802}
803
804/// Export pipeline to Mermaid format
805pub fn export_mermaid(pipeline: &VisualPipeline) -> Result<String> {
806    let mut mermaid = String::new();
807    mermaid.push_str("graph LR\n");
808
809    // Add nodes
810    for (id, node) in &pipeline.nodes {
811        let label = format!("{}[{}]", id, node.name);
812        mermaid.push_str(&format!("  {}\n", label));
813    }
814
815    // Add edges
816    for edge in pipeline.edges.values() {
817        mermaid.push_str(&format!(
818            "  {} --> {}\n",
819            edge.source_node_id, edge.target_node_id
820        ));
821    }
822
823    Ok(mermaid)
824}
825
826/// Escape special XML/HTML characters for safe embedding in SVG text elements.
827fn xml_escape(s: &str) -> String {
828    let mut out = String::with_capacity(s.len());
829    for ch in s.chars() {
830        match ch {
831            '&' => out.push_str("&amp;"),
832            '<' => out.push_str("&lt;"),
833            '>' => out.push_str("&gt;"),
834            '"' => out.push_str("&quot;"),
835            '\'' => out.push_str("&apos;"),
836            other => out.push(other),
837        }
838    }
839    out
840}