From a112c928934c4f0ec293bcfe6cf476562177917f Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Fri, 27 Nov 2026 10:55:29 +0100 Subject: [PATCH] E2: motore delle copie esterne (porta, destinazioni, piano, copia) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Prima metà della tappa E2 «Copie esterne» (#58), parte Core e Data: - porta del lavoro lungo: importazione, copia e ricostruzione mai insieme; - radice /esporta in Docker con mountinfo, controllo delle cartelle con il file di prova, destinazioni con «Esporta questo account» acceso se Alberto non ha mai scelto (decisione del 27/11/2026); - filtro «Copie», segni delle tessere e conteggi dell'account sui soli file dovuti (D3); - percorsi «Come la libreria», segmento dell'account nella cartella generale, 240 caratteri, storia in evidenza; - piano di «Copia in…», un lavoro per destinazione, copia in .part con SHA-256 riletto dal disco, nome libero, mai sovrascrivere, adozione per percorso, pausa della destinazione su prova, spazio e FAT32, attesa fuori dalle sessioni del motore, ripresa e recupero; - .part rimossi solo nelle cartelle degli elementi di lavori non finiti; - «Tolto» e «Superato» (agganci in importazione, scaricamenti, doppioni e ricostruzione), mai ricopiati da soli; - rapporti e testi in italiano, prove del lavoro di copia. Interfaccia, API e composizione restano alla parte successiva. Co-Authored-By: Claude Opus 5.5 --- src/Febe.App/FebeApp.cs | 8 + src/Febe.Core/Abstractions/LongWorkGate.cs | 106 +++ src/Febe.Core/Export/EngineSessionState.cs | 29 + src/Febe.Core/Export/ExportAccounts.cs | 31 + src/Febe.Core/Export/ExportCopier.cs | 672 ++++++++++++++++++ src/Febe.Core/Export/ExportDestinations.cs | 387 ++++++++++ src/Febe.Core/Export/ExportDisk.cs | 82 +++ src/Febe.Core/Export/ExportEnvironment.cs | 144 ++++ src/Febe.Core/Export/ExportFolderCheck.cs | 389 ++++++++++ src/Febe.Core/Export/ExportLeftovers.cs | 89 +++ src/Febe.Core/Export/ExportModels.cs | 114 +++ src/Febe.Core/Export/ExportNamingPreview.cs | 35 + src/Febe.Core/Export/ExportPaths.cs | 145 ++++ src/Febe.Core/Export/ExportPause.cs | 70 ++ src/Febe.Core/Export/ExportPlanner.cs | 238 +++++++ src/Febe.Core/Export/ExportReports.cs | 106 +++ src/Febe.Core/Export/ExportRoot.cs | 269 +++++++ src/Febe.Core/Export/ExportRunSettings.cs | 26 + src/Febe.Core/Export/ExportService.cs | 642 +++++++++++++++++ src/Febe.Core/Export/ExportSupersession.cs | 36 + src/Febe.Core/Export/ExportText.cs | 138 ++++ src/Febe.Core/Import/ImportCopier.cs | 4 + src/Febe.Core/Import/ImportEnvironment.cs | 6 + src/Febe.Core/Import/ImportService.cs | 17 + .../Library/DownloadDuplicateReview.cs | 6 + src/Febe.Core/Library/LibraryIngest.cs | 5 + src/Febe.Core/Library/LibraryRebuilder.cs | 13 + src/Febe.Core/Library/MountInfo.cs | 114 +++ src/Febe.Core/Library/SafeFileWriter.cs | 58 ++ src/Febe.Core/Storage/IExportStore.cs | 85 +++ src/Febe.Core/Storage/LibraryQueries.cs | 19 + src/Febe.Data/Stores/EntryStore.cs | 57 +- src/Febe.Data/Stores/ExportFilterSql.cs | 225 ++++++ src/Febe.Data/Stores/ExportStore.cs | 327 +++++++++ src/Febe.Web/Api/SettingsApi.cs | 8 +- src/Febe.Web/FebeWeb.cs | 5 +- src/Febe.Web/Import/ImportHub.cs | 10 +- src/Febe.Web/Library/DataFolderServices.cs | 28 +- .../Export/ExportCopiesFilterTests.cs | 124 ++++ tests/Febe.Tests/Export/ExportCopyJobTests.cs | 358 ++++++++++ .../Export/ExportFoundationTests.cs | 172 +++++ 41 files changed, 5370 insertions(+), 27 deletions(-) create mode 100644 src/Febe.Core/Abstractions/LongWorkGate.cs create mode 100644 src/Febe.Core/Export/EngineSessionState.cs create mode 100644 src/Febe.Core/Export/ExportAccounts.cs create mode 100644 src/Febe.Core/Export/ExportCopier.cs create mode 100644 src/Febe.Core/Export/ExportDestinations.cs create mode 100644 src/Febe.Core/Export/ExportDisk.cs create mode 100644 src/Febe.Core/Export/ExportEnvironment.cs create mode 100644 src/Febe.Core/Export/ExportFolderCheck.cs create mode 100644 src/Febe.Core/Export/ExportLeftovers.cs create mode 100644 src/Febe.Core/Export/ExportModels.cs create mode 100644 src/Febe.Core/Export/ExportNamingPreview.cs create mode 100644 src/Febe.Core/Export/ExportPaths.cs create mode 100644 src/Febe.Core/Export/ExportPause.cs create mode 100644 src/Febe.Core/Export/ExportPlanner.cs create mode 100644 src/Febe.Core/Export/ExportReports.cs create mode 100644 src/Febe.Core/Export/ExportRoot.cs create mode 100644 src/Febe.Core/Export/ExportRunSettings.cs create mode 100644 src/Febe.Core/Export/ExportService.cs create mode 100644 src/Febe.Core/Export/ExportSupersession.cs create mode 100644 src/Febe.Core/Export/ExportText.cs create mode 100644 src/Febe.Core/Library/MountInfo.cs create mode 100644 src/Febe.Data/Stores/ExportFilterSql.cs create mode 100644 tests/Febe.Tests/Export/ExportCopiesFilterTests.cs create mode 100644 tests/Febe.Tests/Export/ExportCopyJobTests.cs create mode 100644 tests/Febe.Tests/Export/ExportFoundationTests.cs diff --git a/src/Febe.App/FebeApp.cs b/src/Febe.App/FebeApp.cs index ef7f100..439cbf8 100644 --- a/src/Febe.App/FebeApp.cs +++ b/src/Febe.App/FebeApp.cs @@ -182,6 +182,7 @@ public sealed class FebeApp : IAsyncDisposable // The same services as a normal start, on the empty temporary database, so that every endpoint can be built; // the configuration gate answers 503 before any of them runs. + var longWork = new LongWorkGate(); Import = new ImportService(new ImportEnvironment { Storage = Database, @@ -190,9 +191,11 @@ public sealed class FebeApp : IAsyncDisposable Clock = Clock, Sources = ImportSourceOptions.Docker(Path.Combine(_temporaryFolder, "importa")), DataFolder = data.Root, + Gate = longWork, }); await StartWebAsync(hooks, services => { + services.AddSingleton(longWork); services.AddSingleton(Database); services.AddSingleton(library); services.AddSingleton(Clock); @@ -236,6 +239,9 @@ public sealed class FebeApp : IAsyncDisposable var library = new FebeLibrary(Database, data, layout, Clock, hashes); var staging = Path.Combine(data.Root, "temporanei"); + // One gate for import, copies to external folders and rebuild: they never run together (spec §4.10). + var longWork = new LongWorkGate(); + // Import (spec §9). Docker: sources under /importa, read-only, over the fixed library; what was running when // Febe stopped becomes «interrotto». Windows: the web layer's ImportHub builds the service over the library // and builds it again when the library folder changes in Impostazioni (any source folder, native picker). @@ -255,6 +261,7 @@ public sealed class FebeApp : IAsyncDisposable SetFileTimeToPublication = settings.SetFileTimeToPublication, Sources = importRoot is null ? ImportSourceOptions.AnyFolder : ImportSourceOptions.Docker(importRoot), DataFolder = data.Root, + Gate = longWork, }); LogRecovered(await Import.RecoverAsync(ct).ConfigureAwait(false)); } @@ -321,6 +328,7 @@ public sealed class FebeApp : IAsyncDisposable await StartWebAsync(hooks, s => { + s.AddSingleton(longWork); s.AddSingleton(Database); s.AddSingleton(library); s.AddSingleton(Clock); diff --git a/src/Febe.Core/Abstractions/LongWorkGate.cs b/src/Febe.Core/Abstractions/LongWorkGate.cs new file mode 100644 index 0000000..92dd75a --- /dev/null +++ b/src/Febe.Core/Abstractions/LongWorkGate.cs @@ -0,0 +1,106 @@ +using System.Diagnostics.CodeAnalysis; + +namespace Febe.Core.Abstractions; + +/// The long pieces of work that never run together (spec §4.10: «esportazione, importazione e ricostruzione non girano insieme»). +public enum LongWorkKind +{ + /// An import job: analysis or copy (spec §9). + Import, + + /// A job of copies to external folders (spec §4.10). + Export, + + /// «Ricostruisci il database dalla libreria» (spec §8.5). + Rebuild, +} + +/// +/// 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. +/// +public sealed class LongWorkGate +{ + private readonly Lock _lock = new(); + private Lease? _holder; + + /// Who holds the gate, or null when it is free. + public LongWorkKind? Busy + { + get + { + lock (_lock) + { + return _holder?.Kind; + } + } + } + + /// + /// Takes the gate for . False, with set, when another job (of any + /// kind, the same one included) holds it. + /// + public bool TryEnter(LongWorkKind kind, [NotNullWhen(true)] out IDisposable? lease, out LongWorkKind? busyWith) + { + lock (_lock) + { + if (_holder is { } holder) + { + lease = null; + busyWith = holder.Kind; + return false; + } + + var taken = new Lease(this, kind); + _holder = taken; + lease = taken; + busyWith = null; + return true; + } + } + + /// The Italian answer when cannot start because is running. + public static string BusyMessage(LongWorkKind wanted, LongWorkKind busy) => (wanted, busy) switch + { + (LongWorkKind.Import, LongWorkKind.Import) => "C'è già un'importazione al lavoro: aspetta che finisca o interrompila.", + (LongWorkKind.Export, LongWorkKind.Export) => "C'è già una copia al lavoro: aspetta che finisca o interrompila.", + (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.", + }; + + private static string Verb(LongWorkKind kind) => kind switch + { + LongWorkKind.Import => "importa", + LongWorkKind.Export => "copia", + _ => "ricostruisci", + }; + + private void Release(Lease lease) + { + lock (_lock) + { + if (ReferenceEquals(_holder, lease)) + { + _holder = null; + } + } + } + + private sealed class Lease(LongWorkGate gate, LongWorkKind kind) : IDisposable + { + private int _disposed; + + public LongWorkKind Kind { get; } = kind; + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) == 0) + { + gate.Release(this); + } + } + } +} diff --git a/src/Febe.Core/Export/EngineSessionState.cs b/src/Febe.Core/Export/EngineSessionState.cs new file mode 100644 index 0000000..e99b3ed --- /dev/null +++ b/src/Febe.Core/Export/EngineSessionState.cs @@ -0,0 +1,29 @@ +using Febe.Core.Engine; + +namespace Febe.Core.Export; + +/// Whether the engine is in a session now: copies never run during one (spec §4.10, decision D11 of tappa E2). +public interface IEngineSessionState +{ + bool InSession { get; } +} + +/// No engine (tests, a start with problems): never in a session. +public sealed class NoEngineSession : IEngineSessionState +{ + public static readonly NoEngineSession Instance = new(); + + private NoEngineSession() + { + } + + public bool InSession => false; +} + +/// The session of the running engine. +public sealed class RuntimeSessionState(EngineRuntime runtime) : IEngineSessionState +{ + private readonly EngineRuntime _runtime = runtime ?? throw new ArgumentNullException(nameof(runtime)); + + public bool InSession => _runtime.CurrentSession is not null; +} diff --git a/src/Febe.Core/Export/ExportAccounts.cs b/src/Febe.Core/Export/ExportAccounts.cs new file mode 100644 index 0000000..36776b8 --- /dev/null +++ b/src/Febe.Core/Export/ExportAccounts.cs @@ -0,0 +1,31 @@ +using Febe.Core.Domain; + +namespace Febe.Core.Export; + +/// «Esporta questo account» (spec §4.10). +public static class ExportAccounts +{ + /// On when Alberto never chose: decision of Alberto, 27 November 2026 (D1 of tappa E2). + public const bool DefaultEnabled = true; + + /// The switch of an account from its stored choice (null: none recorded). + public static bool IsEnabled(bool? stored) => stored ?? DefaultEnabled; +} + +/// +/// The effective destination of an account (D2): its own folder in use, otherwise the general folder in use, otherwise +/// none; with the switch «Esporta questo account». +/// +public sealed record EffectiveDestination(long AccountId, ExportDestination? Destination, bool Enabled) +{ + /// The account's own folder. + public bool IsOwn => Destination?.Scope == ExportScope.Account; + + public bool HasDestination => Destination is not null; + + /// The switch is on and there is a destination: files of the account may be copied (D3). + public bool Exports => Enabled && Destination is not null; + + /// The account's files of this content type are copied (D3, D4). + public bool Wants(ContentTypes type) => Exports && (Destination!.ContentTypes & type) != ContentTypes.None; +} diff --git a/src/Febe.Core/Export/ExportCopier.cs b/src/Febe.Core/Export/ExportCopier.cs new file mode 100644 index 0000000..8664c32 --- /dev/null +++ b/src/Febe.Core/Export/ExportCopier.cs @@ -0,0 +1,672 @@ +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Core.Storage; + +namespace Febe.Core.Export; + +/// +/// One export job towards one destination (spec §4.10 «Come si copia»; decisions D11, D12, D16, D17 of tappa E2): +/// +/// before each group of files (at most files, or until +/// bytes are reached) the destination is checked with a probe file; a failed +/// check pauses the destination and the job, never the red strip; +/// each file is written to a .part in its final folder, hashed while writing, read back from the disk and +/// compared, compared with the library's SHA-256, then renamed to a free name: nothing is ever overwritten, and no +/// other file of the destination is deleted or moved; +/// a file already at the planned path with the same SHA-256 is adopted, not written again; +/// «Tolto» and «Superato» are never copied again by themselves, only with «Copia di nuovo»; +/// nothing is copied during an engine session: the job waits; +/// resumable: every file has its state, and the target path is recorded before its .part exists. +/// +/// +public sealed class ExportCopier(ExportEnvironment env) +{ + private const int PageSize = 500; + private const int MaxSiblings = 1000; + private const int MaxPath = WindowsFileNames.MaxPathLength; + + private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env)); + + /// + /// Runs (or resumes) a job. A destination that does not answer pauses it (returns, does not throw). On cancellation + /// the job becomes «interrotto» and is thrown. + /// + /// No such job. + /// The job already ended. + public async Task CopyAsync(long runId, IProgress? progress = null, CancellationToken ct = default) + { + var store = _env.Storage.Exports; + var none = CancellationToken.None; + var run = await store.GetRunAsync(runId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Lavoro di copia {runId} non trovato."); + if (run.State is not (ExportRunState.Running or ExportRunState.Interrupted or ExportRunState.Paused)) + { + throw new InvalidOperationException("Questo lavoro di copia è già finito: non c'è niente da riprendere."); + } + + var destination = await store.GetDestinationAsync(run.DestinationId, ct).ConfigureAwait(false); + if (destination is null || destination.IsRetired) + { + run = run with { State = ExportRunState.Cancelled, CompletedAt = _env.Clock.Now, LastError = ExportText.RetiredDestination }; + await store.UpdateRunAsync(run, none).ConfigureAwait(false); + await ExportRunSettings.ClearAsync(_env.Storage.Settings, runId, none).ConfigureAwait(false); + return run; + } + + run = run with { State = ExportRunState.Running, LastError = null }; + await store.UpdateRunAsync(run, none).ConfigureAwait(false); + var x = new RunContext(run, destination, progress); + try + { + x.Report(_env, ExportPhase.Preparing, null); + await ExportLeftovers.CleanAsync(_env, run, destination, ct).ConfigureAwait(false); + var layout = _env.Layout(); + var library = await LibrarySettings.LoadAsync(_env.Storage.Settings, layout.Root, ct).ConfigureAwait(false); + var settings = await ExportSettings.LoadAsync(_env.Storage.Settings, ct).ConfigureAwait(false); + x.Naming = library.Naming; + x.SetFileTime = library.SetFileTimeToPublication; + x.OneOnly = settings.SamePost == SamePostCopies.OneOnly; + x.CopyAgain = await ExportRunSettings.GetCopyAgainAsync(_env.Storage.Settings, runId, ct).ConfigureAwait(false); + x.Effective = await new ExportDestinations(_env).ResolveAllAsync(ct).ConfigureAwait(false); + var summary = await store.GetRunSummaryAsync(runId, ct).ConfigureAwait(false); + x.FilesTotal = summary.Total; + x.FilesDone = summary.Total - summary.ByState.GetValueOrDefault(ExportItemState.Pending); + x.ByState = new Dictionary(summary.ByState); + x.BytesTotal = await PendingBytesAsync(runId, ct).ConfigureAwait(false); + + var groupFiles = 0; + long groupBytes = 0; + long after = 0; + while (true) + { + var page = await store.ListItemsAsync(new ExportItemQuery { RunId = runId, State = ExportItemState.Pending, AfterId = after, Limit = PageSize }, ct).ConfigureAwait(false); + if (page.Count == 0) + { + break; + } + + after = page[^1].Id; + foreach (var item in page) + { + ct.ThrowIfCancellationRequested(); + if (groupFiles == 0 && await ProbeAsync(x, ct).ConfigureAwait(false) is { } problem) + { + return await PauseAsync(x, problem).ConfigureAwait(false); + } + + await WaitOutsideSessionAsync(x, ct).ConfigureAwait(false); + var result = await ProcessItemAsync(x, item, ct).ConfigureAwait(false); + if (result.Pause is { } pause) + { + return await PauseAsync(x, pause).ConfigureAwait(false); + } + + x.FilesDone++; + x.BytesDone += result.Bytes; + x.ByState[ExportItemState.Pending] = Math.Max(0, x.ByState.GetValueOrDefault(ExportItemState.Pending) - 1); + x.ByState[result.State] = x.ByState.GetValueOrDefault(result.State) + 1; + groupFiles++; + groupBytes += result.Bytes; + if (groupFiles >= Math.Max(1, _env.GroupFiles) || groupBytes >= _env.GroupBytes) + { + groupFiles = 0; + groupBytes = 0; + } + + x.Report(_env, ExportPhase.Copying, result.Path); + } + } + + var final = await store.GetRunSummaryAsync(runId, none).ConfigureAwait(false); + run = run with { State = ExportRunState.Completed, CompletedAt = _env.Clock.Now, LastError = null }; + await store.UpdateRunAsync(run, none).ConfigureAwait(false); + await _env.Storage.Events.AppendAsync( + new EventRecord + { + At = _env.Clock.Now, + Code = "esportazione-completata", + Message = ExportText.CompletionMessage(final, x.Destination), + Severity = final.ByState.GetValueOrDefault(ExportItemState.Failed) > 0 ? EventSeverity.Warning : EventSeverity.Success, + AccountId = x.Destination.AccountId, + }, + none).ConfigureAwait(false); + await ExportRunSettings.ClearAsync(_env.Storage.Settings, runId, none).ConfigureAwait(false); + x.ByState = new Dictionary(final.ByState); + x.Report(_env, ExportPhase.Finished, null); + return run; + } + catch (Exception ex) + { + var cancelled = ex is OperationCanceledException && ct.IsCancellationRequested; + run = run with { State = ExportRunState.Interrupted, LastError = cancelled ? null : ExportText.ErrorText(ex) }; + await store.UpdateRunAsync(run, none).ConfigureAwait(false); + throw; + } + } + + /// + /// Checks a destination before a group of copies: the mount rule in Docker, then the folder check with its probe + /// file and the identity test (WP1.3). Returns why it cannot be written, or null; a success clears its pause. + /// + internal async Task CheckDestinationAsync(ExportDestination destination, CancellationToken ct) + { + if (ExportRoots.MountProblem(_env.Root, destination.RootPath) is { } mount) + { + return mount; + } + + var context = await _env.FolderContextAsync(null, ct).ConfigureAwait(false); + var verdict = await _env.CreateFolderCheck().CheckAsync(destination.RootPath, context, ct).ConfigureAwait(false); + return verdict.Problem switch + { + null => null, + { Kind: ExportFolderProblemKind.Missing or ExportFolderProblemKind.NotResponding } => + $"{ExportDestinations.Label(destination)} non è raggiungibile: controlla che il disco o la condivisione siano collegati, poi riprendi.", + { } problem => problem.Message, + }; + } + + private async Task ProbeAsync(RunContext x, CancellationToken ct) + { + var problem = await CheckDestinationAsync(x.Destination, ct).ConfigureAwait(false); + if (problem is null && (x.Destination.PausedAt is not null || x.Destination.LastError is not null)) + { + x.Destination = await ExportPause.ClearAsync(_env, x.Destination).ConfigureAwait(false); + } + + return problem; + } + + private async Task PauseAsync(RunContext x, string message) + { + x.Destination = await ExportPause.PauseAsync(_env, x.Destination, message).ConfigureAwait(false); + var run = x.Run with { State = ExportRunState.Paused, LastError = message }; + await _env.Storage.Exports.UpdateRunAsync(run, CancellationToken.None).ConfigureAwait(false); + x.Report(_env, ExportPhase.Finished, null); + return run; + } + + private async Task WaitOutsideSessionAsync(RunContext x, CancellationToken ct) + { + while (_env.Session.InSession) + { + x.Report(_env, ExportPhase.WaitingForSession, null); + await _env.Clock.Delay(_env.SessionPoll, ct).ConfigureAwait(false); + } + } + + private async Task PendingBytesAsync(long runId, CancellationToken ct) + { + long total = 0; + long after = 0; + while (true) + { + var page = await _env.Storage.Exports.ListItemsAsync(new ExportItemQuery { RunId = runId, State = ExportItemState.Pending, AfterId = after, Limit = PageSize }, ct).ConfigureAwait(false); + if (page.Count == 0) + { + return total; + } + + after = page[^1].Id; + foreach (var item in page) + { + if (item.MediaId is { } id && await _env.Storage.Media.GetAsync(id, ct).ConfigureAwait(false) is { Bytes: { } bytes }) + { + total += bytes; + } + } + } + } + + private async Task ProcessItemAsync(RunContext x, ExportItem item, CancellationToken ct) + { + var storage = _env.Storage; + var exports = storage.Exports; + var none = CancellationToken.None; + var destination = x.Destination; + var root = destination.RootPath; + + // a. No longer in the library. + if (item.AccountId is not { } accountId || await storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false) is not { } account) + { + return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.AccountRemoved, LastError = null }, 0, null).ConfigureAwait(false); + } + + var media = item.MediaId is { } mediaId ? await storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false) : null; + var entry = media is null ? null : await storage.Entries.GetAsync(media.EntryId, ct).ConfigureAwait(false); + var source = media is { Sha256.Length: 64, RelativePath: not null } && EntryStateRules.IsPresent(media.State) && entry?.AccountId == accountId + ? _env.ResolveSourcePath(account, media) + : null; + if (source is null || media is null || entry is null) + { + return await FinishAsync(item with { State = ExportItemState.Missing, Note = ExportText.Notes.SourceMissing, LastError = null }, 0, null).ConfigureAwait(false); + } + + // The account may have been switched off, or got another folder, or the destination stopped taking this type + // since the job was planned (decisions D2, D3 of tappa E2): «Esporta questo account» off skips every copy. + var (title, inHighlight) = await HighlightAsync(entry, ct).ConfigureAwait(false); + if (!x.Effective.TryGetValue(accountId, out var effective) || effective.Destination?.Id != destination.Id + || !effective.Wants(ExportPaths.TypeOf(entry.Kind, media.Kind, inHighlight))) + { + return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.NotExported, LastError = null }, media.Bytes ?? 0, null).ConfigureAwait(false); + } + + // b. The file may have changed since the job was planned. + var sha = media.Sha256!; + if (!string.Equals(item.SourceSha256, sha, StringComparison.Ordinal)) + { + item = item with { SourceSha256 = sha }; + } + + var bytes = media.Bytes ?? _env.FileSystem.FileLength(source) ?? 0; + var identity = new ExportCopyIdentity(destination.Id, accountId, sha, ExportVariant.Whole, ExportFormat.Original, null); + var file = new FileContext(account, entry, media, source, sha, bytes, identity, title, inHighlight); + + // c. Already copied, removed, superseded, copied for another account, or failed before. + var current = await exports.FindCurrentCopyAsync(identity, ct).ConfigureAwait(false); + ExportCopy? failed = null; + if (current is { State: ExportCopyState.Copied }) + { + if (current.RelativePath is { } copied && Exists(root, copied)) + { + return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = current.Id, RelativePath = copied, Note = null, LastError = null }, bytes, copied).ConfigureAwait(false); + } + + // The file is not there: «Tolto», unless the whole destination went away meanwhile. + if (!Directory.Exists(root) && await ProbeAsync(x, ct).ConfigureAwait(false) is { } gone) + { + return ItemResult.Paused(gone); + } + + await exports.UpdateCopyAsync(current with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, none).ConfigureAwait(false); + if (!x.CopyAgain) + { + return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Removed, CopyId = current.Id, LastError = null }, bytes, current.RelativePath).ConfigureAwait(false); + } + } + else if (current is { State: ExportCopyState.Failed }) + { + failed = current; + } + else if (!x.CopyAgain) + { + var latest = await exports.FindLatestCopyAsync(identity, ct).ConfigureAwait(false); + if (latest is { State: ExportCopyState.Removed or ExportCopyState.Superseded }) + { + var note = latest.State == ExportCopyState.Removed ? ExportText.Notes.Removed : ExportText.Notes.Superseded; + return await FinishAsync(item with { State = ExportItemState.Skipped, Note = note, CopyId = latest.Id, LastError = null }, bytes, latest.RelativePath).ConfigureAwait(false); + } + + if (await exports.FindReplacedCopyAsync(destination.Id, accountId, sha, ct).ConfigureAwait(false) is { } replaced) + { + return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Superseded, CopyId = replaced.Id, LastError = null }, bytes, replaced.RelativePath).ConfigureAwait(false); + } + } + + if (x.OneOnly + && await exports.FindCopiedElsewhereAsync(sha, ExportVariant.Whole, ExportFormat.Original, ct).ConfigureAwait(false) is { AccountId: { } other, RelativePath: { } elsewherePath } elsewhere + && other != accountId + && await x.DestinationAsync(storage, elsewhere.DestinationId, ct).ConfigureAwait(false) is { IsRetired: false } where + && Exists(where.RootPath, elsewherePath)) + { + return await FinishAsync( + item with { State = ExportItemState.AlreadyCopied, Note = ExportText.Notes.CopiedForAnotherAccount, CopyId = elsewhere.Id, LastError = null }, + bytes, + null).ConfigureAwait(false); + } + + return await WriteAsync(x, item, file, failed, ct).ConfigureAwait(false); + } + + /// d. and e.: the path, the limits of the disk, adoption, the safe write and its record. + private async Task WriteAsync(RunContext x, ExportItem item, FileContext file, ExportCopy? failed, CancellationToken ct) + { + var exports = _env.Storage.Exports; + var none = CancellationToken.None; + var destination = x.Destination; + var root = destination.RootPath; + + string planned; + try + { + planned = ExportPaths.RelativePathFor( + destination, + ExportPaths.Segments(destination, x.Naming!, file.Account, file.Entry, file.Media, file.HighlightTitle, file.InHighlight, _env.Clock.LocalZone), + MaxPath); + } + catch (PathTooLongException ex) + { + return await FailAsync(item, file, failed, ex.Message, null).ConfigureAwait(false); + } + + if (_env.Disk.MaxFileBytes(root) is { } max && file.Bytes > max) + { + return await FailAsync(item, file, failed, ExportText.TooLarge(file.Bytes), ExportText.Notes.TooLargeForFileSystem).ConfigureAwait(false); + } + + if (_env.Disk.FreeBytes(root) is { } free && free < file.Bytes + ExportSpace.Margin) + { + return ItemResult.Paused(ExportText.NoSpace(destination, free, Path.GetFileName(planned), file.Bytes)); + } + + // Adoption by path: the planned file, and after a crash the name it was given («nome (2).jpg», …). + foreach (var candidate in AdoptionCandidates(root, planned, item.RelativePath)) + { + var full = LibraryLayout.FullPath(root, candidate); + if (_env.FileSystem.FileLength(full) != file.Bytes + || !string.Equals(await _env.FileSystem.ComputeSha256Async(full, ct).ConfigureAwait(false), file.Sha256, StringComparison.Ordinal)) + { + continue; + } + + var holder = await exports.FindCopyByPathAsync(destination.Id, candidate, ct).ConfigureAwait(false); + if (holder is null || (holder.AccountId is null && string.Equals(holder.SourceSha256, file.Sha256, StringComparison.Ordinal))) + { + return await RecordAsync(item, file, failed, holder, candidate, file.Bytes, ExportCopyOrigin.Adopted, null).ConfigureAwait(false); + } + + if (holder.Identity == file.Identity) + { + return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = holder.Id, RelativePath = candidate, Note = null, LastError = null }, file.Bytes, candidate).ConfigureAwait(false); + } + + // The same bytes, recorded for another copy: not ours to take. + } + + // A path recorded for another copy whose file is gone is free again («Tolto»). + await ReleaseStalePathAsync(destination, planned, file.Identity, ct).ConfigureAwait(false); + + // The intent, in its own transaction, before the .part exists (WP1.8 cleans only the folders of items). + item = item with { RelativePath = planned }; + await exports.UpdateItemsAsync([item], none).ConfigureAwait(false); + + SavedFile saved; + try + { + var directory = planned.Contains('/', StringComparison.Ordinal) ? planned[..planned.LastIndexOf('/')] : string.Empty; + await using var content = _env.FileSystem.OpenRead(file.Source); + saved = (await new SafeFileWriter(MaxPath).SaveAsync( + content, + root, + directory, + (digest, _) => string.Equals(digest.Sha256, file.Sha256, StringComparison.Ordinal) + ? ValueTask.FromResult(planned) + : throw new ContentChangedException("Il file della libreria non corrisponde a quello registrato."), + new SafeWriteOptions + { + RequireExistingRoot = true, + VerifyFromDisk = true, + LastWriteTime = x.SetFileTime ? file.Entry.PublishedAt : null, + }, + ct).ConfigureAwait(false))!; + } + catch (ContentChangedException ex) + { + return await FailAsync(item, file, failed, ex.Message, ExportText.Notes.SourceChanged).ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + if (IsDiskFull(ex)) + { + return ItemResult.Paused(_env.Disk.FreeBytes(root) is { } left + ? ExportText.NoSpace(destination, left, Path.GetFileName(planned), file.Bytes) + : ExportText.DiskFull(destination)); + } + + if ((ex is ExportRootMissingException or DirectoryNotFoundException || !Directory.Exists(root)) && await ProbeAsync(x, ct).ConfigureAwait(false) is { } problem) + { + return ItemResult.Paused(problem); // the item stays pending + } + + return await FailAsync(item, file, failed, ExportText.ErrorText(ex), null).ConfigureAwait(false); + } + + string? taken = null; + if (!string.Equals(saved.RelativePath, planned, StringComparison.Ordinal)) + { + taken = ExportText.Notes.NameTaken; + await ReleaseStalePathAsync(destination, saved.RelativePath, file.Identity, ct).ConfigureAwait(false); + } + + return await RecordAsync(item, file, failed, null, saved.RelativePath, saved.Bytes, ExportCopyOrigin.Written, taken).ConfigureAwait(false); + } + + /// Files to look at for adoption: the planned path, then the one recorded before a crash and its numbered names. + private IEnumerable AdoptionCandidates(string root, string planned, string? previous) + { + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + if (seen.Add(planned) && Exists(root, planned)) + { + yield return planned; + } + + if (previous is null) + { + yield break; + } + + for (var attempt = 1; attempt <= MaxSiblings; attempt++) + { + string name; + try + { + name = ExportPaths.NumberedName(root, previous, attempt, MaxPath); + } + catch (PathTooLongException) + { + yield break; + } + + if (!Exists(root, name)) + { + yield break; // the writer takes the first free name: nothing of ours after it + } + + if (seen.Add(name)) + { + yield return name; + } + } + } + + /// A Copied or Superseded row of another copy on this path whose file is not there becomes «Tolto». + private async Task ReleaseStalePathAsync(ExportDestination destination, string path, ExportCopyIdentity identity, CancellationToken ct) + { + var held = await _env.Storage.Exports.FindCopyByPathAsync(destination.Id, path, ct).ConfigureAwait(false); + if (held is not null && held.Identity != identity && !Exists(destination.RootPath, path)) + { + await _env.Storage.Exports.UpdateCopyAsync(held with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, CancellationToken.None).ConfigureAwait(false); + } + } + + private async Task RecordAsync(ExportItem item, FileContext file, ExportCopy? failed, ExportCopy? orphan, string path, long bytes, ExportCopyOrigin origin, string? note) + { + var exports = _env.Storage.Exports; + var none = CancellationToken.None; + var now = _env.Clock.Now; + ExportCopy copy; + try + { + if (failed is not null) + { + copy = failed with + { + State = ExportCopyState.Copied, + Origin = origin, + RelativePath = path, + Bytes = bytes, + CopySha256 = file.Sha256, + CopiedAt = now, + StateChangedAt = now, + LastError = null, + MediaId = file.Media.Id, + }; + await exports.UpdateCopyAsync(copy, none).ConfigureAwait(false); + } + else if (orphan is not null) + { + copy = await exports.RelinkOrphanCopyAsync(orphan.Id, file.Identity.AccountId, file.Media.Id, now, none).ConfigureAwait(false); + } + else + { + copy = await exports.AddCopyAsync( + new ExportCopy + { + DestinationId = file.Identity.DestinationId, + AccountId = file.Identity.AccountId, + MediaId = file.Media.Id, + SourceSha256 = file.Sha256, + Variant = ExportVariant.Whole, + Format = ExportFormat.Original, + State = ExportCopyState.Copied, + Origin = origin, + RelativePath = path, + Bytes = bytes, + CopySha256 = file.Sha256, + CopiedAt = now, + }, + none).ConfigureAwait(false); + } + } + catch (DuplicateRecordException) + { + // Taken meanwhile by another record. The file written stays where it is: nothing is ever removed. + return await FinishAsync(item with { State = ExportItemState.Failed, Note = ExportText.Notes.PathTaken, LastError = ExportText.Note(ExportText.Notes.PathTaken) }, file.Bytes, path).ConfigureAwait(false); + } + + var state = origin == ExportCopyOrigin.Adopted ? ExportItemState.Adopted : ExportItemState.Copied; + return await FinishAsync(item with { State = state, CopyId = copy.Id, RelativePath = path, Note = note, LastError = null }, file.Bytes, path).ConfigureAwait(false); + } + + /// f.: the item fails, and its copy is «Non riuscito» (the viewer shows it), the job goes on. + private async Task FailAsync(ExportItem item, FileContext file, ExportCopy? failed, string error, string? note) + { + var exports = _env.Storage.Exports; + var none = CancellationToken.None; + long? copyId = failed?.Id; + try + { + if (failed is not null) + { + await exports.UpdateCopyAsync(failed with { LastError = error, StateChangedAt = _env.Clock.Now, MediaId = file.Media.Id }, none).ConfigureAwait(false); + } + else + { + copyId = (await exports.AddCopyAsync( + new ExportCopy + { + DestinationId = file.Identity.DestinationId, + AccountId = file.Identity.AccountId, + MediaId = file.Media.Id, + SourceSha256 = file.Sha256, + Variant = ExportVariant.Whole, + Format = ExportFormat.Original, + State = ExportCopyState.Failed, + CopiedAt = _env.Clock.Now, + LastError = error, + }, + none).ConfigureAwait(false)).Id; + } + } + catch (DuplicateRecordException) + { + // The identity got a current row meanwhile: that one tells the state. + } + + return await FinishAsync(item with { State = ExportItemState.Failed, Note = note, LastError = error, CopyId = copyId }, file.Bytes, item.RelativePath).ConfigureAwait(false); + } + + private async Task FinishAsync(ExportItem item, long bytes, string? path) + { + await _env.Storage.Exports.UpdateItemsAsync([item], CancellationToken.None).ConfigureAwait(false); + return new ItemResult(item.State, bytes, path, null); + } + + private async Task<(string? Title, bool InHighlight)> HighlightAsync(Entry entry, CancellationToken ct) + { + if (entry.Kind is not (EntryKind.Story or EntryKind.Highlight)) + { + return (null, false); + } + + var collections = await _env.Storage.Highlights.ListForEntryAsync(entry.Id, ct).ConfigureAwait(false); + return (collections.FirstOrDefault()?.Title, collections.Count > 0); + } + + private bool Exists(string root, string relativePath) + { + try + { + return _env.FileSystem.FileExists(LibraryLayout.FullPath(root, relativePath)); + } + catch (ArgumentException) + { + return false; + } + } + + /// «Disco pieno»: ERROR_DISK_FULL or ERROR_HANDLE_DISK_FULL on Windows, ENOSPC elsewhere. + internal static bool IsDiskFull(Exception ex) => + ex is IOException io + && (io.HResult is unchecked((int)0x80070070) or unchecked((int)0x80070027) or 28 + || io.Message.Contains("No space left on device", StringComparison.OrdinalIgnoreCase)); + + private sealed record FileContext(Account Account, Entry Entry, Media Media, string Source, string Sha256, long Bytes, ExportCopyIdentity Identity, string? HighlightTitle, bool InHighlight); + + /// What happened to an item; stops the job with the destination paused. + private sealed record ItemResult(ExportItemState State, long Bytes, string? Path, string? Pause) + { + public static ItemResult Paused(string message) => new(ExportItemState.Pending, 0, null, message); + } + + private sealed class RunContext(ExportRun run, ExportDestination destination, IProgress? progress) + { + private readonly Dictionary _destinations = []; + + public ExportRun Run { get; } = run; + + public ExportDestination Destination { get; set; } = destination; + + public LibraryNaming? Naming { get; set; } + + public bool SetFileTime { get; set; } = true; + + public bool OneOnly { get; set; } + + public bool CopyAgain { get; set; } + + public IReadOnlyDictionary Effective { get; set; } = new Dictionary(); + + public int FilesDone { get; set; } + + public int FilesTotal { get; set; } + + public long BytesDone { get; set; } + + public long BytesTotal { get; set; } + + public Dictionary ByState { get; set; } = []; + + public async Task DestinationAsync(IFebeStorage storage, long id, CancellationToken ct) + { + if (!_destinations.TryGetValue(id, out var row)) + { + _destinations[id] = row = await storage.Exports.GetDestinationAsync(id, ct).ConfigureAwait(false); + } + + return row; + } + + public void Report(ExportEnvironment env, ExportPhase phase, string? current) => + progress?.Report(new ExportProgress( + Run.Id, + phase, + FilesDone, + FilesTotal, + BytesDone, + Math.Max(BytesTotal, BytesDone), + current, + ExportDestinations.Label(Destination), + new Dictionary(ByState), + env.Clock.Now)); + } +} diff --git a/src/Febe.Core/Export/ExportDestinations.cs b/src/Febe.Core/Export/ExportDestinations.cs new file mode 100644 index 0000000..cb1ada1 --- /dev/null +++ b/src/Febe.Core/Export/ExportDestinations.cs @@ -0,0 +1,387 @@ +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Core.Storage; + +namespace Febe.Core.Export; + +/// What Alberto sets for a destination (Impostazioni → Esportazione, scheda account → «Copie esterne»). +/// General folder or own folder of an account. +/// The account of an own folder; null for the general folder. +/// The folder as chosen (Docker: relative to /esporta, or a full path inside it). +/// Name shown; null: the last segment of the folder. +/// At least one type. +/// General scheme; null: «Come la libreria». +/// Scheme of highlight collections; null: «Come la libreria». +/// Scheme of profile pictures; null: «Come la libreria». +/// «Automatica»: stored only in tappa E2 (tappa E5 acts on it). +/// «Solo i nuovi» when «Automatica» is turned on. +public sealed record DestinationSpec( + ExportScope Scope, + long? AccountId, + string Path, + string? Label, + ContentTypes ContentTypes, + string? NamingScheme, + string? HighlightNamingScheme, + string? ProfileNamingScheme, + bool Automatic = false, + bool OnlyNew = true); + +/// A saved destination and the warnings of its naming schemes (shown, they do not block). +public sealed record DestinationSaveResult(ExportDestination Destination, IReadOnlyList Warnings); + +/// A destination in use that now overlaps a protected folder (WP1.10 of tappa E2). +public sealed record ExportFolderConflict(ExportDestination Destination, ExportFolderProblem Problem); + +/// What Impostazioni and the Dashboard show of a destination. +/// The stored row (paused or not). +/// The folder answered now (and, in Docker, sits on a usable mount). +/// Why it is not reachable, or the error of its pause; null when fine. +/// Copies per state, every state present. +/// Free space when reachable and measurable. +public sealed record ExportDestinationStatus( + ExportDestination Destination, + bool Reachable, + string? Problem, + IReadOnlyDictionary Counts, + long? FreeBytes); + +/// +/// Destinations and the switch «Esporta questo account» (spec §4.10 «Destinazioni»), for the API. No file is touched +/// here except through (its probe, only in the candidate folder). +/// +public sealed class ExportDestinations(ExportEnvironment env) +{ + /// The answer to «Togli la cartella». + public const string RetiredText = "Cartella tolta. I file già copiati restano dove sono."; + + /// A destination with an unfinished job cannot be retired nor moved. + public const string UnfinishedRunText = "C'è un lavoro di copia non finito verso questa cartella: finiscilo o annullalo, poi cambia cartella."; + + private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env)); + + /// The name shown for a destination: its label, or the last segment of its folder. + public static string Label(ExportDestination destination) + { + ArgumentNullException.ThrowIfNull(destination); + if (!string.IsNullOrWhiteSpace(destination.Label)) + { + return destination.Label.Trim(); + } + + var trimmed = ExportPaths.Trim(destination.RootPath); + var name = System.IO.Path.GetFileName(trimmed); + return string.IsNullOrEmpty(name) ? trimmed : name; + } + + /// The effective destination of an account (D2) with its switch (D1). + public async Task ResolveAsync(long accountId, CancellationToken ct) + { + var exports = _env.Storage.Exports; + var own = await exports.GetAccountDestinationAsync(accountId, ct).ConfigureAwait(false); + var destination = own ?? await exports.GetGeneralDestinationAsync(ct).ConfigureAwait(false); + var enabled = ExportAccounts.IsEnabled(await exports.GetAccountExportEnabledAsync(accountId, ct).ConfigureAwait(false)); + return new EffectiveDestination(accountId, destination, enabled); + } + + /// The effective destination of every account, with one read of each table. + public async Task> ResolveAllAsync(CancellationToken ct) + { + var accounts = await _env.Storage.Accounts.ListAsync(ct).ConfigureAwait(false); + var destinations = await _env.Storage.Exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false); + var switches = await _env.Storage.Exports.ListAccountExportSwitchesAsync(ct).ConfigureAwait(false); + var general = destinations.FirstOrDefault(d => d.Scope == ExportScope.General); + var own = destinations.Where(d => d.Scope == ExportScope.Account && d.AccountId is not null).ToDictionary(d => d.AccountId!.Value); + return accounts.ToDictionary( + a => a.Id, + a => new EffectiveDestination( + a.Id, + own.GetValueOrDefault(a.Id) ?? general, + ExportAccounts.IsEnabled(switches.TryGetValue(a.Id, out var on) ? on : null))); + } + + /// + /// Adds a destination after checking folder (WP1.3), content types and naming schemes. + /// + /// The folder cannot be a destination. + /// Types, schemes, scope or account are not valid (Italian message). + public async Task CreateAsync(DestinationSpec spec, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(spec); + var account = await CheckScopeAsync(spec, ct).ConfigureAwait(false); + var warnings = ValidateSettings(spec); + if (spec.Scope == ExportScope.General && await _env.Storage.Exports.GetGeneralDestinationAsync(ct).ConfigureAwait(false) is not null) + { + throw new ArgumentException("C'è già una cartella generale: cambiala invece di aggiungerne un'altra.", nameof(spec)); + } + + if (account is not null && await _env.Storage.Exports.GetAccountDestinationAsync(account.Id, ct).ConfigureAwait(false) is not null) + { + throw new ArgumentException(OwnFolderInUse(account), nameof(spec)); + } + + var full = await CheckedFolderAsync(spec.Path, ct).ConfigureAwait(false); + var now = _env.Clock.Now; + var row = Build(spec, full, now) with { AutomaticSince = spec.Automatic && spec.OnlyNew ? now : null }; + try + { + return new DestinationSaveResult(await _env.Storage.Exports.AddDestinationAsync(row, ct).ConfigureAwait(false), warnings); + } + catch (DuplicateRecordException) + { + throw new ArgumentException( + account is null ? "C'è già una cartella generale: cambiala invece di aggiungerne un'altra." : OwnFolderInUse(account), + nameof(spec)); + } + } + + /// + /// Changes a destination. The same folder updates the row; another folder retires it and adds a new row (the copies + /// stay with the retired one), refused while an unfinished job writes to it. + /// + /// No such destination. + /// The new folder cannot be a destination. + /// Types, schemes, scope or account are not valid. + /// An unfinished job uses the old folder. + public async Task UpdateAsync(long id, DestinationSpec spec, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(spec); + var exports = _env.Storage.Exports; + var stored = await exports.GetDestinationAsync(id, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Destinazione di esportazione {id} non trovata."); + if (stored.IsRetired) + { + throw new ArgumentException("Questa cartella è stata tolta: non si modifica più.", nameof(id)); + } + + if (stored.Scope != spec.Scope || stored.AccountId != spec.AccountId) + { + throw new ArgumentException("Una cartella generale resta generale, e la cartella di un account resta di quell'account.", nameof(spec)); + } + + var warnings = ValidateSettings(spec); + var now = _env.Clock.Now; + string? full = null; + try + { + full = ExportRoots.Resolve(_env.Root, spec.Path); + } + catch (ExportFolderException) + { + // Not the same folder: the full check below gives the reason. + } + + if (full is not null && ExportPaths.Same(full, stored.RootPath)) + { + var since = !spec.Automatic ? null + : stored.Automatic ? stored.AutomaticSince + : spec.OnlyNew ? now : (DateTimeOffset?)null; + var updated = Build(spec, stored.RootPath, stored.CreatedAt) with + { + Id = stored.Id, + AutomaticSince = since, + PausedAt = stored.PausedAt, + LastError = stored.LastError, + }; + await exports.UpdateDestinationAsync(updated, ct).ConfigureAwait(false); + return new DestinationSaveResult(updated, warnings); + } + + if (stored.IsOrphan) + { + throw new ArgumentException("La cartella di un account rimosso non si cambia: toglila, oppure ridalla all'account quando torna.", nameof(spec)); + } + + await EnsureNoUnfinishedRunAsync(id, ct).ConfigureAwait(false); + var newFolder = await CheckedFolderAsync(spec.Path, ct).ConfigureAwait(false); + + // Two transactions, as the store wants: the old folder is retired with its copies, then the new one is added. + await exports.RetireDestinationAsync(id, now, CancellationToken.None).ConfigureAwait(false); + var row = Build(spec, newFolder, now) with { AutomaticSince = spec.Automatic && spec.OnlyNew ? now : null }; + return new DestinationSaveResult(await exports.AddDestinationAsync(row, CancellationToken.None).ConfigureAwait(false), warnings); + } + + /// «Togli la cartella»: only the configuration goes; copies and files stay (). + /// No such destination. + /// An unfinished job uses it. + public async Task RetireAsync(long id, CancellationToken ct) + { + var stored = await _env.Storage.Exports.GetDestinationAsync(id, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Destinazione di esportazione {id} non trovata."); + if (stored.IsRetired) + { + return; + } + + await EnsureNoUnfinishedRunAsync(id, ct).ConfigureAwait(false); + await _env.Storage.Exports.RetireDestinationAsync(id, _env.Clock.Now, ct).ConfigureAwait(false); + } + + /// «Esporta questo account». + /// No such account. + public async Task SetAccountEnabledAsync(long accountId, bool enabled, CancellationToken ct) + { + _ = await _env.Storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Account {accountId} non trovato."); + await _env.Storage.Exports.SetAccountExportEnabledAsync(accountId, enabled, ct).ConfigureAwait(false); + } + + /// Checks a folder for the dialog, before saving (WP1.3). + public async Task CheckFolderAsync(string candidate, CancellationToken ct) + { + var context = await _env.FolderContextAsync(null, ct).ConfigureAwait(false); + return await _env.CreateFolderCheck().CheckAsync(candidate, context, ct).ConfigureAwait(false); + } + + /// + /// Checks again every destination in use against the protected folders, with + /// (an account folder about to be saved). Only overlaps are conflicts: an unreachable folder is checked anyway at the + /// start of its next group of copies. + /// + public Task> RecheckAsync(IReadOnlyList? extraAccountFolders, CancellationToken ct) => + RecheckAgainstAsync(extraAccountFolders?.Select(f => new ProtectedFolder(f, ProtectedFolderKind.Account, null)).ToList(), ct); + + /// As , with folders of any kind (a new library root is ). + public async Task> RecheckAgainstAsync(IReadOnlyList? extra, CancellationToken ct) + { + var destinations = await _env.Storage.Exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false); + if (destinations.Count == 0) + { + return []; + } + + var context = await _env.FolderContextAsync(extra, ct).ConfigureAwait(false); + var check = _env.CreateFolderCheck(); + var verdicts = await Task.WhenAll(destinations.Select(async d => (Destination: d, Verdict: await check.CheckAsync(d.RootPath, context, ct).ConfigureAwait(false)))) + .ConfigureAwait(false); + return verdicts + .Where(v => v.Verdict.Problem is { IsOverlap: true }) + .Select(v => new ExportFolderConflict(v.Destination, v.Verdict.Problem!)) + .ToList(); + } + + /// Whether a destination answers now, its pause, its copies and its free space. + /// No such destination. + public async Task StatusAsync(long id, CancellationToken ct) + { + var destination = await _env.Storage.Exports.GetDestinationAsync(id, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Destinazione di esportazione {id} non trovata."); + var counts = await _env.Storage.Exports.CountCopiesAsync(id, ct).ConfigureAwait(false); + if (destination.IsRetired) + { + return new ExportDestinationStatus(destination, false, "Questa cartella è stata tolta.", counts, null); + } + + if (ExportRoots.MountProblem(_env.Root, destination.RootPath) is { } mountProblem) + { + return new ExportDestinationStatus(destination, false, mountProblem, counts, null); + } + + bool reachable; + try + { + reachable = await Task.Run(() => Directory.Exists(destination.RootPath), ct).WaitAsync(_env.FolderCheckTimeout, ct).ConfigureAwait(false); + } + catch (TimeoutException) + { + reachable = false; + } + + if (!reachable) + { + return new ExportDestinationStatus( + destination, + false, + $"{Label(destination)} non è raggiungibile: controlla che il disco o la condivisione siano collegati.", + counts, + null); + } + + long? free; + try + { + free = await Task.Run(() => _env.Disk.FreeBytes(destination.RootPath), ct).WaitAsync(_env.FolderCheckTimeout, ct).ConfigureAwait(false); + } + catch (TimeoutException) + { + free = null; + } + + return new ExportDestinationStatus(destination, true, destination.PausedAt is not null ? destination.LastError : null, counts, free); + } + + private async Task CheckScopeAsync(DestinationSpec spec, CancellationToken ct) + { + if (spec.Scope == ExportScope.General) + { + return spec.AccountId is null + ? null + : throw new ArgumentException("La cartella generale non è di un account.", nameof(spec)); + } + + if (spec.AccountId is not { } accountId) + { + throw new ArgumentException("Scegli l'account di questa cartella.", nameof(spec)); + } + + return await _env.Storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false) + ?? throw new ArgumentException("Questo account non c'è più.", nameof(spec)); + } + + /// Content types and naming schemes; returns the warnings of the schemes. + private static List ValidateSettings(DestinationSpec spec) + { + if (spec.ContentTypes == ContentTypes.None || (spec.ContentTypes & ~ContentTypes.All) != ContentTypes.None) + { + throw new ArgumentException("Scegli almeno un tipo di contenuto.", nameof(spec)); + } + + var errors = new List(); + var warnings = new List(); + void Check(string? text, NamingSchemeUse use) + { + if (Clean(text) is not { } scheme) + { + return; + } + + var validation = NamingScheme.Validate(scheme, use); + errors.AddRange(validation.Errors.Select(e => NamingPreview.Prefix(use) + e)); + warnings.AddRange(validation.Warnings.Select(w => NamingPreview.Prefix(use) + w)); + } + + Check(spec.NamingScheme, NamingSchemeUse.General); + Check(spec.HighlightNamingScheme, NamingSchemeUse.Highlight); + Check(spec.ProfileNamingScheme, NamingSchemeUse.ProfilePicture); + return errors.Count > 0 ? throw new ArgumentException(string.Join(" ", errors), nameof(spec)) : warnings; + } + + private async Task CheckedFolderAsync(string path, CancellationToken ct) + { + var verdict = await CheckFolderAsync(path, ct).ConfigureAwait(false); + return verdict.Problem is { } problem ? throw new ExportFolderException(problem.Message, problem.Kind) : verdict.FullPath; + } + + private async Task EnsureNoUnfinishedRunAsync(long destinationId, CancellationToken ct) + { + var unfinished = await _env.Storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false); + if (unfinished.Any(r => r.DestinationId == destinationId)) + { + throw new InvalidOperationException(UnfinishedRunText); + } + } + + private static ExportDestination Build(DestinationSpec spec, string root, DateTimeOffset createdAt) => new() + { + Scope = spec.Scope, + AccountId = spec.AccountId, + Label = Clean(spec.Label), + RootPath = root, + ContentTypes = spec.ContentTypes, + NamingScheme = Clean(spec.NamingScheme), + HighlightNamingScheme = Clean(spec.HighlightNamingScheme), + ProfileNamingScheme = Clean(spec.ProfileNamingScheme), + Automatic = spec.Automatic, + CreatedAt = createdAt, + }; + + private static string? Clean(string? text) => string.IsNullOrWhiteSpace(text) ? null : text.Trim(); + + private static string OwnFolderInUse(Account account) => $"@{account.Username} ha già una cartella sua: cambiala invece di aggiungerne un'altra."; +} diff --git a/src/Febe.Core/Export/ExportDisk.cs b/src/Febe.Core/Export/ExportDisk.cs new file mode 100644 index 0000000..7a1e948 --- /dev/null +++ b/src/Febe.Core/Export/ExportDisk.cs @@ -0,0 +1,82 @@ +using Febe.Core.Alerts; + +namespace Febe.Core.Export; + +/// Free space and the largest file a destination's disk accepts (a seam: tests give their own). +public interface IExportDisk +{ + /// Bytes free for Febe on the disk of ; null when it cannot be measured. + long? FreeBytes(string root); + + /// The largest file the file system accepts (FAT32: 4 GB − 1); null when there is no known limit. + long? MaxFileBytes(string root); +} + +/// Limits of the space check before each copy (spec §4.10 «Spazio»). +public static class ExportSpace +{ + /// The margin left free after the next file (decision of Alberto, question Q6 of tappa E2): 64 MiB. + public const long Margin = 64L * 1024 * 1024; + + /// The largest file on FAT32: 4 GiB − 1 byte. + public const long Fat32Limit = (4L * 1024 * 1024 * 1024) - 1; + + private static readonly HashSet FatTypes = new(StringComparer.OrdinalIgnoreCase) { "FAT32", "FAT", "vfat", "msdos", "fat" }; + + /// True for the names Windows (DriveFormat) and Linux (mount type) give to FAT file systems. + public static bool IsFat(string? fileSystem) => fileSystem is not null && FatTypes.Contains(fileSystem); +} + +/// +/// The real disks: free space through (a UNC share gives null: the Windows edition +/// registers its own measure), the FAT32 limit from the drive format on Windows and from the mount type on Linux. +/// +public sealed class SystemExportDisk(IExportMounts mounts) : IExportDisk +{ + private readonly IExportMounts _mounts = mounts ?? throw new ArgumentNullException(nameof(mounts)); + + public long? FreeBytes(string root) + { + if (string.IsNullOrWhiteSpace(root)) + { + return null; + } + + try + { + return new DriveFreeSpaceProbe().Measure(root)?.AvailableBytes; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) + { + return null; + } + } + + public long? MaxFileBytes(string root) + { + if (string.IsNullOrWhiteSpace(root)) + { + return null; + } + + try + { + string? type; + if (OperatingSystem.IsWindows()) + { + var drive = Path.GetPathRoot(Path.GetFullPath(root)); + type = string.IsNullOrEmpty(drive) || drive.StartsWith(@"\\", StringComparison.Ordinal) ? null : new DriveInfo(drive).DriveFormat; + } + else + { + type = _mounts.FindContaining(Path.GetFullPath(root))?.FileSystemType; + } + + return ExportSpace.IsFat(type) ? ExportSpace.Fat32Limit : null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException or System.Security.SecurityException) + { + return null; + } + } +} diff --git a/src/Febe.Core/Export/ExportEnvironment.cs b/src/Febe.Core/Export/ExportEnvironment.cs new file mode 100644 index 0000000..703aec2 --- /dev/null +++ b/src/Febe.Core/Export/ExportEnvironment.cs @@ -0,0 +1,144 @@ +using System.Security.Cryptography; +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Core.Storage; + +namespace Febe.Core.Export; + +/// +/// What the export needs from the rest of Febe (spec §4.10). Built once by the composition (the web layer's export +/// hub); the layout is a function because on Windows the library folder can change while Febe runs. +/// +public sealed record ExportEnvironment +{ + public required IFebeStorage Storage { get; init; } + + /// The library folder and account folders now. + public required Func Layout { get; init; } + + /// The Data folder: a destination may not overlap it. + public required string DataFolder { get; init; } + + public required IClock Clock { get; init; } + + /// Docker /importa: a destination may not overlap it. Null on Windows. + public string? ImportRoot { get; init; } + + /// Where destinations may be chosen (Docker: /esporta). + public ExportRootOptions Root { get; init; } = ExportRootOptions.AnyFolder; + + /// + /// The full path of a library file present on disk, or null. Null: the library layout (as the web layer's + /// LibraryFileResolver). Use . + /// + public Func? ResolveSource { get; init; } + + /// Reading and hashing files (library files and files found in a destination). + public IExportFileSystem FileSystem { get; init; } = ExportFileSystem.Instance; + + /// Free space and the FAT32 limit of a destination. + public IExportDisk Disk { get; init; } = new SystemExportDisk(new ProcMountInfo()); + + /// Copies never run during an engine session. + public IEngineSessionState Session { get; init; } = NoEngineSession.Instance; + + /// Shared with import and rebuild: never together (spec §4.10). Null: nothing else to keep out (tests). + public LongWorkGate? Gate { get; init; } + + /// Time allowed to a check of a destination folder (a disconnected share must not block). + public TimeSpan FolderCheckTimeout { get; init; } = TimeSpan.FromSeconds(10); + + /// How often a waiting job looks whether the engine session ended. + public TimeSpan SessionPoll { get; init; } = TimeSpan.FromSeconds(5); + + /// A group of copies, checked with a probe before it starts: at most this many files… + public int GroupFiles { get; init; } = 100; + + /// …or this many planned bytes, whichever comes first. + public long GroupBytes { get; init; } = 1L << 30; + + /// The checker of destination folders of this environment. + public ExportFolderCheck CreateFolderCheck() => new(Root.Mounts, FolderCheckTimeout); + + /// The protected folders now (Data, library, account folders, /importa) and the extra ones. + public Task FolderContextAsync(IReadOnlyList? extra, CancellationToken ct) => + ExportFolderCheck.ContextAsync(Storage, Layout(), DataFolder, ImportRoot, Root, extra, ct); + + /// The full path of a library file present on disk, or null ( or the layout). + public string? ResolveSourcePath(Account account, Media media) + { + ArgumentNullException.ThrowIfNull(account); + ArgumentNullException.ThrowIfNull(media); + if (ResolveSource is { } resolve) + { + return resolve(account, media); + } + + if (media.RelativePath is null || !EntryStateRules.IsPresent(media.State)) + { + return null; + } + + try + { + var path = Layout().FullPath(account, media.RelativePath); + return FileSystem.FileExists(path) ? path : null; + } + catch (ArgumentException) + { + return null; + } + } +} + +/// File operations of the export (a seam, like IImportFileSystem). +public interface IExportFileSystem +{ + /// Opens a file for reading only. + Stream OpenRead(string path); + + /// SHA-256 (lowercase hex) of a file as it is on disk now. + Task ComputeSha256Async(string path, CancellationToken ct); + + bool FileExists(string path); + + /// Size of a file, or null when it is not there. + long? FileLength(string path); +} + +/// The real file system. +public sealed class ExportFileSystem : IExportFileSystem +{ + private const int BufferSize = 128 * 1024; + + private ExportFileSystem() + { + } + + public static ExportFileSystem Instance { get; } = new(); + + public Stream OpenRead(string path) => + new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan); + + public async Task ComputeSha256Async(string path, CancellationToken ct) + { + await using var stream = OpenRead(path); + return Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false)); + } + + public bool FileExists(string path) => File.Exists(path); + + public long? FileLength(string path) + { + try + { + var info = new FileInfo(path); + return info.Exists ? info.Length : null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException) + { + return null; + } + } +} diff --git a/src/Febe.Core/Export/ExportFolderCheck.cs b/src/Febe.Core/Export/ExportFolderCheck.cs new file mode 100644 index 0000000..fa7a4e3 --- /dev/null +++ b/src/Febe.Core/Export/ExportFolderCheck.cs @@ -0,0 +1,389 @@ +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Core.Storage; + +namespace Febe.Core.Export; + +/// Why a folder cannot be a destination (spec §4.10 «Cartelle rifiutate»). +public enum ExportFolderProblemKind +{ + Empty, + NotFullyQualified, + OutsideExportRoot, + ExportRootItself, + ParentSegment, + NotMounted, + ReadOnlyMount, + Missing, + NotAFolder, + Link, + RootOfDisk, + PathTooLong, + InsideProtected, + ContainsProtected, + SameAsProtected, + ProbeFailed, + NotResponding, +} + +/// A refused folder: the kind and the Italian message that says why and what to do. +public sealed record ExportFolderProblem(ExportFolderProblemKind Kind, string Message) +{ + /// The folder overlaps Data, Libreria, an account folder or /importa (the conflicts of a re-check). + public bool IsOverlap => Kind is ExportFolderProblemKind.InsideProtected or ExportFolderProblemKind.ContainsProtected or ExportFolderProblemKind.SameAsProtected; +} + +/// The outcome of a folder check. +/// The full path of the candidate (as typed when it could not be resolved). +/// Null when the folder is accepted. +public sealed record ExportFolderVerdict(string FullPath, ExportFolderProblem? Problem) +{ + public bool Accepted => Problem is null; +} + +/// What a protected folder is. +public enum ProtectedFolderKind +{ + /// The Data folder. + Data, + + /// The library folder. + Library, + + /// The folder of an account (inside the library or outside it). + Account, + + /// The root of the import sources (Docker /importa). + Import, +} + +/// A folder a destination may neither be, sit inside nor contain. +/// Full path. +/// What it is (for the message). +/// The account of an account folder, when known. +public sealed record ProtectedFolder(string Path, ProtectedFolderKind Kind, string? Username) +{ + /// «la cartella dei dati di Febe», «la cartella dell'account @x»… + public string Description => Kind switch + { + ProtectedFolderKind.Data => "la cartella dei dati di Febe", + ProtectedFolderKind.Library => "la cartella della libreria", + ProtectedFolderKind.Import => "la cartella delle importazioni", + _ => Username is { Length: > 0 } name ? $"la cartella dell'account @{name}" : "la cartella di un account", + }; +} + +/// The folders a candidate is checked against, and where destinations may be chosen. +public sealed record ExportFolderContext(IReadOnlyList Protected, ExportRootOptions Root); + +/// A folder or path that cannot be used as a destination; the message (Italian) says why. The API answers 400. +public sealed class ExportFolderException : IOException +{ + public ExportFolderException() + { + } + + public ExportFolderException(string message) + : base(message) + { + } + + public ExportFolderException(string message, Exception innerException) + : base(message, innerException) + { + } + + public ExportFolderException(string message, ExportFolderProblemKind kind) + : base(message) => Kind = kind; + + /// The kind of refusal, when known. + public ExportFolderProblemKind? Kind { get; } +} + +/// +/// Checks a candidate destination folder (spec §4.10, decision D13 of tappa E2): textual checks first, then the +/// identity test with a probe file written and removed only in the candidate, so that a drive letter and a UNC +/// path to the same place are recognised. In Data, Libreria, the account folders and /importa the probe is only +/// looked for, read-only. Everything that touches the disk runs in the background with a timeout (10 s by default): a +/// disconnected share never blocks the caller. +/// +public sealed class ExportFolderCheck(IExportMounts mounts, TimeSpan? timeout = null) +{ + /// Prefix of the probe file (a temporary file of : .febe-prova-*.part). + public const string ProbePrefix = SafeFileWriter.TempPrefix + "prova-"; + + private readonly IExportMounts _mounts = mounts ?? throw new ArgumentNullException(nameof(mounts)); + private readonly TimeSpan _timeout = timeout ?? TimeSpan.FromSeconds(10); + + /// A new probe file name: .febe-prova-<12 hex>.part. + public static string NewProbeName() => ProbePrefix + Guid.NewGuid().ToString("N")[..12] + SafeFileWriter.TempSuffix; + + /// + /// The protected folders: Data, the library, the folder of every account (outside the library too), the extra + /// folders (an account folder or a library root about to be saved) and the import root. + /// + public static async Task ContextAsync( + IFebeStorage storage, + LibraryLayout layout, + string dataFolder, + string? importRoot, + ExportRootOptions root, + IReadOnlyList? extra = null, + CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(storage); + ArgumentNullException.ThrowIfNull(layout); + ArgumentException.ThrowIfNullOrWhiteSpace(dataFolder); + ArgumentNullException.ThrowIfNull(root); + var folders = new List + { + new(Full(dataFolder), ProtectedFolderKind.Data, null), + new(Full(layout.Root), ProtectedFolderKind.Library, null), + }; + foreach (var account in await storage.Accounts.ListAsync(ct).ConfigureAwait(false)) + { + string folder; + try + { + folder = Full(layout.AccountFolder(account)); + } + catch (ArgumentException) + { + continue; // an unusable stored folder protects nothing + } + + folders.Add(new ProtectedFolder(folder, ProtectedFolderKind.Account, account.Username)); + } + + foreach (var folder in extra ?? []) + { + folders.Add(folder with { Path = Full(folder.Path) }); + } + + if (importRoot is { Length: > 0 }) + { + folders.Add(new ProtectedFolder(Full(importRoot), ProtectedFolderKind.Import, null)); + } + + return new ExportFolderContext(folders, root); + } + + /// + /// Checks . Never throws for a refused folder (the verdict says why); only + /// cancels it. + /// + public async Task CheckAsync(string candidate, ExportFolderContext context, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(context); + if (string.IsNullOrWhiteSpace(candidate)) + { + return new ExportFolderVerdict(candidate ?? string.Empty, new ExportFolderProblem(ExportFolderProblemKind.Empty, "Scegli la cartella in cui copiare i file.")); + } + + string full; + try + { + full = ExportRoots.Resolve(context.Root, candidate); + } + catch (ExportFolderException ex) + { + return new ExportFolderVerdict(candidate, new ExportFolderProblem(ex.Kind ?? ExportFolderProblemKind.NotFullyQualified, ex.Message)); + } + + try + { + return await Task.Run(() => CheckOnDisk(full, context, ct), ct).WaitAsync(_timeout, ct).ConfigureAwait(false); + } + catch (TimeoutException) + { + return new ExportFolderVerdict(full, new ExportFolderProblem( + ExportFolderProblemKind.NotResponding, + $"La cartella non risponde entro {_timeout.TotalSeconds:0} secondi: controlla che il disco o la condivisione siano collegati, poi riprova.")); + } + } + + private ExportFolderVerdict CheckOnDisk(string full, ExportFolderContext context, CancellationToken ct) + { + var o = context.Root; + var shown = ExportRoots.DisplayPath(o, full); + ExportFolderVerdict Refuse(ExportFolderProblemKind kind, string message) => new(full, new ExportFolderProblem(kind, message)); + + if (ExportRoots.MountCheck(o, full) is { } mountProblem) + { + return new ExportFolderVerdict(full, mountProblem); + } + + if (File.Exists(full)) + { + return Refuse(ExportFolderProblemKind.NotAFolder, $"{shown} è un file: scegli una cartella."); + } + + if (!Directory.Exists(full)) + { + return Refuse( + ExportFolderProblemKind.Missing, + $"La cartella {shown} non esiste. Febe non crea mai la cartella di una destinazione: creala tu, o collega il disco, poi sceglila di nuovo."); + } + + if (o.Root is not null && new DirectoryInfo(full).LinkTarget is not null) + { + return Refuse(ExportFolderProblemKind.Link, "La cartella scelta è un collegamento: scegli la cartella a cui punta."); + } + + if (IsRootOfDisk(full)) + { + return Refuse( + ExportFolderProblemKind.RootOfDisk, + $"{shown} è la radice di un disco o di una condivisione: scegli una sua cartella, così i file di Febe non si mescolano al resto."); + } + + try + { + WindowsFileNames.FitPath(full, ["x"]); + } + catch (PathTooLongException) + { + return Refuse( + ExportFolderProblemKind.PathTooLong, + $"Il percorso di {shown} è troppo lungo: i nomi dei file non ci starebbero nei {WindowsFileNames.MaxPathLength} caratteri. Scegli una cartella con un percorso più corto."); + } + + // Textual overlap first: it needs no write. + foreach (var folder in context.Protected) + { + if (Overlap(full, folder.Path, shown, folder) is { } problem) + { + return new ExportFolderVerdict(full, problem); + } + } + + ct.ThrowIfCancellationRequested(); + return ProbeIdentity(full, shown, context.Protected); + } + + private static ExportFolderProblem? Overlap(string full, string protectedPath, string shown, ProtectedFolder folder) + { + if (ExportPaths.Same(full, protectedPath)) + { + return Same(shown, folder); + } + + if (ExportPaths.IsSameOrInside(full, protectedPath)) + { + return Inside(shown, folder); + } + + return ExportPaths.IsSameOrInside(protectedPath, full) ? Contains(shown, folder) : null; + } + + private static ExportFolderProblem Same(string shown, ProtectedFolder folder) => + new(ExportFolderProblemKind.SameAsProtected, $"{shown} è {folder.Description}: scegli un'altra cartella."); + + private static ExportFolderProblem Inside(string shown, ProtectedFolder folder) => + new(ExportFolderProblemKind.InsideProtected, $"{shown} è dentro {folder.Description}: scegli una cartella fuori."); + + private static ExportFolderProblem Contains(string shown, ProtectedFolder folder) => + new(ExportFolderProblemKind.ContainsProtected, $"{shown} contiene {folder.Description}: scegli una cartella che non la contenga."); + + /// + /// The identity test of spec §4.10: a probe written in the candidate only, then looked for (never written) up the + /// parents of each protected folder (the candidate contains it, or is it) and, for each parent of the candidate, at the + /// same relative path under each protected folder (the candidate is inside it). + /// + private static ExportFolderVerdict ProbeIdentity(string full, string shown, IReadOnlyList protectedFolders) + { + var name = NewProbeName(); + var probe = Path.Combine(full, name); + try + { + try + { + using var stream = new FileStream(probe, FileMode.CreateNew, FileAccess.Write, FileShare.None); + stream.Write("Febe"u8); + stream.Flush(flushToDisk: true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + var reason = ex is UnauthorizedAccessException ? "accesso negato" : ex.Message; + return new ExportFolderVerdict(full, new ExportFolderProblem( + ExportFolderProblemKind.ProbeFailed, + $"Febe non riesce a scrivere in {shown} ({reason}): controlla i permessi o che il disco non sia in sola lettura.")); + } + + foreach (var folder in protectedFolders) + { + // (a) The candidate is the protected folder, or one of its parents, under another name. + for (var ancestor = folder.Path; ancestor is not null; ancestor = Path.GetDirectoryName(ancestor)) + { + if (Exists(Path.Combine(ancestor, name))) + { + var problem = ExportPaths.Same(ancestor, folder.Path) ? Same(shown, folder) : Contains(shown, folder); + return new ExportFolderVerdict(full, problem); + } + } + } + + // (b) The candidate is inside a protected folder under another name: for each parent M of the candidate, + // the probe would appear at F/ for the protected folder F that is M. + for (var parent = Path.GetDirectoryName(full); parent is not null; parent = Path.GetDirectoryName(parent)) + { + var relative = Path.GetRelativePath(parent, full); + foreach (var folder in protectedFolders) + { + if (Exists(Path.Combine(folder.Path, relative, name))) + { + return new ExportFolderVerdict(full, Inside(shown, folder)); + } + } + } + + return new ExportFolderVerdict(full, null); + } + finally + { + try + { + File.Delete(probe); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Best effort: a probe left behind is a temporary file of Febe, harmless. + } + } + } + + private static bool Exists(string path) + { + try + { + return File.Exists(path); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException) + { + return false; + } + } + + /// + /// Decision D15: on Windows the path is its own root (C:\, \\srv\share); on Linux it is / or + /// exactly a mount point that shows the root of its file system. + /// + private bool IsRootOfDisk(string full) + { + if (OperatingSystem.IsWindows()) + { + var root = Path.GetPathRoot(full); + return !string.IsNullOrEmpty(root) && ExportPaths.Same(root, full); + } + + if (full == "/") + { + return true; + } + + var mount = _mounts.FindContaining(full); + return mount is not null && string.Equals(ExportPaths.Trim(mount.MountPoint), full, StringComparison.Ordinal) && mount.Root == "/"; + } + + private static string Full(string path) => ExportPaths.Trim(Path.GetFullPath(path)); +} diff --git a/src/Febe.Core/Export/ExportLeftovers.cs b/src/Febe.Core/Export/ExportLeftovers.cs new file mode 100644 index 0000000..8e6ea22 --- /dev/null +++ b/src/Febe.Core/Export/ExportLeftovers.cs @@ -0,0 +1,89 @@ +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Core.Storage; + +namespace Febe.Core.Export; + +/// +/// The .part files a crash left in a destination (spec §4.10): removed only in the folders where the items of +/// an unfinished job were to be written, never by a scan of the destination, never in a folder of no item. Only our +/// own temporary names (.febe-*.part, the probes included) are touched. +/// +public static class ExportLeftovers +{ + private const int PageSize = 1000; + + /// Removes our temporary files in the folders of the items of . Returns how many. + public static async Task CleanAsync(ExportEnvironment env, ExportRun run, ExportDestination destination, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(env); + ArgumentNullException.ThrowIfNull(run); + ArgumentNullException.ThrowIfNull(destination); + if (ExportRoots.MountProblem(env.Root, destination.RootPath) is not null || !await AnswersAsync(env, destination.RootPath, ct).ConfigureAwait(false)) + { + return 0; + } + + var folders = new HashSet(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + long after = 0; + while (true) + { + var page = await env.Storage.Exports.ListItemsAsync(new ExportItemQuery { RunId = run.Id, AfterId = after, Limit = PageSize }, ct).ConfigureAwait(false); + if (page.Count == 0) + { + break; + } + + after = page[^1].Id; + foreach (var item in page) + { + if (item.RelativePath is { } relative && item.State is ExportItemState.Pending or ExportItemState.Failed) + { + try + { + if (Path.GetDirectoryName(LibraryLayout.FullPath(destination.RootPath, relative)) is { } folder) + { + folders.Add(folder); + } + } + catch (ArgumentException) + { + // A path that would leave the root: nothing of ours can be there. + } + } + } + } + + var removed = 0; + foreach (var folder in folders) + { + ct.ThrowIfCancellationRequested(); + try + { + removed += await Task.Run(() => SafeFileWriter.CleanupTemporaryFiles(folder, recursive: false), ct).WaitAsync(env.FolderCheckTimeout, ct).ConfigureAwait(false); + } + catch (TimeoutException) + { + return removed; // the disk stopped answering: the next resume tries again + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Best effort: a leftover .part takes some space, nothing more. + } + } + + return removed; + } + + private static async Task AnswersAsync(ExportEnvironment env, string root, CancellationToken ct) + { + try + { + return await Task.Run(() => Directory.Exists(root), ct).WaitAsync(env.FolderCheckTimeout, ct).ConfigureAwait(false); + } + catch (TimeoutException) + { + return false; + } + } +} diff --git a/src/Febe.Core/Export/ExportModels.cs b/src/Febe.Core/Export/ExportModels.cs new file mode 100644 index 0000000..8c89db3 --- /dev/null +++ b/src/Febe.Core/Export/ExportModels.cs @@ -0,0 +1,114 @@ +using Febe.Core.Domain; +using Febe.Core.Storage; + +namespace Febe.Core.Export; + +/// What a «Copia in…» is asked for (spec §4.10 «Manuale sempre»). +public abstract record ExportSelection +{ + private ExportSelection() + { + } + + /// Files by id: a selection of «Tutte le foto», a file of the viewer. + public sealed record Media(IReadOnlyList MediaIds) : ExportSelection; + + /// Entries by id: a grouped selection, an entry of the viewer. + public sealed record Entries(IReadOnlyList EntryIds) : ExportSelection; + + /// The current filter («Copia i file in…» of the CSV menu). + public sealed record Filter(LibraryFilter LibraryFilter, MosaicMode Mode) : ExportSelection; + + /// Every file of an account (the account card). + public sealed record Account(long AccountId) : ExportSelection; +} + +/// A «Copia in…»: what to copy, whether «Tolti» and «Superati» are copied again (D9), who asked. +public sealed record ExportJobRequest(ExportSelection Selection, bool CopyAgain = false, ExportRunOrigin Origin = ExportRunOrigin.Manual); + +/// +/// What a «Copia in…» would do (database only, decisions D3 and D9 of tappa E2). Each file goes to the effective +/// destination of its account (D5). +/// +/// Files to write. +/// Their bytes. +/// Already in their destination (or, with «Una copia sola», copied for another account). +/// +/// «Tolti o superati»: never copied again by themselves. With they are also +/// counted in and , since they will be written. +/// +/// «Esporta questo account» off, no destination, or a content type the destination does not take. +/// «File non presente in libreria». +/// Each destination that gets files, with whether it answers now. +public sealed record ExportPlan( + int Files, + long Bytes, + int AlreadyCopied, + int RemovedOrSuperseded, + int NotExported, + int Missing, + IReadOnlyList Destinations) +{ + public static ExportPlan Empty { get; } = new(0, 0, 0, 0, 0, 0, []); +} + +/// A destination of a plan. +/// The account of an own folder; null for the general folder. +/// Files to write there. +/// The destination is paused (its last check failed). +/// Why it cannot be written now (not reachable, not mounted, paused), in Italian; null when fine. +/// Free space, when it can be measured. +public sealed record ExportPlanDestination( + long DestinationId, + string Label, + string RootPath, + ExportScope Scope, + string? Username, + int Files, + long Bytes, + bool Paused, + string? Problem, + long? FreeBytes); + +/// What the export job is doing. +public enum ExportPhase +{ + Preparing, + + /// «Controlla le copie». + Checking, + + /// An engine session is running: copies wait for it to end (decision D11). + WaitingForSession, + + Copying, + + Finished, +} + +/// Progress of the export job, for the progress card (polled, D20). +/// The job's run being worked on; null for «Controlla le copie» and when nothing ever ran. +/// Bytes of the files still pending when the run (re)started, plus those done since; 0 when unknown. +public sealed record ExportProgress( + long? RunId, + ExportPhase Phase, + int FilesDone, + int FilesTotal, + long BytesDone, + long BytesTotal, + string? CurrentFile, + string? DestinationLabel, + IReadOnlyDictionary ByState, + DateTimeOffset UpdatedAt) +{ + /// 0..1: by bytes when known, otherwise by files. + public double Fraction => BytesTotal > 0 + ? Math.Clamp((double)BytesDone / BytesTotal, 0, 1) + : FilesTotal > 0 ? Math.Clamp((double)FilesDone / FilesTotal, 0, 1) : 0; +} + +/// What ExportService.StartAsync did: one run per destination (D6), and the plan it followed. +public sealed record ExportStart(IReadOnlyList Runs, ExportPlan Plan); + +/// The export job ended (however it ended): the runs it worked on, and whether copies may have changed. +public sealed record ExportJobFinished(IReadOnlyList RunIds, bool CopiesChanged); diff --git a/src/Febe.Core/Export/ExportNamingPreview.cs b/src/Febe.Core/Export/ExportNamingPreview.cs new file mode 100644 index 0000000..70bbb93 --- /dev/null +++ b/src/Febe.Core/Export/ExportNamingPreview.cs @@ -0,0 +1,35 @@ +using Febe.Core.Domain; +using Febe.Core.Library; + +namespace Febe.Core.Export; + +/// +/// The «Risultato» tree of a destination's naming (spec §4.10 «Nomi dei file»): the library preview rendered with the +/// destination's schemes, «Come la libreria» (null) taking the library's. In the general folder each file sits under +/// its account segment. +/// +public static class ExportNamingPreview +{ + public static NamingPreview Build( + ExportScope scope, + string? general, + string? highlight, + string? profile, + LibraryNaming library, + TimeZoneInfo zone, + string sampleAccount = "nome.utente") + { + ArgumentNullException.ThrowIfNull(library); + var preview = NamingPreview.Build(general ?? library.General.Text, highlight ?? library.Highlight.Text, profile ?? library.ProfilePicture.Text, zone, sampleAccount); + if (scope != ExportScope.General) + { + return preview; + } + + var segment = WindowsFileNames.SanitizeSegment(sampleAccount); + return preview with + { + Folders = preview.Folders.Select(f => f with { Path = [segment, .. f.Path] }).ToList(), + }; + } +} diff --git a/src/Febe.Core/Export/ExportPaths.cs b/src/Febe.Core/Export/ExportPaths.cs new file mode 100644 index 0000000..d085b1f --- /dev/null +++ b/src/Febe.Core/Export/ExportPaths.cs @@ -0,0 +1,145 @@ +using System.Globalization; +using Febe.Core.Domain; +using Febe.Core.Library; + +namespace Febe.Core.Export; + +/// Paths and content types of the export (spec §4.10). +public static class ExportPaths +{ + /// Folders compare without case on Windows (and its shares), exactly elsewhere, as the import does. + public static StringComparison PathComparison { get; } = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + + /// True when is or inside it, as text (full paths). + public static bool IsSameOrInside(string path, string folder) + { + ArgumentNullException.ThrowIfNull(path); + ArgumentNullException.ThrowIfNull(folder); + var p = Trim(path); + var f = Trim(folder); + return string.Equals(p, f, PathComparison) + || p.StartsWith(f.EndsWith(Path.DirectorySeparatorChar) || f.EndsWith(Path.AltDirectorySeparatorChar) ? f : f + Path.DirectorySeparatorChar, PathComparison); + } + + /// The same folder, as text. + public static bool Same(string a, string b) => string.Equals(Trim(a), Trim(b), PathComparison); + + /// A full path without its trailing separator (a root such as C:\ or / keeps it). + public static string Trim(string path) + { + ArgumentNullException.ThrowIfNull(path); + return path.Length > 1 ? Path.TrimEndingDirectorySeparator(path) : path; + } + + /// + /// The content type of a file (decision D4 of tappa E2): a post photo or video, a story (also a highlight when the + /// story is in a collection), a highlight, a tagged post, a profile picture. The «Copie» filter repeats it in SQL. + /// + public static ContentTypes TypeOf(EntryKind kind, MediaKind media, bool inHighlight) => kind switch + { + EntryKind.Post => media == MediaKind.Photo ? ContentTypes.PostPhotos : ContentTypes.PostVideos, + EntryKind.Story => inHighlight ? ContentTypes.Stories | ContentTypes.Highlights : ContentTypes.Stories, + EntryKind.Highlight => ContentTypes.Highlights, + EntryKind.Tagged => ContentTypes.Tagged, + EntryKind.ProfilePicture => ContentTypes.ProfilePicture, + _ => ContentTypes.None, + }; + + /// Folder of imported files without a known date or code (as the import names it). + public const string ImportedFolder = "importati"; + + /// + /// The path of a copy below the destination root, as sanitized segments, before + /// (decision D18 of tappa E2). «Come la libreria» (a null scheme) renders the library's current scheme again, except + /// for a file the import left in importati/, which keeps its path. A story in a highlight collection takes the + /// highlight scheme only when the destination takes highlights and not stories. In the general folder the account + /// segment comes first. + /// + public static IReadOnlyList Segments( + ExportDestination d, + LibraryNaming library, + Account account, + Entry entry, + Media media, + string? highlightTitle, + bool inHighlight, + TimeZoneInfo zone) + { + ArgumentNullException.ThrowIfNull(d); + ArgumentNullException.ThrowIfNull(library); + ArgumentNullException.ThrowIfNull(account); + ArgumentNullException.ThrowIfNull(entry); + ArgumentNullException.ThrowIfNull(media); + ArgumentNullException.ThrowIfNull(zone); + var stored = media.RelativePath is { Length: > 0 } path + ? LibraryLayout.ToStored(path) + : throw new ArgumentException("Il file non è nella libreria: non ha un percorso.", nameof(media)); + + var renderAs = entry.Kind == EntryKind.Story && inHighlight + && d.ContentTypes.HasFlag(ContentTypes.Highlights) && !d.ContentTypes.HasFlag(ContentTypes.Stories) + ? EntryKind.Highlight + : entry.Kind; + var use = UseOf(renderAs); + var text = use switch + { + NamingSchemeUse.Highlight => d.HighlightNamingScheme, + NamingSchemeUse.ProfilePicture => d.ProfileNamingScheme, + _ => d.NamingScheme, + }; + + IReadOnlyList segments; + if (text is null && stored.StartsWith(ImportedFolder + "/", StringComparison.Ordinal)) + { + segments = stored.Split('/', StringSplitOptions.RemoveEmptyEntries).Select(WindowsFileNames.SanitizeSegment).ToList(); + } + else + { + var scheme = (text is null ? null : NamingScheme.Validate(text, use).Scheme) ?? library.For(renderAs); + var extension = Path.GetExtension(stored).TrimStart('.').ToLowerInvariant(); + var values = NamingValues.For( + account.Username, + entry with { Kind = renderAs }, + media.Position, + extension, + renderAs == EntryKind.Highlight ? highlightTitle : null, + media.Sha256); + segments = scheme.Render(values, zone); + } + + return d.Scope == ExportScope.General ? [WindowsFileNames.SanitizeSegment(account.Username), .. segments] : segments; + } + + /// The relative path ('/' separated) of a copy: the segments fitted to the length limit under the root. + /// Even shortened, the path does not fit. + public static string RelativePathFor(ExportDestination d, IReadOnlyList segments, int maxPath = WindowsFileNames.MaxPathLength) + { + ArgumentNullException.ThrowIfNull(d); + return string.Join('/', WindowsFileNames.FitPath(d.RootPath, segments, maxPath)); + } + + /// + /// The name the safe writer gives a file at its -th try when the planned name is taken + /// («nome (2).jpg», «nome (3).jpg», …), so a resumed copy finds a file it renamed before a crash. + /// + public static string NumberedName(string root, string relativePath, int attempt, int maxPath = WindowsFileNames.MaxPathLength) + { + ArgumentException.ThrowIfNullOrWhiteSpace(relativePath); + var segments = LibraryLayout.ToStored(relativePath).Split('/', StringSplitOptions.RemoveEmptyEntries); + if (attempt <= 1) + { + return string.Join('/', segments); + } + + var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]); + var name = WindowsFileNames.SanitizeSegment(string.Create(CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}")); + return string.Join('/', WindowsFileNames.FitPath(root, [.. segments[..^1], name], maxPath)); + } + + /// The scheme that names an entry kind. + public static NamingSchemeUse UseOf(EntryKind kind) => kind switch + { + EntryKind.Highlight => NamingSchemeUse.Highlight, + EntryKind.ProfilePicture => NamingSchemeUse.ProfilePicture, + _ => NamingSchemeUse.General, + }; +} diff --git a/src/Febe.Core/Export/ExportPause.cs b/src/Febe.Core/Export/ExportPause.cs new file mode 100644 index 0000000..cf2fdf6 --- /dev/null +++ b/src/Febe.Core/Export/ExportPause.cs @@ -0,0 +1,70 @@ +using Febe.Core.Domain; + +namespace Febe.Core.Export; + +/// +/// The pause of a destination (spec §4.10): its probe could not be written, it is not reachable, or the disk is full. +/// The state shows in Impostazioni and in the Dashboard and the next check clears it. Never the red strip: the event +/// esportazione-in-pausa is not an alert of the engine. +/// +public static class ExportPause +{ + /// Code of the event written once when a destination goes into pause. + public const string PausedEventCode = "esportazione-in-pausa"; + + /// + /// Pauses a destination with an Italian reason (read-modify-write on the stored row; a retired row is left as it + /// is). The event is written only on the transition from running to paused. Returns the stored row. + /// + public static async Task PauseAsync(ExportEnvironment env, ExportDestination destination, string message) + { + ArgumentNullException.ThrowIfNull(env); + ArgumentNullException.ThrowIfNull(destination); + ArgumentException.ThrowIfNullOrWhiteSpace(message); + var stored = await env.Storage.Exports.GetDestinationAsync(destination.Id, CancellationToken.None).ConfigureAwait(false) ?? destination; + if (stored.IsRetired) + { + return stored; + } + + var wasPaused = stored.PausedAt is not null; + if (wasPaused && string.Equals(stored.LastError, message, StringComparison.Ordinal)) + { + return stored; + } + + var paused = stored with { PausedAt = stored.PausedAt ?? env.Clock.Now, LastError = message }; + await env.Storage.Exports.UpdateDestinationAsync(paused, CancellationToken.None).ConfigureAwait(false); + if (!wasPaused) + { + await env.Storage.Events.AppendAsync( + new EventRecord + { + At = env.Clock.Now, + Code = PausedEventCode, + Severity = EventSeverity.Warning, + Message = $"{ExportDestinations.Label(paused)} in pausa: {message}", + AccountId = paused.AccountId, + }, + CancellationToken.None).ConfigureAwait(false); + } + + return paused; + } + + /// Clears the pause of a destination after a check succeeded. Returns the stored row. + public static async Task ClearAsync(ExportEnvironment env, ExportDestination destination) + { + ArgumentNullException.ThrowIfNull(env); + ArgumentNullException.ThrowIfNull(destination); + var stored = await env.Storage.Exports.GetDestinationAsync(destination.Id, CancellationToken.None).ConfigureAwait(false) ?? destination; + if (stored.IsRetired || (stored.PausedAt is null && stored.LastError is null)) + { + return stored; + } + + var cleared = stored with { PausedAt = null, LastError = null }; + await env.Storage.Exports.UpdateDestinationAsync(cleared, CancellationToken.None).ConfigureAwait(false); + return cleared; + } +} diff --git a/src/Febe.Core/Export/ExportPlanner.cs b/src/Febe.Core/Export/ExportPlanner.cs new file mode 100644 index 0000000..f232110 --- /dev/null +++ b/src/Febe.Core/Export/ExportPlanner.cs @@ -0,0 +1,238 @@ +using System.Runtime.CompilerServices; +using Febe.Core.Domain; +using Febe.Core.Storage; + +namespace Febe.Core.Export; + +/// +/// What a «Copia in…» would do, from the database only (decisions D3, D5 and D9 of tappa E2): each file goes to the +/// effective destination of its account; a file already copied there is «già copiato»; «Tolti» and «Superati» are +/// skipped unless «Copia di nuovo» was asked. The only look at a destination is whether it answers, for the dialog. +/// +public sealed class ExportPlanner(ExportEnvironment env) +{ + private const int PageSize = 2000; + + private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env)); + + /// The plan of a request, for the «Copia in…» dialog. + public async Task PlanAsync(ExportJobRequest request, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(request); + var destinations = new ExportDestinations(_env); + var effective = await destinations.ResolveAllAsync(ct).ConfigureAwait(false); + var settings = await ExportSettings.LoadAsync(_env.Storage.Settings, ct).ConfigureAwait(false); + var tally = new PlanTally(); + await foreach (var file in EnumerateAsync(request, effective, settings, ct).ConfigureAwait(false)) + { + tally.Add(file); + } + + return await tally.BuildAsync(_env, destinations, effective, checkDestinations: true, ct).ConfigureAwait(false); + } + + /// + /// Every candidate of the request with what to do with it, in media id order. Within one plan the same file of an + /// account in one destination counts once (a story and its highlight entry, two files with the same bytes); with + /// «Una copia sola» the same file counts once across accounts. + /// + internal async IAsyncEnumerable EnumerateAsync( + ExportJobRequest request, + IReadOnlyDictionary effective, + ExportSettings settings, + [EnumeratorCancellation] CancellationToken ct) + { + var exports = _env.Storage.Exports; + var oneOnly = settings.SamePost == SamePostCopies.OneOnly; + var seen = new HashSet<(long Destination, long Account, string Sha256)>(); + long after = 0; + while (true) + { + var page = await exports.ListCandidatesAsync(request.Selection, after, PageSize, ct).ConfigureAwait(false); + if (page.Count == 0) + { + yield break; + } + + after = page[^1].MediaId; + var keys = new Dictionary>(); + foreach (var c in page) + { + if (Due(c, effective) is { } destination) + { + if (!keys.TryGetValue(destination, out var set)) + { + keys[destination] = set = []; + } + + set.Add((c.AccountId, c.Sha256!)); + } + } + + var states = new Dictionary>(); + foreach (var (destination, set) in keys) + { + states[destination] = await exports.GetCopyStatesAsync(destination, set, ct).ConfigureAwait(false); + } + + foreach (var c in page) + { + if (!IsPresent(c)) + { + yield return new PlannedFile(c, null, PlannedCopy.Missing); + continue; + } + + if (Due(c, effective) is not { } destination) + { + yield return new PlannedFile(c, null, PlannedCopy.NotExported); + continue; + } + + var sha = c.Sha256!; + var key = oneOnly ? (0L, 0L, sha) : (destination, c.AccountId, sha); + var state = states[destination].TryGetValue((c.AccountId, sha), out var s) ? s : (ExportCopyState?)null; + PlannedFile planned; + if (state == ExportCopyState.Copied) + { + planned = new PlannedFile(c, destination, PlannedCopy.AlreadyCopied); + } + else if (state is ExportCopyState.Removed or ExportCopyState.Superseded) + { + planned = request.CopyAgain + ? new PlannedFile(c, destination, PlannedCopy.Write, Again: true) + : new PlannedFile(c, destination, PlannedCopy.RemovedOrSuperseded); + } + else if (oneOnly && await exports.FindCopiedElsewhereAsync(sha, ExportVariant.Whole, ExportFormat.Original, ct).ConfigureAwait(false) is { } other + && other.AccountId != c.AccountId) + { + planned = new PlannedFile(c, destination, PlannedCopy.AlreadyCopied); + } + else + { + planned = new PlannedFile(c, destination, PlannedCopy.Write); + } + + if (planned.Action is PlannedCopy.Write or PlannedCopy.AlreadyCopied && !seen.Add(key)) + { + planned = planned with { Action = PlannedCopy.AlreadyCopied, Again = false }; + } + + yield return planned; + } + } + } + + /// A file present in the library, with its SHA-256 and path. + internal static bool IsPresent(ExportCandidate c) => EntryStateRules.IsPresent(c.State) && c.Sha256 is { Length: 64 } && !string.IsNullOrEmpty(c.RelativePath); + + /// The destination a present file goes to (D3), or null when it is not exported. + private static long? Due(ExportCandidate c, IReadOnlyDictionary effective) => + IsPresent(c) && effective.TryGetValue(c.AccountId, out var e) && e.Wants(ExportPaths.TypeOf(c.EntryKind, c.MediaKind, c.InHighlight)) + ? e.Destination!.Id + : null; +} + +/// A candidate with what the plan does with it. +/// Where it goes; null when not exported or missing. +/// Written although «Tolto» or «Superato», because «Copia di nuovo» was asked. +internal sealed record PlannedFile(ExportCandidate Candidate, long? DestinationId, PlannedCopy Action, bool Again = false); + +internal enum PlannedCopy +{ + Write, + AlreadyCopied, + RemovedOrSuperseded, + NotExported, + Missing, +} + +/// Counts of a plan while its files go by. +internal sealed class PlanTally +{ + private readonly Dictionary _byDestination = []; + + public int Files { get; private set; } + + public long Bytes { get; private set; } + + public int AlreadyCopied { get; private set; } + + public int RemovedOrSuperseded { get; private set; } + + public int NotExported { get; private set; } + + public int Missing { get; private set; } + + public void Add(PlannedFile file) + { + switch (file.Action) + { + case PlannedCopy.Missing: + Missing++; + return; + case PlannedCopy.NotExported: + NotExported++; + return; + case PlannedCopy.AlreadyCopied: + AlreadyCopied++; + break; + case PlannedCopy.RemovedOrSuperseded: + RemovedOrSuperseded++; + break; + case PlannedCopy.Write: + var bytes = file.Candidate.Bytes ?? 0; + Files++; + Bytes += bytes; + if (file.Again) + { + RemovedOrSuperseded++; + } + + var (f, b) = _byDestination.GetValueOrDefault(file.DestinationId!.Value); + _byDestination[file.DestinationId.Value] = (f + 1, b + bytes); + return; + } + + _byDestination.TryAdd(file.DestinationId!.Value, (0, 0)); + } + + /// The plan. With each destination is asked whether it answers now. + public async Task BuildAsync( + ExportEnvironment env, + ExportDestinations destinations, + IReadOnlyDictionary effective, + bool checkDestinations, + CancellationToken ct) + { + var rows = effective.Values.Where(e => e.Destination is not null).Select(e => e.Destination!).DistinctBy(d => d.Id).ToDictionary(d => d.Id); + var accounts = (await env.Storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id, a => a.Username); + var list = new List(); + foreach (var (id, (files, bytes)) in _byDestination.OrderBy(d => rows.TryGetValue(d.Key, out var r) && r.Scope == ExportScope.General ? 0 : 1).ThenBy(d => d.Key)) + { + var d = rows.TryGetValue(id, out var row) ? row : await env.Storage.Exports.GetDestinationAsync(id, ct).ConfigureAwait(false); + if (d is null) + { + continue; + } + + string? problem = null; + long? free = null; + if (checkDestinations) + { + var status = await destinations.StatusAsync(id, ct).ConfigureAwait(false); + problem = status.Problem; + free = status.FreeBytes; + } + + problem ??= d.PausedAt is not null ? d.LastError : null; + var username = d.AccountId is { } a ? accounts.GetValueOrDefault(a) : null; + list.Add(new ExportPlanDestination(d.Id, ExportDestinations.Label(d), d.RootPath, d.Scope, username, files, bytes, d.PausedAt is not null, problem, free)); + } + + return new ExportPlan(Files, Bytes, AlreadyCopied, RemovedOrSuperseded, NotExported, Missing, list); + } + + /// Destinations that get a run: those with files to write, already copied, or «tolti o superati». + public IReadOnlyCollection Destinations => _byDestination.Keys; +} diff --git a/src/Febe.Core/Export/ExportReports.cs b/src/Febe.Core/Export/ExportReports.cs new file mode 100644 index 0000000..c8bc328 --- /dev/null +++ b/src/Febe.Core/Export/ExportReports.cs @@ -0,0 +1,106 @@ +using Febe.Core.Domain; +using Febe.Core.Storage; + +namespace Febe.Core.Export; + +/// The report of an export job (spec §4.10): counts, per account, and the files that need a look. +/// At most lines: failed, missing, and skipped files with a note. +public sealed record ExportReport( + ExportRun Run, + ExportDestination Destination, + int Total, + IReadOnlyDictionary ByState, + long BytesCopied, + IReadOnlyList Accounts, + IReadOnlyList Problems); + +/// The files of one account in a job («Copiato» counts written and adopted files). +public sealed record ExportReportAccount(long? AccountId, string Username, int Copied, int AlreadyCopied, int Skipped, int Failed); + +/// A file of the report, with its reason in Italian. +public sealed record ExportReportLine(long ItemId, string Username, string? RelativePath, ExportItemState State, string Text); + +/// Builds the report of a job from the database (no CSV in E2: §4.10 leaves «Copiato in» in the CSV out of 0.3.0). +public sealed class ExportReports(ExportEnvironment env) +{ + public const int MaxProblems = 200; + + private const int PageSize = 1000; + + /// A name for files whose account was removed. + public const string RemovedAccount = "account rimosso"; + + private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env)); + + /// No such job. + public async Task BuildAsync(long runId, CancellationToken ct = default) + { + var exports = _env.Storage.Exports; + var run = await exports.GetRunAsync(runId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Lavoro di copia {runId} non trovato."); + var destination = await exports.GetDestinationAsync(run.DestinationId, ct).ConfigureAwait(false) + ?? throw new KeyNotFoundException($"Destinazione di esportazione {run.DestinationId} non trovata."); + var summary = await exports.GetRunSummaryAsync(runId, ct).ConfigureAwait(false); + var names = (await _env.Storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id, a => a.Username); + string Name(long? id) => id is { } a && names.TryGetValue(a, out var n) ? n : RemovedAccount; + + var accounts = new Dictionary(); + var problems = new List(); + long bytes = 0; + long after = 0; + while (true) + { + var page = await exports.ListItemsAsync(new ExportItemQuery { RunId = runId, AfterId = after, Limit = PageSize }, ct).ConfigureAwait(false); + if (page.Count == 0) + { + break; + } + + after = page[^1].Id; + foreach (var item in page) + { + var key = item.AccountId ?? 0; + if (!accounts.TryGetValue(key, out var row)) + { + accounts[key] = row = new int[4]; + } + + switch (item.State) + { + case ExportItemState.Copied or ExportItemState.Adopted: + row[0]++; + if (item.CopyId is { } copyId && await exports.GetCopyAsync(copyId, ct).ConfigureAwait(false) is { Bytes: { } b }) + { + bytes += b; + } + + break; + case ExportItemState.AlreadyCopied: + row[1]++; + break; + case ExportItemState.Skipped or ExportItemState.Missing: + row[2]++; + break; + case ExportItemState.Failed: + row[3]++; + break; + } + + var problem = item.State is ExportItemState.Failed or ExportItemState.Missing + || (item.State == ExportItemState.Skipped && item.Note is not null); + if (problem && problems.Count < MaxProblems) + { + var text = item.State == ExportItemState.Failed + ? item.LastError ?? ExportText.Note(item.Note) ?? ExportText.State(item.State) + : ExportText.Note(item.Note) ?? ExportText.State(item.State); + problems.Add(new ExportReportLine(item.Id, Name(item.AccountId), item.RelativePath, item.State, text)); + } + } + } + + var perAccount = accounts + .Select(a => new ExportReportAccount(a.Key == 0 ? null : a.Key, Name(a.Key == 0 ? null : a.Key), a.Value[0], a.Value[1], a.Value[2], a.Value[3])) + .OrderBy(a => a.Username, StringComparer.OrdinalIgnoreCase) + .ToList(); + return new ExportReport(run, destination, summary.Total, summary.ByState, bytes, perAccount, problems); + } +} diff --git a/src/Febe.Core/Export/ExportRoot.cs b/src/Febe.Core/Export/ExportRoot.cs new file mode 100644 index 0000000..2f2eacd --- /dev/null +++ b/src/Febe.Core/Export/ExportRoot.cs @@ -0,0 +1,269 @@ +using Febe.Core.Import; +using Febe.Core.Library; + +namespace Febe.Core.Export; + +/// A mounted file system, as the export needs it (spec §4.10 «Docker e Windows»). +/// Where it is mounted. +/// Folder of its file system shown there (/: the root of that file system). +/// File system type (vfat for FAT32). +/// Mounted read-only. +public sealed record ExportMount(string MountPoint, string Root, string FileSystemType, bool ReadOnly); + +/// The mount table (a seam: tests give their own; Linux reads /proc/self/mountinfo). +public interface IExportMounts +{ + /// The mount that holds a full path, or null (always null on Windows). + ExportMount? FindContaining(string fullPath); + + /// Every mount (empty on Windows). + IReadOnlyList All(); +} + +/// The mounts of this process from /proc/self/mountinfo, read at each call (it is small). +public sealed class ProcMountInfo(Func? read = null) : IExportMounts +{ + private readonly Func _read = read ?? MountInfoTable.ReadProcSelf; + + public ExportMount? FindContaining(string fullPath) + { + ArgumentNullException.ThrowIfNull(fullPath); + var mounts = Read(); + return mounts.Count == 0 ? null : Map(MountInfoTable.FindContaining(mounts, fullPath)); + } + + public IReadOnlyList All() => Read().Select(m => Map(m)!).ToList(); + + private IReadOnlyList Read() + { + try + { + return _read() is { } content ? MountInfoTable.Parse(content) : []; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return []; + } + } + + private static ExportMount? Map(MountInfoEntry? m) => m is null ? null : new ExportMount(m.MountPoint, m.Root, m.FileSystemType, m.ReadOnly); +} + +/// +/// Where destinations may be chosen. Docker: subfolders of /esporta, only when it is declared +/// (--esporta, FEBE_ESPORTA) and the destination sits on a mount at /esporta or below it (decision of +/// Alberto, question Q2 of tappa E2). Windows: any folder, through the native picker. +/// +public sealed record ExportRootOptions +{ + /// Docker: the full path of /esporta. Null: any folder. + public string? Root { get; init; } + + /// --esporta or FEBE_ESPORTA (always true without a root). + public bool Declared { get; init; } + + /// The mount table. + public IExportMounts Mounts { get; init; } = new ProcMountInfo(); + + /// Windows (and development): any folder. + public static ExportRootOptions AnyFolder { get; } = new() { Declared = true }; + + /// Docker: destinations under . + public static ExportRootOptions Docker(string root, bool declared, IExportMounts? mounts = null) + { + ArgumentException.ThrowIfNullOrWhiteSpace(root); + return new ExportRootOptions { Root = ExportPaths.Trim(Path.GetFullPath(root)), Declared = declared, Mounts = mounts ?? new ProcMountInfo() }; + } +} + +/// Whether copies to external folders can be written at all, and why not. +/// True: destinations may be created and written. +/// Docker: the root (/esporta); null on Windows. +/// Italian text of the reason when not active. +public sealed record ExportRootState(bool Active, string? Root, string? Problem); + +/// The rules of the export root (spec §4.10, §11): /esporta in Docker, any folder on Windows. +public static class ExportRoots +{ + /// Copies to external folders are switched off in Docker (not declared). + public const string NotDeclaredText = + "Le copie esterne in Docker sono spente: si accendono con FEBE_ESPORTA=1 (o --esporta) e una cartella del server montata su /esporta."; + + /// Whether the root is usable: always without a root; in Docker declared and with a mount at or below it. + public static ExportRootState Evaluate(ExportRootOptions o) + { + ArgumentNullException.ThrowIfNull(o); + if (o.Root is not { } root) + { + return new ExportRootState(true, null, null); + } + + if (!o.Declared) + { + return new ExportRootState(false, root, NotDeclaredText); + } + + return o.Mounts.All().Any(m => ExportPaths.IsSameOrInside(ExportPaths.Trim(m.MountPoint), root)) + ? new ExportRootState(true, root, null) + : new ExportRootState(false, root, NotMountedText(o)); + } + + /// + /// Null when a destination may be written as far as the mounts are concerned (always on Windows); otherwise the + /// Italian reason: not declared, not on a mount at or below the root, or a read-only mount. + /// + public static string? MountProblem(ExportRootOptions o, string destinationFullPath) => MountCheck(o, destinationFullPath)?.Message; + + internal static ExportFolderProblem? MountCheck(ExportRootOptions o, string destinationFullPath) + { + ArgumentNullException.ThrowIfNull(o); + ArgumentException.ThrowIfNullOrWhiteSpace(destinationFullPath); + if (o.Root is not { } root) + { + return null; + } + + if (!o.Declared) + { + return new ExportFolderProblem(ExportFolderProblemKind.NotMounted, NotDeclaredText); + } + + var full = ExportPaths.Trim(Path.GetFullPath(destinationFullPath)); + var mount = o.Mounts.FindContaining(full); + if (mount is null || !ExportPaths.IsSameOrInside(ExportPaths.Trim(mount.MountPoint), root)) + { + return new ExportFolderProblem( + ExportFolderProblemKind.NotMounted, + o.Mounts.All().Any(m => ExportPaths.IsSameOrInside(ExportPaths.Trim(m.MountPoint), root)) + ? $"{DisplayPath(o, full)} non è su una cartella montata in {DisplayPath(o, root)}: Febe non ci scrive nulla. Scegli una cartella dentro un montaggio di {DisplayPath(o, root)}." + : NotMountedText(o)); + } + + return mount.ReadOnly + ? new ExportFolderProblem(ExportFolderProblemKind.ReadOnlyMount, $"{DisplayPath(o, full)} è montata in sola lettura: Febe non può copiarci nulla.") + : null; + } + + /// + /// Subfolders offered by the picker in Docker: is relative to the root, and so are the + /// returned paths. Without a root it is an absolute folder. Links, hidden and system folders are skipped. + /// + /// The folder cannot be browsed. + public static IReadOnlyList Browse(ExportRootOptions o, string? relative) + { + ArgumentNullException.ThrowIfNull(o); + string folder; + if (o.Root is { } root) + { + folder = string.IsNullOrWhiteSpace(relative) ? root : Resolve(o, relative, allowRoot: true); + } + else if (string.IsNullOrWhiteSpace(relative) || !Path.IsPathFullyQualified(relative)) + { + throw new ExportFolderException("Scegli la cartella da sfogliare con il suo percorso completo.", ExportFolderProblemKind.NotFullyQualified); + } + else + { + folder = ExportPaths.Trim(Path.GetFullPath(relative)); + } + + if (!Directory.Exists(folder)) + { + throw new ExportFolderException($"La cartella {DisplayPath(o, folder)} non esiste.", ExportFolderProblemKind.Missing); + } + + try + { + return Directory.EnumerateDirectories(folder, "*", ImportSources.Enumeration(recursive: false)) + .Order(StringComparer.Ordinal) + .Select(d => new SourceFolderChoice( + Path.GetFileName(d), + o.Root is { } r ? LibraryLayout.ToStored(Path.GetRelativePath(r, d)) : d, + Directory.EnumerateDirectories(d, "*", ImportSources.Enumeration(recursive: false)).Any())) + .ToList(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + throw new ExportFolderException($"Febe non riesce a leggere {DisplayPath(o, folder)}: controlla che il disco sia collegato.", ExportFolderProblemKind.Missing); + } + } + + /// + /// The full path of a chosen folder: in Docker the root plus a relative path (or a full path inside the root), never + /// the root itself, never with «..»; without a root a fully qualified path. + /// + /// The path cannot be a destination; the message says why. + public static string Resolve(ExportRootOptions o, string chosen) => Resolve(o, chosen, allowRoot: false); + + /// The path shown to Alberto: in Docker «/esporta/usb»; elsewhere the full path. + public static string DisplayPath(ExportRootOptions o, string full) + { + ArgumentNullException.ThrowIfNull(o); + ArgumentNullException.ThrowIfNull(full); + if (o.Root is { } root && ExportPaths.IsSameOrInside(full, root)) + { + var relative = Path.GetRelativePath(root, full); + return relative == "." ? LibraryLayout.ToStored(root) : LibraryLayout.ToStored(root).TrimEnd('/') + "/" + LibraryLayout.ToStored(relative); + } + + return full; + } + + private static string Resolve(ExportRootOptions o, string chosen, bool allowRoot) + { + ArgumentNullException.ThrowIfNull(o); + if (string.IsNullOrWhiteSpace(chosen)) + { + throw new ExportFolderException("Scegli la cartella in cui copiare i file.", ExportFolderProblemKind.Empty); + } + + var display = o.Root is { } shown ? DisplayPath(o, shown) : null; + + // Refused as text, before any normalisation: «..» never walks out of the list the picker shows. + if (chosen.Split('/', '\\').Any(s => s == "..")) + { + throw new ExportFolderException( + display is null ? "«..» non è ammesso: scegli la cartella con il suo percorso completo." : $"«..» non è ammesso: scegli una sottocartella di {display} dall'elenco.", + ExportFolderProblemKind.ParentSegment); + } + + if (o.Root is not { } root) + { + if (!Path.IsPathFullyQualified(chosen)) + { + throw new ExportFolderException("Scegli la cartella con il suo percorso completo.", ExportFolderProblemKind.NotFullyQualified); + } + + return ExportPaths.Trim(FullPath(chosen)); + } + + var full = ExportPaths.Trim(Path.IsPathFullyQualified(chosen) ? FullPath(chosen) : FullPath(Path.Combine(root, chosen.TrimStart('/', '\\')))); + if (!ExportPaths.IsSameOrInside(full, root)) + { + throw new ExportFolderException( + $"In Docker le copie vanno solo in una sottocartella di {display}: monta lì una cartella del server e sceglila dall'elenco.", + ExportFolderProblemKind.OutsideExportRoot); + } + + if (!allowRoot && ExportPaths.Same(full, root)) + { + throw new ExportFolderException($"Scegli una sottocartella di {display}: {display} stessa non è una destinazione.", ExportFolderProblemKind.ExportRootItself); + } + + return full; + } + + private static string FullPath(string path) + { + try + { + return Path.GetFullPath(path); + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) + { + throw new ExportFolderException("Il percorso scelto non è valido: scegli di nuovo la cartella.", ExportFolderProblemKind.NotFullyQualified); + } + } + + private static string NotMountedText(ExportRootOptions o) => + $"{DisplayPath(o, o.Root!)} è dichiarata ma non è montata: Febe non scrive nulla finché non monti una cartella del server su {DisplayPath(o, o.Root!)}."; +} diff --git a/src/Febe.Core/Export/ExportRunSettings.cs b/src/Febe.Core/Export/ExportRunSettings.cs new file mode 100644 index 0000000..de8e04b --- /dev/null +++ b/src/Febe.Core/Export/ExportRunSettings.cs @@ -0,0 +1,26 @@ +using System.Globalization; +using Febe.Core.Storage; + +namespace Febe.Core.Export; + +/// +/// Settings of one export job (like ImportRunSettings): a row of the setting table each, so the schema +/// stays as E1 left it. Cleared when the job completes, is cancelled or deleted. +/// +internal static class ExportRunSettings +{ + public static string CopyAgainKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"esportazione.lavoro.{runId}.copia-di-nuovo"); + + /// «Copia di nuovo anche i tolti o superati» was chosen for this job (decision D9). + public static async Task GetCopyAgainAsync(ISettingsStore store, long runId, CancellationToken ct) + { + var text = await store.GetAsync(CopyAgainKey(runId), ct).ConfigureAwait(false); + return string.Equals(text?.Trim(), "1", StringComparison.Ordinal); + } + + public static Task SetCopyAgainAsync(ISettingsStore store, long runId, bool value, CancellationToken ct) => + store.SetAsync(CopyAgainKey(runId), value ? "1" : null, ct); + + public static Task ClearAsync(ISettingsStore store, long runId, CancellationToken ct) => + store.SetAsync(CopyAgainKey(runId), null, ct); +} diff --git a/src/Febe.Core/Export/ExportService.cs b/src/Febe.Core/Export/ExportService.cs new file mode 100644 index 0000000..2ba975e --- /dev/null +++ b/src/Febe.Core/Export/ExportService.cs @@ -0,0 +1,642 @@ +using System.Diagnostics; +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Core.Storage; + +namespace Febe.Core.Export; + +/// +/// The copies to external folders for the interface (spec §4.10): one background job at a time, never together with +/// an import or a rebuild (), never during an engine session. A «Copia in…» makes one job +/// record per destination (decision D6 of tappa E2) and the job works on them in order. Every state lives in the +/// database: after a restart call once; «Riprendi» is always Alberto's. +/// +public sealed class ExportService : IAsyncDisposable +{ + private const string BusyText = "C'è già una copia al lavoro: aspetta che finisca o interrompila."; + private const int ItemBatch = 2000; + private static readonly TimeSpan ProgressInterval = TimeSpan.FromMilliseconds(250); + + private readonly ExportEnvironment _env; + private readonly Lock _gate = new(); + private Job? _job; + private ExportProgress? _current; + private long _lastPublished; + private Task _cleanup = Task.CompletedTask; + private bool _starting; + + public ExportService(ExportEnvironment env) + { + ArgumentNullException.ThrowIfNull(env); + _env = env; + Destinations = new ExportDestinations(env); + Planner = new ExportPlanner(env); + Copier = new ExportCopier(env); + Reports = new ExportReports(env); + } + + /// Progress of the running job, at most four times a second and at every change of phase (pool thread). + public event EventHandler? ProgressChanged; + + /// The job ended, however it ended (pool thread): the interface refreshes tiles and filter. + public event EventHandler? JobFinished; + + public ExportDestinations Destinations { get; } + + public ExportPlanner Planner { get; } + + public ExportCopier Copier { get; } + + public ExportReports Reports { get; } + + /// The runs of the running job; empty when idle (and for «Controlla le copie», which has none). + public IReadOnlyList ActiveRunIds + { + get + { + lock (_gate) + { + return _job is { Task.IsCompleted: false } job ? job.RunIds : []; + } + } + } + + /// A job is running. + public bool IsBusy + { + get + { + lock (_gate) + { + return _starting || _job is { Task.IsCompleted: false }; + } + } + } + + /// The last error of a background job that could not be stored with its run (normally null). + public string? LastJobError { get; private set; } + + /// + /// After a restart: a job that was running becomes «interrotto» (paused and interrupted ones stay), and the + /// .part files of unfinished jobs are removed in the background, only in their items' folders. Never resumes + /// by itself. Returns how many jobs became interrupted. + /// + public async Task RecoverAsync(CancellationToken ct = default) + { + var active = ActiveRunIds; + var recovered = 0; + var unfinished = await _env.Storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false); + foreach (var run in unfinished) + { + if (run.State == ExportRunState.Running && !active.Contains(run.Id)) + { + await _env.Storage.Exports.UpdateRunAsync(run with { State = ExportRunState.Interrupted, LastError = null }, CancellationToken.None).ConfigureAwait(false); + recovered++; + } + } + + var toClean = unfinished.Where(r => !active.Contains(r.Id)).ToList(); + lock (_gate) + { + _cleanup = Task.Run(() => CleanLeftoversAsync(toClean)); + } + + return recovered; + } + + /// The plan of a «Copia in…», for its dialog (database only, plus whether each destination answers). + public Task PlanAsync(ExportJobRequest request, CancellationToken ct = default) => Planner.PlanAsync(request, ct); + + /// + /// «Copia in…»: records one job per destination that gets files, with its items, and starts copying in the + /// background. Files not exported or missing are only counted in the returned plan. When nothing is due, no job is + /// recorded and nothing starts. + /// + /// A copy, an import or a rebuild is running. + public async Task StartAsync(ExportJobRequest request, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(request); + lock (_gate) + { + EnsureIdle(); + _starting = true; // a second «Copia in…» meanwhile records nothing + } + + try + { + return await StartReservedAsync(request, ct).ConfigureAwait(false); + } + finally + { + lock (_gate) + { + _starting = false; + } + } + } + + private async Task StartReservedAsync(ExportJobRequest request, CancellationToken ct) + { + var effective = await Destinations.ResolveAllAsync(ct).ConfigureAwait(false); + var settings = await ExportSettings.LoadAsync(_env.Storage.Settings, ct).ConfigureAwait(false); + var tally = new PlanTally(); + var runs = new Dictionary(); + var pending = new List(); + var exports = _env.Storage.Exports; + try + { + await foreach (var file in Planner.EnumerateAsync(request, effective, settings, ct).ConfigureAwait(false)) + { + tally.Add(file); + if (file.DestinationId is not { } destination || file.Action is PlannedCopy.Missing or PlannedCopy.NotExported) + { + continue; + } + + if (!runs.TryGetValue(destination, out var run)) + { + run = await exports.CreateRunAsync( + new ExportRun { DestinationId = destination, Kind = ExportRunKind.Copy, Origin = request.Origin, State = ExportRunState.Running, StartedAt = _env.Clock.Now }, + CancellationToken.None).ConfigureAwait(false); + runs[destination] = run; + if (request.CopyAgain) + { + await ExportRunSettings.SetCopyAgainAsync(_env.Storage.Settings, run.Id, true, CancellationToken.None).ConfigureAwait(false); + } + } + + pending.Add(new ExportItem + { + RunId = run.Id, + MediaId = file.Candidate.MediaId, + AccountId = file.Candidate.AccountId, + SourceSha256 = file.Candidate.Sha256, + Variant = ExportVariant.Whole, + Format = ExportFormat.Original, + State = ExportItemState.Pending, + }); + if (pending.Count >= ItemBatch) + { + await exports.AddItemsAsync(pending, CancellationToken.None).ConfigureAwait(false); + pending.Clear(); + } + } + + if (pending.Count > 0) + { + await exports.AddItemsAsync(pending, CancellationToken.None).ConfigureAwait(false); + } + } + catch + { + await StopRunsAsync(runs.Values).ConfigureAwait(false); + throw; + } + + var plan = await tally.BuildAsync(_env, Destinations, effective, checkDestinations: false, CancellationToken.None).ConfigureAwait(false); + var ordered = runs.Values.OrderBy(r => r.Id).ToList(); + if (ordered.Count == 0) + { + return new ExportStart([], plan); + } + + try + { + lock (_gate) + { + _starting = false; + StartCopyJob(ordered.Select(r => r.Id).ToList()); + } + } + catch + { + await StopRunsAsync(ordered).ConfigureAwait(false); + throw; + } + + return new ExportStart(ordered, plan); + } + + /// + /// «Riprendi»: continues unfinished jobs in the background, oldest first. Null: every interrupted or paused one (a + /// paused one checks its destination first and pauses again if it still does not answer). + /// + public async Task> ResumeAsync(IReadOnlyList? runIds = null, CancellationToken ct = default) + { + EnsureIdle(); + var unfinished = await _env.Storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false); + List chosen; + if (runIds is null) + { + chosen = unfinished.ToList(); + } + else + { + chosen = []; + foreach (var id in runIds.Distinct()) + { + var run = unfinished.FirstOrDefault(r => r.Id == id); + if (run is null) + { + _ = await _env.Storage.Exports.GetRunAsync(id, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Lavoro di copia {id} non trovato."); + throw new InvalidOperationException("Questo lavoro di copia è già finito: non c'è niente da riprendere."); + } + + chosen.Add(run); + } + } + + chosen = chosen.OrderBy(r => r.Id).ToList(); + if (chosen.Count > 0) + { + StartCopyJob(chosen.Select(r => r.Id).ToList()); + } + + return chosen; + } + + /// «Interrompi»: stops the running job and waits until its states are saved. + public async Task InterruptAsync(CancellationToken ct = default) + { + Job? job; + lock (_gate) + { + job = _job is { Task.IsCompleted: false } j ? j : null; + } + + if (job is null) + { + return; + } + + await job.Cancellation.CancelAsync().ConfigureAwait(false); + await job.Task.WaitAsync(ct).ConfigureAwait(false); + } + + /// + /// «Annulla»: an unfinished job becomes «annullato» (the running job is interrupted first when it holds it). Our + /// .part files in its folders go; no other file is touched, and the copies made stay. + /// + public async Task DiscardAsync(long runId, CancellationToken ct = default) + { + if (ActiveRunIds.Contains(runId)) + { + await InterruptAsync(ct).ConfigureAwait(false); + } + + var run = await _env.Storage.Exports.GetRunAsync(runId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Lavoro di copia {runId} non trovato."); + if (run.State is ExportRunState.Completed or ExportRunState.Cancelled) + { + return; + } + + await _env.Storage.Exports.UpdateRunAsync(run with { State = ExportRunState.Cancelled, CompletedAt = _env.Clock.Now }, CancellationToken.None).ConfigureAwait(false); + await ExportRunSettings.ClearAsync(_env.Storage.Settings, runId, CancellationToken.None).ConfigureAwait(false); + if (await _env.Storage.Exports.GetDestinationAsync(run.DestinationId, ct).ConfigureAwait(false) is { } destination) + { + await ExportLeftovers.CleanAsync(_env, run, destination, ct).ConfigureAwait(false); + } + } + + /// + /// «Controlla le copie»: a job without a record (not resumable, idempotent) that looks for every Copied or + /// Superseded copy of a destination and marks «Tolto» those whose file is gone. Never touches a file. + /// + public async Task CheckCopiesAsync(long destinationId, CancellationToken ct = default) + { + EnsureIdle(); + var destination = await _env.Storage.Exports.GetDestinationAsync(destinationId, ct).ConfigureAwait(false) + ?? throw new KeyNotFoundException($"Destinazione di esportazione {destinationId} non trovata."); + if (destination.IsRetired) + { + throw new InvalidOperationException("Questa cartella è stata tolta: non c'è niente da controllare."); + } + + StartJob([], (progress, token) => CheckJobAsync(destination, progress, token)); + } + + /// The progress of the running job, or a snapshot of the newest job. + public async Task GetProgressAsync(CancellationToken ct = default) + { + lock (_gate) + { + if (_job is { Task.IsCompleted: false } && _current is { } current) + { + return current; + } + } + + var newest = (await _env.Storage.Exports.ListRecentRunsAsync(1, ct).ConfigureAwait(false)).FirstOrDefault(); + return newest is null + ? new ExportProgress(null, ExportPhase.Finished, 0, 0, 0, 0, null, null, new Dictionary(), _env.Clock.Now) + : await SnapshotAsync(newest, ct).ConfigureAwait(false); + } + + /// Waits for the running job (if any) to end, however it ends. + public async Task WaitAsync(CancellationToken ct = default) + { + Job? job; + Task cleanup; + lock (_gate) + { + job = _job; + cleanup = _cleanup; + } + + if (job is not null) + { + await job.Task.WaitAsync(ct).ConfigureAwait(false); + } + + await cleanup.WaitAsync(ct).ConfigureAwait(false); + } + + public async ValueTask DisposeAsync() + { + Job? job; + Task cleanup; + lock (_gate) + { + job = _job; + cleanup = _cleanup; + } + + if (job is not null) + { + await job.Cancellation.CancelAsync().ConfigureAwait(false); + await job.Task.ConfigureAwait(false); + job.Cancellation.Dispose(); + } + + await cleanup.ConfigureAwait(false); + } + + private async Task SnapshotAsync(ExportRun run, CancellationToken ct) + { + var summary = await _env.Storage.Exports.GetRunSummaryAsync(run.Id, ct).ConfigureAwait(false); + var destination = await _env.Storage.Exports.GetDestinationAsync(run.DestinationId, ct).ConfigureAwait(false); + var phase = run.State == ExportRunState.Running && IsBusy ? ExportPhase.Copying : ExportPhase.Finished; + return new ExportProgress( + run.Id, + phase, + summary.Total - summary.ByState.GetValueOrDefault(ExportItemState.Pending), + summary.Total, + 0, + 0, + null, + destination is null ? null : ExportDestinations.Label(destination), + summary.ByState, + _env.Clock.Now); + } + + private async Task CheckJobAsync(ExportDestination destination, IProgress progress, CancellationToken ct) + { + var exports = _env.Storage.Exports; + var label = ExportDestinations.Label(destination); + var counts = await exports.CountCopiesAsync(destination.Id, ct).ConfigureAwait(false); + var total = counts.GetValueOrDefault(ExportCopyState.Copied) + counts.GetValueOrDefault(ExportCopyState.Superseded); + void Report(ExportPhase phase, int done) => + progress.Report(new ExportProgress(null, phase, done, total, 0, 0, null, label, new Dictionary(), _env.Clock.Now)); + + Report(ExportPhase.Checking, 0); + if (await Copier.CheckDestinationAsync(destination, ct).ConfigureAwait(false) is { } problem) + { + await ExportPause.PauseAsync(_env, destination, problem).ConfigureAwait(false); + Report(ExportPhase.Finished, 0); + return; + } + + await ExportPause.ClearAsync(_env, destination).ConfigureAwait(false); + var done = 0; + var removed = 0; + foreach (var state in new[] { ExportCopyState.Copied, ExportCopyState.Superseded }) + { + long after = 0; + while (true) + { + while (_env.Session.InSession) + { + Report(ExportPhase.WaitingForSession, done); + await _env.Clock.Delay(_env.SessionPoll, ct).ConfigureAwait(false); + } + + var page = await exports.ListCopiesAsync(destination.Id, state, after, 1000, ct).ConfigureAwait(false); + if (page.Count == 0) + { + break; + } + + after = page[^1].Id; + if (!Directory.Exists(destination.RootPath)) + { + // The disk went away during the check: nothing is «Tolto» because of that. + var gone = await Copier.CheckDestinationAsync(destination, ct).ConfigureAwait(false) ?? $"{label} non è raggiungibile."; + await ExportPause.PauseAsync(_env, destination, gone).ConfigureAwait(false); + Report(ExportPhase.Finished, done); + return; + } + + var missing = new List(); + foreach (var copy in page) + { + ct.ThrowIfCancellationRequested(); + if (copy.RelativePath is not { } path || !FileExists(destination.RootPath, path)) + { + missing.Add(copy.Id); + } + } + + removed += await exports.MarkCopiesRemovedAsync(missing, _env.Clock.Now, CancellationToken.None).ConfigureAwait(false); + done += page.Count; + Report(ExportPhase.Checking, done); + } + } + + await _env.Storage.Events.AppendAsync( + new EventRecord + { + At = _env.Clock.Now, + Code = "esportazione-controllo", + Message = ExportText.CheckMessage(done, removed, destination), + Severity = removed > 0 ? EventSeverity.Warning : EventSeverity.Success, + AccountId = destination.AccountId, + }, + CancellationToken.None).ConfigureAwait(false); + Report(ExportPhase.Finished, done); + } + + private bool FileExists(string root, string relativePath) + { + try + { + return _env.FileSystem.FileExists(LibraryLayout.FullPath(root, relativePath)); + } + catch (ArgumentException) + { + return false; + } + } + + private async Task CleanLeftoversAsync(IReadOnlyList runs) + { + foreach (var run in runs) + { + try + { + if (await _env.Storage.Exports.GetDestinationAsync(run.DestinationId).ConfigureAwait(false) is { } destination) + { + await ExportLeftovers.CleanAsync(_env, run, destination, CancellationToken.None).ConfigureAwait(false); + } + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + // Best effort: the resume of that job cleans again. + } + } + } + + private async Task StopRunsAsync(IEnumerable runs) + { + foreach (var run in runs) + { + try + { + // The job never started: nothing was copied, there is nothing to resume. + await _env.Storage.Exports.UpdateRunAsync(run with { State = ExportRunState.Cancelled, CompletedAt = _env.Clock.Now }, CancellationToken.None).ConfigureAwait(false); + await ExportRunSettings.ClearAsync(_env.Storage.Settings, run.Id, CancellationToken.None).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + // RecoverAsync makes it «interrotto» at the next start. + } + } + } + + private void EnsureIdle() + { + if (IsBusy) + { + throw new InvalidOperationException(BusyText); + } + + if (_env.Gate?.Busy is { } busy) + { + throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Export, busy)); + } + } + + private void StartCopyJob(IReadOnlyList runIds) => + StartJob(runIds, async (progress, token) => + { + foreach (var runId in runIds) + { + token.ThrowIfCancellationRequested(); + try + { + await Copier.CopyAsync(runId, progress, token).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException || !token.IsCancellationRequested) + { + // Stored with the run (Interrupted, with its error); the next destination still gets its files. + LastJobError = ExportText.ErrorText(ex); + } + } + }); + + private void StartJob(IReadOnlyList runIds, Func, CancellationToken, Task> work) + { + lock (_gate) + { + if (_job is { Task.IsCompleted: false }) + { + throw new InvalidOperationException(BusyText); + } + + IDisposable? lease = null; + if (_env.Gate is { } gate && !gate.TryEnter(LongWorkKind.Export, out lease, out var busy)) + { + throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Export, busy!.Value)); + } + + _job?.Cancellation.Dispose(); + var cancellation = new CancellationTokenSource(); + var reporter = new Reporter(this); + LastJobError = null; + _current = new ExportProgress(runIds.Count > 0 ? runIds[0] : null, runIds.Count > 0 ? ExportPhase.Preparing : ExportPhase.Checking, 0, 0, 0, 0, null, null, new Dictionary(), _env.Clock.Now); + var task = Task.Run(async () => + { + try + { + await work(reporter, cancellation.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellation.IsCancellationRequested) + { + // Interrupted: the states were saved by the job. + } + catch (Exception ex) + { + LastJobError = ExportText.ErrorText(ex); + } + finally + { + try + { + var last = _current is { } c ? c with { Phase = ExportPhase.Finished, UpdatedAt = _env.Clock.Now } : null; + if (last is not null) + { + Publish(last, force: true); + } + } + finally + { + lease?.Dispose(); + } + + try + { + JobFinished?.Invoke(this, new ExportJobFinished(runIds, CopiesChanged: true)); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + // A handler failed: the job is over all the same. + } + } + }); + _job = new Job(runIds, cancellation, task); + } + } + + private void Publish(ExportProgress progress, bool force) + { + lock (_gate) + { + _current = progress; + } + + var now = Stopwatch.GetTimestamp(); + var last = Interlocked.Read(ref _lastPublished); + if (!force && Stopwatch.GetElapsedTime(last, now) < ProgressInterval) + { + return; + } + + Interlocked.Exchange(ref _lastPublished, now); + ProgressChanged?.Invoke(this, progress); + } + + private sealed record Job(IReadOnlyList RunIds, CancellationTokenSource Cancellation, Task Task); + + private sealed class Reporter(ExportService owner) : IProgress + { + private (ExportPhase, long?)? _phase; + + public void Report(ExportProgress value) + { + var key = (value.Phase, value.RunId); + var changed = _phase != key; + _phase = key; + owner.Publish(value, changed); + } + } +} diff --git a/src/Febe.Core/Export/ExportSupersession.cs b/src/Febe.Core/Export/ExportSupersession.cs new file mode 100644 index 0000000..77377a7 --- /dev/null +++ b/src/Febe.Core/Export/ExportSupersession.cs @@ -0,0 +1,36 @@ +using Febe.Core.Domain; +using Febe.Core.Storage; + +namespace Febe.Core.Export; + +/// +/// «Superato» (spec §4.10): the library file of an account changed («Tieni il più grande», a slot filled again with +/// other bytes, a rebuild that found other bytes on disk), so its copies are of a file the library no longer has. The +/// copies stay where they are; they are only marked, and the new file is never copied by itself. +/// +public static class ExportSupersession +{ + /// + /// Marks the copies of the account's old file as superseded by the new one. A no-op when the old SHA-256 is null or + /// equal to the new one, or when a present file of that account still has the old SHA-256. Writes are not + /// cancellable: the library already changed. + /// + public static async Task FileChangedAsync(IFebeStorage storage, long accountId, string? oldSha256, string newSha256, DateTimeOffset at, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(storage); + ArgumentException.ThrowIfNullOrWhiteSpace(newSha256); + if (oldSha256 is not { Length: 64 } || newSha256.Length != 64 || string.Equals(oldSha256, newSha256, StringComparison.OrdinalIgnoreCase)) + { + return 0; + } + + var old = oldSha256.ToLowerInvariant(); + var users = await storage.Media.FindBySha256Async(old, ct).ConfigureAwait(false); + if (users.Any(u => u.Entry.AccountId == accountId && EntryStateRules.IsPresent(u.Media.State))) + { + return 0; + } + + return await storage.Exports.SupersedeCopiesAsync(accountId, old, newSha256.ToLowerInvariant(), at, CancellationToken.None).ConfigureAwait(false); + } +} diff --git a/src/Febe.Core/Export/ExportText.cs b/src/Febe.Core/Export/ExportText.cs new file mode 100644 index 0000000..384dfc1 --- /dev/null +++ b/src/Febe.Core/Export/ExportText.cs @@ -0,0 +1,138 @@ +using Febe.Core.Domain; +using Febe.Core.Engine; +using Febe.Core.Storage; + +namespace Febe.Core.Export; + +/// +/// Texts of the copies to external folders for Alberto (spec §4.10, §10.4): sentence case, dots for thousands, the same +/// names everywhere. Notes are stored in export_item.note as English codes () and shown with +/// . +/// +public static class ExportText +{ + /// The codes of export_item.note. + public static class Notes + { + public const string SourceMissing = "SourceMissing"; + public const string AccountRemoved = "AccountRemoved"; + public const string Removed = "Removed"; + public const string Superseded = "Superseded"; + public const string CopiedForAnotherAccount = "CopiedForAnotherAccount"; + public const string SourceChanged = "SourceChanged"; + public const string TooLargeForFileSystem = "TooLargeForFileSystem"; + public const string NameTaken = "NameTaken"; + public const string PathTaken = "PathTaken"; + public const string NotExported = "NotExported"; + } + + /// Name of the state of a file of a job. + public static string State(ExportItemState state) => state switch + { + ExportItemState.Pending => "In attesa", + ExportItemState.Copied => "Copiato", + ExportItemState.Adopted => "Adottato", + ExportItemState.AlreadyCopied => "Già copiato", + ExportItemState.Skipped => "Saltato", + ExportItemState.Missing => "File non presente in libreria", + ExportItemState.Failed => "Non riuscito", + _ => state.ToString(), + }; + + /// Name of the state of a copy. + public static string CopyState(ExportCopyState state) => state switch + { + ExportCopyState.Copied => "Copiato", + ExportCopyState.Removed => "Tolto", + ExportCopyState.Superseded => "Superato", + ExportCopyState.Failed => "Non riuscito", + _ => state.ToString(), + }; + + /// The Italian text of a note code; null for none; an unknown code is shown as it is. + public static string? Note(string? code) => code switch + { + null or "" => null, + Notes.SourceMissing => "File non presente in libreria", + Notes.AccountRemoved => "L'account è stato rimosso", + Notes.Removed => "Tolto dalla destinazione: non si ricopia da solo («Copia di nuovo»)", + Notes.Superseded => "Superato da un file nuovo della libreria: non si ricopia da solo", + Notes.CopiedForAnotherAccount => "Già copiato per un altro account («Una copia sola»)", + Notes.SourceChanged => "Il file della libreria non corrisponde a quello registrato", + Notes.TooLargeForFileSystem => "Più grande di 4 GB: il disco FAT32 non lo accetta", + Notes.NameTaken => "Nome già occupato da un altro file: copiato con un nome libero", + Notes.PathTaken => "Percorso preso nel frattempo: riprova", + Notes.NotExported => "Non si copia qui: «Esporta questo account» è spento, o il file va in un'altra cartella", + _ => code, + }; + + /// «1 file copiato», «1.204 file copiati». + public static string Count(int count, string one, string many) => count == 1 ? "1 " + one : ItalianText.Number(count) + " " + many; + + /// The event written when a job ends: «Copia in Disco USB finita: 120 file copiati, 30 già copiati.» + public static string CompletionMessage(ExportRunSummary summary, ExportDestination destination) + { + ArgumentNullException.ThrowIfNull(summary); + ArgumentNullException.ThrowIfNull(destination); + int Of(ExportItemState s) => summary.ByState.GetValueOrDefault(s); + var parts = new List { Count(Of(ExportItemState.Copied) + Of(ExportItemState.Adopted), "file copiato", "file copiati") }; + if (Of(ExportItemState.AlreadyCopied) > 0) + { + parts.Add(Count(Of(ExportItemState.AlreadyCopied), "già copiato", "già copiati")); + } + + if (Of(ExportItemState.Skipped) > 0) + { + parts.Add(Count(Of(ExportItemState.Skipped), "saltato", "saltati")); + } + + if (Of(ExportItemState.Missing) > 0) + { + parts.Add(Count(Of(ExportItemState.Missing), "non presente in libreria", "non presenti in libreria")); + } + + if (Of(ExportItemState.Failed) > 0) + { + parts.Add(Count(Of(ExportItemState.Failed), "non riuscito", "non riusciti")); + } + + return $"Copia in {ExportDestinations.Label(destination)} finita: {string.Join(", ", parts)}."; + } + + /// The event of «Controlla le copie». + public static string CheckMessage(int checkedCopies, int removed, ExportDestination destination) + { + ArgumentNullException.ThrowIfNull(destination); + var text = $"Controllate {ItalianText.Number(checkedCopies)} copie in {ExportDestinations.Label(destination)}: "; + return text + (removed == 0 ? "ci sono tutte." : $"{Count(removed, "non c'è più (tolta)", "non ci sono più (tolte)")}."); + } + + /// The space is not enough for the next file (decision D16). + public static string NoSpace(ExportDestination destination, long free, string file, long bytes) => + $"Su {ExportDestinations.Label(destination)} restano {ItalianText.Bytes(free)}: per copiare {file} ({ItalianText.Bytes(bytes)}) serve più spazio, " + + $"con un margine di {ItalianText.Bytes(ExportSpace.Margin)}. Libera spazio, poi riprendi."; + + /// The disk said it is full. + public static string DiskFull(ExportDestination destination) => + $"Su {ExportDestinations.Label(destination)} non c'è più spazio: libera spazio, poi riprendi."; + + /// A file over the FAT32 limit. + public static string TooLarge(long bytes) => + $"Il file pesa {ItalianText.Bytes(bytes)}: su un disco FAT32 un file non può superare 4 GB."; + + /// The destination was retired while a job used it. + public const string RetiredDestination = "La cartella è stata tolta."; + + /// An error for Alberto, without paths of secrets: the message of a file error, or a generic sentence. + public static string ErrorText(Exception ex) + { + ArgumentNullException.ThrowIfNull(ex); + return ex switch + { + ExportFolderException folder => folder.Message, + IOException io => $"Errore di lettura o scrittura: {io.Message}", + UnauthorizedAccessException => "Febe non ha il permesso di scrivere nella cartella: controlla i permessi.", + _ => $"Errore inatteso ({ex.GetType().Name}): riprova; se si ripete, segnalalo.", + }; + } +} diff --git a/src/Febe.Core/Import/ImportCopier.cs b/src/Febe.Core/Import/ImportCopier.cs index 1a75ac2..e053946 100644 --- a/src/Febe.Core/Import/ImportCopier.cs +++ b/src/Febe.Core/Import/ImportCopier.cs @@ -1,5 +1,6 @@ using Febe.Core.Domain; using Febe.Core.Engine; +using Febe.Core.Export; using Febe.Core.Library; using Febe.Core.Storage; @@ -545,6 +546,9 @@ public sealed class ImportCopier(ImportEnvironment env) media.State, env.Clock.Now, none).ConfigureAwait(false); + + // The copies of the old file in external folders are now «Superato» (spec §4.10): never copied again by themselves. + await ExportSupersession.FileChangedAsync(env.Storage, account.Id, media.Sha256, saved.Sha256, env.Clock.Now, none).ConfigureAwait(false); await context.Ingest.TryAppendJournalAsync(entry.Id, none).ConfigureAwait(false); if (entry.InstagramId is null && string.IsNullOrWhiteSpace(entry.Code) && !string.Equals(oldRelative, saved.RelativePath, StringComparison.Ordinal)) { diff --git a/src/Febe.Core/Import/ImportEnvironment.cs b/src/Febe.Core/Import/ImportEnvironment.cs index 25e8e00..3018f48 100644 --- a/src/Febe.Core/Import/ImportEnvironment.cs +++ b/src/Febe.Core/Import/ImportEnvironment.cs @@ -58,6 +58,12 @@ public sealed record ImportEnvironment /// Reading, hashing and deleting source files. public IImportFileSystem FileSystem { get; init; } = ImportFileSystem.Instance; + /// + /// The gate shared with the export and the rebuild (spec §4.10: they never run together). Null: no other long work + /// to keep out (tests, the import alone). + /// + public LongWorkGate? Gate { get; init; } + /// Files analysed at the same time (hashing and decoding). public int Parallelism { get; init; } = Math.Clamp(Environment.ProcessorCount, 1, 4); diff --git a/src/Febe.Core/Import/ImportService.cs b/src/Febe.Core/Import/ImportService.cs index 0c17708..44d543d 100644 --- a/src/Febe.Core/Import/ImportService.cs +++ b/src/Febe.Core/Import/ImportService.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Core.Storage; @@ -283,6 +284,12 @@ public sealed class ImportService : IAsyncDisposable { throw new InvalidOperationException("C'è già un'importazione al lavoro: aspetta che finisca o interrompila."); } + + // Checked up front too, so a refused start records nothing; StartJob takes the gate for real. + if (_env.Gate?.Busy is { } busy) + { + throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Import, busy)); + } } private void StartJob(long runId, ImportPhase phase, Func, CancellationToken, Task> work) @@ -294,6 +301,12 @@ public sealed class ImportService : IAsyncDisposable throw new InvalidOperationException("C'è già un'importazione al lavoro: aspetta che finisca o interrompila."); } + IDisposable? lease = null; + if (_env.Gate is { } gate && !gate.TryEnter(LongWorkKind.Import, out lease, out var busy)) + { + throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Import, busy!.Value)); + } + _job?.Cancellation.Dispose(); var cancellation = new CancellationTokenSource(); var reporter = new Reporter(this); @@ -322,6 +335,10 @@ public sealed class ImportService : IAsyncDisposable { // The database is closing: nothing to publish. } + finally + { + lease?.Dispose(); + } } }); _job = new Job(runId, phase, cancellation, task); diff --git a/src/Febe.Core/Library/DownloadDuplicateReview.cs b/src/Febe.Core/Library/DownloadDuplicateReview.cs index 81ce928..75e13e6 100644 --- a/src/Febe.Core/Library/DownloadDuplicateReview.cs +++ b/src/Febe.Core/Library/DownloadDuplicateReview.cs @@ -1,5 +1,6 @@ using Febe.Core.Abstractions; using Febe.Core.Domain; +using Febe.Core.Export; using Febe.Core.Storage; namespace Febe.Core.Library; @@ -174,6 +175,11 @@ public sealed class DownloadDuplicateReview( if (ok) { removed++; + if (decision == DuplicateDecision.KeepLarger && loser == item.Existing && item.Candidate.Sha256 is { } larger) + { + // «Tieni il più grande» replaced the file already there: its copies in external folders are «Superato». + await ExportSupersession.FileChangedAsync(storage, item.Existing.AccountId, item.Existing.Sha256, larger, clock.Now, CancellationToken.None).ConfigureAwait(false); + } } else if (problem is not null) { diff --git a/src/Febe.Core/Library/LibraryIngest.cs b/src/Febe.Core/Library/LibraryIngest.cs index cc883d0..45b8dc3 100644 --- a/src/Febe.Core/Library/LibraryIngest.cs +++ b/src/Febe.Core/Library/LibraryIngest.cs @@ -2,6 +2,7 @@ using System.Collections.Concurrent; using System.Globalization; using Febe.Core.Abstractions; using Febe.Core.Domain; +using Febe.Core.Export; using Febe.Core.Storage; namespace Febe.Core.Library; @@ -319,6 +320,10 @@ public sealed class LibraryIngest( throw new EntryDeletedException(); } + // A slot that had other bytes (a rebuild left the journal's SHA-256 on a file to download again, an import + // filled it): the copies of the old file in external folders are now «Superato» (spec §4.10). + await ExportSupersession.FileChangedAsync(storage, account.Id, media.Sha256, saved.Sha256, now, CancellationToken.None).ConfigureAwait(false); + var pairs = new List(); if (hash is { } h && hashIndex is not null) { diff --git a/src/Febe.Core/Library/LibraryRebuilder.cs b/src/Febe.Core/Library/LibraryRebuilder.cs index 341893e..a7915aa 100644 --- a/src/Febe.Core/Library/LibraryRebuilder.cs +++ b/src/Febe.Core/Library/LibraryRebuilder.cs @@ -1,6 +1,7 @@ using System.Security.Cryptography; using Febe.Core.Abstractions; using Febe.Core.Domain; +using Febe.Core.Export; using Febe.Core.Storage; namespace Febe.Core.Library; @@ -202,6 +203,14 @@ public sealed class LibraryRebuilder( } await FlushAsync(account, 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) + { + await ExportSupersession.FileChangedAsync(storage, account.Id, old, now, clock.Now, CancellationToken.None).ConfigureAwait(false); + } + + report.Changed.Clear(); CountUntracked(folder, allItems, report); } @@ -554,6 +563,7 @@ public sealed class LibraryRebuilder( report.FilesVerified++; if (media.Sha256 is not null && !string.Equals(media.Sha256, check.Sha256, StringComparison.Ordinal)) { + report.Changed.Add((media.Sha256, check.Sha256)); report.HashMismatches++; report.Note($"Contenuto diverso da quello registrato: {file.Path}"); } @@ -738,6 +748,9 @@ public sealed class LibraryRebuilder( public int InvalidLines { get; set; } + /// (journal SHA-256, SHA-256 on disk) of the folder being rebuilt, for the copies to mark «Superato». + public List<(string Old, string New)> Changed { get; } = []; + public void Note(string note) { if (_notes.Count < MaxNotes) diff --git a/src/Febe.Core/Library/MountInfo.cs b/src/Febe.Core/Library/MountInfo.cs new file mode 100644 index 0000000..a3d180d --- /dev/null +++ b/src/Febe.Core/Library/MountInfo.cs @@ -0,0 +1,114 @@ +namespace Febe.Core.Library; + +/// +/// One line of /proc/self/mountinfo (proc(5)): unlike /proc/self/mounts it says which folder of its file +/// system a mount shows (: / when the mount is the root of that file system) and gives the exact +/// mount point, which the export needs for /esporta (spec §4.10, §11). +/// +/// Mount id. +/// Id of the parent mount. +/// Folder of the file system shown at the mount point (/: its root). +/// Where it is mounted, unescaped. +/// Per-mount options (rw, ro, noatime…). +/// File system type (ext4, vfat, cifs…). +/// Mount source (/dev/sdb1, //server/share…), unescaped. +public sealed record MountInfoEntry(int Id, int ParentId, string Root, string MountPoint, IReadOnlyList Options, string FileSystemType, string Source) +{ + /// The mount is read-only (ro, as for a Docker volume mounted with :ro). + public bool ReadOnly => Options.Contains("ro", StringComparer.Ordinal); +} + +/// Reads /proc/self/mountinfo. +public static class MountInfoTable +{ + private const string MountInfoPath = "/proc/self/mountinfo"; + + /// + /// Parses the content of /proc/self/mountinfo: fields 0-5, then optional fields up to the separator «-», then + /// file system type and source. Malformed lines are skipped; nothing throws. + /// + public static IReadOnlyList Parse(string content) + { + ArgumentNullException.ThrowIfNull(content); + var entries = new List(); + foreach (var raw in content.Split('\n')) + { + var fields = raw.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (fields.Length < 9 + || !int.TryParse(fields[0], System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var id) + || !int.TryParse(fields[1], System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var parent)) + { + continue; + } + + var separator = Array.IndexOf(fields, "-", 6); + if (separator < 0 || separator + 2 >= fields.Length) + { + continue; + } + + var root = MountTable.Unescape(fields[3]); + var point = MountTable.Unescape(fields[4]); + if (!root.StartsWith('/') || !point.StartsWith('/')) + { + continue; + } + + entries.Add(new MountInfoEntry( + id, + parent, + root, + point, + fields[5].Split(',', StringSplitOptions.RemoveEmptyEntries), + fields[separator + 1], + MountTable.Unescape(fields[separator + 2]))); + } + + return entries; + } + + /// + /// The mount that holds a path: the longest mount point that is the path itself or one of its parents (ordinal + /// comparison; a later mount over the same point wins, as the kernel shows the last one). Null when none matches. + /// + public static MountInfoEntry? FindContaining(IReadOnlyList mounts, string fullPath) + { + ArgumentNullException.ThrowIfNull(mounts); + ArgumentNullException.ThrowIfNull(fullPath); + var path = fullPath.Length > 1 ? fullPath.TrimEnd('/') : fullPath; + MountInfoEntry? best = null; + var bestLength = -1; + foreach (var mount in mounts) + { + var point = mount.MountPoint.Length > 1 ? mount.MountPoint.TrimEnd('/') : mount.MountPoint; + var contains = point == "/" + || string.Equals(path, point, StringComparison.Ordinal) + || path.StartsWith(point + "/", StringComparison.Ordinal); + if (contains && point.Length >= bestLength) + { + best = mount; + bestLength = point.Length; + } + } + + return best; + } + + /// The content of /proc/self/mountinfo on Linux; null elsewhere or when it cannot be read. + public static string? ReadProcSelf() + { + if (!OperatingSystem.IsLinux()) + { + return null; + } + + try + { + return File.Exists(MountInfoPath) ? File.ReadAllText(MountInfoPath) : null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return null; + } + } +} diff --git a/src/Febe.Core/Library/SafeFileWriter.cs b/src/Febe.Core/Library/SafeFileWriter.cs index fc4c65c..086de82 100644 --- a/src/Febe.Core/Library/SafeFileWriter.cs +++ b/src/Febe.Core/Library/SafeFileWriter.cs @@ -27,6 +27,21 @@ public sealed record SafeWriteOptions /// Bytes written so far. public IProgress? Progress { get; init; } + + /// + /// The root folder must already exist: before anything is created (spec §4.10 + /// «La radice di una destinazione non si crea mai»: a missing disk or share must not become a local folder). + /// Subfolders are still created. The root could vanish between the check and the creation of a subfolder: on Windows + /// a missing drive or share throws anyway, and in Docker a mount cannot vanish inside a running container. + /// + public bool RequireExistingRoot { get; init; } + + /// + /// After the flush, read the temporary file back from the disk and compare its SHA-256 with the one computed while + /// writing, before the final name is decided (copies to external disks, spec §4.10). On a mismatch the temporary file + /// is removed and an says so. + /// + public bool VerifyFromDisk { get; init; } } /// The content exceeded ; nothing was kept. @@ -47,6 +62,24 @@ public sealed class FileTooLargeException : IOException } } +/// The root folder of a write with does not exist; nothing was created. +public sealed class ExportRootMissingException : DirectoryNotFoundException +{ + public ExportRootMissingException() + { + } + + public ExportRootMissingException(string message) + : base(message) + { + } + + public ExportRootMissingException(string message, Exception innerException) + : base(message, innerException) + { + } +} + /// /// Writes library files safely (spec §6.5 point 4, rule 12): /// @@ -136,6 +169,11 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL options ??= new SafeWriteOptions(); var root = Path.GetFullPath(rootFolder); var tempFolder = string.IsNullOrEmpty(tempDirectory) ? root : LibraryLayout.FullPath(root, tempDirectory); + if (options.RequireExistingRoot && !Directory.Exists(root)) + { + throw new ExportRootMissingException($"La cartella {root} non c'è: Febe non la crea, perché un disco o una condivisione assente non deve diventare una cartella locale."); + } + Directory.CreateDirectory(tempFolder); var tempPath = Path.Combine(tempFolder, TempPrefix + Guid.NewGuid().ToString("N")[..12] + TempSuffix); using var reservation = ReserveTemporaryFile(tempPath); @@ -144,6 +182,10 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL { var digest = await WriteTempAsync(source, tempPath, options, ct).ConfigureAwait(false); ct.ThrowIfCancellationRequested(); + if (options.VerifyFromDisk) + { + await VerifyFromDiskAsync(tempPath, digest, ct).ConfigureAwait(false); + } var desired = await decide(digest, ct).ConfigureAwait(false); if (desired is null) @@ -247,6 +289,22 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL return new FileDigest(total, Convert.ToHexStringLower(hash.GetHashAndReset())); } + /// Reads the temporary file back and compares its SHA-256 with the one computed while writing. + private static async Task VerifyFromDiskAsync(string tempPath, FileDigest digest, CancellationToken ct) + { + string onDisk; + await using (var stream = new FileStream(tempPath, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan)) + { + onDisk = Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false)); + } + + if (!string.Equals(onDisk, digest.Sha256, StringComparison.Ordinal)) + { + TryDelete(tempPath); // our own temporary file: the caller's finally would remove it too + throw new IOException("La copia scritta sul disco non corrisponde: il disco potrebbe avere problemi."); + } + } + /// Sanitized segments of a relative path ('/' or '\' separated). «..» becomes «_»: nothing escapes the root. private static List Segments(string relativePath) { diff --git a/src/Febe.Core/Storage/IExportStore.cs b/src/Febe.Core/Storage/IExportStore.cs index 77f3241..0cd89ec 100644 --- a/src/Febe.Core/Storage/IExportStore.cs +++ b/src/Febe.Core/Storage/IExportStore.cs @@ -1,4 +1,5 @@ using Febe.Core.Domain; +using Febe.Core.Export; namespace Febe.Core.Storage; @@ -169,6 +170,90 @@ public interface IExportStore /// Removes a job with its items. Only records: copies stay. Task DeleteRunAsync(long runId, CancellationToken ct = default); + + // Tappa E2: the copies to external folders ---------------------------------------------------------------------- + + /// Every recorded «Esporta questo account», in one read: only accounts with a row (absent = the default). + Task> ListAccountExportSwitchesAsync(CancellationToken ct = default); + + /// + /// The newest Superseded or Removed row of (destination, account) whose is + /// this SHA-256: the library file that took the place of a copied one, never copied again by itself. + /// + Task FindReplacedCopyAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default); + + /// «Una copia sola»: the newest Copied row of this original, variant and format in a destination in use, any account. + Task FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, CancellationToken ct = default); + + /// + /// The state of whole copies (, ) of (account, + /// SHA-256) pairs in one destination, for the plan: the current row (Copied or Failed) first, else the newest row + /// when Removed or Superseded, else Removed or Superseded when a row was replaced by this SHA-256 + /// (). Pairs without any are absent. + /// + Task> GetCopyStatesAsync( + long destinationId, + IReadOnlyCollection<(long AccountId, string Sha256)> keys, + CancellationToken ct = default); + + /// «Controlla le copie»: Copied or Superseded rows become Removed («Tolto», state time ) in one transaction. Returns the rows changed. + Task MarkCopiesRemovedAsync(IReadOnlyList copyIds, DateTimeOffset at, CancellationToken ct = default); + + /// + /// The library files of a «Copia in…», by media id, a page at a time (after ), present + /// or not: the plan decides. An account gives the files of its entries in the library (visible states); a filter + /// the files of its entries (with «Tutte le foto», only the files it shows). + /// + Task> ListCandidatesAsync(ExportSelection selection, long afterMediaId, int limit, CancellationToken ct = default); + + /// Jobs for the Dashboard: newest first, at most . + Task> ListRecentRunsAsync(int limit, CancellationToken ct = default); + + /// + /// The mark of each tile of a page (decision D3 of tappa E2): of the files of the entry that are due (present, of an + /// account with «Esporta questo account» on, a destination and a content type it takes), how many are copied in + /// the account's effective destination. Entries without due files are absent. + /// + Task> GetEntryMarksAsync(IReadOnlyList entryIds, CancellationToken ct = default); + + /// The mark of single files («Tutte le foto»): Copied or None; files that are not due are absent. + Task> GetFileMarksAsync(IReadOnlyList mediaIds, CancellationToken ct = default); + + /// The counts of the account card: «312 su 1.204 non ancora copiati» (decision D3 of tappa E2). + Task CountAccountFilesAsync(long accountId, CancellationToken ct = default); +} + +/// A library file a «Copia in…» may copy (one row per media, with what the plan needs of its entry). +public sealed record ExportCandidate( + long MediaId, + long EntryId, + long AccountId, + EntryKind EntryKind, + MediaKind MediaKind, + MediaState State, + string? Sha256, + long? Bytes, + string? RelativePath, + int Position, + bool InHighlight); + +/// The copy mark of a tile (spec §4.10): «Non ancora copiato», «Copiato in parte», «Copiato». +public enum ExportMark +{ + None, + Partly, + Copied, +} + +/// Counts of the due files of an account (decision D3 of tappa E2). +/// Files that go to the account's effective destination. +/// Due files «Copia in…» would copy: neither copied nor «Tolti o superati» (failed ones included). +/// Due files whose copy was removed from the destination or superseded: never copied again by themselves. +/// Due files whose last copy failed (also counted in ). +public sealed record ExportAccountCounts(int Due, int NotCopied, int RemovedOrSuperseded, int Failed) +{ + /// Due files copied. + public int Copied => Due - NotCopied - RemovedOrSuperseded; } /// A page of the items of an export job. diff --git a/src/Febe.Core/Storage/LibraryQueries.cs b/src/Febe.Core/Storage/LibraryQueries.cs index b180f76..f78171e 100644 --- a/src/Febe.Core/Storage/LibraryQueries.cs +++ b/src/Febe.Core/Storage/LibraryQueries.cs @@ -30,6 +30,22 @@ public enum LibraryKindFilter Posts, } +/// +/// The «Copie» filter (spec §4.6, §4.10), over the files that are due (decision D3 of tappa E2): «Non ancora copiati», +/// «Copiati», «Tolti o superati». Null: «Tutti». +/// +public enum LibraryCopiesFilter +{ + /// «Non ancora copiati»: an entry with a due file that «Copia in…» would copy (a failed copy included). + NotCopied, + + /// «Copiati»: an entry whose due files are all copied in their effective destination. + Copied, + + /// «Tolti o superati»: an entry with a due file whose copy was removed or superseded (never copied again by itself). + RemovedOrSuperseded, +} + /// Filters of the library mosaic and of the account tabs (spec §4.6). public sealed record LibraryFilter { @@ -54,6 +70,9 @@ public sealed record LibraryFilter /// Entry states shown. Null means (entries with files). public IReadOnlyList? States { get; init; } + + /// «Copie» (null: «Tutti»). With «Tutte le foto» it applies to each file. + public LibraryCopiesFilter? Copies { get; init; } } /// diff --git a/src/Febe.Data/Stores/EntryStore.cs b/src/Febe.Data/Stores/EntryStore.cs index f41213f..1f9754a 100644 --- a/src/Febe.Data/Stores/EntryStore.cs +++ b/src/Febe.Data/Stores/EntryStore.cs @@ -343,13 +343,13 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore // in SQL, no sort, and the day bounds are computed once per day rather than once per entry. var command = c.Command(string.Empty); var files = mode == MosaicMode.Files; - var where = BuildWhere(c, command, files ? EntriesOfFiles(filter) : filter, aggregate: true); + var where = BuildWhere(c, command, files ? EntriesOfFiles(filter) : filter, aggregate: true, files: files); var counts = files ? FileCounts(c, filter) : null; var perEntry = files && counts is null; command.CommandText = !files ? $"SELECT e.published_at FROM entry e WHERE {where} ORDER BY e.published_at" : perEntry - ? $"SELECT e.published_at, {FilesOfEntry(filter)} FROM entry e WHERE {where} ORDER BY e.published_at" + ? $"SELECT e.published_at, {FilesOfEntry(c, filter)} FROM entry e WHERE {where} ORDER BY e.published_at" : $"SELECT e.published_at, e.id FROM entry e WHERE {where} ORDER BY e.published_at"; var days = new List(); long dayStart = long.MaxValue, dayEnd = long.MinValue; @@ -417,15 +417,22 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore // --------------------------------------------------------------------------------------------- «Tutte le foto» - /// The files of «Tutte le foto» on media m: those in the library, of the kind of «Foto» or «Video». - private static string FileTerms(LibraryFilter filter) => + /// + /// The files of «Tutte le foto» on media m: those in the library, of the kind of «Foto» or «Video», and of the + /// class of the «Copie» filter. With «Copie» the term reads the entry e of the file too (account and kind), so + /// the caller must have it in scope (). + /// + internal static string FileTerms(SqliteConnection c, LibraryFilter filter) => // The unary + keeps SQLite on the key of the entry (entry_id, position) rather than on the broad state index. "+m.state IN ('Downloaded', 'Imported')" + filter.Kind switch { LibraryKindFilter.Photos => " AND m.kind = 'Photo'", LibraryKindFilter.Videos => " AND m.kind = 'Video'", _ => string.Empty, - }; + } + (filter.Copies is { } copies ? " AND " + ExportFilterSql.FileTerm(ExportFilterSql.Load(c), copies) : string.Empty); + + /// The file terms of this filter read the entry of the file (the «Copie» filter). + private static bool NeedsEntry(LibraryFilter filter) => filter.Copies is not null; /// /// The files of «Tutte le foto» of every entry, in one pass over ix_media_entry_files: over the whole library a @@ -439,7 +446,8 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore return null; } - using var command = c.Command($"SELECT m.entry_id, COUNT(*) FROM media m WHERE {FileTerms(filter)} GROUP BY m.entry_id"); + var from = NeedsEntry(filter) ? "media m JOIN entry e ON e.id = m.entry_id" : "media m"; + using var command = c.Command($"SELECT m.entry_id, COUNT(*) FROM {from} WHERE {FileTerms(c, filter)} GROUP BY m.entry_id"); var counts = new Dictionary(); using var r = command.ExecuteReader(); while (r.Read()) @@ -459,8 +467,8 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore filter.Kind is LibraryKindFilter.Photos or LibraryKindFilter.Videos ? filter with { Kind = LibraryKindFilter.Posts } : filter; /// A correlated count of the files of «Tutte le foto» of the entry e. - private static string FilesOfEntry(LibraryFilter filter) => - $"(SELECT COUNT(*) FROM media m WHERE m.entry_id = e.id AND {FileTerms(filter)})"; + private static string FilesOfEntry(SqliteConnection c, LibraryFilter filter) => + $"(SELECT COUNT(*) FROM media m WHERE m.entry_id = e.id AND {FileTerms(c, filter)})"; /// /// A window of «Tutte le foto»: the keys of the entries come from the same keyset scan of the publication index as @@ -575,7 +583,7 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore private static List<(long Id, long PublishedAt)> EntryKeys(SqliteConnection c, LibraryFilter filter, LibraryCursor? cursor, bool newer, bool inclusive, int limit) { using var command = c.Command(string.Empty); - var where = BuildWhere(c, command, filter); + var where = BuildWhere(c, command, filter, files: true); var sql = new StringBuilder($"SELECT e.id, e.published_at FROM entry e WHERE {where}"); if (cursor is { } at) { @@ -607,8 +615,9 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore { using var command = c.Command(string.Empty); var list = command.AddList("f", chunk); + var from = NeedsEntry(filter) ? "media m JOIN entry e ON e.id = m.entry_id" : "media m"; command.CommandText = "SELECT m.entry_id, m.id, m.position, m.kind, m.width, m.height, m.duration_ms, m.sha256, m.has_thumbnail " - + $"FROM media m WHERE m.entry_id IN ({list}) AND {FileTerms(filter)} ORDER BY m.entry_id, m.position"; + + $"FROM {from} WHERE m.entry_id IN ({list}) AND {FileTerms(c, filter)} ORDER BY m.entry_id, m.position"; using var r = command.ExecuteReader(); while (r.Read()) { @@ -638,11 +647,16 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore private static bool FileExists(SqliteConnection c, LibraryFilter filter, LibraryCursor cursor, bool older) { using var command = c.Command(string.Empty); - var where = BuildWhere(c, command, filter); - var terms = FileTerms(filter); + var where = BuildWhere(c, command, filter, files: true); + var terms = FileTerms(c, filter); + var position = older ? ">" : "<"; + // With «Copie» the file terms read the entry: the first branch then joins it instead of testing it apart. + var first = NeedsEntry(filter) + ? $"SELECT EXISTS (SELECT 1 FROM media m JOIN entry e ON e.id = m.entry_id WHERE m.entry_id = @xi AND m.position {position} @xn AND {terms} AND {where}) " + : $"SELECT EXISTS (SELECT 1 FROM media m WHERE m.entry_id = @xi AND m.position {position} @xn AND {terms} " + + $"AND EXISTS (SELECT 1 FROM entry e WHERE e.id = m.entry_id AND {where})) "; command.CommandText = - $"SELECT EXISTS (SELECT 1 FROM media m WHERE m.entry_id = @xi AND m.position {(older ? ">" : "<")} @xn AND {terms} " - + $"AND EXISTS (SELECT 1 FROM entry e WHERE e.id = m.entry_id AND {where})) " + first + $"OR EXISTS (SELECT 1 FROM entry e WHERE {where} AND (e.published_at, e.id) {(older ? "<" : ">")} (@xp, @xi) " + $"AND EXISTS (SELECT 1 FROM media m WHERE m.entry_id = e.id AND {terms}))"; command.With("@xp", Sql.Time(cursor.PublishedAt)).With("@xi", cursor.EntryId).With("@xn", (long)cursor.Position); @@ -730,6 +744,13 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore } /// The WHERE clause of a library filter on entry e; parameters are added to . + /// The connection (for the accounts of a search and the export tables of «Copie»). + /// The command that gets the parameters. + /// The filter. + /// + /// «Tutte le foto»: «Copie» keeps an entry when one of its files is of the chosen class, rather than judging the entry + /// as a whole (all its due files copied, for «Copiati»). + /// /// /// The clause is for a count over every entry of the filter (totals, day counts) rather than for a window. «Foto» and /// «Video» then test the key of each post, on a covering index, against one list of the entries that have such @@ -738,7 +759,7 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore /// hundred posts in index order. /// With a filter on accounts the posts are few and the EXISTS is the cheaper of the two. /// - internal static string BuildWhere(SqliteConnection c, SqliteCommand command, LibraryFilter filter, bool aggregate = false) + internal static string BuildWhere(SqliteConnection c, SqliteCommand command, LibraryFilter filter, bool aggregate = false, bool files = false) { var byList = aggregate && filter.AccountIds is not { Count: > 0 }; // The unary + on kind and key keeps SQLite on a covering index of entry (kind, state and account in the index): @@ -790,6 +811,12 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore command.With("@prov", Sql.Enum(provenance)); } + if (filter.Copies is { } copies) + { + var export = ExportFilterSql.Load(c); + parts.Add(files ? ExportFilterSql.EntryOfFiles(export, copies) : ExportFilterSql.EntryTerm(export, copies)); + } + var term = TextSearch.Normalize(filter.Search); if (term.Length > 0) { diff --git a/src/Febe.Data/Stores/ExportFilterSql.cs b/src/Febe.Data/Stores/ExportFilterSql.cs new file mode 100644 index 0000000..0ce78c0 --- /dev/null +++ b/src/Febe.Data/Stores/ExportFilterSql.cs @@ -0,0 +1,225 @@ +using System.Globalization; +using System.Text; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Storage; +using Microsoft.Data.Sqlite; + +namespace Febe.Data.Stores; + +/// +/// What the «Copie» filter, the tile marks and the account counts need of the export tables, read once per query: +/// the destinations in use, the switches that are off, «Una copia sola», and whether any copy, failure or removed or +/// superseded row exists at all (so the common cases pay nothing for what is not there). +/// +internal sealed record ExportFilterContext( + long? GeneralId, + ContentTypes GeneralTypes, + IReadOnlyList<(long AccountId, long DestinationId, ContentTypes Types)> Own, + IReadOnlySet Off, + SamePostCopies SamePost, + bool HasCopies, + bool HasFailed, + bool HasHistory) +{ + public bool HasDestination => GeneralId is not null || Own.Count > 0; + + public IEnumerable InUse => (GeneralId is { } g ? [g] : Array.Empty()).Concat(Own.Select(o => o.DestinationId)); +} + +/// +/// The SQL of decision D3 of tappa E2 on media m joined to its entry e: a file is due when it is +/// present, its account has «Esporta questo account» on and an effective destination (its own folder in use, else the +/// general folder in use), and that destination takes its content type (D4). The values (ids and content types) are +/// integers from the database and are written into the text, so the terms can be repeated in one statement without +/// parameters colliding. +/// +internal static class ExportFilterSql +{ + private const string Present = "m.sha256 IS NOT NULL AND +m.state IN ('Downloaded', 'Imported')"; + + /// The content type of a file as a bit of , as . + internal const string TypeOfFile = + "(CASE e.kind WHEN 'Post' THEN (CASE m.kind WHEN 'Photo' THEN 1 ELSE 2 END) " + + "WHEN 'Story' THEN (4 | (CASE WHEN EXISTS (SELECT 1 FROM highlight_entry he WHERE he.entry_id = e.id) THEN 8 ELSE 0 END)) " + + "WHEN 'Highlight' THEN 8 WHEN 'Tagged' THEN 16 WHEN 'ProfilePicture' THEN 32 ELSE 0 END)"; + + /// Reads the context of one query. + public static ExportFilterContext Load(SqliteConnection c) + { + long? general = null; + var generalTypes = ContentTypes.None; + var own = new List<(long, long, ContentTypes)>(); + using (var r = c.Command("SELECT id, scope, account_id, content_types FROM export_destination WHERE removed_at IS NULL").ExecuteReader()) + { + while (r.Read()) + { + if (r.GetString(1) == nameof(ExportScope.General)) + { + general = r.GetInt64(0); + generalTypes = (ContentTypes)r.GetInt32(3); + } + else if (r.GetInt64OrNull(2) is { } account) + { + own.Add((account, r.GetInt64(0), (ContentTypes)r.GetInt32(3))); + } + } + } + + var off = new HashSet(); + using (var r = c.Command("SELECT account_id FROM export_account WHERE enabled = 0").ExecuteReader()) + { + while (r.Read()) + { + off.Add(r.GetInt64(0)); + } + } + + var samePost = c.Command("SELECT value FROM setting WHERE key = @k").With("@k", ExportSettingKeys.SamePost).ExecuteScalar() is string value + && string.Equals(value, nameof(SamePostCopies.OneOnly), StringComparison.Ordinal) + ? SamePostCopies.OneOnly + : SamePostCopies.OnePerAccount; + + if (general is null && own.Count == 0) + { + return new ExportFilterContext(null, ContentTypes.None, own, off, samePost, false, false, false); + } + + var inUse = string.Join(", ", (general is { } g ? [g] : Array.Empty()).Concat(own.Select(o => o.Item2)).Select(Literal)); + bool Any(string states) => c.Command( + $"SELECT EXISTS (SELECT 1 FROM export_copy WHERE destination_id IN ({inUse}) AND state IN ({states}))").ScalarInt64() != 0; + return new ExportFilterContext(general, generalTypes, own, off, samePost, Any("'Copied'"), Any("'Failed'"), Any("'Removed', 'Superseded'")); + } + + /// The file m of entry e is due (D3). + public static string DueFile(ExportFilterContext x) + { + if (!x.HasDestination) + { + return "0"; + } + + var general = x.GeneralId is null ? "0" : TypeTerm(x.GeneralTypes); + var branches = new StringBuilder(); + foreach (var (account, _, types) in x.Own) + { + branches.Append(CultureInfo.InvariantCulture, $" WHEN {account} THEN {(x.Off.Contains(account) ? "0" : TypeTerm(types))}"); + } + + foreach (var account in x.Off.Where(a => x.Own.All(o => o.AccountId != a))) + { + branches.Append(CultureInfo.InvariantCulture, $" WHEN {account} THEN 0"); + } + + var destination = branches.Length == 0 ? general : $"(CASE e.account_id{branches} ELSE {general} END)"; + return destination == "1" ? $"({Present})" : $"({Present} AND {destination})"; + } + + /// The file is copied in its effective destination (or, with «Una copia sola», in any destination in use). + public static string Copied(ExportFilterContext x) + { + if (!x.HasCopies) + { + return "0"; + } + + return x.SamePost == SamePostCopies.OneOnly + ? $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id IN ({InUse(x)}) AND c.state = 'Copied' AND c.variant <> 'Frame')" + : $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id AND c.state = 'Copied' AND c.variant <> 'Frame')"; + } + + /// The last copy of the file in its effective destination failed («Non riuscito»): «Copia in…» tries again. + public static string Failed(ExportFilterContext x) => !x.HasFailed + ? "0" + : $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id AND c.state = 'Failed')"; + + /// + /// «Tolto o superato»: not copied, not failed, and its copy in the effective destination was removed, or a copy was + /// superseded (or removed) by this file. Never copied again by itself (D9). Two EXISTS, one per index. + /// + public static string Replaced(ExportFilterContext x) + { + if (!x.HasHistory) + { + return "0"; + } + + var destination = DestinationOf(x); + return $"(NOT {Copied(x)} AND NOT {Failed(x)} AND (" + + $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id " + + "AND c.state = 'Removed' AND c.superseded_by_sha256 IS NULL) " + + $"OR EXISTS (SELECT 1 FROM export_copy c WHERE c.superseded_by_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id " + + "AND c.state IN ('Superseded', 'Removed'))))"; + } + + /// «Non ancora copiato»: what «Copia in…» would copy (neither copied nor removed or superseded). + public static string NotCopied(ExportFilterContext x) => x.HasHistory ? $"(NOT {Copied(x)} AND NOT {Replaced(x)})" : $"(NOT {Copied(x)})"; + + /// The term of «Tutte le foto» on m (with e its entry): a due file of the chosen class. + public static string FileTerm(ExportFilterContext x, LibraryCopiesFilter filter) => filter switch + { + LibraryCopiesFilter.Copied => $"({DueFile(x)} AND {Copied(x)})", + LibraryCopiesFilter.NotCopied => $"({DueFile(x)} AND {NotCopied(x)})", + LibraryCopiesFilter.RemovedOrSuperseded => $"({DueFile(x)} AND {Replaced(x)})", + _ => throw new ArgumentOutOfRangeException(nameof(filter), filter, null), + }; + + /// + /// The term of the grouped mosaic on entry e. «Copiati»: every due file copied, behind a list of the entries + /// with a copy (materialized once, a superset); «Non ancora copiati»: a due file to copy; «Tolti o superati»: a due + /// file removed or superseded, behind the list of the entries with such a row. + /// + public static string EntryTerm(ExportFilterContext x, LibraryCopiesFilter filter) + { + if (!x.HasDestination) + { + return "0"; + } + + string Files(string term) => $"EXISTS (SELECT 1 FROM media m WHERE m.entry_id = e.id AND {DueFile(x)} AND {term})"; + return filter switch + { + LibraryCopiesFilter.Copied => !x.HasCopies + ? "0" + : $"+e.id IN (SELECT m2.entry_id FROM export_copy c JOIN media m2 ON m2.sha256 = c.source_sha256 WHERE c.destination_id IN ({InUse(x)}) " + + $"AND c.state = 'Copied' AND c.variant <> 'Frame') AND {Files("1")} AND NOT {Files($"NOT {Copied(x)}")}", + LibraryCopiesFilter.NotCopied => Files(NotCopied(x)), + LibraryCopiesFilter.RemovedOrSuperseded => !x.HasHistory + ? "0" + : $"+e.id IN (SELECT m2.entry_id FROM export_copy c JOIN media m2 ON m2.sha256 = coalesce(c.superseded_by_sha256, c.source_sha256) " + + $"WHERE c.destination_id IN ({InUse(x)}) AND c.state IN ('Removed', 'Superseded')) AND {Files(Replaced(x))}", + _ => throw new ArgumentOutOfRangeException(nameof(filter), filter, null), + }; + } + + /// With «Tutte le foto» an entry qualifies when one of its files does. + public static string EntryOfFiles(ExportFilterContext x, LibraryCopiesFilter filter) => + x.HasDestination ? $"EXISTS (SELECT 1 FROM media m WHERE m.entry_id = e.id AND {FileTerm(x, filter)})" : "0"; + + /// The effective destination of the account of e: its own folder, else the general one (NULL: none). + public static string DestinationOf(ExportFilterContext x) + { + var general = x.GeneralId is { } g ? Literal(g) : "NULL"; + if (x.Own.Count == 0) + { + return general; + } + + var builder = new StringBuilder("(CASE e.account_id"); + foreach (var (account, destination, _) in x.Own) + { + builder.Append(CultureInfo.InvariantCulture, $" WHEN {account} THEN {destination}"); + } + + return builder.Append(CultureInfo.InvariantCulture, $" ELSE {general} END)").ToString(); + } + + private static string InUse(ExportFilterContext x) => string.Join(", ", x.InUse.Select(Literal)); + + private static string TypeTerm(ContentTypes types) => + (types & ContentTypes.All) == ContentTypes.All ? "1" + : (types & ContentTypes.All) == ContentTypes.None ? "0" + : string.Create(CultureInfo.InvariantCulture, $"(({TypeOfFile} & {(int)(types & ContentTypes.All)}) <> 0)"); + + private static string Literal(long value) => value.ToString(CultureInfo.InvariantCulture); +} diff --git a/src/Febe.Data/Stores/ExportStore.cs b/src/Febe.Data/Stores/ExportStore.cs index 23fff09..4bb1f39 100644 --- a/src/Febe.Data/Stores/ExportStore.cs +++ b/src/Febe.Data/Stores/ExportStore.cs @@ -1,4 +1,5 @@ using Febe.Core.Domain; +using Febe.Core.Export; using Febe.Core.Storage; using Microsoft.Data.Sqlite; @@ -868,4 +869,330 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore w.Command("DELETE FROM export_run WHERE id = @r").With("@r", runId).ExecuteNonQuery(); }, ct); + + // Tappa E2 ------------------------------------------------------------------------------------------------------- + + /// SQLite allows 999 parameters per statement: id lists go in chunks below that. + private const int IdChunk = 900; + + internal const string ReplacedCopySql = $""" + SELECT {CopyColumns} FROM export_copy + WHERE superseded_by_sha256 = @h AND destination_id = @d AND account_id = @a AND state IN ('Superseded', 'Removed') + ORDER BY id DESC LIMIT 1 + """; + + internal const string CopiedElsewhereSql = $""" + SELECT {CopyColumns} FROM export_copy + WHERE source_sha256 = @h AND variant = @v AND format = @f AND state = 'Copied' AND account_id IS NOT NULL + AND destination_id IN (SELECT id FROM export_destination WHERE removed_at IS NULL) + ORDER BY id DESC LIMIT 1 + """; + + internal const string RecentRunsSql = $"SELECT {RunColumns} FROM export_run ORDER BY started_at DESC, id DESC LIMIT @limit"; + + /// The whole copies of a destination for some originals (ix_export_copy_sha256); @d and the list of SHA-256. + internal static string CopyStatesSql(string shaList) => $""" + SELECT account_id, source_sha256, state, id FROM export_copy + WHERE source_sha256 IN ({shaList}) AND destination_id = @d AND account_id IS NOT NULL AND variant = 'Whole' AND format = 'Original' + """; + + /// The rows of a destination superseded or removed in favour of some files (ix_export_copy_superseded_by). + internal static string ReplacedStatesSql(string shaList) => $""" + SELECT account_id, superseded_by_sha256, state, id FROM export_copy + WHERE superseded_by_sha256 IN ({shaList}) AND destination_id = @d AND account_id IS NOT NULL AND state IN ('Superseded', 'Removed') + """; + + private const string CandidateColumns = + "m.id, m.entry_id, e.account_id, e.kind, m.kind, m.state, m.sha256, m.bytes, m.relative_path, m.position, " + + "EXISTS (SELECT 1 FROM highlight_entry he WHERE he.entry_id = e.id)"; + + private static ExportCandidate ReadCandidate(SqliteDataReader r) => new( + r.GetInt64(0), + r.GetInt64(1), + r.GetInt64(2), + r.GetEnum(3), + r.GetEnum(4), + r.GetEnum(5), + r.GetTextOrNull(6), + r.GetInt64OrNull(7), + r.GetTextOrNull(8), + r.GetInt32(9), + r.GetBool(10)); + + public Task> ListAccountExportSwitchesAsync(CancellationToken ct = default) => + db.ReadAsync>( + c => + { + var switches = new Dictionary(); + using var r = c.Command("SELECT account_id, enabled FROM export_account").ExecuteReader(); + while (r.Read()) + { + switches[r.GetInt64(0)] = r.GetBool(1); + } + + return switches; + }, + ct); + + public Task FindReplacedCopyAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default) + { + var sha = ExportValues.Sha(sha256, nameof(sha256)); + return db.ReadAsync( + c => ReadFirst(c.Command(ReplacedCopySql).With("@h", sha).With("@d", destinationId).With("@a", accountId), ReadCopy), + ct); + } + + public Task FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, CancellationToken ct = default) + { + var sha = ExportValues.Sha(sha256, nameof(sha256)); + return db.ReadAsync( + c => ReadFirst(c.Command(CopiedElsewhereSql).With("@h", sha).With("@v", Sql.Enum(variant)).With("@f", Sql.Enum(format)), ReadCopy), + ct); + } + + public Task> GetCopyStatesAsync( + long destinationId, + IReadOnlyCollection<(long AccountId, string Sha256)> keys, + CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(keys); + var wanted = keys.Select(k => (k.AccountId, Sha256: ExportValues.Sha(k.Sha256, nameof(keys)))).ToHashSet(); + return db.ReadAsync>( + c => + { + // Per pair: the current row (Copied or Failed), else the newest row when Removed or Superseded, else a row + // replaced by this file. Rows of other accounts that share a SHA-256 are read and dropped here. + var current = new Dictionary<(long, string), ExportCopyState>(); + var newest = new Dictionary<(long, string), (long Id, ExportCopyState State)>(); + var replaced = new Dictionary<(long, string), (long Id, ExportCopyState State)>(); + void Keep(Dictionary<(long, string), (long Id, ExportCopyState State)> into, (long, string) key, long id, ExportCopyState state) + { + if (!into.TryGetValue(key, out var seen) || seen.Id < id) + { + into[key] = (id, state); + } + } + + void Read(Func sql, string[] chunk, Action<(long, string), ExportCopyState, long> add) + { + using var command = c.Command(string.Empty).With("@d", destinationId); + command.CommandText = sql(command.AddList("h", chunk)); + using var r = command.ExecuteReader(); + while (r.Read()) + { + var key = (r.GetInt64(0), r.GetString(1)); + if (wanted.Contains(key)) + { + add(key, r.GetEnum(2), r.GetInt64(3)); + } + } + } + + foreach (var chunk in wanted.Select(k => k.Sha256).Distinct(StringComparer.Ordinal).Chunk(IdChunk)) + { + Read(CopyStatesSql, chunk, (key, state, id) => + { + if (state is ExportCopyState.Copied or ExportCopyState.Failed) + { + current[key] = state; + } + else + { + Keep(newest, key, id, state); + } + }); + Read(ReplacedStatesSql, chunk, (key, state, id) => Keep(replaced, key, id, state)); + } + + var result = new Dictionary<(long AccountId, string Sha256), ExportCopyState>(); + foreach (var key in wanted) + { + if (current.TryGetValue(key, out var state)) + { + result[key] = state; + } + else if (newest.TryGetValue(key, out var history)) + { + result[key] = history.State; + } + else if (replaced.TryGetValue(key, out var by)) + { + result[key] = by.State; + } + } + + return result; + }, + ct); + } + + public Task MarkCopiesRemovedAsync(IReadOnlyList copyIds, DateTimeOffset at, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(copyIds); + if (copyIds.Count == 0) + { + return Task.FromResult(0); + } + + return db.WriteAsync( + w => + { + var changed = 0; + foreach (var chunk in copyIds.Distinct().Chunk(IdChunk)) + { + var command = w.Command(string.Empty).With("@at", Sql.Time(at)); + var list = command.AddList("i", chunk); + // A Superseded row keeps the SHA-256 of the file that replaced it: still never copied again by itself. + command.CommandText = $"UPDATE export_copy SET state = 'Removed', state_changed_at = @at WHERE id IN ({list}) AND state IN ('Copied', 'Superseded')"; + changed += command.ExecuteNonQuery(); + } + + return changed; + }, + ct); + } + + public Task> ListCandidatesAsync(ExportSelection selection, long afterMediaId, int limit, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(selection); + var n = Math.Clamp(limit, 1, 10_000); + return db.ReadAsync>( + c => + { + List Page(Func where) + { + using var command = c.Command(string.Empty).With("@after", afterMediaId).With("@n", (long)n); + var terms = where(command); + command.CommandText = $"SELECT {CandidateColumns} FROM media m JOIN entry e ON e.id = m.entry_id WHERE {terms} AND m.id > @after ORDER BY m.id LIMIT @n"; + return ReadAll(command, ReadCandidate); + } + + // Id lists go in chunks: each chunk gives its first n files after the key, and the first n of all of them are + // the page. + List ByIds(IReadOnlyList ids, string column) => + ids.Distinct().Chunk(IdChunk) + .SelectMany(chunk => Page(command => $"{column} IN ({command.AddList("x", chunk)})")) + .OrderBy(x => x.MediaId) + .Take(n) + .ToList(); + + return selection switch + { + ExportSelection.Media media => ByIds(media.MediaIds, "m.id"), + ExportSelection.Entries entries => ByIds(entries.EntryIds, "m.entry_id"), + ExportSelection.Account account => Page(command => + { + command.With("@acc", account.AccountId); + return $"e.account_id = @acc AND +e.state IN ({command.AddList("st", EntryStateRules.Visible.Select(s => s.ToString()))})"; + }), + ExportSelection.Filter filter => Page(command => + { + var where = EntryStore.BuildWhere(c, command, filter.LibraryFilter, aggregate: true, files: filter.Mode == MosaicMode.Files); + // «Tutte le foto»: only the files the mosaic shows (EntryStore.FileTerms, on m with its entry e). + return filter.Mode == MosaicMode.Files ? $"{where} AND {EntryStore.FileTerms(c, filter.LibraryFilter)}" : where; + }), + _ => throw new ArgumentOutOfRangeException(nameof(selection)), + }; + }, + ct); + } + + public Task> ListRecentRunsAsync(int limit, CancellationToken ct = default) => + db.ReadAsync>( + c => ReadAll(c.Command(RecentRunsSql).With("@limit", (long)Math.Clamp(limit, 1, 1000)), ReadRun), + ct); + + public Task> GetEntryMarksAsync(IReadOnlyList entryIds, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(entryIds); + return db.ReadAsync>( + c => + { + var marks = new Dictionary(); + var x = ExportFilterSql.Load(c); + if (!x.HasDestination || entryIds.Count == 0) + { + return marks; + } + + foreach (var chunk in entryIds.Distinct().Chunk(IdChunk)) + { + using var command = c.Command(string.Empty); + var list = command.AddList("x", chunk); + command.CommandText = $""" + SELECT m.entry_id, COUNT(*), SUM(CASE WHEN {ExportFilterSql.Copied(x)} THEN 1 ELSE 0 END) + FROM media m JOIN entry e ON e.id = m.entry_id + WHERE m.entry_id IN ({list}) AND {ExportFilterSql.DueFile(x)} + GROUP BY m.entry_id + """; + using var r = command.ExecuteReader(); + while (r.Read()) + { + var due = r.GetInt32(1); + var copied = r.GetInt32(2); + marks[r.GetInt64(0)] = copied == 0 ? ExportMark.None : copied >= due ? ExportMark.Copied : ExportMark.Partly; + } + } + + return marks; + }, + ct); + } + + public Task> GetFileMarksAsync(IReadOnlyList mediaIds, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(mediaIds); + return db.ReadAsync>( + c => + { + var marks = new Dictionary(); + var x = ExportFilterSql.Load(c); + if (!x.HasDestination || mediaIds.Count == 0) + { + return marks; + } + + foreach (var chunk in mediaIds.Distinct().Chunk(IdChunk)) + { + using var command = c.Command(string.Empty); + var list = command.AddList("x", chunk); + command.CommandText = $""" + SELECT m.id, {ExportFilterSql.Copied(x)} FROM media m JOIN entry e ON e.id = m.entry_id + WHERE m.id IN ({list}) AND {ExportFilterSql.DueFile(x)} + """; + using var r = command.ExecuteReader(); + while (r.Read()) + { + marks[r.GetInt64(0)] = r.GetInt64(1) != 0 ? ExportMark.Copied : ExportMark.None; + } + } + + return marks; + }, + ct); + } + + public Task CountAccountFilesAsync(long accountId, CancellationToken ct = default) => + db.ReadAsync( + c => + { + var x = ExportFilterSql.Load(c); + if (!x.HasDestination) + { + return new ExportAccountCounts(0, 0, 0, 0); + } + + using var command = c.Command($""" + SELECT COUNT(*), + ifnull(SUM(CASE WHEN {ExportFilterSql.NotCopied(x)} THEN 1 ELSE 0 END), 0), + ifnull(SUM(CASE WHEN {ExportFilterSql.Replaced(x)} THEN 1 ELSE 0 END), 0), + ifnull(SUM(CASE WHEN {ExportFilterSql.Failed(x)} AND NOT {ExportFilterSql.Copied(x)} THEN 1 ELSE 0 END), 0) + FROM media m JOIN entry e ON e.id = m.entry_id + WHERE e.account_id = @a AND {ExportFilterSql.DueFile(x)} + """).With("@a", accountId); + using var r = command.ExecuteReader(); + r.Read(); + return new ExportAccountCounts(r.GetInt32(0), r.GetInt32(1), r.GetInt32(2), r.GetInt32(3)); + }, + ct); } diff --git a/src/Febe.Web/Api/SettingsApi.cs b/src/Febe.Web/Api/SettingsApi.cs index baee7ae..8f38d92 100644 --- a/src/Febe.Web/Api/SettingsApi.cs +++ b/src/Febe.Web/Api/SettingsApi.cs @@ -231,14 +231,16 @@ public static class SettingsApi throw new BadRequestException("Per confermare scrivi la parola «ricostruisci»."); } + // An import service built without the shared gate (a composition of tests) is still checked by itself. if ((await import.GetAsync(ct).ConfigureAwait(false)).ActiveRunId is not null) { - throw new BadRequestException("C'è un'importazione al lavoro: aspetta che finisca, poi ricostruisci."); + throw new BadRequestException(LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Import)); } - if (!job.TryStart()) + // The gate covers import, copies to external folders and another rebuild (spec §4.10). + if (!job.TryStart(out var busy)) { - throw new BadRequestException("La ricostruzione è già in corso."); + throw new BadRequestException(busy ?? LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Rebuild)); } return ApiHttp.Message("Ricostruzione avviata: Febe rilegge le cartelle degli account e i loro file _febe.jsonl. Nessun file viene spostato o cancellato."); diff --git a/src/Febe.Web/FebeWeb.cs b/src/Febe.Web/FebeWeb.cs index d4c6254..67a4354 100644 --- a/src/Febe.Web/FebeWeb.cs +++ b/src/Febe.Web/FebeWeb.cs @@ -73,10 +73,13 @@ public static class FebeWeb services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); + // One gate for import, copies to external folders and rebuild (spec §4.10); the composition may register its own + // instance first, the one its import service already uses. + services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(sp => sp.GetService() is { } import ? new ImportHub(import, sp.GetRequiredService(), sp.GetRequiredService()) - : new ImportHub(sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), options, sp.GetRequiredService())); + : new ImportHub(sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), options, sp.GetRequiredService(), sp.GetRequiredService())); services.AddHttpContextAccessor(); if (options.Access == AccessMode.Password && !string.IsNullOrEmpty(options.Password)) { diff --git a/src/Febe.Web/Import/ImportHub.cs b/src/Febe.Web/Import/ImportHub.cs index ec1fab2..6d3fdfc 100644 --- a/src/Febe.Web/Import/ImportHub.cs +++ b/src/Febe.Web/Import/ImportHub.cs @@ -21,6 +21,7 @@ public sealed class ImportHub : IAsyncDisposable private readonly IClock _clock; private readonly FebeWebOptions? _options; private readonly LibraryChanges _changes; + private readonly LongWorkGate? _longWork; private readonly bool _owned; private ImportService? _service; private bool _stale; @@ -35,9 +36,13 @@ public sealed class ImportHub : IAsyncDisposable _service.ProgressChanged += OnProgress; } - /// Builds its own service over the library of the web host. - public ImportHub(IFebeStorage storage, FebeLibrary library, IClock clock, FebeWebOptions options, LibraryChanges changes) + /// + /// Builds its own service over the library of the web host. is the gate shared with the + /// copies to external folders and the rebuild (null: the import alone, as in some tests). + /// + public ImportHub(IFebeStorage storage, FebeLibrary library, IClock clock, FebeWebOptions options, LibraryChanges changes, LongWorkGate? longWork = null) { + _longWork = longWork; _storage = storage ?? throw new ArgumentNullException(nameof(storage)); _library = library ?? throw new ArgumentNullException(nameof(library)); _clock = clock ?? throw new ArgumentNullException(nameof(clock)); @@ -127,6 +132,7 @@ public sealed class ImportHub : IAsyncDisposable SetFileTimeToPublication = settings.SetFileTimeToPublication, Sources = SourceRoot is { } root ? ImportSourceOptions.Docker(root) : ImportSourceOptions.AnyFolder, DataFolder = library.Data.Root, + Gate = _longWork, }); } diff --git a/src/Febe.Web/Library/DataFolderServices.cs b/src/Febe.Web/Library/DataFolderServices.cs index c824448..b89dc15 100644 --- a/src/Febe.Web/Library/DataFolderServices.cs +++ b/src/Febe.Web/Library/DataFolderServices.cs @@ -156,9 +156,10 @@ public sealed class FolderSizes(IClock clock) /// /// «Ricostruisci il database dalla libreria» (spec §8.5) as a background job with its progress and its last report, -/// one at a time. It never moves, renames or deletes a file (rule 12). +/// one at a time, never together with an import or a copy to external folders (the shared , +/// spec §4.10). It never moves, renames or deletes a file (rule 12). /// -public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock clock, LibraryChanges changes) +public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock clock, LibraryChanges changes, LongWorkGate gate) { private readonly Lock _gate = new(); private Task? _task; @@ -176,18 +177,32 @@ public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock } } - /// Starts the rebuild; false when one is already running. - public bool TryStart() + /// Starts the rebuild; false when one is already running or another long job holds the gate. + public bool TryStart() => TryStart(out _); + + /// + /// Starts the rebuild; false, with the Italian reason in , when a rebuild, an import or a copy + /// to external folders is running. + /// + public bool TryStart(out string? busy) { lock (_gate) { if (_task is { IsCompleted: false }) { + busy = LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Rebuild); return false; } + if (!gate.TryEnter(LongWorkKind.Rebuild, out var lease, out var holder)) + { + busy = LongWorkGate.BusyMessage(LongWorkKind.Rebuild, holder!.Value); + return false; + } + + busy = null; State = RebuildState.Idle with { Running = true, StartedAt = clock.Now }; - _task = Task.Run(RunAsync); + _task = Task.Run(() => RunAsync(lease)); return true; } } @@ -195,8 +210,9 @@ public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock /// Waits for the running rebuild (tests). public Task WaitAsync() => _task ?? Task.CompletedTask; - private async Task RunAsync() + private async Task RunAsync(IDisposable lease) { + using var held = lease; var progress = new SyncProgress(p => State = State with { Folder = p.Folder, FoldersDone = p.FoldersDone, FoldersTotal = p.FoldersTotal, FilesChecked = p.FilesChecked }); try { diff --git a/tests/Febe.Tests/Export/ExportCopiesFilterTests.cs b/tests/Febe.Tests/Export/ExportCopiesFilterTests.cs new file mode 100644 index 0000000..11c4b3a --- /dev/null +++ b/tests/Febe.Tests/Export/ExportCopiesFilterTests.cs @@ -0,0 +1,124 @@ +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Storage; +using Febe.Data; +using Febe.Tests.Data; +using Febe.Tests.Support; + +namespace Febe.Tests.Export; + +/// +/// The «Copie» filter, the tile marks, the account counts and the store lookups of tappa E2 on a small real database +/// (decision D3: only due files count). WP5 of tappa E2 adds the full set and the timings over 200,000 entries. +/// +[TestClass] +public sealed class ExportCopiesFilterTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task TheCopiesFilterSplitsDueFilesIntoCopiedNotCopiedAndRemoved() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var w = await ExportWorld.CreateAsync(db); + // A post of marta.demo with two photos: only the first is copied («Copiato in parte»). + var pair = await db.Entries.AddAsync( + Make.Entry(w.Marta, "777", Make.T0.AddDays(1)), + [Make.Stored(Make.Photo(1), Make.Sha(2), "post/b1.jpg"), Make.Stored(Make.Photo(2), Make.Sha(3), "post/b2.jpg")], + ct); + var pairEntry = pair.Stored.Entry.Id; + + // Marta's own folder has her shared post and the first photo of the pair; luca.demo's tagged post was copied + // in the general folder and then removed from it. + await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own), ct); + await db.Exports.AddCopyAsync(w.WholeCopy("b1.jpg", destination: w.Own, media: pair.Stored.Media[0].Id) with { SourceSha256 = Make.Sha(2), CopySha256 = Make.Sha(2) }, ct); + var removed = await db.Exports.AddCopyAsync( + w.WholeCopy("luca.demo/a.jpg", destination: w.General, account: w.Luca, media: w.LucaMedia) with { State = ExportCopyState.Removed }, + ct); + + Assert.IsTrue(AreSame([w.MartaEntry], await EntriesAsync(db, LibraryCopiesFilter.Copied, ct))); + Assert.IsTrue(AreSame([pairEntry], await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct))); + Assert.IsTrue(AreSame([w.LucaEntry], await EntriesAsync(db, LibraryCopiesFilter.RemovedOrSuperseded, ct))); + Assert.AreEqual(new LibraryTotals(1, 1), await db.Entries.GetLibraryTotalsAsync(new LibraryFilter { Copies = LibraryCopiesFilter.Copied }, ct)); + Assert.AreEqual(1, (await db.Entries.CountLibraryByDayAsync(new LibraryFilter { Copies = LibraryCopiesFilter.NotCopied }, TestZones.Rome, ct: ct)).Sum(d => d.Count)); + + // «Tutte le foto» judges each file: the copied photo of the pair is «Copiato», the other «Non ancora copiato». + var copiedFiles = await FilesAsync(db, LibraryCopiesFilter.Copied, ct); + Assert.IsTrue(AreSame([w.MartaMedia, pair.Stored.Media[0].Id], copiedFiles)); + Assert.IsTrue(AreSame([pair.Stored.Media[1].Id], await FilesAsync(db, LibraryCopiesFilter.NotCopied, ct))); + Assert.AreEqual(2, (await db.Entries.CountLibraryByDayAsync(new LibraryFilter { Copies = LibraryCopiesFilter.Copied }, TestZones.Rome, MosaicMode.Files, ct)).Sum(d => d.Count)); + Assert.AreEqual(2, (await db.Entries.CountLibraryByDayAsync(new LibraryFilter { Copies = LibraryCopiesFilter.Copied, AccountIds = [w.Marta] }, TestZones.Rome, MosaicMode.Files, ct)).Sum(d => d.Count)); + Assert.AreEqual(0, (await db.Entries.CountLibraryByDayAsync(new LibraryFilter { Copies = LibraryCopiesFilter.Copied, AccountIds = [w.Luca] }, TestZones.Rome, MosaicMode.Files, ct)).Sum(d => d.Count)); + + var marks = await db.Exports.GetEntryMarksAsync([w.MartaEntry, w.LucaEntry, pairEntry], ct); + Assert.AreEqual(ExportMark.Copied, marks[w.MartaEntry]); + Assert.AreEqual(ExportMark.None, marks[w.LucaEntry]); + Assert.AreEqual(ExportMark.Partly, marks[pairEntry]); + var fileMarks = await db.Exports.GetFileMarksAsync([.. pair.Stored.Media.Select(m => m.Id)], ct); + Assert.AreEqual(ExportMark.Copied, fileMarks[pair.Stored.Media[0].Id]); + Assert.AreEqual(ExportMark.None, fileMarks[pair.Stored.Media[1].Id]); + Assert.AreEqual(new ExportAccountCounts(3, 1, 0, 0), await db.Exports.CountAccountFilesAsync(w.Marta, ct)); + Assert.AreEqual(new ExportAccountCounts(1, 0, 1, 0), await db.Exports.CountAccountFilesAsync(w.Luca, ct)); + + // «Esporta questo account» off: marta.demo has no due files any more. + await db.Exports.SetAccountExportEnabledAsync(w.Marta, false, ct); + Assert.IsEmpty(await EntriesAsync(db, LibraryCopiesFilter.Copied, ct)); + Assert.IsEmpty(await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct)); + Assert.AreEqual(new ExportAccountCounts(0, 0, 0, 0), await db.Exports.CountAccountFilesAsync(w.Marta, ct)); + Assert.IsFalse((await db.Exports.GetEntryMarksAsync([w.MartaEntry], ct)).ContainsKey(w.MartaEntry)); + var switches = await db.Exports.ListAccountExportSwitchesAsync(ct); + Assert.IsFalse(switches[w.Marta]); + Assert.IsFalse(switches.ContainsKey(w.Luca)); + + // «Controlla le copie» turns a Copied row into Removed. + Assert.AreEqual(1, await db.Exports.MarkCopiesRemovedAsync([removed.Id, (await db.Exports.FindCurrentCopyAsync(new ExportCopyIdentity(w.Own, w.Marta, Make.Sha(1), ExportVariant.Whole, ExportFormat.Original, null), ct))!.Id], Make.T0.AddDays(2), ct)); + } + + [TestMethod] + public async Task TheStoreAnswersThePlannerLookups() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var w = await ExportWorld.CreateAsync(db); + var copy = await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own), ct); + await db.Exports.AddCopyAsync( + w.WholeCopy("luca.demo/old.jpg", destination: w.General, account: w.Luca, media: w.LucaMedia) with + { + SourceSha256 = Make.Sha(9), + CopySha256 = Make.Sha(9), + State = ExportCopyState.Superseded, + SupersededBySha256 = Make.Sha(1), + }, + ct); + + var states = await db.Exports.GetCopyStatesAsync(w.General, [(w.Luca, Make.Sha(1)), (w.Marta, Make.Sha(1))], ct); + Assert.AreEqual(ExportCopyState.Superseded, states[(w.Luca, Make.Sha(1))]); + Assert.IsFalse(states.ContainsKey((w.Marta, Make.Sha(1)))); + Assert.AreEqual(ExportCopyState.Copied, (await db.Exports.GetCopyStatesAsync(w.Own, [(w.Marta, Make.Sha(1))], ct))[(w.Marta, Make.Sha(1))]); + Assert.IsNotNull(await db.Exports.FindReplacedCopyAsync(w.General, w.Luca, Make.Sha(1), ct)); + Assert.IsNull(await db.Exports.FindReplacedCopyAsync(w.Own, w.Luca, Make.Sha(1), ct)); + Assert.AreEqual(copy.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original, ct))!.Id); + + var byAccount = await db.Exports.ListCandidatesAsync(new ExportSelection.Account(w.Marta), 0, 10, ct); + Assert.AreEqual(w.MartaMedia, byAccount.Single().MediaId); + Assert.AreEqual(EntryKind.Post, byAccount[0].EntryKind); + var byFilter = await db.Exports.ListCandidatesAsync(new ExportSelection.Filter(new LibraryFilter(), MosaicMode.Files), 0, 10, ct); + Assert.HasCount(2, byFilter); + Assert.AreEqual(w.LucaMedia, (await db.Exports.ListCandidatesAsync(new ExportSelection.Entries([w.LucaEntry, w.MartaEntry]), w.MartaMedia, 10, ct)).Single().MediaId); + Assert.AreEqual(w.MartaMedia, (await db.Exports.ListCandidatesAsync(new ExportSelection.Media([w.MartaMedia, w.LucaMedia]), 0, 1, ct)).Single().MediaId); + + var run = await db.Exports.CreateRunAsync(new ExportRun { DestinationId = w.General, StartedAt = Make.T0 }, ct); + Assert.AreEqual(run.Id, (await db.Exports.ListRecentRunsAsync(5, ct)).Single().Id); + } + + private static async Task> EntriesAsync(FebeDatabase db, LibraryCopiesFilter filter, CancellationToken ct) => + [.. (await db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = new LibraryFilter { Copies = filter } }, ct)).Tiles.Select(t => t.EntryId)]; + + private static async Task> FilesAsync(FebeDatabase db, LibraryCopiesFilter filter, CancellationToken ct) => + [.. (await db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = new LibraryFilter { Copies = filter }, Mode = MosaicMode.Files }, ct)).Tiles.Select(t => t.CoverMediaId!.Value)]; + + private static bool AreSame(IEnumerable expected, IEnumerable actual) => expected.Order().SequenceEqual(actual.Order()); +} diff --git a/tests/Febe.Tests/Export/ExportCopyJobTests.cs b/tests/Febe.Tests/Export/ExportCopyJobTests.cs new file mode 100644 index 0000000..a02db4d --- /dev/null +++ b/tests/Febe.Tests/Export/ExportCopyJobTests.cs @@ -0,0 +1,358 @@ +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Library; +using Febe.Tests.Support; + +namespace Febe.Tests.Export; + +/// +/// The copy job of tappa E2 (WP1b) on a real library and real folders: paths, never overwriting, adoption by path, +/// «Tolto» and «Copia di nuovo», pause of a missing destination, engine sessions, leftovers and «Superato». WP5 adds +/// the full set. +/// +[TestClass] +public sealed class ExportCopyJobTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task ACopyGoesUnderTheAccountSegmentAndIsNotWrittenTwice() + { + var ct = TestContext.CancellationToken; + await using var w = await World.CreateAsync(); + var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "777", Make.T0.AddDays(-1)), [TestFile.Photo(1, 1), TestFile.Photo(2, 2)]); + var usb = await w.GeneralAsync(ct); + + var plan = await w.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct); + Assert.AreEqual(2, plan.Files); + Assert.AreEqual(usb.Id, plan.Destinations.Single().DestinationId); + Assert.IsNull(plan.Destinations.Single().Problem); + + var start = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct); + await w.Service.WaitAsync(ct); + var run = (await w.Library.Db.Exports.GetRunAsync(start.Runs.Single().Id, ct))!; + Assert.AreEqual(ExportRunState.Completed, run.State, run.LastError); + foreach (var media in post.Media) + { + var copied = Path.Combine(w.Usb, "marta.demo", LibraryLayout.ToPlatform(media.RelativePath!)); + Assert.IsTrue(File.Exists(copied), copied); + CollectionAssert.AreEqual(await File.ReadAllBytesAsync(w.Library.Layout.FullPath(w.Marta, media.RelativePath!), ct), await File.ReadAllBytesAsync(copied, ct)); + } + + Assert.IsEmpty(Directory.GetFiles(w.Usb, "*.part", SearchOption.AllDirectories)); + var report = await w.Service.Reports.BuildAsync(run.Id, ct); + Assert.AreEqual(2, report.ByState[ExportItemState.Copied]); + Assert.AreEqual(2, report.Accounts.Single().Copied); + + // Nothing is written twice: the plan says «già copiati», a second job finds them. + var again = await w.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct); + Assert.AreEqual(0, again.Files); + Assert.AreEqual(2, again.AlreadyCopied); + var second = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Entries([post.Entry.Id])), ct); + await w.Service.WaitAsync(ct); + Assert.AreEqual(2, (await w.Library.Db.Exports.GetRunSummaryAsync(second.Runs.Single().Id, ct)).ByState[ExportItemState.AlreadyCopied]); + Assert.HasCount(2, Directory.GetFiles(w.Usb, "*", SearchOption.AllDirectories)); + } + + [TestMethod] + public async Task ARemovedCopyIsNotCopiedAgainUnlessAsked() + { + var ct = TestContext.CancellationToken; + await using var w = await World.CreateAsync(); + var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "778", Make.T0.AddDays(-1)), [TestFile.Photo(1, 3)]); + await w.GeneralAsync(ct); + var request = new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)); + await w.Service.StartAsync(request, ct); + await w.Service.WaitAsync(ct); + var copy = Path.Combine(w.Usb, "marta.demo", LibraryLayout.ToPlatform(post.Media[0].RelativePath!)); + File.Delete(copy); // Alberto removed it from the disk + + var skipped = await w.Service.StartAsync(request, ct); + await w.Service.WaitAsync(ct); + var item = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = skipped.Runs.Single().Id }, ct)).Single(); + Assert.AreEqual(ExportItemState.Skipped, item.State); + Assert.AreEqual(ExportText.Notes.Removed, item.Note); + Assert.IsFalse(File.Exists(copy)); + var plan = await w.Service.PlanAsync(request, ct); + Assert.AreEqual((0, 1), (plan.Files, plan.RemovedOrSuperseded)); + + var again = await w.Service.StartAsync(request with { CopyAgain = true }, ct); + await w.Service.WaitAsync(ct); + Assert.AreEqual(1, again.Plan.Files); + Assert.AreEqual(ExportItemState.Copied, (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = again.Runs.Single().Id }, ct)).Single().State); + Assert.IsTrue(File.Exists(copy)); + } + + [TestMethod] + public async Task AFileAlreadyThereIsAdoptedAndAnotherFileIsNeverOverwritten() + { + var ct = TestContext.CancellationToken; + await using var w = await World.CreateAsync(); + var first = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "779", Make.T0.AddDays(-1)), [TestFile.Photo(1, 4)]); + var second = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "780", Make.T0.AddDays(-2)), [TestFile.Photo(1, 5)]); + await w.GeneralAsync(ct); + var same = Path.Combine(w.Usb, "marta.demo", LibraryLayout.ToPlatform(first.Media[0].RelativePath!)); + var other = Path.Combine(w.Usb, "marta.demo", LibraryLayout.ToPlatform(second.Media[0].RelativePath!)); + Directory.CreateDirectory(Path.GetDirectoryName(same)!); + Directory.CreateDirectory(Path.GetDirectoryName(other)!); + File.Copy(w.Library.Layout.FullPath(w.Marta, first.Media[0].RelativePath!), same); + await File.WriteAllBytesAsync(other, [1, 2, 3], ct); // something else with that name + + var start = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct); + await w.Service.WaitAsync(ct); + var items = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = start.Runs.Single().Id }, ct)).ToDictionary(i => i.MediaId!.Value); + Assert.AreEqual(ExportItemState.Adopted, items[first.Media[0].Id].State); + Assert.AreEqual(ExportItemState.Copied, items[second.Media[0].Id].State); + Assert.AreEqual(ExportText.Notes.NameTaken, items[second.Media[0].Id].Note); + CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, await File.ReadAllBytesAsync(other, ct)); + var renamed = Path.Combine(w.Usb, LibraryLayout.ToPlatform(items[second.Media[0].Id].RelativePath!)); + StringAssert.EndsWith(renamed, " (2).jpg"); + Assert.IsTrue(File.Exists(renamed)); + Assert.AreEqual(ExportCopyOrigin.Adopted, (await w.Library.Db.Exports.GetCopyAsync(items[first.Media[0].Id].CopyId!.Value, ct))!.Origin); + } + + [TestMethod] + public async Task AMissingDestinationPausesAndIsNeverCreated() + { + var ct = TestContext.CancellationToken; + await using var w = await World.CreateAsync(); + await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "781", Make.T0.AddDays(-1)), [TestFile.Photo(1, 6)]); + var usb = await w.GeneralAsync(ct); + Directory.Delete(w.Usb); // the disk was unplugged + + var plan = await w.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct); + Assert.IsNotNull(plan.Destinations.Single().Problem); + var start = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct); + await w.Service.WaitAsync(ct); + var run = (await w.Library.Db.Exports.GetRunAsync(start.Runs.Single().Id, ct))!; + Assert.AreEqual(ExportRunState.Paused, run.State); + Assert.IsFalse(Directory.Exists(w.Usb)); + var paused = (await w.Library.Db.Exports.GetDestinationAsync(usb.Id, ct))!; + Assert.IsNotNull(paused.PausedAt); + Assert.Contains("non è raggiungibile", paused.LastError!); + Assert.AreEqual(ExportItemState.Pending, (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = run.Id }, ct)).Single().State); + + // The disk is back: «Riprendi» clears the pause and copies. + Directory.CreateDirectory(w.Usb); + await w.Service.ResumeAsync(null, ct); + await w.Service.WaitAsync(ct); + Assert.AreEqual(ExportRunState.Completed, (await w.Library.Db.Exports.GetRunAsync(run.Id, ct))!.State); + Assert.IsNull((await w.Library.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt); + } + + [TestMethod] + public async Task CopiesWaitForTheEngineSessionAndForSpace() + { + var ct = TestContext.CancellationToken; + var session = new CountedSession(3); + var disk = new FakeDisk(); + await using var w = await World.CreateAsync(session, disk); + await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "782", Make.T0.AddDays(-1)), [TestFile.Photo(1, 7)]); + await w.GeneralAsync(ct); + var before = w.Library.Clock.Now; + + disk.Free = 1000; // less than the file plus 64 MB + var start = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct); + await w.Service.WaitAsync(ct); + var run = (await w.Library.Db.Exports.GetRunAsync(start.Runs.Single().Id, ct))!; + Assert.AreEqual(ExportRunState.Paused, run.State); + Assert.Contains("margine di 64 MB", run.LastError!); + Assert.AreEqual(w.Library.Clock.Now, before + TimeSpan.FromSeconds(15)); // three polls of 5 s while the session ran + + disk.Free = null; + disk.Max = 10; // a FAT32 disk, with a tiny limit for the test + await w.Service.ResumeAsync([run.Id], ct); + await w.Service.WaitAsync(ct); + var item = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = run.Id }, ct)).Single(); + Assert.AreEqual(ExportItemState.Failed, item.State); + Assert.AreEqual(ExportText.Notes.TooLargeForFileSystem, item.Note); + Assert.AreEqual(ExportRunState.Completed, (await w.Library.Db.Exports.GetRunAsync(run.Id, ct))!.State); + Assert.AreEqual(ExportCopyState.Failed, (await w.Library.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!.State); + } + + [TestMethod] + public async Task LeftoversGoOnlyInTheFoldersOfAnUnfinishedJob() + { + var ct = TestContext.CancellationToken; + await using var w = await World.CreateAsync(); + var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "783", Make.T0.AddDays(-1)), [TestFile.Photo(1, 8)]); + var usb = await w.GeneralAsync(ct); + var relative = "marta.demo/" + post.Media[0].RelativePath; + var folder = Path.GetDirectoryName(Path.Combine(w.Usb, LibraryLayout.ToPlatform(relative)))!; + Directory.CreateDirectory(folder); + var leftover = Path.Combine(folder, ".febe-0123456789ab.part"); + var elsewhere = Path.Combine(w.Usb, ".febe-ba9876543210.part"); + await File.WriteAllBytesAsync(leftover, [9], ct); + await File.WriteAllBytesAsync(elsewhere, [9], ct); + + // A job interrupted after it recorded the target path. + var run = await w.Library.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, State = ExportRunState.Running, StartedAt = w.Library.Clock.Now }, ct); + await w.Library.Db.Exports.AddItemsAsync([new ExportItem { RunId = run.Id, MediaId = post.Media[0].Id, AccountId = w.Marta.Id, SourceSha256 = post.Media[0].Sha256 }], ct); + var item = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = run.Id }, ct)).Single(); + await w.Library.Db.Exports.UpdateItemsAsync([item with { RelativePath = relative }], ct); + + Assert.AreEqual(1, await w.Service.RecoverAsync(ct)); + await w.Service.WaitAsync(ct); + Assert.AreEqual(ExportRunState.Interrupted, (await w.Library.Db.Exports.GetRunAsync(run.Id, ct))!.State); + Assert.IsFalse(File.Exists(leftover)); + Assert.IsTrue(File.Exists(elsewhere)); // the root holds no item: never cleaned + + await w.Service.ResumeAsync(null, ct); + await w.Service.WaitAsync(ct); + Assert.AreEqual(ExportItemState.Copied, (await w.Library.Db.Exports.GetItemAsync(item.Id, ct))!.State); + } + + [TestMethod] + public async Task ASwitchedOffAccountIsSkippedWhenAJobResumes() + { + var ct = TestContext.CancellationToken; + await using var w = await World.CreateAsync(); + var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "786", Make.T0.AddDays(-1)), [TestFile.Photo(1, 11)]); + var usb = await w.GeneralAsync(ct); + var run = await w.Library.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, State = ExportRunState.Interrupted, StartedAt = w.Library.Clock.Now }, ct); + await w.Library.Db.Exports.AddItemsAsync([new ExportItem { RunId = run.Id, MediaId = post.Media[0].Id, AccountId = w.Marta.Id, SourceSha256 = post.Media[0].Sha256 }], ct); + await w.Service.Destinations.SetAccountEnabledAsync(w.Marta.Id, false, ct); + + await w.Service.ResumeAsync([run.Id], ct); + await w.Service.WaitAsync(ct); + var item = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = run.Id }, ct)).Single(); + Assert.AreEqual((ExportItemState.Skipped, ExportText.Notes.NotExported), (item.State, item.Note)); + Assert.IsEmpty(Directory.GetFiles(w.Usb, "*", SearchOption.AllDirectories)); + } + + [TestMethod] + public async Task AChangedLibraryFileSupersedesItsCopies() + { + var ct = TestContext.CancellationToken; + await using var w = await World.CreateAsync(); + var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "784", Make.T0.AddDays(-1)), [TestFile.Photo(1, 9)]); + await w.GeneralAsync(ct); + var request = new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)); + await w.Service.StartAsync(request, ct); + await w.Service.WaitAsync(ct); + + // «Tieni il più grande» put another file in the slot. + var oldSha = post.Media[0].Sha256!; + var newSha = Make.Sha(4242); + await w.Library.Db.Media.MarkStoredAsync(post.Media[0].Id, new StoredFile(post.Media[0].RelativePath!, 10, newSha, null, 1, 1, null, false), MediaState.Downloaded, w.Library.Clock.Now, ct); + Assert.AreEqual(0, await ExportSupersession.FileChangedAsync(w.Library.Db, w.Marta.Id, newSha, newSha, w.Library.Clock.Now, ct)); + Assert.AreEqual(1, await ExportSupersession.FileChangedAsync(w.Library.Db, w.Marta.Id, oldSha, newSha, w.Library.Clock.Now, ct)); + var copies = await w.Library.Db.Exports.ListCopiesBySha256Async(newSha, ct); + Assert.AreEqual(ExportCopyState.Superseded, copies.Single().State); + Assert.AreEqual(1, (await w.Service.PlanAsync(request, ct)).RemovedOrSuperseded); + } + + [TestMethod] + public async Task AnExportDoesNotStartWhileAnImportHoldsTheGate() + { + var ct = TestContext.CancellationToken; + var gate = new LongWorkGate(); + await using var w = await World.CreateAsync(gate: gate); + await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "785", Make.T0.AddDays(-1)), [TestFile.Photo(1, 10)]); + await w.GeneralAsync(ct); + Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var lease, out _)); + var refused = await Assert.ThrowsExactlyAsync(() => w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct)); + Assert.StartsWith("C'è un'importazione al lavoro", refused.Message); + Assert.IsEmpty(await w.Library.Db.Exports.ListRunsAsync(ct)); + lease.Dispose(); + } + + [TestMethod] + public void PathsFollowTheLibraryTheAccountSegmentAndTheHighlightRule() + { + var naming = LibraryNaming.Default; + var account = Make.Account("marta.demo") with { Id = 1 }; + var general = new ExportDestination { Id = 1, Scope = ExportScope.General, RootPath = Path.GetTempPath(), ContentTypes = ContentTypes.All, CreatedAt = Make.T0 }; + var story = Make.Entry(1, "9001", Make.T0, EntryKind.Story); + var media = Make.Stored(Make.Photo(), Make.Sha(1), "storie/2026/x.jpg"); + + var asStory = ExportPaths.Segments(general, naming, account, story, media, "Estate", inHighlight: true, TestZones.Rome); + Assert.AreEqual("marta.demo", asStory[0]); + Assert.AreEqual("storie", asStory[1]); + + var onlyHighlights = general with { Scope = ExportScope.Account, AccountId = 1, ContentTypes = ContentTypes.Highlights }; + var asHighlight = ExportPaths.Segments(onlyHighlights, naming, account, story, media, "Estate", inHighlight: true, TestZones.Rome); + CollectionAssert.AreEqual(new[] { "evidenza", "Estate" }, asHighlight.Take(2).ToArray()); + + var imported = media with { RelativePath = "importati/IMG_0001.JPG" }; + CollectionAssert.AreEqual(new[] { "marta.demo", "importati", "IMG_0001.JPG" }, ExportPaths.Segments(general, naming, account, story, imported, null, false, TestZones.Rome).ToArray()); + var renamed = ExportPaths.Segments(general with { NamingScheme = @"{anno}\{codice}_{n}" }, naming, account, story, imported, null, false, TestZones.Rome); + CollectionAssert.AreEqual(new[] { "marta.demo", "2026", "9001_1.jpg" }, renamed.ToArray()); + + var deep = general with { RootPath = Path.Combine(Path.GetTempPath(), new string('d', 150)) }; + var fitted = ExportPaths.RelativePathFor(deep, ["marta.demo", new string('x', 120) + ".jpg"]); + Assert.IsLessThanOrEqualTo(240, Path.TrimEndingDirectorySeparator(deep.RootPath).Length + 1 + fitted.Length); + StringAssert.EndsWith(fitted, ".jpg"); + } + + private sealed class CountedSession(int polls) : IEngineSessionState + { + private int _left = polls; + + public bool InSession => Interlocked.Decrement(ref _left) >= 0; + } + + private sealed class FakeDisk : IExportDisk + { + public long? Free { get; set; } + + public long? Max { get; set; } + + public long? FreeBytes(string root) => Free; + + public long? MaxFileBytes(string root) => Max; + } + + private sealed class World : IAsyncDisposable + { + private readonly TempFolder _temp; + + private World(TempFolder temp, TestLibrary library, ExportService service, Account marta) + { + _temp = temp; + Library = library; + Service = service; + Marta = marta; + Usb = temp.Combine("usb"); + Directory.CreateDirectory(Usb); + } + + public TestLibrary Library { get; } + + public ExportService Service { get; } + + public Account Marta { get; } + + public string Usb { get; } + + public static async Task CreateAsync(IEngineSessionState? session = null, IExportDisk? disk = null, LongWorkGate? gate = null) + { + var temp = new TempFolder(); + var library = await TestLibrary.CreateAsync(temp); + var marta = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100")); + var env = new ExportEnvironment + { + Storage = library.Db, + Layout = () => library.Layout, + DataFolder = library.Data.Root, + Clock = library.Clock, + Root = ExportRootOptions.AnyFolder with { Mounts = new ProcMountInfo(() => null) }, + Disk = disk ?? new FakeDisk(), + Session = session ?? NoEngineSession.Instance, + Gate = gate, + }; + return new World(temp, library, new ExportService(env), marta); + } + + public async Task GeneralAsync(CancellationToken ct) => + (await Service.Destinations.CreateAsync(new DestinationSpec(ExportScope.General, null, Usb, "Disco USB", ContentTypes.All, null, null, null), ct)).Destination; + + public async ValueTask DisposeAsync() + { + await Service.DisposeAsync(); + await Library.DisposeAsync(); + _temp.Dispose(); + } + } +} diff --git a/tests/Febe.Tests/Export/ExportFoundationTests.cs b/tests/Febe.Tests/Export/ExportFoundationTests.cs new file mode 100644 index 0000000..9e10d0b --- /dev/null +++ b/tests/Febe.Tests/Export/ExportFoundationTests.cs @@ -0,0 +1,172 @@ +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Import; +using Febe.Core.Library; +using Febe.Tests.Import.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Export; + +/// +/// The shared pieces of tappa E2 (WP1a): the gate of long work, the mount table, the export root in Docker, the folder +/// check with its probe, the destinations with «Esporta questo account» on by default. WP5 adds the full set. +/// +[TestClass] +public sealed class ExportFoundationTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public void TheGateLetsOneLongJobRunAtATime() + { + var gate = new LongWorkGate(); + Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var lease, out _)); + Assert.AreEqual(LongWorkKind.Import, gate.Busy); + Assert.IsFalse(gate.TryEnter(LongWorkKind.Export, out _, out var busy)); + Assert.AreEqual(LongWorkKind.Import, busy); + Assert.AreEqual( + "C'è un'importazione al lavoro: aspetta che finisca o interrompila, poi copia.", + LongWorkGate.BusyMessage(LongWorkKind.Export, busy!.Value)); + + lease.Dispose(); + Assert.IsNull(gate.Busy); + Assert.IsTrue(gate.TryEnter(LongWorkKind.Rebuild, out var rebuild, out _)); + lease.Dispose(); // a second dispose of the old lease releases nothing + Assert.AreEqual(LongWorkKind.Rebuild, gate.Busy); + rebuild.Dispose(); + } + + [TestMethod] + public async Task AnImportDoesNotStartWhileTheGateIsHeld() + { + using var temp = new TempFolder(); + await using var bed = await ImportTestBed.CreateAsync(temp); + var gate = new LongWorkGate(); + await using var service = new ImportService(bed.Environment with { Gate = gate }); + Assert.IsTrue(gate.TryEnter(LongWorkKind.Export, out var lease, out _)); + + var refused = await Assert.ThrowsExactlyAsync(() => service.StartAsync(bed.Source, ct: TestContext.CancellationToken)); + Assert.StartsWith("C'è una copia nelle cartelle esterne al lavoro", refused.Message); + Assert.IsEmpty(await bed.Library.Db.Imports.ListRunsAsync(TestContext.CancellationToken)); + + lease.Dispose(); + var run = await service.StartAsync(bed.Source, ct: TestContext.CancellationToken); + await service.WaitAsync(run.Id, TestContext.CancellationToken); + Assert.IsNull(gate.Busy); // the job's lease went with it + } + + [TestMethod] + public void MountInfoGivesRootMountPointAndType() + { + const string content = """ + 22 1 8:1 / / rw,relatime shared:1 - ext4 /dev/sda1 rw + 40 22 8:17 /backup/foto /esporta/usb rw,noatime master:3 - vfat /dev/sdb1 rw + 41 22 0:50 / /esporta/nas\040rete ro,relatime - cifs //nas/copie rw + bad line + """; + var mounts = MountInfoTable.Parse(content); + Assert.HasCount(3, mounts); + Assert.AreEqual("/esporta/nas rete", mounts[2].MountPoint); + Assert.IsTrue(mounts[2].ReadOnly); + Assert.AreEqual("/backup/foto", MountInfoTable.FindContaining(mounts, "/esporta/usb/Febe")!.Root); + Assert.AreEqual("vfat", MountInfoTable.FindContaining(mounts, "/esporta/usb")!.FileSystemType); + Assert.AreEqual("/", MountInfoTable.FindContaining(mounts, "/esporta/usbx")!.MountPoint); + + var o = ExportRootOptions.Docker("/esporta", declared: true, new ProcMountInfo(() => content)); + Assert.IsFalse(ExportRoots.Evaluate(o with { Declared = false }).Active); + Assert.IsFalse(ExportRoots.Evaluate(ExportRootOptions.Docker("/esporta", declared: true, new ProcMountInfo(() => "22 1 8:1 / / rw - ext4 /dev/sda1 rw"))).Active); + if (!OperatingSystem.IsWindows()) + { + // Docker paths are Linux paths: on Windows "/esporta" becomes a drive path the table cannot hold. + Assert.IsTrue(ExportRoots.Evaluate(o).Active); + Assert.IsNull(ExportRoots.MountProblem(o, "/esporta/usb/Febe")); + Assert.Contains("sola lettura", ExportRoots.MountProblem(o, "/esporta/nas rete/x")!); + Assert.IsNotNull(ExportRoots.MountProblem(o, "/esporta/altro")); + } + + Assert.AreEqual(ExportFolderProblemKind.ParentSegment, Assert.ThrowsExactly(() => ExportRoots.Resolve(o, "usb/../../etc")).Kind); + Assert.AreEqual(ExportFolderProblemKind.ExportRootItself, Assert.ThrowsExactly(() => ExportRoots.Resolve(o, "/")).Kind); + } + + [TestMethod] + public async Task TheFolderCheckRefusesOverlapsAndLeavesNoProbe() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + var library = temp.Combine("libreria"); + var data = temp.Combine("dati"); + var outside = temp.Combine("copie"); + Directory.CreateDirectory(Path.Combine(library, "marta.demo")); + Directory.CreateDirectory(data); + Directory.CreateDirectory(outside); + var context = new ExportFolderContext( + [new(data, ProtectedFolderKind.Data, null), new(library, ProtectedFolderKind.Library, null), new(Path.Combine(library, "marta.demo"), ProtectedFolderKind.Account, "marta.demo")], + ExportRootOptions.AnyFolder); + var check = new ExportFolderCheck(new ProcMountInfo(() => null)); + + var accepted = await check.CheckAsync(outside, context, ct); + Assert.IsTrue(accepted.Accepted, accepted.Problem?.Message); + Assert.IsEmpty(Directory.GetFileSystemEntries(outside)); + Assert.AreEqual(ExportFolderProblemKind.InsideProtected, (await check.CheckAsync(Path.Combine(library, "marta.demo"), context with { Protected = context.Protected.Take(2).ToList() }, ct)).Problem!.Kind); + Assert.AreEqual(ExportFolderProblemKind.SameAsProtected, (await check.CheckAsync(data, context, ct)).Problem!.Kind); + Assert.AreEqual(ExportFolderProblemKind.ContainsProtected, (await check.CheckAsync(temp.Path, context, ct)).Problem!.Kind); + Assert.AreEqual(ExportFolderProblemKind.Missing, (await check.CheckAsync(temp.Combine("non-esiste"), context, ct)).Problem!.Kind); + Assert.AreEqual(ExportFolderProblemKind.NotFullyQualified, (await check.CheckAsync("relativa", context, ct)).Problem!.Kind); + Assert.AreEqual(ExportFolderProblemKind.RootOfDisk, (await check.CheckAsync(Path.GetPathRoot(temp.Path)!, context, ct)).Problem!.Kind); + Assert.IsFalse(Directory.Exists(temp.Combine("non-esiste"))); + } + + [TestMethod] + public async Task TheSafeWriterNeverCreatesAMissingRoot() + { + using var temp = new TempFolder(); + var root = temp.Combine("disco-assente"); + using var source = new MemoryStream([1, 2, 3]); + await Assert.ThrowsExactlyAsync(() => new SafeFileWriter().SaveAsync( + source, root, "a/b.jpg", new SafeWriteOptions { RequireExistingRoot = true, VerifyFromDisk = true }, TestContext.CancellationToken)); + Assert.IsFalse(Directory.Exists(root)); + + Directory.CreateDirectory(root); + source.Position = 0; + var saved = await new SafeFileWriter().SaveAsync(source, root, "a/b.jpg", new SafeWriteOptions { RequireExistingRoot = true, VerifyFromDisk = true }, TestContext.CancellationToken); + Assert.AreEqual("a/b.jpg", saved.RelativePath); + } + + [TestMethod] + public async Task DestinationsAreCheckedAndTheSwitchIsOnByDefault() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var account = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100"), ct); + var env = new ExportEnvironment { Storage = library.Db, Layout = () => library.Layout, DataFolder = library.Data.Root, Clock = library.Clock, Root = ExportRootOptions.AnyFolder with { Mounts = new ProcMountInfo(() => null) } }; + var destinations = new ExportDestinations(env); + var usb = temp.Combine("usb"); + Directory.CreateDirectory(usb); + + Assert.IsTrue((await destinations.ResolveAsync(account.Id, ct)) is { Enabled: true, HasDestination: false }); + await Assert.ThrowsExactlyAsync(() => destinations.CreateAsync(Spec(library.Layout.Root), ct)); + await Assert.ThrowsExactlyAsync(() => destinations.CreateAsync(Spec(usb) with { ContentTypes = ContentTypes.None }, ct)); + await Assert.ThrowsExactlyAsync(() => destinations.CreateAsync(Spec(usb) with { NamingScheme = "{inesistente}" }, ct)); + + var saved = await destinations.CreateAsync(Spec(usb) with { Label = " Disco USB " }, ct); + Assert.AreEqual("Disco USB", saved.Destination.Label); + var all = await destinations.ResolveAllAsync(ct); + Assert.AreEqual(saved.Destination.Id, all[account.Id].Destination!.Id); + Assert.IsTrue(all[account.Id].Exports); + + await destinations.SetAccountEnabledAsync(account.Id, false, ct); + Assert.IsFalse((await destinations.ResolveAsync(account.Id, ct)).Exports); + + var run = await library.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = saved.Destination.Id, StartedAt = library.Clock.Now }, ct); + await Assert.ThrowsExactlyAsync(() => destinations.RetireAsync(saved.Destination.Id, ct)); + await library.Db.Exports.UpdateRunAsync(run with { State = ExportRunState.Cancelled }, ct); + await destinations.RetireAsync(saved.Destination.Id, ct); + Assert.IsTrue(Directory.Exists(usb)); + Assert.IsFalse((await destinations.ResolveAsync(account.Id, ct)).HasDestination); + Assert.IsEmpty(await destinations.RecheckAsync(null, ct)); + + static DestinationSpec Spec(string path) => new(ExportScope.General, null, path, null, ContentTypes.All, null, null, null); + } +}