use std::collections::BTreeMap;
use std::sync::Arc;
use crate::workflow::{Edge, Node, Route, StringRoute};
#[derive(Clone, Default)]
pub struct EdgeBuilder {
edges: Vec<Edge>,
}
impl EdgeBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn add(&mut self, from: &Arc<dyn Node>, to: &Arc<dyn Node>) -> &mut Self {
self.edges.push(Edge {
from: Arc::clone(from),
to: Arc::clone(to),
route: None,
});
self
}
pub fn add_route(
&mut self,
from: &Arc<dyn Node>,
to: &Arc<dyn Node>,
route: Arc<dyn Route>,
) -> &mut Self {
self.edges.push(Edge {
from: Arc::clone(from),
to: Arc::clone(to),
route: Some(route),
});
self
}
pub fn add_fan_out(&mut self, from: &Arc<dyn Node>, to: &[Arc<dyn Node>]) -> &mut Self {
for t in to {
self.add(from, t);
}
self
}
pub fn add_fan_in(&mut self, to: &Arc<dyn Node>, from: &[Arc<dyn Node>]) -> &mut Self {
for f in from {
self.add(f, to);
}
self
}
pub fn add_routes(
&mut self,
from: &Arc<dyn Node>,
routes: impl IntoIterator<Item = (String, Arc<dyn Node>)>,
) -> &mut Self {
let sorted: BTreeMap<String, Arc<dyn Node>> = routes.into_iter().collect();
for (key, to) in sorted {
self.add_route(from, &to, Arc::new(StringRoute(key)));
}
self
}
pub fn build(&self) -> Vec<Edge> {
self.edges.clone()
}
}
pub fn chain(nodes: &[Arc<dyn Node>]) -> Vec<Edge> {
nodes
.windows(2)
.map(|w| Edge {
from: Arc::clone(&w[0]),
to: Arc::clone(&w[1]),
route: None,
})
.collect()
}
pub fn concat(parts: impl IntoIterator<Item = Vec<Edge>>) -> Vec<Edge> {
parts.into_iter().flatten().collect()
}