Files
Febe/src/Febe.Core/Export/ExportService.cs
T
Alby96andClaude Opus 5.5 958cb71cd6 E3: correzioni della revisione di formati e fotogrammi
Le 16 osservazioni confermate della revisione, ognuna con la sua prova:

- JPEG: il controllo stima la memoria di lavoro del decodificatore
  (progressivo), così un file che non si decodifica esce «troppo
  grande» e non «illeggibile».
- Un EXIF che non si tiene lascia un EXIF minimo con l'orientamento,
  perché la foto convertita non esca girata.
- Fotogrammi: istanti in millisecondi interi; la copia trova l'indice
  del nome dall'istante, non dall'ordine delle righe.
- Video di durata sconosciuta misurati prima di registrare: contano
  nei limiti di 500 per richiesta e 5000 per video.
- Rimuxaggio: la durata del segmento di elst passa nell'MP4, la fine
  tagliata resta nascosta (anche nei fotogrammi).
- H.264: il punto di recupero vale come IDR solo con exact_match_flag.
- MP3 in MP4: objectTypeIndication 0x69 fino a 24 kHz, 0x6B oltre.
- Conversione della libreria: il lavoro toglie le righe di un formato
  spento o cambiato; spegnere toglie anche i «Non riuscito»; «Riprova»
  solo i formati di adesso; pausa per spazio prima di rileggere
  l'originale.
- «Anche i N» conta e mette in coda solo il tipo che si cambia; le
  impostazioni dell'esportazione si salvano una per volta.
- Eliminazione e «Tieni il più grande» scelgono i convertiti nella
  stessa transazione: nessun convertito orfano.
- Un file arrivato tardi in un elemento vecchio mette in coda solo sé
  (file nuovo = salvato da quando il formato è scelto).
- Zip dei fotogrammi a pezzi di 64 KB: un browser lento che legge non
  si interrompe, uno fermo sì.

Decisioni in docs/decisioni.md (28/11), §4.10 della specifica precisato.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 13:30:33 +01:00

874 lines
35 KiB
C#

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.";
/// <summary>A frames request over <see cref="ExportFrames.MaxPerRequest"/>.</summary>
public const string TooManyFramesText = "Più di 20.000 fotogrammi in una richiesta: scegli meno video o un intervallo più lungo";
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>
/// <exception cref="ArgumentException">
/// The request is not valid, or a frames request asks more than 1.000 frames of a video or 20.000 in all (Italian message).
/// </exception>
public async Task<ExportStart> StartAsync(ExportJobRequest request, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(request);
ExportPlanner.Validate(request);
var held = new LeaseHolder();
lock (_gate)
{
EnsureIdle();
// The long-work gate is held from the plan on (§4.10 «esportazione, importazione e ricostruzione non girano
// insieme»): a rebuild or an import cannot start while the runs and their items are being recorded.
if (_env.Gate is { } gate)
{
if (!gate.TryEnter(LongWorkKind.Export, out var lease, out var busy))
{
throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Export, busy!.Value));
}
held.Lease = lease;
}
_starting = true; // a second «Copia in…» meanwhile records nothing
}
try
{
return await StartReservedAsync(request, held, ct).ConfigureAwait(false);
}
finally
{
lock (_gate)
{
_starting = false;
}
held.Lease?.Dispose(); // not handed to a job: nothing to copy, or the start failed
}
}
private async Task<ExportStart> StartReservedAsync(ExportJobRequest request, LeaseHolder held, 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;
// Frames job: the videos whose length the library does not know are measured once, in the first pass, so that
// their frames count against the caps; the recording pass reuses the lengths (they cannot disagree).
var lengths = new Dictionary<long, TimeSpan?>();
Func<ExportCandidate, CancellationToken, Task<TimeSpan?>>? lengthOf = request.Frames is null
? null
: async (candidate, token) =>
{
if (!lengths.TryGetValue(candidate.MediaId, out var length))
{
length = await ProbeLengthAsync(candidate, token).ConfigureAwait(false);
lengths[candidate.MediaId] = length;
}
return length;
};
if (request.Frames is not null)
{
// Refused before anything is recorded (D12 of tappa E3): a video over 1.000 frames, more than 20.000 in all.
var count = new PlanTally();
await foreach (var file in Planner.EnumerateAsync(request, effective, settings, ct, lengthOf).ConfigureAwait(false))
{
count.Add(file);
}
if (count.OverCap > 0)
{
throw new ArgumentException(ExportFrames.OverCapMessage, nameof(request));
}
if (count.Frames > ExportFrames.MaxPerRequest)
{
throw new ArgumentException(TooManyFramesText, nameof(request));
}
}
var frameItems = 0;
try
{
await foreach (var file in Planner.EnumerateAsync(request, effective, settings, ct, lengthOf).ConfigureAwait(false))
{
tally.Add(file);
if (file.DestinationId is not { } destination || file.Action is PlannedCopy.Missing or PlannedCopy.NotExported or PlannedCopy.PhotoSkipped or PlannedCopy.OverCap)
{
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;
await RecordRunSettingsAsync(run.Id, request).ConfigureAwait(false);
}
// Frame items of one video are added together, in instant order (the copy takes them as one batch).
// The first pass already refused more than 20.000: this only guards that it saw the same files.
if (file.Variant == ExportVariant.Frame && file.Action == PlannedCopy.Write && ++frameItems > ExportFrames.MaxPerRequest)
{
throw new ArgumentException(TooManyFramesText, nameof(request));
}
pending.Add(new ExportItem
{
RunId = run.Id,
MediaId = file.Candidate.MediaId,
AccountId = file.Candidate.AccountId,
SourceSha256 = file.Candidate.Sha256,
Variant = file.Variant,
Format = file.Format,
FrameAt = file.FrameAt,
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(), held.Lease);
held.Lease = null; // the job owns it now
}
}
catch
{
await StopRunsAsync(ordered).ConfigureAwait(false);
throw;
}
return new ExportStart(ordered, plan);
}
/// <summary>
/// The keys of a new job: cleared first (a run id can be used again after <c>DeleteRunAsync</c>), then what a resume
/// needs to know (WP1.2 of tappa E3): «Copia di nuovo», the frames request, the exact identity of «Copia di nuovo»
/// of one copy.
/// </summary>
private async Task RecordRunSettingsAsync(long runId, ExportJobRequest request)
{
var store = _env.Storage.Settings;
var none = CancellationToken.None;
await ExportRunSettings.ClearAsync(store, runId, none).ConfigureAwait(false);
if (request.CopyAgain)
{
await ExportRunSettings.SetCopyAgainAsync(store, runId, true, none).ConfigureAwait(false);
}
if (request.Frames is { } frames)
{
await ExportRunSettings.SetFramesAsync(store, runId, frames.Mode, frames.Count ?? 0, none).ConfigureAwait(false);
}
else if (request.Exact is { Variant: ExportVariant.Frame })
{
await ExportRunSettings.SetFramesAsync(store, runId, FrameMode.At, 1, none).ConfigureAwait(false);
}
if (request.Exact is not null)
{
await ExportRunSettings.SetExactAsync(store, runId, none).ConfigureAwait(false);
}
}
/// <summary>
/// The length of a video the library does not know, from its headers (only the library file, never the
/// destination); null when it cannot be read now (the job then gives it one instant, and the copy tells).
/// </summary>
private async Task<TimeSpan?> ProbeLengthAsync(ExportCandidate candidate, CancellationToken ct)
{
var media = await _env.Storage.Media.GetAsync(candidate.MediaId, ct).ConfigureAwait(false);
var account = await _env.Storage.Accounts.GetAsync(candidate.AccountId, ct).ConfigureAwait(false);
if (media is null || account is null || _env.ResolveSourcePath(account, media) is not { } path)
{
return null;
}
try
{
return await Task.Run(
() =>
{
using var stream = _env.FileSystem.OpenRandomAccess(path);
return VideoFrameReader.ProbeDuration(stream);
},
ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return null; // not readable now: one instant, the copy tells
}
}
/// <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>
/// «Riprova» of a paused destination: checks it with its probe (WP1.3). Still not writable: it stays paused with the
/// new reason, returned. Writable: the pause goes and, when no other long work runs, its paused jobs resume (oldest
/// first); otherwise they wait for «Riprendi».
/// </summary>
/// <exception cref="KeyNotFoundException">No such destination.</exception>
/// <exception cref="InvalidOperationException">The destination was retired.</exception>
public async Task<ExportRetry> RetryDestinationAsync(long destinationId, CancellationToken ct = default)
{
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 riprovare.");
}
if (await Copier.CheckDestinationAsync(destination, ct).ConfigureAwait(false) is { } problem)
{
await ExportPause.PauseAsync(_env, destination, problem).ConfigureAwait(false);
return new ExportRetry(problem, []);
}
await ExportPause.ClearAsync(_env, destination).ConfigureAwait(false);
var paused = (await _env.Storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false))
.Where(r => r.DestinationId == destinationId && r.State == ExportRunState.Paused)
.Select(r => r.Id)
.ToList();
if (paused.Count == 0 || IsBusy || _env.Gate?.Busy is not null)
{
return new ExportRetry(null, []);
}
return new ExportRetry(null, await ResumeAsync(paused, ct).ConfigureAwait(false));
}
/// <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 (!await RootAnswersAsync(destination, ct).ConfigureAwait(false))
{
await PauseCheckAsync(destination, label, ct).ConfigureAwait(false);
Report(ExportPhase.Finished, done);
return;
}
var missing = new List<ExportCopy>();
foreach (var copy in page)
{
ct.ThrowIfCancellationRequested();
if (copy.RelativePath is not { } path || !FileExists(destination.RootPath, path))
{
missing.Add(copy);
}
}
// The disk may have gone away while the page was read (decision of 2026-11-27, §4.10): the root is asked
// again after the files and before anything is marked, and a missing file is looked for once more.
if (missing.Count > 0 && !await RootAnswersAsync(destination, ct).ConfigureAwait(false))
{
await PauseCheckAsync(destination, label, ct).ConfigureAwait(false);
Report(ExportPhase.Finished, done);
return;
}
var gone = missing
.Where(copy => copy.RelativePath is not { } path || !FileExists(destination.RootPath, path))
.Select(copy => copy.Id)
.ToList();
removed += await exports.MarkCopiesRemovedAsync(gone, _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);
}
/// <summary>The root of the destination is there, asked within the folder-check time (a dead share must not block).</summary>
private async Task<bool> RootAnswersAsync(ExportDestination destination, CancellationToken ct)
{
try
{
return await Task.Run(() => Directory.Exists(destination.RootPath), ct).WaitAsync(_env.FolderCheckTimeout, ct).ConfigureAwait(false);
}
catch (TimeoutException)
{
return false;
}
}
/// <summary>The disk went away during «Controlla le copie»: nothing is «Tolto» because of that, the destination pauses.</summary>
private async Task PauseCheckAsync(ExportDestination destination, string label, CancellationToken ct)
{
var problem = await Copier.CheckDestinationAsync(destination, ct).ConfigureAwait(false) ?? $"{label} non è raggiungibile.";
await ExportPause.PauseAsync(_env, destination, problem).ConfigureAwait(false);
}
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, IDisposable? lease = null) =>
StartJob(
runIds,
async (progress, token) =>
{
var next = 0;
try
{
for (; next < runIds.Count; next++)
{
token.ThrowIfCancellationRequested();
try
{
await Copier.CopyAsync(runIds[next], 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);
}
}
}
finally
{
// «Interrompi» (or «Annulla», or the end of Febe) stopped the job before its later destinations: those
// runs were recorded as running and nothing runs them now. They become «interrotto», resumable, as
// RecoverAsync would make them at the next start.
await InterruptQueuedAsync(runIds.Skip(next)).ConfigureAwait(false);
}
},
lease);
/// <summary>Runs of a stopped job that were never reached and are still recorded as running become «interrotto».</summary>
private async Task InterruptQueuedAsync(IEnumerable<long> runIds)
{
foreach (var runId in runIds)
{
try
{
if (await _env.Storage.Exports.GetRunAsync(runId, CancellationToken.None).ConfigureAwait(false) is { State: ExportRunState.Running } run)
{
await _env.Storage.Exports.UpdateRunAsync(run with { State = ExportRunState.Interrupted, LastError = null }, CancellationToken.None).ConfigureAwait(false);
}
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// RecoverAsync makes it «interrotto» at the next start.
}
}
}
/// <summary>Starts a job; <paramref name="held"/> is a lease of the gate already taken (the job owns it once started).</summary>
private void StartJob(IReadOnlyList<long> runIds, Func<IProgress<ExportProgress>, CancellationToken, Task> work, IDisposable? held = null)
{
lock (_gate)
{
if (_job is { Task.IsCompleted: false })
{
throw new InvalidOperationException(BusyText);
}
var lease = held;
if (lease is null && _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);
/// <summary>A lease of the long-work gate on its way from <see cref="StartAsync"/> to the job.</summary>
private sealed class LeaseHolder
{
public IDisposable? Lease { get; set; }
}
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);
}
}
}