using System.Reflection; using System.Runtime.Loader; using System.Text.Json; using XFEWorkflow.Abstractions; using XFEWorkflow.Core.Runtime; using XFEWorkflow.Infrastructure.Storage; namespace XFEWorkflow.Infrastructure.Plugins; public sealed class PluginManager(WorkspacePaths paths, ClientState state) { private readonly SemaphoreSlim gate = new(1); private readonly Dictionary leases = []; public event Action? Changed; public List Installed => state.Plugins; private static string Key(InstalledPlugin p) => p.Manifest.Id + "/" + p.Manifest.Version; public IReadOnlyList<(InstalledPlugin Plugin, PluginPageDescriptor Page)> PageCatalog() => Installed .Where(x => x.Enabled && !x.PendingRemoval && (x.Manifest.SupportedRids.Count == 0 || x.Manifest.SupportedRids.Contains(System.Runtime.InteropServices.RuntimeInformation.RuntimeIdentifier))) .GroupBy(x => x.Manifest.Id).Select(x => x.MaxBy(p => SemanticVersion.Parse(p.Manifest.Version))!) .SelectMany(x => x.Manifest.Pages.Select(page => (x, page))).ToList(); public IReadOnlyDictionary Catalog(WorkflowDefinition? workflow = null) { var selected = Installed.Where(x => x.Enabled && !x.PendingRemoval) .GroupBy(x => x.Manifest.Id).Select(g => workflow?.PluginVersions.TryGetValue(g.Key, out var version) == true ? g.FirstOrDefault(x => x.Manifest.Version == version) : g.MaxBy(x => SemanticVersion.Parse(x.Manifest.Version))).OfType(); var catalog = CoreCapabilities.Catalog(selected.SelectMany(x => x.Manifest.Capabilities)); return workflow is null ? catalog : WorkflowPortCatalog.For(workflow, catalog); } // Browsing new nodes must not change an existing workflow's version locks. public IReadOnlyDictionary AvailableNodeCatalog(WorkflowDefinition? workflow) { var current = Catalog(workflow); return current.Concat(Catalog().Where(x => !current.ContainsKey(x.Key))).ToDictionary(x => x.Key, x => x.Value); } public void UseNodeCapability(WorkflowDefinition workflow, string capabilityId) { if (Catalog(workflow).ContainsKey(capabilityId)) return; var plugin = Installed.Where(x => x.Enabled && !x.PendingRemoval && x.Manifest.Capabilities.Any(c => c.Id == capabilityId)) .MaxBy(x => SemanticVersion.Parse(x.Manifest.Version)) ?? throw new InvalidOperationException("找不到可用的节点能力:" + capabilityId); var proposed = WorkflowJson.Clone(workflow); proposed.PluginVersions[plugin.Manifest.Id] = plugin.Manifest.Version; proposed.Graph.Nodes.Add(new() { CapabilityId = capabilityId }); // Preserve all other locks and reject incompatible existing nodes or dependencies. Resolve(proposed); workflow.PluginVersions[plugin.Manifest.Id] = plugin.Manifest.Version; } public async Task ImportBundledAsync(string root, CancellationToken ct = default) { await gate.WaitAsync(ct); try { await PruneAsync(ct); } finally { gate.Release(); } if (!Directory.Exists(root)) return; foreach (var manifestFile in Directory.EnumerateFiles(root, "plugin.json", SearchOption.AllDirectories)) { var manifest = await AtomicJson.ReadAsync(manifestFile, ct) ?? throw new InvalidDataException("无效的内置插件"); if (Installed.Any(x => x.Manifest.Id == manifest.Id && x.Manifest.Version == manifest.Version)) continue; var package = WorkspacePaths.Inside(paths.Temp, Guid.NewGuid().ToString("N") + ".xfeplugin"); try { System.IO.Compression.ZipFile.CreateFromDirectory(Path.GetDirectoryName(manifestFile)!, package); await InstallAsync(package, "官方内置", ct); } finally { if (File.Exists(package)) File.Delete(package); } } } public async Task InstallAsync(string package, string source = "本地导入", CancellationToken ct = default) { await gate.WaitAsync(ct); var temporary = WorkspacePaths.Inside(paths.Temp, Guid.NewGuid().ToString("N")); try { var manifest = PluginPackage.Inspect(package); if (Installed.Any(x => x.Manifest.Id == manifest.Id && x.Manifest.Version == manifest.Version)) throw new InvalidOperationException("此版本已经安装,版本内容不可覆盖"); var destination = WorkspacePaths.Inside(paths.Plugins, manifest.Id + "/" + manifest.Version); PluginPackage.Extract(package, temporary); Directory.CreateDirectory(Path.GetDirectoryName(destination)!); if (Directory.Exists(destination)) throw new InvalidOperationException("此版本目录已经存在"); for (var attempt = 0; ; attempt++) { try { Directory.Move(temporary, destination); break; } catch (IOException) when (OperatingSystem.IsWindows() && attempt < 9 && Directory.Exists(temporary) && !Directory.Exists(destination)) { await Task.Delay(Math.Min(500, 100 * (attempt + 1)), ct); } catch (UnauthorizedAccessException) when (OperatingSystem.IsWindows() && attempt < 9 && Directory.Exists(temporary) && !Directory.Exists(destination)) { await Task.Delay(Math.Min(500, 100 * (attempt + 1)), ct); } } var plugin = new InstalledPlugin { Manifest = manifest, Directory = destination, Source = source }; state.Store.Update(p => p.InstancePlugins.Add(plugin)); await state.SaveAsync(ct); Changed?.Invoke(); return plugin; } finally { if (Directory.Exists(temporary)) Directory.Delete(WorkspacePaths.Inside(paths.Temp, Path.GetFileName(temporary)), true); gate.Release(); } } public async Task SetEnabledAsync(InstalledPlugin plugin, bool enabled, CancellationToken ct = default) { await gate.WaitAsync(ct); try { state.Store.Update(p => p.InstancePlugins.Single(x => Key(x) == Key(plugin)).Enabled = enabled); await state.SaveAsync(ct); Changed?.Invoke(); } finally { gate.Release(); } } public async Task RemoveAsync(InstalledPlugin plugin, CancellationToken ct = default) { await gate.WaitAsync(ct); try { state.Store.Update(p => { var installed = p.InstancePlugins.Single(x => Key(x) == Key(plugin)); installed.Enabled = false; installed.PendingRemoval = true; }); await PruneAsync(ct); Changed?.Invoke(); } finally { gate.Release(); } } private async Task PruneAsync(CancellationToken ct) { foreach (var item in Installed.Where(x => x.PendingRemoval && leases.GetValueOrDefault(Key(x)) == 0)) { var directory = WorkspacePaths.Inside(paths.Plugins, Key(item)); // Collectible ALC/native controls can release file handles after Dispose. // Keep the version disabled and pending rather than failing page shutdown. try { if (Directory.Exists(directory)) Directory.Delete(directory, true); } catch (IOException) { continue; } catch (UnauthorizedAccessException) { continue; } state.Store.Update(p => p.InstancePlugins.RemoveAll(x => Key(x) == Key(item))); } await state.SaveAsync(ct); } public List Resolve(WorkflowDefinition workflow) { var available = Installed.Where(x => x.Enabled && !x.PendingRemoval).ToList(); var requiredCapabilities = new Dictionary>(); foreach (var capability in UsedCapabilities(workflow.Graph).Concat(WorkflowTriggerNodes.Enumerate(workflow).Where(x => x.Kind == TriggerKind.Plugin).Select(x => x.CapabilityId)).Concat(workflow.Triggers.Where(x => x.Kind == TriggerKind.Plugin).Select(x => x.CapabilityId))) { if (capability.StartsWith("core.", StringComparison.Ordinal)) continue; var id = available.FirstOrDefault(x => x.Manifest.Capabilities.Any(c => c.Id == capability))?.Manifest.Id ?? throw new InvalidOperationException("找不到节点能力:" + capability); if (!requiredCapabilities.TryGetValue(id, out var required)) requiredCapabilities[id] = required = []; required.Add(capability); } var roots = workflow.PluginVersions.Keys.Concat(requiredCapabilities.Keys).Distinct().ToArray(); if (roots.Length == 0) return []; var root = new PluginManifest { Id = "$workflow", Version = "1.0.0", Dependencies = roots.Select(id => new PluginDependency { Id = id, MinimumVersion = "0.0.0", ExactVersion = workflow.PluginVersions.GetValueOrDefault(id) }).ToList() }; var rid = System.Runtime.InteropServices.RuntimeInformation.RuntimeIdentifier; // This resolver receives only completed in-memory tasks, so it never blocks // on the UI synchronization context. Installation and execution use one solver. var solution = PluginDependencyResolver.ResolveAsync(root, (id, _) => Task.FromResult(available .Where(x => x.Manifest.Id == id && (x.Manifest.SupportedRids.Count == 0 || x.Manifest.SupportedRids.Contains(rid)) && (!requiredCapabilities.TryGetValue(id, out var capabilities) || capabilities.All(capability => x.Manifest.Capabilities.Any(c => c.Id == capability)))) .Select(x => x.Manifest).ToList())).GetAwaiter().GetResult(); return solution.Where(x => x.Id != root.Id).Select(x => available.Single(p => p.Manifest.Id == x.Id && p.Manifest.Version == x.Version)).ToList(); } private static IEnumerable UsedCapabilities(GraphDefinition graph) => graph.Nodes.Select(x => x.CapabilityId).Concat(graph.Nodes.SelectMany(x => x.Children.Values).SelectMany(UsedCapabilities)); public async Task AcquireAsync(IEnumerable plugins, CancellationToken ct = default) { var keys = plugins.Select(Key).Distinct().ToArray(); await gate.WaitAsync(ct); try { foreach (var key in keys) if (!Installed.Any(x => Key(x) == key && x.Enabled && !x.PendingRemoval)) throw new InvalidOperationException("插件已禁用或卸载:" + key); foreach (var key in keys) leases[key] = leases.GetValueOrDefault(key) + 1; } finally { gate.Release(); } return new PluginLease(async () => { await gate.WaitAsync(); try { foreach (var key in keys) leases[key]--; await PruneAsync(CancellationToken.None); } finally { gate.Release(); } }); } private sealed class PluginLease(Func release) : IAsyncDisposable { private int disposed; public async ValueTask DisposeAsync() { if (Interlocked.Exchange(ref disposed, 1) == 0) await release(); } } } public sealed class PluginLoader : IDisposable { private readonly List contexts = []; private readonly Dictionary pluginContexts = []; public CapabilityRegistry Registry { get; } = new(); public void Load(IEnumerable plugins) { foreach (var plugin in plugins) { var assemblyPath = WorkspacePaths.Inside(plugin.Directory, plugin.Manifest.Assembly); var context = new PluginLoadContext(assemblyPath); contexts.Add(context); pluginContexts.Add(plugin.Manifest.Id + "/" + plugin.Manifest.Version, context); var assembly = context.LoadFromAssemblyPath(assemblyPath); var type = assembly.GetType(plugin.Manifest.EntryType, true)!; if (Activator.CreateInstance(type) is not IWorkflowPlugin instance) throw new InvalidDataException("插件入口未实现 IWorkflowPlugin"); instance.Register(new GuardedRegistry(Registry, plugin.Manifest)); foreach (var declared in plugin.Manifest.Capabilities) if (!Registry.Descriptors.ContainsKey(declared.Id)) throw new InvalidDataException("插件未注册声明的能力:" + declared.Id); foreach (var declared in plugin.Manifest.Pages) if (!Registry.Pages.ContainsKey(declared.Id)) throw new InvalidDataException("插件未注册声明的页面:" + declared.Id); } } public T CreatePage(InstalledPlugin plugin, string pageId) where T : class { var descriptor = plugin.Manifest.Pages.Single(x => x.Id == pageId); var context = pluginContexts[plugin.Manifest.Id + "/" + plugin.Manifest.Version]; var assembly = context.LoadFromAssemblyPath(WorkspacePaths.Inside(plugin.Directory, descriptor.Assembly)); return Activator.CreateInstance(assembly.GetType(descriptor.EntryType, true)!) as T ?? throw new InvalidDataException("页面入口未实现 " + typeof(T).Name); } public void Dispose() { foreach (var context in contexts) context.Unload(); contexts.Clear(); pluginContexts.Clear(); } private sealed class PluginLoadContext(string entry) : AssemblyLoadContext(isCollectible: true) { private readonly AssemblyDependencyResolver resolver = new(entry); protected override Assembly? Load(AssemblyName name) { if (name.Name == typeof(IWorkflowPlugin).Assembly.GetName().Name) return typeof(IWorkflowPlugin).Assembly; if (name.Name is "XFEWorkflow.Desktop.Sdk" or "Microsoft.WinUI" or "Microsoft.Web.WebView2.Core" or "Microsoft.Web.WebView2.Core.Projection" or "Microsoft.Windows.SDK.NET" or "Microsoft.InteractiveExperiences.Projection" || name.Name?.StartsWith("WinRT.", StringComparison.Ordinal) == true) return Default.Assemblies.FirstOrDefault(x => x.GetName().Name == name.Name) ?? Default.LoadFromAssemblyName(name); var path = resolver.ResolveAssemblyToPath(name); if (path is null && name.Name is { } file && file.IndexOfAny(['/', '\\', ':']) < 0) { var sibling = WorkspacePaths.Inside(Path.GetDirectoryName(entry)!, file + ".dll"); if (File.Exists(sibling)) path = sibling; } return path is null ? null : LoadFromAssemblyPath(path); } protected override nint LoadUnmanagedDll(string name) { var path = resolver.ResolveUnmanagedDllToPath(name); return path is null ? 0 : LoadUnmanagedDllFromPath(path); } } private sealed class GuardedRegistry(CapabilityRegistry registry, PluginManifest manifest) : IPluginRegistry { public void RegisterPage(PluginPageDescriptor descriptor) => registry.RegisterPage(manifest.Pages.SingleOrDefault(x => x.Id == descriptor.Id) ?? throw new InvalidDataException("未声明的页面:" + descriptor.Id)); private CapabilityDescriptor Check(CapabilityDescriptor value, bool trigger) { var declared = manifest.Capabilities.SingleOrDefault(x => x.Id == value.Id && x.IsTrigger == trigger) ?? throw new InvalidDataException("未声明的能力:" + value.Id); return declared; } public void RegisterAction(CapabilityDescriptor descriptor, Func factory) => registry.RegisterAction(Check(descriptor, false), factory); public void RegisterTrigger(CapabilityDescriptor descriptor, Func factory) => registry.RegisterTrigger(Check(descriptor, true), factory); } }