Files
slp-modular-cms/src/SlpModularCms.Core/Media/ImageProcessing.cs
T
SluijsensandClaude Sonnet 5.5 a71db84632
Continuous Integration / config-sls (pull_request) Successful in 8s
Continuous Integration / changes (pull_request) Successful in 13s
Continuous Integration / frontend-prepare (pull_request) Skipped
Continuous Integration / frontend-build (pull_request) Skipped
Continuous Integration / frontend-test (pull_request) Skipped
Continuous Integration / frontend-lint (pull_request) Skipped
Continuous Integration / config-asf (pull_request) Successful in 5s
Continuous Integration / compile-sites (pull_request) Successful in 1m31s
Continuous Integration / vulnerability-scan (pull_request) Successful in 1m18s
Continuous Integration / backend-build (pull_request) Successful in 3m10s
Continuous Integration / publish-sls-test (pull_request) Canceled after 0s
Continuous Integration / publish-sls-production (pull_request) Canceled after 0s
Continuous Integration / deploy-sls-test (pull_request) Canceled after 0s
Continuous Integration / deploy-sls-production (pull_request) Canceled after 0s
Continuous Integration / publish-asf-test (pull_request) Canceled after 0s
Continuous Integration / deploy-asf-test (pull_request) Canceled after 0s
Continuous Integration / backend-test (pull_request) Canceled after 1m25s
Continuous Integration / smoke-sls-test (pull_request) Canceled after 0s
Continuous Integration / smoke-asf-test (pull_request) Canceled after 0s
Media: instelling Media:AutoCleanupUnattached (standaard true) om ongebruikte uploads te bewaren
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 14:17:28 +01:00

173 lines
7.5 KiB
C#

using Microsoft.Extensions.Options;
namespace SlpModularCms.Core.Media;
/// <summary>Why an upload was refused. The names are the stable codes the API returns (see <see cref="ImageRejectedException.Code"/>).</summary>
public enum ImageRejection
{
TooLarge,
UnsupportedFormat,
Corrupt,
TooManyPixels,
Timeout,
Busy,
Unavailable,
}
/// <summary>A refused image. The message is technical English for logs; users see a text from the language files.</summary>
public sealed class ImageRejectedException(ImageRejection reason, string message) : Exception(message)
{
public ImageRejection Reason { get; } = reason;
/// <summary>A stable code for the API: <c>too_large</c>, <c>unsupported_format</c>, <c>corrupt</c>, <c>too_many_pixels</c>, <c>timeout</c>, <c>busy</c>, <c>unavailable</c>.</summary>
public string Code => Reason switch
{
ImageRejection.TooLarge => "too_large",
ImageRejection.UnsupportedFormat => "unsupported_format",
ImageRejection.Corrupt => "corrupt",
ImageRejection.TooManyPixels => "too_many_pixels",
ImageRejection.Timeout => "timeout",
ImageRejection.Busy => "busy",
_ => "unavailable",
};
}
/// <summary>Settings of the media service (<c>Media:*</c>).</summary>
public sealed class MediaOptions
{
public const string SectionName = "Media";
/// <summary>The directory outside the release where files are stored. Empty = uploads are unavailable.</summary>
public string? Directory { get; set; }
public long MaxUploadBytes { get; set; } = 10 * 1024 * 1024;
public long MaxPixels { get; set; } = 64_000_000;
public int MaxSide { get; set; } = 16_384;
public int MaxParallelJobs { get; set; } = 2;
public int DecodeTimeoutSeconds { get; set; } = 20;
/// <summary>The time allowed to remove metadata from an upload (it decodes and writes the whole picture again).</summary>
public int StripTimeoutSeconds { get; set; } = 60;
/// <summary>
/// The time allowed to cut ALL variants of one photo in the background (one decode, then every variant). Generous on
/// purpose: a large photo on a Raspberry Pi needs minutes; a runaway job is stopped after this.
/// </summary>
public int RenderSetTimeoutSeconds { get; set; } = 600;
/// <summary>How long a free processing slot is awaited before the answer is "busy".</summary>
public int BusyWaitSeconds { get; set; } = 3;
public long MaxTotalBytes { get; set; } = 2L * 1024 * 1024 * 1024;
public int RetentionDays { get; set; } = 7;
/// <summary>
/// Whether photos that were uploaded but never used are removed automatically after <see cref="RetentionDays"/>.
/// The media library keeps everything until a person removes it, so set this to <c>false</c> (<c>Media__AutoCleanupUnattached=false</c>)
/// once the library can show and delete photos. Retired files of photos a person removed stay housekeeping either way.
/// Default <c>true</c> keeps today's behaviour (assumption 3 of the media-library list).
/// </summary>
public bool AutoCleanupUnattached { get; set; } = true;
}
/// <summary>
/// The image library behind one small interface. Implementations must apply the resource limits of
/// <see cref="MediaOptions"/>, decode only the format the caller names (decided from the signature), never use a
/// client file name and never write metadata into an output.
/// </summary>
public interface IImageProcessor
{
/// <summary>The formats it can decode.</summary>
IReadOnlySet<ImageFormat> SupportedInput { get; }
/// <summary>The formats it can write (WebP always; AVIF when the platform can).</summary>
IReadOnlySet<ImageFormat> SupportedOutput { get; }
/// <summary>Reads size (after orientation), frame count and whether metadata is present, without decoding the pixels.</summary>
/// <exception cref="ImageRejectedException">The data is not a decodable image of that format.</exception>
Task<ImageInfo> InspectAsync(ReadOnlyMemory<byte> data, ImageFormat declared, CancellationToken cancellationToken);
/// <summary>
/// Decodes the first frame, applies the orientation, cuts the crop, resizes to the variant size (never above the
/// crop), strips metadata and encodes in the variant's format and quality.
/// </summary>
Task<RenderedImage> RenderAsync(ReadOnlyMemory<byte> data, ImageFormat declared, VariantSpec variant, CancellationToken cancellationToken);
/// <summary>
/// Cuts all variants of a photo from ONE decode (the picture is decoded and oriented once, then every variant is
/// cropped, resized and encoded from it). <paramref name="progress"/> is called with (variants done, variants in total)
/// after every variant. Stops between variants when cancelled. The result has the order of <paramref name="variants"/>.
/// </summary>
Task<IReadOnlyList<RenderedImage>> RenderSetAsync(ReadOnlyMemory<byte> data, ImageFormat declared, IReadOnlyList<VariantSpec> variants, Action<int, int>? progress, CancellationToken cancellationToken);
/// <summary>
/// Removes metadata from an original that carries any, keeping the pixels as they are as far as the format
/// allows. Returns null when there is nothing to remove (the original is stored as received).
/// </summary>
Task<byte[]?> StripMetadataAsync(ReadOnlyMemory<byte> data, ImageFormat declared, CancellationToken cancellationToken);
/// <summary>Encodes and decodes a tiny image in every supported format. Throws when the library does not work here.</summary>
Task SelfTestAsync(CancellationToken cancellationToken);
}
/// <summary>What the start-up self-test found; uploads are refused while the processor is not available.</summary>
public sealed class MediaStatus
{
private volatile bool _processorAvailable;
private volatile bool _directoryWritable;
public bool ProcessorAvailable => _processorAvailable;
public bool DirectoryWritable => _directoryWritable;
public bool UploadsAvailable => _processorAvailable && _directoryWritable;
public IReadOnlySet<ImageFormat> AcceptedInput { get; private set; } = new HashSet<ImageFormat>();
public IReadOnlySet<ImageFormat> Output { get; private set; } = new HashSet<ImageFormat>();
public void SetProcessor(bool available, IReadOnlySet<ImageFormat> input, IReadOnlySet<ImageFormat> output)
{
AcceptedInput = input;
Output = output;
_processorAvailable = available;
}
public void SetDirectory(bool writable) => _directoryWritable = writable;
}
/// <summary>Limits how many images are processed at once; a full gate answers "busy" after a short wait.</summary>
public sealed class MediaProcessingGate(IOptions<MediaOptions> options)
{
private readonly SemaphoreSlim _slots = new(Math.Max(1, options.Value.MaxParallelJobs));
private readonly TimeSpan _wait = TimeSpan.FromSeconds(Math.Max(0, options.Value.BusyWaitSeconds));
public async Task<IDisposable> EnterAsync(CancellationToken cancellationToken)
{
if (!await _slots.WaitAsync(_wait, cancellationToken))
{
throw new ImageRejectedException(ImageRejection.Busy, "All image processing slots are in use.");
}
return new Releaser(_slots);
}
private sealed class Releaser(SemaphoreSlim slots) : IDisposable
{
private int _released;
public void Dispose()
{
if (Interlocked.Exchange(ref _released, 1) == 0)
{
slots.Release();
}
}
}
}