diff --git a/src/Febe.App/FebeApp.cs b/src/Febe.App/FebeApp.cs index b7ac062..12951d9 100644 --- a/src/Febe.App/FebeApp.cs +++ b/src/Febe.App/FebeApp.cs @@ -14,6 +14,7 @@ using Febe.Core.Engine; using Febe.Core.Export; using Febe.Core.Import; using Febe.Core.Library; +using Febe.Core.Library.Conversion; using Febe.Core.Security; using Febe.Core.Storage; using Febe.Data; @@ -194,9 +195,12 @@ public sealed class FebeApp : IAsyncDisposable DataFolder = data.Root, Gate = longWork, }); + var idleConversion = new LibraryConversionWorker(new LibraryConversionEnvironment { Storage = Database, Layout = () => library.Layout, Clock = Clock, Gate = longWork }); await StartWebAsync(hooks, services => { services.AddSingleton(longWork); + services.AddSingleton(idleConversion); + services.AddSingleton(new LibraryConversionQueue(Database, Clock)); services.AddSingleton(ExportRootOptions.Docker(Path.Combine(_temporaryFolder, "esporta"), declared: false)); services.AddSingleton(Database); services.AddSingleton(library); @@ -336,12 +340,28 @@ public sealed class FebeApp : IAsyncDisposable _telegram = new TelegramClient(hooks.TelegramHandler); var telegramChannel = new TelegramAlertChannel(_telegram); + // The conversion for the library (tappa E3, spec §4.10): one worker, started below in the background; it yields + // to import, copies and rebuild through the gate and never runs during an engine session. Never in the demo. + var sessionState = new RuntimeSessionState(services.Runtime); + var conversion = new LibraryConversionWorker(new LibraryConversionEnvironment + { + Storage = Database, + Layout = () => library.Layout, + Clock = Clock, + Gate = longWork, + Session = sessionState, + FreeSpace = hooks.FreeSpace ?? new DriveFreeSpaceProbe(), + Log = message => Log.Write(LogLevel.Warning, "conversione", message), + }); + await StartWebAsync(hooks, s => { s.AddSingleton(longWork); + s.AddSingleton(conversion); + s.AddSingleton(new LibraryConversionQueue(Database, Clock)); s.AddSingleton(exportRoot); s.AddSingleton(hooks.ExportDisk ?? new SystemExportDisk(exportRoot.Mounts)); - s.AddSingleton(new RuntimeSessionState(services.Runtime)); + s.AddSingleton(sessionState); s.AddSingleton(Database); s.AddSingleton(library); s.AddSingleton(Clock); @@ -398,6 +418,7 @@ public sealed class FebeApp : IAsyncDisposable InBackground(() => BackupLoopAsync(new DailyBackup(Database, Clock, data.Backups), lifetime)); InBackground(() => BringUpBrowserAsync(ingest, staging, services, engine, runner, search, lifetime)); InBackground(() => Alerts.WatchDiskSpaceAsync(lifetime)); + InBackground(() => conversion.RunAsync(lifetime)); } /// Runs in the background; the stop waits for it. diff --git a/src/Febe.Core/Abstractions/LongWorkGate.cs b/src/Febe.Core/Abstractions/LongWorkGate.cs index 92dd75a..7609544 100644 --- a/src/Febe.Core/Abstractions/LongWorkGate.cs +++ b/src/Febe.Core/Abstractions/LongWorkGate.cs @@ -13,19 +13,38 @@ public enum LongWorkKind /// «Ricostruisci il database dalla libreria» (spec §8.5). Rebuild, + + /// + /// The conversion for the library (tappa E3, spec §4.10): held only as a , + /// which any of the others pre-empts. + /// + LibraryConversion, + + /// A zip of 21 to 500 frames being prepared for «Scarica» (tappa E3, D14). + FrameDownload, } /// -/// Lets only one of import, export and rebuild run at a time, in both directions. One instance is shared by the whole -/// process (the composition registers it once). A lease is taken when a job starts and disposed when it ends; disposing -/// it twice releases nothing more. +/// Lets only one of import, export, rebuild and frame download run at a time, in both directions. One instance is +/// shared by the whole process (the composition registers it once). A lease is taken when a job starts and disposed when +/// it ends; disposing it twice releases nothing more. +/// +/// The conversion for the library takes a instead (tappa E3, WP2.1): it runs only while +/// no foreground lease is held, and a foreground pre-empts it. Outside a commit the conversion +/// only reads an original and writes its own temporary file, so it simply stops; a commit (one rename and one +/// transaction) is waited for, at most . +/// /// public sealed class LongWorkGate { private readonly Lock _lock = new(); private Lease? _holder; + private BackgroundLease? _background; - /// Who holds the gate, or null when it is free. + /// How long a foreground waits for a commit of the background work to end. + public TimeSpan CommitWait { get; init; } = TimeSpan.FromSeconds(10); + + /// Who holds the gate in the foreground, or null when it is free. The background lease does not count. public LongWorkKind? Busy { get @@ -37,12 +56,34 @@ public sealed class LongWorkGate } } + /// True while the background lease (the conversion for the library) is held and not pre-empted. + public bool BackgroundRunning + { + get + { + lock (_lock) + { + return _background is not null; + } + } + } + /// /// Takes the gate for . False, with set, when another job (of any - /// kind, the same one included) holds it. + /// kind, the same one included) holds it in the foreground. A background lease is pre-empted: its token is + /// cancelled and, if it is committing a file, the commit is waited for (at most ; past it, + /// false with ). /// public bool TryEnter(LongWorkKind kind, [NotNullWhen(true)] out IDisposable? lease, out LongWorkKind? busyWith) { + if (kind == LongWorkKind.LibraryConversion) + { + throw new ArgumentException("La conversione della libreria prende il cancello solo in sottofondo.", nameof(kind)); + } + + Lease taken; + BackgroundLease? preempted; + bool committing; lock (_lock) { if (_holder is { } holder) @@ -52,10 +93,47 @@ public sealed class LongWorkGate return false; } - var taken = new Lease(this, kind); + taken = new Lease(this, kind); _holder = taken; - lease = taken; - busyWith = null; + preempted = _background; + _background = null; + committing = preempted?.MarkPreempted() ?? false; + } + + if (preempted is not null) + { + // Outside the lock: the token's callbacks run synchronously and may take the gate's lock. + preempted.CancelPreempted(); + if (committing && !preempted.WaitForCommit(CommitWait)) + { + taken.Dispose(); + lease = null; + busyWith = LongWorkKind.LibraryConversion; + return false; + } + } + + lease = taken; + busyWith = null; + return true; + } + + /// + /// Takes the gate in the background for the conversion for the library. False while any foreground lease, or + /// another background lease, is held. + /// + public bool TryEnterBackground([NotNullWhen(true)] out BackgroundLease? lease) + { + lock (_lock) + { + if (_holder is not null || _background is not null) + { + lease = null; + return false; + } + + lease = new BackgroundLease(this); + _background = lease; return true; } } @@ -68,14 +146,20 @@ public sealed class LongWorkGate (LongWorkKind.Rebuild, LongWorkKind.Rebuild) => "La ricostruzione è già in corso.", (_, LongWorkKind.Import) => $"C'è un'importazione al lavoro: aspetta che finisca o interrompila, poi {Verb(wanted)}.", (_, LongWorkKind.Export) => $"C'è una copia nelle cartelle esterne al lavoro: aspetta che finisca o interrompila, poi {Verb(wanted)}.", - _ => "La ricostruzione del database è in corso: aspetta che finisca.", + (_, LongWorkKind.LibraryConversion) => "La conversione della libreria sta salvando un file: riprova fra un attimo.", + (_, LongWorkKind.FrameDownload) => $"Si sta preparando uno zip di fotogrammi: aspetta che finisca, poi {Verb(wanted)}.", + (_, LongWorkKind.Rebuild) => "La ricostruzione del database è in corso: aspetta che finisca.", + _ => "Un altro lavoro lungo è in corso: aspetta che finisca.", }; private static string Verb(LongWorkKind kind) => kind switch { LongWorkKind.Import => "importa", LongWorkKind.Export => "copia", - _ => "ricostruisci", + LongWorkKind.Rebuild => "ricostruisci", + LongWorkKind.FrameDownload => "scarica i fotogrammi", + LongWorkKind.LibraryConversion => "converti", + _ => "riprova", }; private void Release(Lease lease) @@ -89,6 +173,17 @@ public sealed class LongWorkGate } } + private void Release(BackgroundLease lease) + { + lock (_lock) + { + if (ReferenceEquals(_background, lease)) + { + _background = null; + } + } + } + private sealed class Lease(LongWorkGate gate, LongWorkKind kind) : IDisposable { private int _disposed; @@ -103,4 +198,112 @@ public sealed class LongWorkGate } } } + + /// + /// The background lease of the conversion for the library. is cancelled when a foreground + /// job wants the gate; a commit () is waited for by that job, and none begins once + /// pre-empted or disposed. + /// + public sealed class BackgroundLease : IDisposable + { + private readonly LongWorkGate _gate; + + // Neither is disposed: a foreground TryEnter may cancel or wait on them after the lease ended, and without a + // timer or a wait handle asked for they hold nothing but memory. + private readonly CancellationTokenSource _preempted = new(); + private readonly ManualResetEventSlim _noCommit = new(initialState: true); + private bool _isPreempted; + private bool _committing; + private int _disposed; + + internal BackgroundLease(LongWorkGate gate) + { + _gate = gate; + Preempted = _preempted.Token; + } + + /// Cancelled when a foreground job takes the gate. + public CancellationToken Preempted { get; } + + /// True once a foreground job asked for the gate (or the lease ended). + public bool IsPreempted + { + get + { + lock (_gate._lock) + { + return _isPreempted; + } + } + } + + /// + /// Begins a commit (a rename and its record) that a foreground job waits for. False once pre-empted or disposed, + /// or while another commit of this lease runs: then nothing may be renamed or recorded. + /// + public bool TryBeginCommit([NotNullWhen(true)] out IDisposable? commit) + { + lock (_gate._lock) + { + if (_isPreempted || _disposed != 0 || _committing) + { + commit = null; + return false; + } + + _committing = true; + _noCommit.Reset(); + commit = new Commit(this); + return true; + } + } + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + + EndCommit(); + _gate.Release(this); + lock (_gate._lock) + { + _isPreempted = true; + } + } + + /// Under the gate's lock: marks the lease pre-empted and tells whether a commit is running. + internal bool MarkPreempted() + { + _isPreempted = true; + return _committing; + } + + internal void CancelPreempted() => _preempted.Cancel(); + + internal bool WaitForCommit(TimeSpan timeout) => _noCommit.Wait(timeout); + + private void EndCommit() + { + lock (_gate._lock) + { + _committing = false; + _noCommit.Set(); + } + } + + private sealed class Commit(BackgroundLease lease) : IDisposable + { + private int _disposed; + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) == 0) + { + lease.EndCommit(); + } + } + } + } } diff --git a/src/Febe.Core/Export/ExportSupersession.cs b/src/Febe.Core/Export/ExportSupersession.cs index 77377a7..4d6e775 100644 --- a/src/Febe.Core/Export/ExportSupersession.cs +++ b/src/Febe.Core/Export/ExportSupersession.cs @@ -1,4 +1,5 @@ using Febe.Core.Domain; +using Febe.Core.Library.Conversion; using Febe.Core.Storage; namespace Febe.Core.Export; @@ -25,6 +26,7 @@ public static class ExportSupersession } var old = oldSha256.ToLowerInvariant(); + await LibraryConversionsChangedAsync(storage, accountId, old, newSha256.ToLowerInvariant(), at).ConfigureAwait(false); var users = await storage.Media.FindBySha256Async(old, ct).ConfigureAwait(false); if (users.Any(u => u.Entry.AccountId == accountId && EntryStateRules.IsPresent(u.Media.State))) { @@ -33,4 +35,31 @@ public static class ExportSupersession return await storage.Exports.SupersedeCopiesAsync(accountId, old, newSha256.ToLowerInvariant(), at, CancellationToken.None).ConfigureAwait(false); } + + /// + /// The conversions for the library of the account's file that now has (tappa E3, + /// WP2.4): a converted file of the old bytes is «Superato» (it stays), the queue and the failures take the new bytes, + /// and the file is queued again in the library formats set now. + /// + private static async Task LibraryConversionsChangedAsync(IFebeStorage storage, long accountId, string oldSha256, string newSha256, DateTimeOffset at) + { + var none = CancellationToken.None; + var changed = await storage.Conversions.SupersedeAsync(accountId, oldSha256, newSha256, at, none).ConfigureAwait(false); + if (changed.Count == 0) + { + return; + } + + var media = new List(); + foreach (var id in changed) + { + if (await storage.Media.GetAsync(id, none).ConfigureAwait(false) is { } m) + { + media.Add(m); + } + } + + await LibraryConversionQueue.EnqueueEntryAsync(storage, media, at, none).ConfigureAwait(false); + LibraryConversionQueue.Signal(); + } } diff --git a/src/Febe.Core/Import/ImportComparer.cs b/src/Febe.Core/Import/ImportComparer.cs index 03eff3b..f97e3bb 100644 --- a/src/Febe.Core/Import/ImportComparer.cs +++ b/src/Febe.Core/Import/ImportComparer.cs @@ -7,6 +7,9 @@ namespace Febe.Core.Import; /// What the comparison decided for one file. internal sealed record Comparison(ImportOutcome Outcome, long? MatchedMediaId, DuplicatePair? Pair, string? Note); +/// A file of the source that is a converted copy of a library file; its original when known. +internal sealed record ConvertedCopyMatch(long? MediaId); + /// /// The comparison with the library (spec §9.3), for one analysis session. In this order: /// @@ -39,6 +42,9 @@ internal sealed class ImportComparer private readonly Dictionary _sourceIdentity = new(StringComparer.Ordinal); private readonly PerceptualHashIndex _sourceHashes = new(); + // The SHA-256 of the converted copies and frames written in destinations (one read per run, tappa E3, Q37). + private IReadOnlySet _copyShas = new HashSet(StringComparer.Ordinal); + private ImportComparer(IFebeStorage storage, PerceptualHashIndex library, Func now) { _storage = storage; @@ -69,6 +75,7 @@ internal sealed class ImportComparer } var comparer = new ImportComparer(storage, library, now); + comparer._copyShas = await storage.Exports.LoadConvertedCopyShasAsync(ct).ConfigureAwait(false); var identifiers = await storage.Imports.LoadLibraryIdentifiersAsync(ct).ConfigureAwait(false); foreach (var entry in identifiers.Entries) { @@ -141,6 +148,13 @@ internal sealed class ImportComparer return new Comparison(ImportOutcome.AlreadyInLibrary, deleted.Media.Id, null, ImportText.NoteDeletedByAlberto); } + // A converted file of the library, or a converted copy or a frame of a destination: already in the library as + // its original, never a probable duplicate of it (tappa E3, Q37). + if (await IsConvertedCopyAsync(_storage, _copyShas, file.Sha256, ct).ConfigureAwait(false) is { } converted) + { + return new Comparison(ImportOutcome.AlreadyInLibrary, converted.MediaId, null, ImportText.NoteConvertedCopy); + } + // 2. Same bytes earlier in the source. if (_sourceSha.TryGetValue(file.Sha256, out var twin) && twin.Id != file.Id) { @@ -177,6 +191,21 @@ internal sealed class ImportComparer return new Comparison(ImportOutcome.New, null, null, null); } + /// + /// Whether is the SHA-256 of a converted file of the library (with its original's media + /// id) or of a converted copy or frame written in a destination (media id null); null when it is neither. + /// + internal static async Task IsConvertedCopyAsync(IFebeStorage storage, IReadOnlySet copyShas, string sha256, CancellationToken ct) + { + var conversions = await storage.Conversions.FindBySha256Async(sha256, ct).ConfigureAwait(false); + if (conversions.Count > 0) + { + return new ConvertedCopyMatch(conversions[0].MediaId); + } + + return copyShas.Contains(sha256) ? new ConvertedCopyMatch(null) : null; + } + private async Task MatchIdentityAsync(ImportFile file, FileHints hints, long? target, CancellationToken ct) { var candidates = new List<(EntryIdentity Entry, long? MediaId)>(); diff --git a/src/Febe.Core/Import/ImportCopier.cs b/src/Febe.Core/Import/ImportCopier.cs index e053946..c1b6e53 100644 --- a/src/Febe.Core/Import/ImportCopier.cs +++ b/src/Febe.Core/Import/ImportCopier.cs @@ -258,6 +258,14 @@ public sealed class ImportCopier(ImportEnvironment env) return await SaveAsync(file with { State = ImportFileState.Skipped, MatchedMediaId = twin.Media.Id, LastError = ImportText.NoteAlreadyInLibrary }).ConfigureAwait(false); } + // A converted copy of a library file written since the analysis (tappa E3, Q37): never imported as a new file. + context.CopyShas ??= await env.Storage.Exports.LoadConvertedCopyShasAsync(ct).ConfigureAwait(false); + if (file.EntryId is null && await ImportComparer.IsConvertedCopyAsync(env.Storage, context.CopyShas, file.Sha256!, ct).ConfigureAwait(false) is { } converted) + { + tally.Skipped++; + return await SaveAsync(file with { State = ImportFileState.Skipped, MatchedMediaId = converted.MediaId, LastError = ImportText.NoteConvertedCopy }).ConfigureAwait(false); + } + var account = await env.Storage.Accounts.GetAsync(file.TargetAccountId!.Value, ct).ConfigureAwait(false) ?? throw new InvalidOperationException("L'account di destinazione non esiste più: associa di nuovo la cartella."); var hints = context.Recognizers.Recognize(new ImportFileContext(context.Layout, file.RelativePath)); @@ -790,7 +798,11 @@ public sealed class ImportCopier(ImportEnvironment env) } } - private sealed record CopyContext(ImportRun Run, SourceLayout Layout, ImportRecognizers Recognizers, LibraryIngest Ingest); + private sealed record CopyContext(ImportRun Run, SourceLayout Layout, ImportRecognizers Recognizers, LibraryIngest Ingest) + { + /// The SHA-256 of converted copies and frames in destinations, read once per run when first needed. + public IReadOnlySet? CopyShas { get; set; } + } private sealed class Tally { diff --git a/src/Febe.Core/Import/ImportText.cs b/src/Febe.Core/Import/ImportText.cs index 50f13fb..7fb5bdd 100644 --- a/src/Febe.Core/Import/ImportText.cs +++ b/src/Febe.Core/Import/ImportText.cs @@ -139,6 +139,9 @@ public static class ImportText internal const string NoteLargerInSource = "Hai scelto di tenere il più grande: è un altro file della sorgente, che prende il posto di quello in libreria."; internal const string NoteNotRecognized = "Né foto né video: ignorato."; internal const string NoteAlreadyInLibrary = "Identico a un file già in libreria: saltato."; + + /// A converted file of the library, a converted copy or a frame written in a destination (tappa E3, Q37). + internal const string NoteConvertedCopy = "È una copia convertita (o un fotogramma) di un file già in libreria."; internal const string NoteReplaced = "Ha sostituito il file più piccolo della libreria, come hai scelto."; internal const string NoteChanged = "Il file è cambiato dopo l'analisi: non è stato copiato. Per prenderlo avvia una nuova importazione della cartella."; internal const string NoteNotVerified = "La copia in libreria non corrisponde all'originale: l'originale resta al suo posto. Controlla il disco della libreria."; diff --git a/src/Febe.Core/Library/Conversion/LibraryConversionQueue.cs b/src/Febe.Core/Library/Conversion/LibraryConversionQueue.cs new file mode 100644 index 0000000..d3dc5d5 --- /dev/null +++ b/src/Febe.Core/Library/Conversion/LibraryConversionQueue.cs @@ -0,0 +1,148 @@ +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Storage; + +namespace Febe.Core.Library.Conversion; + +/// What «Anche i N già in libreria» would queue: files and the bytes of their originals («circa», D17). +public sealed record LibraryConversionPreview(int Files, long Bytes); + +/// +/// The queue of the conversion for the library (tappa E3, D15, WP2.2): what enters it and when. A new file enters after +/// its line of _febe.jsonl (); the files already in the library +/// only when Alberto answers «Anche i N già in libreria» to the question asked when the conversion is turned on (Q29); +/// a format turned off or changed empties its queue, the converted files stay where they are. +/// +public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock) +{ + /// «In pausa» (1): the worker converts nothing until it is resumed. + public const string PausedKey = "esportazione.libreria-sospesa"; + + private static readonly Lock SignalGate = new(); + private static TaskCompletionSource _signal = NewSignal(); + + /// The files «Anche i N già in libreria» would queue for the library formats of . + public async Task PreviewExistingAsync(ExportSettings settings, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(settings); + var (files, bytes) = await storage.Conversions.CountExistingAsync( + LibraryConversionRules.FormatFor(MediaKind.Photo, settings), LibraryConversionRules.FormatFor(MediaKind.Video, settings), ct).ConfigureAwait(false); + return new LibraryConversionPreview(files, bytes); + } + + /// «Anche i N già in libreria»: queues the present files that convert, in one statement per kind. Returns how many. + public async Task EnqueueExistingAsync(ExportSettings settings, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(settings); + var added = await storage.Conversions.EnqueueExistingAsync( + LibraryConversionRules.FormatFor(MediaKind.Photo, settings), LibraryConversionRules.FormatFor(MediaKind.Video, settings), clock.Now, ct).ConfigureAwait(false); + if (added > 0) + { + Signal(); + } + + return added; + } + + /// + /// The settings changed: a library format turned off or changed loses its queue (its converted files and rows stay). + /// Turning one on queues nothing here: the interface asks, then calls only for + /// «Anche i N già in libreria». + /// + public async Task OnSettingsChangedAsync(ExportSettings before, ExportSettings after, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(before); + ArgumentNullException.ThrowIfNull(after); + foreach (var kind in new[] { MediaKind.Photo, MediaKind.Video }) + { + var old = LibraryConversionRules.FormatFor(kind, before); + if (old is { } format && old != LibraryConversionRules.FormatFor(kind, after)) + { + await storage.Conversions.DeletePendingAsync(format, ct).ConfigureAwait(false); + } + } + } + + /// «Riprova»: the failed files go back to the queue, except those that never convert (AsIs*). Returns how many. + public async Task RetryFailedAsync(CancellationToken ct = default) + { + var reset = await storage.Conversions.ResetFailedAsync(clock.Now, ct).ConfigureAwait(false); + if (reset > 0) + { + Signal(); + } + + return reset; + } + + /// «In pausa» or not. + public static async Task IsPausedAsync(ISettingsStore settings, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(settings); + return await settings.GetAsync(PausedKey, ct).ConfigureAwait(false) == "1"; + } + + /// «Sospendi» / «Riprendi» the conversion for the library. + public async Task SetPausedAsync(bool paused, CancellationToken ct = default) + { + await storage.Settings.SetAsync(PausedKey, paused ? "1" : "0", ct).ConfigureAwait(false); + if (!paused) + { + Signal(); + } + } + + /// + /// Queues the present files of an entry by the library formats set now, after its journal line (the hook of + /// ). Nothing when both formats are «Originale». Returns how many rows were added. + /// + public static async Task EnqueueEntryAsync(IFebeStorage storage, IReadOnlyList media, DateTimeOffset at, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(storage); + ArgumentNullException.ThrowIfNull(media); + var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false); + if (!settings.ConvertsLibrary) + { + return 0; + } + + var requests = LibraryConversionRules.RequestsFor(media, settings); + if (requests.Count == 0) + { + return 0; + } + + var added = await storage.Conversions.EnqueueAsync(requests, at, ct).ConfigureAwait(false); + if (added > 0) + { + Signal(); + } + + return added; + } + + /// Wakes the worker: something entered the queue (or the pause ended). + public static void Signal() + { + TaskCompletionSource fired; + lock (SignalGate) + { + fired = _signal; + _signal = NewSignal(); + } + + fired.TrySetResult(); + } + + /// A task that completes at the next . + internal static Task NextSignal() + { + lock (SignalGate) + { + return _signal.Task; + } + } + + private static TaskCompletionSource NewSignal() => new(TaskCreationOptions.RunContinuationsAsynchronously); +} diff --git a/src/Febe.Core/Library/Conversion/LibraryConversionRules.cs b/src/Febe.Core/Library/Conversion/LibraryConversionRules.cs new file mode 100644 index 0000000..8defde5 --- /dev/null +++ b/src/Febe.Core/Library/Conversion/LibraryConversionRules.cs @@ -0,0 +1,66 @@ +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Storage; + +namespace Febe.Core.Library.Conversion; + +/// +/// Which library files the conversion for the library queues (tappa E3, D15, WP2.2): a present file whose extension +/// says it converts into the format chosen for its kind ( is Converted). A file +/// already in that format, HEIC, HEIF, AVIF, raw, GIF and WebM are never queued. The same rule is written in SQL by the +/// store (). +/// +public static class LibraryConversionRules +{ + /// The format of the conversion for the library of a kind; null when it is off («Originale»). + public static ExportFormat? FormatFor(MediaKind kind, ExportSettings settings) + { + ArgumentNullException.ThrowIfNull(settings); + var format = kind == MediaKind.Photo ? settings.LibraryPhotoFormat : settings.LibraryVideoFormat; + var fits = kind == MediaKind.Photo ? ExportFormats.IsPhotoFormat(format) : ExportFormats.IsVideoFormat(format); + return format != ExportFormat.Original && fits ? format : null; + } + + /// True when a file at of is queued for . + public static bool Converts(string relativePath, MediaKind kind, ExportFormat format) + { + ArgumentNullException.ThrowIfNull(relativePath); + var fits = kind == MediaKind.Photo ? ExportFormats.IsPhotoFormat(format) : ExportFormats.IsVideoFormat(format); + return format != ExportFormat.Original && fits && ExportConversions.Predict(relativePath, kind, format) == ExportPrediction.Converted; + } + + /// + /// The extensions (with their dot, lower case) of the files that are not queued for : the + /// format's own and the ones copied as they are. Equivalent to on the extension. + /// + public static IReadOnlyList ExcludedExtensions(ExportFormat format) + { + var own = format switch + { + ExportFormat.Jpg => new[] { ".jpg", ".jpeg" }, + ExportFormat.Png => [".png"], + ExportFormat.WebpLossless => [".webp"], + ExportFormat.Mp4 => [".mp4"], + _ => throw new ArgumentOutOfRangeException(nameof(format), "La conversione della libreria ha un formato diverso dall'originale."), + }; + return [.. own, ".heic", ".heif", ".avif", ".gif", ".webm", .. MediaConverter.RawExtensionList.Select(e => e.ToLowerInvariant()).Order(StringComparer.Ordinal)]; + } + + /// The conversions to queue for the present files of an entry, by the settings now. + public static IReadOnlyList RequestsFor(IEnumerable media, ExportSettings settings) + { + ArgumentNullException.ThrowIfNull(media); + ArgumentNullException.ThrowIfNull(settings); + var list = new List(); + foreach (var m in media) + { + if (EntryStateRules.IsPresent(m.State) && m.Sha256 is { Length: 64 } sha && m.RelativePath is { } path + && FormatFor(m.Kind, settings) is { } format && Converts(path, m.Kind, format)) + { + list.Add(new MediaConversionRequest(m.Id, format, sha)); + } + } + + return list; + } +} diff --git a/src/Febe.Core/Library/Conversion/LibraryConversionText.cs b/src/Febe.Core/Library/Conversion/LibraryConversionText.cs new file mode 100644 index 0000000..0d66ace --- /dev/null +++ b/src/Febe.Core/Library/Conversion/LibraryConversionText.cs @@ -0,0 +1,72 @@ +using Febe.Core.Codecs.Images; +using Febe.Core.Export; + +namespace Febe.Core.Library.Conversion; + +/// +/// The codes of media_conversion.last_error (tappa E3, D19) and their Italian texts. A Failed row carries why it +/// failed (an AsIs* code first when the file never converts); a Converted row carries what was not kept. +/// +public static class LibraryConversionText +{ + /// The original is not in the library folder. + public const string SourceMissing = ExportText.Notes.SourceMissing; + + /// The original's bytes are not the ones recorded. + public const string SourceChanged = ExportText.Notes.SourceChanged; + + /// The account folder is not there (an unplugged disk): it is never created. + public const string AccountFolderMissing = "AccountFolderMissing"; + + /// The prefix of an unexpected failure; the exception's type name follows the colon. + public const string Error = "Error"; + + /// The prefix of the codes of files that never convert. + public const string AsIsPrefix = "AsIs"; + + /// «In pausa» for low space (D17). + public const string LowSpace = "Spazio libero sotto la soglia: la conversione della libreria è in pausa"; + + /// Waiting for the end of an engine session. + public const string InSession = "Il motore è in sessione: la conversione della libreria riprende dopo"; + + /// Waiting for an import, a copy or a rebuild. + public const string LongWork = "Un'importazione, una copia o una ricostruzione è al lavoro: la conversione della libreria riprende dopo"; + + /// True when the codes of a Failed row say the file never converts. + public static bool IsAsIs(string? codes) => codes is not null && codes.TrimStart().StartsWith(AsIsPrefix, StringComparison.Ordinal); + + /// The Italian text of a list of codes («·» between them); unknown codes are shown as they are. + public static string? Note(string? codes) + { + if (string.IsNullOrWhiteSpace(codes)) + { + return null; + } + + return string.Join(" · ", codes.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(One)); + } + + private static string One(string code) + { + var colon = code.IndexOf(':', StringComparison.Ordinal); + var name = colon < 0 ? code : code[..colon]; + return name switch + { + SourceMissing => "File non presente in libreria", + SourceChanged => "Il file della libreria non è quello registrato", + AccountFolderMissing => "La cartella dell'account non c'è: ricollega il disco e riprova", + Error => "Conversione non riuscita: riprova", + ImageConversionLosses.AsIsHeif => "Non si converte: HEIC", + ImageConversionLosses.AsIsAvif => "Non si converte: AVIF", + ImageConversionLosses.AsIsRaw => "Non si converte: raw", + ImageConversionLosses.AsIsAnimated => "Non si converte: immagine animata (perderebbe i fotogrammi dopo il primo)", + ImageConversionLosses.AsIsNotDecodable => "Non si converte: Febe non riesce a leggere l'immagine", + ImageConversionLosses.AsIsDeepColor => "Non si converte: più di 8 bit per colore", + ImageConversionLosses.AsIsCmyk => "Non si converte: immagine CMYK", + ImageConversionLosses.AsIsTooLarge => "Non si converte: troppo grande per il formato scelto", + MediaConversionResult.AsIsNotRemuxable => "Non si porta in MP4 senza ricodificarlo" + (ExportText.Note(code) is { } t && t.IndexOf('(', StringComparison.Ordinal) is var i and >= 0 ? " " + t[i..] : string.Empty), + _ => ExportText.Note(code) ?? code, + }; + } +} diff --git a/src/Febe.Core/Library/Conversion/LibraryConversionWorker.cs b/src/Febe.Core/Library/Conversion/LibraryConversionWorker.cs new file mode 100644 index 0000000..be99c3d --- /dev/null +++ b/src/Febe.Core/Library/Conversion/LibraryConversionWorker.cs @@ -0,0 +1,532 @@ +using System.Security.Cryptography; +using Febe.Core.Abstractions; +using Febe.Core.Alerts; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Storage; + +namespace Febe.Core.Library.Conversion; + +/// What the conversion for the library needs from the rest of Febe (tappa E3, WP2.2). +public sealed record LibraryConversionEnvironment +{ + public required IFebeStorage Storage { get; init; } + + /// The library folder and account folders now (on Windows it can change while Febe runs). + public required Func Layout { get; init; } + + public required IClock Clock { get; init; } + + /// Shared with import, export, rebuild and frame download, which pre-empt the conversion. Null: nothing to yield to (tests). + public LongWorkGate? Gate { get; init; } + + /// The conversion never runs during an engine session. + public IEngineSessionState Session { get; init; } = NoEngineSession.Instance; + + /// One conversion at a time in the process (D16): shared with the copies to external folders. + public ConversionThrottle Throttle { get; init; } = ConversionThrottle.Shared; + + /// The free space of the disk of an account folder. + public IFreeSpaceProbe FreeSpace { get; init; } = new DriveFreeSpaceProbe(); + + /// Below this, once the file is written, the conversion pauses (D17): the alerts' «quasi pieno». + public DiskThresholds Thresholds { get; init; } = DiskThresholds.Default; + + /// How long the worker sleeps when nothing wakes it. + public TimeSpan Idle { get; init; } = TimeSpan.FromSeconds(30); + + /// How often it looks again while it waits for an engine session or a long work to end. + public TimeSpan Poll { get; init; } = TimeSpan.FromSeconds(5); + + /// Rows read from the queue at a time. + public int BatchSize { get; init; } = 50; + + /// One line for the log: only Italian text and exception type names, never paths or messages. + public Action? Log { get; init; } + + /// Test seam: runs once the converted file is on disk, before its record. + public Func? AfterWrite { get; init; } +} + +/// The conversion for the library as the interface shows it. +/// Files in the queue. +/// Files converted. +/// Files that failed and can be tried again («Riprova»). +/// Files that never convert («non si convertono»). +/// «In pausa» by Alberto. +/// Why it waits now (an engine session, a long work, low space), or null. +/// The library file being converted now, or null. +public sealed record LibraryConversionStatus(int Pending, int Converted, int Failed, int AsIs, bool Paused, string? Waiting, long? CurrentMediaId); + +/// What one pass over the queue did. +/// Files converted (or adopted). +/// Rows settled: converted, dropped (already in the format), failed. +/// True when the pass stopped early and should look again soon (session, long work, pre-emption). +public sealed record LibraryConversionPass(int Converted, int Done, bool Again); + +/// +/// The conversion for the library (tappa E3, spec §4.10, D15-D18): adds, next to an original, the same file in the +/// format chosen for its kind, as a new file with the same stem and a free name. The original, its record, its +/// thumbnail, perceptual hash and journal line stay as they are; the converted file is only a media_conversion +/// row. It runs in the background through (started by the composition, never in the demo), +/// yields to import, export, rebuild and frame download (), never runs during +/// an engine session and pauses when the disk is almost full. +/// +public sealed class LibraryConversionWorker(LibraryConversionEnvironment env) +{ + private readonly LibraryConversionEnvironment _env = env ?? throw new ArgumentNullException(nameof(env)); + private volatile string? _waiting; + private long _current; + + /// The counts of the store with what the worker is doing now. + public async Task StatusAsync(CancellationToken ct = default) + { + var counts = await _env.Storage.Conversions.CountByStateAsync(ct).ConfigureAwait(false); + var paused = await LibraryConversionQueue.IsPausedAsync(_env.Storage.Settings, ct).ConfigureAwait(false); + var current = Interlocked.Read(ref _current); + return new LibraryConversionStatus(counts.Pending, counts.Converted, counts.Failed, counts.AsIs, paused, paused ? null : _waiting, current == 0 ? null : current); + } + + /// + /// The loop: a pass over the queue, then a wait for or + /// . A failure of a pass is logged by type and the loop goes on; it + /// ends with . + /// + public async Task RunAsync(CancellationToken ct) + { + while (!ct.IsCancellationRequested) + { + var wait = _env.Idle; + try + { + var pass = await RunOnceAsync(ct).ConfigureAwait(false); + if (pass.Again) + { + wait = _env.Poll; + } + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + return; + } + catch (Exception ex) + { + _env.Log?.Invoke($"La conversione della libreria si è fermata per un errore ({ex.GetType().Name}): riprova fra poco."); + } + + using var stop = CancellationTokenSource.CreateLinkedTokenSource(ct); + var signal = LibraryConversionQueue.NextSignal(); + var delay = _env.Clock.Delay(wait, stop.Token); + await Task.WhenAny(signal, delay).ConfigureAwait(false); + await stop.CancelAsync().ConfigureAwait(false); + } + } + + /// One pass over the queue, in order, until it is empty or something stops it. + public async Task RunOnceAsync(CancellationToken ct = default) + { + var storage = _env.Storage; + if (await LibraryConversionQueue.IsPausedAsync(storage.Settings, ct).ConfigureAwait(false)) + { + _waiting = null; + return new LibraryConversionPass(0, 0, false); + } + + if (_env.Session.InSession) + { + _waiting = LibraryConversionText.InSession; + return new LibraryConversionPass(0, 0, true); + } + + if ((await storage.Conversions.ListPendingAsync(0, 1, ct).ConfigureAwait(false)).Count == 0) + { + _waiting = null; + return new LibraryConversionPass(0, 0, false); + } + + LongWorkGate.BackgroundLease? lease = null; + if (_env.Gate is { } gate && !gate.TryEnterBackground(out lease)) + { + _waiting = LibraryConversionText.LongWork; + return new LibraryConversionPass(0, 0, true); + } + + using (lease) + { + using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, lease?.Preempted ?? CancellationToken.None); + var token = linked.Token; + _waiting = null; + var converted = 0; + var done = 0; + var after = 0L; + while (true) + { + var rows = await storage.Conversions.ListPendingAsync(after, _env.BatchSize, ct).ConfigureAwait(false); + if (rows.Count == 0) + { + return new LibraryConversionPass(converted, done, false); + } + + foreach (var row in rows) + { + after = row.Id; + if (token.IsCancellationRequested || _env.Session.InSession + || await LibraryConversionQueue.IsPausedAsync(storage.Settings, ct).ConfigureAwait(false)) + { + ct.ThrowIfCancellationRequested(); + return new LibraryConversionPass(converted, done, true); + } + + var outcome = await ConvertOneAsync(row, lease, token, ct).ConfigureAwait(false); + switch (outcome) + { + case Outcome.Converted: + converted++; + done++; + break; + case Outcome.Settled: + done++; + break; + case Outcome.LowSpace: + _waiting = LibraryConversionText.LowSpace; + return new LibraryConversionPass(converted, done, false); + case Outcome.Stopped: + ct.ThrowIfCancellationRequested(); + return new LibraryConversionPass(converted, done, true); + } + } + } + } + } + + private enum Outcome + { + Converted, + Settled, + Skipped, + LowSpace, + Stopped, + } + + private async Task ConvertOneAsync(MediaConversion row, LongWorkGate.BackgroundLease? lease, CancellationToken token, CancellationToken ct) + { + Interlocked.Exchange(ref _current, row.MediaId); + try + { + return await ConvertAsync(row, lease, token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + // Pre-empted, or Febe stops: our temporary file is gone, the row stays in the queue. + return Outcome.Stopped; + } + catch (Exception ex) + { + // One file never stops the queue: the reason goes to the row (codes, D19), the log gets the type only. + _env.Log?.Invoke($"Un file non si è convertito per la libreria ({ex.GetType().Name})."); + await FailAsync(row, $"{LibraryConversionText.Error}:{ex.GetType().Name}").ConfigureAwait(false); + ct.ThrowIfCancellationRequested(); + return Outcome.Settled; + } + finally + { + Interlocked.Exchange(ref _current, 0); + } + } + + private async Task ConvertAsync(MediaConversion row, LongWorkGate.BackgroundLease? lease, CancellationToken token) + { + var storage = _env.Storage; + var media = await storage.Media.GetAsync(row.MediaId, token).ConfigureAwait(false); + if (media is null || !EntryStateRules.IsPresent(media.State) || media.RelativePath is null || media.Sha256 is not { Length: 64 }) + { + // Not in the library (deleted meanwhile, or never stored): nothing to convert. + await storage.Conversions.DeletePendingRowAsync(row.Id, CancellationToken.None).ConfigureAwait(false); + return Outcome.Skipped; + } + + var entry = await storage.Entries.GetAsync(media.EntryId, token).ConfigureAwait(false); + var account = entry is null ? null : await storage.Accounts.GetAsync(entry.AccountId, token).ConfigureAwait(false); + if (entry is null || account is null) + { + await storage.Conversions.DeletePendingRowAsync(row.Id, CancellationToken.None).ConfigureAwait(false); + return Outcome.Skipped; + } + + var layout = _env.Layout(); + var folder = layout.AccountFolder(account); + if (!Directory.Exists(folder)) + { + // An unplugged disk of an account folder outside the library: never created again here. + await FailAsync(row, LibraryConversionText.AccountFolderMissing).ConfigureAwait(false); + return Outcome.Settled; + } + + var original = LibraryLayout.FullPath(folder, media.RelativePath); + if (!File.Exists(original)) + { + await FailAsync(row, LibraryConversionText.SourceMissing).ConfigureAwait(false); + return Outcome.Settled; + } + + var source = media.Sha256.ToLowerInvariant(); + if (!string.Equals(row.SourceSha256, source, StringComparison.Ordinal)) + { + row = row with { SourceSha256 = source, StateChangedAt = _env.Clock.Now }; + await storage.Conversions.UpdateAsync(row, CancellationToken.None).ConfigureAwait(false); + } + + if (media.Kind == MediaKind.Video && !string.Equals(await HashAsync(original, token).ConfigureAwait(false), source, StringComparison.Ordinal)) + { + // A remux reads the file in pieces: its bytes are checked first (a photo is checked by the converter). + await FailAsync(row, LibraryConversionText.SourceChanged).ConfigureAwait(false); + return Outcome.Settled; + } + + MediaConversionResult result; + try + { + result = await MediaConverter.PrepareAsync(() => OpenRead(original), media.RelativePath, media.Kind, row.Format, source, _env.Throttle, token) + .ConfigureAwait(false); + } + catch (ContentChangedException) + { + await FailAsync(row, LibraryConversionText.SourceChanged).ConfigureAwait(false); + return Outcome.Settled; + } + + using (result) + { + if (result.Variant == ExportVariant.Whole) + { + if (result.Notes.Count == 0) + { + // Already in the format by its bytes (a «.png» that is a JPEG, to JPG): there is no file to add. + await storage.Conversions.DeletePendingRowAsync(row.Id, CancellationToken.None).ConfigureAwait(false); + } + else + { + // Animated, not decodable, CMYK, too large, not remuxable…: it never converts (terminal). + await FailAsync(row, ExportText.JoinNotes(result.Notes)).ConfigureAwait(false); + } + + return Outcome.Settled; + } + + if (_env.FreeSpace.Measure(folder) is { } space + && _env.Thresholds.IsLow(space with { AvailableBytes = space.AvailableBytes - result.Length })) + { + return Outcome.LowSpace; + } + + return await WriteAsync(row, media, entry, account, folder, layout, result, lease, token).ConfigureAwait(false); + } + } + + private async Task WriteAsync(MediaConversion row, Media media, Entry entry, Account account, string folder, LibraryLayout layout, + MediaConversionResult result, LongWorkGate.BackgroundLease? lease, CancellationToken token) + { + var storage = _env.Storage; + var relative = LibraryLayout.ToStored(media.RelativePath!); + var slash = relative.LastIndexOf('/'); + var directory = slash < 0 ? string.Empty : relative[..slash]; + var stem = WindowsFileNames.SplitExtension(relative[(slash + 1)..]).Stem; + var setTime = await SetFileTimeAsync(token).ConfigureAwait(false); + + FileDigest written = default; + string? adopted = null; + var preempted = false; + IDisposable? commit = null; + try + { + var writer = new SafeFileWriter(layout.MaxPathLength); + var saved = await writer.SaveAsync( + result.Produce, + folder, + directory, + async (digest, t) => + { + written = digest; + adopted = await FindAdoptableAsync(account, folder, layout, directory, stem, result.Extension, digest, t).ConfigureAwait(false); + if (lease is not null && !lease.TryBeginCommit(out commit)) + { + preempted = true; + return null; + } + + return adopted is null ? Join(directory, stem + result.Extension) : null; + }, + new SafeWriteOptions + { + RequireExistingRoot = true, + VerifyFromDisk = true, + LastWriteTime = setTime ? entry.PublishedAt : null, + }, + token).ConfigureAwait(false); + if (preempted) + { + return Outcome.Stopped; + } + + var path = adopted ?? saved!.RelativePath; + if (_env.AfterWrite is { } after) + { + await after(row, CancellationToken.None).ConfigureAwait(false); + } + + MediaConversionCommitOutcome outcome; + try + { + outcome = await storage.Conversions.CommitAsync( + new MediaConversionCommit(row.Id, media.Id, row.Format, row.SourceSha256, path, written.Bytes, written.Sha256, _env.Clock.Now, + ExportText.JoinNotes(result.Notes)), + CancellationToken.None).ConfigureAwait(false); + } + catch when (adopted is null) + { + DiscardOwn(folder, path, written.Sha256); + throw; + } + + if (outcome is MediaConversionCommitOutcome.Recorded or MediaConversionCommitOutcome.Upserted) + { + return Outcome.Converted; + } + + if (adopted is null) + { + // The entry was deleted (or the original replaced) while the file was written: the file just written + // belongs to nothing. It is this operation's own file, never one of the library: it goes. + DiscardOwn(folder, path, written.Sha256); + } + + return Outcome.Settled; + } + finally + { + commit?.Dispose(); + } + } + + /// + /// A file already at the path (or at one of its free names) with the conversion's SHA-256 that no library file and + /// no other conversion records: a conversion of an earlier run (or of a lost database) whose record is missing. Null + /// when there is none: the file is written with the next free name. Never by size alone (D10). + /// + private async Task FindAdoptableAsync(Account account, string folder, LibraryLayout layout, string directory, string stem, string extension, + FileDigest digest, CancellationToken ct) + { + for (var attempt = 1; attempt <= 50; attempt++) + { + var name = attempt == 1 ? stem + extension : string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}"); + var segments = Join(directory, WindowsFileNames.SanitizeSegment(name)).Split('/', StringSplitOptions.RemoveEmptyEntries); + var relative = string.Join('/', WindowsFileNames.FitPath(folder, segments, layout.MaxPathLength)); + string full; + try + { + full = LibraryLayout.FullPath(folder, relative); + } + catch (ArgumentException) + { + return null; + } + + var info = new FileInfo(full); + if (!info.Exists) + { + return null; + } + + if (info.Length == digest.Bytes + && string.Equals(await HashAsync(full, ct).ConfigureAwait(false), digest.Sha256, StringComparison.Ordinal) + && !await IsRecordedAsync(account, relative, digest.Sha256, ct).ConfigureAwait(false)) + { + return relative; + } + } + + return null; + } + + /// A library file of the account, or a live conversion of one, records this path (another entry's «x.jpg»). + private async Task IsRecordedAsync(Account account, string relative, string sha, CancellationToken ct) + { + var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + var media = await _env.Storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false); + if (media.Any(m => m.Entry.AccountId == account.Id && m.Media.RelativePath is { } p && string.Equals(LibraryLayout.ToStored(p), relative, comparison))) + { + return true; + } + + foreach (var conversion in await _env.Storage.Conversions.FindBySha256Async(sha, ct).ConfigureAwait(false)) + { + if (conversion.State is MediaConversionState.Converted or MediaConversionState.Superseded + && conversion.RelativePath is { } path && string.Equals(path, relative, comparison)) + { + var owner = await _env.Storage.Media.GetAsync(conversion.MediaId, ct).ConfigureAwait(false); + var entry = owner is null ? null : await _env.Storage.Entries.GetAsync(owner.EntryId, ct).ConfigureAwait(false); + if (entry?.AccountId == account.Id) + { + return true; + } + } + } + + return false; + } + + /// Deletes the file this conversion just wrote, only if it still has the bytes written (precedent: LibraryIngest). + private void DiscardOwn(string folder, string relative, string sha) + { + try + { + var full = LibraryLayout.FullPath(folder, relative); + if (File.Exists(full) && string.Equals(HashFile(full), sha, StringComparison.Ordinal)) + { + File.Delete(full); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) + { + _env.Log?.Invoke($"Un file convertito per un elemento eliminato non si è potuto togliere ({ex.GetType().Name})."); + } + } + + private async Task FailAsync(MediaConversion row, string? codes) + { + try + { + await _env.Storage.Conversions.UpdateAsync( + row with { State = MediaConversionState.Failed, LastError = codes, StateChangedAt = _env.Clock.Now, RelativePath = null, Bytes = null, Sha256 = null, ConvertedAt = null }, + CancellationToken.None).ConfigureAwait(false); + } + catch (Exception ex) when (ex is KeyNotFoundException or DuplicateRecordException) + { + // The row went or changed meanwhile (a deletion, the setting turned off): nothing to record. + } + } + + private async Task SetFileTimeAsync(CancellationToken ct) + { + var text = await _env.Storage.Settings.GetAsync(SettingKeys.SetFileTimeToPublication, ct).ConfigureAwait(false); + return text is null || !bool.TryParse(text, out var parsed) || parsed; + } + + private static string Join(string directory, string name) => directory.Length == 0 ? name : directory + "/" + name; + + private static FileStream OpenRead(string path) => + new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 128 * 1024, FileOptions.RandomAccess); + + private static async Task HashAsync(string path, CancellationToken ct) + { + await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 128 * 1024, + FileOptions.Asynchronous | FileOptions.SequentialScan); + return Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false)); + } + + private static string HashFile(string path) + { + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 128 * 1024, FileOptions.SequentialScan); + return Convert.ToHexStringLower(SHA256.HashData(stream)); + } +} diff --git a/src/Febe.Core/Library/Conversion/MediaConverter.cs b/src/Febe.Core/Library/Conversion/MediaConverter.cs index a5b3c08..61f5cb6 100644 --- a/src/Febe.Core/Library/Conversion/MediaConverter.cs +++ b/src/Febe.Core/Library/Conversion/MediaConverter.cs @@ -47,6 +47,9 @@ public static class MediaConverter /// A raw camera format by its extension (with its dot), copied as it is. public static bool IsRawExtension(string extension) => RawExtensions.Contains(extension); + /// The raw camera extensions (with their dot, lower case), for rules written in SQL. + public static IReadOnlyCollection RawExtensionList => RawExtensions; + /// /// Prepares (only its name is used) in . /// opens the source for reading, seekable; it may be called more than once. diff --git a/src/Febe.Core/Library/DownloadDuplicateReview.cs b/src/Febe.Core/Library/DownloadDuplicateReview.cs index 75e13e6..7d0b150 100644 --- a/src/Febe.Core/Library/DownloadDuplicateReview.cs +++ b/src/Febe.Core/Library/DownloadDuplicateReview.cs @@ -282,7 +282,15 @@ public sealed class DownloadDuplicateReview( } var folder = layout.AccountFolder(account); + + // Its converted files of the library (tappa E3) go with it: the queue and the failures are dropped, the rows + // with a file become «Tolto». No supersession for the loser. + var conversions = await storage.Conversions.ListByMediaAsync(media.Id, ct).ConfigureAwait(false); + var withFiles = conversions + .Where(c => c.State is MediaConversionState.Converted or MediaConversionState.Superseded && c.RelativePath is not null && c.Sha256 is not null) + .ToList(); await storage.Media.UpdateAsync(media with { State = MediaState.Deleted }, ct).ConfigureAwait(false); + await storage.Conversions.ForgetDeletedMediaAsync(media.Id, clock.Now, ct).ConfigureAwait(false); await storage.Entries.RecomputeStateAsync(stored.Entry.Id, ct).ConfigureAwait(false); hashIndex?.Remove(media.Id); var remaining = stored.Media.Select(m => m.Id == media.Id ? m with { State = MediaState.Deleted } : m).ToList(); @@ -312,6 +320,14 @@ public sealed class DownloadDuplicateReview( } } + var failedConverted = new List(); + await LibraryDeletion.DeleteConvertedFilesAsync(storage, account.Id, folder, withFiles, [], [], failedConverted, ct).ConfigureAwait(false); + if (failedConverted.Count > 0) + { + var more = $"@{side.Username}, file convertiti: {string.Join("; ", failedConverted)}."; + problem = problem is null ? more : problem + " " + more; + } + if (thumbnails is not null && media.Sha256 is { } sha) { var users = await storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false); diff --git a/src/Febe.Core/Library/LibraryDeletion.cs b/src/Febe.Core/Library/LibraryDeletion.cs index e560701..3725650 100644 --- a/src/Febe.Core/Library/LibraryDeletion.cs +++ b/src/Febe.Core/Library/LibraryDeletion.cs @@ -31,6 +31,9 @@ public sealed record DeletionResult( IReadOnlyList FailedFiles) { public bool Complete => Found && FailedFiles.Count == 0; + + /// Converted files of the library (tappa E3) deleted with the originals; they are in too. + public int ConvertedFiles { get; init; } } /// @@ -62,6 +65,9 @@ public sealed class LibraryDeletion( var folder = layout.AccountFolder(account); var present = stored.Media.Where(m => m.RelativePath is not null && EntryStateRules.IsPresent(m.State)).ToList(); + // The converted files of the library (tappa E3) go with their originals; only the explicit choice deletes them. + var conversions = await storage.Conversions.ListByEntryAsync(entryId, ct).ConfigureAwait(false); + ct.ThrowIfCancellationRequested(); // From here the deletion goes to the end: a half-done deletion is worse than a late one. @@ -69,13 +75,15 @@ public sealed class LibraryDeletion( await journal.AppendDeletedAsync(folder, account, stored.Entry, present.Select(m => m.RelativePath!).ToList(), mode == DeletionMode.Remember, none) .ConfigureAwait(false); + IReadOnlyList withFiles; if (mode == DeletionMode.Remember) { - await storage.Entries.MarkDeletedAsync(entryId, clock.Now, none).ConfigureAwait(false); + withFiles = conversions.Where(HasFile).ToList(); + await storage.Entries.MarkDeletedAsync(entryId, clock.Now, withFiles.Select(c => c.Id).ToList(), none).ConfigureAwait(false); } else { - await storage.Entries.RemoveAsync(entryId, none).ConfigureAwait(false); + withFiles = (await storage.Entries.RemoveWithConversionsAsync(entryId, none).ConfigureAwait(false)).Where(HasFile).ToList(); } foreach (var media in stored.Media) @@ -108,6 +116,8 @@ public sealed class LibraryDeletion( } } + var converted = await DeleteConvertedFilesAsync(storage, account.Id, folder, withFiles, deleted, missing, failed, none).ConfigureAwait(false); + if (thumbnails is not null) { foreach (var sha in stored.Media.Select(m => m.Sha256).OfType().Distinct(StringComparer.Ordinal)) @@ -127,7 +137,89 @@ public sealed class LibraryDeletion( } } - return new DeletionResult(entryId, true, deleted, missing, failed); + return new DeletionResult(entryId, true, deleted, missing, failed) { ConvertedFiles = converted }; + } + + /// A conversion whose file is (or was last known to be) on disk. + private static bool HasFile(MediaConversion c) => + c.State is MediaConversionState.Converted or MediaConversionState.Superseded && c.RelativePath is not null && c.Sha256 is not null; + + /// + /// Deletes the converted files of conversions just removed or marked «Tolto», each only if no library file and no + /// live conversion still records its path and it still has the bytes recorded: a file replaced by Alberto stays and + /// is listed among the failures with its reason. Returns how many were deleted. + /// + internal static async Task DeleteConvertedFilesAsync(IFebeStorage storage, long accountId, string folder, IReadOnlyList conversions, + List deleted, List missing, List failed, CancellationToken ct) + { + var count = 0; + foreach (var conversion in conversions) + { + var relative = conversion.RelativePath!; + try + { + var path = LibraryLayout.FullPath(folder, relative); + if (!File.Exists(path)) + { + missing.Add(relative); + continue; + } + + if (await IsStillRecordedAsync(storage, accountId, conversion, ct).ConfigureAwait(false)) + { + continue; // another file of the library has that name now: it is not this conversion's to delete + } + + if (!string.Equals(HashFile(path), conversion.Sha256, StringComparison.OrdinalIgnoreCase)) + { + failed.Add($"{relative}: il file convertito è cambiato dopo la conversione, quindi resta dov'è."); + continue; + } + + File.Delete(path); + deleted.Add(relative); + count++; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) + { + failed.Add($"{relative}: {ex.Message}"); + } + } + + return count; + } + + private static async Task IsStillRecordedAsync(IFebeStorage storage, long accountId, MediaConversion conversion, CancellationToken ct) + { + var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + var sha = conversion.Sha256!; + foreach (var m in await storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false)) + { + if (m.Entry.AccountId == accountId && EntryStateRules.IsPresent(m.Media.State) && m.Media.RelativePath is { } p + && string.Equals(LibraryLayout.ToStored(p), conversion.RelativePath, comparison)) + { + return true; + } + } + + foreach (var other in await storage.Conversions.FindBySha256Async(sha, ct).ConfigureAwait(false)) + { + if (other.Id != conversion.Id && other.State is MediaConversionState.Converted or MediaConversionState.Superseded + && string.Equals(other.RelativePath, conversion.RelativePath, comparison) + && await storage.Media.GetAsync(other.MediaId, ct).ConfigureAwait(false) is { } owner + && (await storage.Entries.GetAsync(owner.EntryId, ct).ConfigureAwait(false))?.AccountId == accountId) + { + return true; + } + } + + return false; + } + + private static string HashFile(string path) + { + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 128 * 1024, FileOptions.SequentialScan); + return Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(stream)); } /// Multiple selection: deletes each entry in turn. diff --git a/src/Febe.Core/Library/LibraryIngest.cs b/src/Febe.Core/Library/LibraryIngest.cs index 45b8dc3..6ca9b2f 100644 --- a/src/Febe.Core/Library/LibraryIngest.cs +++ b/src/Febe.Core/Library/LibraryIngest.cs @@ -3,6 +3,7 @@ using System.Globalization; using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Core.Export; +using Febe.Core.Library.Conversion; using Febe.Core.Storage; namespace Febe.Core.Library; @@ -371,6 +372,9 @@ public sealed class LibraryIngest( stored.Media, highlights.Select(h => new JournalHighlight(h.InstagramId, h.Title, h.Position)).ToList(), ct).ConfigureAwait(false); + + // The conversion for the library (tappa E3, Q29): a new file enters its queue after its journal line. + await LibraryConversionQueue.EnqueueEntryAsync(storage, stored.Media, clock.Now, CancellationToken.None).ConfigureAwait(false); } /// diff --git a/src/Febe.Core/Library/LibraryRebuilder.cs b/src/Febe.Core/Library/LibraryRebuilder.cs index a7915aa..f2a2833 100644 --- a/src/Febe.Core/Library/LibraryRebuilder.cs +++ b/src/Febe.Core/Library/LibraryRebuilder.cs @@ -1,7 +1,9 @@ +using System.Globalization; using System.Security.Cryptography; using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Core.Export; +using Febe.Core.Library.Conversion; using Febe.Core.Storage; namespace Febe.Core.Library; @@ -61,6 +63,15 @@ public sealed record RebuildReport /// Files in account folders that no journal line mentions: left untouched, not added. public int UntrackedFiles { get; init; } + /// + /// Converted files of the library without a record (tappa E3): next to a file of the journal, with its name and in a + /// target format. Left untouched; queued again when the conversion for their kind is on with that format. + /// + public int ConversionsFound { get; init; } + + /// Converted files of the library still on disk for entries deleted «ricordando la scelta»: left untouched. + public int ConversionsOfDeletedEntries { get; init; } + public int InvalidLines { get; init; } /// A few examples of what needs attention (Italian), for the report screen. @@ -152,7 +163,7 @@ public sealed class LibraryRebuilder( var allItems = Fold(journal.Lines, report); // Entries already in the database are left as they are (deletions excepted): no hashing, no change. - var items = await SplitPresentAsync(account, allItems, report, ct).ConfigureAwait(false); + var items = await SplitPresentAsync(account, folder, allItems, report, ct).ConfigureAwait(false); // Verify files in parallel: hashing dominates the time. var live = items.Where(i => !i.Deleted).ToList(); @@ -198,11 +209,11 @@ public sealed class LibraryRebuilder( batch.Add((item, new NewEntry(entry, media))); if (batch.Count >= BatchSize) { - await FlushAsync(account, batch, report, ct).ConfigureAwait(false); + await FlushAsync(account, folder, batch, report, ct).ConfigureAwait(false); } } - await FlushAsync(account, batch, report, ct).ConfigureAwait(false); + await FlushAsync(account, folder, batch, report, ct).ConfigureAwait(false); // Files whose bytes on disk differ from the journal: their copies in external folders are «Superato» (spec §4.10). foreach (var (old, now) in report.Changed) @@ -211,14 +222,14 @@ public sealed class LibraryRebuilder( } report.Changed.Clear(); - CountUntracked(folder, allItems, report); + await CountUntrackedAsync(account, folder, allItems, report, ct).ConfigureAwait(false); } /// /// Returns the items that are not in the database yet. Items already present are counted; a remembered deletion /// is applied to them if the database still shows them. /// - private async Task> SplitPresentAsync(Account account, List items, Accumulator report, CancellationToken ct) + private async Task> SplitPresentAsync(Account account, string folder, List items, Accumulator report, CancellationToken ct) { var paths = await storage.Media.MapPathsAsync(account.Id, ct).ConfigureAwait(false); var known = new HashSet<(EntryKind, string)>(); @@ -253,7 +264,7 @@ public sealed class LibraryRebuilder( : null; if (existing is not null && existing.State != EntryState.Deleted) { - await storage.Entries.MarkDeletedAsync(existing.Id, item.DeletedAt ?? clock.Now, ct).ConfigureAwait(false); + await MarkDeletedAsync(folder, existing.Id, item.DeletedAt ?? clock.Now, report, ct).ConfigureAwait(false); } } } @@ -582,7 +593,7 @@ public sealed class LibraryRebuilder( }; } - private async Task FlushAsync(Account account, List<(Item Item, NewEntry Entry)> batch, Accumulator report, CancellationToken ct) + private async Task FlushAsync(Account account, string folder, List<(Item Item, NewEntry Entry)> batch, Accumulator report, CancellationToken ct) { if (batch.Count == 0) { @@ -604,7 +615,7 @@ public sealed class LibraryRebuilder( report.EntriesAlreadyPresent++; if (item.Deleted && stored.Entry.State != EntryState.Deleted) { - await storage.Entries.MarkDeletedAsync(stored.Entry.Id, item.DeletedAt ?? clock.Now, ct).ConfigureAwait(false); + await MarkDeletedAsync(folder, stored.Entry.Id, item.DeletedAt ?? clock.Now, report, ct).ConfigureAwait(false); } } @@ -661,11 +672,98 @@ public sealed class LibraryRebuilder( State = MediaState.Deleted, }; - private static void CountUntracked(string folder, List items, Accumulator report) + /// + /// A remembered deletion found by the rebuild (tappa E3, WP2.4): the entry's conversions whose converted file is + /// missing become «Tolto»; those whose file is still on disk stay as they are (the rebuild never deletes a file) and + /// are counted. + /// + private async Task MarkDeletedAsync(string folder, long entryId, DateTimeOffset at, Accumulator report, CancellationToken ct) { + var missing = new List(); + foreach (var conversion in await storage.Conversions.ListByEntryAsync(entryId, ct).ConfigureAwait(false)) + { + if (conversion.State is not (MediaConversionState.Converted or MediaConversionState.Superseded) || conversion.RelativePath is not { } relative) + { + continue; + } + + if (ExistsIn(folder, relative)) + { + report.ConversionsOfDeletedEntries++; + } + else + { + missing.Add(conversion.Id); + } + } + + await storage.Entries.MarkDeletedAsync(entryId, at, missing, ct).ConfigureAwait(false); + } + + private static bool ExistsIn(string folder, string relative) + { + try + { + return File.Exists(LibraryLayout.FullPath(folder, relative)); + } + catch (ArgumentException) + { + return false; + } + } + + /// The format a converted file of the library has, by its extension; null for any other file. + private static ExportFormat? ConvertedFormatOf(string extension) => extension.ToLowerInvariant() switch + { + ".jpg" or ".jpeg" => ExportFormat.Jpg, + ".png" => ExportFormat.Png, + ".webp" => ExportFormat.WebpLossless, + ".mp4" => ExportFormat.Mp4, + _ => null, + }; + + /// «nome (2)» → «nome»: the free names the conversion for the library gives. + private static string WithoutNumber(string stem) + { + var open = stem.LastIndexOf(" (", StringComparison.Ordinal); + if (open > 0 && stem.EndsWith(')') + && int.TryParse(stem.AsSpan(open + 2, stem.Length - open - 3), NumberStyles.None, CultureInfo.InvariantCulture, out _)) + { + return stem[..open]; + } + + return stem; + } + + /// + /// Counts the files of the account folder that no journal line mentions (left untouched). The converted files of the + /// library (tappa E3) are not unknown: those with a row are skipped; one without a row, next to a file of the + /// journal with its stem and in a target format, is counted apart and, when the conversion for that kind is on with + /// that format, its file is queued again (a Pending row: the worker adopts the file by its SHA-256). Nothing is + /// converted during the rebuild. + /// + private async Task CountUntrackedAsync(Account account, string folder, List items, Accumulator report, CancellationToken ct) + { + var comparer = OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; var known = new HashSet( items.SelectMany(i => i.Files.Values.Concat(i.Removed.Values)).Select(f => LibraryLayout.ToStored(f.Path)), - OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + comparer); + foreach (var path in await storage.Conversions.ListPathsByAccountAsync(account.Id, ct).ConfigureAwait(false)) + { + known.Add(path); + } + + // Files of the journal by folder and stem, for the converted files next to them. + var byStem = new Dictionary(comparer); + foreach (var file in items.Where(i => !i.Deleted).SelectMany(i => i.Files.Values)) + { + var stored = LibraryLayout.ToStored(file.Path); + var slash = stored.LastIndexOf('/'); + byStem.TryAdd((slash < 0 ? string.Empty : stored[..(slash + 1)]) + WindowsFileNames.SplitExtension(stored[(slash + 1)..]).Stem, file); + } + + ExportSettings? settings = null; + IReadOnlyDictionary? paths = null; foreach (var file in Directory.EnumerateFiles(folder, "*", new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true })) { var name = Path.GetFileName(file); @@ -675,11 +773,56 @@ public sealed class LibraryRebuilder( } var relative = LibraryLayout.ToStored(Path.GetRelativePath(folder, file)); - if (!known.Contains(relative)) + if (known.Contains(relative)) { - report.UntrackedFiles++; - report.Note($"File non registrato in _febe.jsonl (lasciato dov'è): {Path.GetFileName(folder)}/{relative}"); + continue; } + + var slash = relative.LastIndexOf('/'); + var (stem, extension) = WindowsFileNames.SplitExtension(relative[(slash + 1)..]); + var key = (slash < 0 ? string.Empty : relative[..(slash + 1)]) + WithoutNumber(stem); + if (ConvertedFormatOf(extension) is { } format && byStem.TryGetValue(key, out var original)) + { + report.ConversionsFound++; + try + { + settings ??= await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false); + paths ??= await storage.Media.MapPathsAsync(account.Id, ct).ConfigureAwait(false); + await QueueFoundAsync(original, format, settings, paths, ct).ConfigureAwait(false); + } + catch (Exception ex) when (ex is DuplicateRecordException or KeyNotFoundException or ArgumentException) + { + // Counted, never thrown: the worker or a later rebuild finds it again. + } + + continue; + } + + report.UntrackedFiles++; + report.Note($"File non registrato in _febe.jsonl (lasciato dov'è): {Path.GetFileName(folder)}/{relative}"); + } + } + + /// Queues the journal file in when its conversion is on with that format. + private async Task QueueFoundAsync(JournalFile original, ExportFormat format, ExportSettings settings, IReadOnlyDictionary paths, CancellationToken ct) + { + var stored = LibraryLayout.ToStored(original.Path); + if (!paths.TryGetValue(stored, out var entryId)) + { + return; + } + + var media = (await storage.Media.ListByEntryAsync(entryId, ct).ConfigureAwait(false)) + .FirstOrDefault(m => m.RelativePath is { } p && string.Equals(LibraryLayout.ToStored(p), stored, StringComparison.Ordinal)); + if (media is null || LibraryConversionRules.FormatFor(media.Kind, settings) != format) + { + return; + } + + var requests = LibraryConversionRules.RequestsFor([media], settings); + if (requests.Count > 0) + { + await storage.Conversions.EnqueueAsync(requests, clock.Now, ct).ConfigureAwait(false); } } @@ -746,6 +889,10 @@ public sealed class LibraryRebuilder( public int UntrackedFiles { get; set; } + public int ConversionsFound { get; set; } + + public int ConversionsOfDeletedEntries { get; set; } + public int InvalidLines { get; set; } /// (journal SHA-256, SHA-256 on disk) of the folder being rebuilt, for the copies to mark «Superato». @@ -773,6 +920,8 @@ public sealed class LibraryRebuilder( FilesUnreadable = FilesUnreadable, HashMismatches = HashMismatches, UntrackedFiles = UntrackedFiles, + ConversionsFound = ConversionsFound, + ConversionsOfDeletedEntries = ConversionsOfDeletedEntries, InvalidLines = InvalidLines, Notes = _notes, }; diff --git a/src/Febe.Core/Storage/IEntryStore.cs b/src/Febe.Core/Storage/IEntryStore.cs index bc61bbc..55ab147 100644 --- a/src/Febe.Core/Storage/IEntryStore.cs +++ b/src/Febe.Core/Storage/IEntryStore.cs @@ -58,11 +58,28 @@ public interface IEntryStore /// «Eliminato»: the entry stays without files so it is not downloaded again (spec §4.6). Its files become /// and lose their path and perceptual hash; SHA-256 and size are kept. Deleting files on disk is the caller's job. /// - Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default); + Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default) => MarkDeletedAsync(entryId, at, [], ct); - /// «Eliminalo e lascia che torni»: removes the record (files records and highlight links by cascade). + /// + /// As , and in the same transaction the + /// conversions for the library of its files: the queue and the failures (Pending, Failed) go, and the rows of + /// (whose converted file goes or is gone) become «Tolto». Other converted rows stay. + /// + Task MarkDeletedAsync(long entryId, DateTimeOffset at, IReadOnlyCollection removedConversionIds, CancellationToken ct = default); + + /// + /// «Eliminalo e lascia che torni»: removes the record (files records and highlight links by cascade). Conversions + /// without a file left (Pending, Failed, Removed) go with it; a Converted or Superseded one makes it fail with + /// (its file would be forgotten): use . + /// Task RemoveAsync(long entryId, CancellationToken ct = default); + /// + /// «Eliminalo e lascia che torni» from «Elimina dalla libreria»: removes the record and every conversion of its files + /// in one transaction, and returns the conversions removed (their converted files are the caller's to delete). + /// + Task> RemoveWithConversionsAsync(long entryId, CancellationToken ct = default); + /// Entries of an account ordered by publication time, newest first (account tabs, collection pipeline). Task> ListByAccountAsync(long accountId, EntryListOptions? options = null, CancellationToken ct = default); diff --git a/src/Febe.Core/Storage/IExportStore.cs b/src/Febe.Core/Storage/IExportStore.cs index 3241720..eacc66a 100644 --- a/src/Febe.Core/Storage/IExportStore.cs +++ b/src/Febe.Core/Storage/IExportStore.cs @@ -198,6 +198,13 @@ public interface IExportStore /// Task FindCopiedElsewhereAsync(string sha256, long? exceptAccountId = null, CancellationToken ct = default); + /// + /// The SHA-256 of every file written converted or as a frame in a destination (any state, any destination): an + /// import recognises them as copies of library files (tappa E3, Q37). No index on copy_sha256: one read per + /// import run, bounded by the converted copies. + /// + Task> LoadConvertedCopyShasAsync(CancellationToken ct = default); + /// /// The current (Copied or Failed) rows of an original for an account in a destination, in any form but a frame, /// newest first: «già copiato» looks at the file, not at its format (decision D3 of tappa E3). diff --git a/src/Febe.Core/Storage/IMediaConversionStore.cs b/src/Febe.Core/Storage/IMediaConversionStore.cs index ed1ede3..fcb5db6 100644 --- a/src/Febe.Core/Storage/IMediaConversionStore.cs +++ b/src/Febe.Core/Storage/IMediaConversionStore.cs @@ -25,9 +25,119 @@ public interface IMediaConversionStore /// The conversions of one library file, in creation order. Task> ListByMediaAsync(long mediaId, CancellationToken ct = default); + /// The conversions of the files of one entry, by file and creation order. + Task> ListByEntryAsync(long entryId, CancellationToken ct = default); + + /// The conversions of these library files, by file and creation order. + Task> ListByMediaIdsAsync(IReadOnlyCollection mediaIds, CancellationToken ct = default); + + /// + /// The paths (relative to the account folder) that conversions of the account's files record: Converted, + /// Superseded and Removed rows (a rebuild does not count them as unknown files). + /// + Task> ListPathsByAccountAsync(long accountId, CancellationToken ct = default); + + /// The conversions of the account's files that record this path (any state with a path), by key. + Task> FindByPathAsync(long accountId, string relativePath, CancellationToken ct = default); + /// Conversions whose converted file has this SHA-256 (a converted file found again is never a duplicate). Task> FindBySha256Async(string sha256, CancellationToken ct = default); /// The queue of the conversion, in order, by key. Task> ListPendingAsync(long afterId = 0, int limit = 500, CancellationToken ct = default); + + /// «Tolto»: these Converted or Superseded rows lost their file with their entry. Returns the rows changed. + Task MarkRemovedAsync(IReadOnlyCollection ids, DateTimeOffset at, CancellationToken ct = default); + + /// + /// A library file left its entry («Tieni il più grande» on a file of a series): its queue and failures go, its rows + /// with a file become «Tolto», in one transaction. Returns the rows marked «Tolto». + /// + Task ForgetDeletedMediaAsync(long mediaId, DateTimeOffset at, CancellationToken ct = default); + + /// + /// The account's file changed from to (spec §4.10 + /// «Superato»): the conversions made from the old bytes of the account's files that now have the new ones become + /// Superseded (their files stay); Pending and retryable Failed rows take the new SHA-256. Returns the media ids of the + /// files concerned (to queue them again). + /// + Task> SupersedeAsync(long accountId, string oldSha256, string newSha256, DateTimeOffset at, CancellationToken ct = default); + + /// The setting of a format went off or changed: its queue is emptied (Converted rows and their files stay). + Task DeletePendingAsync(ExportFormat format, CancellationToken ct = default); + + /// Drops one Pending row (a file already in the format by its bytes: nothing to record). False when it is not Pending. + Task DeletePendingRowAsync(long id, CancellationToken ct = default); + + /// How many rows are in each state; Failed rows with an AsIs* code are counted apart. + Task CountByStateAsync(CancellationToken ct = default); + + /// + /// Queues these files in these formats (Pending, source_sha256 = the given SHA-256). A file that already has a + /// current conversion in the format (Pending, Converted, or Failed, which holds the slot) is left as it is. Returns + /// how many rows were added. + /// + Task EnqueueAsync(IReadOnlyList requests, DateTimeOffset at, CancellationToken ct = default); + + /// + /// «Anche i N già in libreria»: queues, in one statement, every present library file of each kind whose extension + /// says it converts into the format given for its kind (null: that kind is not queued). Returns how many were added. + /// + Task EnqueueExistingAsync(ExportFormat? photo, ExportFormat? video, DateTimeOffset at, CancellationToken ct = default); + + /// What would queue: files and their bytes. + Task<(int Files, long Bytes)> CountExistingAsync(ExportFormat? photo, ExportFormat? video, CancellationToken ct = default); + + /// + /// Records a converted file just written (or adopted) for a Pending row, in one transaction (WP2.2 step 4): the row + /// becomes Converted only if it is still Pending with and its library file is still + /// present with that SHA-256. Otherwise, with the file still present and unchanged, the current conversion of that + /// file and format becomes Converted with this file, or a new row is added; with the file gone or changed nothing is + /// recorded. + /// + Task CommitAsync(MediaConversionCommit commit, CancellationToken ct = default); + + /// «Riprova»: Failed rows go back to Pending, except those with an AsIs* code (they never convert). Returns how many. + Task ResetFailedAsync(DateTimeOffset at, CancellationToken ct = default); +} + +/// One file to queue in one format, made from these bytes. +public sealed record MediaConversionRequest(long MediaId, ExportFormat Format, string SourceSha256); + +/// The rows of the conversion for the library, by state. +/// In the queue. +/// Converted files. +/// Failed, to try again («Riprova»). +/// Failed for good: animated, not decodable, CMYK… («non si convertono»). +/// Converted from bytes the library no longer has. +/// Their file went with the entry. +public sealed record MediaConversionCounts(int Pending, int Converted, int Failed, int AsIs, int Superseded, int Removed); + +/// A converted file written for . +/// The Pending row it was written for. +/// Its library file. +/// The format. +/// The SHA-256 of the original it was made from. +/// Path relative to the account folder. +/// Its size. +/// Its SHA-256. +/// When it was converted. +/// What the conversion could not keep (loss codes, D19), or null. +public sealed record MediaConversionCommit(long ConversionId, long MediaId, ExportFormat Format, string SourceSha256, + string RelativePath, long Bytes, string Sha256, DateTimeOffset At, string? Notes); + +/// What did. +public enum MediaConversionCommitOutcome +{ + /// The Pending row is now Converted. + Recorded, + + /// The row had changed meanwhile; the file is recorded in the current row of its format, or a new one. + Upserted, + + /// Nothing recorded: the library file was deleted or changed meanwhile. + SourceGone, + + /// Nothing recorded: another converted file already holds the format of this library file. + SlotTaken, } diff --git a/src/Febe.Data/Stores/EntryStore.cs b/src/Febe.Data/Stores/EntryStore.cs index fa2cd42..a246224 100644 --- a/src/Febe.Data/Stores/EntryStore.cs +++ b/src/Febe.Data/Stores/EntryStore.cs @@ -148,8 +148,13 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore public Task RecomputeStateAsync(long entryId, CancellationToken ct = default) => db.WriteAsync(w => RecomputeState(w, entryId), ct); - public Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default) => - db.WriteAsync( + public Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default) => MarkDeletedAsync(entryId, at, [], ct); + + public Task MarkDeletedAsync(long entryId, DateTimeOffset at, IReadOnlyCollection removedConversionIds, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(removedConversionIds); + var removed = removedConversionIds.Distinct().ToList(); + return db.WriteAsync( w => { var rows = w.Command("UPDATE entry SET state = 'Deleted', deleted_at = @at WHERE id = @id") @@ -163,11 +168,69 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore UPDATE media SET state = 'Deleted', relative_path = NULL, has_thumbnail = 0, phash = NULL, source_url = NULL, cover_url = NULL WHERE entry_id = @id """).With("@id", entryId).ExecuteNonQuery(); + + // The conversions for the library of its files (tappa E3): nothing left to convert or retry; the + // converted files that go (or are gone) are «Tolto», the others stay as they are. + w.Command(""" + DELETE FROM media_conversion WHERE state IN ('Pending', 'Failed') AND media_id IN (SELECT id FROM media WHERE entry_id = @id) + """).With("@id", entryId).ExecuteNonQuery(); + if (removed.Count > 0) + { + var own = new HashSet(); + using (var r = w.Command("SELECT mc.id FROM media_conversion mc JOIN media m ON m.id = mc.media_id WHERE m.entry_id = @id") + .With("@id", entryId).ExecuteReader()) + { + while (r.Read()) + { + own.Add(r.GetInt64(0)); + } + } + + MediaConversionStore.MarkRemoved(w, removed.Where(own.Contains).ToList(), at); + } + }, + ct); + } + + public Task RemoveAsync(long entryId, CancellationToken ct = default) => + db.WriteAsync( + w => + { + MediaConversionStore.DeleteRowsWithoutFile(w, entryId); + try + { + w.Command("DELETE FROM entry WHERE id = @id").With("@id", entryId).ExecuteNonQuery(); + } + catch (SqliteException ex) when (ex.IsConstraintViolation()) + { + // ON DELETE RESTRICT of media_conversion: a converted file of the library would lose its record. + throw new InvalidOperationException( + "L'elemento ha file convertiti nella libreria: eliminalo con «Elimina dalla libreria», che toglie anche quelli.", ex); + } }, ct); - public Task RemoveAsync(long entryId, CancellationToken ct = default) => - db.WriteAsync(w => w.Command("DELETE FROM entry WHERE id = @id").With("@id", entryId).ExecuteNonQuery(), ct); + public Task> RemoveWithConversionsAsync(long entryId, CancellationToken ct = default) => + db.WriteAsync>( + w => + { + var list = new List(); + using (var r = w.Command($""" + SELECT {MediaConversionStore.JoinedColumnList} FROM media_conversion mc JOIN media m ON m.id = mc.media_id + WHERE m.entry_id = @id ORDER BY mc.media_id, mc.id + """).With("@id", entryId).ExecuteReader()) + { + while (r.Read()) + { + list.Add(MediaConversionStore.ReadRow(r)); + } + } + + w.Command("DELETE FROM media_conversion WHERE media_id IN (SELECT id FROM media WHERE entry_id = @id)").With("@id", entryId).ExecuteNonQuery(); + w.Command("DELETE FROM entry WHERE id = @id").With("@id", entryId).ExecuteNonQuery(); + return list; + }, + ct); public Task> ListByAccountAsync(long accountId, EntryListOptions? options = null, CancellationToken ct = default) { diff --git a/src/Febe.Data/Stores/ExportStore.cs b/src/Febe.Data/Stores/ExportStore.cs index e0fadc7..3492326 100644 --- a/src/Febe.Data/Stores/ExportStore.cs +++ b/src/Febe.Data/Stores/ExportStore.cs @@ -829,6 +829,22 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore /// The first item of a file of a job in a form (ux_export_item_file). internal const string FirstItemSql = "SELECT min(id) FROM export_item WHERE run_id = @r AND media_id = @m AND variant = @v AND format = @f"; + public Task> LoadConvertedCopyShasAsync(CancellationToken ct = default) => + db.ReadAsync>( + c => + { + using var command = c.Command("SELECT DISTINCT copy_sha256 FROM export_copy WHERE variant IN ('Converted', 'Frame') AND copy_sha256 IS NOT NULL"); + using var r = command.ExecuteReader(); + var set = new HashSet(StringComparer.Ordinal); + while (r.Read()) + { + set.Add(r.GetString(0)); + } + + return set; + }, + ct); + public Task FirstItemIdAsync(long runId, long mediaId, ExportVariant variant, ExportFormat format, CancellationToken ct = default) => db.ReadAsync( c => c.Command(FirstItemSql).With("@r", runId).With("@m", mediaId).With("@v", Sql.Enum(variant)).With("@f", Sql.Enum(format)).ExecuteScalar() is long id diff --git a/src/Febe.Data/Stores/MediaConversionStore.Library.cs b/src/Febe.Data/Stores/MediaConversionStore.Library.cs new file mode 100644 index 0000000..66ffeaa --- /dev/null +++ b/src/Febe.Data/Stores/MediaConversionStore.Library.cs @@ -0,0 +1,464 @@ +using System.Globalization; +using System.Text; +using Febe.Core.Domain; +using Febe.Core.Library.Conversion; +using Febe.Core.Storage; +using Microsoft.Data.Sqlite; + +namespace Febe.Data.Stores; + +/// The queue, the commit and the hooks of the conversion for the library (tappa E3, WP2.3). +internal sealed partial class MediaConversionStore +{ + /// The same columns of the alias mc, for joins. + private const string JoinedColumns = + "mc.id, mc.media_id, mc.format, mc.state, mc.source_sha256, mc.relative_path, mc.bytes, mc.sha256, mc.created_at, mc.converted_at, mc.state_changed_at, mc.last_error"; + + /// The columns of the alias mc, for other stores reading rows with . + internal const string JoinedColumnList = JoinedColumns; + + /// The present library files of the alias m, as the conversion for the library sees them. + private const string PresentMedia = "m.state IN ('Downloaded', 'Imported') AND m.sha256 IS NOT NULL AND m.relative_path IS NOT NULL"; + + /// A Failed row whose code says it never converts (animated, not decodable, CMYK…): its first code. + internal const string AsIsCondition = "last_error LIKE 'AsIs%'"; + + /// One row read in the order of . + internal static MediaConversion ReadRow(SqliteDataReader r) => Read(r); + + public Task> ListByEntryAsync(long entryId, CancellationToken ct = default) => + db.ReadAsync>( + c => ReadAll(c.Command($""" + SELECT {JoinedColumns} FROM media_conversion mc JOIN media m ON m.id = mc.media_id + WHERE m.entry_id = @e ORDER BY mc.media_id, mc.id + """).With("@e", entryId)), + ct); + + public Task> ListByMediaIdsAsync(IReadOnlyCollection mediaIds, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(mediaIds); + var ids = mediaIds.Distinct().ToList(); + if (ids.Count == 0) + { + return Task.FromResult>([]); + } + + return db.ReadAsync>( + c => + { + var list = new List(); + foreach (var chunk in ids.Chunk(500)) + { + using var command = c.Command(string.Empty); + command.CommandText = $"SELECT {Columns} FROM media_conversion WHERE media_id IN ({command.AddList("m", chunk)})"; + list.AddRange(ReadAll(command)); + } + + return list.OrderBy(x => x.MediaId).ThenBy(x => x.Id).ToList(); + }, + ct); + } + + public Task> ListPathsByAccountAsync(long accountId, CancellationToken ct = default) => + db.ReadAsync>( + c => + { + using var command = c.Command(""" + SELECT DISTINCT mc.relative_path FROM media_conversion mc + JOIN media m ON m.id = mc.media_id JOIN entry e ON e.id = m.entry_id + WHERE e.account_id = @a AND mc.relative_path IS NOT NULL AND mc.state IN ('Converted', 'Superseded', 'Removed') + """).With("@a", accountId); + using var r = command.ExecuteReader(); + var list = new List(); + while (r.Read()) + { + list.Add(r.GetString(0)); + } + + return list; + }, + ct); + + public Task> FindByPathAsync(long accountId, string relativePath, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(relativePath); + return db.ReadAsync>( + c => ReadAll(c.Command($""" + SELECT {JoinedColumns} FROM media_conversion mc + JOIN media m ON m.id = mc.media_id JOIN entry e ON e.id = m.entry_id + WHERE e.account_id = @a AND mc.relative_path = @p ORDER BY mc.id + """).With("@a", accountId).With("@p", relativePath)), + ct); + } + + public Task MarkRemovedAsync(IReadOnlyCollection ids, DateTimeOffset at, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(ids); + var list = ids.Distinct().ToList(); + return list.Count == 0 ? Task.FromResult(0) : db.WriteAsync(w => MarkRemoved(w, list, at), ct); + } + + /// «Tolto» for these ids among the Converted and Superseded rows, inside the caller's transaction. + internal static int MarkRemoved(WriteContext w, IReadOnlyCollection ids, DateTimeOffset at) + { + var changed = 0; + foreach (var chunk in ids.Chunk(500)) + { + using var command = w.Connection.Command(string.Empty, w.Transaction); + command.CommandText = $""" + UPDATE media_conversion SET state = 'Removed', state_changed_at = @at + WHERE state IN ('Converted', 'Superseded') AND id IN ({command.AddList("i", chunk)}) + """; + changed += command.With("@at", Sql.Time(at)).ExecuteNonQuery(); + } + + return changed; + } + + public Task ForgetDeletedMediaAsync(long mediaId, DateTimeOffset at, CancellationToken ct = default) => + db.WriteAsync( + w => + { + w.Command("DELETE FROM media_conversion WHERE media_id = @m AND state IN ('Pending', 'Failed')").With("@m", mediaId).ExecuteNonQuery(); + return w.Command(""" + UPDATE media_conversion SET state = 'Removed', state_changed_at = @at WHERE media_id = @m AND state IN ('Converted', 'Superseded') + """).With("@m", mediaId).With("@at", Sql.Time(at)).ExecuteNonQuery(); + }, + ct); + + /// The rows without a file left (Pending, Failed, Removed) of an entry's files go, inside the caller's transaction. + internal static int DeleteRowsWithoutFile(WriteContext w, long entryId) => + w.Command(""" + DELETE FROM media_conversion WHERE state IN ('Pending', 'Failed', 'Removed') + AND media_id IN (SELECT id FROM media WHERE entry_id = @e) + """).With("@e", entryId).ExecuteNonQuery(); + + public Task> SupersedeAsync(long accountId, string oldSha256, string newSha256, DateTimeOffset at, CancellationToken ct = default) + { + var old = ExportValues.Sha(oldSha256, nameof(oldSha256)); + var now = ExportValues.Sha(newSha256, nameof(newSha256)); + if (old == now) + { + return Task.FromResult>([]); + } + + return db.WriteAsync>( + w => + { + var media = new List(); + using (var find = w.Connection.Command(""" + SELECT DISTINCT mc.media_id FROM media_conversion mc + JOIN media m ON m.id = mc.media_id JOIN entry e ON e.id = m.entry_id + WHERE e.account_id = @a AND mc.source_sha256 = @old AND m.sha256 = @new + AND mc.state IN ('Pending', 'Converted', 'Failed') + ORDER BY mc.media_id + """, w.Transaction)) + { + find.With("@a", accountId).With("@old", old).With("@new", now); + using var r = find.ExecuteReader(); + while (r.Read()) + { + media.Add(r.GetInt64(0)); + } + } + + foreach (var chunk in media.Chunk(500)) + { + using var command = w.Connection.Command(string.Empty, w.Transaction); + var list = command.AddList("m", chunk); + + // Converted from the old bytes: history, its file stays. The queue and the failures take the new + // bytes (a verdict, «AsIs» included, was about the old ones) and are tried again. + command.CommandText = $""" + UPDATE media_conversion SET state = 'Superseded', state_changed_at = @at + WHERE state = 'Converted' AND source_sha256 = @old AND media_id IN ({list}); + UPDATE media_conversion SET state = 'Pending', source_sha256 = @new, last_error = NULL, state_changed_at = @at + WHERE state IN ('Pending', 'Failed') AND source_sha256 = @old AND media_id IN ({list}); + """; + command.With("@at", Sql.Time(at)).With("@old", old).With("@new", now).ExecuteNonQuery(); + } + + return media; + }, + ct); + } + + public Task DeletePendingAsync(ExportFormat format, CancellationToken ct = default) => + db.WriteAsync( + w => w.Command("DELETE FROM media_conversion WHERE state = 'Pending' AND format = @f").With("@f", Sql.Enum(format)).ExecuteNonQuery(), + ct); + + public Task DeletePendingRowAsync(long id, CancellationToken ct = default) => + db.WriteAsync( + w => w.Command("DELETE FROM media_conversion WHERE id = @id AND state = 'Pending'").With("@id", id).ExecuteNonQuery() > 0, + ct); + + public Task CountByStateAsync(CancellationToken ct = default) => + db.ReadAsync( + c => + { + using var command = c.Command($""" + SELECT state, CASE WHEN state = 'Failed' AND {AsIsCondition} THEN 1 ELSE 0 END, COUNT(*) + FROM media_conversion GROUP BY 1, 2 + """); + using var r = command.ExecuteReader(); + int pending = 0, converted = 0, failed = 0, asIs = 0, superseded = 0, removed = 0; + while (r.Read()) + { + var n = (int)r.GetInt64(2); + switch (r.GetString(0)) + { + case "Pending": + pending += n; + break; + case "Converted": + converted += n; + break; + case "Failed" when r.GetInt64(1) == 1: + asIs += n; + break; + case "Failed": + failed += n; + break; + case "Superseded": + superseded += n; + break; + case "Removed": + removed += n; + break; + } + } + + return new MediaConversionCounts(pending, converted, failed, asIs, superseded, removed); + }, + ct); + + public Task EnqueueAsync(IReadOnlyList requests, DateTimeOffset at, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(requests); + if (requests.Count == 0) + { + return Task.FromResult(0); + } + + var valid = requests.Select(r => + { + ArgumentNullException.ThrowIfNull(r); + if (r.Format == ExportFormat.Original) + { + throw new ArgumentException("Un file convertito ha un formato diverso dall'originale.", nameof(requests)); + } + + return r with { SourceSha256 = ExportValues.Sha(r.SourceSha256, nameof(r.SourceSha256)) }; + }).ToList(); + return db.WriteAsync( + w => + { + var added = 0; + foreach (var r in valid) + { + // A current row (Pending, Converted, or Failed, which holds the slot) is left as it is. + added += w.Command(""" + INSERT INTO media_conversion (media_id, format, state, source_sha256, created_at) + SELECT @m, @f, 'Pending', @s, @at WHERE EXISTS (SELECT 1 FROM media WHERE id = @m) + ON CONFLICT DO NOTHING + """).With("@m", r.MediaId).With("@f", Sql.Enum(r.Format)).With("@s", r.SourceSha256).With("@at", Sql.Time(at)).ExecuteNonQuery(); + } + + return added; + }, + ct); + } + + /// The present files of a kind that convert into , as a condition on the alias m. + private static string ExistingCondition(SqliteCommand command, MediaKind kind, ExportFormat format) + { + var excluded = LibraryConversionRules.ExcludedExtensions(format); + var sql = new StringBuilder($"m.kind = @k AND {PresentMedia}"); + command.With("@k", Sql.Enum(kind)); + for (var i = 0; i < excluded.Count; i++) + { + // LIKE compares ASCII letters without case, as the extension rule does. + sql.Append(CultureInfo.InvariantCulture, $" AND m.relative_path NOT LIKE @x{i}"); + command.With(string.Create(CultureInfo.InvariantCulture, $"@x{i}"), "%" + excluded[i]); + } + + return sql.ToString(); + } + + private static List<(MediaKind Kind, ExportFormat Format)> Kinds(ExportFormat? photo, ExportFormat? video) + { + var kinds = new List<(MediaKind, ExportFormat)>(); + if (photo is { } p && p != ExportFormat.Original) + { + if (!ExportFormats.IsPhotoFormat(p)) + { + throw new ArgumentException("Il formato non è adatto alle foto.", nameof(photo)); + } + + kinds.Add((MediaKind.Photo, p)); + } + + if (video is { } v && v != ExportFormat.Original) + { + if (!ExportFormats.IsVideoFormat(v)) + { + throw new ArgumentException("Il formato non è adatto ai video.", nameof(video)); + } + + kinds.Add((MediaKind.Video, v)); + } + + return kinds; + } + + public Task EnqueueExistingAsync(ExportFormat? photo, ExportFormat? video, DateTimeOffset at, CancellationToken ct = default) + { + var kinds = Kinds(photo, video); + if (kinds.Count == 0) + { + return Task.FromResult(0); + } + + return db.WriteAsync( + w => + { + var added = 0; + foreach (var (kind, format) in kinds) + { + using var command = w.Connection.Command(string.Empty, w.Transaction); + var where = ExistingCondition(command, kind, format); + + // One statement; a file with a current row in the format (a Failed one included) keeps it. + command.CommandText = $""" + INSERT INTO media_conversion (media_id, format, state, source_sha256, created_at) + SELECT m.id, @f, 'Pending', m.sha256, @at FROM media m WHERE {where} ORDER BY m.id + ON CONFLICT DO NOTHING + """; + added += command.With("@f", Sql.Enum(format)).With("@at", Sql.Time(at)).ExecuteNonQuery(); + } + + return added; + }, + ct); + } + + public Task<(int Files, long Bytes)> CountExistingAsync(ExportFormat? photo, ExportFormat? video, CancellationToken ct = default) + { + var kinds = Kinds(photo, video); + if (kinds.Count == 0) + { + return Task.FromResult((0, 0L)); + } + + return db.ReadAsync( + c => + { + var files = 0; + long bytes = 0; + foreach (var (kind, format) in kinds) + { + using var command = c.Command(string.Empty); + var where = ExistingCondition(command, kind, format); + command.CommandText = $""" + SELECT COUNT(*), COALESCE(SUM(m.bytes), 0) FROM media m + WHERE {where} AND NOT EXISTS ( + SELECT 1 FROM media_conversion mc WHERE mc.media_id = m.id AND mc.format = @f AND mc.state IN ('Pending', 'Converted', 'Failed')) + """; + command.With("@f", Sql.Enum(format)); + using var r = command.ExecuteReader(); + if (r.Read()) + { + files += (int)r.GetInt64(0); + bytes += r.GetInt64(1); + } + } + + return (files, bytes); + }, + ct); + } + + public Task CommitAsync(MediaConversionCommit commit, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(commit); + ArgumentException.ThrowIfNullOrWhiteSpace(commit.RelativePath); + ArgumentOutOfRangeException.ThrowIfNegative(commit.Bytes); + if (commit.Format == ExportFormat.Original) + { + throw new ArgumentException("Un file convertito ha un formato diverso dall'originale.", nameof(commit)); + } + + var source = ExportValues.Sha(commit.SourceSha256, nameof(commit.SourceSha256)); + var sha = ExportValues.Sha(commit.Sha256, nameof(commit.Sha256)); + return db.WriteAsync(w => Commit(w, commit, source, sha), ct); + } + + private static MediaConversionCommitOutcome Commit(WriteContext w, MediaConversionCommit commit, string source, string sha) + { + SqliteCommand Bind(SqliteCommand c) => + c.With("@m", commit.MediaId).With("@f", Sql.Enum(commit.Format)).With("@s", source).With("@p", commit.RelativePath) + .With("@b", commit.Bytes).With("@h", sha).With("@at", Sql.Time(commit.At)).With("@e", Sql.Text(commit.Notes)); + + var recorded = Bind(w.Command($""" + UPDATE media_conversion SET state = 'Converted', relative_path = @p, bytes = @b, sha256 = @h, converted_at = @at, + state_changed_at = @at, last_error = @e + WHERE id = @id AND media_id = @m AND format = @f AND state = 'Pending' AND source_sha256 = @s + AND EXISTS (SELECT 1 FROM media m WHERE m.id = @m AND m.sha256 = @s AND {PresentMedia}) + """)).With("@id", commit.ConversionId).ExecuteNonQuery(); + if (recorded == 1) + { + return MediaConversionCommitOutcome.Recorded; + } + + var present = w.Command($"SELECT COUNT(*) FROM media m WHERE m.id = @m AND m.sha256 = @s AND {PresentMedia}") + .With("@m", commit.MediaId).With("@s", source).ScalarInt64() > 0; + if (!present) + { + return MediaConversionCommitOutcome.SourceGone; + } + + long? currentId = null; + string? currentState = null; + using (var r = w.Command("SELECT id, state FROM media_conversion WHERE media_id = @m AND format = @f AND state IN ('Pending', 'Converted', 'Failed')") + .With("@m", commit.MediaId).With("@f", Sql.Enum(commit.Format)).ExecuteReader()) + { + if (r.Read()) + { + currentId = r.GetInt64(0); + currentState = r.GetString(1); + } + } + + if (currentState == "Converted") + { + return MediaConversionCommitOutcome.SlotTaken; + } + + if (currentId is { } id) + { + Bind(w.Command(""" + UPDATE media_conversion SET state = 'Converted', source_sha256 = @s, relative_path = @p, bytes = @b, sha256 = @h, + converted_at = @at, state_changed_at = @at, last_error = @e + WHERE id = @id AND media_id = @m AND format = @f + """)).With("@id", id).ExecuteNonQuery(); + return MediaConversionCommitOutcome.Upserted; + } + + // The row went (the setting was turned off meanwhile): the file just written stays recorded. + Bind(w.Command(""" + INSERT INTO media_conversion (media_id, format, state, source_sha256, relative_path, bytes, sha256, created_at, converted_at, + state_changed_at, last_error) + VALUES (@m, @f, 'Converted', @s, @p, @b, @h, @at, @at, @at, @e) + """)).ExecuteNonQuery(); + return MediaConversionCommitOutcome.Upserted; + } + + public Task ResetFailedAsync(DateTimeOffset at, CancellationToken ct = default) => + db.WriteAsync( + w => w.Command($""" + UPDATE media_conversion SET state = 'Pending', last_error = NULL, state_changed_at = @at + WHERE state = 'Failed' AND (last_error IS NULL OR NOT ({AsIsCondition})) + """).With("@at", Sql.Time(at)).ExecuteNonQuery(), + ct); +} diff --git a/src/Febe.Data/Stores/MediaConversionStore.cs b/src/Febe.Data/Stores/MediaConversionStore.cs index 6517cdf..fd6df02 100644 --- a/src/Febe.Data/Stores/MediaConversionStore.cs +++ b/src/Febe.Data/Stores/MediaConversionStore.cs @@ -4,7 +4,7 @@ using Microsoft.Data.Sqlite; namespace Febe.Data.Stores; -internal sealed class MediaConversionStore(FebeDatabase db) : IMediaConversionStore +internal sealed partial class MediaConversionStore(FebeDatabase db) : IMediaConversionStore { private const string Columns = "id, media_id, format, state, source_sha256, relative_path, bytes, sha256, created_at, converted_at, state_changed_at, last_error"; diff --git a/tests/Febe.Tests/Data/ExportConstraintTests.cs b/tests/Febe.Tests/Data/ExportConstraintTests.cs index 542e81c..9ee2ea1 100644 --- a/tests/Febe.Tests/Data/ExportConstraintTests.cs +++ b/tests/Febe.Tests/Data/ExportConstraintTests.cs @@ -342,15 +342,21 @@ public sealed class ExportConstraintTests var w = await CreateAsync(db); await InsertAsync(db, "export_copy", w.CopyRow()); await InsertAsync(db, "export_run", w.RunRow(("destination_id", w.Own))); - var conversion = await InsertAsync(db, "media_conversion", w.ConversionRow()); + // A conversion with its file: RemoveAsync drops only the rows without one (Pending, Failed, Removed, tappa E3 WP2). + var conversion = await InsertAsync( + db, + "media_conversion", + w.ConversionRow(("state", "Converted"), ("relative_path", "marta.demo/x.jpg"), ("bytes", 1L), ("sha256", Make.Sha(2)), ("converted_at", 0L))); var withCopy = await Assert.ThrowsExactlyAsync(() => ExecuteAsync(db, "DELETE FROM export_destination WHERE id = @id", ("@id", w.General))); Assert.AreEqual(19, withCopy.SqliteErrorCode, "una destinazione con copie si ritira, non si cancella"); var withRun = await Assert.ThrowsExactlyAsync(() => ExecuteAsync(db, "DELETE FROM export_destination WHERE id = @id", ("@id", w.Own))); Assert.AreEqual(19, withRun.SqliteErrorCode, "una destinazione con lavori si ritira, non si cancella"); - var entry = await Assert.ThrowsExactlyAsync(() => db.Entries.RemoveAsync(w.MartaEntry)); - Assert.AreEqual(19, entry.SqliteErrorCode, "un file con un convertito registrato non si cancella"); + var raw = await Assert.ThrowsExactlyAsync(() => ExecuteAsync(db, "DELETE FROM entry WHERE id = @id", ("@id", w.MartaEntry))); + Assert.AreEqual(19, raw.SqliteErrorCode, "un file con un convertito registrato non si cancella"); + var entry = await Assert.ThrowsExactlyAsync(() => db.Entries.RemoveAsync(w.MartaEntry)); + Assert.AreEqual(19, Assert.IsInstanceOfType(entry.InnerException).SqliteErrorCode, "nemmeno attraverso il magazzino"); Assert.IsNotNull(await db.Entries.GetAsync(w.MartaEntry)); Assert.IsNotNull(await db.Media.GetAsync(w.MartaMedia)); Assert.IsNotNull(await db.Conversions.GetAsync(conversion)); diff --git a/tests/Febe.Tests/Export/ExportFoundationTests.cs b/tests/Febe.Tests/Export/ExportFoundationTests.cs index 7c0bd10..73672f1 100644 --- a/tests/Febe.Tests/Export/ExportFoundationTests.cs +++ b/tests/Febe.Tests/Export/ExportFoundationTests.cs @@ -37,6 +37,79 @@ public sealed class ExportFoundationTests rebuild.Dispose(); } + [TestMethod] + public void AForegroundLeasePreemptsTheBackgroundOneAndBusyIgnoresIt() + { + var gate = new LongWorkGate(); + Assert.IsTrue(gate.TryEnterBackground(out var background)); + Assert.IsNull(gate.Busy, "Busy ignores the background lease"); + Assert.IsTrue(gate.BackgroundRunning); + Assert.IsFalse(gate.TryEnterBackground(out _)); + + Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var import, out _)); + Assert.IsTrue(background.Preempted.IsCancellationRequested); + Assert.IsTrue(background.IsPreempted); + Assert.IsFalse(background.TryBeginCommit(out _), "no commit once pre-empted"); + Assert.IsFalse(gate.BackgroundRunning); + Assert.AreEqual(LongWorkKind.Import, gate.Busy); + background.Dispose(); + + Assert.IsFalse(gate.TryEnterBackground(out _), "the background waits for the foreground"); + import.Dispose(); + Assert.IsTrue(gate.TryEnterBackground(out var again)); + again.Dispose(); + Assert.IsFalse(gate.BackgroundRunning); + Assert.IsTrue(gate.TryEnter(LongWorkKind.Export, out var export, out _)); + export.Dispose(); + } + + [TestMethod] + public async Task AForegroundLeaseWaitsForACommit() + { + var gate = new LongWorkGate(); + Assert.IsTrue(gate.TryEnterBackground(out var background)); + Assert.IsTrue(background.TryBeginCommit(out var commit)); + var entering = Task.Run(() => gate.TryEnter(LongWorkKind.Rebuild, out var lease, out _) ? lease : null, TestContext.CancellationToken); + while (!background.Preempted.IsCancellationRequested) + { + await Task.Yield(); + } + + Assert.IsFalse(entering.IsCompleted, "the rebuild waits for the commit"); + commit.Dispose(); + var rebuild = await entering; + Assert.IsNotNull(rebuild); + rebuild.Dispose(); + background.Dispose(); + + // A commit that does not end in time: the foreground job is refused with its own message. + var quick = new LongWorkGate { CommitWait = TimeSpan.FromMilliseconds(20) }; + Assert.IsTrue(quick.TryEnterBackground(out var slow)); + Assert.IsTrue(slow.TryBeginCommit(out var held)); + Assert.IsFalse(quick.TryEnter(LongWorkKind.Export, out _, out var busy)); + Assert.AreEqual(LongWorkKind.LibraryConversion, busy); + Assert.IsNull(quick.Busy); + held.Dispose(); + slow.Dispose(); + } + + [TestMethod] + public void NewKindsHaveTheirOwnMessages() + { + Assert.AreEqual( + "La conversione della libreria sta salvando un file: riprova fra un attimo.", + LongWorkGate.BusyMessage(LongWorkKind.Import, LongWorkKind.LibraryConversion)); + Assert.AreEqual( + "Si sta preparando uno zip di fotogrammi: aspetta che finisca, poi importa.", + LongWorkGate.BusyMessage(LongWorkKind.Import, LongWorkKind.FrameDownload)); + Assert.AreEqual( + "C'è un'importazione al lavoro: aspetta che finisca o interrompila, poi scarica i fotogrammi.", + LongWorkGate.BusyMessage(LongWorkKind.FrameDownload, LongWorkKind.Import)); + Assert.AreEqual( + "La ricostruzione del database è in corso: aspetta che finisca.", + LongWorkGate.BusyMessage(LongWorkKind.FrameDownload, LongWorkKind.Rebuild)); + } + [TestMethod] public async Task AnImportDoesNotStartWhileTheGateIsHeld() { diff --git a/tests/Febe.Tests/Library/LibraryConversionTests.cs b/tests/Febe.Tests/Library/LibraryConversionTests.cs new file mode 100644 index 0000000..46fe864 --- /dev/null +++ b/tests/Febe.Tests/Library/LibraryConversionTests.cs @@ -0,0 +1,448 @@ +using System.Security.Cryptography; +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Library; +using Febe.Core.Library.Conversion; +using Febe.Tests.Alerts.Support; +using Febe.Tests.Export.Support; +using Febe.Tests.Import.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Library; + +/// +/// The conversion for the library (tappa E3, WP2): the queue, the worker and the hooks that keep the +/// media_conversion rows true. The images are built by the tests. +/// +[TestClass] +public sealed class LibraryConversionTests +{ + private static readonly byte[] JpegSignature = [0xFF, 0xD8, 0xFF]; + + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task TheConvertedFileIsAddedAndTheOriginalStays() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 11); + var media = entry.Media[0]; + var original = library.Layout.FullPath(account, media.RelativePath!); + var before = await File.ReadAllBytesAsync(original, ct); + var journalBefore = await File.ReadAllTextAsync(AccountJournal.PathFor(library.Layout.AccountFolder(account)), ct); + + var queued = await library.Db.Conversions.ListPendingAsync(ct: ct); + Assert.HasCount(1, queued, "a new file enters the queue after its journal line"); + var pass = await Worker(library).RunOnceAsync(ct); + Assert.AreEqual(1, pass.Converted); + + var row = (await library.Db.Conversions.ListByMediaAsync(media.Id, ct)).Single(); + Assert.AreEqual((MediaConversionState.Converted, ExportFormat.Jpg, media.Sha256), (row.State, row.Format, row.SourceSha256)); + Assert.AreEqual(Path.ChangeExtension(media.RelativePath!, ".jpg"), row.RelativePath); + var converted = await File.ReadAllBytesAsync(library.Layout.FullPath(account, row.RelativePath!), ct); + CollectionAssert.AreEqual(JpegSignature, converted[..3]); + Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(converted)), row.Sha256); + Assert.AreEqual(converted.Length, row.Bytes); + + // The original, its record and its journal line are untouched. + CollectionAssert.AreEqual(before, await File.ReadAllBytesAsync(original, ct)); + var stored = (await library.Db.Media.GetAsync(media.Id, ct))!; + Assert.AreEqual((media.Sha256, media.RelativePath, media.PerceptualHash, media.HasThumbnail), (stored.Sha256, stored.RelativePath, stored.PerceptualHash, stored.HasThumbnail)); + Assert.AreEqual(journalBefore, await File.ReadAllTextAsync(AccountJournal.PathFor(library.Layout.AccountFolder(account)), ct)); + + var status = await Worker(library).StatusAsync(ct); + Assert.AreEqual((0, 1, 0, 0, false), (status.Pending, status.Converted, status.Failed, status.AsIs, status.Paused)); + } + + [TestMethod] + public async Task OnlyNewFilesByDefaultAndExistingOnesWhenAsked() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await SavePngAsync(library, "1", 12); + var (_, jpg) = await SaveAsync(library, "2", new TestFile(Make.Photo(1), TestFile.PhotoBytes(13, 64, 48), ".jpg")); + await SaveAsync(library, "3", new TestFile(Make.Photo(1), [1, 2, 3, 4], ".heic")); + + var settings = await TurnOnAsync(library, ExportFormat.Jpg); + Assert.IsEmpty(await library.Db.Conversions.ListPendingAsync(ct: ct), "turning it on queues nothing by itself"); + + var queue = new LibraryConversionQueue(library.Db, library.Clock); + var preview = await queue.PreviewExistingAsync(settings, ct); + Assert.AreEqual(1, preview.Files, "only the PNG: a JPG is already in the format, a HEIC is never converted"); + Assert.IsGreaterThan(0L, preview.Bytes); + Assert.AreEqual(1, await queue.EnqueueExistingAsync(settings, ct)); + Assert.AreEqual(0, await queue.EnqueueExistingAsync(settings, ct), "nothing is queued twice"); + Assert.AreEqual(0, (await queue.PreviewExistingAsync(settings, ct)).Files); + Assert.IsEmpty(await library.Db.Conversions.ListByMediaAsync(jpg.Media[0].Id, ct)); + } + + [TestMethod] + public async Task TurningOffDropsThePendingRowsAndKeepsTheConvertedOnes() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var on = await TurnOnAsync(library, ExportFormat.Jpg); + var (account, first) = await SavePngAsync(library, "1", 14); + await Worker(library).RunOnceAsync(ct); + await SavePngAsync(library, "2", 15); + Assert.HasCount(1, await library.Db.Conversions.ListPendingAsync(ct: ct)); + + var off = on with { LibraryPhotoFormat = ExportFormat.Original }; + await off.SaveAsync(library.Db.Settings, ct); + await new LibraryConversionQueue(library.Db, library.Clock).OnSettingsChangedAsync(on, off, ct); + + Assert.IsEmpty(await library.Db.Conversions.ListPendingAsync(ct: ct)); + var kept = (await library.Db.Conversions.ListByMediaAsync(first.Media[0].Id, ct)).Single(); + Assert.AreEqual(MediaConversionState.Converted, kept.State); + Assert.IsTrue(File.Exists(library.Layout.FullPath(account, kept.RelativePath!)), "the converted file stays"); + } + + [TestMethod] + public async Task AFileAlreadyInTheFormatByItsBytesDropsTheRow() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SaveAsync(library, "1", new TestFile(Make.Photo(1), TestFile.PhotoBytes(16, 64, 48), ".png")); + Assert.HasCount(1, await library.Db.Conversions.ListPendingAsync(ct: ct), "by its name it converts"); + + var pass = await Worker(library).RunOnceAsync(ct); + + Assert.AreEqual((0, 1), (pass.Converted, pass.Done)); + Assert.IsEmpty(await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct), "a JPEG named .png is already a JPG: nothing to add"); + Assert.HasCount(1, Directory.GetFiles(library.Layout.AccountFolder(account), "*.*", SearchOption.AllDirectories).Where(f => !f.EndsWith(AccountJournal.FileName, StringComparison.Ordinal))); + } + + [TestMethod] + public async Task AnUndecodableImageIsTerminalAndNotRetried() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (_, entry) = await SaveAsync(library, "1", new TestFile(Make.Photo(1), [.. Enumerable.Range(0, 400).Select(i => (byte)(i * 7))], ".bmp")); + + await Worker(library).RunOnceAsync(ct); + + var row = (await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)).Single(); + Assert.AreEqual((MediaConversionState.Failed, "AsIsNotDecodable"), (row.State, row.LastError)); + Assert.StartsWith("Non si converte", LibraryConversionText.Note(row.LastError)!); + Assert.AreEqual(0, await new LibraryConversionQueue(library.Db, library.Clock).RetryFailedAsync(ct), "«Riprova» skips what never converts"); + var counts = await library.Db.Conversions.CountByStateAsync(ct); + Assert.AreEqual((0, 1), (counts.Failed, counts.AsIs)); + } + + [TestMethod] + public async Task AMissingOriginalSaysSoAndIsRetriedOnRequest() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 17); + var path = library.Layout.FullPath(account, entry.Media[0].RelativePath!); + var bytes = await File.ReadAllBytesAsync(path, ct); + File.Delete(path); + + await Worker(library).RunOnceAsync(ct); + var row = (await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)).Single(); + Assert.AreEqual((MediaConversionState.Failed, LibraryConversionText.SourceMissing), (row.State, row.LastError)); + Assert.AreEqual("File non presente in libreria", LibraryConversionText.Note(row.LastError)); + + await File.WriteAllBytesAsync(path, bytes, ct); + Assert.AreEqual(1, await new LibraryConversionQueue(library.Db, library.Clock).RetryFailedAsync(ct)); + Assert.AreEqual(1, (await Worker(library).RunOnceAsync(ct)).Converted); + } + + [TestMethod] + public async Task ATakenNameGetsAFreeOneAndAFileFoundAgainIsAdopted() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 18); + var media = entry.Media[0]; + var taken = library.Layout.FullPath(account, Path.ChangeExtension(media.RelativePath!, ".jpg")); + await File.WriteAllBytesAsync(taken, [9, 9, 9], ct); + + await Worker(library).RunOnceAsync(ct); + var row = (await library.Db.Conversions.ListByMediaAsync(media.Id, ct)).Single(); + Assert.EndsWith(" (2).jpg", row.RelativePath!, "never overwritten"); + CollectionAssert.AreEqual(new byte[] { 9, 9, 9 }, await File.ReadAllBytesAsync(taken, ct)); + + // The record is lost (a «Tolto» row is history): queued again, the file on disk with its SHA-256 is adopted. + await library.Db.Conversions.MarkRemovedAsync([row.Id], library.Clock.Now, ct); + await library.Db.Conversions.EnqueueAsync([new(media.Id, ExportFormat.Jpg, media.Sha256!)], library.Clock.Now, ct); + await Worker(library).RunOnceAsync(ct); + var again = (await library.Db.Conversions.ListByMediaAsync(media.Id, ct)).Single(r => r.State == MediaConversionState.Converted); + Assert.AreEqual((row.RelativePath, row.Sha256), (again.RelativePath, again.Sha256)); + Assert.IsFalse(File.Exists(library.Layout.FullPath(account, Path.ChangeExtension(media.RelativePath!, null) + " (3).jpg"))); + } + + [TestMethod] + public async Task AnImportPreemptsTheConversion() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 19); + var gate = new LongWorkGate(); + var throttle = new ConversionThrottle(); + + // The photo waits for the throttle (another conversion): meanwhile an import takes the gate. + var busy = new TaskCompletionSource(); + var release = new TaskCompletionSource(); + var other = throttle.RunAsync(_ => + { + busy.SetResult(); + release.Task.Wait(ct); + return 0; + }, ct); + await busy.Task; + var pass = Worker(library, gate, throttle).RunOnceAsync(ct); + while (!gate.BackgroundRunning) + { + await Task.Yield(); + } + + Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var import, out _), "the import starts at once"); + release.SetResult(); + await other; + var result = await pass; + + Assert.IsTrue(result.Again); + Assert.AreEqual(MediaConversionState.Pending, (await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)).Single().State); + Assert.IsEmpty(Directory.GetFiles(library.Layout.AccountFolder(account), "*.jpg", SearchOption.AllDirectories)); + Assert.IsEmpty(Directory.GetFiles(library.Layout.AccountFolder(account), SafeFileWriter.TempPrefix + "*", SearchOption.AllDirectories)); + + Assert.IsTrue((await Worker(library, gate, throttle).RunOnceAsync(ct)).Again, "no conversion while the import runs"); + import.Dispose(); + Assert.AreEqual(1, (await Worker(library, gate, throttle).RunOnceAsync(ct)).Converted, "it resumes after"); + } + + [TestMethod] + public async Task ADeletionDuringTheWriteLeavesNothingUnrecorded() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 20); + var deletion = new LibraryDeletion(library.Db, library.Layout, library.Journal, library.Clock, library.Thumbnails, library.Index); + var worker = new LibraryConversionWorker(Environment(library) with + { + AfterWrite = async (_, _) => await deletion.DeleteAsync(entry.Entry.Id), + }); + + var pass = await worker.RunOnceAsync(ct); + + Assert.AreEqual(0, pass.Converted); + Assert.IsEmpty(await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)); + Assert.IsEmpty(Directory.GetFiles(library.Layout.AccountFolder(account), "*.jpg", SearchOption.AllDirectories), "our own file went"); + } + + [TestMethod] + public async Task NoConversionDuringAnEngineSessionNorWhenPausedOrLowOnSpace() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 21); + var session = new FakeSessionState { InSession = true }; + var space = new FakeFreeSpaceProbe(); + var worker = new LibraryConversionWorker(Environment(library) with { Session = session, FreeSpace = space }); + + Assert.IsTrue((await worker.RunOnceAsync(ct)).Again); + Assert.AreEqual(LibraryConversionText.InSession, (await worker.StatusAsync(ct)).Waiting); + session.InSession = false; + + var queue = new LibraryConversionQueue(library.Db, library.Clock); + await queue.SetPausedAsync(true, ct); + Assert.AreEqual(0, (await worker.RunOnceAsync(ct)).Done); + Assert.IsTrue((await worker.StatusAsync(ct)).Paused); + await queue.SetPausedAsync(false, ct); + + space.Set(library.Layout.AccountFolder(account), 1024, 2 * FakeFreeSpaceProbe.GB); + Assert.AreEqual(0, (await worker.RunOnceAsync(ct)).Done); + Assert.AreEqual(LibraryConversionText.LowSpace, (await worker.StatusAsync(ct)).Waiting); + Assert.AreEqual(MediaConversionState.Pending, (await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)).Single().State); + } + + [TestMethod] + public async Task AnUnpluggedAccountFolderIsNotCreated() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 22); + var folder = library.Layout.AccountFolder(account); + Directory.Move(folder, folder + "-staccato"); + + await Worker(library).RunOnceAsync(ct); + + Assert.IsFalse(Directory.Exists(folder)); + Assert.AreEqual(LibraryConversionText.AccountFolderMissing, (await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)).Single().LastError); + } + + [TestMethod] + public async Task DeletionRemembersOrRemovesTheRowsAndTheirFiles() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, kept) = await SavePngAsync(library, "1", 23); + var (_, gone) = await SavePngAsync(library, "2", 24); + await Worker(library).RunOnceAsync(ct); + var keptRow = (await library.Db.Conversions.ListByMediaAsync(kept.Media[0].Id, ct)).Single(); + var goneRow = (await library.Db.Conversions.ListByMediaAsync(gone.Media[0].Id, ct)).Single(); + var deletion = new LibraryDeletion(library.Db, library.Layout, library.Journal, library.Clock, library.Thumbnails, library.Index); + + var remembered = await deletion.DeleteAsync(kept.Entry.Id, DeletionMode.Remember, ct); + Assert.IsTrue(remembered.Complete); + Assert.AreEqual(1, remembered.ConvertedFiles); + Assert.Contains(keptRow.RelativePath!, remembered.DeletedFiles); + Assert.IsFalse(File.Exists(library.Layout.FullPath(account, keptRow.RelativePath!))); + Assert.AreEqual(MediaConversionState.Removed, (await library.Db.Conversions.GetAsync(keptRow.Id, ct))!.State); + + // A strict removal refuses an entry with converted files: their record would be lost. + await Assert.ThrowsExactlyAsync(() => library.Db.Entries.RemoveAsync(gone.Entry.Id, ct)); + var removed = await deletion.DeleteAsync(gone.Entry.Id, DeletionMode.AllowReturn, ct); + Assert.AreEqual(1, removed.ConvertedFiles); + Assert.IsNull(await library.Db.Conversions.GetAsync(goneRow.Id, ct)); + Assert.IsNull(await library.Db.Entries.GetAsync(gone.Entry.Id, ct)); + Assert.IsFalse(File.Exists(library.Layout.FullPath(account, goneRow.RelativePath!))); + } + + [TestMethod] + public async Task ADeletionKeepsAReplacedConvertedFile() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 25); + await Worker(library).RunOnceAsync(ct); + var row = (await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)).Single(); + var path = library.Layout.FullPath(account, row.RelativePath!); + await File.WriteAllBytesAsync(path, [1, 2, 3], ct); + + var result = await new LibraryDeletion(library.Db, library.Layout, library.Journal, library.Clock).DeleteAsync(entry.Entry.Id, ct: ct); + + Assert.IsTrue(File.Exists(path)); + Assert.HasCount(1, result.FailedFiles); + Assert.Contains("cambiato dopo la conversione", result.FailedFiles[0]); + } + + [TestMethod] + public async Task AChangedOriginalSupersedesItsConversionAndQueuesTheNewBytes() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 26); + await Worker(library).RunOnceAsync(ct); + var media = entry.Media[0]; + var newSha = new string('a', 64); + await library.Db.Media.UpdateAsync((await library.Db.Media.GetAsync(media.Id, ct))! with { Sha256 = newSha }, ct); + + await ExportSupersession.FileChangedAsync(library.Db, account.Id, media.Sha256, newSha, library.Clock.Now, ct); + + var rows = await library.Db.Conversions.ListByMediaAsync(media.Id, ct); + Assert.AreEqual(MediaConversionState.Superseded, rows[0].State); + Assert.IsTrue(File.Exists(library.Layout.FullPath(account, rows[0].RelativePath!)), "the superseded file stays"); + Assert.AreEqual((MediaConversionState.Pending, newSha), (rows[1].State, rows[1].SourceSha256)); + } + + [TestMethod] + public async Task RebuildCountsConvertedFilesWithoutConvertingAndTheWorkerAdoptsThem() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 27); + await Worker(library).RunOnceAsync(ct); + var row = (await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)).Single(); + + await library.LoseDatabaseAsync(); + await TurnOnAsync(library, ExportFormat.Jpg); + var report = await new LibraryRebuilder(library.Db, library.Layout, library.Clock).RebuildAsync(ct: ct); + + Assert.AreEqual((1, 0), (report.ConversionsFound, report.UntrackedFiles), "a converted file is not an unknown file"); + var pending = (await library.Db.Conversions.ListPendingAsync(ct: ct)).Single(); + Assert.AreEqual(ExportFormat.Jpg, pending.Format); + var files = Directory.GetFiles(library.Layout.AccountFolder(account), "*.jpg", SearchOption.AllDirectories); + Assert.HasCount(1, files, "the rebuild converts nothing"); + + await Worker(library).RunOnceAsync(ct); + var adopted = (await library.Db.Conversions.GetAsync(pending.Id, ct))!; + Assert.AreEqual((MediaConversionState.Converted, row.RelativePath, row.Sha256), (adopted.State, adopted.RelativePath, adopted.Sha256)); + Assert.HasCount(1, Directory.GetFiles(library.Layout.AccountFolder(account), "*.jpg", SearchOption.AllDirectories)); + } + + [TestMethod] + public async Task ImportingAConvertedFileSaysItIsInTheLibrary() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + await TurnOnAsync(bed.Library, ExportFormat.Png); + var (account, saved) = await bed.AccountWithPhotoAsync("luca.demo", "500", TestFile.PhotoBytes(28, 64, 48)); + await Worker(bed.Library).RunOnceAsync(ct); + var row = (await bed.Library.Db.Conversions.ListByMediaAsync(saved.Media[0].Id, ct)).Single(); + bed.Write("luca.demo/convertita.png", await File.ReadAllBytesAsync(bed.Library.Layout.FullPath(account, row.RelativePath!), ct)); + + var run = await bed.AnalyzeAsync(); + + var file = await bed.FileAsync(run.Id, "luca.demo/convertita.png"); + Assert.AreEqual((ImportOutcome.AlreadyInLibrary, saved.Media[0].Id), (file.Outcome, file.MatchedMediaId)); + Assert.AreEqual("È una copia convertita (o un fotogramma) di un file già in libreria.", file.LastError); + Assert.AreEqual(0, await bed.Library.Db.Duplicates.CountPendingAsync(DuplicateOrigin.Import, ct), "never a probable duplicate of its original"); + } + + private static LibraryConversionEnvironment Environment(TestLibrary library, LongWorkGate? gate = null, ConversionThrottle? throttle = null) => new() + { + Storage = library.Db, + Layout = () => library.Layout, + Clock = library.Clock, + Gate = gate, + Throttle = throttle ?? new ConversionThrottle(), + FreeSpace = new FakeFreeSpaceProbe(), + }; + + private static LibraryConversionWorker Worker(TestLibrary library, LongWorkGate? gate = null, ConversionThrottle? throttle = null) => + new(Environment(library, gate, throttle)); + + private static async Task TurnOnAsync(TestLibrary library, ExportFormat photo) + { + var settings = ExportSettings.Default with { LibraryPhotoFormat = photo }; + await settings.SaveAsync(library.Db.Settings); + return settings; + } + + private static Task<(Account Account, EntryWithMedia Entry)> SavePngAsync(TestLibrary library, string id, int scene) + { + using var image = TestImages.Scene(scene, 64, 48); + return SaveAsync(library, id, new TestFile(Make.Photo(1), TestImages.Png(image), ".png")); + } + + private static async Task<(Account Account, EntryWithMedia Entry)> SaveAsync(TestLibrary library, string id, TestFile file) + { + var account = await library.Db.Accounts.FindByUsernameAsync("marta.demo") ?? await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100")); + var entry = await library.SaveAsync(account, Make.Entry(account.Id, id, Make.T0.AddMinutes(int.Parse(id, System.Globalization.CultureInfo.InvariantCulture))), [file]); + return (account, entry); + } +}