mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 03:11:10 +00:00
Persists and surfaces plugin load failures
This commit is contained in:
1 parent
18361d5da7
commit
b32cc764a7
11 files changed
+279
-13
No files matched your search
+41
@@ -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())];
|
||||
}
|
||||
}
|
||||
+126
-2
@@ -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]
|
||||
|
||||
Reference in new issue
Block a user