Persists and surfaces plugin load failures

This commit is contained in:
BinaryAlley committed 2026-08-23 05:28:50 -07:00
1 parent 18361d5da7
commit b32cc764a7
11 files changed
+279 -13

No files matched your search

@@ -15,7 +15,8 @@ namespace Lumina.Application.Common.DataAccess.Repositories.Plugins;
/// </summary>
public interface IPluginRepository : IRepository<PluginEntity>,
IGetByIdRepositoryAction<PluginEntity, Guid>,
IGetAllRepositoryAction<PluginEntity>
IGetAllRepositoryAction<PluginEntity>,
IDeleteByIdRepositoryAction<Guid>
{
/// <summary>
/// Inserts the provided <paramref name="plugin"/> into the storage medium, or updates it when it already exists.
@@ -77,6 +77,22 @@ internal sealed class PluginRepository : IPluginRepository
return Result.Updated;
}
/// <summary>
/// Deletes a plugin identified by <paramref name="id"/> from the storage medium.
/// </summary>
/// <param name="id">The id of the plugin to be deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> DeleteByIdAsync(Guid id, CancellationToken cancellationToken)
{
PluginEntity? plugin = await _luminaDbContext.Plugins
.FirstOrDefaultAsync(repositoryPlugin => repositoryPlugin.Id == id, cancellationToken).ConfigureAwait(false);
if (plugin is null)
return Errors.Plugins.PluginNotFound;
_luminaDbContext.Plugins.Remove(plugin);
return Result.Deleted;
}
/// <summary>
/// Updates the settings of the plugin identified by <paramref name="pluginId"/>.
/// </summary>
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Infrastructure.Common.Models.DTO.Plugins;
/// <summary>
/// Data transfer object for the error that occurred while loading a plugin assembly.
/// </summary>
/// <param name="AssemblyName">The file name of the plugin assembly that failed to load, without its extension.</param>
/// <param name="ErrorMessage">The error message describing the load failure.</param>
[DebuggerDisplay("AssemblyName: {AssemblyName}")]
internal sealed record PluginLoadErrorDto(
string AssemblyName,
string ErrorMessage
);
@@ -10,4 +10,7 @@ namespace Lumina.Infrastructure.Common.Models.DTO.Plugins;
/// </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 PluginLoadResultDto(IReadOnlyList<IPlugin> Plugins, IReadOnlyList<string> Errors);
internal sealed record PluginLoadResultDto(
IReadOnlyList<IPlugin> Plugins,
IReadOnlyList<PluginLoadErrorDto> Errors
);
@@ -5,12 +5,16 @@ 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.Infrastructure.Common.Models.DTO.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.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -24,7 +28,7 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
{
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly IPluginManager _pluginManager;
private readonly IReadOnlyList<string> _loadErrors;
private readonly IReadOnlyList<PluginLoadErrorDto> _loadErrors;
private readonly ILogger<PluginDetectionSyncJob> _logger;
/// <summary>
@@ -34,7 +38,7 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
/// <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)
public PluginDetectionSyncJob(IServiceScopeFactory serviceScopeFactory, IPluginManager pluginManager, IReadOnlyList<PluginLoadErrorDto> loadErrors, ILogger<PluginDetectionSyncJob> logger)
{
_serviceScopeFactory = serviceScopeFactory;
_pluginManager = pluginManager;
@@ -49,14 +53,18 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
/// <returns>A <see cref="Task"/> that represents the long running operations.</returns>
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
foreach (string loadError in _loadErrors)
_logger.LogWarning("Plugin load failure: {LoadError}", loadError);
foreach (PluginLoadErrorDto loadError in _loadErrors)
_logger.LogWarning("Plugin load failure: {LoadError}", loadError.ErrorMessage);
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetRequiredService<IUnitOfWork>();
// the Ids of the plugin rows that are currently detected, either loaded successfully or failed to load
HashSet<Guid> detectedPluginIds = [];
foreach (IPlugin plugin in _pluginManager.GetPlugins())
{
detectedPluginIds.Add(plugin.Id);
PluginEntity pluginEntity = new()
{
Id = plugin.Id,
@@ -74,6 +82,58 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
_logger.LogError("Failed to persist the detection of plugin '{PluginName}': {Error}", plugin.Name, upsertResult.FirstError.Description);
}
foreach (PluginLoadErrorDto loadError in _loadErrors)
{
// a failing plugin cannot report its own Id, so it is identified by a stable Id derived from its assembly file name,
// which keeps the same row across restarts and avoids creating a new row every time the application starts
Guid failedPluginId = DerivePluginId(loadError.AssemblyName);
detectedPluginIds.Add(failedPluginId);
PluginEntity pluginEntity = new()
{
Id = failedPluginId,
Name = loadError.AssemblyName,
Author = string.Empty,
Version = string.Empty,
Description = string.Empty,
LoadStatus = PluginLoadStatus.FailedToLoad,
LoadError = loadError.ErrorMessage,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = default,
UpdatedBy = default
};
Result<Updated> upsertResult = await unitOfWork.PluginRepository.UpsertAsync(pluginEntity, stoppingToken).ConfigureAwait(false);
if (upsertResult.IsFailure)
_logger.LogError("Failed to persist the detection of plugin '{PluginName}': {Error}", loadError.AssemblyName, upsertResult.FirstError.Description);
}
// remove the rows of the plugins that are no longer detected, so that each plugin assembly has exactly one row regardless of its load status
Result<IEnumerable<PluginEntity>> getPluginsResult = await unitOfWork.PluginRepository.GetAllAsync(stoppingToken).ConfigureAwait(false);
if (getPluginsResult.IsFailure)
_logger.LogError("Failed to get the detected plugins while reconciling the plugin rows.");
else
{
foreach (PluginEntity plugin in getPluginsResult.Value)
{
if (detectedPluginIds.Contains(plugin.Id))
continue;
Result<Deleted> deleteResult = await unitOfWork.PluginRepository.DeleteByIdAsync(plugin.Id, stoppingToken).ConfigureAwait(false);
if (deleteResult.IsFailure)
_logger.LogError("Failed to remove the stale detection of plugin '{PluginName}': {Error}", plugin.Name, deleteResult.FirstError.Description);
}
}
await unitOfWork.SaveChangesAsync(stoppingToken).ConfigureAwait(false);
}
/// <summary>
/// Derives a stable unique identifier for a plugin from the file name of its assembly, so that a plugin that fails to load
/// is always identified by the same row across application restarts.
/// </summary>
/// <param name="assemblyName">The file name of the plugin assembly, without its extension.</param>
/// <returns>The derived plugin identifier.</returns>
private static Guid DerivePluginId(string assemblyName)
{
byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(assemblyName));
return new Guid([.. hash.Take(16)]);
}
}
@@ -24,7 +24,7 @@ internal static class PluginLoader
public static PluginLoadResultDto LoadPlugins(string pluginsDirectory, IServiceCollection services)
{
List<IPlugin> plugins = [];
List<string> errors = [];
List<PluginLoadErrorDto> errors = [];
if (!Directory.Exists(pluginsDirectory))
return new PluginLoadResultDto(plugins, errors);
@@ -50,7 +50,7 @@ internal static class PluginLoader
}
catch (Exception exception)
{
errors.Add($"Failed to load plugin assembly '{Path.GetFileName(assemblyPath)}': {exception.Message}");
errors.Add(new PluginLoadErrorDto(Path.GetFileNameWithoutExtension(assemblyPath), $"Failed to load plugin assembly '{Path.GetFileName(assemblyPath)}': {exception.Message}"));
}
}
@@ -17,4 +17,5 @@ using System.Runtime.InteropServices;
[assembly: Guid("EADA449A-48B9-4A97-97E8-73D23E9EC56A")]
[assembly: InternalsVisibleTo("Lumina.Infrastructure.UnitTests")]
[assembly: InternalsVisibleTo("Lumina.Infrastructure.Fixtures")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
@@ -383,7 +383,10 @@
<tr data-provider-plugin-id="${provider.pluginId}">
<td>${provider.name}</td>
<td class="text-center">
<input type="checkbox" class="metadata-provider-enabled" ${provider.isEnabled ? 'checked' : ''} />
<label class="enlightenment-checkbox-label">
<input type="checkbox" class="enlightenment-checkbox-hidden metadata-provider-enabled" ${provider.isEnabled ? 'checked' : ''} />
<span class="enlightenment-checkbox"></span>
</label>
</td>
<td class="text-center">
<button type="button" class="metadata-provider-move-up confirm-button f-12 h-20px" ${index === 0 ? 'disabled' : ''}>@_localizer["MoveUp"]</button>