mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 17:11:10 +00:00
Restores missing bundled themes correctly
This commit is contained in:
1 parent
459dab07fe
commit
df057185f3
2 files changed
+83
-14
No files matched your search
@@ -44,12 +44,12 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService
|
|||||||
/// Method called when the background service starts.
|
/// Method called when the background service starts.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetRequiredService<IUnitOfWork>();
|
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetRequiredService<IUnitOfWork>();
|
||||||
|
|
||||||
Result<IEnumerable<ThemeEntity>> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync(stoppingToken);
|
Result<IEnumerable<ThemeEntity>> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync(cancellationToken);
|
||||||
if (getThemesResult.IsFailure)
|
if (getThemesResult.IsFailure)
|
||||||
{
|
{
|
||||||
_logger.LogWarning("Failed to read the installed themes: {Error}", getThemesResult.FirstError.Description);
|
_logger.LogWarning("Failed to read the installed themes: {Error}", getThemesResult.FirstError.Description);
|
||||||
@@ -58,18 +58,21 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService
|
|||||||
|
|
||||||
// themes that were soft deleted by the user must not be reinstalled automatically
|
// themes that were soft deleted by the user must not be reinstalled automatically
|
||||||
List<ThemeEntity> themes = [.. getThemesResult.Value];
|
List<ThemeEntity> themes = [.. getThemesResult.Value];
|
||||||
HashSet<string> knownThemeIds = [.. themes.Select(theme => theme.ThemeId)];
|
|
||||||
|
|
||||||
foreach (string archivePath in _themeService.GetBundledThemeArchivePaths())
|
foreach (string archivePath in _themeService.GetBundledThemeArchivePaths())
|
||||||
{
|
{
|
||||||
Result<ThemeManifestDto> manifestResult = await _themeService.ReadManifestFromArchiveAsync(archivePath, stoppingToken);
|
Result<ThemeManifestDto> manifestResult = await _themeService.ReadManifestFromArchiveAsync(archivePath, cancellationToken);
|
||||||
if (manifestResult.IsFailure)
|
if (manifestResult.IsFailure)
|
||||||
{
|
{
|
||||||
_logger.LogWarning("Skipping bundled theme archive {ArchivePath}: {Error}", archivePath, manifestResult.FirstError.Description);
|
_logger.LogWarning("Skipping bundled theme archive {ArchivePath}: {Error}", archivePath, manifestResult.FirstError.Description);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (knownThemeIds.Contains(manifestResult.Value.Id))
|
ThemeEntity? existingTheme = themes.Where(theme => theme.ThemeId == manifestResult.Value.Id).FirstOrDefault();
|
||||||
|
|
||||||
|
// a theme that was soft deleted by the user must not be reinstalled automatically; an installed bundled theme
|
||||||
|
// whose files are present is already in sync, so only a bundled theme whose files went missing gets its files reinstalled
|
||||||
|
if (existingTheme is not null && (existingTheme.IsDeleted || existingTheme.InstallSource != ThemeInstallSource.Bundled || _themeService.HasThemePack(existingTheme.ThemeId)))
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
// installing a bundled theme at startup is best effort: a file system failure here must never crash the host,
|
// installing a bundled theme at startup is best effort: a file system failure here must never crash the host,
|
||||||
@@ -78,13 +81,17 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
await using FileStream archive = File.OpenRead(archivePath);
|
await using FileStream archive = File.OpenRead(archivePath);
|
||||||
Result<ThemeManifestDto> installResult = await _themeService.InstallAsync(archive, stoppingToken);
|
Result<ThemeManifestDto> installResult = await _themeService.InstallAsync(archive, cancellationToken);
|
||||||
if (installResult.IsFailure)
|
if (installResult.IsFailure)
|
||||||
{
|
{
|
||||||
_logger.LogWarning("Failed to install bundled theme '{ThemeId}': {Error}", manifestResult.Value.Id, installResult.FirstError.Description);
|
_logger.LogWarning("Failed to install bundled theme '{ThemeId}': {Error}", manifestResult.Value.Id, installResult.FirstError.Description);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// a known theme only gets its missing files reinstalled, so no new row is inserted
|
||||||
|
if (existingTheme is not null)
|
||||||
|
continue;
|
||||||
|
|
||||||
ThemeEntity themeEntity = new()
|
ThemeEntity themeEntity = new()
|
||||||
{
|
{
|
||||||
Id = Guid.NewGuid(),
|
Id = Guid.NewGuid(),
|
||||||
@@ -101,7 +108,7 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService
|
|||||||
UpdatedBy = default
|
UpdatedBy = default
|
||||||
};
|
};
|
||||||
|
|
||||||
Result<Created> insertResult = await unitOfWork.ThemeRepository.InsertAsync(themeEntity, stoppingToken);
|
Result<Created> insertResult = await unitOfWork.ThemeRepository.InsertAsync(themeEntity, cancellationToken);
|
||||||
if (insertResult.IsFailure)
|
if (insertResult.IsFailure)
|
||||||
_logger.LogWarning("Failed to persist the detection of theme '{ThemeId}': {Error}", manifestResult.Value.Id, insertResult.FirstError.Description);
|
_logger.LogWarning("Failed to persist the detection of theme '{ThemeId}': {Error}", manifestResult.Value.Id, insertResult.FirstError.Description);
|
||||||
else
|
else
|
||||||
@@ -117,10 +124,10 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await CleanUpMissingThemePacksAsync(unitOfWork, themes, stoppingToken);
|
await CleanUpMissingThemePacksAsync(unitOfWork, themes, cancellationToken);
|
||||||
await EnsureCurrentThemeExistsAsync(unitOfWork, themes, stoppingToken);
|
await EnsureCurrentThemeExistsAsync(unitOfWork, themes, cancellationToken);
|
||||||
|
|
||||||
await unitOfWork.SaveChangesAsync(stoppingToken);
|
await unitOfWork.SaveChangesAsync(cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -149,6 +156,15 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService
|
|||||||
|
|
||||||
_logger.LogWarning("Failed to restore the files of bundled theme '{ThemeId}': {Error}", brokenTheme.ThemeId, restoreResult.FirstError.Description);
|
_logger.LogWarning("Failed to restore the files of bundled theme '{ThemeId}': {Error}", brokenTheme.ThemeId, restoreResult.FirstError.Description);
|
||||||
|
|
||||||
|
// at least one bundled theme must always remain available, so the application never ends up without any theme;
|
||||||
|
// the last remaining bundled theme is kept even when its files cannot be recovered
|
||||||
|
int availableBundledThemes = themes.Count(availableTheme => !availableTheme.IsDeleted && availableTheme.InstallSource == ThemeInstallSource.Bundled);
|
||||||
|
if (availableBundledThemes <= 1)
|
||||||
|
{
|
||||||
|
_logger.LogWarning("Bundled theme '{ThemeId}' is the last remaining bundled theme and its files could not be restored, so it is kept.", brokenTheme.ThemeId);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
// a bundled theme whose files could not be recovered is soft deleted, so it is not shown anymore, but can be restored later
|
// a bundled theme whose files could not be recovered is soft deleted, so it is not shown anymore, but can be restored later
|
||||||
brokenTheme.IsDeleted = true;
|
brokenTheme.IsDeleted = true;
|
||||||
brokenTheme.IsCurrent = null;
|
brokenTheme.IsCurrent = null;
|
||||||
@@ -181,9 +197,12 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService
|
|||||||
if (themes.Any(theme => !theme.IsDeleted && theme.IsCurrent == true))
|
if (themes.Any(theme => !theme.IsDeleted && theme.IsCurrent == true))
|
||||||
return;
|
return;
|
||||||
|
|
||||||
|
// a theme whose files are present is preferred, so the activated theme can render immediately; a bundled theme
|
||||||
|
// whose files could not be restored is kept as the fallback, so the application always has an active theme
|
||||||
ThemeEntity? defaultTheme = themes
|
ThemeEntity? defaultTheme = themes
|
||||||
.Where(theme => !theme.IsDeleted && _themeService.HasThemePack(theme.ThemeId))
|
.Where(theme => !theme.IsDeleted)
|
||||||
.OrderBy(theme => string.Equals(theme.ThemeId, _themeService.DefaultThemeId, StringComparison.OrdinalIgnoreCase) ? 0 : 1)
|
.OrderBy(theme => _themeService.HasThemePack(theme.ThemeId) ? 0 : 1)
|
||||||
|
.ThenBy(theme => string.Equals(theme.ThemeId, _themeService.DefaultThemeId, StringComparison.OrdinalIgnoreCase) ? 0 : 1)
|
||||||
.ThenBy(theme => theme.ThemeId, StringComparer.OrdinalIgnoreCase)
|
.ThenBy(theme => theme.ThemeId, StringComparer.OrdinalIgnoreCase)
|
||||||
.FirstOrDefault();
|
.FirstOrDefault();
|
||||||
if (defaultTheme is null)
|
if (defaultTheme is null)
|
||||||
|
|||||||
+52
-2
@@ -163,6 +163,30 @@ public class ThemeDetectionSyncJobTests : IDisposable
|
|||||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task StartAsync_WhenInstalledBundledThemePackIsMissingAndNotDeleted_ShouldReinstallTheFilesWithoutInsertingANewRow()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
ThemeEntity existingTheme = _themeEntityFixture.Create(themeId: "bundled-theme", isCurrent: true, includeIsCurrent: true, installSource: ThemeInstallSource.Bundled, isDeleted: false);
|
||||||
|
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([existingTheme]));
|
||||||
|
_mockThemeService.HasThemePack("bundled-theme").Returns(false);
|
||||||
|
string archivePath = CreateBundledArchiveFile("bundled-theme");
|
||||||
|
ThemeManifestDto manifest = _themeManifestDtoFixture.Create(id: "bundled-theme");
|
||||||
|
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
|
||||||
|
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any<CancellationToken>()).Returns(manifest);
|
||||||
|
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>()).Returns(manifest);
|
||||||
|
_mockThemeService.RestoreBundledThemeAsync("bundled-theme", Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
await StartAndWaitForExecutionAsync(CreateSut());
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
await _mockThemeService.Received(1).InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
|
||||||
|
await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any<CancellationToken>());
|
||||||
|
await _mockThemeRepository.DidNotReceiveWithAnyArgs().UpdateAsync(default!, Arg.Any<CancellationToken>());
|
||||||
|
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task StartAsync_WhenBundledArchiveManifestCannotBeRead_ShouldSkipTheArchive()
|
public async Task StartAsync_WhenBundledArchiveManifestCannotBeRead_ShouldSkipTheArchive()
|
||||||
{
|
{
|
||||||
@@ -252,7 +276,7 @@ public class ThemeDetectionSyncJobTests : IDisposable
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task StartAsync_WhenMissingBundledThemePackCannotBeRestored_ShouldSoftDeleteTheTheme()
|
public async Task StartAsync_WhenLastBundledThemePackCannotBeRestored_ShouldKeepAndActivateTheTheme()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "bundled-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false);
|
ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "bundled-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false);
|
||||||
@@ -267,7 +291,33 @@ public class ThemeDetectionSyncJobTests : IDisposable
|
|||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
await _mockThemeRepository.Received(1).UpdateAsync(
|
await _mockThemeRepository.Received(1).UpdateAsync(
|
||||||
Arg.Is<ThemeEntity>(theme => theme.ThemeId == "bundled-theme" && theme.IsDeleted && theme.IsCurrent == null),
|
Arg.Is<ThemeEntity>(theme => theme.ThemeId == "bundled-theme" && theme.IsCurrent == true && !theme.IsDeleted),
|
||||||
|
Arg.Any<CancellationToken>());
|
||||||
|
await _mockThemeService.Received(1).RestoreBundledThemeAsync("bundled-theme", Arg.Any<CancellationToken>());
|
||||||
|
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task StartAsync_WhenMissingBundledThemePackCannotBeRestoredAndAnotherBundledThemeRemains_ShouldSoftDeleteTheTheme()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "broken-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false);
|
||||||
|
ThemeEntity healthyTheme = _themeEntityFixture.Create(themeId: "healthy-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false);
|
||||||
|
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([brokenTheme, healthyTheme]));
|
||||||
|
_mockThemeService.HasThemePack("broken-theme").Returns(false);
|
||||||
|
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
|
||||||
|
_mockThemeService.RestoreBundledThemeAsync("broken-theme", Arg.Any<CancellationToken>()).Returns(Error.Failure("Theme.Files", "restore failed"));
|
||||||
|
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()).Returns(Result.From(Result.Updated));
|
||||||
|
|
||||||
|
// Act
|
||||||
|
await StartAndWaitForExecutionAsync(CreateSut());
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
await _mockThemeRepository.Received(1).UpdateAsync(
|
||||||
|
Arg.Is<ThemeEntity>(theme => theme.ThemeId == "broken-theme" && theme.IsDeleted && theme.IsCurrent == null),
|
||||||
|
Arg.Any<CancellationToken>());
|
||||||
|
await _mockThemeRepository.Received(1).UpdateAsync(
|
||||||
|
Arg.Is<ThemeEntity>(theme => theme.ThemeId == "healthy-theme" && theme.IsCurrent == true),
|
||||||
Arg.Any<CancellationToken>());
|
Arg.Any<CancellationToken>());
|
||||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user