Hero: zelftest en mapcontrole van de media draaien op de achtergrond, zodat de host niet later gaat luisteren

De hosted services starten voor de webserver; de zelftest van Magick (laden van de native bibliotheek en een testcodering) kostte op de Pi ongeveer 9 s voordat de host luisterde.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 17:20:59 +01:00
co-authored by Claude Sonnet 5.5
parent bd283d629d
commit 01703ccddf
5 changed files with 102 additions and 34 deletions
@@ -81,6 +81,9 @@ public class HeroAsfSiteE2ETests : IClassFixture<AsfSiteFactory>
var client = _factory.CreateClient(); var client = _factory.CreateClient();
var caller = Guid.NewGuid(); 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<SlpModularCms.Core.Media.MediaStatus>();
for (var i = 0; i < 300 && !status.UploadsAvailable; i++) await Task.Delay(100);
await InScope(async sp => await InScope(async sp =>
{ {
var db = sp.GetRequiredService<HeroDbContext>(); var db = sp.GetRequiredService<HeroDbContext>();
@@ -59,7 +59,10 @@ public class HeroInjectionPipelineTests : IClassFixture<HeroInjectionFactory>
private async Task<T> InScope<T>(Func<IServiceProvider, Task<T>> action) private async Task<T> InScope<T>(Func<IServiceProvider, Task<T>> 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<SlpModularCms.Core.Media.MediaStatus>();
for (var i = 0; i < 300 && !status.UploadsAvailable; i++) await Task.Delay(100);
await using var scope = _factory.Services.CreateAsyncScope(); await using var scope = _factory.Services.CreateAsyncScope();
return await action(scope.ServiceProvider); return await action(scope.ServiceProvider);
} }
@@ -286,7 +286,9 @@ public class MediaDirectoryCheckTests
var status = new MediaStatus(); var status = new MediaStatus();
var areas = new MediaAreaRegistry(); 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(); status.DirectoryWritable.Should().BeTrue();
areas.Contains("hero").Should().BeTrue(); areas.Contains("hero").Should().BeTrue();
@@ -298,7 +300,9 @@ public class MediaDirectoryCheckTests
var status = new MediaStatus(); var status = new MediaStatus();
status.SetDirectory(true); status.SetDirectory(true);
await Check(Substitute.For<IMediaStore>(), status, new MediaAreaRegistry(), null).StartAsync(CancellationToken.None); var check = Check(Substitute.For<IMediaStore>(), status, new MediaAreaRegistry(), null);
await check.StartAsync(CancellationToken.None);
await check.Completion;
status.DirectoryWritable.Should().BeFalse(); status.DirectoryWritable.Should().BeFalse();
} }
@@ -310,7 +314,9 @@ public class MediaDirectoryCheckTests
store.ProbeAsync(default).ReturnsForAnyArgs(false); store.ProbeAsync(default).ReturnsForAnyArgs(false);
var status = new MediaStatus(); 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(); status.DirectoryWritable.Should().BeFalse();
} }
@@ -56,13 +56,28 @@ public sealed class MediaDirectoryCheck(
Microsoft.Extensions.Options.IOptions<MediaOptions> options, Microsoft.Extensions.Options.IOptions<MediaOptions> options,
ILogger<MediaDirectoryCheck> logger) : IHostedService ILogger<MediaDirectoryCheck> logger) : IHostedService
{ {
public async Task StartAsync(CancellationToken cancellationToken) /// <summary>The check in the background; completes when the status is known (tests await it).</summary>
public Task Completion { get; private set; } = Task.CompletedTask;
private readonly CancellationTokenSource _stopping = new();
public Task StartAsync(CancellationToken cancellationToken)
{ {
foreach (var registration in registrations) foreach (var registration in registrations)
{ {
areas.Add(registration.Area); areas.Add(registration.Area);
} }
// 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)) if (string.IsNullOrWhiteSpace(options.Value.Directory))
{ {
status.SetDirectory(false); status.SetDirectory(false);
@@ -84,8 +99,25 @@ public sealed class MediaDirectoryCheck(
logger.LogError("The media directory is over 80 percent of its safety limit ({Bytes} bytes).", total); 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.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.
}
}
} }
/// <summary> /// <summary>
@@ -95,7 +127,22 @@ public sealed class MediaDirectoryCheck(
/// </summary> /// </summary>
public sealed class ImageProcessorSelfTest(IServiceProvider services, MediaStatus status, ILogger<ImageProcessorSelfTest> logger) : IHostedService public sealed class ImageProcessorSelfTest(IServiceProvider services, MediaStatus status, ILogger<ImageProcessorSelfTest> logger) : IHostedService
{ {
public async Task StartAsync(CancellationToken cancellationToken) /// <summary>The self-test in the background; completes when the status is known (tests await it).</summary>
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<IImageProcessor>(); var processor = services.GetService<IImageProcessor>();
if (processor is null) if (processor is null)
@@ -105,8 +152,6 @@ public sealed class ImageProcessorSelfTest(IServiceProvider services, MediaStatu
return; return;
} }
try
{
await processor.SelfTestAsync(cancellationToken); await processor.SelfTestAsync(cancellationToken);
status.SetProcessor(true, processor.SupportedInput, processor.SupportedOutput); 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.
}
}
} }
@@ -44,7 +44,7 @@ public static class HeroPictureRenderer
return textOnlyRegion ? new HeroInjection(TextOnlyRegion(hero), string.Empty) : HeroInjection.None; 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) if (slide is null)
{ {
return HeroInjection.None; return HeroInjection.None;