Skip to main content

domainforge_core/projection/
flows.rs

1//! Shared flow resolution + namespace derivation for projection families.
2//!
3//! Every projection family that consumes SEA flows needs to resolve flow
4//! endpoint/resource ids to display names. This module provides one blessed
5//! helper so the resolution policy — including the dangling-reference policy
6//! (M4) — is uniform across all eight targets. ADR-011 §2 requires this: no
7//! family re-implements flow resolution.
8//!
9//! # Dangling-reference policy
10//! The graph should never contain a flow referencing an unknown entity or
11//! resource, but if one does, [`collect_flows`] returns an **error** (loud)
12//! rather than silently dropping the flow. CloudEvents always errored this
13//! way; the other seven targets previously `continue`-d, emitting a smaller
14//! architecture than the model declares. Loud is correct — a partially
15//! projected authority/verification artifact must not look complete.
16
17use crate::graph::Graph;
18use std::collections::BTreeMap;
19
20/// A flow with display names resolved for its resource and endpoints.
21#[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    /// Flow annotations (e.g. `@cqrs { "kind": "command" }`) copied from the
29    /// graph flow's attribute map. `BTreeMap` gives deterministic ordering.
30    pub annotations: BTreeMap<String, serde_json::Value>,
31}
32
33/// F3: structured errors for the two failure modes this module can produce.
34/// Previously both were a bare `String`, so every one of the eight callers
35/// could only match on substring content if it wanted to distinguish them.
36/// `From<FlowError> for String` is implemented below so every existing
37/// `collect_flows(graph)?` / `model_namespace(graph)?` call site (all
38/// currently inside functions returning `Result<_, String>`) keeps
39/// compiling unchanged.
40#[derive(Clone, Debug, PartialEq, Eq)]
41pub enum FlowError {
42    /// A flow references an entity or resource id that doesn't exist in the
43    /// graph (M4's loud dangling-reference policy).
44    DanglingReference { flow_id: String },
45    /// The graph declares more than one namespace across its entities and
46    /// resources (M5).
47    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
76/// Resolve every flow in the graph to display names, sorted by
77/// (resource, from, to) for deterministic output. Returns an error if any
78/// flow references an unknown entity or resource (loud dangling-reference
79/// policy — M4).
80pub 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
126/// Derive the model's namespace. Returns an error if the model spans more
127/// than one namespace (multi-namespace models previously collapsed silently
128/// to the alphabetically-first entity's namespace — M5). The namespace is
129/// derived from all entities and resources; if none declare a namespace,
130/// `"default"` is returned.
131pub 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        // Sorted by (resource, from, to): A→B before B→A.
167        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        // `@cqrs { "kind": "command" }` on a flow must survive from AST into
174        // the graph and out through `ResolvedFlow::annotations` (Task 1).
175        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        // A flow referencing a non-existent resource is a graph integrity
191        // error — we surface it loudly instead of silently dropping (M4).
192        // `Graph::add_flow` refuses to construct one (and `remove_entity`/
193        // `remove_resource` refuse to leave one dangling), so the only way
194        // to produce this state is to bypass those constructors: `Graph`
195        // derives `Deserialize` directly on its raw field set, so a
196        // hand-edited JSON round-trip can build the otherwise-unreachable
197        // state this function must still handle loudly rather than
198        // silently (F1 — the previous version of this test asserted the
199        // empty case instead of the actual dangling-reference path).
200        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}