use crate::graph::Graph;
use crate::projection::ids::element_id;
use std::collections::{BTreeMap, BTreeSet};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NodeKind {
StartEvent,
EndEvent,
Task,
GatewayDiverging,
GatewayConverging,
}
#[derive(Debug, Clone)]
pub struct Node {
pub id: String,
pub kind: NodeKind,
pub name: Option<String>,
pub incoming: Vec<String>,
pub outgoing: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct SequenceFlow {
pub id: String,
pub source: String,
pub target: String,
}
#[derive(Debug, Clone)]
pub struct Lane {
pub id: String,
pub name: String,
pub flow_node_refs: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct DataObject {
pub id: String,
pub name: String,
}
#[derive(Debug, Clone)]
pub struct ProcessIR {
pub definitions_id: String,
pub process_id: String,
pub process_name: String,
pub lane_set_id: Option<String>,
pub lanes: Vec<Lane>,
pub data_objects: Vec<DataObject>,
pub nodes: Vec<Node>,
pub sequence_flows: Vec<SequenceFlow>,
}
const FAMILY: &str = "bpmn";
fn id(prefix: &str, parts: &[&str]) -> String {
format!("{prefix}_{}", element_id(FAMILY, parts))
}
impl ProcessIR {
pub fn from_graph(graph: &Graph, model_ref: &str) -> Self {
let definitions_id = id("Definitions", &["definitions", model_ref]);
let process_id = id("Process", &["process", model_ref]);
let start_id = id("StartEvent", &["start", &process_id]);
let end_id = id("EndEvent", &["end", &process_id]);
let mut entities: Vec<_> = graph.all_entities();
entities.sort_by_key(|e| (e.name().to_string(), e.id().to_string()));
let entity_name: BTreeMap<String, String> = entities
.iter()
.map(|e| (e.id().to_string(), e.name().to_string()))
.collect();
let mut out_deg: BTreeMap<String, usize> = BTreeMap::new();
let mut in_deg: BTreeMap<String, usize> = BTreeMap::new();
let mut edges: Vec<(String, String)> = Vec::new();
let mut participating: BTreeSet<String> = BTreeSet::new();
for f in graph.all_flows() {
let from = f.from_id().to_string();
let to = f.to_id().to_string();
if !entity_name.contains_key(&from) || !entity_name.contains_key(&to) {
continue;
}
*out_deg.entry(from.clone()).or_default() += 1;
*in_deg.entry(to.clone()).or_default() += 1;
participating.insert(from.clone());
participating.insert(to.clone());
edges.push((from, to));
}
edges.sort();
let task_id = |eid: &str| id("Task", &["task", eid]);
let diverge_id = |eid: &str| id("Gateway", &["diverge", eid]);
let converge_id = |eid: &str| id("Gateway", &["converge", eid]);
let exit_of = |eid: &str| {
if out_deg.get(eid).copied().unwrap_or(0) > 1 {
diverge_id(eid)
} else {
task_id(eid)
}
};
let entry_of = |eid: &str| {
if in_deg.get(eid).copied().unwrap_or(0) > 1 {
converge_id(eid)
} else {
task_id(eid)
}
};
let mut nodes: BTreeMap<String, Node> = BTreeMap::new();
let mut add = |id: String, kind: NodeKind, name: Option<String>| {
nodes.entry(id.clone()).or_insert(Node {
id,
kind,
name,
incoming: Vec::new(),
outgoing: Vec::new(),
});
};
add(start_id.clone(), NodeKind::StartEvent, None);
add(end_id.clone(), NodeKind::EndEvent, None);
for eid in &participating {
add(task_id(eid), NodeKind::Task, Some(entity_name[eid].clone()));
if out_deg.get(eid).copied().unwrap_or(0) > 1 {
add(diverge_id(eid), NodeKind::GatewayDiverging, None);
}
if in_deg.get(eid).copied().unwrap_or(0) > 1 {
add(converge_id(eid), NodeKind::GatewayConverging, None);
}
}
let mut flows: BTreeMap<String, SequenceFlow> = BTreeMap::new();
let mut connect = |source: String, target: String| {
let fid = id("Flow", &["flow", &source, &target]);
flows.entry(fid.clone()).or_insert(SequenceFlow {
id: fid,
source,
target,
});
};
if participating.is_empty() {
connect(start_id.clone(), end_id.clone());
} else {
for eid in &participating {
if out_deg.get(eid).copied().unwrap_or(0) > 1 {
connect(task_id(eid), diverge_id(eid));
}
if in_deg.get(eid).copied().unwrap_or(0) > 1 {
connect(converge_id(eid), task_id(eid));
}
}
for (from, to) in &edges {
connect(exit_of(from), entry_of(to));
}
for eid in &participating {
if in_deg.get(eid).copied().unwrap_or(0) == 0 {
connect(start_id.clone(), entry_of(eid));
}
if out_deg.get(eid).copied().unwrap_or(0) == 0 {
connect(exit_of(eid), end_id.clone());
}
}
}
for f in flows.values() {
if let Some(n) = nodes.get_mut(&f.source) {
n.outgoing.push(f.id.clone());
}
if let Some(n) = nodes.get_mut(&f.target) {
n.incoming.push(f.id.clone());
}
}
for n in nodes.values_mut() {
n.incoming.sort();
n.outgoing.sort();
}
let mut lane_refs: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
for eid in &participating {
let cid = entities
.iter()
.find(|e| e.id().to_string() == *eid)
.map(|e| e.id().clone());
let Some(cid) = cid else { continue };
let mut role_names = graph.role_names_for_entity(&cid);
role_names.sort();
if let Some(role) = role_names.first() {
lane_refs
.entry(role.clone())
.or_default()
.insert(task_id(eid));
}
}
let mut roles: Vec<_> = graph.all_roles();
roles.sort_by_key(|r| (r.name().to_string(), r.id().to_string()));
let lanes: Vec<Lane> = roles
.iter()
.map(|r| {
let name = r.name().to_string();
let refs = lane_refs.remove(&name).unwrap_or_default();
Lane {
id: id("Lane", &["lane", r.namespace(), &name]),
name,
flow_node_refs: refs.into_iter().collect(),
}
})
.collect();
let lane_set_id = (!lanes.is_empty()).then(|| id("LaneSet", &["laneset", &process_id]));
let mut resources: Vec<_> = graph.all_resources();
resources.sort_by_key(|r| (r.name().to_string(), r.id().to_string()));
let data_objects: Vec<DataObject> = resources
.iter()
.map(|r| DataObject {
id: id("DataObject", &["data", r.namespace(), r.name()]),
name: r.name().to_string(),
})
.collect();
ProcessIR {
definitions_id,
process_id,
process_name: model_ref.to_string(),
lane_set_id,
lanes,
data_objects,
nodes: nodes.into_values().collect(),
sequence_flows: flows.into_values().collect(),
}
}
pub fn validate_references(&self) -> Result<(), String> {
let node_ids: BTreeSet<&str> = self.nodes.iter().map(|n| n.id.as_str()).collect();
let flow_ids: BTreeSet<&str> = self.sequence_flows.iter().map(|f| f.id.as_str()).collect();
for f in &self.sequence_flows {
if !node_ids.contains(f.source.as_str()) {
return Err(format!(
"sequence flow {} has sourceRef {} with no matching flow node",
f.id, f.source
));
}
if !node_ids.contains(f.target.as_str()) {
return Err(format!(
"sequence flow {} has targetRef {} with no matching flow node",
f.id, f.target
));
}
}
for n in &self.nodes {
for r in n.incoming.iter().chain(&n.outgoing) {
if !flow_ids.contains(r.as_str()) {
return Err(format!(
"flow node {} references sequence flow {} which does not exist",
n.id, r
));
}
}
}
for lane in &self.lanes {
for r in &lane.flow_node_refs {
if !node_ids.contains(r.as_str()) {
return Err(format!(
"lane {} references flow node {} which does not exist",
lane.id, r
));
}
}
}
Ok(())
}
}