docs(plan): resolve IRemoteImageValidator layering (Core has no ImageSharp)

Core interface returns Task (throws-on-invalid); render path uses a static
Infra method returning Image. Drops the GraphicsEngine threading. refs #525
This commit is contained in:
2026-07-21 13:13:21 +02:00
parent 185de69930
commit 21a4e4d34e
@@ -204,9 +204,14 @@ Extract the ImageSharp identify/decode/validate step so both the render path and
- Move: the ImageSharp-decode tests from `RemoteImageDecodeLimitTests.cs` → `ErsatzTV.Infrastructure.Tests/Images/RemoteImageValidatorTests.cs`
- Modify: `ErsatzTV.Infrastructure/Streaming/Graphics/GraphicsEngine.cs`, `Image/ImageElement.cs`, `Image/WatermarkElement.cs` (thread the validator through, same pattern as `IRemoteImageFetcher`)
**RESOLVED (was a VERIFY item): `ErsatzTV.Core` does NOT reference SixLabors.ImageSharp** (it has SkiaSharp only). So the Core interface must NOT return an ImageSharp `Image`. Final shape:
- Core interface `IRemoteImageValidator.Validate(Stream, Uri, CancellationToken) : Task` — throws on an invalid image (budget violation or corrupt stream), completes on valid. No ImageSharp type crosses Core. This is all the save/upload paths need.
- The render path keeps returning the decoded `Image`, but via a **static** method on the Infra `RemoteImageValidator` (`ImageElementBase` calls it directly — no interface, no DI threading through `GraphicsEngine`). This is a simplification vs. the original draft: no new constructor param on the graphics elements.
**Interfaces:**
- Produces:
- `IRemoteImageValidator.DecodeAndValidate(Stream stream, Uri uri, CancellationToken) : Task<Image>` (SixLabors `Image`; throws `InvalidOperationException` on a budget violation, ImageSharp exceptions on a corrupt stream; caller owns the returned `Image`)
- Core: `IRemoteImageValidator.Validate(Stream stream, Uri uri, CancellationToken) : Task` (throws `InvalidOperationException` on a budget violation / ImageSharp exception on a corrupt stream; returns on success)
- Infra static: `RemoteImageValidator.DecodeAndValidate(Stream stream, Uri uri, CancellationToken) : Task<Image>` (SixLabors `Image`; same throws; caller owns + disposes the returned `Image`) — used by `ImageElementBase` and internally by `Validate`
- Consumes: `RemoteImageDecodeBudget` (Task 1).
- [ ] **Step 1: Write the failing test** — move the existing decode tests and retarget them
@@ -226,13 +231,13 @@ namespace ErsatzTV.Infrastructure.Tests.Images;
public class RemoteImageValidatorTests
{
private static readonly Uri Uri = new("https://example.com/logo.png");
private readonly IRemoteImageValidator _validator = new RemoteImageValidator();
// decode cases exercise the static method (used by the render path)
[Test]
public async Task Should_Decode_A_Normal_Image()
{
await using MemoryStream stream = await RealPng(64, 32);
using Image image = await _validator.DecodeAndValidate(stream, Uri, CancellationToken.None);
using Image image = await RemoteImageValidator.DecodeAndValidate(stream, Uri, CancellationToken.None);
image.Width.ShouldBe(64);
image.Height.ShouldBe(32);
}
@@ -242,16 +247,16 @@ public class RemoteImageValidatorTests
{
await using MemoryStream stream = PngHeaderDeclaring(30000, 30000);
InvalidOperationException ex = await Should.ThrowAsync<InvalidOperationException>(
() => _validator.DecodeAndValidate(stream, Uri, CancellationToken.None));
() => RemoteImageValidator.DecodeAndValidate(stream, Uri, CancellationToken.None));
ex.Message.ShouldContain("pixel limit");
}
[Test]
public async Task Should_Reject_An_Apng_Whose_Header_Under_Reports_Its_Frames()
{
await using MemoryStream stream = Apng(64, 64, RemoteImageDecodeBudgetFrames + 100);
await using MemoryStream stream = Apng(64, 64, RemoteImageDecodeBudget.MaxRemoteFrames + 100);
InvalidOperationException ex = await Should.ThrowAsync<InvalidOperationException>(
() => _validator.DecodeAndValidate(stream, Uri, CancellationToken.None));
() => RemoteImageValidator.DecodeAndValidate(stream, Uri, CancellationToken.None));
ex.Message.ShouldContain("frame limit");
}
@@ -262,12 +267,30 @@ public class RemoteImageValidatorTests
stream.Position = 0;
await Should.ThrowAsync<Exception>(() => Image.IdentifyAsync(stream));
stream.Position = 0;
using Image image = await _validator.DecodeAndValidate(stream, Uri, CancellationToken.None);
using Image image = await RemoteImageValidator.DecodeAndValidate(stream, Uri, CancellationToken.None);
image.Frames.Count.ShouldBe(60);
}
// the Core interface Validate() is the save/upload contract: throws on invalid, returns on valid,
// never surfaces an ImageSharp type
[Test]
public async Task Validate_Returns_On_A_Good_Image()
{
IRemoteImageValidator validator = new RemoteImageValidator();
await using MemoryStream stream = await RealPng(64, 32);
await Should.NotThrowAsync(() => validator.Validate(stream, Uri, CancellationToken.None));
}
[Test]
public async Task Validate_Throws_On_A_Bomb()
{
IRemoteImageValidator validator = new RemoteImageValidator();
await using MemoryStream stream = PngHeaderDeclaring(30000, 30000);
await Should.ThrowAsync<InvalidOperationException>(
() => validator.Validate(stream, Uri, CancellationToken.None));
}
// (move RealPng / PngHeaderDeclaring / Apng / Crc32 helpers here verbatim from RemoteImageDecodeLimitTests)
private const int RemoteImageDecodeBudgetFrames = 600;
}
```
@@ -278,25 +301,25 @@ Expected: FAIL — `RemoteImageValidator` / `IRemoteImageValidator` do not exist
- [ ] **Step 3: Create the interface and implementation**
`ErsatzTV.Core/Interfaces/Images/IRemoteImageValidator.cs`:
`ErsatzTV.Core/Interfaces/Images/IRemoteImageValidator.cs` (NO ImageSharp — Core does not reference it):
```csharp
using SixLabors.ImageSharp;
namespace ErsatzTV.Core.Interfaces.Images;
/// <summary>
/// Decodes a remote image and enforces the decode budget on the decoder itself, returning the
/// decoded image. Shared by the graphics engine (which composites the result) and the logo save
/// path (which validates then discards it, caching the original bytes). (ersatztv#525)
/// Validates that a stream is a decodable image within the decode budget, throwing if not.
/// Used by the logo save path and the artwork upload path (neither needs the decoded pixels,
/// only "is this safe to cache"). The graphics engine uses the static
/// RemoteImageValidator.DecodeAndValidate instead, which returns the Image it composites.
/// (ersatztv#525)
/// </summary>
public interface IRemoteImageValidator
{
Task<Image> DecodeAndValidate(Stream stream, Uri uri, CancellationToken cancellationToken);
Task Validate(Stream stream, Uri uri, CancellationToken cancellationToken);
}
```
`ErsatzTV.Infrastructure/Images/RemoteImageValidator.cs` — move the body of `ImageElementBase.DecodeRemoteImage` here verbatim (the `!CanSeek` guard, the `MaxFrames = 1` Identify workaround, `RemoteImageDecodeBudget.*` calls, the `MaxFrames = affordable + 2` decode, the post-decode re-verify + dispose-on-throw). Class:
`ErsatzTV.Infrastructure/Images/RemoteImageValidator.cs` — move the body of `ImageElementBase.DecodeRemoteImage` here verbatim into the **static** `DecodeAndValidate` (the `!CanSeek` guard, the `MaxFrames = 1` Identify workaround, `RemoteImageDecodeBudget.*` calls, the `MaxFrames = affordable + 2` decode, the post-decode re-verify + dispose-on-throw). `Validate` wraps it and disposes:
```csharp
using ErsatzTV.Core.Images;
@@ -308,7 +331,12 @@ namespace ErsatzTV.Infrastructure.Images;
public class RemoteImageValidator : IRemoteImageValidator
{
public async Task<Image> DecodeAndValidate(Stream stream, Uri uri, CancellationToken cancellationToken)
public async Task Validate(Stream stream, Uri uri, CancellationToken cancellationToken)
{
using Image _ = await DecodeAndValidate(stream, uri, cancellationToken);
}
public static async Task<Image> DecodeAndValidate(Stream stream, Uri uri, CancellationToken cancellationToken)
{
// <verbatim body of ImageElementBase.DecodeRemoteImage, RemoteImageDecodeBudget.* for the
// three budget calls; see that method for the exact code and comments>
@@ -316,11 +344,9 @@ public class RemoteImageValidator : IRemoteImageValidator
}
```
Note (`ErsatzTV.Core` referencing `SixLabors.ImageSharp`): the interface's return type is `SixLabors.ImageSharp.Image`. `ErsatzTV.Core` already references ImageSharp transitively? VERIFY before relying on it: `grep -r "SixLabors.ImageSharp" ErsatzTV.Core/ErsatzTV.Core.csproj Directory.Packages.props`. If Core does NOT reference ImageSharp, change the interface to return the fetched bytes / a small `record RemoteImageInfo(int Width, int Height, int FrameCount)` instead of `Image`, keep the `Image` inside Infrastructure, and have the render path call a concrete Infrastructure method. Pick the byte/record option if in doubt — it keeps Core pure and the save path only needs "valid or not", not the `Image`.
- [ ] **Step 4: Delegate `DecodeRemoteImage` to the static method**
- [ ] **Step 4: Delegate `DecodeRemoteImage` and thread the validator**
`ImageElementBase`: constructor becomes `(IRemoteImageFetcher remoteImageFetcher, IRemoteImageValidator remoteImageValidator)`; `DecodeRemoteImage` body becomes `remoteImageValidator.DecodeAndValidate(...)`. Thread the new dep through `GraphicsEngine` (inject `IRemoteImageValidator`, pass to `new WatermarkElement(...)` / `new ImageElement(...)`) exactly as `IRemoteImageFetcher` is threaded today (see the #511 diff for the pattern). Register in `Startup.cs`: `services.AddScoped<IRemoteImageValidator, RemoteImageValidator>();`.
`ImageElementBase.DecodeRemoteImage` body becomes `return await RemoteImageValidator.DecodeAndValidate(stream, uri, cancellationToken);` (add `using ErsatzTV.Infrastructure.Images;`). **No** constructor change, **no** `GraphicsEngine` threading — the render path calls the static method directly (as it already calls `Image.LoadAsync` statically today). The existing `RemoteImageDecodeLimitTests` decode tests either move to `RemoteImageValidatorTests` (Step 1) or keep calling `ImageElementBase.DecodeRemoteImage` (which now delegates) — either is fine; do not duplicate. Register the interface for the save/upload paths in `Startup.cs`: `services.AddScoped<IRemoteImageValidator, RemoteImageValidator>();`.
- [ ] **Step 5: Run tests to verify they pass**
@@ -383,7 +409,7 @@ public class RemoteLogoCacherTests
var fetcher = Substitute.For<IRemoteImageFetcher>();
fetcher.Fetch(Uri, Arg.Any<CancellationToken>()).Returns(png);
var validator = Substitute.For<IRemoteImageValidator>();
validator.DecodeAndValidate(png, Uri, Arg.Any<CancellationToken>()).Returns(new Image<Rgba32>(64, 64));
validator.Validate(png, Uri, Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
var cache = Substitute.For<IImageCache>();
cache.SaveArtworkToCache(Arg.Any<Stream>(), ArtworkKind.Logo).Returns(Right<BaseError, string>("abc123"));
@@ -414,8 +440,8 @@ public class RemoteLogoCacherTests
var fetcher = Substitute.For<IRemoteImageFetcher>();
fetcher.Fetch(Uri, Arg.Any<CancellationToken>()).Returns(png);
var validator = Substitute.For<IRemoteImageValidator>();
validator.DecodeAndValidate(png, Uri, Arg.Any<CancellationToken>())
.Returns<Image>(_ => throw new InvalidOperationException("over the 50000000 pixel limit"));
validator.Validate(png, Uri, Arg.Any<CancellationToken>())
.Returns<Task>(_ => throw new InvalidOperationException("over the 50000000 pixel limit"));
var cacher = new RemoteLogoCacher(fetcher, validator, Substitute.For<IImageCache>());
Either<BaseError, string> result = await cacher.CacheFromUrl(Uri, CancellationToken.None);
@@ -469,7 +495,6 @@ using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Images;
using ErsatzTV.Core.Interfaces.Streaming;
using LanguageExt;
using SixLabors.ImageSharp;
namespace ErsatzTV.Infrastructure.Images;
@@ -484,10 +509,8 @@ public class RemoteLogoCacher(
{
await using Stream stream = await fetcher.Fetch(uri, cancellationToken);
// validate by decoding under the budget; dispose the decoded image, we cache raw bytes
using (Image _ = await validator.DecodeAndValidate(stream, uri, cancellationToken))
{
}
// validate by decoding under the budget (throws if unsafe); we cache the raw bytes
await validator.Validate(stream, uri, cancellationToken);
stream.Position = 0;
return await imageCache.SaveArtworkToCache(stream, ArtworkKind.Logo);
@@ -504,7 +527,7 @@ public class RemoteLogoCacher(
}
```
Note: `IRemoteImageFetcher.Fetch` returns a seekable, fully-buffered stream at position 0 (its contract), so `stream.Position = 0` after validation rewinds it for the cache write. If Task 2 changed the validator to return bytes/record instead of `Image`, adjust the `using` accordingly.
Note: `IRemoteImageFetcher.Fetch` returns a seekable, fully-buffered stream at position 0 (its contract), so `stream.Position = 0` after validation rewinds it for the cache write.
Register in `Startup.cs`: `services.AddScoped<IRemoteLogoCacher, RemoteLogoCacher>();`.
@@ -709,8 +732,7 @@ Run: `dotnet test ErsatzTV.Tests/ErsatzTV.Tests.csproj --filter "FullyQualifiedN
{
try
{
using Image _ = await validator.DecodeAndValidate(
probe, new Uri("upload://artwork"), cancellationToken);
await validator.Validate(probe, new Uri("upload://artwork"), cancellationToken);
}
catch (Exception ex)
{
@@ -719,7 +741,7 @@ Run: `dotnet test ErsatzTV.Tests/ErsatzTV.Tests.csproj --filter "FullyQualifiedN
}
```
(`upload://artwork` is a synthetic Uri for the message; the validator only uses it for text. If Task 2 made the validator return a record/bytes rather than `Image`, drop the `using`.)
(`upload://artwork` is a synthetic Uri for the message text only.)
- [ ] **Step 4: Run to verify pass.** → PASS. Also run the full `Artworks` + `Channels` test folders.
@@ -874,4 +896,4 @@ git push -u origin feat/525-external-logo-download-on-save
**Placeholder scan:** the two `<verbatim body …>` markers in Task 2 point at an exact existing method (`ImageElementBase.DecodeRemoteImage`, quoted in the spec's source recon) to move unchanged — not new logic to invent. One explicit VERIFY (does `ErsatzTV.Core` reference ImageSharp) with a stated fallback, because the answer changes the interface signature and must be checked in-repo rather than guessed.
**Type consistency:** `IRemoteLogoCacher.CacheFromUrl → Task<Either<BaseError,string>>` (Task 3) is what Tasks 4/5/8 consume; `IRemoteImageValidator.DecodeAndValidate → Task<Image>` (Task 2) is what Tasks 3/6 consume and what `ImageElementBase` delegates to; `RemoteImageDecodeBudget` static members (Task 1) are consumed by Tasks 2 and (transitively) 6. Names match across tasks.
**Type consistency:** `IRemoteLogoCacher.CacheFromUrl → Task<Either<BaseError,string>>` (Task 3) is what Tasks 4/5/8 consume; the Core `IRemoteImageValidator.Validate → Task` (Task 2, throws-on-invalid, no ImageSharp type) is what Tasks 3/6 consume; the Infra static `RemoteImageValidator.DecodeAndValidate → Task<Image>` (Task 2) is what `ImageElementBase` delegates to; `RemoteImageDecodeBudget` static members (Task 1) are consumed by Task 2. Names match across tasks. **Layering note resolved:** Core does not reference ImageSharp, so the Core interface returns `Task`, not `Image`.