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>
@@ -0,0 +1,41 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Infrastructure.Common.Models.DTO.Plugins;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.Fixtures.Common.Models.DTO.Plugins;
/// <summary>
/// Fixture class for the <see cref="PluginLoadErrorDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
internal class PluginLoadErrorDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a valid <see cref="PluginLoadErrorDto"/>.
/// </summary>
/// <param name="assemblyName">Optional. The file name of the plugin assembly that failed to load, without its extension.</param>
/// <param name="errorMessage">Optional. The error message describing the load failure.</param>
/// <returns>The created <see cref="PluginLoadErrorDto"/>.</returns>
public PluginLoadErrorDto Create(string? assemblyName = null, string? errorMessage = null)
{
return new PluginLoadErrorDto(
assemblyName ?? _faker.Hacker.Noun(),
errorMessage ?? $"Failed to load plugin assembly '{_faker.Hacker.Noun()}.dll': {_faker.Lorem.Sentence()}");
}
/// <summary>
/// Creates a list of <see cref="PluginLoadErrorDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PluginLoadErrorDto"/> instances.</returns>
public List<PluginLoadErrorDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -5,6 +5,8 @@ using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
using Lumina.Infrastructure.Common.Models.DTO.Plugins;
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Plugins;
using Lumina.Infrastructure.Core.Plugins;
using Lumina.Plugins.Contracts.Core.Plugins;
using Microsoft.Extensions.DependencyInjection;
@@ -14,7 +16,10 @@ using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -34,6 +39,7 @@ public class PluginDetectionSyncJobTests
private readonly IPluginRepository _mockPluginRepository;
private readonly IPluginManager _mockPluginManager;
private readonly ILogger<PluginDetectionSyncJob> _mockLogger;
private readonly PluginLoadErrorDtoFixture _pluginLoadErrorDtoFixture;
/// <summary>
/// Initializes a new instance of the <see cref="PluginDetectionSyncJobTests"/> class.
@@ -53,6 +59,7 @@ public class PluginDetectionSyncJobTests
_mockPluginManager = Substitute.For<IPluginManager>();
_mockLogger = Substitute.For<ILogger<PluginDetectionSyncJob>>();
_pluginLoadErrorDtoFixture = new PluginLoadErrorDtoFixture();
}
[Fact]
@@ -126,6 +133,88 @@ public class PluginDetectionSyncJobTests
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenPluginFailsToLoad_ShouldPersistFailedPluginWithError()
{
// Arrange
_mockPluginManager.GetPlugins().Returns([]);
_mockPluginRepository.UpsertAsync(Arg.Any<PluginEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
PluginLoadErrorDto loadError = _pluginLoadErrorDtoFixture.Create(
assemblyName: "BrokenPlugin",
errorMessage: "Failed to load plugin assembly 'BrokenPlugin.dll': bad image");
PluginDetectionSyncJob sut = CreateSut([loadError]);
// Act
await StartAndWaitForExecutionAsync(sut);
// Assert
await _mockPluginRepository.Received(1).UpsertAsync(
Arg.Is<PluginEntity>(plugin => plugin.Id == DeriveExpectedId(loadError.AssemblyName)
&& plugin.Name == loadError.AssemblyName
&& plugin.LoadStatus == PluginLoadStatus.FailedToLoad
&& plugin.LoadError == loadError.ErrorMessage),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenPreviouslyDetectedPluginIsNoLongerPresent_ShouldRemoveItsRow()
{
// Arrange
IPlugin loadedPlugin = CreatePlugin(Guid.NewGuid(), "Loaded Plugin", new Version(1, 0, 0));
_mockPluginManager.GetPlugins().Returns([loadedPlugin]);
_mockPluginRepository.UpsertAsync(Arg.Any<PluginEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
PluginEntity loadedPluginRow = CreatePluginEntity(loadedPlugin.Id, loadedPlugin.Name, PluginLoadStatus.Loaded);
PluginEntity stalePluginRow = CreatePluginEntity(Guid.NewGuid(), "Stale Plugin", PluginLoadStatus.Loaded);
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From((IEnumerable<PluginEntity>)[loadedPluginRow, stalePluginRow]));
_mockPluginRepository.DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
PluginDetectionSyncJob sut = CreateSut();
// Act
await StartAndWaitForExecutionAsync(sut);
// Assert
await _mockPluginRepository.Received(1).DeleteByIdAsync(stalePluginRow.Id, Arg.Any<CancellationToken>());
await _mockPluginRepository.DidNotReceive().DeleteByIdAsync(loadedPluginRow.Id, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenPreviouslyLoadedPluginNowFailsToLoad_ShouldReplaceItWithASingleFailedRow()
{
// Arrange
IPlugin previouslyLoadedPlugin = CreatePlugin(Guid.NewGuid(), "My Plugin", new Version(1, 0, 0));
_mockPluginManager.GetPlugins().Returns([]); // the plugin assembly now fails to load
_mockPluginRepository.UpsertAsync(Arg.Any<PluginEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
PluginLoadErrorDto loadError = _pluginLoadErrorDtoFixture.Create(
assemblyName: "MyPlugin",
errorMessage: "Failed to load plugin assembly 'MyPlugin.dll': unexpected error");
PluginEntity staleLoadedRow = CreatePluginEntity(previouslyLoadedPlugin.Id, previouslyLoadedPlugin.Name, PluginLoadStatus.Loaded);
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From((IEnumerable<PluginEntity>)[staleLoadedRow]));
_mockPluginRepository.DeleteByIdAsync(previouslyLoadedPlugin.Id, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
PluginDetectionSyncJob sut = CreateSut([loadError]);
// Act
await StartAndWaitForExecutionAsync(sut);
// Assert
await _mockPluginRepository.Received(1).UpsertAsync(
Arg.Is<PluginEntity>(plugin => plugin.Id == DeriveExpectedId(loadError.AssemblyName)
&& plugin.Name == loadError.AssemblyName
&& plugin.LoadStatus == PluginLoadStatus.FailedToLoad
&& plugin.LoadError == loadError.ErrorMessage),
Arg.Any<CancellationToken>());
await _mockPluginRepository.Received(1).DeleteByIdAsync(previouslyLoadedPlugin.Id, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
/// <summary>
/// Invokes the protected <see cref="BackgroundService.ExecuteAsync"/> of the job and awaits its completion.
/// </summary>
@@ -140,10 +229,11 @@ public class PluginDetectionSyncJobTests
/// <summary>
/// Creates the system under test wired to the mocked dependencies.
/// </summary>
/// <param name="loadErrors">The plugin load errors to feed to the job, when any.</param>
/// <returns>The created job instance.</returns>
private PluginDetectionSyncJob CreateSut()
private PluginDetectionSyncJob CreateSut(IReadOnlyList<PluginLoadErrorDto>? loadErrors = null)
{
return new PluginDetectionSyncJob(_mockServiceScopeFactory, _mockPluginManager, [], _mockLogger);
return new PluginDetectionSyncJob(_mockServiceScopeFactory, _mockPluginManager, loadErrors ?? [], _mockLogger);
}
/// <summary>
@@ -163,4 +253,38 @@ public class PluginDetectionSyncJobTests
plugin.Description.Returns("Test plugin description");
return plugin;
}
/// <summary>
/// Creates a stored plugin row with the provided identity.
/// </summary>
/// <param name="id">The Id of the plugin row.</param>
/// <param name="name">The name of the plugin row.</param>
/// <param name="loadStatus">The load status of the plugin row.</param>
/// <returns>The created plugin entity.</returns>
private static PluginEntity CreatePluginEntity(Guid id, string name, PluginLoadStatus loadStatus)
{
return new PluginEntity
{
Id = id,
Name = name,
Author = "Test Author",
Version = "1.0.0",
Description = "Test plugin description",
LoadStatus = loadStatus,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.NewGuid(),
UpdatedBy = default
};
}
/// <summary>
/// Derives the stable plugin Id expected for a failing plugin assembly, mirroring the detection job logic.
/// </summary>
/// <param name="assemblyName">The file name of the plugin assembly, without its extension.</param>
/// <returns>The derived plugin identifier.</returns>
private static Guid DeriveExpectedId(string assemblyName)
{
byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(assemblyName));
return new Guid(hash.Take(16).ToArray());
}
}
@@ -45,8 +45,9 @@ public class PluginLoaderTests
// Assert
Assert.Empty(result.Plugins);
string error = Assert.Single(result.Errors);
Assert.Contains("invalid.dll", error);
PluginLoadErrorDto error = Assert.Single(result.Errors);
Assert.Equal("invalid", error.AssemblyName);
Assert.Contains("invalid.dll", error.ErrorMessage);
}
[Fact]