Guards structured logging with IsEnabled checks

This commit is contained in:
BinaryAlley committed 2026-11-26 12:35:30 +02:00
1 parent ccbd653ee5
commit 2e53449ada
44 files changed
+326 -14

No files matched your search

@@ -49,6 +49,7 @@ internal static class ApplicationHandlerTelemetry
{ {
activity?.SetStatus(ActivityStatusCode.Ok); activity?.SetStatus(ActivityStatusCode.Ok);
RecordOutcome(activity, handlerName, handlerType, duration, isSuccess: true); RecordOutcome(activity, handlerName, handlerType, duration, isSuccess: true);
if (logger.IsEnabled(LogLevel.Debug))
logger.LogDebug("Completed handling {HandlerType} {HandlerName} in {DurationMs}ms", handlerType, handlerName, duration.TotalMilliseconds); logger.LogDebug("Completed handling {HandlerType} {HandlerName} in {DurationMs}ms", handlerType, handlerName, duration.TotalMilliseconds);
} }
@@ -66,6 +67,7 @@ internal static class ApplicationHandlerTelemetry
activity?.SetStatus(ActivityStatusCode.Error, error); activity?.SetStatus(ActivityStatusCode.Error, error);
RecordOutcome(activity, handlerName, handlerType, duration, isSuccess: false); RecordOutcome(activity, handlerName, handlerType, duration, isSuccess: false);
// Business-rule failures are routine outcomes (e.g. failed logins), so log at Debug to avoid noise from high-frequency handlers. // Business-rule failures are routine outcomes (e.g. failed logins), so log at Debug to avoid noise from high-frequency handlers.
if (logger.IsEnabled(LogLevel.Debug))
logger.LogDebug("Failed handling {HandlerType} {HandlerName} in {DurationMs}ms: {Error}", handlerType, handlerName, duration.TotalMilliseconds, error); logger.LogDebug("Failed handling {HandlerType} {HandlerName} in {DurationMs}ms: {Error}", handlerType, handlerName, duration.TotalMilliseconds, error);
} }
@@ -82,6 +84,7 @@ internal static class ApplicationHandlerTelemetry
{ {
activity?.SetStatus(ActivityStatusCode.Error, exception.Message); activity?.SetStatus(ActivityStatusCode.Error, exception.Message);
RecordOutcome(activity, handlerName, handlerType, duration, isSuccess: false); RecordOutcome(activity, handlerName, handlerType, duration, isSuccess: false);
if (logger.IsEnabled(LogLevel.Error))
logger.LogError(exception, "Failed handling {HandlerType} {HandlerName} in {DurationMs}ms", handlerType, handlerName, duration.TotalMilliseconds); logger.LogError(exception, "Failed handling {HandlerType} {HandlerName} in {DurationMs}ms", handlerType, handlerName, duration.TotalMilliseconds);
} }
@@ -72,6 +72,7 @@ internal sealed class BooksMediaLibraryItemDeletionStrategy : IMediaLibraryItemD
Result<Deleted> deleteArtworkResult = _bookArtworkService.DeleteBookArtwork(libraryId, book.Id, library.Title, authorName, book.Title); Result<Deleted> deleteArtworkResult = _bookArtworkService.DeleteBookArtwork(libraryId, book.Id, library.Title, authorName, book.Title);
if (deleteArtworkResult.IsFailure) if (deleteArtworkResult.IsFailure)
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Failed to delete the stored artwork of the book with Id '{BookId}' at path '{BookPath}', the artwork might remain orphaned.", book.Id, book.Path); _logger.LogWarning("Failed to delete the stored artwork of the book with Id '{BookId}' at path '{BookPath}', the artwork might remain orphaned.", book.Id, book.Path);
// Delete the book, whose stored artwork and participations are removed by the database cascade. // Delete the book, whose stored artwork and participations are removed by the database cascade.
@@ -142,6 +142,7 @@ internal sealed class MusicMediaLibraryItemDeletionStrategy : IMediaLibraryItemD
Result<Deleted> deleteStoredArtworkResult = _musicArtworkService.DeleteStoredArtwork(artwork.FileName); Result<Deleted> deleteStoredArtworkResult = _musicArtworkService.DeleteStoredArtwork(artwork.FileName);
if (deleteStoredArtworkResult.IsFailure) if (deleteStoredArtworkResult.IsFailure)
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Failed to delete the stored {OwnerType} artwork at '{ArtworkPath}' of the music library item with Id '{OwnerId}', the file might remain orphaned.", ownerType, artwork.FileName, ownerId); _logger.LogWarning("Failed to delete the stored {OwnerType} artwork at '{ArtworkPath}' of the music library item with Id '{OwnerId}', the file might remain orphaned.", ownerType, artwork.FileName, ownerId);
} }
@@ -61,6 +61,7 @@ public class LibraryMediaItemDeletedDomainEventHandler : IDomainEventHandler<Lib
IMediaLibraryItemDeletionStrategy? deletionStrategy = _mediaLibraryItemDeletionStrategies.FirstOrDefault(strategy => strategy.SupportedLibraryType == libraryType); IMediaLibraryItemDeletionStrategy? deletionStrategy = _mediaLibraryItemDeletionStrategies.FirstOrDefault(strategy => strategy.SupportedLibraryType == libraryType);
if (deletionStrategy is null) if (deletionStrategy is null)
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("No deletion strategy exists for media library type '{LibraryType}', the item at path '{ItemPath}' was not deleted.", libraryType, domainEvent.Path); _logger.LogWarning("No deletion strategy exists for media library type '{LibraryType}', the item at path '{ItemPath}' was not deleted.", libraryType, domainEvent.Path);
return; return;
} }
@@ -133,6 +133,7 @@ public class GetThemeTemplateQueryHandler : IQueryHandler<GetThemeTemplateQuery,
{ {
// The restore is best effort: an unexpected failure must not fail the request, so the caller falls back to // The restore is best effort: an unexpected failure must not fail the request, so the caller falls back to
// the application view instead of returning an error to the browser. // the application view instead of returning an error to the browser.
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(exception, "Failed to restore the files of bundled theme '{ThemeId}'.", theme.ThemeId); _logger.LogWarning(exception, "Failed to restore the files of bundled theme '{ThemeId}'.", theme.ThemeId);
return false; return false;
} }
@@ -79,12 +79,14 @@ internal static class PublicHostConnectionGuard
catch (PublicHostRejectedException exception) catch (PublicHostRejectedException exception)
{ {
// The address policy refused the target. This is deterministic, so it is logged as a rejection rather than as a transport failure. // The address policy refused the target. This is deterministic, so it is logged as a rejection rather than as a transport failure.
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning("Rejected the outbound connection to the host '{Host}' because {RejectionReason}. The connection was not made.", host, exception.RejectionReason); logger.LogWarning("Rejected the outbound connection to the host '{Host}' because {RejectionReason}. The connection was not made.", host, exception.RejectionReason);
throw; throw;
} }
catch (PublicHostResolutionException) catch (PublicHostResolutionException)
{ {
// The host name could not be resolved. This is reported separately from a policy rejection because it can be transient. // The host name could not be resolved. This is reported separately from a policy rejection because it can be transient.
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning("Could not resolve the outbound host '{Host}'. The connection was not made.", host); logger.LogWarning("Could not resolve the outbound host '{Host}'. The connection was not made.", host);
throw; throw;
} }
@@ -116,6 +116,7 @@ internal sealed class PublicHostRedirectHandler : DelegatingHandler
{ {
if (result.RejectionReason == OutboundRequestRejectionReason.HostCouldNotBeResolved) if (result.RejectionReason == OutboundRequestRejectionReason.HostCouldNotBeResolved)
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Could not resolve the outbound redirect host '{Host}'. The request was not sent.", redirectUri.IdnHost); _logger.LogWarning("Could not resolve the outbound redirect host '{Host}'. The request was not sent.", redirectUri.IdnHost);
throw new PublicHostResolutionException(redirectUri.IdnHost); throw new PublicHostResolutionException(redirectUri.IdnHost);
} }
@@ -142,6 +143,7 @@ internal sealed class PublicHostRedirectHandler : DelegatingHandler
/// <returns>The exception that reports the rejection.</returns> /// <returns>The exception that reports the rejection.</returns>
private PublicHostRejectedException Reject(string host, OutboundRequestRejectionReason rejectionReason) private PublicHostRejectedException Reject(string host, OutboundRequestRejectionReason rejectionReason)
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Rejected the outbound redirect to the host '{Host}' because {RejectionReason}. The request was not sent.", host, rejectionReason); _logger.LogWarning("Rejected the outbound redirect to the host '{Host}' because {RejectionReason}. The request was not sent.", host, rejectionReason);
return new PublicHostRejectedException(host, rejectionReason); return new PublicHostRejectedException(host, rejectionReason);
} }
@@ -55,10 +55,12 @@ internal sealed class PublicHostValidationHandler : DelegatingHandler
if (result.RejectionReason == OutboundRequestRejectionReason.HostCouldNotBeResolved) if (result.RejectionReason == OutboundRequestRejectionReason.HostCouldNotBeResolved)
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Could not resolve the outbound host '{Host}'. The request was not sent.", requestUri.IdnHost); _logger.LogWarning("Could not resolve the outbound host '{Host}'. The request was not sent.", requestUri.IdnHost);
throw new PublicHostResolutionException(requestUri.IdnHost); throw new PublicHostResolutionException(requestUri.IdnHost);
} }
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Rejected the outbound request to the host '{Host}' because {RejectionReason}. The request was not sent.", requestUri.IdnHost, result.RejectionReason); _logger.LogWarning("Rejected the outbound request to the host '{Host}' because {RejectionReason}. The request was not sent.", requestUri.IdnHost, result.RejectionReason);
throw new PublicHostRejectedException(requestUri.IdnHost, result.RejectionReason); throw new PublicHostRejectedException(requestUri.IdnHost, result.RejectionReason);
} }
@@ -545,6 +545,7 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID
} }
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{ {
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "The normalized audio cache directory '{CacheDirectory}' is not available for track {TrackId} in cache entry {CacheId}.", _cacheRoot, request.TrackId, cacheId); _logger.LogError(exception, "The normalized audio cache directory '{CacheDirectory}' is not available for track {TrackId} in cache entry {CacheId}.", _cacheRoot, request.TrackId, cacheId);
return Errors.Playback.NormalizationUnavailable; return Errors.Playback.NormalizationUnavailable;
} }
@@ -588,6 +589,7 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID
catch (Exception exception) catch (Exception exception)
{ {
// The production is shared by requests that are no longer necessarily waiting, so every failure is turned into a result and observed here. // The production is shared by requests that are no longer necessarily waiting, so every failure is turned into a result and observed here.
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "The normalized audio of track {TrackId} in cache entry {CacheId} could not be produced.", request.TrackId, cacheId); _logger.LogError(exception, "The normalized audio of track {TrackId} in cache entry {CacheId} could not be produced.", request.TrackId, cacheId);
return Errors.Playback.NormalizationFailed; return Errors.Playback.NormalizationFailed;
} }
@@ -678,6 +680,7 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID
return Errors.Playback.NormalizationFailed; return Errors.Playback.NormalizationFailed;
} }
if (isKeptOverCapacity) if (isKeptOverCapacity)
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("The normalized audio of track {TrackId} in cache entry {CacheId} was produced successfully but exceeds the configured normalized audio cache limit. It is kept readable and will be evicted when it is no longer in use.", request.TrackId, cacheId); _logger.LogWarning("The normalized audio of track {TrackId} in cache entry {CacheId} was produced successfully but exceeds the configured normalized audio cache limit. It is kept readable and will be evicted when it is no longer in use.", request.TrackId, cacheId);
return GetOrCreateTrackProjection(cacheId, index); return GetOrCreateTrackProjection(cacheId, index);
@@ -688,6 +691,7 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID
} }
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException or NotSupportedException) catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException or NotSupportedException)
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(exception, "The normalized audio of track {TrackId} in cache entry {CacheId} could not be cached.", request.TrackId, cacheId); _logger.LogWarning(exception, "The normalized audio of track {TrackId} in cache entry {CacheId} could not be cached.", request.TrackId, cacheId);
return Errors.Playback.NormalizationFailed; return Errors.Playback.NormalizationFailed;
} }
@@ -748,6 +752,7 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID
} }
catch (Exception exception) when (exception is Win32Exception or InvalidOperationException or IOException) catch (Exception exception) when (exception is Win32Exception or InvalidOperationException or IOException)
{ {
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "The audio transcoder for track {TrackId} in cache entry {CacheId} could not be started.", request.TrackId, cacheId); _logger.LogError(exception, "The audio transcoder for track {TrackId} in cache entry {CacheId} could not be started.", request.TrackId, cacheId);
return Errors.Playback.NormalizationUnavailable; return Errors.Playback.NormalizationUnavailable;
} }
@@ -801,13 +806,17 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID
return Errors.Playback.NormalizationTimedOut; return Errors.Playback.NormalizationTimedOut;
if (process.ExitCode != 0) if (process.ExitCode != 0)
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("The audio transcoder for track {TrackId} in cache entry {CacheId} exited with code {ExitCode}.", request.TrackId, cacheId, process.ExitCode); _logger.LogWarning("The audio transcoder for track {TrackId} in cache entry {CacheId} exited with code {ExitCode}.", request.TrackId, cacheId, process.ExitCode);
if (!string.IsNullOrWhiteSpace(standardError)) if (!string.IsNullOrWhiteSpace(standardError))
{ {
// The bounded stderr can contain the source path and media metadata. It is only written at Debug and never returned to a client. // The bounded stderr can contain the source path and media metadata. It is only written at Debug and never returned to a client.
if (_logger.IsEnabled(LogLevel.Debug))
{
string diagnostic = RedactPath(RedactPath(standardError, inputPath), request.SourcePath); string diagnostic = RedactPath(RedactPath(standardError, inputPath), request.SourcePath);
_logger.LogDebug("The audio transcoder for track {TrackId} in cache entry {CacheId} reported: {StandardError}", request.TrackId, cacheId, diagnostic); _logger.LogDebug("The audio transcoder for track {TrackId} in cache entry {CacheId} reported: {StandardError}", request.TrackId, cacheId, diagnostic);
} }
}
return Errors.Playback.NormalizationFailed; return Errors.Playback.NormalizationFailed;
} }
@@ -1013,6 +1022,7 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID
if (previousEndSeconds < expectedDurationSeconds - durationToleranceSeconds) if (previousEndSeconds < expectedDurationSeconds - durationToleranceSeconds)
return Errors.Playback.NormalizationFailed; return Errors.Playback.NormalizationFailed;
if (previousEndSeconds > expectedDurationSeconds + durationToleranceSeconds) if (previousEndSeconds > expectedDurationSeconds + durationToleranceSeconds)
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("The normalized audio of track {TrackId} in cache entry {CacheId} is longer than the probed duration: produced {ProducedSeconds} seconds, probed {ExpectedSeconds} seconds. The production is kept because only a shortfall is treated as truncation.", request.TrackId, cacheId, previousEndSeconds, expectedDurationSeconds); _logger.LogInformation("The normalized audio of track {TrackId} in cache entry {CacheId} is longer than the probed duration: produced {ProducedSeconds} seconds, probed {ExpectedSeconds} seconds. The production is kept because only a shortfall is treated as truncation.", request.TrackId, cacheId, previousEndSeconds, expectedDurationSeconds);
// The index advertises the produced end, rounded up to the next second, instead of the probed duration. A probe can underestimate a variable // The index advertises the produced end, rounded up to the next second, instead of the probed duration. A probe can underestimate a variable
@@ -1311,6 +1321,7 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID
long actualBytes = outputSizeTracker.GetCurrentSize(); long actualBytes = outputSizeTracker.GetCurrentSize();
if (!reservation.TryUpdate(actualBytes, _settings.MaxCacheBytes, _evictionGracePeriod)) if (!reservation.TryUpdate(actualBytes, _settings.MaxCacheBytes, _evictionGracePeriod))
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("A normalization job for track {TrackId} in cache entry {CacheId} could not reserve enough space in the normalized audio cache and was stopped.", trackId, cacheId); _logger.LogWarning("A normalization job for track {TrackId} in cache entry {CacheId} could not reserve enough space in the normalized audio cache and was stopped.", trackId, cacheId);
KillProcess(process); KillProcess(process);
return true; return true;
@@ -1462,6 +1473,7 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID
OnApplicationStopping(this, EventArgs.Empty); OnApplicationStopping(this, EventArgs.Empty);
if (!_productionsDrained.Wait(TimeSpan.FromSeconds(PRODUCTION_DRAIN_TIMEOUT_SECONDS))) if (!_productionsDrained.Wait(TimeSpan.FromSeconds(PRODUCTION_DRAIN_TIMEOUT_SECONDS)))
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("The normalized audio productions did not drain within {DrainTimeoutSeconds} seconds during shutdown. The process lifetime resources are left undisposed.", PRODUCTION_DRAIN_TIMEOUT_SECONDS); _logger.LogWarning("The normalized audio productions did not drain within {DrainTimeoutSeconds} seconds during shutdown. The process lifetime resources are left undisposed.", PRODUCTION_DRAIN_TIMEOUT_SECONDS);
return; return;
} }
@@ -78,6 +78,7 @@ internal sealed class TranscodingStartupInitializer : IHostedService
catch (OperationCanceledException) catch (OperationCanceledException)
{ {
if (!cancellationToken.IsCancellationRequested) if (!cancellationToken.IsCancellationRequested)
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("The normalized audio cache cleanup did not finish within {CleanupTimeoutSeconds} seconds. Whatever remains is accounted for by the coordinator and is removed by the next cleanup.", CACHE_CLEANUP_TIMEOUT_SECONDS); _logger.LogWarning("The normalized audio cache cleanup did not finish within {CleanupTimeoutSeconds} seconds. Whatever remains is accounted for by the coordinator and is removed by the next cleanup.", CACHE_CLEANUP_TIMEOUT_SECONDS);
} }
} }
@@ -90,12 +91,14 @@ internal sealed class TranscodingStartupInitializer : IHostedService
} }
else else
TranscodingCachePaths.EnsureDirectoryExists(cacheDirectory); TranscodingCachePaths.EnsureDirectoryExists(cacheDirectory);
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("The normalized audio cache uses the directory '{CacheDirectory}'.", cacheDirectory); _logger.LogInformation("The normalized audio cache uses the directory '{CacheDirectory}'.", cacheDirectory);
} }
catch (Exception exception) catch (Exception exception)
{ {
// A locked file, a read-only volume or a directory owned by another account must not stop the whole application; the coordinator accounts // A locked file, a read-only volume or a directory owned by another account must not stop the whole application; the coordinator accounts
// for whatever remains and the service reports normalized playback as unavailable when the directory still cannot be used. // for whatever remains and the service reports normalized playback as unavailable when the directory still cannot be used.
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "The normalized audio cache could not be initialized (configured directory: '{CacheDirectory}'). Normalized playback may be unavailable.", _settings.CacheDirectory ?? "(default)"); _logger.LogError(exception, "The normalized audio cache could not be initialized (configured directory: '{CacheDirectory}'). Normalized playback may be unavailable.", _settings.CacheDirectory ?? "(default)");
} }
@@ -145,6 +148,7 @@ internal sealed class TranscodingStartupInitializer : IHostedService
if (!process.Start()) if (!process.Start())
{ {
_toolchainStatus.RecordUnavailable(); _toolchainStatus.RecordUnavailable();
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("The ffmpeg binary '{FfmpegPath}' could not be started. Normalized playback will be unavailable.", _settings.FfmpegPath); _logger.LogWarning("The ffmpeg binary '{FfmpegPath}' could not be started. Normalized playback will be unavailable.", _settings.FfmpegPath);
return; return;
} }
@@ -173,6 +177,7 @@ internal sealed class TranscodingStartupInitializer : IHostedService
_logger.LogDebug(killException, "The ffmpeg startup probe process could not be stopped."); _logger.LogDebug(killException, "The ffmpeg startup probe process could not be stopped.");
} }
if (!cancellationToken.IsCancellationRequested) if (!cancellationToken.IsCancellationRequested)
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("The ffmpeg binary '{FfmpegPath}' did not respond to the startup probe.", _settings.FfmpegPath); _logger.LogWarning("The ffmpeg binary '{FfmpegPath}' did not respond to the startup probe.", _settings.FfmpegPath);
_toolchainStatus.RecordUnavailable(); _toolchainStatus.RecordUnavailable();
return; return;
@@ -183,6 +188,7 @@ internal sealed class TranscodingStartupInitializer : IHostedService
if (process.ExitCode != 0) if (process.ExitCode != 0)
{ {
_toolchainStatus.RecordUnavailable(); _toolchainStatus.RecordUnavailable();
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("The ffmpeg binary '{FfmpegPath}' exited with code {ExitCode} during the startup probe. Normalized playback may be unavailable.", _settings.FfmpegPath, process.ExitCode); _logger.LogWarning("The ffmpeg binary '{FfmpegPath}' exited with code {ExitCode} during the startup probe. Normalized playback may be unavailable.", _settings.FfmpegPath, process.ExitCode);
return; return;
} }
@@ -195,15 +201,18 @@ internal sealed class TranscodingStartupInitializer : IHostedService
{ {
// An unpinned distribution package can change the encoder set without changing the application build, so this is reported at startup instead of surfacing as a per track playback failure. // An unpinned distribution package can change the encoder set without changing the application build, so this is reported at startup instead of surfacing as a per track playback failure.
_toolchainStatus.RecordMissingEncoders(missingEncoders); _toolchainStatus.RecordMissingEncoders(missingEncoders);
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError("The ffmpeg binary '{FfmpegPath}' is missing the encoders {MissingEncoders}. Normalized playback for those formats will be unavailable.", _settings.FfmpegPath, string.Join(", ", missingEncoders)); _logger.LogError("The ffmpeg binary '{FfmpegPath}' is missing the encoders {MissingEncoders}. Normalized playback for those formats will be unavailable.", _settings.FfmpegPath, string.Join(", ", missingEncoders));
return; return;
} }
_toolchainStatus.RecordAvailable(); _toolchainStatus.RecordAvailable();
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("The ffmpeg binary '{FfmpegPath}' provides every encoder the normalized audio pipeline uses.", _settings.FfmpegPath); _logger.LogInformation("The ffmpeg binary '{FfmpegPath}' provides every encoder the normalized audio pipeline uses.", _settings.FfmpegPath);
} }
catch (Exception exception) when (exception is Win32Exception or InvalidOperationException or IOException or UnauthorizedAccessException or NotSupportedException) catch (Exception exception) when (exception is Win32Exception or InvalidOperationException or IOException or UnauthorizedAccessException or NotSupportedException)
{ {
_toolchainStatus.RecordUnavailable(); _toolchainStatus.RecordUnavailable();
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(exception, "The ffmpeg binary '{FfmpegPath}' could not be probed. Normalized playback will be unavailable.", _settings.FfmpegPath); _logger.LogWarning(exception, "The ffmpeg binary '{FfmpegPath}' could not be probed. Normalized playback will be unavailable.", _settings.FfmpegPath);
} }
} }
@@ -121,6 +121,7 @@ internal sealed class MusicFileSystemDiscoveryJob : MediaLibraryScanJob, IMusicF
// When the library content is stored on a solid state drive, the file system reads of the scan run in parallel. // When the library content is stored on a solid state drive, the file system reads of the scan run in parallel.
bool shouldParallelizeReads = domainLibraryResult.Value.IsContentOnSsd; bool shouldParallelizeReads = domainLibraryResult.Value.IsContentOnSsd;
if (shouldParallelizeReads) if (shouldParallelizeReads)
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug("The content of the media library with Id '{LibraryId}' is stored on a solid state drive, so its file system reads will run in parallel.", LibraryId.Value); _logger.LogDebug("The content of the media library with Id '{LibraryId}' is stored on a solid state drive, so its file system reads will run in parallel.", LibraryId.Value);
// Get the files for each of the media library content locations. // Get the files for each of the media library content locations.
@@ -336,6 +337,7 @@ internal sealed class MusicFileSystemDiscoveryJob : MediaLibraryScanJob, IMusicF
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{ {
// A file might become inaccessible between enumeration and processing, so it is skipped. // A file might become inaccessible between enumeration and processing, so it is skipped.
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(ex, "Failed to read the metadata of the music file '{Path}', so it is skipped for this scan.", filesToProcess[index].Path); _logger.LogWarning(ex, "Failed to read the metadata of the music file '{Path}', so it is skipped for this scan.", filesToProcess[index].Path);
} }
}); });
@@ -120,6 +120,7 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
.Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Music) .Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Music)
&& (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))]; && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))];
if (configuredProviders.Count == 0) if (configuredProviders.Count == 0)
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("No artwork provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Music); _logger.LogWarning("No artwork provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Music);
artworkProviders.AddRange(configuredProviders); artworkProviders.AddRange(configuredProviders);
} }
@@ -129,6 +130,7 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
// When no artwork provider is available, the items must not be marked as failed to resolve, so the enrichment is skipped entirely. // When no artwork provider is available, the items must not be marked as failed to resolve, so the enrichment is skipped entirely.
if (artworkProviders.Count == 0) if (artworkProviders.Count == 0)
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("No artwork provider is configured for the media library with Id '{LibraryId}', the artwork enrichment will be skipped.", libraryId.Value); _logger.LogWarning("No artwork provider is configured for the media library with Id '{LibraryId}', the artwork enrichment will be skipped.", libraryId.Value);
return; return;
} }
@@ -414,18 +416,19 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
Result<Deleted> deleteStoredArtworkResult = deleteStoredArtwork(); Result<Deleted> deleteStoredArtworkResult = deleteStoredArtwork();
if (deleteStoredArtworkResult.IsFailure) if (deleteStoredArtworkResult.IsFailure)
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Failed to clear the stored artwork files of the {OwnerType} '{OwnerDescription}'.", ownerType, ownerDescription); _logger.LogWarning("Failed to clear the stored artwork files of the {OwnerType} '{OwnerDescription}'.", ownerType, ownerDescription);
// Some files may have been deleted before the failure, so the stored records are dropped and the owner is marked as failed, // Some files may have been deleted before the failure, so the stored records are dropped and the owner is marked as failed,
// keeping it eligible for a retry without serving the paths of the files that no longer exist. // keeping it eligible for a retry without serving the paths of the files that no longer exist.
Result<Deleted> deleteFailedEntitiesResult = await unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(ownerType, ownerId, cancellationToken).ConfigureAwait(false); Result<Deleted> deleteFailedEntitiesResult = await unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(ownerType, ownerId, cancellationToken).ConfigureAwait(false);
if (deleteFailedEntitiesResult.IsFailure) if (deleteFailedEntitiesResult.IsSuccess)
_logger.LogWarning("Failed to clear the stored artwork records of the {OwnerType} '{OwnerDescription}'.", ownerType, ownerDescription);
else
{ {
List<MusicArtworkEntity> failedArtworkEntities = [CreateArtworkEntity(ownerId, ownerType, ArtworkType.Cover, 0, null, 0, ArtworkStatus.Failed, null)]; List<MusicArtworkEntity> failedArtworkEntities = [CreateArtworkEntity(ownerId, ownerType, ArtworkType.Cover, 0, null, 0, ArtworkStatus.Failed, null)];
await PersistArtworkAsync(unitOfWork, failedArtworkEntities, cancellationToken).ConfigureAwait(false); await PersistArtworkAsync(unitOfWork, failedArtworkEntities, cancellationToken).ConfigureAwait(false);
} }
else if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Failed to clear the stored artwork records of the {OwnerType} '{OwnerDescription}'.", ownerType, ownerDescription);
DeleteTemporaryArtworks(resolution.Artworks.Select(resolvedArtwork => resolvedArtwork.Artwork)); DeleteTemporaryArtworks(resolution.Artworks.Select(resolvedArtwork => resolvedArtwork.Artwork));
return false; return false;
@@ -433,6 +436,7 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
Result<Deleted> deleteEntitiesResult = await unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(ownerType, ownerId, cancellationToken).ConfigureAwait(false); Result<Deleted> deleteEntitiesResult = await unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(ownerType, ownerId, cancellationToken).ConfigureAwait(false);
if (deleteEntitiesResult.IsFailure) if (deleteEntitiesResult.IsFailure)
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Failed to clear the stored artwork records of the {OwnerType} '{OwnerDescription}'.", ownerType, ownerDescription); _logger.LogWarning("Failed to clear the stored artwork records of the {OwnerType} '{OwnerDescription}'.", ownerType, ownerDescription);
DeleteTemporaryArtworks(resolution.Artworks.Select(resolvedArtwork => resolvedArtwork.Artwork)); DeleteTemporaryArtworks(resolution.Artworks.Select(resolvedArtwork => resolvedArtwork.Artwork));
return false; return false;
@@ -448,6 +452,7 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
Result<string> saveArtworkResult = await saveArtworkAsync(artwork, cancellationToken).ConfigureAwait(false); Result<string> saveArtworkResult = await saveArtworkAsync(artwork, cancellationToken).ConfigureAwait(false);
if (saveArtworkResult.IsFailure) if (saveArtworkResult.IsFailure)
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Failed to store the {ArtworkType} artwork of the {OwnerType} '{OwnerDescription}'.", artwork.Type, ownerType, ownerDescription); _logger.LogWarning("Failed to store the {ArtworkType} artwork of the {OwnerType} '{OwnerDescription}'.", artwork.Type, ownerType, ownerDescription);
continue; continue;
} }
@@ -558,6 +563,7 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
{ {
// A failing artwork provider must not prevent the other providers from being tried, but the failure must be surfaced for diagnostics. // A failing artwork provider must not prevent the other providers from being tried, but the failure must be surfaced for diagnostics.
hasFailed = true; hasFailed = true;
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(exception, "The artwork provider '{ProviderName}' failed while resolving the artwork of '{OwnerDescription}'.", provider.Name, ownerDescription); _logger.LogWarning(exception, "The artwork provider '{ProviderName}' failed while resolving the artwork of '{OwnerDescription}'.", provider.Name, ownerDescription);
continue; continue;
} }
@@ -601,6 +607,7 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
{ {
// A failing artwork provider must not prevent the other providers from being tried, but the failure must be surfaced for diagnostics. // A failing artwork provider must not prevent the other providers from being tried, but the failure must be surfaced for diagnostics.
hasFailed = true; hasFailed = true;
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(exception, "The artwork provider '{ProviderName}' failed while resolving the artwork of '{OwnerDescription}'.", provider.Name, ownerDescription); _logger.LogWarning(exception, "The artwork provider '{ProviderName}' failed while resolving the artwork of '{OwnerDescription}'.", provider.Name, ownerDescription);
continue; continue;
} }
@@ -105,6 +105,7 @@ internal sealed class MusicMediaLibraryScanMetadataEnricher : IMediaLibraryScanM
.Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Music) .Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Music)
&& (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))]; && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))];
if (configuredProviders.Count == 0) if (configuredProviders.Count == 0)
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("No metadata provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Music); _logger.LogWarning("No metadata provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Music);
providers.AddRange(configuredProviders); providers.AddRange(configuredProviders);
} }
@@ -193,7 +194,10 @@ internal sealed class MusicMediaLibraryScanMetadataEnricher : IMediaLibraryScanM
// A unique constraint conflict on a shared lookup such as a media contributor can happen when two scans enrich concurrently; // A unique constraint conflict on a shared lookup such as a media contributor can happen when two scans enrich concurrently;
// it must not abort the whole scan, so the artist is left unenriched and retried on the next scan, while the rest proceeds. // it must not abort the whole scan, so the artist is left unenriched and retried on the next scan, while the rest proceeds.
if (saveChangesResult.FirstError == Errors.Persistence.UniqueConstraintViolation) if (saveChangesResult.FirstError == Errors.Persistence.UniqueConstraintViolation)
{
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("The enriched metadata of the artist '{ArtistName}' could not be persisted because of a unique constraint conflict; it will be retried on the next scan.", artistEntity.Name); _logger.LogWarning("The enriched metadata of the artist '{ArtistName}' could not be persisted because of a unique constraint conflict; it will be retried on the next scan.", artistEntity.Name);
}
else else
throw new InvalidOperationException(saveChangesResult.FirstError.Description); throw new InvalidOperationException(saveChangesResult.FirstError.Description);
} }
@@ -209,7 +213,7 @@ internal sealed class MusicMediaLibraryScanMetadataEnricher : IMediaLibraryScanM
if (publishFinalProgressResult.IsFailure) if (publishFinalProgressResult.IsFailure)
throw new InvalidOperationException(publishFinalProgressResult.FirstError.Description); throw new InvalidOperationException(publishFinalProgressResult.FirstError.Description);
} }
else else if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("No metadata provider is configured for the media library with Id '{LibraryId}', the metadata enrichment will be skipped.", libraryId.Value); _logger.LogWarning("No metadata provider is configured for the media library with Id '{LibraryId}', the metadata enrichment will be skipped.", libraryId.Value);
} }
@@ -414,6 +418,7 @@ internal sealed class MusicMediaLibraryScanMetadataEnricher : IMediaLibraryScanM
catch (Exception exception) catch (Exception exception)
{ {
// A failing metadata provider must not prevent the other providers from being tried, but the failure must be surfaced for diagnostics. // A failing metadata provider must not prevent the other providers from being tried, but the failure must be surfaced for diagnostics.
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning(exception, "The metadata provider '{ProviderName}' failed while resolving a {LookupType} lookup for '{Lookup}'.", metadataProvider.Name, typeof(TLookup).Name, lookup); logger.LogWarning(exception, "The metadata provider '{ProviderName}' failed while resolving a {LookupType} lookup for '{Lookup}'.", metadataProvider.Name, typeof(TLookup).Name, lookup);
} }
} }
@@ -456,6 +461,7 @@ internal sealed class MusicMediaLibraryScanMetadataEnricher : IMediaLibraryScanM
catch (Exception exception) catch (Exception exception)
{ {
// A failing metadata provider must not prevent the other providers from being tried, but the failure must be surfaced for diagnostics. // A failing metadata provider must not prevent the other providers from being tried, but the failure must be surfaced for diagnostics.
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning(exception, "The metadata provider '{ProviderName}' failed while resolving a {LookupType} lookup for '{Lookup}'.", metadataProvider.Name, typeof(TLookup).Name, lookup); logger.LogWarning(exception, "The metadata provider '{ProviderName}' failed while resolving a {LookupType} lookup for '{Lookup}'.", metadataProvider.Name, typeof(TLookup).Name, lookup);
} }
} }
@@ -311,6 +311,7 @@ internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMe
{ {
// A music file whose tags cannot be read still contributes the metadata derived from its path, but the failure is logged, so that a // A music file whose tags cannot be read still contributes the metadata derived from its path, but the failure is logged, so that a
// systematic tagging failure of a whole library does not silently degrade every file to path only metadata. // systematic tagging failure of a whole library does not silently degrade every file to path only metadata.
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(exception, "Failed to read the embedded tags of the music file '{Path}'. Its metadata will be derived from the path only.", path); _logger.LogWarning(exception, "Failed to read the embedded tags of the music file '{Path}'. Its metadata will be derived from the path only.", path);
} }
@@ -124,6 +124,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
// When the library content is stored on a solid state drive, the file system reads of the scan run in parallel. // When the library content is stored on a solid state drive, the file system reads of the scan run in parallel.
bool shouldParallelizeReads = domainLibraryResult.Value.IsContentOnSsd; bool shouldParallelizeReads = domainLibraryResult.Value.IsContentOnSsd;
if (shouldParallelizeReads) if (shouldParallelizeReads)
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug("The content of the media library with Id '{LibraryId}' is stored on a solid state drive, so its file system reads will run in parallel.", LibraryId.Value); _logger.LogDebug("The content of the media library with Id '{LibraryId}' is stored on a solid state drive, so its file system reads will run in parallel.", LibraryId.Value);
// Get the files for each of the media library content locations. // Get the files for each of the media library content locations.
@@ -261,6 +262,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
} }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(ex, "Failed to enumerate the files of the directory '{DirectoryPath}', so its files are skipped for this scan.", currentDirectory.FullName); _logger.LogWarning(ex, "Failed to enumerate the files of the directory '{DirectoryPath}', so its files are skipped for this scan.", currentDirectory.FullName);
} }
@@ -289,6 +291,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{ {
// A file might become inaccessible between enumeration and processing, so the remaining files of the directory are skipped. // A file might become inaccessible between enumeration and processing, so the remaining files of the directory are skipped.
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(ex, "Failed to read the metadata of the files of the directory '{DirectoryPath}', so the remaining files of the directory are skipped for this scan.", currentDirectory.FullName); _logger.LogWarning(ex, "Failed to read the metadata of the files of the directory '{DirectoryPath}', so the remaining files of the directory are skipped for this scan.", currentDirectory.FullName);
} }
} }
@@ -301,6 +304,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
} }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(ex, "Failed to enumerate the subdirectories of the directory '{DirectoryPath}', so its subtree is skipped for this scan.", currentDirectory.FullName); _logger.LogWarning(ex, "Failed to enumerate the subdirectories of the directory '{DirectoryPath}', so its subtree is skipped for this scan.", currentDirectory.FullName);
} }
@@ -316,6 +320,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
} }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(ex, "Failed to process the subdirectories of the directory '{DirectoryPath}', so the remaining subdirectories are skipped for this scan.", currentDirectory.FullName); _logger.LogWarning(ex, "Failed to process the subdirectories of the directory '{DirectoryPath}', so the remaining subdirectories are skipped for this scan.", currentDirectory.FullName);
} }
} }
@@ -350,6 +355,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{ {
// A file might become inaccessible between enumeration and processing, so it is skipped. // A file might become inaccessible between enumeration and processing, so it is skipped.
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(ex, "Failed to read the metadata of the book file '{Path}', so it is skipped for this scan.", filesToProcess[index].FullName); _logger.LogWarning(ex, "Failed to read the metadata of the book file '{Path}', so it is skipped for this scan.", filesToProcess[index].FullName);
} }
}); });
@@ -105,6 +105,7 @@ internal sealed class BooksMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
.Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Book) .Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Book)
&& (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))]; && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))];
if (configuredProviders.Count == 0) if (configuredProviders.Count == 0)
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("No artwork provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book); _logger.LogWarning("No artwork provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book);
artworkProviders.AddRange(configuredProviders); artworkProviders.AddRange(configuredProviders);
} }
@@ -176,7 +177,7 @@ internal sealed class BooksMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
lastPath = booksPage[^1].Path; lastPath = booksPage[^1].Path;
} }
} }
else else if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("No artwork provider is configured for the media library with Id '{LibraryId}', the artwork enrichment will be skipped.", libraryId.Value); _logger.LogWarning("No artwork provider is configured for the media library with Id '{LibraryId}', the artwork enrichment will be skipped.", libraryId.Value);
} }
@@ -103,6 +103,7 @@ internal sealed class BooksMediaLibraryScanMetadataEnricher : IMediaLibraryScanM
&& provider.SupportedLibraryTypes.Contains(LibraryType.Book) && provider.SupportedLibraryTypes.Contains(LibraryType.Book)
&& (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))]; && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))];
if (configuredProviders.Count == 0) if (configuredProviders.Count == 0)
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("No metadata provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book); _logger.LogWarning("No metadata provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book);
providers.AddRange(configuredProviders); providers.AddRange(configuredProviders);
} }
@@ -180,7 +181,7 @@ internal sealed class BooksMediaLibraryScanMetadataEnricher : IMediaLibraryScanM
lastPath = booksPage[^1].Path; lastPath = booksPage[^1].Path;
} }
} }
else else if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("No metadata provider is configured for the media library with Id '{LibraryId}', the metadata enrichment will be skipped.", libraryId.Value); _logger.LogWarning("No metadata provider is configured for the media library with Id '{LibraryId}', the metadata enrichment will be skipped.", libraryId.Value);
} }
@@ -68,6 +68,7 @@ internal sealed class MediaLibraryScanProcessorJob : BackgroundService
catch (Exception exception) catch (Exception exception)
{ {
// A scan that fails must never stop the scans that are queued behind it, so its failure is logged and the queue keeps draining. // A scan that fails must never stop the scans that are queued behind it, so its failure is logged and the queue keeps draining.
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "Failed to process the media library scan '{ScanId}'.", compositeId.ScanId.Value); _logger.LogError(exception, "Failed to process the media library scan '{ScanId}'.", compositeId.ScanId.Value);
} }
} }
@@ -105,6 +106,7 @@ internal sealed class MediaLibraryScanProcessorJob : BackgroundService
compositeId.ScanId.Value, shouldTrackEntities: false, cancellationToken: linkedSource.Token).ConfigureAwait(false); compositeId.ScanId.Value, shouldTrackEntities: false, cancellationToken: linkedSource.Token).ConfigureAwait(false);
if (getLibraryScanResult.IsFailure) if (getLibraryScanResult.IsFailure)
{ {
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError("Failed to read the media library scan '{ScanId}': {Error}", compositeId.ScanId.Value, getLibraryScanResult.FirstError.Description); _logger.LogError("Failed to read the media library scan '{ScanId}': {Error}", compositeId.ScanId.Value, getLibraryScanResult.FirstError.Description);
return; return;
} }
@@ -142,12 +144,14 @@ internal sealed class MediaLibraryScanProcessorJob : BackgroundService
rootJob = startScanResult.Value; rootJob = startScanResult.Value;
} }
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("Started the media library scan '{ScanId}' of the media library '{LibraryId}'.", compositeId.ScanId.Value, libraryScan.LibraryId.Value); _logger.LogInformation("Started the media library scan '{ScanId}' of the media library '{LibraryId}'.", compositeId.ScanId.Value, libraryScan.LibraryId.Value);
// The file system discovery job is the only top level job of the scan job graph, and every job awaits its children, so awaiting it // The file system discovery job is the only top level job of the scan job graph, and every job awaits its children, so awaiting it
// completes the entire scan. The next queued scan is only dequeued once this call returns. // completes the entire scan. The next queued scan is only dequeued once this call returns.
await rootJob.ExecuteAsync(Guid.CreateVersion7(), new { }, linkedSource.Token).ConfigureAwait(false); await rootJob.ExecuteAsync(Guid.CreateVersion7(), new { }, linkedSource.Token).ConfigureAwait(false);
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("Completed the media library scan '{ScanId}' of the media library '{LibraryId}'.", compositeId.ScanId.Value, libraryScan.LibraryId.Value); _logger.LogInformation("Completed the media library scan '{ScanId}' of the media library '{LibraryId}'.", compositeId.ScanId.Value, libraryScan.LibraryId.Value);
} }
catch (OperationCanceledException) catch (OperationCanceledException)
@@ -158,10 +162,10 @@ internal sealed class MediaLibraryScanProcessorJob : BackgroundService
{ {
// An unexpected preparation failure must still leave the scan failed instead of pending forever, and must not affect the scans queued behind it. // An unexpected preparation failure must still leave the scan failed instead of pending forever, and must not affect the scans queued behind it.
// The failure is reported without a cancellation token, because the scan token may already be cancelled and the report must still be published. // The failure is reported without a cancellation token, because the scan token may already be cancelled and the report must still be published.
if (libraryId is null) if (libraryId is not null)
_logger.LogError(exception, "Failed to process the media library scan '{ScanId}'.", compositeId.ScanId.Value);
else
await ReportScanFailureAsync(compositeId, libraryId, exception, CancellationToken.None).ConfigureAwait(false); await ReportScanFailureAsync(compositeId, libraryId, exception, CancellationToken.None).ConfigureAwait(false);
else if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "Failed to process the media library scan '{ScanId}'.", compositeId.ScanId.Value);
} }
} }
@@ -175,6 +179,7 @@ internal sealed class MediaLibraryScanProcessorJob : BackgroundService
/// <returns>A task that represents the asynchronous operation.</returns> /// <returns>A task that represents the asynchronous operation.</returns>
private async Task ReportScanFailureAsync(MediaLibraryScanCompositeId compositeId, LibraryId libraryId, Exception exception, CancellationToken cancellationToken) private async Task ReportScanFailureAsync(MediaLibraryScanCompositeId compositeId, LibraryId libraryId, Exception exception, CancellationToken cancellationToken)
{ {
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "Failed to start the media library scan '{ScanId}'.", compositeId.ScanId.Value); _logger.LogError(exception, "Failed to start the media library scan '{ScanId}'.", compositeId.ScanId.Value);
await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, libraryId, compositeId, exception, cancellationToken).ConfigureAwait(false); await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, libraryId, compositeId, exception, cancellationToken).ConfigureAwait(false);
} }
@@ -186,6 +186,7 @@ internal sealed class BookReadingService : IBookReadingService
} }
catch (Exception exception) catch (Exception exception)
{ {
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "Failed to produce the resource '{ResourceKey}' of the book '{BookId}'.", resourceKey, bookId); _logger.LogError(exception, "Failed to produce the resource '{ResourceKey}' of the book '{BookId}'.", resourceKey, bookId);
return Error.Failure(code: "Reading.ResourceProductionFailed", description: "The resource of the book could not be produced."); return Error.Failure(code: "Reading.ResourceProductionFailed", description: "The resource of the book could not be produced.");
} }
@@ -335,6 +336,7 @@ internal sealed class BookReadingService : IBookReadingService
} }
catch (Exception exception) catch (Exception exception)
{ {
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "Failed to open the book '{BookId}' for reading.", bookId); _logger.LogError(exception, "Failed to open the book '{BookId}' for reading.", bookId);
return Error.Failure(code: "Reading.ExtractionFailed", description: "The book could not be opened for reading."); return Error.Failure(code: "Reading.ExtractionFailed", description: "The book could not be opened for reading.");
} }
@@ -56,6 +56,7 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
protected override async Task ExecuteAsync(CancellationToken stoppingToken) protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{ {
foreach (PluginLoadErrorDto loadError in _loadErrors) foreach (PluginLoadErrorDto loadError in _loadErrors)
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Plugin load failure: {LoadError}", loadError.ErrorMessage); _logger.LogWarning("Plugin load failure: {LoadError}", loadError.ErrorMessage);
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
@@ -78,6 +79,7 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
}; };
Result<Updated> upsertResult = await unitOfWork.PluginRepository.UpsertAsync(pluginEntity, stoppingToken).ConfigureAwait(false); Result<Updated> upsertResult = await unitOfWork.PluginRepository.UpsertAsync(pluginEntity, stoppingToken).ConfigureAwait(false);
if (upsertResult.IsFailure) if (upsertResult.IsFailure)
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError("Failed to persist the detection of plugin '{PluginName}': {Error}", plugin.Name, upsertResult.FirstError.Description); _logger.LogError("Failed to persist the detection of plugin '{PluginName}': {Error}", plugin.Name, upsertResult.FirstError.Description);
} }
@@ -99,6 +101,7 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
}; };
Result<Updated> upsertResult = await unitOfWork.PluginRepository.UpsertAsync(pluginEntity, stoppingToken).ConfigureAwait(false); Result<Updated> upsertResult = await unitOfWork.PluginRepository.UpsertAsync(pluginEntity, stoppingToken).ConfigureAwait(false);
if (upsertResult.IsFailure) if (upsertResult.IsFailure)
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError("Failed to persist the detection of plugin '{PluginName}': {Error}", loadError.AssemblyName, upsertResult.FirstError.Description); _logger.LogError("Failed to persist the detection of plugin '{PluginName}': {Error}", loadError.AssemblyName, upsertResult.FirstError.Description);
} }
@@ -116,9 +119,11 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
continue; continue;
Result<Deleted> deleteResult = await unitOfWork.PluginRepository.DeleteByIdAsync(plugin.Id, stoppingToken).ConfigureAwait(false); Result<Deleted> deleteResult = await unitOfWork.PluginRepository.DeleteByIdAsync(plugin.Id, stoppingToken).ConfigureAwait(false);
if (deleteResult.IsFailure) if (deleteResult.IsFailure)
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError("Failed to remove the stale detection of plugin '{PluginName}': {Error}", plugin.Name, deleteResult.FirstError.Description); _logger.LogError("Failed to remove the stale detection of plugin '{PluginName}': {Error}", plugin.Name, deleteResult.FirstError.Description);
Result<Deleted> removeConfigurationsResult = await providerConfigurationStore.RemoveProviderConfigurationsAsync(plugin.Id, stoppingToken).ConfigureAwait(false); Result<Deleted> removeConfigurationsResult = await providerConfigurationStore.RemoveProviderConfigurationsAsync(plugin.Id, stoppingToken).ConfigureAwait(false);
if (removeConfigurationsResult.IsFailure) if (removeConfigurationsResult.IsFailure)
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError("Failed to remove the provider configurations of the removed plugin '{PluginName}': {Error}", plugin.Name, removeConfigurationsResult.FirstError.Description); _logger.LogError("Failed to remove the provider configurations of the removed plugin '{PluginName}': {Error}", plugin.Name, removeConfigurationsResult.FirstError.Description);
} }
} }
@@ -135,6 +140,7 @@ internal sealed class PluginDetectionSyncJob : BackgroundService
{ {
Result<Success> ensureResult = await providerConfigurationStore.EnsureProviderConfigurationsAsync(library.Id, library.LibraryType, stoppingToken).ConfigureAwait(false); Result<Success> ensureResult = await providerConfigurationStore.EnsureProviderConfigurationsAsync(library.Id, library.LibraryType, stoppingToken).ConfigureAwait(false);
if (ensureResult.IsFailure) if (ensureResult.IsFailure)
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError("Failed to seed the provider configurations of the media library '{LibraryTitle}': {Error}", library.Title, ensureResult.FirstError.Description); _logger.LogError("Failed to seed the provider configurations of the media library '{LibraryTitle}': {Error}", library.Title, ensureResult.FirstError.Description);
} }
} }
@@ -44,6 +44,7 @@ internal sealed class PluginSettingsStore : IPluginSettingsStore
Result<PluginEntity?> getPluginResult = await _unitOfWork.PluginRepository.GetByIdAsync(pluginId, cancellationToken: cancellationToken).ConfigureAwait(false); Result<PluginEntity?> getPluginResult = await _unitOfWork.PluginRepository.GetByIdAsync(pluginId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getPluginResult.IsFailure) if (getPluginResult.IsFailure)
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Failed to read the settings of the plugin with Id '{PluginId}': {Error}", pluginId, getPluginResult.FirstError.Description); _logger.LogWarning("Failed to read the settings of the plugin with Id '{PluginId}': {Error}", pluginId, getPluginResult.FirstError.Description);
return null; return null;
} }
@@ -133,6 +133,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
Result<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await unitOfWork.ScheduledJobRepository.GetActiveOrRunningAsync(cancellationToken).ConfigureAwait(false); Result<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await unitOfWork.ScheduledJobRepository.GetActiveOrRunningAsync(cancellationToken).ConfigureAwait(false);
if (getScheduledJobsResult.IsFailure) if (getScheduledJobsResult.IsFailure)
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Failed to read the scheduled jobs to decide whether the themes must be synchronized: {Error}", getScheduledJobsResult.FirstError.Description); _logger.LogWarning("Failed to read the scheduled jobs to decide whether the themes must be synchronized: {Error}", getScheduledJobsResult.FirstError.Description);
return; return;
} }
@@ -170,6 +171,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false); .GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
if (getScheduledJobsResult.IsFailure) if (getScheduledJobsResult.IsFailure)
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Failed to read the scheduled jobs to ensure the technical data cleanup job: {Error}", getScheduledJobsResult.FirstError.Description); _logger.LogWarning("Failed to read the scheduled jobs to ensure the technical data cleanup job: {Error}", getScheduledJobsResult.FirstError.Description);
return; return;
} }
@@ -196,12 +198,14 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
Result<Created> insertScheduledJobResult = await unitOfWork.ScheduledJobRepository.InsertAsync(technicalDataCleanupJob, cancellationToken).ConfigureAwait(false); Result<Created> insertScheduledJobResult = await unitOfWork.ScheduledJobRepository.InsertAsync(technicalDataCleanupJob, cancellationToken).ConfigureAwait(false);
if (insertScheduledJobResult.IsFailure) if (insertScheduledJobResult.IsFailure)
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Failed to insert the technical data cleanup scheduled job: {Error}", insertScheduledJobResult.FirstError.Description); _logger.LogWarning("Failed to insert the technical data cleanup scheduled job: {Error}", insertScheduledJobResult.FirstError.Description);
return; return;
} }
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure) if (saveChangesResult.IsFailure)
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Failed to save the technical data cleanup scheduled job: {Error}", saveChangesResult.FirstError.Description); _logger.LogWarning("Failed to save the technical data cleanup scheduled job: {Error}", saveChangesResult.FirstError.Description);
return; return;
} }
@@ -226,6 +230,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
Result<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await unitOfWork.ScheduledJobRepository.GetActiveOrRunningAsync(cancellationToken).ConfigureAwait(false); Result<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await unitOfWork.ScheduledJobRepository.GetActiveOrRunningAsync(cancellationToken).ConfigureAwait(false);
if (getScheduledJobsResult.IsFailure) if (getScheduledJobsResult.IsFailure)
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("Failed to read the scheduled jobs to resume: {Error}", getScheduledJobsResult.FirstError.Description); _logger.LogWarning("Failed to read the scheduled jobs to resume: {Error}", getScheduledJobsResult.FirstError.Description);
return; return;
} }
@@ -311,6 +316,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
catch (Exception exception) catch (Exception exception)
{ {
// Failures of a single run are handled inside RunScheduledJobAsync, so an exception reaching this point is unexpected and ends the cycle. // Failures of a single run are handled inside RunScheduledJobAsync, so an exception reaching this point is unexpected and ends the cycle.
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "The execution cycle of the scheduled job '{ScheduledJobId}' failed.", scheduledJobId.Value); _logger.LogError(exception, "The execution cycle of the scheduled job '{ScheduledJobId}' failed.", scheduledJobId.Value);
} }
finally finally
@@ -335,6 +341,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
catch (OperationCanceledException) { } catch (OperationCanceledException) { }
catch (Exception exception) catch (Exception exception)
{ {
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "The one time execution of the scheduled job '{ScheduledJobId}' failed.", scheduledJobId.Value); _logger.LogError(exception, "The one time execution of the scheduled job '{ScheduledJobId}' failed.", scheduledJobId.Value);
} }
} }
@@ -360,6 +367,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
} }
catch (Exception exception) catch (Exception exception)
{ {
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "The execution of the scheduled job '{ScheduledJobId}' failed unexpectedly.", scheduledJobId.Value); _logger.LogError(exception, "The execution of the scheduled job '{ScheduledJobId}' failed unexpectedly.", scheduledJobId.Value);
await ReconcileInterruptedRunAsync(scheduledJobId, CancellationToken.None).ConfigureAwait(false); await ReconcileInterruptedRunAsync(scheduledJobId, CancellationToken.None).ConfigureAwait(false);
} }
@@ -410,6 +418,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
IScheduledTaskExecutor taskExecutor = taskExecutorFactory.CreateExecutor(scheduledJob.TaskType); IScheduledTaskExecutor taskExecutor = taskExecutorFactory.CreateExecutor(scheduledJob.TaskType);
Result<Success> executePayloadResult = await taskExecutor.ExecutePayloadAsync(scheduledJob, cancellationToken).ConfigureAwait(false); Result<Success> executePayloadResult = await taskExecutor.ExecutePayloadAsync(scheduledJob, cancellationToken).ConfigureAwait(false);
if (executePayloadResult.IsFailure) if (executePayloadResult.IsFailure)
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("The task of the scheduled job '{ScheduledJobName}' failed: {Error}", scheduledJob.Name, executePayloadResult.FirstError.Description); _logger.LogWarning("The task of the scheduled job '{ScheduledJobName}' failed: {Error}", scheduledJob.Name, executePayloadResult.FirstError.Description);
} }
catch (OperationCanceledException) catch (OperationCanceledException)
@@ -418,6 +427,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
} }
catch (Exception exception) catch (Exception exception)
{ {
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "The task of the scheduled job '{ScheduledJobName}' threw an exception.", scheduledJob.Name); _logger.LogError(exception, "The task of the scheduled job '{ScheduledJobName}' threw an exception.", scheduledJob.Name);
} }
@@ -461,6 +471,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
catch (Exception exception) catch (Exception exception)
{ {
// The completion failed after the execution was persisted as running, so the interrupted run is reconciled directly. // The completion failed after the execution was persisted as running, so the interrupted run is reconciled directly.
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(exception, "Failed to complete the execution of the scheduled job '{ScheduledJobId}'.", scheduledJob.Id.Value); _logger.LogError(exception, "Failed to complete the execution of the scheduled job '{ScheduledJobId}'.", scheduledJob.Id.Value);
await ReconcileInterruptedRunAsync(scheduledJob.Id, CancellationToken.None).ConfigureAwait(false); await ReconcileInterruptedRunAsync(scheduledJob.Id, CancellationToken.None).ConfigureAwait(false);
} }
@@ -513,6 +524,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure) if (saveChangesResult.IsFailure)
throw new InvalidOperationException(saveChangesResult.FirstError.Description); throw new InvalidOperationException(saveChangesResult.FirstError.Description);
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("The interrupted execution of the scheduled job '{ScheduledJobName}' was closed.", scheduledJob.Name); _logger.LogInformation("The interrupted execution of the scheduled job '{ScheduledJobName}' was closed.", scheduledJob.Name);
return reconciledStatus; return reconciledStatus;
} }
@@ -522,6 +534,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
} }
catch (Exception exception) catch (Exception exception)
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(exception, "Failed to reconcile the interrupted execution of the scheduled job '{ScheduledJobId}'.", scheduledJobId.Value); _logger.LogWarning(exception, "Failed to reconcile the interrupted execution of the scheduled job '{ScheduledJobId}'.", scheduledJobId.Value);
return ScheduledJobStatus.Added; return ScheduledJobStatus.Added;
} }
@@ -46,6 +46,7 @@ public class CleanScheduledJobExecutionHistoryTaskExecutor : IScheduledTaskExecu
if (deleteResult.IsFailure) if (deleteResult.IsFailure)
return deleteResult.Errors; return deleteResult.Errors;
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("Cleaned the execution history of the scheduled jobs on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name); _logger.LogInformation("Cleaned the execution history of the scheduled jobs on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name);
return Result.Success; return Result.Success;
} }
@@ -106,6 +106,7 @@ public class MediaLibraryScanTaskExecutor : IScheduledTaskExecutor
foreach (IDomainEvent domainEvent in domainEvents) foreach (IDomainEvent domainEvent in domainEvents)
await _domainEventPublisher.PublishAsync(domainEvent, cancellationToken).ConfigureAwait(false); await _domainEventPublisher.PublishAsync(domainEvent, cancellationToken).ConfigureAwait(false);
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("Scanned all enabled media libraries on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name); _logger.LogInformation("Scanned all enabled media libraries on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name);
return Result.Success; return Result.Success;
} }
@@ -46,6 +46,7 @@ public class RepairThemesTaskExecutor : IScheduledTaskExecutor
try try
{ {
await ThemeSynchronizer.SynchronizeAsync(_themeService, _unitOfWork, _logger, cancellationToken).ConfigureAwait(false); await ThemeSynchronizer.SynchronizeAsync(_themeService, _unitOfWork, _logger, cancellationToken).ConfigureAwait(false);
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("Repaired the themes on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name); _logger.LogInformation("Repaired the themes on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name);
return Result.Success; return Result.Success;
} }
@@ -55,6 +56,7 @@ public class RepairThemesTaskExecutor : IScheduledTaskExecutor
} }
catch (Exception exception) catch (Exception exception)
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(exception, "The themes could not be repaired on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name); _logger.LogWarning(exception, "The themes could not be repaired on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name);
return Error.Failure(description: nameof(RepairThemesTaskExecutor)); return Error.Failure(description: nameof(RepairThemesTaskExecutor));
} }
@@ -40,6 +40,7 @@ public class TechnicalDataCleanupTaskExecutor : IScheduledTaskExecutor
if (failInterruptedScansResult.IsFailure) if (failInterruptedScansResult.IsFailure)
return failInterruptedScansResult.Errors; return failInterruptedScansResult.Errors;
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("Cleaned the technical data on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name); _logger.LogInformation("Cleaned the technical data on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name);
return Result.Success; return Result.Success;
} }
@@ -45,6 +45,7 @@ public class TemporaryFilesCleanupTaskExecutor : IScheduledTaskExecutor
!temporaryDirectoryRoot.StartsWith(applicationBaseDirectory, comparison) || !temporaryDirectoryRoot.StartsWith(applicationBaseDirectory, comparison) ||
string.Equals(temporaryDirectoryRoot, applicationBaseDirectory, comparison)) string.Equals(temporaryDirectoryRoot, applicationBaseDirectory, comparison))
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning("The temporary directory to clean could not be resolved safely, so the scheduled job '{ScheduledJobName}' was skipped.", scheduledJob.Name); _logger.LogWarning("The temporary directory to clean could not be resolved safely, so the scheduled job '{ScheduledJobName}' was skipped.", scheduledJob.Name);
return Result.Success; return Result.Success;
} }
@@ -54,11 +55,13 @@ public class TemporaryFilesCleanupTaskExecutor : IScheduledTaskExecutor
if (Directory.Exists(temporaryDirectoryRoot)) if (Directory.Exists(temporaryDirectoryRoot))
Directory.Delete(temporaryDirectoryRoot, recursive: true); Directory.Delete(temporaryDirectoryRoot, recursive: true);
Directory.CreateDirectory(temporaryDirectoryRoot); Directory.CreateDirectory(temporaryDirectoryRoot);
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("Emptied the temporary directory '{TemporaryDirectory}'.", temporaryDirectoryRoot); _logger.LogInformation("Emptied the temporary directory '{TemporaryDirectory}'.", temporaryDirectoryRoot);
return Result.Success; return Result.Success;
} }
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{ {
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(exception, "The temporary directory '{TemporaryDirectory}' could not be emptied.", temporaryDirectoryRoot); _logger.LogWarning(exception, "The temporary directory '{TemporaryDirectory}' could not be emptied.", temporaryDirectoryRoot);
return await Task.FromResult(Error.Failure(description: nameof(TemporaryFilesCleanupTaskExecutor))); return await Task.FromResult(Error.Failure(description: nameof(TemporaryFilesCleanupTaskExecutor)));
} }
@@ -832,6 +832,7 @@ public sealed class ThemeService : IThemeService
} }
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{ {
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug(exception, "Could not remove stale theme staging path {StagingPath}.", path); _logger.LogDebug(exception, "Could not remove stale theme staging path {StagingPath}.", path);
} }
} }
@@ -35,6 +35,7 @@ internal static class ThemeSynchronizer
Result<PaginatedResultDto<ThemeEntity>> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false); Result<PaginatedResultDto<ThemeEntity>> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
if (getThemesResult.IsFailure) if (getThemesResult.IsFailure)
{ {
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning("Failed to read the installed themes: {Error}", getThemesResult.FirstError.Description); logger.LogWarning("Failed to read the installed themes: {Error}", getThemesResult.FirstError.Description);
return; return;
} }
@@ -47,6 +48,7 @@ internal static class ThemeSynchronizer
Result<ThemeManifestDto> manifestResult = await themeService.ReadManifestFromArchiveAsync(archivePath, cancellationToken).ConfigureAwait(false); Result<ThemeManifestDto> manifestResult = await themeService.ReadManifestFromArchiveAsync(archivePath, cancellationToken).ConfigureAwait(false);
if (manifestResult.IsFailure) if (manifestResult.IsFailure)
{ {
if (logger.IsEnabled(LogLevel.Warning))
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;
} }
@@ -74,6 +76,7 @@ internal static class ThemeSynchronizer
Result<ThemeManifestDto> installResult = await themeService.InstallAsync(archive, cancellationToken).ConfigureAwait(false); Result<ThemeManifestDto> installResult = await themeService.InstallAsync(archive, cancellationToken).ConfigureAwait(false);
if (installResult.IsFailure) if (installResult.IsFailure)
{ {
if (logger.IsEnabled(LogLevel.Warning))
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;
} }
@@ -86,6 +89,7 @@ internal static class ThemeSynchronizer
existingTheme.Version = manifestResult.Value.Version; existingTheme.Version = manifestResult.Value.Version;
Result<Updated> updateResult = await unitOfWork.ThemeRepository.UpdateAsync(existingTheme, cancellationToken).ConfigureAwait(false); Result<Updated> updateResult = await unitOfWork.ThemeRepository.UpdateAsync(existingTheme, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure) if (updateResult.IsFailure)
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning("Failed to update the version of theme '{ThemeId}': {Error}", existingTheme.ThemeId, updateResult.FirstError.Description); logger.LogWarning("Failed to update the version of theme '{ThemeId}': {Error}", existingTheme.ThemeId, updateResult.FirstError.Description);
} }
continue; continue;
@@ -105,17 +109,19 @@ internal static class ThemeSynchronizer
}; };
Result<Created> insertResult = await unitOfWork.ThemeRepository.InsertAsync(themeEntity, cancellationToken).ConfigureAwait(false); Result<Created> insertResult = await unitOfWork.ThemeRepository.InsertAsync(themeEntity, cancellationToken).ConfigureAwait(false);
if (insertResult.IsFailure) if (insertResult.IsSuccess)
logger.LogWarning("Failed to persist the detection of theme '{ThemeId}': {Error}", manifestResult.Value.Id, insertResult.FirstError.Description);
else
themes.Add(themeEntity); themes.Add(themeEntity);
else if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning("Failed to persist the detection of theme '{ThemeId}': {Error}", manifestResult.Value.Id, insertResult.FirstError.Description);
} }
catch (IOException exception) catch (IOException exception)
{ {
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning(exception, "Failed to install bundled theme '{ThemeId}': the theme files could not be written.", manifestResult.Value.Id); logger.LogWarning(exception, "Failed to install bundled theme '{ThemeId}': the theme files could not be written.", manifestResult.Value.Id);
} }
catch (UnauthorizedAccessException exception) catch (UnauthorizedAccessException exception)
{ {
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning(exception, "Failed to install bundled theme '{ThemeId}': access to the theme files was denied.", manifestResult.Value.Id); logger.LogWarning(exception, "Failed to install bundled theme '{ThemeId}': access to the theme files was denied.", manifestResult.Value.Id);
} }
} }
@@ -155,6 +161,7 @@ internal static class ThemeSynchronizer
if (restoreResult.IsSuccess) if (restoreResult.IsSuccess)
continue; continue;
if (logger.IsEnabled(LogLevel.Warning))
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; // At least one bundled theme must always remain available, so the application never ends up without any theme;
@@ -162,6 +169,7 @@ internal static class ThemeSynchronizer
int availableBundledThemes = themes.Count(availableTheme => !availableTheme.IsDeleted && availableTheme.InstallSource == ThemeInstallSource.Bundled); int availableBundledThemes = themes.Count(availableTheme => !availableTheme.IsDeleted && availableTheme.InstallSource == ThemeInstallSource.Bundled);
if (availableBundledThemes <= 1) if (availableBundledThemes <= 1)
{ {
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning("Bundled theme '{ThemeId}' is the last remaining bundled theme and its files could not be restored, so it is kept.", brokenTheme.ThemeId); 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; continue;
} }
@@ -171,15 +179,18 @@ internal static class ThemeSynchronizer
brokenTheme.IsCurrent = null; brokenTheme.IsCurrent = null;
Result<Updated> updateResult = await unitOfWork.ThemeRepository.UpdateAsync(brokenTheme, cancellationToken).ConfigureAwait(false); Result<Updated> updateResult = await unitOfWork.ThemeRepository.UpdateAsync(brokenTheme, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure) if (updateResult.IsFailure)
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, updateResult.FirstError.Description); logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, updateResult.FirstError.Description);
} }
else else
{ {
// A user theme has no shipped archive to restore from, so damage is permanent and the theme is removed entirely. // A user theme has no shipped archive to restore from, so damage is permanent and the theme is removed entirely.
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning("The stored files of user theme '{ThemeId}' are missing, so the theme is deleted.", brokenTheme.ThemeId); logger.LogWarning("The stored files of user theme '{ThemeId}' are missing, so the theme is deleted.", brokenTheme.ThemeId);
brokenTheme.IsCurrent = null; brokenTheme.IsCurrent = null;
Result<Deleted> deleteResult = await unitOfWork.ThemeRepository.DeleteByIdAsync(brokenTheme.Id, cancellationToken).ConfigureAwait(false); Result<Deleted> deleteResult = await unitOfWork.ThemeRepository.DeleteByIdAsync(brokenTheme.Id, cancellationToken).ConfigureAwait(false);
if (deleteResult.IsFailure) if (deleteResult.IsFailure)
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, deleteResult.FirstError.Description); logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, deleteResult.FirstError.Description);
} }
} }
@@ -190,6 +201,7 @@ internal static class ThemeSynchronizer
catch (Exception exception) catch (Exception exception)
{ {
// Repairing a broken theme is best effort: an unexpected failure on one theme must not crash the host, so it is logged and the remaining broken themes are still processed. // Repairing a broken theme is best effort: an unexpected failure on one theme must not crash the host, so it is logged and the remaining broken themes are still processed.
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning(exception, "Failed to repair the broken theme '{ThemeId}'.", brokenTheme.ThemeId); logger.LogWarning(exception, "Failed to repair the broken theme '{ThemeId}'.", brokenTheme.ThemeId);
} }
} }
@@ -222,6 +234,7 @@ internal static class ThemeSynchronizer
defaultTheme.IsCurrent = true; defaultTheme.IsCurrent = true;
Result<Updated> updateResult = await unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken).ConfigureAwait(false); Result<Updated> updateResult = await unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure) if (updateResult.IsFailure)
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning("Failed to activate theme '{ThemeId}': {Error}", defaultTheme.ThemeId, updateResult.FirstError.Description); logger.LogWarning("Failed to activate theme '{ThemeId}': {Error}", defaultTheme.ThemeId, updateResult.FirstError.Description);
} }
} }
@@ -76,6 +76,7 @@ public static class PresentationApiLayerServices
.FirstOrDefault()?.Split(',')[0].Trim() .FirstOrDefault()?.Split(',')[0].Trim()
?? onRejectedContext.HttpContext.Connection.RemoteIpAddress?.ToString() ?? onRejectedContext.HttpContext.Connection.RemoteIpAddress?.ToString()
?? "unknown"; ?? "unknown";
if (logger.IsEnabled(LogLevel.Warning))
logger.LogWarning( logger.LogWarning(
"Rate limit exceeded. IP: {IpAddress}, Route: {Route}, Lease Acquired: {IsAcquired}", "Rate limit exceeded. IP: {IpAddress}, Route: {Route}, Lease Acquired: {IsAcquired}",
clientIp, clientIp,
@@ -80,6 +80,7 @@ public class EventualConsistencyMiddleware
} }
catch (Exception ex) // The response is already complete, so this failure cannot reach the client. It is logged, and the transaction is still closed by the rollback below. catch (Exception ex) // The response is already complete, so this failure cannot reach the client. It is logged, and the transaction is still closed by the rollback below.
{ {
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(ex, "Failed to complete the request transaction for {Path}", context.Request.Path); _logger.LogError(ex, "Failed to complete the request transaction for {Path}", context.Request.Path);
} }
finally finally
@@ -93,6 +94,7 @@ public class EventualConsistencyMiddleware
} }
catch (Exception ex) catch (Exception ex)
{ {
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(ex, "Failed to roll back the request transaction for {Path}", context.Request.Path); _logger.LogError(ex, "Failed to roll back the request transaction for {Path}", context.Request.Path);
} }
} }
@@ -53,6 +53,7 @@ public class ExceptionHandlingMiddleware
// Once the response has started, it is no longer possible to replace it with a ProblemDetails response. // Once the response has started, it is no longer possible to replace it with a ProblemDetails response.
if (context.Response.HasStarted) if (context.Response.HasStarted)
throw; throw;
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(ex, "Unhandled exception occurred while processing request {Method} {Path}", context.Request.Method, context.Request.Path); _logger.LogError(ex, "Unhandled exception occurred while processing request {Method} {Path}", context.Request.Method, context.Request.Path);
await WriteProblemDetailsResponseAsync(context).ConfigureAwait(false); await WriteProblemDetailsResponseAsync(context).ConfigureAwait(false);
} }
@@ -63,6 +63,7 @@ public class ExceptionHandlingMiddleware
} }
catch (Exception ex) // Other cases. catch (Exception ex) // Other cases.
{ {
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError(ex, "Unexpected exception occurred: {Message}", ex.Message); _logger.LogError(ex, "Unexpected exception occurred: {Message}", ex.Message);
// Once the response has started, its status and headers are already on the wire, so they can no longer be replaced: the connection // Once the response has started, its status and headers are already on the wire, so they can no longer be replaced: the connection
// is aborted instead, so that the client sees a failed transfer rather than a success response it cannot trust. // is aborted instead, so that the client sees a failed transfer rather than a success response it cannot trust.
@@ -105,6 +106,7 @@ public class ExceptionHandlingMiddleware
private async Task HandleApiExceptionAsync(HttpContext context, ApiException apiException) private async Task HandleApiExceptionAsync(HttpContext context, ApiException apiException)
{ {
// Log all available details for debugging/monitoring. // Log all available details for debugging/monitoring.
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError( _logger.LogError(
apiException, apiException,
"API Exception occurred. Status: {StatusCode}, Title: {Title}, Detail: {Detail}, Extensions: {Extensions}", "API Exception occurred. Status: {StatusCode}, Title: {Title}, Detail: {Detail}, Extensions: {Extensions}",
@@ -284,6 +286,7 @@ public class ExceptionHandlingMiddleware
string culture = context.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us"; string culture = context.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us";
string returnUrl = $"{context.Request.Path}{context.Request.QueryString}"; string returnUrl = $"{context.Request.Path}{context.Request.QueryString}";
string loginUrl = $"/{culture}/auth/login?returnUrl={Uri.EscapeDataString(returnUrl)}"; string loginUrl = $"/{culture}/auth/login?returnUrl={Uri.EscapeDataString(returnUrl)}";
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation("Redirecting unauthorized user to {Url}", loginUrl); _logger.LogInformation("Redirecting unauthorized user to {Url}", loginUrl);
context.Response.Redirect(loginUrl); // Force an entire refresh of the current location, so that header and footer are re-rendered too. context.Response.Redirect(loginUrl); // Force an entire refresh of the current location, so that header and footer are re-rendered too.
} }
@@ -310,6 +313,7 @@ public class ExceptionHandlingMiddleware
if (errorsObj.ValueKind == JsonValueKind.Object) if (errorsObj.ValueKind == JsonValueKind.Object)
foreach (JsonProperty error in errorsObj.EnumerateObject()) foreach (JsonProperty error in errorsObj.EnumerateObject())
{ {
if (_logger.IsEnabled(LogLevel.Error))
_logger.LogError("Validation error {Field}: {@ErrorValues}", error.Name, error.Value.EnumerateArray().Select(jsonElement => jsonElement.ToString())); _logger.LogError("Validation error {Field}: {@ErrorValues}", error.Name, error.Value.EnumerateArray().Select(jsonElement => jsonElement.ToString()));
if (error.Value.ValueKind == JsonValueKind.Array) if (error.Value.ValueKind == JsonValueKind.Array)
foreach (JsonElement errorValue in error.Value.EnumerateArray()) foreach (JsonElement errorValue in error.Value.EnumerateArray())
@@ -43,6 +43,7 @@ public class TranscodingStartupInitializerTests : IDisposable
_settings = _transcodingSettingsDtoFixture.Create(ffmpegPath: missingFfmpegPath, cacheDirectory: _cacheDirectory); _settings = _transcodingSettingsDtoFixture.Create(ffmpegPath: missingFfmpegPath, cacheDirectory: _cacheDirectory);
_toolchainStatus = new TranscodingToolchainStatus(); _toolchainStatus = new TranscodingToolchainStatus();
_mockLogger = Substitute.For<ILogger<TranscodingStartupInitializer>>(); _mockLogger = Substitute.For<ILogger<TranscodingStartupInitializer>>();
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
_sut = new TranscodingStartupInitializer(Options.Create(_settings), _toolchainStatus, _mockLogger); _sut = new TranscodingStartupInitializer(Options.Create(_settings), _toolchainStatus, _mockLogger);
} }
@@ -102,6 +103,28 @@ public class TranscodingStartupInitializerTests : IDisposable
Arg.Any<Func<object, Exception?, string>>()); Arg.Any<Func<object, Exception?, string>>());
} }
[Fact]
public async Task StartAsync_WhenLoggingIsDisabledAndTheDirectoryExistsNonEmptyWithoutTheMarker_ShouldNotLogAnError()
{
// Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(false);
Directory.CreateDirectory(_cacheDirectory);
File.WriteAllText(Path.Combine(_cacheDirectory, "operator-data.txt"), "operator data");
// Act
await _sut.StartAsync(CancellationToken.None);
// Assert
Assert.False(TranscodingCachePaths.HasCacheMarker(_cacheDirectory));
Assert.False(_toolchainStatus.IsTranscoderAvailable);
_mockLogger.DidNotReceive().Log(
LogLevel.Error,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact] [Fact]
public async Task StartAsync_WhenTheDirectoryIsMarked_ShouldRemoveOnlyTheEntriesOfTheCacheNamespace() public async Task StartAsync_WhenTheDirectoryIsMarked_ShouldRemoveOnlyTheEntriesOfTheCacheNamespace()
{ {
@@ -15,6 +15,7 @@ using Microsoft.Extensions.Logging;
using NSubstitute; using NSubstitute;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -106,6 +107,7 @@ public class BooksMediaLibraryItemDeletionStrategyTests
public async Task DeleteItemAsync_WhenDeleteArtworkFails_ShouldStillDeleteTheBook() public async Task DeleteItemAsync_WhenDeleteArtworkFails_ShouldStillDeleteTheBook()
{ {
// Arrange // Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
LibraryId libraryId = _libraryIdFixture.Create(); LibraryId libraryId = _libraryIdFixture.Create();
BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub"); BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub");
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library"); LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library");
@@ -129,6 +131,12 @@ public class BooksMediaLibraryItemDeletionStrategyTests
Assert.True(result.IsSuccess); Assert.True(result.IsSuccess);
await _mockBookRepository.Received(1).DeleteByIdAsync(book.Id, Arg.Any<CancellationToken>()); await _mockBookRepository.Received(1).DeleteByIdAsync(book.Id, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockLogger.Received(1).Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Is<object>(state => state.ToString()!.Contains("Failed to delete the stored artwork of the book")),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
} }
[Fact] [Fact]
@@ -52,6 +52,7 @@ public class MusicMediaLibraryItemDeletionStrategyTests
_mockMusicArtworkRepository = Substitute.For<IMusicArtworkRepository>(); _mockMusicArtworkRepository = Substitute.For<IMusicArtworkRepository>();
_mockMusicArtworkService = Substitute.For<IMusicArtworkService>(); _mockMusicArtworkService = Substitute.For<IMusicArtworkService>();
_mockLogger = Substitute.For<ILogger<MusicMediaLibraryItemDeletionStrategy>>(); _mockLogger = Substitute.For<ILogger<MusicMediaLibraryItemDeletionStrategy>>();
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
_mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository); _mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository);
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
@@ -293,6 +294,54 @@ public class MusicMediaLibraryItemDeletionStrategyTests
Arg.Any<Func<object, Exception?, string>>()); Arg.Any<Func<object, Exception?, string>>());
} }
[Fact]
public async Task DeleteItemAsync_WhenLoggingIsDisabledAndDeletingAStoredArtworkFileFails_ShouldNotLogAWarningButStillDeleteTheRow()
{
// Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(false);
LibraryId libraryId = _libraryIdFixture.Create();
Guid albumId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/deleted.flac");
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, includeTracks: false);
AlbumEntity otherAlbum = _albumEntityFixture.Create(artistId: artistId, includeTracks: false);
MusicArtworkEntity trackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: track.Id, fileName: "/media/music/track-cover.jpg");
_mockTrackRepository.GetByPathAsync(libraryId.Value, track.Path, Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([trackArtwork]));
_mockMusicArtworkService.DeleteStoredArtwork(trackArtwork.FileName!)
.Returns(Errors.FileSystemManagement.FileNotFound);
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetIncludingDeletedByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
_mockTrackRepository.GetByAlbumIdIncludingDeletedAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<TrackEntity>>([track]));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockAlbumRepository.DeleteByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetByArtistIdIncludingDeletedAsync(artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([otherAlbum]));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
// Act
Result<Success> result = await _sut.DeleteItemAsync(libraryId.Value, track.Path, CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any<CancellationToken>());
_mockLogger.DidNotReceive().Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact] [Fact]
public async Task DeleteItemAsync_WhenAlbumWasAlreadyRemoved_ShouldPersistTheTrackDeletion() public async Task DeleteItemAsync_WhenAlbumWasAlreadyRemoved_ShouldPersistTheTrackDeletion()
{ {
@@ -113,6 +113,7 @@ public class PublicHostValidationHandlerTests
{ {
// Arrange // Arrange
ILogger<PublicHostValidationHandler> mockLogger = Substitute.For<ILogger<PublicHostValidationHandler>>(); ILogger<PublicHostValidationHandler> mockLogger = Substitute.For<ILogger<PublicHostValidationHandler>>();
mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
StubHttpMessageHandler innerHandler = new(); StubHttpMessageHandler innerHandler = new();
PublicHostValidationHandler handler = new(CreateValidator(), mockLogger) { InnerHandler = innerHandler }; PublicHostValidationHandler handler = new(CreateValidator(), mockLogger) { InnerHandler = innerHandler };
using HttpClient client = new(handler); using HttpClient client = new(handler);
@@ -23,6 +23,7 @@ using Microsoft.Extensions.Logging;
using NSubstitute; using NSubstitute;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
@@ -120,6 +121,7 @@ public class PluginDetectionSyncJobTests
public async Task StartAsync_WhenUpsertFails_ShouldLogErrorAndContinueWithOtherPlugins() public async Task StartAsync_WhenUpsertFails_ShouldLogErrorAndContinueWithOtherPlugins()
{ {
// Arrange // Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
IPlugin failingPlugin = CreatePlugin(Guid.NewGuid(), "Failing Plugin", new Version(1, 0, 0)); IPlugin failingPlugin = CreatePlugin(Guid.NewGuid(), "Failing Plugin", new Version(1, 0, 0));
IPlugin successfulPlugin = CreatePlugin(Guid.NewGuid(), "Successful Plugin", new Version(1, 0, 0)); IPlugin successfulPlugin = CreatePlugin(Guid.NewGuid(), "Successful Plugin", new Version(1, 0, 0));
_mockPluginManager.GetPlugins().Returns([failingPlugin, successfulPlugin]); _mockPluginManager.GetPlugins().Returns([failingPlugin, successfulPlugin]);
@@ -139,6 +141,12 @@ public class PluginDetectionSyncJobTests
// Assert // Assert
await _mockPluginRepository.Received(1).UpsertAsync(Arg.Is<PluginEntity>(plugin => plugin.Id == successfulPlugin.Id), Arg.Any<CancellationToken>()); await _mockPluginRepository.Received(1).UpsertAsync(Arg.Is<PluginEntity>(plugin => plugin.Id == successfulPlugin.Id), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockLogger.Received(1).Log(
LogLevel.Error,
Arg.Any<EventId>(),
Arg.Is<object>(state => state.ToString()!.Contains("Failed to persist the detection of plugin")),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
} }
[Fact] [Fact]
@@ -9,6 +9,7 @@ using Microsoft.Extensions.Logging;
using NSubstitute; using NSubstitute;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.Text.Json; using System.Text.Json;
using System.Threading; using System.Threading;
@@ -96,6 +97,7 @@ public class PluginSettingsStoreTests
public async Task GetSettingsAsync_WhenRepositoryReturnsFailure_ShouldReturnNullAndLogWarning() public async Task GetSettingsAsync_WhenRepositoryReturnsFailure_ShouldReturnNullAndLogWarning()
{ {
// Arrange // Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
Guid pluginId = Guid.NewGuid(); Guid pluginId = Guid.NewGuid();
_mockPluginRepository.GetByIdAsync(pluginId, cancellationToken: Arg.Any<CancellationToken>()) _mockPluginRepository.GetByIdAsync(pluginId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to retrieve the plugin")); .Returns(Error.Failure("Database.Error", "Failed to retrieve the plugin"));
@@ -105,5 +107,11 @@ public class PluginSettingsStoreTests
// Assert // Assert
Assert.Null(result); Assert.Null(result);
_mockLogger.Received(1).Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Is<object>(state => state.ToString()!.Contains("Failed to read the settings of the plugin")),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
} }
} }
@@ -25,6 +25,7 @@ using Microsoft.Extensions.Logging;
using NSubstitute; using NSubstitute;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
@@ -49,6 +50,7 @@ public class ScheduledJobSchedulerJobTests
private readonly IDomainEventPublisher _mockDomainEventPublisher; private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly IScheduledTaskExecutorFactory _mockTaskExecutorFactory; private readonly IScheduledTaskExecutorFactory _mockTaskExecutorFactory;
private readonly IScheduledTaskExecutor _mockTaskExecutor; private readonly IScheduledTaskExecutor _mockTaskExecutor;
private readonly ILogger<ScheduledJobSchedulerJob> _mockLogger;
private readonly ScheduledJobRuntimeRegistry _runtimeRegistry; private readonly ScheduledJobRuntimeRegistry _runtimeRegistry;
private readonly ScheduledJobSchedulerJob _sut; private readonly ScheduledJobSchedulerJob _sut;
private readonly Dictionary<Type, object> _services; private readonly Dictionary<Type, object> _services;
@@ -95,8 +97,8 @@ public class ScheduledJobSchedulerJobTests
.Returns(callInfo => _services.TryGetValue((Type)callInfo[0]!, out object? service) ? service : null); .Returns(callInfo => _services.TryGetValue((Type)callInfo[0]!, out object? service) ? service : null);
_runtimeRegistry = new ScheduledJobRuntimeRegistry(); _runtimeRegistry = new ScheduledJobRuntimeRegistry();
ILogger<ScheduledJobSchedulerJob> logger = Substitute.For<ILogger<ScheduledJobSchedulerJob>>(); _mockLogger = Substitute.For<ILogger<ScheduledJobSchedulerJob>>();
_sut = new ScheduledJobSchedulerJob(_runtimeRegistry, logger, _mockServiceScopeFactory); _sut = new ScheduledJobSchedulerJob(_runtimeRegistry, _mockLogger, _mockServiceScopeFactory);
} }
[Fact] [Fact]
@@ -555,6 +557,7 @@ public class ScheduledJobSchedulerJobTests
public async Task ExecuteScheduledJobRunAsync_WhenTheTaskPayloadFails_ShouldLogTheFailureAndStillCompleteTheExecution() public async Task ExecuteScheduledJobRunAsync_WhenTheTaskPayloadFails_ShouldLogTheFailureAndStillCompleteTheExecution()
{ {
// Arrange // Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60);
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id);
_mockScheduledJobRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>()).Returns(addedJob); _mockScheduledJobRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>()).Returns(addedJob);
@@ -568,12 +571,19 @@ public class ScheduledJobSchedulerJobTests
// Assert // Assert
await _mockTaskExecutor.Received(1).ExecutePayloadAsync(Arg.Any<ScheduledJob>(), Arg.Any<CancellationToken>()); await _mockTaskExecutor.Received(1).ExecutePayloadAsync(Arg.Any<ScheduledJob>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<ScheduledJobExecutionCompletedDomainEvent>(domainEvent => !domainEvent.IsCycleRun), Arg.Any<CancellationToken>()); await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<ScheduledJobExecutionCompletedDomainEvent>(domainEvent => !domainEvent.IsCycleRun), Arg.Any<CancellationToken>());
_mockLogger.Received(1).Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Is<object>(state => state.ToString()!.Contains("failed:")),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
} }
[Fact] [Fact]
public async Task ExecuteScheduledJobRunAsync_WhenTheTaskPayloadThrows_ShouldLogTheExceptionAndStillCompleteTheExecution() public async Task ExecuteScheduledJobRunAsync_WhenTheTaskPayloadThrows_ShouldLogTheExceptionAndStillCompleteTheExecution()
{ {
// Arrange // Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60);
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id);
_mockScheduledJobRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>()).Returns(addedJob); _mockScheduledJobRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>()).Returns(addedJob);
@@ -586,6 +596,12 @@ public class ScheduledJobSchedulerJobTests
// Assert // Assert
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<ScheduledJobExecutionCompletedDomainEvent>(domainEvent => !domainEvent.IsCycleRun), Arg.Any<CancellationToken>()); await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<ScheduledJobExecutionCompletedDomainEvent>(domainEvent => !domainEvent.IsCycleRun), Arg.Any<CancellationToken>());
_mockLogger.Received(1).Log(
LogLevel.Error,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Is<Exception>(exception => exception is InvalidOperationException && exception.Message == "The task threw."),
Arg.Any<Func<object, Exception?, string>>());
} }
[Fact] [Fact]
@@ -52,6 +52,7 @@ public class ThemeSynchronizerTests : IDisposable
_mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success); _mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockLogger = Substitute.For<ILogger>(); _mockLogger = Substitute.For<ILogger>();
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
_mockThemeService.GetBundledThemeArchivePaths().Returns([]); _mockThemeService.GetBundledThemeArchivePaths().Returns([]);
_mockThemeService.HasThemePack(Arg.Any<string>()).Returns(true); _mockThemeService.HasThemePack(Arg.Any<string>()).Returns(true);
_mockThemeService.DefaultThemeId.Returns("lumina-default"); _mockThemeService.DefaultThemeId.Returns("lumina-default");
@@ -79,6 +80,28 @@ public class ThemeSynchronizerTests : IDisposable
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
} }
[Fact]
public async Task SynchronizeAsync_WhenLoggingIsDisabledAndTheInstalledThemesCannotBeRead_ShouldNotLogAWarning()
{
// Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(false);
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(Error.Failure("Themes.NotFound", "Failed to read the installed themes"));
_mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]);
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockLogger.DidNotReceive().Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact] [Fact]
public async Task SynchronizeAsync_WhenABundledArchiveManifestCannotBeRead_ShouldSkipThatArchive() public async Task SynchronizeAsync_WhenABundledArchiveManifestCannotBeRead_ShouldSkipThatArchive()
{ {
@@ -235,6 +258,12 @@ public class ThemeSynchronizerTests : IDisposable
// Assert // Assert
await _mockThemeRepository.Received(1).InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()); await _mockThemeRepository.Received(1).InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockLogger.Received(1).Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Is<object>(state => state.ToString()!.Contains("Failed to persist the detection of theme")),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
} }
[Fact] [Fact]
@@ -14,6 +14,7 @@ using Microsoft.Extensions.Logging;
using NSubstitute; using NSubstitute;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
@@ -154,6 +155,7 @@ public class EventualConsistencyMiddlewareTests
httpContext.Request.Path = "/api/v1/probe"; httpContext.Request.Path = "/api/v1/probe";
httpContext.Response.StatusCode = StatusCodes.Status200OK; httpContext.Response.StatusCode = StatusCodes.Status200OK;
ILogger<EventualConsistencyMiddleware> mockLogger = Substitute.For<ILogger<EventualConsistencyMiddleware>>(); ILogger<EventualConsistencyMiddleware> mockLogger = Substitute.For<ILogger<EventualConsistencyMiddleware>>();
mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
EventualConsistencyMiddleware sut = new(_ => Task.CompletedTask, mockLogger); EventualConsistencyMiddleware sut = new(_ => Task.CompletedTask, mockLogger);
IUnitOfWork mockUnitOfWork = Substitute.For<IUnitOfWork>(); IUnitOfWork mockUnitOfWork = Substitute.For<IUnitOfWork>();
mockUnitOfWork mockUnitOfWork
@@ -170,6 +172,12 @@ public class EventualConsistencyMiddlewareTests
// The completion callback must never leave a transaction open after a failed commit, and it must never publish events that belong to a transaction that did not commit. // The completion callback must never leave a transaction open after a failed commit, and it must never publish events that belong to a transaction that did not commit.
await mockUnitOfWork.Received(1).RollbackTransactionAsync(Arg.Any<CancellationToken>()); await mockUnitOfWork.Received(1).RollbackTransactionAsync(Arg.Any<CancellationToken>());
await mockPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>()); await mockPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
mockLogger.Received(1).Log(
LogLevel.Error,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Is<Exception>(exception => exception is InvalidOperationException && exception.Message == "commit failed"),
Arg.Any<Func<object, Exception?, string>>());
} }
/// <summary> /// <summary>
@@ -33,6 +33,7 @@ public class ExceptionHandlingMiddlewareTests
public ExceptionHandlingMiddlewareTests() public ExceptionHandlingMiddlewareTests()
{ {
_mockLogger = Substitute.For<ILogger<ExceptionHandlingMiddleware>>(); _mockLogger = Substitute.For<ILogger<ExceptionHandlingMiddleware>>();
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
_sut = new ExceptionHandlingMiddleware(context => _nextDelegate(context), _mockLogger); _sut = new ExceptionHandlingMiddleware(context => _nextDelegate(context), _mockLogger);
} }
@@ -87,6 +88,30 @@ public class ExceptionHandlingMiddlewareTests
Arg.Any<Func<object, Exception?, string>>()); Arg.Any<Func<object, Exception?, string>>());
} }
[Fact]
public async Task InvokeAsync_WhenLoggingIsDisabledAndNextThrowsException_ShouldNotLogTheException()
{
// Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(false);
DefaultHttpContext context = new()
{
Response = { Body = new MemoryStream() }
};
_nextDelegate = _ => throw new InvalidOperationException("sensitive internal details");
// Act
await _sut.InvokeAsync(context);
// Assert
Assert.Equal(StatusCodes.Status500InternalServerError, context.Response.StatusCode);
_mockLogger.DidNotReceive().Log(
LogLevel.Error,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact] [Fact]
public async Task InvokeAsync_WhenNextThrowsExceptionAndActivityIsCurrent_ShouldUseTheActivityIdAsTraceId() public async Task InvokeAsync_WhenNextThrowsExceptionAndActivityIsCurrent_ShouldUseTheActivityIdAsTraceId()
{ {
@@ -41,6 +41,7 @@ public class ExceptionHandlingMiddlewareTests
public ExceptionHandlingMiddlewareTests() public ExceptionHandlingMiddlewareTests()
{ {
_mockLogger = Substitute.For<ILogger<ExceptionHandlingMiddleware>>(); _mockLogger = Substitute.For<ILogger<ExceptionHandlingMiddleware>>();
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
_mockStringLocalizer = Substitute.For<IStringLocalizer<ExceptionHandlingMiddleware>>(); _mockStringLocalizer = Substitute.For<IStringLocalizer<ExceptionHandlingMiddleware>>();
_mockStringLocalizer[Arg.Any<string>()].Returns(callInfo => new LocalizedString(callInfo.Arg<string>(), $"localized:{callInfo.Arg<string>()}")); _mockStringLocalizer[Arg.Any<string>()].Returns(callInfo => new LocalizedString(callInfo.Arg<string>(), $"localized:{callInfo.Arg<string>()}"));
_mockAuthenticationService = Substitute.For<IAuthenticationService>(); _mockAuthenticationService = Substitute.For<IAuthenticationService>();
@@ -91,6 +92,27 @@ public class ExceptionHandlingMiddlewareTests
Arg.Any<Func<object, Exception?, string>>()); Arg.Any<Func<object, Exception?, string>>());
} }
[Fact]
public async Task InvokeAsync_WhenLoggingIsDisabledAndNextThrowsNonApiExceptionAndApiRequest_ShouldNotLogError()
{
// Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(false);
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
_nextDelegate = _ => throw new InvalidOperationException("Unexpected failure");
// Act
await _sut.InvokeAsync(httpContext);
// Assert
Assert.Contains("application/json", httpContext.Response.ContentType);
_mockLogger.DidNotReceive().Log(
LogLevel.Error,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact] [Fact]
public async Task InvokeAsync_WhenNextThrowsNonApiExceptionAndPageRequest_ShouldWriteHtmlErrorPage() public async Task InvokeAsync_WhenNextThrowsNonApiExceptionAndPageRequest_ShouldWriteHtmlErrorPage()
{ {