using XFEWorkflow.Abstractions; namespace XFEWorkflow.Infrastructure.Plugins; public static class PluginDependencyResolver { public static async Task> ResolveAsync(PluginManifest root, Func>> versions, CancellationToken ct = default) { var cache = new Dictionary>(); var attempts = 0; var visited = new HashSet(); async Task?> Search(Dictionary chosen) { ct.ThrowIfCancellationRequested(); if (++attempts > 10000 || chosen.Count > 128) throw new InvalidOperationException("插件依赖过于复杂"); var requirements = chosen.Values.SelectMany(x => x.Dependencies).GroupBy(x => x.Id).ToDictionary(x => x.Key, x => x.ToList()); foreach (var pair in requirements) { visited.Add(pair.Key); if (chosen.TryGetValue(pair.Key, out var selected) && !pair.Value.All(x => x.Accepts(selected.Version))) return null; } var pending = requirements.Keys.Where(x => !chosen.ContainsKey(x)).Order(StringComparer.Ordinal).FirstOrDefault(); if (pending is null) return HasCycle(chosen) ? null : chosen; if (!cache.TryGetValue(pending, out var candidates)) cache[pending] = candidates = await versions(pending, ct); foreach (var candidate in candidates.Where(x => x.Id == pending && requirements[pending].All(r => r.Accepts(x.Version))).OrderByDescending(x => SemanticVersion.Parse(x.Version))) { PluginPackage.Validate(candidate); var next = new Dictionary(chosen) { [pending] = candidate }; if (await Search(next) is { } solution) return solution; } return null; } var result = await Search(new() { [root.Id] = root }) ?? throw new InvalidOperationException("依赖缺失、版本冲突或循环引用:" + string.Join("、", visited.Order())); List ordered = []; HashSet added = []; void Add(PluginManifest manifest) { if (!added.Add(manifest.Id)) return; foreach (var dependency in manifest.Dependencies) Add(result[dependency.Id]); ordered.Add(manifest); } Add(root); return ordered; } private static bool HasCycle(Dictionary chosen) { HashSet active = [], complete = []; bool Visit(string id) { if (active.Contains(id)) return true; if (!complete.Add(id)) return false; active.Add(id); foreach (var dependency in chosen[id].Dependencies) if (Visit(dependency.Id)) return true; active.Remove(id); return false; } return chosen.Keys.Any(Visit); } }