diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/IPluginRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/IPluginRepository.cs index 54ac313e..b66039a4 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/IPluginRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/IPluginRepository.cs @@ -15,7 +15,8 @@ namespace Lumina.Application.Common.DataAccess.Repositories.Plugins; /// public interface IPluginRepository : IRepository, IGetByIdRepositoryAction, - IGetAllRepositoryAction + IGetAllRepositoryAction, + IDeleteByIdRepositoryAction { /// /// Inserts the provided into the storage medium, or updates it when it already exists. diff --git a/src/Lumina.DataAccess/Core/Repositories/Plugins/PluginRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Plugins/PluginRepository.cs index 4c1a4bd9..c71d54fd 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Plugins/PluginRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Plugins/PluginRepository.cs @@ -77,6 +77,22 @@ internal sealed class PluginRepository : IPluginRepository return Result.Updated; } + /// + /// Deletes a plugin identified by from the storage medium. + /// + /// The id of the plugin to be deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> 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; + } + /// /// Updates the settings of the plugin identified by . /// diff --git a/src/Lumina.Infrastructure/Common/Models/DTO/Plugins/PluginLoadErrorDto.cs b/src/Lumina.Infrastructure/Common/Models/DTO/Plugins/PluginLoadErrorDto.cs new file mode 100644 index 00000000..527803b1 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Models/DTO/Plugins/PluginLoadErrorDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Infrastructure.Common.Models.DTO.Plugins; + +/// +/// Data transfer object for the error that occurred while loading a plugin assembly. +/// +/// The file name of the plugin assembly that failed to load, without its extension. +/// The error message describing the load failure. +[DebuggerDisplay("AssemblyName: {AssemblyName}")] +internal sealed record PluginLoadErrorDto( + string AssemblyName, + string ErrorMessage +); diff --git a/src/Lumina.Infrastructure/Common/Models/DTO/Plugins/PluginLoadResultDto.cs b/src/Lumina.Infrastructure/Common/Models/DTO/Plugins/PluginLoadResultDto.cs index f658b6d2..94c232c0 100644 --- a/src/Lumina.Infrastructure/Common/Models/DTO/Plugins/PluginLoadResultDto.cs +++ b/src/Lumina.Infrastructure/Common/Models/DTO/Plugins/PluginLoadResultDto.cs @@ -10,4 +10,7 @@ namespace Lumina.Infrastructure.Common.Models.DTO.Plugins; /// /// The plugins that were loaded successfully. /// The errors that occurred while loading the plugins. -internal sealed record PluginLoadResultDto(IReadOnlyList Plugins, IReadOnlyList Errors); +internal sealed record PluginLoadResultDto( + IReadOnlyList Plugins, + IReadOnlyList Errors +); diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs index d1de207d..8a433b7a 100644 --- a/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs +++ b/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs @@ -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 _loadErrors; + private readonly IReadOnlyList _loadErrors; private readonly ILogger _logger; /// @@ -34,7 +38,7 @@ internal sealed class PluginDetectionSyncJob : BackgroundService /// Injected manager of the plugins loaded by the host application. /// The errors that occurred while loading the plugins. /// Injected logger used for logging. - public PluginDetectionSyncJob(IServiceScopeFactory serviceScopeFactory, IPluginManager pluginManager, IReadOnlyList loadErrors, ILogger logger) + public PluginDetectionSyncJob(IServiceScopeFactory serviceScopeFactory, IPluginManager pluginManager, IReadOnlyList loadErrors, ILogger logger) { _serviceScopeFactory = serviceScopeFactory; _pluginManager = pluginManager; @@ -49,14 +53,18 @@ internal sealed class PluginDetectionSyncJob : BackgroundService /// A that represents the long running operations. 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(); + // the Ids of the plugin rows that are currently detected, either loaded successfully or failed to load + HashSet 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 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> 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 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); } + + /// + /// 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. + /// + /// The file name of the plugin assembly, without its extension. + /// The derived plugin identifier. + private static Guid DerivePluginId(string assemblyName) + { + byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(assemblyName)); + return new Guid([.. hash.Take(16)]); + } } diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginLoader.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginLoader.cs index a0307de2..7ce4b358 100644 --- a/src/Lumina.Infrastructure/Core/Plugins/PluginLoader.cs +++ b/src/Lumina.Infrastructure/Core/Plugins/PluginLoader.cs @@ -24,7 +24,7 @@ internal static class PluginLoader public static PluginLoadResultDto LoadPlugins(string pluginsDirectory, IServiceCollection services) { List plugins = []; - List errors = []; + List 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}")); } } diff --git a/src/Lumina.Infrastructure/Properties/AssemblyInfo.cs b/src/Lumina.Infrastructure/Properties/AssemblyInfo.cs index 09c567c1..10decd96 100644 --- a/src/Lumina.Infrastructure/Properties/AssemblyInfo.cs +++ b/src/Lumina.Infrastructure/Properties/AssemblyInfo.cs @@ -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")] diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/Management/Item.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Item.cshtml index 091c47cf..722c1505 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/Management/Item.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Item.cshtml @@ -383,7 +383,10 @@ ${provider.name} - + diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Plugins/PluginLoadErrorDtoFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Plugins/PluginLoadErrorDtoFixture.cs new file mode 100644 index 00000000..d235967c --- /dev/null +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Plugins/PluginLoadErrorDtoFixture.cs @@ -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; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +internal class PluginLoadErrorDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a valid . + /// + /// Optional. The file name of the plugin assembly that failed to load, without its extension. + /// Optional. The error message describing the load failure. + /// The created . + 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()}"); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs index 723a1fe2..ddfd630d 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs @@ -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 _mockLogger; + private readonly PluginLoadErrorDtoFixture _pluginLoadErrorDtoFixture; /// /// Initializes a new instance of the class. @@ -53,6 +59,7 @@ public class PluginDetectionSyncJobTests _mockPluginManager = Substitute.For(); _mockLogger = Substitute.For>(); + _pluginLoadErrorDtoFixture = new PluginLoadErrorDtoFixture(); } [Fact] @@ -126,6 +133,88 @@ public class PluginDetectionSyncJobTests await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } + [Fact] + public async Task StartAsync_WhenPluginFailsToLoad_ShouldPersistFailedPluginWithError() + { + // Arrange + _mockPluginManager.GetPlugins().Returns([]); + _mockPluginRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .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(plugin => plugin.Id == DeriveExpectedId(loadError.AssemblyName) + && plugin.Name == loadError.AssemblyName + && plugin.LoadStatus == PluginLoadStatus.FailedToLoad + && plugin.LoadError == loadError.ErrorMessage), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [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(), Arg.Any()) + .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()) + .Returns(Result.From((IEnumerable)[loadedPluginRow, stalePluginRow])); + _mockPluginRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Deleted); + PluginDetectionSyncJob sut = CreateSut(); + + // Act + await StartAndWaitForExecutionAsync(sut); + + // Assert + await _mockPluginRepository.Received(1).DeleteByIdAsync(stalePluginRow.Id, Arg.Any()); + await _mockPluginRepository.DidNotReceive().DeleteByIdAsync(loadedPluginRow.Id, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [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(), Arg.Any()) + .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()) + .Returns(Result.From((IEnumerable)[staleLoadedRow])); + _mockPluginRepository.DeleteByIdAsync(previouslyLoadedPlugin.Id, Arg.Any()) + .Returns(Result.Deleted); + PluginDetectionSyncJob sut = CreateSut([loadError]); + + // Act + await StartAndWaitForExecutionAsync(sut); + + // Assert + await _mockPluginRepository.Received(1).UpsertAsync( + Arg.Is(plugin => plugin.Id == DeriveExpectedId(loadError.AssemblyName) + && plugin.Name == loadError.AssemblyName + && plugin.LoadStatus == PluginLoadStatus.FailedToLoad + && plugin.LoadError == loadError.ErrorMessage), + Arg.Any()); + await _mockPluginRepository.Received(1).DeleteByIdAsync(previouslyLoadedPlugin.Id, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + /// /// Invokes the protected of the job and awaits its completion. /// @@ -140,10 +229,11 @@ public class PluginDetectionSyncJobTests /// /// Creates the system under test wired to the mocked dependencies. /// + /// The plugin load errors to feed to the job, when any. /// The created job instance. - private PluginDetectionSyncJob CreateSut() + private PluginDetectionSyncJob CreateSut(IReadOnlyList? loadErrors = null) { - return new PluginDetectionSyncJob(_mockServiceScopeFactory, _mockPluginManager, [], _mockLogger); + return new PluginDetectionSyncJob(_mockServiceScopeFactory, _mockPluginManager, loadErrors ?? [], _mockLogger); } /// @@ -163,4 +253,38 @@ public class PluginDetectionSyncJobTests plugin.Description.Returns("Test plugin description"); return plugin; } + + /// + /// Creates a stored plugin row with the provided identity. + /// + /// The Id of the plugin row. + /// The name of the plugin row. + /// The load status of the plugin row. + /// The created plugin entity. + 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 + }; + } + + /// + /// Derives the stable plugin Id expected for a failing plugin assembly, mirroring the detection job logic. + /// + /// The file name of the plugin assembly, without its extension. + /// The derived plugin identifier. + private static Guid DeriveExpectedId(string assemblyName) + { + byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(assemblyName)); + return new Guid(hash.Take(16).ToArray()); + } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginLoaderTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginLoaderTests.cs index 84dcff66..e4a40ccd 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginLoaderTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginLoaderTests.cs @@ -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]