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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-27 10:55:29 +01:00
1 parent 213b89a618
commit a112c92893
41 files changed
+5370 -27

No files matched your search

+642
View File
@@ -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;
/// <summary>
/// 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 (<see cref="LongWorkGate"/>), 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 <see cref="RecoverAsync"/> once; «Riprendi» is always Alberto's.
/// </summary>
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);
}
/// <summary>Progress of the running job, at most four times a second and at every change of phase (pool thread).</summary>
public event EventHandler<ExportProgress>? ProgressChanged;
/// <summary>The job ended, however it ended (pool thread): the interface refreshes tiles and filter.</summary>
public event EventHandler<ExportJobFinished>? JobFinished;
public ExportDestinations Destinations { get; }
public ExportPlanner Planner { get; }
public ExportCopier Copier { get; }
public ExportReports Reports { get; }
/// <summary>The runs of the running job; empty when idle (and for «Controlla le copie», which has none).</summary>
public IReadOnlyList<long> ActiveRunIds
{
get
{
lock (_gate)
{
return _job is { Task.IsCompleted: false } job ? job.RunIds : [];
}
}
}
/// <summary>A job is running.</summary>
public bool IsBusy
{
get
{
lock (_gate)
{
return _starting || _job is { Task.IsCompleted: false };
}
}
}
/// <summary>The last error of a background job that could not be stored with its run (normally null).</summary>
public string? LastJobError { get; private set; }
/// <summary>
/// After a restart: a job that was running becomes «interrotto» (paused and interrupted ones stay), and the
/// <c>.part</c> files of unfinished jobs are removed in the background, only in their items' folders. Never resumes
/// by itself. Returns how many jobs became interrupted.
/// </summary>
public async Task<int> 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;
}
/// <summary>The plan of a «Copia in…», for its dialog (database only, plus whether each destination answers).</summary>
public Task<ExportPlan> PlanAsync(ExportJobRequest request, CancellationToken ct = default) => Planner.PlanAsync(request, ct);
/// <summary>
/// «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.
/// </summary>
/// <exception cref="InvalidOperationException">A copy, an import or a rebuild is running.</exception>
public async Task<ExportStart> 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<ExportStart> 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<long, ExportRun>();
var pending = new List<ExportItem>();
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);
}
/// <summary>
/// «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).
/// </summary>
public async Task<IReadOnlyList<ExportRun>> ResumeAsync(IReadOnlyList<long>? runIds = null, CancellationToken ct = default)
{
EnsureIdle();
var unfinished = await _env.Storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false);
List<ExportRun> 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;
}
/// <summary>«Interrompi»: stops the running job and waits until its states are saved.</summary>
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);
}
/// <summary>
/// «Annulla»: an unfinished job becomes «annullato» (the running job is interrupted first when it holds it). Our
/// <c>.part</c> files in its folders go; no other file is touched, and the copies made stay.
/// </summary>
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);
}
}
/// <summary>
/// «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.
/// </summary>
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));
}
/// <summary>The progress of the running job, or a snapshot of the newest job.</summary>
public async Task<ExportProgress> 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<ExportItemState, int>(), _env.Clock.Now)
: await SnapshotAsync(newest, ct).ConfigureAwait(false);
}
/// <summary>Waits for the running job (if any) to end, however it ends.</summary>
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<ExportProgress> 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<ExportProgress> 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<ExportItemState, int>(), _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<long>();
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<ExportRun> 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<ExportRun> 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<long> 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<long> runIds, Func<IProgress<ExportProgress>, 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<ExportItemState, int>(), _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<long> RunIds, CancellationTokenSource Cancellation, Task Task);
private sealed class Reporter(ExportService owner) : IProgress<ExportProgress>
{
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);
}
}
}