From df057185f3a791cebaec966e896b3bcb343ecb5c Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 28 Aug 2026 11:18:08 -0700 Subject: [PATCH] Restores missing bundled themes correctly --- .../Core/Themes/ThemeDetectionSyncJob.cs | 43 ++++++++++----- .../Core/Themes/ThemeDetectionSyncJobTests.cs | 54 ++++++++++++++++++- 2 files changed, 83 insertions(+), 14 deletions(-) diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs index 35feb9c3..46777467 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs @@ -44,12 +44,12 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService /// Method called when the background service starts. /// /// Cancellation token that can be used to stop the execution. - protected override async Task ExecuteAsync(CancellationToken stoppingToken) + protected override async Task ExecuteAsync(CancellationToken cancellationToken) { await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetRequiredService(); - Result> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync(stoppingToken); + Result> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync(cancellationToken); if (getThemesResult.IsFailure) { _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 List themes = [.. getThemesResult.Value]; - HashSet knownThemeIds = [.. themes.Select(theme => theme.ThemeId)]; foreach (string archivePath in _themeService.GetBundledThemeArchivePaths()) { - Result manifestResult = await _themeService.ReadManifestFromArchiveAsync(archivePath, stoppingToken); + Result manifestResult = await _themeService.ReadManifestFromArchiveAsync(archivePath, cancellationToken); if (manifestResult.IsFailure) { _logger.LogWarning("Skipping bundled theme archive {ArchivePath}: {Error}", archivePath, manifestResult.FirstError.Description); 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; // 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 { await using FileStream archive = File.OpenRead(archivePath); - Result installResult = await _themeService.InstallAsync(archive, stoppingToken); + Result installResult = await _themeService.InstallAsync(archive, cancellationToken); if (installResult.IsFailure) { _logger.LogWarning("Failed to install bundled theme '{ThemeId}': {Error}", manifestResult.Value.Id, installResult.FirstError.Description); 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() { Id = Guid.NewGuid(), @@ -101,7 +108,7 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService UpdatedBy = default }; - Result insertResult = await unitOfWork.ThemeRepository.InsertAsync(themeEntity, stoppingToken); + Result insertResult = await unitOfWork.ThemeRepository.InsertAsync(themeEntity, cancellationToken); if (insertResult.IsFailure) _logger.LogWarning("Failed to persist the detection of theme '{ThemeId}': {Error}", manifestResult.Value.Id, insertResult.FirstError.Description); else @@ -117,10 +124,10 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService } } - await CleanUpMissingThemePacksAsync(unitOfWork, themes, stoppingToken); - await EnsureCurrentThemeExistsAsync(unitOfWork, themes, stoppingToken); + await CleanUpMissingThemePacksAsync(unitOfWork, themes, cancellationToken); + await EnsureCurrentThemeExistsAsync(unitOfWork, themes, cancellationToken); - await unitOfWork.SaveChangesAsync(stoppingToken); + await unitOfWork.SaveChangesAsync(cancellationToken); } /// @@ -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); + // 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 brokenTheme.IsDeleted = true; brokenTheme.IsCurrent = null; @@ -181,9 +197,12 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService if (themes.Any(theme => !theme.IsDeleted && theme.IsCurrent == true)) 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 - .Where(theme => !theme.IsDeleted && _themeService.HasThemePack(theme.ThemeId)) - .OrderBy(theme => string.Equals(theme.ThemeId, _themeService.DefaultThemeId, StringComparison.OrdinalIgnoreCase) ? 0 : 1) + .Where(theme => !theme.IsDeleted) + .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) .FirstOrDefault(); if (defaultTheme is null) diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs index 4ac21505..9c0f5633 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs @@ -163,6 +163,30 @@ public class ThemeDetectionSyncJobTests : IDisposable await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } + [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()).Returns(Result.From>([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()).Returns(manifest); + _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(manifest); + _mockThemeService.RestoreBundledThemeAsync("bundled-theme", Arg.Any()).Returns(Result.Success); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeService.Received(1).InstallAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); + await _mockThemeRepository.DidNotReceiveWithAnyArgs().UpdateAsync(default!, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + [Fact] public async Task StartAsync_WhenBundledArchiveManifestCannotBeRead_ShouldSkipTheArchive() { @@ -252,7 +276,7 @@ public class ThemeDetectionSyncJobTests : IDisposable } [Fact] - public async Task StartAsync_WhenMissingBundledThemePackCannotBeRestored_ShouldSoftDeleteTheTheme() + public async Task StartAsync_WhenLastBundledThemePackCannotBeRestored_ShouldKeepAndActivateTheTheme() { // Arrange ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "bundled-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); @@ -267,7 +291,33 @@ public class ThemeDetectionSyncJobTests : IDisposable // Assert await _mockThemeRepository.Received(1).UpdateAsync( - Arg.Is(theme => theme.ThemeId == "bundled-theme" && theme.IsDeleted && theme.IsCurrent == null), + Arg.Is(theme => theme.ThemeId == "bundled-theme" && theme.IsCurrent == true && !theme.IsDeleted), + Arg.Any()); + await _mockThemeService.Received(1).RestoreBundledThemeAsync("bundled-theme", Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [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()).Returns(Result.From>([brokenTheme, healthyTheme])); + _mockThemeService.HasThemePack("broken-theme").Returns(false); + _mockThemeService.GetBundledThemeArchivePaths().Returns([]); + _mockThemeService.RestoreBundledThemeAsync("broken-theme", Arg.Any()).Returns(Error.Failure("Theme.Files", "restore failed")); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.From(Result.Updated)); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(theme => theme.ThemeId == "broken-theme" && theme.IsDeleted && theme.IsCurrent == null), + Arg.Any()); + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(theme => theme.ThemeId == "healthy-theme" && theme.IsCurrent == true), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); }