Fase 2 stap C: leesschakelaar (off/compare/on) voor het bibliotheekscherm, read-check endpoint, workflow-input

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 23:25:14 +01:00
co-authored by Claude Sonnet 5.5
parent 3558e91fde
commit e1010007fa
16 changed files with 633 additions and 6 deletions
@@ -103,4 +103,33 @@ public class MediaLibraryControllerTests
result.Should().Be(new MediaStorageDto(0, 0, "ok", 80));
}
[Fact]
public async Task The_read_check_lists_what_each_module_found_and_the_mode()
{
var library = Substitute.For<IMediaLibraryService>();
library.Modules.Returns(["hero"]);
var verifier = Substitute.For<IMediaReadVerifier>();
verifier.CheckAsync(Arg.Any<CancellationToken>()).Returns(new MediaReadCheck("hero", MediaReadMode.Compare, 3, 2, ["photo x is missing in the library"]));
var reader = Substitute.For<IMediaLibraryReader>();
reader.Mode.Returns(MediaReadMode.Compare);
var result = await new MediaLibraryController(library, new Clock(), null, [verifier], reader).ReadCheck(CancellationToken.None);
var response = result.Should().BeOfType<OkObjectResult>().Subject.Value.Should().BeOfType<MediaReadCheckResponse>().Subject;
response.Mode.Should().Be("compare");
response.Modules.Should().ContainSingle().Which.Should().Match<MediaReadCheckDto>(m => m.Module == "hero" && m.Photos == 3 && m.Uses == 2 && !m.Matches && m.Differences.Count == 1);
}
[Fact]
public async Task The_read_check_without_modules_says_off_and_nothing()
{
var library = Substitute.For<IMediaLibraryService>();
var result = await new MediaLibraryController(library, new Clock()).ReadCheck(CancellationToken.None);
var response = result.Should().BeOfType<OkObjectResult>().Subject.Value.Should().BeOfType<MediaReadCheckResponse>().Subject;
response.Mode.Should().Be("off");
response.Modules.Should().BeEmpty();
}
}
@@ -88,6 +88,7 @@ public static class ServiceCollectionExtensions
// The media library reads from the usage providers of whichever modules are loaded (none is fine).
services.TryAddScoped<Media.Library.IMediaLibraryService, Media.Library.MediaLibraryService>();
services.TryAddScoped<Media.Library.IMediaLibrarySync, Media.Library.NoMediaLibrarySync>();
services.TryAddScoped<Media.Library.IMediaLibraryReader, Media.Library.NoMediaLibraryReader>();
services.TryAddSingleton(sp =>
new ResetCooldown(sp.GetRequiredService<TimeProvider>(), TimeSpan.FromMinutes(sp.GetRequiredService<IOptions<PasswordResetSettings>>().Value.CooldownMinutes)));
services.AddScoped<IPasswordResetService, PasswordResetService>();
@@ -20,6 +20,11 @@ public sealed record MediaPhotoDto(
DateTimeOffset? UnusedSince = null,
DateTimeOffset? DeletedAt = null);
/// <summary>The result of comparing a module's own tables with the library tables (read switch, phase 2 step C).</summary>
public sealed record MediaReadCheckDto(string Module, string Mode, int Photos, int Uses, bool Matches, IReadOnlyList<string> Differences);
public sealed record MediaReadCheckResponse(string Mode, IReadOnlyList<MediaReadCheckDto> Modules);
public sealed record MediaLibraryDto(IReadOnlyList<MediaPhotoDto> Photos, IReadOnlyList<string> Modules);
public sealed record MediaStorageDto(long UsedBytes, long LimitBytes, string Level, int WarningPercent);
@@ -49,8 +54,26 @@ public sealed record MediaTrashResponse(IReadOnlyList<MediaUseResultDto> Results
[ApiController]
[Route("media-library")]
[Authorize(Policy = "AdminOnly")]
public class MediaLibraryController(IMediaLibraryService library, TimeProvider time, MediaStorageUsage? storage = null) : ControllerBase
public class MediaLibraryController(IMediaLibraryService library, TimeProvider time, MediaStorageUsage? storage = null, IEnumerable<IMediaReadVerifier>? verifiers = null, IMediaLibraryReader? reader = null) : ControllerBase
{
/// <summary>
/// Compares what each module holds with what the library's own tables hold and lists every difference. Read-only; works
/// whatever the read switch says, so it can be used before the switch is turned on.
/// </summary>
[HttpGet("read-check")]
[ProducesResponseType<MediaReadCheckResponse>(StatusCodes.Status200OK)]
public async Task<IActionResult> ReadCheck(CancellationToken cancellationToken)
{
var results = new List<MediaReadCheckDto>();
foreach (var verifier in verifiers ?? [])
{
var check = await verifier.CheckAsync(cancellationToken);
results.Add(new MediaReadCheckDto(check.Module, check.Mode.ToString().ToLowerInvariant(), check.Photos, check.Uses, check.Matches, check.Differences.Take(50).ToList()));
}
return Ok(new MediaReadCheckResponse((reader?.Mode ?? MediaReadMode.Off).ToString().ToLowerInvariant(), results));
}
[HttpGet("photos")]
[ProducesResponseType<MediaLibraryDto>(StatusCodes.Status200OK)]
public async Task<IActionResult> Photos(CancellationToken cancellationToken)
@@ -0,0 +1,110 @@
namespace SlpModularCms.Core.Media.Library;
/// <summary>Where the media library screen reads the photos of a module from (migration phase 2, step C).</summary>
public enum MediaReadMode
{
/// <summary>The module's own tables (the default, and the truth until phase 3).</summary>
Off,
/// <summary>Still the module's own tables, but the library tables are read too and every difference is logged and reported.</summary>
Compare,
/// <summary>The library tables. Needs the write-through (<c>Media:Library:DualWrite</c>) to be current.</summary>
On,
}
/// <summary>Reads a module's photos and uses back from the library's own tables.</summary>
public interface IMediaLibraryReader
{
MediaReadMode Mode { get; }
Task<IReadOnlyList<MediaAssetSnapshot>> ListAssetsAsync(string module, CancellationToken cancellationToken);
Task<IReadOnlyList<MediaUseSnapshot>> ListUsesAsync(string module, CancellationToken cancellationToken);
}
/// <summary>The default: no library tables to read, so everything stays with the module.</summary>
public sealed class NoMediaLibraryReader : IMediaLibraryReader
{
public MediaReadMode Mode => MediaReadMode.Off;
public Task<IReadOnlyList<MediaAssetSnapshot>> ListAssetsAsync(string module, CancellationToken cancellationToken) => Task.FromResult<IReadOnlyList<MediaAssetSnapshot>>([]);
public Task<IReadOnlyList<MediaUseSnapshot>> ListUsesAsync(string module, CancellationToken cancellationToken) => Task.FromResult<IReadOnlyList<MediaUseSnapshot>>([]);
}
/// <summary>What a comparison of a module's own tables with the library tables found. <c>Differences</c> is empty when they agree.</summary>
public sealed record MediaReadCheck(string Module, MediaReadMode Mode, int Photos, int Uses, IReadOnlyList<string> Differences)
{
public bool Matches => Differences.Count == 0;
}
/// <summary>A module that can compare its own data with the library tables (used by <c>GET media-library/read-check</c>).</summary>
public interface IMediaReadVerifier
{
string Module { get; }
Task<MediaReadCheck> CheckAsync(CancellationToken cancellationToken);
}
/// <summary>Compares what a module holds with what the library tables hold, by id, and lists every difference in words.</summary>
public static class MediaReadComparer
{
public static IReadOnlyList<string> Compare(
IReadOnlyList<MediaAssetSnapshot> ownAssets,
IReadOnlyList<MediaUseSnapshot> ownUses,
IReadOnlyList<MediaAssetSnapshot> libraryAssets,
IReadOnlyList<MediaUseSnapshot> libraryUses)
{
var differences = new List<string>();
var library = libraryAssets.ToDictionary(a => a.Id);
foreach (var own in ownAssets)
{
if (!library.Remove(own.Id, out var copy))
{
differences.Add($"photo {own.Id} is missing in the library");
continue;
}
if (own.OriginalSha256 != copy.OriginalSha256 || own.OriginalKey != copy.OriginalKey || own.Bytes != copy.Bytes)
{
differences.Add($"photo {own.Id}: hash, key or size differs");
}
if ((own.DeletedAt is null) != (copy.DeletedAt is null))
{
differences.Add($"photo {own.Id}: trash state differs");
}
if (own.OriginalFileName != copy.OriginalFileName)
{
differences.Add($"photo {own.Id}: file name differs");
}
if (own.LastUsedAt?.ToUnixTimeSeconds() != copy.LastUsedAt?.ToUnixTimeSeconds())
{
differences.Add($"photo {own.Id}: last used differs");
}
}
differences.AddRange(library.Keys.Select(id => $"photo {id} is in the library but not in the module"));
var libraryUsesById = libraryUses.ToDictionary(u => u.Id);
foreach (var own in ownUses)
{
if (!libraryUsesById.Remove(own.Id, out var copy))
{
differences.Add($"use {own.Id} is missing in the library");
continue;
}
if (own.AssetId != copy.AssetId || own.Position != copy.Position || own.Active != copy.Active || own.SetHash != copy.SetHash)
{
differences.Add($"use {own.Id}: photo, position, active flag or set hash differs");
}
}
differences.AddRange(libraryUsesById.Keys.Select(id => $"use {id} is in the library but not in the module"));
return differences;
}
}
@@ -0,0 +1,124 @@
using FluentAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using SlpModularCms.Core.Media.Library;
using SlpModularCms.Modules.Hero.Models;
using SlpModularCms.Modules.Hero.Services;
using Xunit;
namespace SlpModularCms.Modules.Hero.Tests;
/// <summary>Phase 2, step C: the library screen reads the hero's photos from the library tables (on), or compares (compare).</summary>
public class HeroReadFromLibraryTests
{
private sealed class FakeReader(MediaReadMode mode, List<MediaAssetSnapshot> assets, List<MediaUseSnapshot> uses, bool fails = false) : IMediaLibraryReader
{
public MediaReadMode Mode => mode;
public Task<IReadOnlyList<MediaAssetSnapshot>> ListAssetsAsync(string module, CancellationToken cancellationToken)
=> fails ? throw new InvalidOperationException("library down") : Task.FromResult<IReadOnlyList<MediaAssetSnapshot>>(assets.ToList());
public Task<IReadOnlyList<MediaUseSnapshot>> ListUsesAsync(string module, CancellationToken cancellationToken)
=> fails ? throw new InvalidOperationException("library down") : Task.FromResult<IReadOnlyList<MediaUseSnapshot>>(uses.ToList());
}
private static HeroSaveRequest Request(params HeroSlideRequest[] slides) => new("Titel", null, null, "slideshow", [], slides);
/// <summary>A hero with two photos, one in a slide, one not; the library tables made equal to it.</summary>
private static async Task<(HeroTestRig Rig, List<MediaAssetSnapshot> Assets, List<MediaUseSnapshot> Uses, Guid Used, Guid Unused)> ArrangeAsync()
{
var rig = new HeroTestRig();
var used = Guid.Parse((await rig.Upload(HeroTestRig.Photo())).Id);
var unused = Guid.Parse((await rig.Upload(HeroTestRig.Photo(seed: 7))).Id);
await rig.Service.SaveAsync(Request(new HeroSlideRequest(null, used, "een")), HeroTestRig.Admin, CancellationToken.None);
var source = new HeroMediaMigrationSource(rig.Repository);
return (rig, (await source.ListAssetsAsync(CancellationToken.None)).ToList(), (await source.ListUsesAsync(CancellationToken.None)).ToList(), used, unused);
}
private static HeroMediaUsageProvider Provider(HeroTestRig rig, IMediaLibraryReader? reader) => new(rig.Repository, rig.Images, reader, NullLogger<HeroMediaUsageProvider>.Instance);
[Fact]
public async Task With_the_switch_off_the_heros_own_tables_answer_and_the_library_is_not_asked()
{
var (rig, assets, uses, used, _) = await ArrangeAsync();
using var _r = rig;
assets.RemoveAll(a => a.Id == used);
var photos = await Provider(rig, new FakeReader(MediaReadMode.Off, assets, uses, fails: true)).ListPhotosAsync(CancellationToken.None);
photos.Should().HaveCount(2);
}
[Fact]
public async Task On_answers_from_the_library_tables_with_the_thumbnail_of_the_hero()
{
var (rig, assets, uses, used, unused) = await ArrangeAsync();
using var _r = rig;
// The library knows a file name the hero does not (proof that the answer comes from the library) and lacks the unused photo.
assets[assets.FindIndex(a => a.Id == used)] = assets.Single(a => a.Id == used) with { OriginalFileName = "uit-de-bibliotheek.jpg" };
assets.RemoveAll(a => a.Id == unused);
var provider = Provider(rig, new FakeReader(MediaReadMode.On, assets, uses));
var photos = await provider.ListPhotosAsync(CancellationToken.None);
photos.Should().ContainSingle().Which.Should().Match<MediaPhoto>(p => p.Id == used && p.OriginalFileName == "uit-de-bibliotheek.jpg" && p.ThumbnailUrl != null && p.ThumbnailUrl.StartsWith("/media/hero/"));
(await provider.ListUsesAsync([used, unused], CancellationToken.None)).Should().ContainSingle().Which.Should().Match<MediaUse>(u => u.PhotoId == used && u.Position == 1 && u.PlaceKind == "slide");
}
[Fact]
public async Task On_splits_the_library_into_photos_and_trash_by_the_deleted_date()
{
var (rig, assets, uses, used, unused) = await ArrangeAsync();
using var _r = rig;
assets[assets.FindIndex(a => a.Id == unused)] = assets.Single(a => a.Id == unused) with { DeletedAt = DateTimeOffset.UtcNow };
var provider = Provider(rig, new FakeReader(MediaReadMode.On, assets, uses));
(await provider.ListPhotosAsync(CancellationToken.None)).Select(p => p.Id).Should().Equal(used);
(await provider.ListTrashAsync(CancellationToken.None)).Select(p => p.Id).Should().Equal(unused);
}
[Fact]
public async Task On_falls_back_to_the_heros_own_tables_when_the_library_cannot_be_read()
{
var (rig, assets, uses, _, _) = await ArrangeAsync();
using var _r = rig;
var provider = Provider(rig, new FakeReader(MediaReadMode.On, assets, uses, fails: true));
(await provider.ListPhotosAsync(CancellationToken.None)).Should().HaveCount(2);
(await provider.ListUsesAsync([Guid.NewGuid()], CancellationToken.None)).Should().BeEmpty();
(await provider.ListTrashAsync(CancellationToken.None)).Should().BeEmpty();
}
[Fact]
public async Task Compare_still_answers_from_the_heros_tables_and_the_check_lists_every_difference()
{
var (rig, assets, uses, used, unused) = await ArrangeAsync();
using var _r = rig;
assets.RemoveAll(a => a.Id == unused);
assets[assets.FindIndex(a => a.Id == used)] = assets.Single(a => a.Id == used) with { Bytes = 1 };
uses[0] = uses[0] with { Position = 9 };
var provider = Provider(rig, new FakeReader(MediaReadMode.Compare, assets, uses));
(await provider.ListPhotosAsync(CancellationToken.None)).Should().HaveCount(2, "compare never changes the answer");
var check = await provider.CheckAsync(CancellationToken.None);
check.Matches.Should().BeFalse();
check.Mode.Should().Be(MediaReadMode.Compare);
check.Photos.Should().Be(2);
check.Uses.Should().Be(1);
check.Differences.Should().Contain(d => d.Contains(unused.ToString()) && d.Contains("missing in the library"));
check.Differences.Should().Contain(d => d.Contains(used.ToString()) && d.Contains("hash, key or size"));
check.Differences.Should().Contain(d => d.StartsWith("use ") && d.Contains("position"));
}
[Fact]
public async Task The_check_agrees_when_the_library_is_a_mirror_of_the_hero()
{
var (rig, assets, uses, _, _) = await ArrangeAsync();
using var _r = rig;
var check = await Provider(rig, new FakeReader(MediaReadMode.Compare, assets, uses)).CheckAsync(CancellationToken.None);
check.Matches.Should().BeTrue();
check.Differences.Should().BeEmpty();
}
}
+3 -1
View File
@@ -45,7 +45,9 @@ public class HeroModule : IModule
services.AddScoped<IHeroService, HeroService>();
services.AddScoped<IPublicHeroService, PublicHeroService>();
services.AddScoped<IHeroImageService, HeroImageService>();
services.AddScoped<IMediaUsageProvider, HeroMediaUsageProvider>();
services.AddScoped<HeroMediaUsageProvider>();
services.AddScoped<IMediaUsageProvider>(provider => provider.GetRequiredService<HeroMediaUsageProvider>());
services.AddScoped<IMediaReadVerifier>(provider => provider.GetRequiredService<HeroMediaUsageProvider>());
services.AddScoped<IMediaMigrationSource, HeroMediaMigrationSource>();
services.AddScoped<IHeroPageModel, HeroPageModel>();
services.AddScoped<IHtmlPageTransform, HeroHtmlTransform>();
@@ -1,3 +1,4 @@
using Microsoft.Extensions.Logging;
using SlpModularCms.Core.Media;
using SlpModularCms.Core.Media.Library;
using SlpModularCms.Modules.Hero.Data.Entities;
@@ -9,21 +10,59 @@ namespace SlpModularCms.Modules.Hero.Services;
/// Tells the media library which hero images exist and where they are used (one use per slide, with its position in the
/// hero), and moves them to the trash and back for it. The files are removed by <see cref="HeroMediaCleanup"/> after the trash period.
/// </summary>
public class HeroMediaUsageProvider(IHeroRepository repository, IHeroImageService images) : IMediaUsageProvider
public class HeroMediaUsageProvider(
IHeroRepository repository,
IHeroImageService images,
IMediaLibraryReader? reader = null,
ILogger<HeroMediaUsageProvider>? logger = null) : IMediaUsageProvider, IMediaReadVerifier
{
public const string SlideKind = "slide";
public string Module => HeroMapping.Area;
private MediaReadMode Mode => reader?.Mode ?? MediaReadMode.Off;
public async Task<IReadOnlyList<MediaPhoto>> ListPhotosAsync(CancellationToken cancellationToken)
=> (await repository.GetAllImagesReadOnlyAsync(cancellationToken)).Select(ToPhoto).ToList();
{
if (Mode == MediaReadMode.On && await TryReadPhotosAsync(trash: false, cancellationToken) is { } fromLibrary)
{
return fromLibrary;
}
await CompareInTheLogAsync(cancellationToken);
return (await repository.GetAllImagesReadOnlyAsync(cancellationToken)).Select(ToPhoto).ToList();
}
public async Task<IReadOnlyList<MediaPhoto>> ListTrashAsync(CancellationToken cancellationToken)
=> (await repository.GetTrashedImagesReadOnlyAsync(cancellationToken)).Select(ToPhoto).ToList();
{
if (Mode == MediaReadMode.On && await TryReadPhotosAsync(trash: true, cancellationToken) is { } fromLibrary)
{
return fromLibrary;
}
return (await repository.GetTrashedImagesReadOnlyAsync(cancellationToken)).Select(ToPhoto).ToList();
}
public async Task<IReadOnlyList<MediaUse>> ListUsesAsync(IReadOnlyCollection<Guid> photoIds, CancellationToken cancellationToken)
{
var wanted = photoIds.ToHashSet();
if (Mode == MediaReadMode.On)
{
try
{
return (await reader!.ListUsesAsync(Module, cancellationToken))
.Where(u => wanted.Contains(u.AssetId))
.GroupBy(u => u.AssetId)
.SelectMany(g => g.OrderBy(u => u.Position))
.Select(u => new MediaUse(Module, u.AssetId, u.PlaceKind, u.Position, u.Active))
.ToList();
}
catch (Exception exception) when (exception is not OperationCanceledException)
{
logger?.LogError(exception, "Reading the hero uses from the media library failed; the hero's own tables are used instead.");
}
}
var slides = await repository.GetAllSlidesReadOnlyAsync(cancellationToken);
// The position of a slide is its place in its hero, in display order (1-based), also for slides that are off.
@@ -44,6 +83,64 @@ public class HeroMediaUsageProvider(IHeroRepository repository, IHeroImageServic
return uses;
}
/// <summary>
/// The photos of the library tables (identity, size, name, dates), with the thumbnail from the hero (the variants are not in
/// the library tables until phase 3). Null when the library cannot be read: the hero's own tables are used then.
/// </summary>
private async Task<IReadOnlyList<MediaPhoto>?> TryReadPhotosAsync(bool trash, CancellationToken cancellationToken)
{
try
{
var assets = (await reader!.ListAssetsAsync(Module, cancellationToken)).Where(a => (a.DeletedAt is not null) == trash).ToList();
var own = (await repository.GetAllImagesIncludingTrashedReadOnlyAsync(cancellationToken)).ToDictionary(i => i.Id);
var photos = assets.Select(a => new MediaPhoto(
Module, a.Id, a.Bytes, a.Width, a.Height, a.CreatedAt, own.TryGetValue(a.Id, out var image) ? Thumbnail(image) : null, a.OriginalFileName, a.LastUsedAt, a.DeletedAt));
return (trash ? photos.OrderByDescending(p => p.DeletedAt) : photos.OrderByDescending(p => p.CreatedAt)).ToList();
}
catch (Exception exception) when (exception is not OperationCanceledException)
{
logger?.LogError(exception, "Reading the hero photos from the media library failed; the hero's own tables are used instead.");
return null;
}
}
/// <summary>In compare mode: every difference between the hero's tables and the library tables is a warning in the log.</summary>
private async Task CompareInTheLogAsync(CancellationToken cancellationToken)
{
if (Mode != MediaReadMode.Compare)
{
return;
}
try
{
var check = await CheckAsync(cancellationToken);
foreach (var difference in check.Differences.Take(20))
{
logger?.LogWarning("Media library read check (hero): {Difference}", difference);
}
if (check.Differences.Count > 20)
{
logger?.LogWarning("Media library read check (hero): {More} more differences not listed.", check.Differences.Count - 20);
}
}
catch (Exception exception) when (exception is not OperationCanceledException)
{
logger?.LogError(exception, "The media library read check of the hero failed.");
}
}
public async Task<MediaReadCheck> CheckAsync(CancellationToken cancellationToken)
{
var source = new HeroMediaMigrationSource(repository);
var ownAssets = await source.ListAssetsAsync(cancellationToken);
var ownUses = await source.ListUsesAsync(cancellationToken);
var libraryAssets = await reader!.ListAssetsAsync(Module, cancellationToken);
var libraryUses = await reader.ListUsesAsync(Module, cancellationToken);
return new MediaReadCheck(Module, Mode, ownAssets.Count, ownUses.Count, MediaReadComparer.Compare(ownAssets, ownUses, libraryAssets, libraryUses));
}
public async Task<int?> TrashAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken)
{
try
@@ -0,0 +1,70 @@
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Media.Library;
using SlpModularCms.Modules.Media.Data;
using SlpModularCms.Modules.Media.Services;
namespace SlpModularCms.Modules.Media.Tests;
/// <summary>Phase 2, step C: reading the library tables back, per module, and the mode from the setting.</summary>
public class MediaLibraryReaderTests : IDisposable
{
private static readonly DateTimeOffset Now = new(2026, 11, 17, 12, 0, 0, TimeSpan.Zero);
private readonly MediaDbContext _db = new(new DbContextOptionsBuilder<MediaDbContext>().UseInMemoryDatabase("media-read-" + Guid.NewGuid()).Options);
public void Dispose() => _db.Dispose();
private sealed class Source(string module, List<MediaAssetSnapshot> assets, List<MediaUseSnapshot> uses) : IMediaMigrationSource
{
public string Module => module;
public Task<IReadOnlyList<MediaAssetSnapshot>> ListAssetsAsync(CancellationToken cancellationToken) => Task.FromResult<IReadOnlyList<MediaAssetSnapshot>>(assets);
public Task<IReadOnlyList<MediaUseSnapshot>> ListUsesAsync(CancellationToken cancellationToken) => Task.FromResult<IReadOnlyList<MediaUseSnapshot>>(uses);
}
private static MediaAssetSnapshot Asset(string module)
=> new(Guid.NewGuid(), module, Guid.NewGuid().ToString("N") + Guid.NewGuid().ToString("N"), "originals/x.jpg", "jpg", 3000, 2000, 2_000_000, 0.5, 0.5, 1, "0123456789abcdef",
[new MediaCropSnapshot("wide", 0.5, 0.5, 1)], Now.AddDays(-9), Guid.NewGuid(), "zomer.jpg", Now.AddDays(-2), null);
[Fact]
public async Task Reads_back_what_was_mirrored_for_one_module_and_agrees_with_the_comparer()
{
var hero = Asset("hero");
var other = Asset("gallery");
var use = new MediaUseSnapshot(Guid.NewGuid(), hero.Id, "hero", "slide", 2, false, "fedcba9876543210");
await new MediaLibraryCopier(_db, [new Source("hero", [hero], [use]), new Source("gallery", [other], [])], NullLogger<MediaLibraryCopier>.Instance).CopyAsync(CancellationToken.None);
var reader = new MediaLibraryReader(_db, Options.Create(new MediaLibraryOptions { ReadFromLibrary = MediaReadMode.Compare }));
var assets = await reader.ListAssetsAsync("hero", CancellationToken.None);
var uses = await reader.ListUsesAsync("hero", CancellationToken.None);
reader.Mode.Should().Be(MediaReadMode.Compare);
assets.Should().ContainSingle().Which.Should().Match<MediaAssetSnapshot>(a => a.Id == hero.Id && a.OriginalFileName == "zomer.jpg" && a.Bytes == 2_000_000);
uses.Should().ContainSingle().Which.Should().Match<MediaUseSnapshot>(u => u.Id == use.Id && u.Position == 2 && !u.Active && u.SetHash == "fedcba9876543210");
MediaReadComparer.Compare([hero], [use], assets, uses).Should().BeEmpty();
}
[Fact]
public void The_mode_is_off_by_default()
=> new MediaLibraryReader(_db, Options.Create(new MediaLibraryOptions())).Mode.Should().Be(MediaReadMode.Off);
[Fact]
public void The_comparer_reports_missing_extra_and_changed_rows()
{
var a = Asset("hero");
var b = Asset("hero");
var useA = new MediaUseSnapshot(Guid.NewGuid(), a.Id, "hero", "slide", 1, true, "aaaa");
var ghost = new MediaUseSnapshot(Guid.NewGuid(), a.Id, "hero", "slide", 2, true, "aaaa");
var differences = MediaReadComparer.Compare([a, b], [useA], [a with { Bytes = 5 }, Asset("hero")], [useA with { Active = false }, ghost]);
differences.Should().Contain(d => d.Contains(b.Id.ToString()) && d.Contains("missing in the library"));
differences.Should().Contain(d => d.Contains(a.Id.ToString()) && d.Contains("hash, key or size"));
differences.Should().Contain(d => d.Contains("in the library but not in the module"));
differences.Should().Contain(d => d.StartsWith("use ") && d.Contains("differs"));
differences.Should().Contain(d => d.Contains(ghost.Id.ToString()));
}
}
@@ -16,4 +16,11 @@ public class MediaLibraryOptions
/// the library tables are mirrored too. Off by default; the modules' own tables stay the truth.
/// </summary>
public bool DualWrite { get; set; }
/// <summary>
/// Where the library screen reads the photos from (phase 2, step C, <c>Media__Library__ReadFromLibrary</c>): <c>Off</c> (the
/// module's own tables, the default), <c>Compare</c> (still those, but differences with the library tables are logged and
/// shown by <c>GET media-library/read-check</c>) or <c>On</c> (the library tables; needs <c>DualWrite</c>).
/// </summary>
public SlpModularCms.Core.Media.Library.MediaReadMode ReadFromLibrary { get; set; } = SlpModularCms.Core.Media.Library.MediaReadMode.Off;
}
@@ -39,6 +39,7 @@ public class MediaModule : IModule
configuration.GetSection(MediaLibraryOptions.SectionName).Bind(options));
services.AddScoped<MediaLibraryCopier>();
services.Replace(ServiceDescriptor.Scoped<IMediaLibrarySync, MediaLibrarySync>());
services.Replace(ServiceDescriptor.Scoped<IMediaLibraryReader, MediaLibraryReader>());
services.AddHostedService<MediaLibraryCopyService>();
}
@@ -0,0 +1,24 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Media.Library;
using SlpModularCms.Modules.Media.Data;
namespace SlpModularCms.Modules.Media.Services;
/// <summary>Reads a module's photos and uses back from the library's own tables (phase 2, step C).</summary>
public sealed class MediaLibraryReader(MediaDbContext db, IOptions<MediaLibraryOptions> options) : IMediaLibraryReader
{
public MediaReadMode Mode => options.Value.ReadFromLibrary;
public async Task<IReadOnlyList<MediaAssetSnapshot>> ListAssetsAsync(string module, CancellationToken cancellationToken)
=> (await db.MediaAssets.AsNoTracking().Where(a => a.Module == module).ToListAsync(cancellationToken))
.Select(a => new MediaAssetSnapshot(
a.Id, a.Module, a.OriginalSha256, a.OriginalKey, a.SourceFormat, a.Width, a.Height, a.Bytes,
a.DefaultFocusX, a.DefaultFocusY, a.DefaultZoom, string.Empty, [], a.CreatedAt, a.CreatedByUserId, a.OriginalFileName, a.LastUsedAt, a.DeletedAt))
.ToList();
public async Task<IReadOnlyList<MediaUseSnapshot>> ListUsesAsync(string module, CancellationToken cancellationToken)
=> (await db.MediaUses.AsNoTracking().Where(u => u.Module == module).ToListAsync(cancellationToken))
.Select(u => new MediaUseSnapshot(u.Id, u.AssetId, u.Module, u.PlaceKind, u.Position, u.Active, u.SetHash))
.ToList();
}