Integrates the plugin system into the host and the media library scan pipeline

This commit is contained in:
BinaryAlley committed 2026-08-12 11:04:45 -07:00
1 parent f71e72a948
commit 6f501a51f3
45 files changed
+1268 -370

No files matched your search

@@ -0,0 +1,76 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
using Lumina.Plugins.Contracts.Core.Plugins;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.Plugins;
/// <summary>
/// Background job that persists the detection of the loaded plugins into the storage medium at startup.
/// </summary>
internal sealed class PluginDetectionSyncJob : BackgroundService
{
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly IPluginManager _pluginManager;
private readonly IReadOnlyList<string> _loadErrors;
private readonly ILogger<PluginDetectionSyncJob> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="PluginDetectionSyncJob"/> class.
/// </summary>
/// <param name="serviceScopeFactory">Injected factory for creating scopes in which services are requested.</param>
/// <param name="pluginManager">Injected manager of the plugins loaded by the host application.</param>
/// <param name="loadErrors">The errors that occurred while loading the plugins.</param>
/// <param name="logger">Injected logger used for logging.</param>
public PluginDetectionSyncJob(IServiceScopeFactory serviceScopeFactory, IPluginManager pluginManager, IReadOnlyList<string> loadErrors, ILogger<PluginDetectionSyncJob> logger)
{
_serviceScopeFactory = serviceScopeFactory;
_pluginManager = pluginManager;
_loadErrors = loadErrors;
_logger = logger;
}
/// <inheritdoc/>
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
foreach (string loadError in _loadErrors)
_logger.LogWarning("Plugin load failure: {LoadError}", loadError);
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetRequiredService<IUnitOfWork>();
IPluginRepository pluginRepository = unitOfWork.GetRepository<IPluginRepository>();
foreach (IPlugin plugin in _pluginManager.GetPlugins())
{
PluginEntity pluginEntity = new()
{
Id = plugin.Id,
Name = plugin.Name,
Author = plugin.Author,
Version = plugin.Version.ToString(),
Description = plugin.Description,
LoadStatus = PluginLoadStatus.Loaded,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = default,
UpdatedBy = default
};
ErrorOr<Updated> upsertResult = await pluginRepository.UpsertAsync(pluginEntity, stoppingToken).ConfigureAwait(false);
if (upsertResult.IsError)
_logger.LogError("Failed to persist the detection of plugin '{PluginName}': {Error}", plugin.Name, upsertResult.FirstError.Description);
}
await unitOfWork.SaveChangesAsync(stoppingToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using System.IO;
using System.Reflection;
using System.Runtime.Loader;
#endregion
namespace Lumina.Infrastructure.Core.Plugins;
/// <summary>
/// Assembly load context of a single plugin, resolving the shared host assemblies from the default context and the plugin local dependencies from the plugin directory.
/// </summary>
internal sealed class PluginLoadContext : AssemblyLoadContext
{
private readonly string _pluginDirectory;
/// <summary>
/// Initializes a new instance of the <see cref="PluginLoadContext"/> class.
/// </summary>
/// <param name="pluginDirectory">The directory where the plugin assemblies and their dependencies are located.</param>
/// <param name="name">The name of the load context.</param>
public PluginLoadContext(string pluginDirectory, string name) : base(name, isCollectible: true)
{
_pluginDirectory = pluginDirectory;
}
/// <inheritdoc/>
protected override Assembly? Load(AssemblyName assemblyName)
{
if (assemblyName.Name is null)
return null;
// try to resolve the assembly from the default context first, so that the plugin shares the host and framework assemblies
try
{
return AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyName);
}
catch (FileNotFoundException)
{
}
// fall back to resolving the assembly from the plugin directory
string dependencyPath = Path.Combine(_pluginDirectory, assemblyName.Name + ".dll");
if (File.Exists(dependencyPath))
return LoadFromAssemblyPath(dependencyPath);
return null;
}
}
@@ -0,0 +1,65 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Core.Plugins;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
#endregion
namespace Lumina.Infrastructure.Core.Plugins;
/// <summary>
/// Result of loading the plugins from the plugins directory.
/// </summary>
/// <param name="Plugins">The plugins that were loaded successfully.</param>
/// <param name="Errors">The errors that occurred while loading the plugins.</param>
internal sealed record PluginLoadResult(IReadOnlyList<IPlugin> Plugins, IReadOnlyList<string> Errors);
/// <summary>
/// Loads the plugins from the plugins directory, discovers their descriptors and registers their services.
/// </summary>
internal static class PluginLoader
{
/// <summary>
/// Loads the plugins from the <paramref name="pluginsDirectory"/>, discovers their descriptors and registers their services.
/// </summary>
/// <param name="pluginsDirectory">The directory where the plugin assemblies are located.</param>
/// <param name="services">The service collection to which the plugin services are added.</param>
/// <returns>The result of loading the plugins.</returns>
public static PluginLoadResult LoadPlugins(string pluginsDirectory, IServiceCollection services)
{
List<IPlugin> plugins = [];
List<string> errors = [];
if (!Directory.Exists(pluginsDirectory))
return new PluginLoadResult(plugins, errors);
foreach (string assemblyPath in Directory.EnumerateFiles(pluginsDirectory, "*.dll"))
{
// a failing plugin must not prevent the other plugins from loading, so each assembly is isolated in its own load context
PluginLoadContext loadContext = new(pluginsDirectory, Path.GetFileNameWithoutExtension(assemblyPath));
try
{
Assembly assembly = loadContext.LoadFromAssemblyPath(assemblyPath);
foreach (Type type in assembly.GetTypes())
{
if (type.IsClass && !type.IsAbstract && typeof(IPlugin).IsAssignableFrom(type))
{
IPlugin plugin = (IPlugin)Activator.CreateInstance(type)!;
if (plugin is IPluginServiceRegistrator serviceRegistrator)
serviceRegistrator.RegisterServices(services);
plugins.Add(plugin);
break; // only one plugin descriptor per assembly
}
}
}
catch (Exception exception)
{
errors.Add($"Failed to load plugin assembly '{Path.GetFileName(assemblyPath)}': {exception.Message}");
}
}
return new PluginLoadResult(plugins, errors);
}
}
@@ -0,0 +1,38 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Plugins.Contracts.Core.Plugins;
using System;
using System.Collections.Generic;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.Core.Plugins;
/// <summary>
/// Manager of the plugins loaded by the host application.
/// </summary>
internal sealed class PluginManager : IPluginManager
{
private readonly IReadOnlyDictionary<Guid, IPlugin> _pluginsById;
/// <summary>
/// Initializes a new instance of the <see cref="PluginManager"/> class.
/// </summary>
/// <param name="plugins">The plugins that were loaded successfully.</param>
public PluginManager(IEnumerable<IPlugin> plugins)
{
_pluginsById = plugins.ToDictionary(plugin => plugin.Id);
}
/// <inheritdoc/>
public IReadOnlyList<IPlugin> GetPlugins()
{
return [.. _pluginsById.Values];
}
/// <inheritdoc/>
public IPlugin? GetPlugin(Guid pluginId)
{
return _pluginsById.GetValueOrDefault(pluginId);
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Plugins.Contracts.Core.Plugins;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.Plugins;
/// <summary>
/// Reads the settings persisted by the host for a plugin.
/// </summary>
internal sealed class PluginSettingsStore : IPluginSettingsStore
{
private readonly IUnitOfWork _unitOfWork;
private readonly ILogger<PluginSettingsStore> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="PluginSettingsStore"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="logger">Injected logger used to report the failures to read the plugin settings.</param>
public PluginSettingsStore(IUnitOfWork unitOfWork, ILogger<PluginSettingsStore> logger)
{
_unitOfWork = unitOfWork;
_logger = logger;
}
/// <inheritdoc/>
public async Task<IReadOnlyDictionary<string, string>?> GetSettingsAsync(Guid pluginId, CancellationToken cancellationToken)
{
IPluginRepository pluginRepository = _unitOfWork.GetRepository<IPluginRepository>();
ErrorOr<PluginEntity?> getPluginResult = await pluginRepository.GetByIdAsync(pluginId, cancellationToken).ConfigureAwait(false);
if (getPluginResult.IsError)
{
_logger.LogWarning("Failed to read the settings of the plugin with Id '{PluginId}': {Error}", pluginId, getPluginResult.FirstError.Description);
return null;
}
return getPluginResult.Value?.ToSettings();
}
}