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

XFEWorkflow

【WinUI】XFE基于windows的工作流

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

namespace XFEWorkflow.Core.Runtime;

/// <summary>Pure, typed operations shared by graphs, generated C# and packaged graph methods.</summary>
public static partial class WorkflowBasicNodes
{
    public const int MaxItems = 100_000;
    public const int MaxTextLength = 1_048_576;
    private sealed record Operation(CapabilityDescriptor Descriptor, Func<JsonObject, CancellationToken, JsonObject> Run);
    private static readonly IReadOnlyDictionary<string, Operation> Operations = Build();
    public static IReadOnlyList<CapabilityDescriptor> Descriptors { get; } = Operations.Values.Select(x => x.Descriptor).ToArray();
    public static bool Contains(string capabilityId) => Operations.ContainsKey(capabilityId);

    public static JsonObject Execute(string capabilityId, JsonObject input, CancellationToken cancellationToken = default)
    {
        if (!Operations.TryGetValue(capabilityId, out var operation)) throw new ArgumentException("未知的基础节点:" + capabilityId);
        cancellationToken.ThrowIfCancellationRequested();
        var values = WorkflowJson.Copy(input);
        foreach (var port in operation.Descriptor.Inputs)
        {
            if (!values.ContainsKey(port.Name) && port.DefaultValue is { } fallback) values[port.Name] = fallback.DeepClone();
            if (values[port.Name] is not { } value)
            { if (port.Required) throw new ArgumentException("缺少参数:" + port.Label); }
            else if (!GraphValidator.Matches(value, port.Type)) throw new ArgumentException("参数类型错误:" + port.Label + ",请先使用类型转换节点");
            if (values[port.Name] is JsonArray array && array.Count > MaxItems) throw new ArgumentException("输入数组过长:" + port.Label);
            if (values[port.Name] is JsonValue scalar && scalar.TryGetValue<string>(out var text)) CheckText(text);
            if (port.Choices.Count > 0 && !port.Choices.Contains(values[port.Name].Text())) throw new ArgumentException("参数选项无效:" + port.Label);
        }
        var result = operation.Run(values, cancellationToken);
        cancellationToken.ThrowIfCancellationRequested();
        foreach (var port in operation.Descriptor.Outputs)
            if (!result.ContainsKey(port.Name) || result[port.Name] is { } value && !GraphValidator.Matches(value, port.Type)) throw new InvalidOperationException("基础节点返回类型错误:" + port.Name);
        return result;
    }

    private static Dictionary<string, Operation> Build()
    {
        Dictionary<string, Operation> operations = new(StringComparer.Ordinal);
        AddText(operations); AddNumbers(operations); AddLogic(operations); AddCollections(operations); AddObjects(operations); AddDateTime(operations); AddEncodingAndPaths(operations);
        return operations;
    }
    private static void Add(Dictionary<string, Operation> operations, string id, string name, string category, string description,
        List<PortDefinition> inputs, List<PortDefinition> outputs, Func<JsonObject, CancellationToken, JsonObject> run)
    {
        var descriptor = new CapabilityDescriptor { Id = "core." + id, PluginId = "core", Name = name, Category = category,
            Description = description, Inputs = inputs, Outputs = outputs };
        operations.Add(descriptor.Id, new(descriptor, run));
    }
    private static PortDefinition P(string name, string label, WorkflowValueType type, JsonNode? value = null, bool required = false, string description = "") => new()
    { Name = name, Label = label, Type = type, DefaultValue = value, Required = required, Description = description.Length > 0 ? description : label + ";通过同类型数据端口连接。" };
    private static PortDefinition S(string name, string label, string value = "", string description = "") => new()
    { Name = name, Label = label, Type = WorkflowValueType.String, DefaultValue = JsonValue.Create(value), EditorHint = "literal-text",
        Description = description.Length > 0 ? description : label + ";按原文保存,包括空白、换行、中文和表情,不解析变量或表达式。" };
    private static PortDefinition N(string name, string label, decimal value = 0, string description = "") => P(name, label, WorkflowValueType.Number, JsonValue.Create(value), description: description);
    private static PortDefinition B(string name, string label, bool value = false) => P(name, label, WorkflowValueType.Boolean, JsonValue.Create(value));
    private static PortDefinition A(string name = "items", string label = "数组") => P(name, label, WorkflowValueType.Array, new JsonArray());
    private static PortDefinition O(string name = "value", string label = "对象") => P(name, label, WorkflowValueType.Object, new JsonObject());
    private static PortDefinition V(string name = "value", string label = "值") => P(name, label, WorkflowValueType.Any);
    private static PortDefinition Choice(string name, string label, params string[] choices) => new()
    { Name = name, Label = label, Type = WorkflowValueType.String, DefaultValue = JsonValue.Create(choices[0]), Choices = [.. choices], Description = label + ":" + string.Join(" / ", choices) };
    private static PortDefinition Out(WorkflowValueType type, string name = "value", string label = "结果", string description = "") => P(name, label, type, description: description);
    private static JsonObject Value(JsonNode? value) => new() { ["value"] = value?.DeepClone() };
    private static JsonObject Value(string value) => Value(JsonValue.Create(CheckText(value)));
    private static JsonObject Value(decimal value) => Value(JsonValue.Create(value));
    private static JsonObject Value(double value) => double.IsFinite(value) ? Value(JsonValue.Create(value)) : throw new ArithmeticException("运算结果不是有限数字");
    private static JsonObject Value(bool value) => Value(JsonValue.Create(value));
    private static string Str(JsonObject input, string name = "value") => input[name] is null ? "" : input[name]!.GetValue<string>();
    private static decimal Number(JsonObject input, string name = "value") => Number(input[name]);
    private static decimal Number(JsonNode? value)
    {
        if (value is null || value.GetValueKind() != JsonValueKind.Number || !decimal.TryParse(value.ToJsonString(), NumberStyles.Float, CultureInfo.InvariantCulture, out var number))
            throw new ArgumentException("需要 decimal 范围内的数字,请先使用数字转换节点");
        return number;
    }
    private static int Int(JsonObject input, string name, int min = int.MinValue, int max = int.MaxValue)
    {
        var number = Number(input, name);
        if (number != decimal.Truncate(number) || number < min || number > max) throw new ArgumentOutOfRangeException(name, $"必须为 {min} 到 {max} 的整数");
        return (int)number;
    }
    private static bool Flag(JsonObject input, string name) => input[name]?.GetValue<bool>() ?? false;
    private static JsonArray Array(JsonObject input, string name = "items") => input[name] as JsonArray ?? throw new ArgumentException(name + " 必须为数组");
    private static JsonObject Object(JsonObject input, string name = "value") => input[name] as JsonObject ?? throw new ArgumentException(name + " 必须为对象");
    private static string CheckText(string value) => value.Length <= MaxTextLength ? value : throw new ArgumentException($"文本结果超过 {MaxTextLength} 个 UTF-16 单元");
    private static JsonArray Pack(IEnumerable<JsonNode?> values, CancellationToken ct)
    {
        JsonArray result = [];
        foreach (var value in values)
        { ct.ThrowIfCancellationRequested(); if (result.Count >= MaxItems) throw new ArgumentException($"数组结果超过 {MaxItems} 项"); result.Add(value?.DeepClone()); }
        return result;
    }
    private static StringComparison Comparison(JsonObject input) => Flag(input, "ignoreCase") ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
    private static bool Equal(JsonNode? left, JsonNode? right) => JsonNode.DeepEquals(left, right);
}