Files
Febe/src/Febe.Core/Export/ExportPlanner.cs
T
Alby96andClaude Opus 5.5 a112c92893 E2: motore delle copie esterne (porta, destinazioni, piano, copia)
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 <noreply@anthropic.com>
2026-11-27 10:55:29 +01:00

239 lines
10 KiB
C#

using System.Runtime.CompilerServices;
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>
/// 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.
/// </summary>
public sealed class ExportPlanner(ExportEnvironment env)
{
private const int PageSize = 2000;
private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env));
/// <summary>The plan of a request, for the «Copia in…» dialog.</summary>
public async Task<ExportPlan> 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);
}
/// <summary>
/// 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.
/// </summary>
internal async IAsyncEnumerable<PlannedFile> EnumerateAsync(
ExportJobRequest request,
IReadOnlyDictionary<long, EffectiveDestination> 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<long, HashSet<(long AccountId, string Sha256)>>();
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<long, IReadOnlyDictionary<(long AccountId, string Sha256), ExportCopyState>>();
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;
}
}
}
/// <summary>A file present in the library, with its SHA-256 and path.</summary>
internal static bool IsPresent(ExportCandidate c) => EntryStateRules.IsPresent(c.State) && c.Sha256 is { Length: 64 } && !string.IsNullOrEmpty(c.RelativePath);
/// <summary>The destination a present file goes to (D3), or null when it is not exported.</summary>
private static long? Due(ExportCandidate c, IReadOnlyDictionary<long, EffectiveDestination> effective) =>
IsPresent(c) && effective.TryGetValue(c.AccountId, out var e) && e.Wants(ExportPaths.TypeOf(c.EntryKind, c.MediaKind, c.InHighlight))
? e.Destination!.Id
: null;
}
/// <summary>A candidate with what the plan does with it.</summary>
/// <param name="DestinationId">Where it goes; null when not exported or missing.</param>
/// <param name="Again">Written although «Tolto» or «Superato», because «Copia di nuovo» was asked.</param>
internal sealed record PlannedFile(ExportCandidate Candidate, long? DestinationId, PlannedCopy Action, bool Again = false);
internal enum PlannedCopy
{
Write,
AlreadyCopied,
RemovedOrSuperseded,
NotExported,
Missing,
}
/// <summary>Counts of a plan while its files go by.</summary>
internal sealed class PlanTally
{
private readonly Dictionary<long, (int Files, long Bytes)> _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));
}
/// <summary>The plan. With <paramref name="checkDestinations"/> each destination is asked whether it answers now.</summary>
public async Task<ExportPlan> BuildAsync(
ExportEnvironment env,
ExportDestinations destinations,
IReadOnlyDictionary<long, EffectiveDestination> 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<ExportPlanDestination>();
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);
}
/// <summary>Destinations that get a run: those with files to write, already copied, or «tolti o superati».</summary>
public IReadOnlyCollection<long> Destinations => _byDestination.Keys;
}