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; }