using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Media.Library;
namespace SlpModularCms.Modules.Media.Services;
///
/// The write-through (): mirrors one module into the library tables with the same verified
/// copy the start-up copy uses, one at a time. Off unless Media:Library:DualWrite is on. Never throws: the module's
/// own data is the truth and a failed mirror is logged and repaired by the next sync.
///
public sealed class MediaLibrarySync(MediaLibraryCopier copier, IOptions options, ILogger 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();
}
}
}