Fase 2 stap A: write-through van de Hero naar de bibliotheek (schakelaar uit), per-slide uitsnede en set in de bibliotheek

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 23:05:35 +01:00
co-authored by Claude Sonnet 5.5
parent ed0b6ad61c
commit 369bf73666
18 changed files with 332 additions and 15 deletions
@@ -87,6 +87,7 @@ public static class ServiceCollectionExtensions
services.TryAddSingleton(TimeProvider.System);
// 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.TryAddSingleton(sp =>
new ResetCooldown(sp.GetRequiredService<TimeProvider>(), TimeSpan.FromMinutes(sp.GetRequiredService<IOptions<PasswordResetSettings>>().Value.CooldownMinutes)));
services.AddScoped<IPasswordResetService, PasswordResetService>();
@@ -0,0 +1,19 @@
namespace SlpModularCms.Core.Media.Library;
/// <summary>
/// Write-through of a module's photos and uses into the media library's own tables (migration phase 2, step A). A module
/// calls it after every change it saved to its OWN tables, which stay the truth until phase 3. It never throws and never
/// changes the module's data: a failure is logged by the implementation and the next sync (or the verified copy) repairs it.
/// With the switch <c>Media:Library:DualWrite</c> off (the default) it does nothing.
/// </summary>
public interface IMediaLibrarySync
{
/// <summary>Mirrors everything the module offers through its <see cref="IMediaMigrationSource"/> into the library tables.</summary>
Task SyncAsync(string module, CancellationToken cancellationToken);
}
/// <summary>The default: the Media module is not there or the switch is off, so nothing is written.</summary>
public sealed class NoMediaLibrarySync : IMediaLibrarySync
{
public Task SyncAsync(string module, CancellationToken cancellationToken) => Task.CompletedTask;
}
@@ -27,8 +27,8 @@ public sealed record MediaAssetSnapshot(
DateTimeOffset? LastUsedAt,
DateTimeOffset? DeletedAt);
/// <summary>One place a photo is used, as a module holds it today.</summary>
public sealed record MediaUseSnapshot(Guid Id, Guid AssetId, string Module, string PlaceKind, int Position, bool Active, string SetHash);
/// <summary>One place a photo is used, as a module holds it today. <c>Crops</c> are the crops of THIS use (crop per use); null = the crops of its photo.</summary>
public sealed record MediaUseSnapshot(Guid Id, Guid AssetId, string Module, string PlaceKind, int Position, bool Active, string SetHash, IReadOnlyList<MediaCropSnapshot>? Crops = null);
/// <summary>
/// What a module offers so the library can copy its photos and uses into its own tables. Read-only: the module's data is
@@ -0,0 +1,76 @@
using FluentAssertions;
using NSubstitute;
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 A: the hero tells the media library after every change it saved (the write-through).</summary>
public class HeroLibrarySyncTests
{
private static (HeroTestRig Rig, IMediaLibrarySync Sync) Rig()
{
var sync = Substitute.For<IMediaLibrarySync>();
return (new HeroTestRig(librarySync: sync), sync);
}
private static HeroSaveRequest Request(params HeroSlideRequest[] slides) => new("Titel", null, null, "slideshow", [], slides);
[Fact]
public async Task Every_change_of_a_photo_or_a_slide_is_written_through_for_the_hero_module()
{
var (rig, sync) = Rig();
using var _r = rig;
var image = await rig.Upload(HeroTestRig.Photo());
var id = Guid.Parse(image.Id);
var afterUpload = sync.ReceivedCalls().Count();
afterUpload.Should().BeGreaterThan(0, "the upload and the rendering of its variants both wrote through");
var saved = await rig.Service.SaveAsync(Request(new HeroSlideRequest(null, id, "een")), HeroTestRig.Admin, CancellationToken.None);
var slideId = Guid.Parse(saved.Slides[0].Id);
await rig.Images.SetFocusAsync(id, new HeroFocusRequest(new FocusDto(0.2, 0.3, 1.5)), HeroTestRig.Admin, CancellationToken.None);
await rig.Images.SetSlideFocusAsync(slideId, new HeroFocusRequest(new FocusDto(0.6, 0.6, 1.2)), HeroTestRig.Admin, CancellationToken.None);
await rig.RenderPending();
await rig.Images.ResetSlideFocusAsync(slideId, HeroTestRig.Admin, CancellationToken.None);
await new HeroMediaUsageProvider(rig.Repository, rig.Images).TrashAsync(id, HeroTestRig.Admin, CancellationToken.None);
await rig.Images.RestoreAsync(id, HeroTestRig.Admin, CancellationToken.None);
await sync.Received().SyncAsync("hero", Arg.Any<CancellationToken>());
sync.ReceivedCalls().Count().Should().BeGreaterThan(afterUpload + 5);
sync.ReceivedCalls().Select(c => c.GetArguments()[0]).Should().OnlyContain(m => (string)m! == "hero");
}
[Fact]
public async Task Without_a_write_through_nothing_changes_for_the_hero()
{
using var rig = new HeroTestRig();
var image = await rig.Upload(HeroTestRig.Photo());
image.Processing.Should().BeFalse();
}
[Fact]
public async Task The_migration_source_gives_a_slide_with_its_own_crop_its_own_set_and_crops()
{
using var rig = new HeroTestRig();
var image = await rig.Upload(HeroTestRig.Photo());
var id = Guid.Parse(image.Id);
var saved = await rig.Service.SaveAsync(Request(new HeroSlideRequest(null, id, "een"), new HeroSlideRequest(null, id, "twee")), HeroTestRig.Admin, CancellationToken.None);
await rig.Images.SetSlideFocusAsync(Guid.Parse(saved.Slides[1].Id), new HeroFocusRequest(new FocusDto(0.1, 0.9, 1.4)), HeroTestRig.Admin, CancellationToken.None);
await rig.RenderPending();
var uses = await new HeroMediaMigrationSource(rig.Repository).ListUsesAsync(CancellationToken.None);
var photoSet = rig.Db.HeroImages.Single(i => i.Id == id).SetHash;
var first = uses.Single(u => u.Position == 1);
var second = uses.Single(u => u.Position == 2);
first.SetHash.Should().Be(photoSet);
first.Crops.Should().BeNull("a slide without its own crop uses the crops of its photo");
second.SetHash.Should().NotBe(photoSet).And.Be(rig.Db.HeroSlides.Single(s => s.Id == Guid.Parse(saved.Slides[1].Id)).SetHash);
second.Crops.Should().NotBeNull();
second.Crops!.Single(c => c.Ratio == "wide").X.Should().BeApproximately(0.1, 0.0001);
}
}
@@ -39,7 +39,7 @@ public sealed class HeroTestRig : IDisposable
public HeroMediaCleanup Cleanup { get; }
public HeroOptions HeroOptions { get; } = new();
public HeroTestRig(int maxPublishedSlides = 50)
public HeroTestRig(int maxPublishedSlides = 50, SlpModularCms.Core.Media.Library.IMediaLibrarySync? librarySync = null)
{
HeroOptions.MaxPublishedSlides = maxPublishedSlides;
Media = new MediaOptions { Directory = Directory, BusyWaitSeconds = 0 };
@@ -52,10 +52,10 @@ public sealed class HeroTestRig : IDisposable
Status.SetDirectory(true);
var gate = new MediaProcessingGate(mediaOptions);
var guard = new MediaUploadGuard(Processor, gate, Status, mediaOptions);
Images = new HeroImageService(guard, Processor, Store, gate, Repository, mediaOptions, NullLogger<HeroImageService>.Instance, Time, IndexCache, Signal);
Service = new HeroService(Repository, Images, Options.Create(HeroOptions), NullLogger<HeroService>.Instance, Time, IndexCache);
Images = new HeroImageService(guard, Processor, Store, gate, Repository, mediaOptions, NullLogger<HeroImageService>.Instance, Time, IndexCache, Signal, librarySync);
Service = new HeroService(Repository, Images, Options.Create(HeroOptions), NullLogger<HeroService>.Instance, Time, IndexCache, null, librarySync);
Public = new PublicHeroService(Repository, Options.Create(HeroOptions), Time);
Cleanup = new HeroMediaCleanup(Repository, Store, mediaOptions, NullLogger<HeroMediaCleanup>.Instance, Time);
Cleanup = new HeroMediaCleanup(Repository, Store, mediaOptions, NullLogger<HeroMediaCleanup>.Instance, Time, librarySync);
}
/// <summary>A photo-like fixture: the left half red, the right half blue, with a camera tag.</summary>
@@ -113,8 +113,12 @@ public class HeroImageService(
ILogger<HeroImageService> logger,
TimeProvider? time = null,
IIndexHtmlCache? indexCache = null,
HeroRenderSignal? signal = null) : IHeroImageService
HeroRenderSignal? signal = null,
IMediaLibrarySync? librarySync = null) : IHeroImageService
{
/// <summary>Mirrors the hero into the media library's tables (write-through, off unless switched on). Never throws.</summary>
private Task SyncLibraryAsync() => librarySync?.SyncAsync(HeroMapping.Area, CancellationToken.None) ?? Task.CompletedTask;
private readonly TimeProvider _time = time ?? TimeProvider.System;
public async Task<HeroImageDto> UploadAsync(Stream upload, long declaredLength, Guid callerId, CancellationToken cancellationToken, string? originalFileName = null)
@@ -137,6 +141,7 @@ public class HeroImageService(
if (existing is not null && await FilesExistAsync(existing, cancellationToken))
{
await repository.SaveChangesAsync(cancellationToken);
await SyncLibraryAsync();
// The same photo again also gives up the failed state: the renderer tries it again when it is still pending.
signal?.Reset(existing.Id);
signal?.Notify();
@@ -176,6 +181,7 @@ public class HeroImageService(
}
await repository.SaveChangesAsync(cancellationToken);
await SyncLibraryAsync();
signal?.Notify();
logger.LogInformation("Hero image {ImageId} {Action} by user {UserId} ({Width}x{Height}); its variants are cut in the background", image.Id, existing is null ? "uploaded" : "repaired", callerId, image.Width, image.Height);
@@ -222,6 +228,7 @@ public class HeroImageService(
ApplyFocus(image, request);
await repository.SaveChangesAsync(cancellationToken);
await SyncLibraryAsync();
signal?.Reset(imageId);
signal?.Notify();
@@ -242,6 +249,7 @@ public class HeroImageService(
Apply(request.Wide, v => (slide.WideFocusX, slide.WideFocusY, slide.WideZoom) = v);
Apply(request.Tall, v => (slide.TallFocusX, slide.TallFocusY, slide.TallZoom) = v);
await repository.SaveChangesAsync(cancellationToken);
await SyncLibraryAsync();
signal?.Reset(slideId);
signal?.Notify();
@@ -265,6 +273,7 @@ public class HeroImageService(
}
await repository.SaveChangesAsync(cancellationToken);
await SyncLibraryAsync();
signal?.Reset(slideId);
indexCache?.Invalidate();
@@ -454,6 +463,7 @@ public class HeroImageService(
}
await repository.SaveChangesAsync(cancellationToken);
await SyncLibraryAsync();
indexCache?.Invalidate();
logger.LogInformation("Hero slide {SlideId}: {Variants} variants cut in {Seconds:0.0} s", slide.Id, variants.Count, watch.Elapsed.TotalSeconds);
return slide.Id;
@@ -507,6 +517,7 @@ public class HeroImageService(
}
await repository.SaveChangesAsync(cancellationToken);
await SyncLibraryAsync();
indexCache?.Invalidate();
logger.LogInformation("Hero image {ImageId}: {Variants} variants cut in {Seconds:0.0} s", image.Id, variants.Count, watch.Elapsed.TotalSeconds);
return image.Id;
@@ -525,6 +536,7 @@ public class HeroImageService(
repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "original", Key = image.OriginalKey, RetiredAt = now });
repository.RemoveImage(image);
await repository.SaveChangesAsync(cancellationToken);
await SyncLibraryAsync();
logger.LogInformation("Hero image {ImageId} removed by user {UserId}", imageId, callerId);
}
@@ -548,6 +560,7 @@ public class HeroImageService(
image.DeletedAt = now;
await repository.SaveChangesAsync(cancellationToken);
await SyncLibraryAsync();
indexCache?.Invalidate();
logger.LogInformation("Hero image {ImageId} moved to the trash by user {UserId} ({Slides} slides removed)", imageId, callerId, slides.Count);
@@ -572,6 +585,7 @@ public class HeroImageService(
var (setHash, originalKey) = (image.SetHash, image.OriginalKey);
repository.RemoveImage(image);
await repository.SaveChangesAsync(cancellationToken);
await SyncLibraryAsync();
if (setHash.Length > 0 && !setShared)
{
@@ -598,6 +612,7 @@ public class HeroImageService(
image.DeletedAt = null;
await repository.SaveChangesAsync(cancellationToken);
await SyncLibraryAsync();
signal?.Notify();
logger.LogInformation("Hero image {ImageId} restored from the trash by user {UserId}", imageId, callerId);
@@ -18,7 +18,8 @@ public class HeroMediaCleanup(
IMediaStore store,
IOptions<MediaOptions> options,
ILogger<HeroMediaCleanup> logger,
TimeProvider? time = null)
TimeProvider? time = null,
SlpModularCms.Core.Media.Library.IMediaLibrarySync? librarySync = null)
{
private readonly TimeProvider _time = time ?? TimeProvider.System;
@@ -42,14 +43,20 @@ public class HeroMediaCleanup(
// 1b. Photos that have been in the trash for the trash period: their files go now (they are retired, immediately due).
var trashCutoff = now.AddDays(-Math.Max(0, options.Value.TrashDays));
var trashedGone = false;
foreach (var image in await repository.GetTrashedBeforeAsync(trashCutoff, cancellationToken))
{
trashedGone = true;
repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "set", Key = image.SetHash, RetiredAt = cutoff.AddSeconds(-1) });
repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "original", Key = image.OriginalKey, RetiredAt = cutoff.AddSeconds(-1) });
repository.RemoveImage(image);
}
await repository.SaveChangesAsync(cancellationToken);
if (librarySync is not null && (unattached.Count > 0 || trashedGone))
{
await librarySync.SyncAsync(HeroMapping.Area, CancellationToken.None);
}
// 2. Retired files whose retention has passed, unless an image uses them again.
var referencedSets = await repository.GetReferencedSetHashesAsync(cancellationToken);
@@ -26,8 +26,21 @@ public class HeroMediaMigrationSource(IHeroRepository repository) : IMediaMigrat
for (var index = 0; index < ordered.Count; index++)
{
var slide = ordered[index];
var setHash = images.TryGetValue(slide.ImageId, out var image) ? image.SetHash : string.Empty;
uses.Add(new MediaUseSnapshot(slide.Id, slide.ImageId, Module, HeroMediaUsageProvider.SlideKind, index + 1, slide.IsActive, setHash));
var setHash = string.Empty;
IReadOnlyList<MediaCropSnapshot>? crops = null;
if (images.TryGetValue(slide.ImageId, out var image))
{
// The slide as it shows the photo: its own crop and set when it has them (crop per use), else the photo's.
slide.Image = image;
var shown = HeroMapping.Effective(slide) ?? image;
setHash = shown.SetHash;
if (slide.HasOwnCrop)
{
crops = [Crop("wide", shown), Crop("tall", shown)];
}
}
uses.Add(new MediaUseSnapshot(slide.Id, slide.ImageId, Module, HeroMediaUsageProvider.SlideKind, index + 1, slide.IsActive, setHash, crops));
}
}
@@ -30,7 +30,8 @@ public class HeroService(
ILogger<HeroService> logger,
TimeProvider? time = null,
IIndexHtmlCache? indexCache = null,
ITextCatalog? texts = null) : IHeroService
ITextCatalog? texts = null,
SlpModularCms.Core.Media.Library.IMediaLibrarySync? librarySync = null) : IHeroService
{
private readonly TimeProvider _time = time ?? TimeProvider.System;
private readonly ITextCatalog _texts = texts ?? TextCatalog.Default;
@@ -155,6 +156,11 @@ public class HeroService(
indexCache?.Invalidate();
imageService.NotifyPending();
if (librarySync is not null)
{
await librarySync.SyncAsync(HeroMapping.Area, CancellationToken.None);
}
logger.LogInformation("Hero {HeroId} {Action} by user {LastModifiedByUserId} ({Slides} slides)", hero.Id, created ? "Created" : "Updated", callerId, keep.Count);
return WithFailures(HeroMapping.ToAdmin(hero, now, options.Value.MaxPublishedSlides));
@@ -0,0 +1,85 @@
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 A: the write-through mirrors one module into the library tables, only when it is switched on, and never throws.</summary>
public class MediaLibrarySyncTests : 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-sync-" + Guid.NewGuid()).Options);
public void Dispose() => _db.Dispose();
private sealed class Source(string module, Func<List<MediaAssetSnapshot>> assets, Func<List<MediaUseSnapshot>> uses, bool fails = false) : IMediaMigrationSource
{
public string Module => module;
public Task<IReadOnlyList<MediaAssetSnapshot>> ListAssetsAsync(CancellationToken cancellationToken)
=> fails ? throw new InvalidOperationException("source failed") : 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", null, null);
private MediaLibrarySync Sync(bool on, params IMediaMigrationSource[] sources)
=> new(new MediaLibraryCopier(_db, sources, NullLogger<MediaLibraryCopier>.Instance), Options.Create(new MediaLibraryOptions { DualWrite = on }), NullLogger<MediaLibrarySync>.Instance);
[Fact]
public async Task Does_nothing_while_the_switch_is_off()
{
var a = Asset("hero");
await Sync(false, new Source("hero", () => [a], () => [])).SyncAsync("hero", CancellationToken.None);
(await _db.MediaAssets.CountAsync()).Should().Be(0);
}
[Fact]
public async Task Mirrors_only_the_given_module_and_follows_the_changes_of_the_source()
{
var hero = Asset("hero");
var other = Asset("gallery");
var heroAssets = new List<MediaAssetSnapshot> { hero };
var sync = Sync(true, new Source("hero", () => heroAssets.ToList(), () => []), new Source("gallery", () => [other], () => []));
await sync.SyncAsync("hero", CancellationToken.None);
(await _db.MediaAssets.Select(a => a.Module).ToListAsync()).Should().Equal("hero");
var second = Asset("hero");
heroAssets.Add(second);
heroAssets.Remove(hero);
await sync.SyncAsync("hero", CancellationToken.None);
(await _db.MediaAssets.Select(a => a.Id).ToListAsync()).Should().Equal(second.Id);
}
[Fact]
public async Task Stores_the_crops_of_a_use_when_the_source_gives_them()
{
var hero = Asset("hero");
var use = new MediaUseSnapshot(Guid.NewGuid(), hero.Id, "hero", "slide", 1, true, "fedcba9876543210", [new MediaCropSnapshot("wide", 0.1, 0.9, 1.4)]);
await Sync(true, new Source("hero", () => [hero], () => [use])).SyncAsync("hero", CancellationToken.None);
var row = await _db.MediaUses.SingleAsync();
row.SetHash.Should().Be("fedcba9876543210");
row.Crops.Should().Contain("0.9").And.Contain("1.4");
}
[Fact]
public async Task Never_throws_when_the_source_fails()
{
var act = () => Sync(true, new Source("hero", () => [], () => [], fails: true)).SyncAsync("hero", CancellationToken.None);
await act.Should().NotThrowAsync();
}
}
@@ -10,4 +10,10 @@ public class MediaLibraryOptions
/// (<c>Media__Library__CopyOnStartup=true</c>). Safe to repeat: the copy mirrors the source. Never touches the modules' own data.
/// </summary>
public bool CopyOnStartup { get; set; }
/// <summary>
/// Write-through (phase 2, step A, <c>Media__Library__DualWrite=true</c>): after every change a module saved to its own tables,
/// the library tables are mirrored too. Off by default; the modules' own tables stay the truth.
/// </summary>
public bool DualWrite { get; set; }
}
@@ -4,6 +4,8 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using SlpModularCms.Core.Media.Library;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -36,6 +38,7 @@ public class MediaModule : IModule
services.AddOptions<MediaLibraryOptions>().Configure<IConfiguration>((options, configuration) =>
configuration.GetSection(MediaLibraryOptions.SectionName).Bind(options));
services.AddScoped<MediaLibraryCopier>();
services.Replace(ServiceDescriptor.Scoped<IMediaLibrarySync, MediaLibrarySync>());
services.AddHostedService<MediaLibraryCopyService>();
}
@@ -29,12 +29,13 @@ public sealed class MediaLibraryCopier(MediaDbContext db, IEnumerable<IMediaMigr
{
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
public async Task<MediaCopyReport> CopyAsync(CancellationToken cancellationToken)
/// <param name="onlyModule">Mirror only this module (the write-through); null = every module (the verified copy).</param>
public async Task<MediaCopyReport> CopyAsync(CancellationToken cancellationToken, string? onlyModule = null)
{
var assets = new List<MediaAssetSnapshot>();
var uses = new List<MediaUseSnapshot>();
var modules = new List<string>();
foreach (var source in sources)
foreach (var source in sources.Where(s => onlyModule is null || s.Module == onlyModule))
{
modules.Add(source.Module);
assets.AddRange(await source.ListAssetsAsync(cancellationToken));
@@ -139,7 +140,7 @@ public sealed class MediaLibraryCopier(MediaDbContext db, IEnumerable<IMediaMigr
row.Position = snapshot.Position;
row.Active = snapshot.Active;
row.SetHash = snapshot.SetHash;
row.Crops = cropsByAsset.TryGetValue(snapshot.AssetId, out var crops) ? crops : "[]";
row.Crops = snapshot.Crops is not null ? JsonSerializer.Serialize(snapshot.Crops, Json) : cropsByAsset.TryGetValue(snapshot.AssetId, out var crops) ? crops : "[]";
}
// What is left no longer exists at the source.
@@ -0,0 +1,38 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Media.Library;
namespace SlpModularCms.Modules.Media.Services;
/// <summary>
/// The write-through (<see cref="IMediaLibrarySync"/>): mirrors one module into the library tables with the same verified
/// copy the start-up copy uses, one at a time. Off unless <c>Media:Library:DualWrite</c> is on. Never throws: the module's
/// own data is the truth and a failed mirror is logged and repaired by the next sync.
/// </summary>
public sealed class MediaLibrarySync(MediaLibraryCopier copier, IOptions<MediaLibraryOptions> options, ILogger<MediaLibrarySync> logger) : IMediaLibrarySync
{
// Two requests (or the background renderer) must not mirror at the same moment: one transaction at a time.
private static readonly SemaphoreSlim Gate = new(1, 1);
public async Task SyncAsync(string module, CancellationToken cancellationToken)
{
if (!options.Value.DualWrite)
{
return;
}
await Gate.WaitAsync(CancellationToken.None);
try
{
await copier.CopyAsync(CancellationToken.None, module);
}
catch (Exception exception) when (exception is not OperationCanceledException)
{
logger.LogError(exception, "The write-through of {Module} to the media library failed; the module's own data is untouched and the next change repairs it.", module);
}
finally
{
Gate.Release();
}
}
}