XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWorkflow

【WinUI】XFE基于windows的工作流

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Text.Json;
using System.Text.Json.Nodes;
using XFEWorkflow.Abstractions;

namespace XFEWorkflow.Core.Runtime;

public static class GraphValidator
{
    public static List<WorkflowDiagnostic> Validate(WorkflowDefinition workflow, IReadOnlyDictionary<string, CapabilityDescriptor> catalog)
    {
        List<WorkflowDiagnostic> errors = [];
        catalog = WorkflowPortCatalog.For(workflow, catalog);
        foreach (var ports in new[] { workflow.Inputs, workflow.Outputs })
            if (ports.Any(x => string.IsNullOrWhiteSpace(x.Name) || x.Name == "inputs") || ports.Select(x => x.Name).Distinct().Count() != ports.Count)
                errors.Add(new("参数与返回值名称不能为空、重复或使用保留名称 inputs"));
        if (workflow.SchemaVersion != 1) errors.Add(new("不支持的工作流格式版本"));
        if (string.IsNullOrWhiteSpace(workflow.Name)) errors.Add(new("工作流名称不能为空"));
        if (workflow.Kind == WorkflowKind.Graph) ValidateGraph(workflow.Graph, catalog, errors, []);
        else if (string.IsNullOrWhiteSpace(workflow.Code)) errors.Add(new("C# 工作流代码为空"));
        foreach (var node in workflow.Graph.Nodes.Where(WorkflowTriggerNodes.IsTrigger))
        {
            if (node.Trigger is not { } trigger) { errors.Add(new("触发节点缺少配置", node.Id)); continue; }
            if (workflow.Enabled == true && WorkflowTriggerNodes.ConfigurationError(trigger, catalog, workflow.Id) is { } error) errors.Add(new(error, node.Id));
            if (workflow.Kind == WorkflowKind.Graph && workflow.Enabled == true && trigger.Enabled && !workflow.Graph.Edges.Any(x => x.Kind == PortKind.Execution && x.FromNode == node.Id))
                errors.Add(new("启用的触发节点需要连接后续步骤", node.Id));
        }
        return errors;
    }

    private static void ValidateGraph(GraphDefinition graph, IReadOnlyDictionary<string, CapabilityDescriptor> catalog, List<WorkflowDiagnostic> errors, HashSet<string> ids, int depth = 0, bool inLoop = false, bool inCatch = false)
    {
        if (depth > 32) { errors.Add(new("结构化子图嵌套不能超过 32 层")); return; }
        var nodes = new Dictionary<string, NodeDefinition>();
        foreach (var node in graph.Nodes)
        {
            nodes.TryAdd(node.Id, node);
            if (string.IsNullOrWhiteSpace(node.Id) || !ids.Add(node.Id)) errors.Add(new("节点 ID 为空或在工作流内重复", node.Id));
        }
        var starts = graph.Nodes.Count(x => x.CapabilityId == "core.start");
        if (starts > 1 || (depth > 0 && starts != 1) || (depth == 0 && starts == 0 && !graph.Nodes.Any(WorkflowTriggerNodes.IsTrigger))) errors.Add(new("流程需要一个手动入口或触发节点,手动入口不能重复"));
        foreach (var node in graph.Nodes)
        {
            if (!catalog.ContainsKey(node.CapabilityId)) errors.Add(new($"缺少插件或能力:{node.CapabilityId}", node.Id));
            if (catalog.GetValueOrDefault(node.CapabilityId)?.IsTrigger == true && node.Trigger is null) errors.Add(new("触发节点缺少配置", node.Id));
            if (node.Trigger is { } trigger && (trigger.Kind == TriggerKind.Manual || node.CapabilityId != (trigger.Kind == TriggerKind.Plugin ? trigger.CapabilityId : WorkflowTriggerNodes.CapabilityId(trigger.Kind))))
                errors.Add(new("触发节点能力与配置类型不一致", node.Id));
            if (depth > 0 && WorkflowTriggerNodes.IsTrigger(node)) errors.Add(new("自动触发节点只能放在工作流主图", node.Id));
            if (node.RetryCount is < 0 or > 100 || node.TimeoutSeconds < 0 || node.RetryDelayMilliseconds < 0)
                errors.Add(new("超时或重试设置无效", node.Id));
            if (node.CapabilityId is "core.break" or "core.continue" && !inLoop) errors.Add(new("循环控制只能在循环 body 内,不能跨并行分支或子工作流", node.Id));
            if (node.CapabilityId == "core.error.current" && !inCatch) errors.Add(new("当前异常只能在 catch 子图中读取", node.Id));
            foreach (var child in node.Children)
            {
                var loop = node.CapabilityId is "core.foreach" or "core.for" or "core.repeat" or "core.while" or "core.doWhile";
                var childLoop = loop ? child.Key == "body" : node.CapabilityId != "core.parallel" && inLoop;
                ValidateGraph(child.Value, CoreCapabilities.Catalog(catalog.Values.Where(x => x.PluginId != "core")), errors, ids, depth + 1, childLoop,
                    inCatch || node.CapabilityId == "core.try" && child.Key == "catch");
            }
        }
        foreach (var edge in graph.Edges)
        {
            if (!nodes.TryGetValue(edge.FromNode, out var from) || !nodes.TryGetValue(edge.ToNode, out var to))
            { errors.Add(new("连线引用了不存在的节点", edge.ToNode)); continue; }
            if (!catalog.TryGetValue(from.CapabilityId, out var source) || !catalog.TryGetValue(to.CapabilityId, out var target)) continue;
            if (edge.Kind == PortKind.Execution)
            {
                var ports = ExecutionOutputs(from, source);
                if (!ports.Contains(edge.FromPort) || edge.ToPort != "in" || to.CapabilityId == "core.start" || WorkflowTriggerNodes.IsTrigger(to))
                    errors.Add(new("执行端口无效", edge.FromNode));
            }
            else
            {
                var output = WorkflowPortCatalog.Find(source.Outputs, edge.FromPort);
                var input = WorkflowPortCatalog.Find(target.Inputs, edge.ToPort);
                if (output is null || input is null) errors.Add(new("数据端口不存在", edge.ToNode));
                else if (!Compatible(output, input)) errors.Add(new($"端口类型不兼容:{WorkflowPortCatalog.TypeName(output)} → {WorkflowPortCatalog.TypeName(input)},请使用类型转换节点", edge.ToNode));
            }
        }
        foreach (var group in graph.Edges.GroupBy(x => (x.Kind, x.Kind == PortKind.Execution ? x.FromNode : x.ToNode, x.Kind == PortKind.Execution ? x.FromPort : x.ToPort)))
            if (group.Count() > 1) errors.Add(new("一个执行输出或数据输入只能连接一次,请使用并行节点", group.First().ToNode));
        HashSet<string> active = [], complete = [];
        bool Visit(string id)
        {
            if (active.Contains(id)) return false;
            if (!complete.Add(id)) return true;
            active.Add(id);
            foreach (var edge in graph.Edges.Where(x => x.Kind == PortKind.Execution && x.FromNode == id))
                if (!Visit(edge.ToNode)) return false;
            active.Remove(id);
            return true;
        }
        foreach (var node in graph.Nodes)
            if (!Visit(node.Id)) { errors.Add(new("执行连线存在环,请使用循环节点", node.Id)); break; }
    }

    public static List<string> ExecutionOutputs(NodeDefinition node, CapabilityDescriptor descriptor) =>
        node.CapabilityId == "core.switch" && node.Parameters["cases"] is JsonArray cases
            ? cases.Select(x => x.Text()).Where(x => x.Length > 0).Append("default").Distinct().ToList()
            : descriptor.ExecutionOutputs;
    public static bool Compatible(WorkflowValueType source, WorkflowValueType target) => source == target || target == WorkflowValueType.Any;
    public static bool Compatible(PortDefinition source, PortDefinition target) => target.Type == WorkflowValueType.Any && target.TypeId.Length == 0
        || source.Type == target.Type && source.TypeId == target.TypeId;
    public static bool Matches(JsonNode value, WorkflowValueType type) => type switch
    {
        WorkflowValueType.Any => true,
        WorkflowValueType.Object => value is JsonObject,
        WorkflowValueType.Array => value is JsonArray,
        WorkflowValueType.Resource or WorkflowValueType.String => value.GetValueKind() == JsonValueKind.String,
        WorkflowValueType.Number => value.GetValueKind() == JsonValueKind.Number,
        WorkflowValueType.Boolean => value.GetValueKind() is JsonValueKind.True or JsonValueKind.False,
        _ => false
    };
}