Continuous Integration / config-asf (pull_request) Successful in 6s
Continuous Integration / config-sls (pull_request) Successful in 7s
Continuous Integration / changes (pull_request) Successful in 11s
Continuous Integration / compile-sites (pull_request) Successful in 1m44s
Continuous Integration / backend-build (pull_request) Successful in 1m49s
Continuous Integration / vulnerability-scan (pull_request) Successful in 1m51s
Continuous Integration / frontend-prepare (pull_request) Successful in 2m2s
Continuous Integration / frontend-build (pull_request) Successful in 42s
Continuous Integration / backend-test (pull_request) Failing after 3m56s
Continuous Integration / frontend-lint (pull_request) Successful in 39s
Continuous Integration / frontend-test (pull_request) Successful in 2m33s
Continuous Integration / publish-sls-test (pull_request) Skipped
Continuous Integration / publish-sls-production (pull_request) Skipped
Continuous Integration / deploy-sls-test (pull_request) Skipped
Continuous Integration / deploy-sls-production (pull_request) Skipped
Continuous Integration / publish-asf-test (pull_request) Skipped
Continuous Integration / deploy-asf-test (pull_request) Skipped
Continuous Integration / smoke-sls-test (pull_request) Skipped
Continuous Integration / smoke-asf-test (pull_request) Skipped
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
179 lines
7.4 KiB
C#
179 lines
7.4 KiB
C#
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.DependencyInjection.Extensions;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace SlpModularCms.Core.Media;
|
|
|
|
public static class MediaServiceCollectionExtensions
|
|
{
|
|
/// <summary>
|
|
/// The general media service: options (<c>Media:*</c>), the processing gate, the status the admin reads, the upload
|
|
/// guard and the start-up self-test. Safe to call from every module that needs it. An <see cref="IImageProcessor"/>
|
|
/// has to be registered separately (the Magick project does that); without one the status stays "unavailable".
|
|
/// </summary>
|
|
public static IServiceCollection AddCmsMedia(this IServiceCollection services)
|
|
{
|
|
services.AddOptions<MediaOptions>().Configure<IConfiguration>((options, configuration) =>
|
|
configuration.GetSection(MediaOptions.SectionName).Bind(options));
|
|
services.TryAddSingleton<MediaProcessingGate>();
|
|
services.TryAddSingleton<MediaStatus>();
|
|
services.TryAddSingleton<MediaAreaRegistry>();
|
|
services.TryAddSingleton<IMediaStore, FileSystemMediaStore>();
|
|
services.TryAddSingleton<IMediaUploadGuard, MediaUploadGuard>();
|
|
services.TryAddSingleton<Library.MediaStorageUsage>();
|
|
if (!services.Any(d => d.ImplementationType == typeof(ImageProcessorSelfTest)))
|
|
{
|
|
services.AddHostedService<ImageProcessorSelfTest>();
|
|
services.AddHostedService<MediaDirectoryCheck>();
|
|
}
|
|
|
|
return services;
|
|
}
|
|
|
|
/// <summary>Lets the <c>/media</c> endpoint serve the given area (for example <c>hero</c>).</summary>
|
|
public static IServiceCollection AddCmsMediaArea(this IServiceCollection services, string area)
|
|
{
|
|
services.AddCmsMedia();
|
|
services.AddSingleton(new MediaAreaRegistration(area));
|
|
return services;
|
|
}
|
|
}
|
|
|
|
/// <summary>A module declares the media area it owns; the host adds all of them to the <see cref="MediaAreaRegistry"/> at start-up.</summary>
|
|
public sealed record MediaAreaRegistration(string Area);
|
|
|
|
/// <summary>
|
|
/// At start-up, proves that the media directory exists (creating it when needed) and is writable, fills the area
|
|
/// registry and warns when the directory fills up. A failure only turns image uploads off; files that are already
|
|
/// stored keep being served.
|
|
/// </summary>
|
|
public sealed class MediaDirectoryCheck(
|
|
IMediaStore store,
|
|
MediaStatus status,
|
|
MediaAreaRegistry areas,
|
|
IEnumerable<MediaAreaRegistration> registrations,
|
|
Microsoft.Extensions.Options.IOptions<MediaOptions> options,
|
|
ILogger<MediaDirectoryCheck> logger) : IHostedService
|
|
{
|
|
/// <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)
|
|
{
|
|
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))
|
|
{
|
|
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.LogError(exception, "The media directory check failed: image uploads are unavailable on this host.");
|
|
}
|
|
}
|
|
|
|
public async Task StopAsync(CancellationToken cancellationToken)
|
|
{
|
|
await _stopping.CancelAsync();
|
|
try
|
|
{
|
|
await Completion.WaitAsync(cancellationToken);
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
// Shutting down.
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// At start-up, proves the image library works on this host (encodes and decodes a tiny image in every supported
|
|
/// format) and publishes what it found. A failure only turns image uploads off: nothing else depends on it, and
|
|
/// reading pages and media keeps working.
|
|
/// </summary>
|
|
public sealed class ImageProcessorSelfTest(IServiceProvider services, MediaStatus status, ILogger<ImageProcessorSelfTest> logger) : IHostedService
|
|
{
|
|
/// <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>();
|
|
if (processor is null)
|
|
{
|
|
status.SetProcessor(false, new HashSet<ImageFormat>(), new HashSet<ImageFormat>());
|
|
logger.LogWarning("No image processor is registered: image uploads are unavailable.");
|
|
return;
|
|
}
|
|
|
|
await processor.SelfTestAsync(cancellationToken);
|
|
status.SetProcessor(true, processor.SupportedInput, processor.SupportedOutput);
|
|
}
|
|
catch (Exception exception) when (exception is not OperationCanceledException)
|
|
{
|
|
status.SetProcessor(false, new HashSet<ImageFormat>(), new HashSet<ImageFormat>());
|
|
logger.LogError(exception, "The image library self-test failed: image uploads are unavailable on this host.");
|
|
}
|
|
}
|
|
|
|
public async Task StopAsync(CancellationToken cancellationToken)
|
|
{
|
|
await _stopping.CancelAsync();
|
|
try
|
|
{
|
|
await Completion.WaitAsync(cancellationToken);
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
// Shutting down.
|
|
}
|
|
}
|
|
}
|