arc-flow-core 0.4.0

Framework-free graph model for arc-flow: nodes, typed ports, edges, reversible ops, history, validation, edge geometry and spatial index.
Documentation
//! 连接校验:带错误码,视图层据此把非法目标染红并给出原因
//! (错误码分类参考 ferrum-flow `EdgeValidationErrorCode`,Apache-2.0,已改写;
//! 自连 / 重复 / `connectable` 规则参考 gpui-flow,MIT)。

use crate::graph::Graph;
use crate::ids::{EdgeId, PortId};
use crate::port::{PortDirection, PortScope};

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ConnectErrorCode {
    MissingPort,
    NotConnectable,
    /// 需要一个输出端和一个输入端。
    DirectionMismatch,
    SameNode,
    TypeMismatch,
    ScopeMismatch,
    AlreadyConnected,
    /// 目标端口连接数已满。
    PortFull,
    WouldCreateCycle,
    Custom,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ConnectError {
    pub code: ConnectErrorCode,
    pub message: String,
}

impl ConnectError {
    pub fn new(code: ConnectErrorCode, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
        }
    }
}

/// 可替换的校验器。`replacing` 为重新连接时被替换的旧边(不计入重复与占用)。
pub trait ConnectionValidator {
    fn validate(
        &self,
        graph: &Graph,
        from: PortId,
        to: PortId,
        replacing: Option<EdgeId>,
    ) -> Result<(), ConnectError>;
}

/// 内置规则。字段为开关,可按产品需要组合。
#[derive(Clone, Copy, Debug)]
pub struct DefaultValidator {
    pub check_types: bool,
    pub check_scope: bool,
    pub allow_self_loops: bool,
    pub allow_cycles: bool,
}

impl Default for DefaultValidator {
    fn default() -> Self {
        Self {
            check_types: true,
            check_scope: true,
            allow_self_loops: false,
            allow_cycles: true,
        }
    }
}

impl DefaultValidator {
    /// 工作流(DAG)场景:禁止成环。
    pub fn dag() -> Self {
        Self {
            allow_cycles: false,
            ..Self::default()
        }
    }

    /// 把任意顺序的两个端口规范为 (输出, 输入)。
    pub fn normalise(graph: &Graph, a: PortId, b: PortId) -> Option<(PortId, PortId)> {
        let pa = graph.port(a)?;
        let pb = graph.port(b)?;
        match (pa.direction, pb.direction) {
            (PortDirection::Output, PortDirection::Input) => Some((a, b)),
            (PortDirection::Input, PortDirection::Output) => Some((b, a)),
            _ => None,
        }
    }
}

impl ConnectionValidator for DefaultValidator {
    fn validate(
        &self,
        graph: &Graph,
        from: PortId,
        to: PortId,
        replacing: Option<EdgeId>,
    ) -> Result<(), ConnectError> {
        use ConnectErrorCode as C;
        let (Some(out), Some(inp)) = (graph.port(from), graph.port(to)) else {
            return Err(ConnectError::new(C::MissingPort, "端口不存在"));
        };
        if !out.connectable || !inp.connectable {
            return Err(ConnectError::new(C::NotConnectable, "该端口不可连接"));
        }
        if out.direction != PortDirection::Output || inp.direction != PortDirection::Input {
            return Err(ConnectError::new(
                C::DirectionMismatch,
                "只能从输出端连到输入端",
            ));
        }
        if out.node == inp.node && !self.allow_self_loops {
            return Err(ConnectError::new(C::SameNode, "不能连到同一个节点"));
        }
        if self.check_types && !out.ty.flows_into(&inp.ty) {
            return Err(ConnectError::new(
                C::TypeMismatch,
                format!("类型不匹配:{} → {}", out.ty.label(), inp.ty.label()),
            ));
        }
        if self.check_scope {
            let pa = graph.node(out.node).and_then(|n| n.parent);
            let pb = graph.node(inp.node).and_then(|n| n.parent);
            let boundary = out.scope == PortScope::Boundary || inp.scope == PortScope::Boundary;
            if pa != pb && !boundary {
                return Err(ConnectError::new(
                    C::ScopeMismatch,
                    "只能连接同一分组内的节点",
                ));
            }
        }
        let live = |e: &&EdgeId| Some(**e) != replacing;
        if graph
            .edges_of_port(from)
            .iter()
            .filter(live)
            .filter_map(|e| graph.edge(*e))
            .any(|e| e.to == to)
        {
            return Err(ConnectError::new(C::AlreadyConnected, "这两个端口已经相连"));
        }
        if let Some(max) = inp.max_connections
            && graph.edges_of_port(to).iter().filter(live).count() >= max
        {
            return Err(ConnectError::new(C::PortFull, "输入端口已被占用"));
        }
        if let Some(max) = out.max_connections
            && graph.edges_of_port(from).iter().filter(live).count() >= max
        {
            return Err(ConnectError::new(C::PortFull, "输出端口连接数已满"));
        }
        if !self.allow_cycles && graph.would_create_cycle(out.node, inp.node) {
            return Err(ConnectError::new(C::WouldCreateCycle, "连接后会形成环"));
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::geometry::{Size2, Vec2};
    use crate::port::PortType;

    fn code(r: Result<(), ConnectError>) -> Option<ConnectErrorCode> {
        r.err().map(|e| e.code)
    }

    #[test]
    fn rules() {
        let mut g = Graph::new();
        let sz = Size2::new(10.0, 10.0);
        let (_, ai, ao) = g.add_node_with("a", Vec2::ZERO, sz, 1, 1);
        let (_, bi, bo) = g.add_node_with("b", Vec2::ZERO, sz, 1, 1);
        let v = DefaultValidator::dag();
        assert_eq!(code(v.validate(&g, ao[0], bi[0], None)), None);
        assert_eq!(
            code(v.validate(&g, bi[0], ao[0], None)),
            Some(ConnectErrorCode::DirectionMismatch)
        );
        assert_eq!(
            code(v.validate(&g, ao[0], ai[0], None)),
            Some(ConnectErrorCode::SameNode)
        );
        let e = g.connect(ao[0], bi[0]).unwrap();
        assert_eq!(
            code(v.validate(&g, ao[0], bi[0], None)),
            Some(ConnectErrorCode::AlreadyConnected)
        );
        assert_eq!(
            code(v.validate(&g, ao[0], bi[0], Some(e))),
            None,
            "reconnect ignores old edge"
        );
        assert_eq!(
            code(v.validate(&g, bo[0], ai[0], None)),
            Some(ConnectErrorCode::WouldCreateCycle)
        );
        assert_eq!(
            code(DefaultValidator::default().validate(&g, bo[0], ai[0], None)),
            None
        );

        let (_, ci, _) = g.add_node_with("c", Vec2::ZERO, sz, 1, 0);
        g.ports.get_mut(&ci[0]).unwrap().ty = PortType::Int;
        g.ports.get_mut(&bo[0]).unwrap().ty = PortType::String;
        assert_eq!(
            code(v.validate(&g, bo[0], ci[0], None)),
            Some(ConnectErrorCode::TypeMismatch)
        );
        let (_, _, do_) = g.add_node_with("d", Vec2::ZERO, sz, 0, 1);
        g.connect(do_[0], ci[0]).unwrap();
        g.ports.get_mut(&bo[0]).unwrap().ty = PortType::Int;
        assert_eq!(
            code(v.validate(&g, bo[0], ci[0], None)),
            Some(ConnectErrorCode::PortFull)
        );
    }

    #[test]
    fn scope() {
        let mut g = Graph::new();
        let sz = Size2::new(10.0, 10.0);
        let (group, _, _) = g.add_node_with("group", Vec2::ZERO, sz, 0, 0);
        let (a, _, ao) = g.add_node_with("a", Vec2::ZERO, sz, 0, 1);
        let (_, bi, _) = g.add_node_with("b", Vec2::ZERO, sz, 1, 0);
        g.set_parent(a, Some(group)).unwrap();
        let v = DefaultValidator::default();
        assert_eq!(
            code(v.validate(&g, ao[0], bi[0], None)),
            Some(ConnectErrorCode::ScopeMismatch)
        );
        g.ports.get_mut(&ao[0]).unwrap().scope = PortScope::Boundary;
        assert_eq!(code(v.validate(&g, ao[0], bi[0], None)), None);
    }
}