domainforge_core/projection/
flows.rs1use crate::graph::Graph;
18use std::collections::BTreeMap;
19
20#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct ResolvedFlow {
23 pub resource: String,
24 pub from: String,
25 pub to: String,
26 pub quantity: String,
27 pub namespace: String,
28 pub annotations: BTreeMap<String, serde_json::Value>,
31}
32
33#[derive(Clone, Debug, PartialEq, Eq)]
41pub enum FlowError {
42 DanglingReference { flow_id: String },
45 MultiNamespace { namespaces: Vec<String> },
48}
49
50impl std::fmt::Display for FlowError {
51 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52 match self {
53 Self::DanglingReference { flow_id } => write!(
54 f,
55 "flow {flow_id} references an unknown entity or resource (dangling reference)"
56 ),
57 Self::MultiNamespace { namespaces } => write!(
58 f,
59 "model spans multiple namespaces ({}); the projection targets require a single \
60 namespace. Namespaces found: {}",
61 namespaces.len(),
62 namespaces.join(", ")
63 ),
64 }
65 }
66}
67
68impl std::error::Error for FlowError {}
69
70impl From<FlowError> for String {
71 fn from(e: FlowError) -> String {
72 e.to_string()
73 }
74}
75
76pub fn collect_flows(graph: &Graph) -> Result<Vec<ResolvedFlow>, FlowError> {
81 let entity_name: BTreeMap<String, String> = graph
82 .all_entities()
83 .iter()
84 .map(|e| (e.id().to_string(), e.name().to_string()))
85 .collect();
86 let resource_name: BTreeMap<String, String> = graph
87 .all_resources()
88 .iter()
89 .map(|r| (r.id().to_string(), r.name().to_string()))
90 .collect();
91
92 let mut flows: Vec<ResolvedFlow> = Vec::new();
93 for f in graph.all_flows() {
94 let (Some(from), Some(to), Some(resource)) = (
95 entity_name.get(&f.from_id().to_string()),
96 entity_name.get(&f.to_id().to_string()),
97 resource_name.get(&f.resource_id().to_string()),
98 ) else {
99 return Err(FlowError::DanglingReference {
100 flow_id: f.id().to_string(),
101 });
102 };
103 flows.push(ResolvedFlow {
104 resource: resource.clone(),
105 from: from.clone(),
106 to: to.clone(),
107 quantity: f.quantity().to_string(),
108 namespace: f.namespace().to_string(),
109 annotations: f
110 .attributes()
111 .iter()
112 .map(|(k, v)| (k.clone(), v.clone()))
113 .collect(),
114 });
115 }
116 flows.sort_by(|a, b| {
117 a.resource
118 .cmp(&b.resource)
119 .then(a.from.cmp(&b.from))
120 .then(a.to.cmp(&b.to))
121 .then(a.quantity.cmp(&b.quantity))
122 });
123 Ok(flows)
124}
125
126pub fn model_namespace(graph: &Graph) -> Result<String, FlowError> {
132 let mut namespaces: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
133 for e in graph.all_entities() {
134 namespaces.insert(e.namespace().to_string());
135 }
136 for r in graph.all_resources() {
137 namespaces.insert(r.namespace().to_string());
138 }
139 match namespaces.len() {
140 0 => Ok("default".to_string()),
141 1 => Ok(namespaces.iter().next().unwrap().clone()),
142 _ => Err(FlowError::MultiNamespace {
143 namespaces: namespaces.into_iter().collect(),
144 }),
145 }
146}
147
148#[cfg(test)]
149mod tests {
150 use super::*;
151 use crate::parser::parse_to_graph;
152
153 #[test]
154 fn collect_flows_resolves_and_sorts() {
155 let src = r#"
156@namespace "proc"
157Entity "A" in proc
158Entity "B" in proc
159Resource "R" units in proc
160Flow "R" from "B" to "A" quantity 2
161Flow "R" from "A" to "B" quantity 1
162"#;
163 let g = parse_to_graph(src).unwrap();
164 let flows = collect_flows(&g).unwrap();
165 assert_eq!(flows.len(), 2);
166 assert_eq!(flows[0].from, "A");
168 assert_eq!(flows[1].from, "B");
169 }
170
171 #[test]
172 fn collect_flows_preserves_flow_annotations() {
173 let src = r#"
176@namespace "proc"
177Entity "A" in proc
178Entity "B" in proc
179Resource "R" units in proc
180Flow "R" @cqrs { "kind": "command" } from "A" to "B" quantity 1
181"#;
182 let g = parse_to_graph(src).unwrap();
183 let flows = collect_flows(&g).unwrap();
184 assert_eq!(flows.len(), 1);
185 assert_eq!(flows[0].annotations["cqrs"]["kind"], "command");
186 }
187
188 #[test]
189 fn collect_flows_errors_on_dangling_reference() {
190 let src = r#"
201@namespace "proc"
202Entity "A" in proc
203Entity "B" in proc
204Resource "R" units in proc
205Flow "R" from "A" to "B" quantity 1
206"#;
207 let g = parse_to_graph(src).unwrap();
208 let mut value = serde_json::to_value(&g).unwrap();
209 let flow = value["flows"]
210 .as_object_mut()
211 .unwrap()
212 .values_mut()
213 .next()
214 .unwrap();
215 flow["resource_id"] = serde_json::json!(uuid::Uuid::new_v4().to_string());
216 let dangling: Graph = serde_json::from_value(value).unwrap();
217
218 let err = collect_flows(&dangling).unwrap_err();
219 assert!(matches!(err, FlowError::DanglingReference { .. }));
220 assert!(err.to_string().contains("dangling reference"), "{err}");
221 }
222
223 #[test]
224 fn model_namespace_single() {
225 let src = r#"
226@namespace "procurement"
227Entity "Buyer" in procurement
228Resource "PO" units in procurement
229"#;
230 let g = parse_to_graph(src).unwrap();
231 assert_eq!(model_namespace(&g).unwrap(), "procurement");
232 }
233
234 #[test]
235 fn model_namespace_errors_on_multiple() {
236 let src = r#"
237@namespace "a"
238Entity "A" in a
239Entity "B" in b
240"#;
241 let g = parse_to_graph(src).unwrap();
242 let err = model_namespace(&g).unwrap_err();
243 assert!(matches!(err, FlowError::MultiNamespace { .. }));
244 assert!(err.to_string().contains("multiple namespaces"), "{err}");
245 }
246
247 #[test]
248 fn model_namespace_default_when_empty() {
249 let g = parse_to_graph("@namespace \"empty\"\n").unwrap();
250 assert_eq!(model_namespace(&g).unwrap(), "default");
251 }
252}