diff options
Diffstat (limited to 'lib/Plugins.Essentials.ServiceStack/src/Plugins')
8 files changed, 819 insertions, 0 deletions
diff --git a/lib/Plugins.Essentials.ServiceStack/src/Plugins/IHttpPluginManager.cs b/lib/Plugins.Essentials.ServiceStack/src/Plugins/IHttpPluginManager.cs new file mode 100644 index 0000000..23e436b --- /dev/null +++ b/lib/Plugins.Essentials.ServiceStack/src/Plugins/IHttpPluginManager.cs @@ -0,0 +1,63 @@ +/* +* Copyright (c) 2024 Vaughn Nugent +* +* Library: VNLib +* Package: VNLib.Plugins.Essentials.ServiceStack +* File: IHttpPluginManager.cs +* +* IHttpPluginManager.cs is part of VNLib.Plugins.Essentials.ServiceStack which +* is part of the larger VNLib collection of libraries and utilities. +* +* VNLib.Plugins.Essentials.ServiceStack is free software: you can redistribute it and/or modify +* it under the terms of the GNU Affero General Public License as +* published by the Free Software Foundation, either version 2 of the +* License, or (at your option) any later version. +* +* VNLib.Plugins.Essentials.ServiceStack is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU Affero General Public License for more details. +* +* You should have received a copy of the GNU Affero General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ + +using System; +using System.Collections.Generic; + +namespace VNLib.Plugins.Essentials.ServiceStack.Plugins +{ + /// <summary> + /// Represents a live plugin controller that manages all + /// plugins loaded in a <see cref="ServiceDomain"/> + /// </summary> + public interface IHttpPluginManager + { + /// <summary> + /// The the plugins managed by this <see cref="IHttpPluginManager"/> + /// </summary> + public IEnumerable<IManagedPlugin> Plugins { get; } + + /// <summary> + /// Sends a message to a plugin identified by it's name. + /// </summary> + /// <param name="pluginName">The name of the plugin to pass the message to</param> + /// <param name="message">The message to pass to the plugin</param> + /// <param name="nameComparison">The name string comparison type</param> + /// <returns>True if the plugin was found and it has a message handler loaded</returns> + /// <exception cref="ObjectDisposedException"></exception> + bool SendCommandToPlugin(string pluginName, string message, StringComparison nameComparison = StringComparison.Ordinal); + + /// <summary> + /// Manually reloads all plugins loaded to the current service manager + /// </summary> + /// <exception cref="AggregateException"></exception> + /// <exception cref="ObjectDisposedException"></exception> + void ForceReloadAllPlugins(); + + /// <summary> + /// Unloads all loaded plugins and calls thier event handlers + /// </summary> + void UnloadPlugins(); + } +} diff --git a/lib/Plugins.Essentials.ServiceStack/src/Plugins/IManagedPlugin.cs b/lib/Plugins.Essentials.ServiceStack/src/Plugins/IManagedPlugin.cs new file mode 100644 index 0000000..b2506c5 --- /dev/null +++ b/lib/Plugins.Essentials.ServiceStack/src/Plugins/IManagedPlugin.cs @@ -0,0 +1,63 @@ +/* +* Copyright (c) 2024 Vaughn Nugent +* +* Library: VNLib +* Package: VNLib.Plugins.Essentials.ServiceStack +* File: IManagedPlugin.cs +* +* IManagedPlugin.cs is part of VNLib.Plugins.Essentials.ServiceStack which is part of the larger +* VNLib collection of libraries and utilities. +* +* VNLib.Plugins.Essentials.ServiceStack is free software: you can redistribute it and/or modify +* it under the terms of the GNU Affero General Public License as +* published by the Free Software Foundation, either version 2 of the +* License, or (at your option) any later version. +* +* VNLib.Plugins.Essentials.ServiceStack is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU Affero General Public License for more details. +* +* You should have received a copy of the GNU Affero General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ + +using System; +using System.ComponentModel.Design; + +namespace VNLib.Plugins.Essentials.ServiceStack.Plugins +{ + /// <summary> + /// Represents a plugin managed by a <see cref="IHttpPluginManager"/> that includes dynamically loaded plugins + /// </summary> + public interface IManagedPlugin + { + /// <summary> + /// The exposed services the inernal plugin provides + /// </summary> + /// <remarks> + /// WARNING: Services exposed by the plugin will abide by the plugin lifecycle, so consumers + /// must listen for plugin load/unload events to respect lifecycles properly. + /// </remarks> + IServiceContainer Services { get; } + + /// <summary> + /// Internal notification that the plugin is loaded + /// </summary> + internal void OnPluginLoaded(); + + /// <summary> + /// Internal notification that the plugin is unloaded + /// </summary> + internal void OnPluginUnloaded(); + + /// <summary> + /// Sends the specified command to the desired plugin by it's name + /// </summary> + /// <param name="pluginName">The name of the plugin to find</param> + /// <param name="command">The command text to send to the plugin</param> + /// <param name="comp">The string name comparison type</param> + /// <returns>True if the command was sent successfully</returns> + internal bool SendCommandToPlugin(string pluginName, string command, StringComparison comp); + } +} diff --git a/lib/Plugins.Essentials.ServiceStack/src/Plugins/IManualPlugin.cs b/lib/Plugins.Essentials.ServiceStack/src/Plugins/IManualPlugin.cs new file mode 100644 index 0000000..57fd631 --- /dev/null +++ b/lib/Plugins.Essentials.ServiceStack/src/Plugins/IManualPlugin.cs @@ -0,0 +1,71 @@ +/* +* Copyright (c) 2024 Vaughn Nugent +* +* Library: VNLib +* Package: VNLib.Plugins.Essentials.ServiceStack +* File: IManualPlugin.cs +* +* IManualPlugin.cs is part of VNLib.Plugins.Essentials.ServiceStack which is part of the larger +* VNLib collection of libraries and utilities. +* +* VNLib.Plugins.Essentials.ServiceStack is free software: you can redistribute it and/or modify +* it under the terms of the GNU Affero General Public License as +* published by the Free Software Foundation, either version 2 of the +* License, or (at your option) any later version. +* +* VNLib.Plugins.Essentials.ServiceStack is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU Affero General Public License for more details. +* +* You should have received a copy of the GNU Affero General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ + +using System; +using System.ComponentModel.Design; + +namespace VNLib.Plugins.Essentials.ServiceStack.Plugins +{ + /// <summary> + /// Represents a plugin that may be added to a service stack in user-code + /// instead of the conventional runtime plugin loading system + /// </summary> + public interface IManualPlugin : IDisposable + { + /// <summary> + /// The name of the plugin + /// </summary> + string Name { get; } + + /// <summary> + /// Collects all exported services for use within the service stack + /// </summary> + /// <param name="container">The container to add services to</param> + void GetAllExportedServices(IServiceContainer container); + + /// <summary> + /// Initializes the plugin, called before accessing any other methods + /// </summary> + void Initialize(); + + /// <summary> + /// Loads the plugin, called after initialization but before getting + /// endpoints or services to allow for the plugin to configure itself + /// and perform initial setup + /// </summary> + void Load(); + + /// <summary> + /// Called when an unload was requested, either manually by the plugin controller + /// or when the service stack is unloading + /// </summary> + void Unload(); + + /// <summary> + /// Passes a console command to the plugin + /// </summary> + /// <param name="command">The raw command text to pass to the plugin from the console</param> + void OnConsoleCommand(string command); + } +} diff --git a/lib/Plugins.Essentials.ServiceStack/src/Plugins/IPluginInitializer.cs b/lib/Plugins.Essentials.ServiceStack/src/Plugins/IPluginInitializer.cs new file mode 100644 index 0000000..9435d9b --- /dev/null +++ b/lib/Plugins.Essentials.ServiceStack/src/Plugins/IPluginInitializer.cs @@ -0,0 +1,40 @@ +/* +* Copyright (c) 2024 Vaughn Nugent +* +* Library: VNLib +* Package: VNLib.Plugins.Essentials.ServiceStack +* File: IPluginInitializer.cs +* +* IPluginInitializer.cs is part of VNLib.Plugins.Essentials.ServiceStack which +* is part of the larger VNLib collection of libraries and utilities. +* +* VNLib.Plugins.Essentials.ServiceStack is free software: you can redistribute it and/or modify +* it under the terms of the GNU Affero General Public License as +* published by the Free Software Foundation, either version 2 of the +* License, or (at your option) any later version. +* +* VNLib.Plugins.Essentials.ServiceStack is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU Affero General Public License for more details. +* +* You should have received a copy of the GNU Affero General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ + + +using VNLib.Utils.Logging; + +namespace VNLib.Plugins.Essentials.ServiceStack.Plugins +{ + internal interface IPluginInitializer + { + IManagedPlugin[] InitializePluginStack(ILogProvider eventLogger); + + void UnloadPlugins(); + + void ReloadPlugins(); + + void Dispose(); + } +} diff --git a/lib/Plugins.Essentials.ServiceStack/src/Plugins/PluginExtensions.cs b/lib/Plugins.Essentials.ServiceStack/src/Plugins/PluginExtensions.cs new file mode 100644 index 0000000..4d04c54 --- /dev/null +++ b/lib/Plugins.Essentials.ServiceStack/src/Plugins/PluginExtensions.cs @@ -0,0 +1,57 @@ +/* +* Copyright (c) 2024 Vaughn Nugent +* +* Library: VNLib +* Package: VNLib.Plugins.Essentials.ServiceStack +* File: PluginExtensions.cs +* +* PluginExtensions.cs is part of VNLib.Plugins.Essentials.ServiceStack which is part of the larger +* VNLib collection of libraries and utilities. +* +* VNLib.Plugins.Essentials.ServiceStack is free software: you can redistribute it and/or modify +* it under the terms of the GNU Affero General Public License as +* published by the Free Software Foundation, either version 2 of the +* License, or (at your option) any later version. +* +* VNLib.Plugins.Essentials.ServiceStack is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU Affero General Public License for more details. +* +* You should have received a copy of the GNU Affero General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ + +using System.Linq; +using System.Collections.Generic; + +using VNLib.Plugins.Essentials.Runtime; + +namespace VNLib.Plugins.Essentials.ServiceStack.Plugins +{ + /// <summary> + /// Internal and service stack specific extensions for plugins + /// </summary> + public static class PluginExtensions + { + /// <summary> + /// Gets the endpoints exposed by the plugin + /// </summary> + /// <param name="plugin"></param> + /// <returns>The enumeration of web endpoints</returns> + internal static IEnumerable<IEndpoint> GetEndpoints(this IManagedPlugin plugin) + { + //Try to get the endpoint defintion + if (plugin.Services.GetService(typeof(IVirtualEndpointDefinition)) is IVirtualEndpointDefinition defintion) + { + //Return the endpoints from the definition + return defintion.GetEndpoints(); + } + + //If the plugin does not have an endpoint definition, return an empty enumeration + return Enumerable.Empty<IEndpoint>(); + } + + internal static PluginRutimeEventHandler GetListener(this ServiceDomain domain) => new(domain); + } +} diff --git a/lib/Plugins.Essentials.ServiceStack/src/Plugins/PluginManager.cs b/lib/Plugins.Essentials.ServiceStack/src/Plugins/PluginManager.cs new file mode 100644 index 0000000..ce80a9e --- /dev/null +++ b/lib/Plugins.Essentials.ServiceStack/src/Plugins/PluginManager.cs @@ -0,0 +1,118 @@ +/* +* Copyright (c) 2024 Vaughn Nugent +* +* Library: VNLib +* Package: VNLib.Plugins.Essentials.ServiceStack +* File: PluginManager.cs +* +* PluginManager.cs is part of VNLib.Plugins.Essentials.ServiceStack which +* is part of the larger VNLib collection of libraries and utilities. +* +* VNLib.Plugins.Essentials.ServiceStack is free software: you can redistribute it and/or modify +* it under the terms of the GNU Affero General Public License as +* published by the Free Software Foundation, either version 2 of the +* License, or (at your option) any later version. +* +* VNLib.Plugins.Essentials.ServiceStack is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU Affero General Public License for more details. +* +* You should have received a copy of the GNU Affero General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ + + +using System; +using System.Collections.Generic; + +using VNLib.Utils; +using VNLib.Utils.Logging; + +namespace VNLib.Plugins.Essentials.ServiceStack.Plugins +{ + + /// <summary> + /// A sealed type that manages the plugin interaction layer. Manages the lifetime of plugin + /// instances, exposes controls, and relays stateful plugin events. + /// </summary> + internal sealed class PluginManager(IPluginInitializer stack) : VnDisposeable, IHttpPluginManager + { + + /// <summary> + /// The collection of internal controllers + /// </summary> + public IEnumerable<IManagedPlugin> Plugins => _loadedPlugins; + + private IManagedPlugin[] _loadedPlugins = []; + + /// <summary> + /// Configures the manager to capture and manage plugins within a plugin stack + /// </summary> + /// <param name="debugLog"></param> + /// <exception cref="InvalidOperationException"></exception> + /// <exception cref="AggregateException"></exception> + public void LoadPlugins(ILogProvider debugLog) + { + _ = stack ?? throw new InvalidOperationException("Plugin stack has not been set."); + + Check(); + + //Initialize the plugin stack and store the loaded plugins + _loadedPlugins = stack.InitializePluginStack(debugLog); + + debugLog.Information("Plugin loading completed"); + } + + + /// <inheritdoc/> + public bool SendCommandToPlugin(string pluginName, string message, StringComparison nameComparison = StringComparison.Ordinal) + { + Check(); + + foreach (IManagedPlugin plugin in _loadedPlugins) + { + if (plugin.SendCommandToPlugin(pluginName, message, nameComparison)) + { + return true; + } + } + + return false; + } + + /// <inheritdoc/> + public void ForceReloadAllPlugins() + { + Check(); + + //Reload all plugins, causing an event cascade + stack.ReloadPlugins(); + } + + /// <inheritdoc/> + public void UnloadPlugins() + { + Check(); + + //Unload all plugin controllers + stack.UnloadPlugins(); + + /* + * All plugin instances must be destroyed because the + * only way they will be loaded is from their files + * again, so they must be released + */ + Free(); + } + + protected override void Free() + { + //Clear plugin table + _loadedPlugins = []; + + //Dispose the plugin stack + stack.Dispose(); + } + } +} diff --git a/lib/Plugins.Essentials.ServiceStack/src/Plugins/PluginRutimeEventHandler.cs b/lib/Plugins.Essentials.ServiceStack/src/Plugins/PluginRutimeEventHandler.cs new file mode 100644 index 0000000..c5b094f --- /dev/null +++ b/lib/Plugins.Essentials.ServiceStack/src/Plugins/PluginRutimeEventHandler.cs @@ -0,0 +1,80 @@ +/* +* Copyright (c) 2024 Vaughn Nugent +* +* Library: VNLib +* Package: VNLib.Plugins.Essentials.ServiceStack +* File: PluginRutimeEventHandler.cs +* +* PluginRutimeEventHandler.cs is part of VNLib.Plugins.Essentials.ServiceStack which +* is part of the larger VNLib collection of libraries and utilities. +* +* VNLib.Plugins.Essentials.ServiceStack is free software: you can redistribute it and/or modify +* it under the terms of the GNU Affero General Public License as +* published by the Free Software Foundation, either version 2 of the +* License, or (at your option) any later version. +* +* VNLib.Plugins.Essentials.ServiceStack is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU Affero General Public License for more details. +* +* You should have received a copy of the GNU Affero General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ + + +using System.Linq; + +using VNLib.Utils.Extensions; +using VNLib.Plugins.Runtime; + +namespace VNLib.Plugins.Essentials.ServiceStack.Plugins +{ + internal sealed class PluginRutimeEventHandler(ServiceDomain Domain) : IPluginEventListener + { + ///<inheritdoc/> + void IPluginEventListener.OnPluginLoaded(PluginController controller, object? state) => OnPluginLoaded((state as IManagedPlugin)!); + + ///<inheritdoc/> + void IPluginEventListener.OnPluginUnloaded(PluginController controller, object? state) => OnPluginUnloaded((state as IManagedPlugin)!); + + /// <summary> + /// Called when a plugin has been successfully loaded and + /// should be put into service + /// </summary> + /// <param name="plugin">The plugin that was loaded</param> + internal void OnPluginLoaded(IManagedPlugin plugin) + { + //Run onload method before invoking other handlers + plugin.OnPluginLoaded(); + + //Get event listeners at event time because deps may be modified by the domain + ServiceGroup[] deps = Domain.ServiceGroups.Select(static d => d).ToArray(); + + //run onload method + deps.TryForeach(d => d.OnPluginLoaded(plugin)); + } + + /// <summary> + /// Called when a plugin is about to be unloaded and should + /// be removed from service. + /// </summary> + /// <param name="plugin">The plugin instance to unload</param> + internal void OnPluginUnloaded(IManagedPlugin plugin) + { + try + { + //Get event listeners at event time because deps may be modified by the domain + ServiceGroup[] deps = Domain.ServiceGroups.Select(static d => d).ToArray(); + + //Run unloaded method + deps.TryForeach(d => d.OnPluginUnloaded(plugin)); + } + finally + { + //always unload the plugin wrapper + plugin.OnPluginUnloaded(); + } + } + } +} diff --git a/lib/Plugins.Essentials.ServiceStack/src/Plugins/PluginStackInitializer.cs b/lib/Plugins.Essentials.ServiceStack/src/Plugins/PluginStackInitializer.cs new file mode 100644 index 0000000..fb685f7 --- /dev/null +++ b/lib/Plugins.Essentials.ServiceStack/src/Plugins/PluginStackInitializer.cs @@ -0,0 +1,327 @@ +/* +* Copyright (c) 2024 Vaughn Nugent +* +* Library: VNLib +* Package: VNLib.Plugins.Essentials.ServiceStack +* File: PluginStackInitializer.cs +* +* PluginStackInitializer.cs is part of VNLib.Plugins.Essentials.ServiceStack which +* is part of the larger VNLib collection of libraries and utilities. +* +* VNLib.Plugins.Essentials.ServiceStack is free software: you can redistribute it and/or modify +* it under the terms of the GNU Affero General Public License as +* published by the Free Software Foundation, either version 2 of the +* License, or (at your option) any later version. +* +* VNLib.Plugins.Essentials.ServiceStack is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU Affero General Public License for more details. +* +* You should have received a copy of the GNU Affero General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ + + +using System; +using System.IO; +using System.Linq; +using System.Diagnostics; +using System.Threading.Tasks; +using System.Collections.Generic; +using System.ComponentModel.Design; + +using VNLib.Utils.Logging; +using VNLib.Plugins.Runtime; +using VNLib.Utils.Extensions; +using VNLib.Plugins.Runtime.Services; + +namespace VNLib.Plugins.Essentials.ServiceStack.Plugins +{ + + internal sealed class PluginStackInitializer(PluginRutimeEventHandler Listener, IPluginStack Stack, IManualPlugin[] ManualPlugins, bool ConcurrentLoad) + : IPluginInitializer + { + private readonly LinkedList<IManagedPlugin> _managedPlugins = new(); + private readonly LinkedList<ManualPluginWrapper> _manualPlugins = new(); + + private void PrepareStack() + { + /* + * Since we own the plugin stack, it is safe to build it here. + * This method is not public and should not be called more than + * once. Otherwise it can cause issues with the plugin stack. + */ + Stack.BuildStack(); + + //Create plugin wrappers from loaded plugins + ManagedPlugin[] wrapper = Stack.Plugins.Select(static p => new ManagedPlugin(p)).ToArray(); + + //Add wrappers to list of managed plugins + Array.ForEach(wrapper, p => _managedPlugins.AddLast(p)); + + //Register for all plugins and pass the plugin instance as the state object + Array.ForEach(wrapper, p => p.Plugin.Controller.Register(Listener, p)); + + //Add manual plugins to list of managed plugins + Array.ForEach(ManualPlugins, p => _manualPlugins.AddLast(new ManualPluginWrapper(Listener, p))); + } + + ///<inheritdoc/> + public IManagedPlugin[] InitializePluginStack(ILogProvider debugLog) + { + //Prepare the plugin stack before initializing + PrepareStack(); + + //single thread initialziation + LinkedList<IManagedPlugin> _loadedPlugins = new(); + + //Combine all managed plugins and initialize them individually + IEnumerable<IManagedPlugin> plugins = _managedPlugins.Union(_manualPlugins); + + foreach (IManagedPlugin p in plugins) + { + //Try init plugin and add it to the list of loaded plugins + if (InitializePluginCore(p, debugLog)) + { + _loadedPlugins.AddLast(p); + } + } + + /* + * Load stage, load only initialized plugins. + * + * Optionally single-threaded or parallel + */ + + if (ConcurrentLoad) + { + Parallel.ForEach(_loadedPlugins, wp => LoadPlugin(wp, debugLog)); + } + else + { + _loadedPlugins.TryForeach(_loadedPlugins => LoadPlugin(_loadedPlugins, debugLog)); + } + + return [.. _loadedPlugins]; + } + + ///<inheritdoc/> + public void UnloadPlugins() + { + Stack.UnloadAll(); + + //Unload manual plugins in listener + _manualPlugins.TryForeach(static mp => mp.Unload()); + } + + ///<inheritdoc/> + public void ReloadPlugins() + { + Stack.ReloadAll(); + + //Unload manual plugins in listener + _manualPlugins.TryForeach(static mp => mp.Unload()); + + //Load, then invoke on-loaded events + _manualPlugins.TryForeach(static mp => mp.Load()); + } + + ///<inheritdoc/> + public void Dispose() + { + Stack.Dispose(); + _manualPlugins.TryForeach(static mp => mp.Dispose()); + _manualPlugins.Clear(); + } + + private static bool InitializePluginCore(IManagedPlugin plugin, ILogProvider debugLog) + { + try + { + if (plugin is ManagedPlugin mp) + { + //Initialzie plugin wrapper + mp.Plugin.InitializeController(); + + /* + * If the plugin assembly does not expose any plugin types or there is an issue loading the assembly, + * its types my not unify, then we should give the user feedback insead of a silent fail. + */ + if (!mp.Plugin.Controller.Plugins.Any()) + { + debugLog.Warn("No plugin instances were exposed via {asm} assembly. This may be due to an assebmly mismatch", plugin.ToString()); + } + } + else if (plugin is ManualPluginWrapper mpw) + { + //Initialzie plugin wrapper + mpw.Plugin.Initialize(); + } + else + { + Debug.Fail("Missed managed plugin wrapper type"); + } + + return true; + } + catch (Exception ex) + { + debugLog.Error("Exception raised during initialzation of {asm}. It has been removed from the collection\n{ex}", plugin.ToString(), ex); + } + + return false; + } + + private void LoadPlugin(IManagedPlugin plugin, ILogProvider debugLog) + { + Stopwatch sw = new(); + try + { + sw.Start(); + + //Recover the base class used to load instances + if (plugin is ManagedPlugin mp) + { + mp.Plugin.LoadPlugins(); + } + else if (plugin is ManualPluginWrapper mpw) + { + mpw.Load(); + } + else + { + Debug.Fail("Missed managed plugin wrapper type"); + } + + sw.Stop(); + + debugLog.Verbose("Loaded {pl} in {tm} ms", plugin.ToString(), sw.ElapsedMilliseconds); + } + catch (Exception ex) + { + debugLog.Error("Exception raised during loading {asf}. Failed to load plugin \n{ex}", plugin.ToString(), ex); + } + finally + { + sw.Stop(); + } + } + + + private sealed record class ManagedPlugin(RuntimePluginLoader Plugin) : IManagedPlugin + { + private ServiceContainer? _services; + + ///<inheritdoc/> + public IServiceContainer Services => _services ?? throw new InvalidOperationException("The service container is not currently loaded"); + + /* + * Automatically called after the plugin has successfully loaded + * by event handlers below + */ + + ///<inheritdoc/> + void IManagedPlugin.OnPluginLoaded() + { + //If the service container is defined, dispose + _services?.Dispose(); + + //Init new service container + _services = new(); + + //Get all exported services and add them to the container + PluginServiceExport[] exports = Plugin.Controller.GetExportedServices(); + Array.ForEach(exports, e => _services.AddService(e.ServiceType, e.Service, true)); + } + + ///<inheritdoc/> + void IManagedPlugin.OnPluginUnloaded() + { + //Cleanup services no longer in use. Plugin is still valid until this method returns + _services?.Dispose(); + + //Remove ref to services + _services = null; + } + + ///<inheritdoc/> + bool IManagedPlugin.SendCommandToPlugin(string pluginName, string command, StringComparison comp) + { + //Get plugin + LivePlugin? plugin = Plugin.Controller.Plugins.FirstOrDefault(p => p.PluginName.Equals(pluginName, comp)); + + //If plugin is null, return false + if (plugin == null) + { + return false; + } + + return plugin.SendConsoleMessage(command); + } + + public override string ToString() => Path.GetFileName(Plugin.Config.AssemblyFile); + } + + private sealed record class ManualPluginWrapper(PluginRutimeEventHandler Listener, IManualPlugin Plugin) : IManagedPlugin, IDisposable + { + private ServiceContainer _container = new(); + + ///<inheritdoc/> + public IServiceContainer Services => _container; + + public void Load() + { + Plugin.Load(); + Plugin.GetAllExportedServices(_container); + + //Finally notify of load + Listener.OnPluginLoaded(this); + } + + public void Unload() + { + //Notify of unload + Listener.OnPluginUnloaded(this); + + Plugin.Unload(); + + //Unload and re-init container + _container.Dispose(); + _container = new(); + } + + public void Dispose() + { + //Dispose container + _container.Dispose(); + + //Dispose plugin + Plugin.Dispose(); + } + + ///<inheritdoc/> + bool IManagedPlugin.SendCommandToPlugin(string pluginName, string command, StringComparison comp) + { + + if (Plugin.Name.Equals(pluginName, comp)) + { + Plugin.OnConsoleCommand(command); + return true; + } + + return false; + } + + void IManagedPlugin.OnPluginLoaded() + { } + + void IManagedPlugin.OnPluginUnloaded() + { } + + ///<inheritdoc/> + public override string ToString() => Plugin.Name; + } + + } +} |