1use std::collections::{HashMap, HashSet};
2use std::error::Error;
3use std::fmt::{Display, Write};
4use std::num::ParseIntError;
5use std::sync::OnceLock;
6
7use auto_impl::auto_impl;
8use slotmap::{Key, SecondaryMap, SlotMap};
9
10pub use super::graphviz::{HydroDot, escape_dot};
11pub use super::json::HydroJson;
12pub use super::mermaid::{HydroMermaid, escape_mermaid};
14use crate::compile::ir::backtrace::Backtrace;
15use crate::compile::ir::{DebugExpr, HydroIrMetadata, HydroNode, HydroRoot, HydroSource};
16use crate::location::dynamic::LocationId;
17use crate::location::{LocationKey, LocationType};
18
19#[derive(Debug, Clone)]
21pub enum NodeLabel {
22 Static(String),
24 WithExprs {
26 op_name: String,
27 exprs: Vec<DebugExpr>,
28 },
29}
30
31impl NodeLabel {
32 pub fn static_label(s: String) -> Self {
34 Self::Static(s)
35 }
36
37 pub fn with_exprs(op_name: String, exprs: Vec<DebugExpr>) -> Self {
39 Self::WithExprs { op_name, exprs }
40 }
41}
42
43impl Display for NodeLabel {
44 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45 match self {
46 Self::Static(s) => write!(f, "{}", s),
47 Self::WithExprs { op_name, exprs } => {
48 if exprs.is_empty() {
49 write!(f, "{}()", op_name)
50 } else {
51 let expr_strs: Vec<_> = exprs.iter().map(|e| e.to_string()).collect();
52 write!(f, "{}({})", op_name, expr_strs.join(", "))
53 }
54 }
55 }
56 }
57}
58
59pub struct IndentedGraphWriter<'a, W> {
62 pub write: W,
63 pub indent: usize,
64 pub config: HydroWriteConfig<'a>,
65}
66
67impl<'a, W> IndentedGraphWriter<'a, W> {
68 pub fn new(write: W) -> Self {
70 Self {
71 write,
72 indent: 0,
73 config: HydroWriteConfig::default(),
74 }
75 }
76
77 pub fn new_with_config(write: W, config: HydroWriteConfig<'a>) -> Self {
79 Self {
80 write,
81 indent: 0,
82 config,
83 }
84 }
85}
86
87impl<W: Write> IndentedGraphWriter<'_, W> {
88 pub fn writeln_indented(&mut self, content: &str) -> Result<(), std::fmt::Error> {
90 writeln!(self.write, "{b:i$}{content}", b = "", i = self.indent)
91 }
92}
93
94pub type GraphWriteError = std::fmt::Error;
96
97#[auto_impl(&mut, Box)]
99pub trait HydroGraphWrite {
100 type Err: Error;
102
103 fn write_prologue(&mut self) -> Result<(), Self::Err>;
105
106 fn write_node_definition(
108 &mut self,
109 node_id: VizNodeKey,
110 node_label: &NodeLabel,
111 node_type: HydroNodeType,
112 location_key: Option<LocationKey>,
113 location_type: Option<LocationType>,
114 backtrace: Option<&Backtrace>,
115 ) -> Result<(), Self::Err>;
116
117 fn write_edge(
119 &mut self,
120 src_id: VizNodeKey,
121 dst_id: VizNodeKey,
122 edge_properties: &HashSet<HydroEdgeProp>,
123 label: Option<&str>,
124 ) -> Result<(), Self::Err>;
125
126 fn write_location_start(
128 &mut self,
129 location_key: LocationKey,
130 location_type: LocationType,
131 ) -> Result<(), Self::Err>;
132
133 fn write_node(&mut self, node_id: VizNodeKey) -> Result<(), Self::Err>;
135
136 fn write_location_end(&mut self) -> Result<(), Self::Err>;
138
139 fn write_epilogue(&mut self) -> Result<(), Self::Err>;
141}
142
143pub mod node_type_utils {
145 use super::HydroNodeType;
146
147 const NODE_TYPE_DATA: &[(HydroNodeType, &str)] = &[
149 (HydroNodeType::Source, "Source"),
150 (HydroNodeType::Transform, "Transform"),
151 (HydroNodeType::Join, "Join"),
152 (HydroNodeType::Aggregation, "Aggregation"),
153 (HydroNodeType::Network, "Network"),
154 (HydroNodeType::Sink, "Sink"),
155 (HydroNodeType::Tee, "Tee"),
156 (HydroNodeType::NonDeterministic, "NonDeterministic"),
157 ];
158
159 pub fn to_string(node_type: HydroNodeType) -> &'static str {
161 NODE_TYPE_DATA
162 .iter()
163 .find(|(nt, _)| *nt == node_type)
164 .map(|(_, name)| *name)
165 .unwrap_or("Unknown")
166 }
167
168 pub fn all_types_with_strings() -> Vec<(HydroNodeType, &'static str)> {
170 NODE_TYPE_DATA.to_vec()
171 }
172}
173
174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
176pub enum HydroNodeType {
177 Source,
178 Transform,
179 Join,
180 Aggregation,
181 Network,
182 Sink,
183 Tee,
184 NonDeterministic,
185}
186
187#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
189pub enum HydroEdgeProp {
190 Bounded,
191 Unbounded,
192 TotalOrder,
193 NoOrder,
194 Keyed,
195 Stream,
197 KeyedSingleton,
198 KeyedStream,
199 Singleton,
200 Optional,
201 Network,
202 Cycle,
203}
204
205#[derive(Debug, Clone, PartialEq, Eq)]
208pub struct UnifiedEdgeStyle {
209 pub line_pattern: LinePattern,
211 pub line_width: u8,
213 pub arrowhead: ArrowheadStyle,
215 pub line_style: LineStyle,
217 pub halo: HaloStyle,
219 pub waviness: WavinessStyle,
221 pub animation: AnimationStyle,
223 pub color: &'static str,
225}
226
227#[derive(Debug, Clone, Copy, PartialEq, Eq)]
228pub enum LinePattern {
229 Solid,
230 Dotted,
231 Dashed,
232}
233
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub enum ArrowheadStyle {
236 TriangleFilled,
237 CircleFilled,
238 DiamondOpen,
239 Default,
240}
241
242#[derive(Debug, Clone, Copy, PartialEq, Eq)]
243pub enum LineStyle {
244 Single,
246 HashMarks,
248}
249
250#[derive(Debug, Clone, Copy, PartialEq, Eq)]
251pub enum HaloStyle {
252 None,
253 LightBlue,
254}
255
256#[derive(Debug, Clone, Copy, PartialEq, Eq)]
257pub enum WavinessStyle {
258 None,
259 Wavy,
260}
261
262#[derive(Debug, Clone, Copy, PartialEq, Eq)]
263pub enum AnimationStyle {
264 Static,
265 Animated,
266}
267
268impl Default for UnifiedEdgeStyle {
269 fn default() -> Self {
270 Self {
271 line_pattern: LinePattern::Solid,
272 line_width: 1,
273 arrowhead: ArrowheadStyle::Default,
274 line_style: LineStyle::Single,
275 halo: HaloStyle::None,
276 waviness: WavinessStyle::None,
277 animation: AnimationStyle::Static,
278 color: "#666666",
279 }
280 }
281}
282
283pub fn get_unified_edge_style(
296 edge_properties: &HashSet<HydroEdgeProp>,
297 src_location: Option<usize>,
298 dst_location: Option<usize>,
299) -> UnifiedEdgeStyle {
300 let mut style = UnifiedEdgeStyle::default();
301
302 let is_network = edge_properties.contains(&HydroEdgeProp::Network)
304 || (src_location.is_some() && dst_location.is_some() && src_location != dst_location);
305
306 if is_network {
307 style.line_pattern = LinePattern::Dashed;
308 style.animation = AnimationStyle::Animated;
309 } else {
310 style.line_pattern = LinePattern::Solid;
311 style.animation = AnimationStyle::Static;
312 }
313
314 if edge_properties.contains(&HydroEdgeProp::Unbounded) {
316 style.halo = HaloStyle::LightBlue;
317 } else {
318 style.halo = HaloStyle::None;
319 }
320
321 if edge_properties.contains(&HydroEdgeProp::Stream) {
323 style.arrowhead = ArrowheadStyle::TriangleFilled;
324 style.color = "#2563eb"; } else if edge_properties.contains(&HydroEdgeProp::KeyedStream) {
326 style.arrowhead = ArrowheadStyle::TriangleFilled;
327 style.color = "#2563eb"; } else if edge_properties.contains(&HydroEdgeProp::KeyedSingleton) {
329 style.arrowhead = ArrowheadStyle::TriangleFilled;
330 style.color = "#000000"; } else if edge_properties.contains(&HydroEdgeProp::Singleton) {
332 style.arrowhead = ArrowheadStyle::CircleFilled;
333 style.color = "#000000"; } else if edge_properties.contains(&HydroEdgeProp::Optional) {
335 style.arrowhead = ArrowheadStyle::DiamondOpen;
336 style.color = "#6b7280"; }
338
339 if edge_properties.contains(&HydroEdgeProp::Keyed) {
341 style.line_style = LineStyle::HashMarks; } else {
343 style.line_style = LineStyle::Single;
344 }
345
346 if edge_properties.contains(&HydroEdgeProp::NoOrder) {
348 style.waviness = WavinessStyle::Wavy;
349 } else if edge_properties.contains(&HydroEdgeProp::TotalOrder) {
350 style.waviness = WavinessStyle::None;
351 }
352
353 style
354}
355
356pub fn extract_edge_properties_from_collection_kind(
360 collection_kind: &crate::compile::ir::CollectionKind,
361) -> HashSet<HydroEdgeProp> {
362 use crate::compile::ir::CollectionKind;
363
364 let mut properties = HashSet::new();
365
366 match collection_kind {
367 CollectionKind::Stream { bound, order, .. } => {
368 properties.insert(HydroEdgeProp::Stream);
369 add_bound_property(&mut properties, bound);
370 add_order_property(&mut properties, order);
371 }
372 CollectionKind::KeyedStream {
373 bound, value_order, ..
374 } => {
375 properties.insert(HydroEdgeProp::KeyedStream);
376 properties.insert(HydroEdgeProp::Keyed);
377 add_bound_property(&mut properties, bound);
378 add_order_property(&mut properties, value_order);
379 }
380 CollectionKind::Singleton { bound, .. } => {
381 properties.insert(HydroEdgeProp::Singleton);
382 add_bound_property(&mut properties, bound);
383 properties.insert(HydroEdgeProp::TotalOrder);
385 }
386 CollectionKind::Optional { bound, .. } => {
387 properties.insert(HydroEdgeProp::Optional);
388 add_bound_property(&mut properties, bound);
389 properties.insert(HydroEdgeProp::TotalOrder);
391 }
392 CollectionKind::KeyedSingleton { bound, .. } => {
393 properties.insert(HydroEdgeProp::Singleton);
394 properties.insert(HydroEdgeProp::Keyed);
395 add_keyed_singleton_bound_property(&mut properties, bound);
397 properties.insert(HydroEdgeProp::TotalOrder);
398 }
399 }
400
401 properties
402}
403
404fn add_bound_property(
406 properties: &mut HashSet<HydroEdgeProp>,
407 bound: &crate::compile::ir::BoundKind,
408) {
409 use crate::compile::ir::BoundKind;
410
411 match bound {
412 BoundKind::Bounded => {
413 properties.insert(HydroEdgeProp::Bounded);
414 }
415 BoundKind::Unbounded => {
416 properties.insert(HydroEdgeProp::Unbounded);
417 }
418 }
419}
420
421fn add_keyed_singleton_bound_property(
423 properties: &mut HashSet<HydroEdgeProp>,
424 bound: &crate::compile::ir::KeyedSingletonBoundKind,
425) {
426 use crate::compile::ir::KeyedSingletonBoundKind;
427
428 match bound {
429 KeyedSingletonBoundKind::Bounded | KeyedSingletonBoundKind::BoundedValue => {
430 properties.insert(HydroEdgeProp::Bounded);
431 }
432 KeyedSingletonBoundKind::Unbounded => {
433 properties.insert(HydroEdgeProp::Unbounded);
434 }
435 }
436}
437
438fn add_order_property(
440 properties: &mut HashSet<HydroEdgeProp>,
441 order: &crate::compile::ir::StreamOrder,
442) {
443 use crate::compile::ir::StreamOrder;
444
445 match order {
446 StreamOrder::TotalOrder => {
447 properties.insert(HydroEdgeProp::TotalOrder);
448 }
449 StreamOrder::NoOrder => {
450 properties.insert(HydroEdgeProp::NoOrder);
451 }
452 }
453}
454
455pub fn is_network_edge(src_location: &LocationId, dst_location: &LocationId) -> bool {
458 src_location.root() != dst_location.root()
460}
461
462pub fn add_network_edge_tag(
464 properties: &mut HashSet<HydroEdgeProp>,
465 src_location: &LocationId,
466 dst_location: &LocationId,
467) {
468 if is_network_edge(src_location, dst_location) {
469 properties.insert(HydroEdgeProp::Network);
470 }
471}
472
473#[derive(Debug, Clone, Copy)]
475pub struct HydroWriteConfig<'a> {
476 pub show_metadata: bool,
477 pub show_location_groups: bool,
478 pub use_short_labels: bool,
479 pub location_names: &'a SecondaryMap<LocationKey, String>,
480}
481
482impl Default for HydroWriteConfig<'_> {
483 fn default() -> Self {
484 static EMPTY: OnceLock<SecondaryMap<LocationKey, String>> = OnceLock::new();
485 Self {
486 show_metadata: false,
487 show_location_groups: true,
488 use_short_labels: true, location_names: EMPTY.get_or_init(SecondaryMap::new),
490 }
491 }
492}
493
494#[derive(Clone)]
496pub struct HydroGraphNode {
497 pub label: NodeLabel,
498 pub node_type: HydroNodeType,
499 pub location_key: Option<LocationKey>,
500 pub backtrace: Option<Backtrace>,
501}
502
503slotmap::new_key_type! {
504 pub struct VizNodeKey;
508}
509
510impl Display for VizNodeKey {
511 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
512 write!(f, "viz{:?}", self.data()) }
514}
515
516impl std::str::FromStr for VizNodeKey {
519 type Err = Option<ParseIntError>;
520
521 fn from_str(s: &str) -> Result<Self, Self::Err> {
522 let nvn = s.strip_prefix("viz").ok_or(None)?;
523 let (idx, ver) = nvn.split_once("v").ok_or(None)?;
524 let idx: u64 = idx.parse()?;
525 let ver: u64 = ver.parse()?;
526 Ok(slotmap::KeyData::from_ffi((ver << 32) | idx).into())
527 }
528}
529
530impl VizNodeKey {
531 #[cfg(test)]
533 pub const TEST_KEY_1: Self = Self(slotmap::KeyData::from_ffi(0x0000008f00000001)); #[cfg(test)]
537 pub const TEST_KEY_2: Self = Self(slotmap::KeyData::from_ffi(0x0000008f00000002)); }
539
540#[derive(Debug, Clone)]
542pub struct HydroGraphEdge {
543 pub src: VizNodeKey,
544 pub dst: VizNodeKey,
545 pub edge_properties: HashSet<HydroEdgeProp>,
546 pub label: Option<String>,
547}
548
549#[derive(Default)]
551pub struct HydroGraphStructure {
552 pub nodes: SlotMap<VizNodeKey, HydroGraphNode>,
553 pub edges: Vec<HydroGraphEdge>,
554 pub locations: SecondaryMap<LocationKey, LocationType>,
555}
556
557impl HydroGraphStructure {
558 pub fn new() -> Self {
559 Self::default()
560 }
561
562 pub fn add_node(
563 &mut self,
564 label: NodeLabel,
565 node_type: HydroNodeType,
566 location_key: Option<LocationKey>,
567 ) -> VizNodeKey {
568 self.add_node_with_backtrace(label, node_type, location_key, None)
569 }
570
571 pub fn add_node_with_backtrace(
572 &mut self,
573 label: NodeLabel,
574 node_type: HydroNodeType,
575 location_key: Option<LocationKey>,
576 backtrace: Option<Backtrace>,
577 ) -> VizNodeKey {
578 self.nodes.insert(HydroGraphNode {
579 label,
580 node_type,
581 location_key,
582 backtrace,
583 })
584 }
585
586 pub fn add_node_with_metadata(
588 &mut self,
589 label: NodeLabel,
590 node_type: HydroNodeType,
591 metadata: &HydroIrMetadata,
592 ) -> VizNodeKey {
593 let location_key = Some(setup_location(self, metadata));
594 let backtrace = Some(metadata.op.backtrace.clone());
595 self.add_node_with_backtrace(label, node_type, location_key, backtrace)
596 }
597
598 pub fn add_edge(
599 &mut self,
600 src: VizNodeKey,
601 dst: VizNodeKey,
602 edge_properties: HashSet<HydroEdgeProp>,
603 label: Option<String>,
604 ) {
605 self.edges.push(HydroGraphEdge {
606 src,
607 dst,
608 edge_properties,
609 label,
610 });
611 }
612
613 pub fn add_edge_single(
615 &mut self,
616 src: VizNodeKey,
617 dst: VizNodeKey,
618 edge_type: HydroEdgeProp,
619 label: Option<String>,
620 ) {
621 let mut properties = HashSet::new();
622 properties.insert(edge_type);
623 self.edges.push(HydroGraphEdge {
624 src,
625 dst,
626 edge_properties: properties,
627 label,
628 });
629 }
630
631 pub fn add_location(&mut self, location_key: LocationKey, location_type: LocationType) {
632 self.locations.insert(location_key, location_type);
633 }
634}
635
636pub fn extract_op_name(full_label: String) -> String {
638 full_label
639 .split('(')
640 .next()
641 .unwrap_or("unknown")
642 .to_lowercase()
643}
644
645pub fn extract_short_label(full_label: &str) -> String {
647 if let Some(op_name) = full_label.split('(').next() {
649 let base_name = op_name.to_lowercase();
650 match base_name.as_str() {
651 "source" => {
653 if full_label.contains("Iter") {
654 "source_iter".to_owned()
655 } else if full_label.contains("Stream") {
656 "source_stream".to_owned()
657 } else if full_label.contains("ExternalNetwork") {
658 "external_network".to_owned()
659 } else if full_label.contains("Spin") {
660 "spin".to_owned()
661 } else {
662 "source".to_owned()
663 }
664 }
665 "network" => {
666 if full_label.contains("deser") {
667 "network(recv)".to_owned()
668 } else if full_label.contains("ser") {
669 "network(send)".to_owned()
670 } else {
671 "network".to_owned()
672 }
673 }
674 _ => base_name,
676 }
677 } else {
678 if full_label.len() > 20 {
680 format!("{}...", &full_label[..17])
681 } else {
682 full_label.to_owned()
683 }
684 }
685}
686
687fn setup_location(structure: &mut HydroGraphStructure, metadata: &HydroIrMetadata) -> LocationKey {
689 let root = metadata.location_id.root();
690 let location_key = root.key();
691 let location_type = root.location_type().unwrap();
692 structure.add_location(location_key, location_type);
693 location_key
694}
695
696fn add_edge_with_metadata(
699 structure: &mut HydroGraphStructure,
700 src_id: VizNodeKey,
701 dst_id: VizNodeKey,
702 src_metadata: Option<&HydroIrMetadata>,
703 dst_metadata: Option<&HydroIrMetadata>,
704 label: Option<String>,
705) {
706 let mut properties = HashSet::new();
707
708 if let Some(metadata) = src_metadata {
710 properties.extend(extract_edge_properties_from_collection_kind(
711 &metadata.collection_kind,
712 ));
713 }
714
715 if let (Some(src_meta), Some(dst_meta)) = (src_metadata, dst_metadata) {
717 add_network_edge_tag(
718 &mut properties,
719 &src_meta.location_id,
720 &dst_meta.location_id,
721 );
722 }
723
724 if properties.is_empty() {
726 properties.insert(HydroEdgeProp::Stream);
727 }
728
729 structure.add_edge(src_id, dst_id, properties, label);
730}
731
732fn write_graph_structure<W>(
734 structure: &HydroGraphStructure,
735 graph_write: W,
736 config: HydroWriteConfig<'_>,
737) -> Result<(), W::Err>
738where
739 W: HydroGraphWrite,
740{
741 let mut graph_write = graph_write;
742 graph_write.write_prologue()?;
744
745 for (node_id, node) in structure.nodes.iter() {
747 let location_type = node
748 .location_key
749 .and_then(|loc_key| structure.locations.get(loc_key))
750 .copied();
751
752 graph_write.write_node_definition(
753 node_id,
754 &node.label,
755 node.node_type,
756 node.location_key,
757 location_type,
758 node.backtrace.as_ref(),
759 )?;
760 }
761
762 if config.show_location_groups {
764 let mut nodes_by_location = SecondaryMap::<LocationKey, Vec<VizNodeKey>>::new();
765 for (node_id, node) in structure.nodes.iter() {
766 if let Some(location_key) = node.location_key {
767 nodes_by_location
768 .entry(location_key)
769 .expect("location was removed")
770 .or_default()
771 .push(node_id);
772 }
773 }
774
775 for (location_key, node_ids) in nodes_by_location.iter() {
776 if let Some(&location_type) = structure.locations.get(location_key) {
777 graph_write.write_location_start(location_key, location_type)?;
778 for &node_id in node_ids.iter() {
779 graph_write.write_node(node_id)?;
780 }
781 graph_write.write_location_end()?;
782 }
783 }
784 }
785
786 for edge in structure.edges.iter() {
788 graph_write.write_edge(
789 edge.src,
790 edge.dst,
791 &edge.edge_properties,
792 edge.label.as_deref(),
793 )?;
794 }
795
796 graph_write.write_epilogue()?;
797 Ok(())
798}
799
800impl HydroRoot {
801 pub fn build_graph_structure(
803 &self,
804 structure: &mut HydroGraphStructure,
805 seen_tees: &mut HashMap<*const std::cell::RefCell<HydroNode>, VizNodeKey>,
806 config: HydroWriteConfig<'_>,
807 ) -> VizNodeKey {
808 fn build_sink_node(
810 structure: &mut HydroGraphStructure,
811 seen_tees: &mut HashMap<*const std::cell::RefCell<HydroNode>, VizNodeKey>,
812 config: HydroWriteConfig<'_>,
813 input: &HydroNode,
814 sink_metadata: Option<&HydroIrMetadata>,
815 label: NodeLabel,
816 ) -> VizNodeKey {
817 let input_id = input.build_graph_structure(structure, seen_tees, config);
818
819 let effective_metadata = if let Some(meta) = sink_metadata {
821 Some(meta)
822 } else {
823 match input {
824 HydroNode::Placeholder => None,
825 _ => Some(input.metadata()),
827 }
828 };
829
830 let location_key = effective_metadata.map(|m| setup_location(structure, m));
831 let sink_id = structure.add_node_with_backtrace(
832 label,
833 HydroNodeType::Sink,
834 location_key,
835 effective_metadata.map(|m| m.op.backtrace.clone()),
836 );
837
838 let input_metadata = input.metadata();
840 add_edge_with_metadata(
841 structure,
842 input_id,
843 sink_id,
844 Some(input_metadata),
845 sink_metadata,
846 None,
847 );
848
849 sink_id
850 }
851
852 match self {
853 HydroRoot::ForEach { f, input, .. } => build_sink_node(
855 structure,
856 seen_tees,
857 config,
858 input,
859 None,
860 NodeLabel::with_exprs("for_each".to_owned(), vec![f.clone()]),
861 ),
862
863 HydroRoot::SendExternal {
864 to_external_key,
865 to_port_id,
866 input,
867 ..
868 } => build_sink_node(
869 structure,
870 seen_tees,
871 config,
872 input,
873 None,
874 NodeLabel::with_exprs(
875 format!("send_external({}:{})", to_external_key, to_port_id),
876 vec![],
877 ),
878 ),
879
880 HydroRoot::DestSink { sink, input, .. } => build_sink_node(
881 structure,
882 seen_tees,
883 config,
884 input,
885 None,
886 NodeLabel::with_exprs("dest_sink".to_owned(), vec![sink.clone()]),
887 ),
888
889 HydroRoot::CycleSink {
890 cycle_id, input, ..
891 } => build_sink_node(
892 structure,
893 seen_tees,
894 config,
895 input,
896 None,
897 NodeLabel::static_label(format!("cycle_sink({})", cycle_id)),
898 ),
899
900 HydroRoot::EmbeddedOutput { ident, input, .. } => build_sink_node(
901 structure,
902 seen_tees,
903 config,
904 input,
905 None,
906 NodeLabel::static_label(format!("embedded_output({})", ident)),
907 ),
908 }
909 }
910}
911
912impl HydroNode {
913 pub fn build_graph_structure(
915 &self,
916 structure: &mut HydroGraphStructure,
917 seen_tees: &mut HashMap<*const std::cell::RefCell<HydroNode>, VizNodeKey>,
918 config: HydroWriteConfig<'_>,
919 ) -> VizNodeKey {
920 struct TransformParams<'a> {
924 structure: &'a mut HydroGraphStructure,
925 seen_tees: &'a mut HashMap<*const std::cell::RefCell<HydroNode>, VizNodeKey>,
926 config: HydroWriteConfig<'a>,
927 input: &'a HydroNode,
928 metadata: &'a HydroIrMetadata,
929 op_name: String,
930 node_type: HydroNodeType,
931 }
932
933 fn build_simple_transform(params: TransformParams) -> VizNodeKey {
935 let input_id = params.input.build_graph_structure(
936 params.structure,
937 params.seen_tees,
938 params.config,
939 );
940 let node_id = params.structure.add_node_with_metadata(
941 NodeLabel::Static(params.op_name.to_string()),
942 params.node_type,
943 params.metadata,
944 );
945
946 let input_metadata = params.input.metadata();
948 add_edge_with_metadata(
949 params.structure,
950 input_id,
951 node_id,
952 Some(input_metadata),
953 Some(params.metadata),
954 None,
955 );
956
957 node_id
958 }
959
960 fn build_single_expr_transform(params: TransformParams, expr: &DebugExpr) -> VizNodeKey {
962 let input_id = params.input.build_graph_structure(
963 params.structure,
964 params.seen_tees,
965 params.config,
966 );
967 let node_id = params.structure.add_node_with_metadata(
968 NodeLabel::with_exprs(params.op_name.to_string(), vec![expr.clone()]),
969 params.node_type,
970 params.metadata,
971 );
972
973 let input_metadata = params.input.metadata();
975 add_edge_with_metadata(
976 params.structure,
977 input_id,
978 node_id,
979 Some(input_metadata),
980 Some(params.metadata),
981 None,
982 );
983
984 node_id
985 }
986
987 fn build_dual_expr_transform(
989 params: TransformParams,
990 expr1: &DebugExpr,
991 expr2: &DebugExpr,
992 ) -> VizNodeKey {
993 let input_id = params.input.build_graph_structure(
994 params.structure,
995 params.seen_tees,
996 params.config,
997 );
998 let node_id = params.structure.add_node_with_metadata(
999 NodeLabel::with_exprs(
1000 params.op_name.to_string(),
1001 vec![expr1.clone(), expr2.clone()],
1002 ),
1003 params.node_type,
1004 params.metadata,
1005 );
1006
1007 let input_metadata = params.input.metadata();
1009 add_edge_with_metadata(
1010 params.structure,
1011 input_id,
1012 node_id,
1013 Some(input_metadata),
1014 Some(params.metadata),
1015 None,
1016 );
1017
1018 node_id
1019 }
1020
1021 fn build_source_node(
1023 structure: &mut HydroGraphStructure,
1024 metadata: &HydroIrMetadata,
1025 label: String,
1026 ) -> VizNodeKey {
1027 structure.add_node_with_metadata(
1028 NodeLabel::Static(label),
1029 HydroNodeType::Source,
1030 metadata,
1031 )
1032 }
1033
1034 match self {
1035 HydroNode::Placeholder => structure.add_node(
1036 NodeLabel::Static("PLACEHOLDER".to_owned()),
1037 HydroNodeType::Transform,
1038 None,
1039 ),
1040
1041 HydroNode::Source {
1042 source, metadata, ..
1043 } => {
1044 let label = match source {
1045 HydroSource::Stream(expr) => format!("source_stream({})", expr),
1046 HydroSource::ExternalNetwork() => "external_network()".to_owned(),
1047 HydroSource::Iter(expr) => format!("source_iter({})", expr),
1048 HydroSource::Spin() => "spin()".to_owned(),
1049 HydroSource::ClusterMembers(location_id, _) => {
1050 format!(
1051 "source_stream(cluster_membership_stream({:?}))",
1052 location_id
1053 )
1054 }
1055 HydroSource::Embedded(ident) => {
1056 format!("embedded_input({})", ident)
1057 }
1058 };
1059 build_source_node(structure, metadata, label)
1060 }
1061
1062 HydroNode::SingletonSource {
1063 value,
1064 first_tick_only,
1065 metadata,
1066 } => {
1067 let label = if *first_tick_only {
1068 format!("singleton_first_tick({})", value)
1069 } else {
1070 format!("singleton({})", value)
1071 };
1072 build_source_node(structure, metadata, label)
1073 }
1074
1075 HydroNode::ExternalInput {
1076 from_external_key,
1077 from_port_id,
1078 metadata,
1079 ..
1080 } => build_source_node(
1081 structure,
1082 metadata,
1083 format!("external_input({}:{})", from_external_key, from_port_id),
1084 ),
1085
1086 HydroNode::CycleSource {
1087 cycle_id, metadata, ..
1088 } => build_source_node(structure, metadata, format!("cycle_source({})", cycle_id)),
1089
1090 HydroNode::Tee { inner, metadata } => {
1091 let ptr = inner.as_ptr();
1092 if let Some(&existing_id) = seen_tees.get(&ptr) {
1093 return existing_id;
1094 }
1095
1096 let input_id = inner
1097 .0
1098 .borrow()
1099 .build_graph_structure(structure, seen_tees, config);
1100 let tee_id = structure.add_node_with_metadata(
1101 NodeLabel::Static(extract_op_name(self.print_root())),
1102 HydroNodeType::Tee,
1103 metadata,
1104 );
1105
1106 seen_tees.insert(ptr, tee_id);
1107
1108 let inner_borrow = inner.0.borrow();
1110 let input_metadata = inner_borrow.metadata();
1111 add_edge_with_metadata(
1112 structure,
1113 input_id,
1114 tee_id,
1115 Some(input_metadata),
1116 Some(metadata),
1117 None,
1118 );
1119 drop(inner_borrow);
1120
1121 tee_id
1122 }
1123
1124 HydroNode::Partition {
1125 inner, metadata, ..
1126 } => {
1127 let ptr = inner.as_ptr();
1128 if let Some(&existing_id) = seen_tees.get(&ptr) {
1129 return existing_id;
1130 }
1131
1132 let input_id = inner
1133 .0
1134 .borrow()
1135 .build_graph_structure(structure, seen_tees, config);
1136 let partition_id = structure.add_node_with_metadata(
1137 NodeLabel::Static(extract_op_name(self.print_root())),
1138 HydroNodeType::Tee,
1139 metadata,
1140 );
1141
1142 seen_tees.insert(ptr, partition_id);
1143
1144 let inner_borrow = inner.0.borrow();
1146 let input_metadata = inner_borrow.metadata();
1147 add_edge_with_metadata(
1148 structure,
1149 input_id,
1150 partition_id,
1151 Some(input_metadata),
1152 Some(metadata),
1153 None,
1154 );
1155 drop(inner_borrow);
1156
1157 partition_id
1158 }
1159
1160 HydroNode::ObserveNonDet {
1162 inner, metadata, ..
1163 } => build_simple_transform(TransformParams {
1164 structure,
1165 seen_tees,
1166 config,
1167 input: inner,
1168 metadata,
1169 op_name: extract_op_name(self.print_root()),
1170 node_type: HydroNodeType::NonDeterministic,
1171 }),
1172
1173 HydroNode::Cast { inner, metadata }
1175 | HydroNode::DeferTick {
1176 input: inner,
1177 metadata,
1178 }
1179 | HydroNode::Enumerate {
1180 input: inner,
1181 metadata,
1182 ..
1183 }
1184 | HydroNode::Unique {
1185 input: inner,
1186 metadata,
1187 }
1188 | HydroNode::ResolveFutures {
1189 input: inner,
1190 metadata,
1191 }
1192 | HydroNode::ResolveFuturesOrdered {
1193 input: inner,
1194 metadata,
1195 } => build_simple_transform(TransformParams {
1196 structure,
1197 seen_tees,
1198 config,
1199 input: inner,
1200 metadata,
1201 op_name: extract_op_name(self.print_root()),
1202 node_type: HydroNodeType::Transform,
1203 }),
1204
1205 HydroNode::Sort {
1207 input: inner,
1208 metadata,
1209 } => build_simple_transform(TransformParams {
1210 structure,
1211 seen_tees,
1212 config,
1213 input: inner,
1214 metadata,
1215 op_name: extract_op_name(self.print_root()),
1216 node_type: HydroNodeType::Aggregation,
1217 }),
1218
1219 HydroNode::Map { f, input, metadata }
1221 | HydroNode::Filter { f, input, metadata }
1222 | HydroNode::FlatMap { f, input, metadata }
1223 | HydroNode::FilterMap { f, input, metadata }
1224 | HydroNode::Inspect { f, input, metadata } => build_single_expr_transform(
1225 TransformParams {
1226 structure,
1227 seen_tees,
1228 config,
1229 input,
1230 metadata,
1231 op_name: extract_op_name(self.print_root()),
1232 node_type: HydroNodeType::Transform,
1233 },
1234 f,
1235 ),
1236
1237 HydroNode::Reduce { f, input, metadata }
1239 | HydroNode::ReduceKeyed { f, input, metadata } => build_single_expr_transform(
1240 TransformParams {
1241 structure,
1242 seen_tees,
1243 config,
1244 input,
1245 metadata,
1246 op_name: extract_op_name(self.print_root()),
1247 node_type: HydroNodeType::Aggregation,
1248 },
1249 f,
1250 ),
1251
1252 HydroNode::Join {
1254 left,
1255 right,
1256 metadata,
1257 }
1258 | HydroNode::CrossProduct {
1259 left,
1260 right,
1261 metadata,
1262 }
1263 | HydroNode::CrossSingleton {
1264 left,
1265 right,
1266 metadata,
1267 } => {
1268 let left_id = left.build_graph_structure(structure, seen_tees, config);
1269 let right_id = right.build_graph_structure(structure, seen_tees, config);
1270 let node_id = structure.add_node_with_metadata(
1271 NodeLabel::Static(extract_op_name(self.print_root())),
1272 HydroNodeType::Join,
1273 metadata,
1274 );
1275
1276 let left_metadata = left.metadata();
1278 add_edge_with_metadata(
1279 structure,
1280 left_id,
1281 node_id,
1282 Some(left_metadata),
1283 Some(metadata),
1284 Some("left".to_owned()),
1285 );
1286
1287 let right_metadata = right.metadata();
1289 add_edge_with_metadata(
1290 structure,
1291 right_id,
1292 node_id,
1293 Some(right_metadata),
1294 Some(metadata),
1295 Some("right".to_owned()),
1296 );
1297
1298 node_id
1299 }
1300
1301 HydroNode::Difference {
1303 pos: left,
1304 neg: right,
1305 metadata,
1306 }
1307 | HydroNode::AntiJoin {
1308 pos: left,
1309 neg: right,
1310 metadata,
1311 } => {
1312 let left_id = left.build_graph_structure(structure, seen_tees, config);
1313 let right_id = right.build_graph_structure(structure, seen_tees, config);
1314 let node_id = structure.add_node_with_metadata(
1315 NodeLabel::Static(extract_op_name(self.print_root())),
1316 HydroNodeType::Join,
1317 metadata,
1318 );
1319
1320 let left_metadata = left.metadata();
1322 add_edge_with_metadata(
1323 structure,
1324 left_id,
1325 node_id,
1326 Some(left_metadata),
1327 Some(metadata),
1328 Some("pos".to_owned()),
1329 );
1330
1331 let right_metadata = right.metadata();
1333 add_edge_with_metadata(
1334 structure,
1335 right_id,
1336 node_id,
1337 Some(right_metadata),
1338 Some(metadata),
1339 Some("neg".to_owned()),
1340 );
1341
1342 node_id
1343 }
1344
1345 HydroNode::Fold {
1347 init,
1348 acc,
1349 input,
1350 metadata,
1351 }
1352 | HydroNode::FoldKeyed {
1353 init,
1354 acc,
1355 input,
1356 metadata,
1357 }
1358 | HydroNode::Scan {
1359 init,
1360 acc,
1361 input,
1362 metadata,
1363 } => {
1364 let node_type = HydroNodeType::Aggregation; build_dual_expr_transform(
1367 TransformParams {
1368 structure,
1369 seen_tees,
1370 config,
1371 input,
1372 metadata,
1373 op_name: extract_op_name(self.print_root()),
1374 node_type,
1375 },
1376 init,
1377 acc,
1378 )
1379 }
1380
1381 HydroNode::ReduceKeyedWatermark {
1383 f,
1384 input,
1385 watermark,
1386 metadata,
1387 } => {
1388 let input_id = input.build_graph_structure(structure, seen_tees, config);
1389 let watermark_id = watermark.build_graph_structure(structure, seen_tees, config);
1390 let location_key = Some(setup_location(structure, metadata));
1391 let join_node_id = structure.add_node_with_backtrace(
1392 NodeLabel::Static(extract_op_name(self.print_root())),
1393 HydroNodeType::Join,
1394 location_key,
1395 Some(metadata.op.backtrace.clone()),
1396 );
1397
1398 let input_metadata = input.metadata();
1400 add_edge_with_metadata(
1401 structure,
1402 input_id,
1403 join_node_id,
1404 Some(input_metadata),
1405 Some(metadata),
1406 Some("input".to_owned()),
1407 );
1408
1409 let watermark_metadata = watermark.metadata();
1411 add_edge_with_metadata(
1412 structure,
1413 watermark_id,
1414 join_node_id,
1415 Some(watermark_metadata),
1416 Some(metadata),
1417 Some("watermark".to_owned()),
1418 );
1419
1420 let node_id = structure.add_node_with_backtrace(
1421 NodeLabel::with_exprs(extract_op_name(self.print_root()), vec![f.clone()]),
1422 HydroNodeType::Aggregation,
1423 location_key,
1424 Some(metadata.op.backtrace.clone()),
1425 );
1426
1427 let join_metadata = metadata; add_edge_with_metadata(
1430 structure,
1431 join_node_id,
1432 node_id,
1433 Some(join_metadata),
1434 Some(metadata),
1435 None,
1436 );
1437
1438 node_id
1439 }
1440
1441 HydroNode::Network {
1442 serialize_fn,
1443 deserialize_fn,
1444 input,
1445 metadata,
1446 ..
1447 } => {
1448 let input_id = input.build_graph_structure(structure, seen_tees, config);
1449 let _from_location_key = setup_location(structure, metadata);
1450
1451 let root = metadata.location_id.root();
1452 let to_location_key = root.key();
1453 let to_location_type = root.location_type().unwrap();
1454 structure.add_location(to_location_key, to_location_type);
1455
1456 let mut label = "network(".to_owned();
1457 if serialize_fn.is_some() {
1458 label.push_str("send");
1459 }
1460 if deserialize_fn.is_some() {
1461 if serialize_fn.is_some() {
1462 label.push_str(" + ");
1463 }
1464 label.push_str("recv");
1465 }
1466 label.push(')');
1467
1468 let network_id = structure.add_node_with_backtrace(
1469 NodeLabel::Static(label),
1470 HydroNodeType::Network,
1471 Some(to_location_key),
1472 Some(metadata.op.backtrace.clone()),
1473 );
1474
1475 let input_metadata = input.metadata();
1477 add_edge_with_metadata(
1478 structure,
1479 input_id,
1480 network_id,
1481 Some(input_metadata),
1482 Some(metadata),
1483 Some(format!("to {:?}({})", to_location_type, to_location_key)),
1484 );
1485
1486 network_id
1487 }
1488
1489 HydroNode::Batch { inner, metadata } => build_simple_transform(TransformParams {
1491 structure,
1492 seen_tees,
1493 config,
1494 input: inner,
1495 metadata,
1496 op_name: extract_op_name(self.print_root()),
1497 node_type: HydroNodeType::NonDeterministic,
1498 }),
1499
1500 HydroNode::YieldConcat { inner, .. } => {
1501 inner.build_graph_structure(structure, seen_tees, config)
1503 }
1504
1505 HydroNode::BeginAtomic { inner, .. } => {
1506 inner.build_graph_structure(structure, seen_tees, config)
1507 }
1508
1509 HydroNode::EndAtomic { inner, .. } => {
1510 inner.build_graph_structure(structure, seen_tees, config)
1511 }
1512
1513 HydroNode::Chain {
1514 first,
1515 second,
1516 metadata,
1517 } => {
1518 let first_id = first.build_graph_structure(structure, seen_tees, config);
1519 let second_id = second.build_graph_structure(structure, seen_tees, config);
1520 let location_key = Some(setup_location(structure, metadata));
1521 let chain_id = structure.add_node_with_backtrace(
1522 NodeLabel::Static(extract_op_name(self.print_root())),
1523 HydroNodeType::Transform,
1524 location_key,
1525 Some(metadata.op.backtrace.clone()),
1526 );
1527
1528 let first_metadata = first.metadata();
1530 add_edge_with_metadata(
1531 structure,
1532 first_id,
1533 chain_id,
1534 Some(first_metadata),
1535 Some(metadata),
1536 Some("first".to_owned()),
1537 );
1538
1539 let second_metadata = second.metadata();
1541 add_edge_with_metadata(
1542 structure,
1543 second_id,
1544 chain_id,
1545 Some(second_metadata),
1546 Some(metadata),
1547 Some("second".to_owned()),
1548 );
1549
1550 chain_id
1551 }
1552
1553 HydroNode::ChainFirst {
1554 first,
1555 second,
1556 metadata,
1557 } => {
1558 let first_id = first.build_graph_structure(structure, seen_tees, config);
1559 let second_id = second.build_graph_structure(structure, seen_tees, config);
1560 let location_key = Some(setup_location(structure, metadata));
1561 let chain_id = structure.add_node_with_backtrace(
1562 NodeLabel::Static(extract_op_name(self.print_root())),
1563 HydroNodeType::Transform,
1564 location_key,
1565 Some(metadata.op.backtrace.clone()),
1566 );
1567
1568 let first_metadata = first.metadata();
1570 add_edge_with_metadata(
1571 structure,
1572 first_id,
1573 chain_id,
1574 Some(first_metadata),
1575 Some(metadata),
1576 Some("first".to_owned()),
1577 );
1578
1579 let second_metadata = second.metadata();
1581 add_edge_with_metadata(
1582 structure,
1583 second_id,
1584 chain_id,
1585 Some(second_metadata),
1586 Some(metadata),
1587 Some("second".to_owned()),
1588 );
1589
1590 chain_id
1591 }
1592
1593 HydroNode::Counter {
1594 tag: _,
1595 prefix: _,
1596 duration,
1597 input,
1598 metadata,
1599 } => build_single_expr_transform(
1600 TransformParams {
1601 structure,
1602 seen_tees,
1603 config,
1604 input,
1605 metadata,
1606 op_name: extract_op_name(self.print_root()),
1607 node_type: HydroNodeType::Transform,
1608 },
1609 duration,
1610 ),
1611 }
1612 }
1613}
1614
1615macro_rules! render_hydro_ir {
1618 ($name:ident, $write_fn:ident) => {
1619 pub fn $name(roots: &[HydroRoot], config: HydroWriteConfig<'_>) -> String {
1620 let mut output = String::new();
1621 $write_fn(&mut output, roots, config).unwrap();
1622 output
1623 }
1624 };
1625}
1626
1627macro_rules! write_hydro_ir {
1629 ($name:ident, $writer_type:ty, $constructor:expr) => {
1630 pub fn $name(
1631 output: impl std::fmt::Write,
1632 roots: &[HydroRoot],
1633 config: HydroWriteConfig<'_>,
1634 ) -> std::fmt::Result {
1635 let mut graph_write: $writer_type = $constructor(output, config);
1636 write_hydro_ir_graph(&mut graph_write, roots, config)
1637 }
1638 };
1639}
1640
1641render_hydro_ir!(render_hydro_ir_mermaid, write_hydro_ir_mermaid);
1642write_hydro_ir!(
1643 write_hydro_ir_mermaid,
1644 HydroMermaid<_>,
1645 HydroMermaid::new_with_config
1646);
1647
1648render_hydro_ir!(render_hydro_ir_dot, write_hydro_ir_dot);
1649write_hydro_ir!(write_hydro_ir_dot, HydroDot<_>, HydroDot::new_with_config);
1650
1651render_hydro_ir!(render_hydro_ir_hydroscope, write_hydro_ir_json);
1653
1654render_hydro_ir!(render_hydro_ir_json, write_hydro_ir_json);
1656write_hydro_ir!(write_hydro_ir_json, HydroJson<_>, HydroJson::new);
1657
1658fn write_hydro_ir_graph<W>(
1659 graph_write: W,
1660 roots: &[HydroRoot],
1661 config: HydroWriteConfig<'_>,
1662) -> Result<(), W::Err>
1663where
1664 W: HydroGraphWrite,
1665{
1666 let mut structure = HydroGraphStructure::new();
1667 let mut seen_tees = HashMap::new();
1668
1669 for leaf in roots {
1671 leaf.build_graph_structure(&mut structure, &mut seen_tees, config);
1672 }
1673
1674 write_graph_structure(&structure, graph_write, config)
1675}