diff --git a/src/SlpModularCms.Api.Tests/HeroAsfSiteE2ETests.cs b/src/SlpModularCms.Api.Tests/HeroAsfSiteE2ETests.cs index ccd235f..8ebfaab 100644 --- a/src/SlpModularCms.Api.Tests/HeroAsfSiteE2ETests.cs +++ b/src/SlpModularCms.Api.Tests/HeroAsfSiteE2ETests.cs @@ -81,6 +81,9 @@ public class HeroAsfSiteE2ETests : IClassFixture var client = _factory.CreateClient(); var caller = Guid.NewGuid(); + // The image library self-test and the media directory check run in the background after start-up. + var status = _factory.Services.GetRequiredService(); + for (var i = 0; i < 300 && !status.UploadsAvailable; i++) await Task.Delay(100); await InScope(async sp => { var db = sp.GetRequiredService(); diff --git a/src/SlpModularCms.Api.Tests/HeroInjectionPipelineTests.cs b/src/SlpModularCms.Api.Tests/HeroInjectionPipelineTests.cs index d0a30df..e5599e0 100644 --- a/src/SlpModularCms.Api.Tests/HeroInjectionPipelineTests.cs +++ b/src/SlpModularCms.Api.Tests/HeroInjectionPipelineTests.cs @@ -59,7 +59,10 @@ public class HeroInjectionPipelineTests : IClassFixture private async Task InScope(Func> action) { - _ = _factory.CreateClient(); // starts the host, migrates and runs the start-up checks + _ = _factory.CreateClient(); // starts the host, migrates and starts the start-up checks + // The image library self-test and the media directory check run in the background after start-up. + var status = _factory.Services.GetRequiredService(); + for (var i = 0; i < 300 && !status.UploadsAvailable; i++) await Task.Delay(100); await using var scope = _factory.Services.CreateAsyncScope(); return await action(scope.ServiceProvider); } diff --git a/src/SlpModularCms.Core.Tests/Media/MediaStoreAndEndpointTests.cs b/src/SlpModularCms.Core.Tests/Media/MediaStoreAndEndpointTests.cs index c5271c4..0f500cb 100644 --- a/src/SlpModularCms.Core.Tests/Media/MediaStoreAndEndpointTests.cs +++ b/src/SlpModularCms.Core.Tests/Media/MediaStoreAndEndpointTests.cs @@ -286,7 +286,9 @@ public class MediaDirectoryCheckTests var status = new MediaStatus(); var areas = new MediaAreaRegistry(); - await Check(media.Store, status, areas, media.Directory, "hero").StartAsync(CancellationToken.None); + var check = Check(media.Store, status, areas, media.Directory, "hero"); + await check.StartAsync(CancellationToken.None); + await check.Completion; status.DirectoryWritable.Should().BeTrue(); areas.Contains("hero").Should().BeTrue(); @@ -298,7 +300,9 @@ public class MediaDirectoryCheckTests var status = new MediaStatus(); status.SetDirectory(true); - await Check(Substitute.For(), status, new MediaAreaRegistry(), null).StartAsync(CancellationToken.None); + var check = Check(Substitute.For(), status, new MediaAreaRegistry(), null); + await check.StartAsync(CancellationToken.None); + await check.Completion; status.DirectoryWritable.Should().BeFalse(); } @@ -310,7 +314,9 @@ public class MediaDirectoryCheckTests store.ProbeAsync(default).ReturnsForAnyArgs(false); var status = new MediaStatus(); - await Check(store, status, new MediaAreaRegistry(), "/somewhere").StartAsync(CancellationToken.None); + var check = Check(store, status, new MediaAreaRegistry(), "/somewhere"); + await check.StartAsync(CancellationToken.None); + await check.Completion; status.DirectoryWritable.Should().BeFalse(); } diff --git a/src/SlpModularCms.Core/Media/MediaServiceCollectionExtensions.cs b/src/SlpModularCms.Core/Media/MediaServiceCollectionExtensions.cs index 0c7c177..6b93cc4 100644 --- a/src/SlpModularCms.Core/Media/MediaServiceCollectionExtensions.cs +++ b/src/SlpModularCms.Core/Media/MediaServiceCollectionExtensions.cs @@ -56,36 +56,68 @@ public sealed class MediaDirectoryCheck( Microsoft.Extensions.Options.IOptions options, ILogger logger) : IHostedService { - public async Task StartAsync(CancellationToken cancellationToken) + /// The check in the background; completes when the status is known (tests await it). + public Task Completion { get; private set; } = Task.CompletedTask; + + private readonly CancellationTokenSource _stopping = new(); + + public Task StartAsync(CancellationToken cancellationToken) { foreach (var registration in registrations) { areas.Add(registration.Area); } - if (string.IsNullOrWhiteSpace(options.Value.Directory)) + // Not awaited: a hosted service delays the moment the host starts listening, and a disk that is slow to answer must + // never keep the website from coming up. Until it is done, uploads are simply not available yet. + Completion = Task.Run(() => CheckAsync(_stopping.Token), CancellationToken.None); + return Task.CompletedTask; + } + + private async Task CheckAsync(CancellationToken cancellationToken) + { + try + { + if (string.IsNullOrWhiteSpace(options.Value.Directory)) + { + status.SetDirectory(false); + logger.LogWarning("Media:Directory is not configured: image uploads are unavailable on this host."); + return; + } + + var writable = await store.ProbeAsync(cancellationToken); + status.SetDirectory(writable); + if (!writable) + { + logger.LogError("The media directory is missing or not writable: image uploads are unavailable until it is fixed."); + return; + } + + var total = await store.GetTotalBytesAsync(cancellationToken); + if (options.Value.MaxTotalBytes > 0 && total > options.Value.MaxTotalBytes * 8 / 10) + { + logger.LogError("The media directory is over 80 percent of its safety limit ({Bytes} bytes).", total); + } + } + catch (Exception exception) when (exception is not OperationCanceledException) { status.SetDirectory(false); - logger.LogWarning("Media:Directory is not configured: image uploads are unavailable on this host."); - return; - } - - var writable = await store.ProbeAsync(cancellationToken); - status.SetDirectory(writable); - if (!writable) - { - logger.LogError("The media directory is missing or not writable: image uploads are unavailable until it is fixed."); - return; - } - - var total = await store.GetTotalBytesAsync(cancellationToken); - if (options.Value.MaxTotalBytes > 0 && total > options.Value.MaxTotalBytes * 8 / 10) - { - logger.LogError("The media directory is over 80 percent of its safety limit ({Bytes} bytes).", total); + logger.LogError(exception, "The media directory check failed: image uploads are unavailable on this host."); } } - public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; + public async Task StopAsync(CancellationToken cancellationToken) + { + await _stopping.CancelAsync(); + try + { + await Completion.WaitAsync(cancellationToken); + } + catch (OperationCanceledException) + { + // Shutting down. + } + } } /// @@ -95,18 +127,31 @@ public sealed class MediaDirectoryCheck( /// public sealed class ImageProcessorSelfTest(IServiceProvider services, MediaStatus status, ILogger logger) : IHostedService { - public async Task StartAsync(CancellationToken cancellationToken) - { - var processor = services.GetService(); - if (processor is null) - { - status.SetProcessor(false, new HashSet(), new HashSet()); - logger.LogWarning("No image processor is registered: image uploads are unavailable."); - return; - } + /// The self-test in the background; completes when the status is known (tests await it). + public Task Completion { get; private set; } = Task.CompletedTask; + private readonly CancellationTokenSource _stopping = new(); + + public Task StartAsync(CancellationToken cancellationToken) + { + // Not awaited: loading the native library and encoding a test image can take seconds on a small machine, and a + // hosted service delays the moment the host starts listening (the health check of a deploy waits for it). + Completion = Task.Run(() => TestAsync(_stopping.Token), CancellationToken.None); + return Task.CompletedTask; + } + + private async Task TestAsync(CancellationToken cancellationToken) + { try { + var processor = services.GetService(); + if (processor is null) + { + status.SetProcessor(false, new HashSet(), new HashSet()); + logger.LogWarning("No image processor is registered: image uploads are unavailable."); + return; + } + await processor.SelfTestAsync(cancellationToken); status.SetProcessor(true, processor.SupportedInput, processor.SupportedOutput); } @@ -117,5 +162,16 @@ public sealed class ImageProcessorSelfTest(IServiceProvider services, MediaStatu } } - public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; + public async Task StopAsync(CancellationToken cancellationToken) + { + await _stopping.CancelAsync(); + try + { + await Completion.WaitAsync(cancellationToken); + } + catch (OperationCanceledException) + { + // Shutting down. + } + } } diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroPictureRenderer.cs b/src/SlpModularCms.Modules.Hero/Services/HeroPictureRenderer.cs index daf929b..0e12d81 100644 --- a/src/SlpModularCms.Modules.Hero/Services/HeroPictureRenderer.cs +++ b/src/SlpModularCms.Modules.Hero/Services/HeroPictureRenderer.cs @@ -44,7 +44,7 @@ public static class HeroPictureRenderer return textOnlyRegion ? new HeroInjection(TextOnlyRegion(hero), string.Empty) : HeroInjection.None; } - var slide = hero.Slides.FirstOrDefault(IsUsable); + var slide = (hero.Slides ?? []).FirstOrDefault(IsUsable); if (slide is null) { return HeroInjection.None;