La copia automatica prenderà il cancello con un permesso che cede (TryEnterYielding): esclude gli altri lavori come ogni permesso, ma importazione, ricostruzione e zip di fotogrammi lo prendono con EnterAsync prima del proprio lucchetto e prima di registrare qualcosa. Chi entra diventa subito titolare, la copia automatica riceve l'ordine di fermarsi e si aspetta che lasci, in tempo reale, al più 15 secondi; oltre, il lavoro è rifiutato con il messaggio della copia e la copia resta titolare finché non lascia. «Cerca i video fermi» la ferma con CancelYielding. BusyFirm decide i rifiuti anticipati, Busy resta per chi aspetta (conversione della libreria, video fermi). Una ricostruzione finita risveglia la copia automatica, e la sonda del controllo delle cartelle è riservata come i file temporanei, così la pulizia dei resti di un altro lavoro non la toglie mentre è in uso. Risposta 49 di Alberto: la copia automatica cede sempre il passo. Una riga in decisioni.md. ExportService resta alla tappa successiva. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
425 lines
17 KiB
C#
425 lines
17 KiB
C#
using System.Diagnostics;
|
|
using Febe.Core.Abstractions;
|
|
using Febe.Core.Domain;
|
|
using Febe.Core.Storage;
|
|
|
|
namespace Febe.Core.Import;
|
|
|
|
/// <summary>
|
|
/// The import for the interface (spec §9, mockup 09): one object with the four steps. Analysis and copy run in the
|
|
/// background, one job at a time; the interface follows them with <see cref="ProgressChanged"/> or
|
|
/// <see cref="GetProgressAsync"/> and stops them with <see cref="InterruptAsync"/>. Every state lives in the database:
|
|
/// after a restart call <see cref="RecoverAsync"/> once, then <see cref="ResumeAsync"/> continues where it stopped.
|
|
/// See <c>src/Febe.Core/Import/LEGGIMI.md</c>.
|
|
/// </summary>
|
|
public sealed class ImportService : IAsyncDisposable
|
|
{
|
|
private static readonly TimeSpan ProgressInterval = TimeSpan.FromMilliseconds(250);
|
|
|
|
private readonly ImportEnvironment _env;
|
|
private readonly Lock _gate = new();
|
|
private Job? _job;
|
|
private ImportProgress? _current;
|
|
private long _lastPublished;
|
|
|
|
public ImportService(ImportEnvironment env)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(env);
|
|
_env = env;
|
|
Sources = env.CreateSources();
|
|
Analyzer = new ImportAnalyzer(env);
|
|
Copier = new ImportCopier(env);
|
|
Review = new ImportReview(env);
|
|
Reports = new ImportReports(env);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Progress of the running job, at most four times a second and at every change of phase. Raised on a pool thread:
|
|
/// handlers must be quick and thread-safe.
|
|
/// </summary>
|
|
public event EventHandler<ImportProgress>? ProgressChanged;
|
|
|
|
/// <summary>Step 1: checking sources.</summary>
|
|
public ImportSources Sources { get; }
|
|
|
|
public ImportAnalyzer Analyzer { get; }
|
|
|
|
public ImportCopier Copier { get; }
|
|
|
|
public ImportReview Review { get; }
|
|
|
|
public ImportReports Reports { get; }
|
|
|
|
/// <summary>The import whose job is running, if any.</summary>
|
|
public long? ActiveRunId
|
|
{
|
|
get
|
|
{
|
|
lock (_gate)
|
|
{
|
|
return _job is { Task.IsCompleted: false } job ? job.RunId : null;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>The last error of a background job that could not be stored with the import (normally null).</summary>
|
|
public string? LastJobError { get; private set; }
|
|
|
|
/// <summary>
|
|
/// After a restart: an analysis or a copy that was running when Febe stopped becomes «interrotta», ready to resume.
|
|
/// Call once at start-up, before anything else.
|
|
/// </summary>
|
|
public async Task<int> RecoverAsync(CancellationToken ct = default)
|
|
{
|
|
var active = ActiveRunId;
|
|
var recovered = 0;
|
|
foreach (var run in await _env.Storage.Imports.ListRunsAsync(ct).ConfigureAwait(false))
|
|
{
|
|
if (run.Id == active)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var state = run.State switch
|
|
{
|
|
ImportRunState.Analyzing => ImportRunState.AnalysisInterrupted,
|
|
ImportRunState.Copying => ImportRunState.CopyInterrupted,
|
|
_ => run.State,
|
|
};
|
|
if (state != run.State)
|
|
{
|
|
await _env.Storage.Imports.UpdateRunAsync(run with { State = state }, ct).ConfigureAwait(false);
|
|
recovered++;
|
|
}
|
|
}
|
|
|
|
return recovered;
|
|
}
|
|
|
|
/// <summary>Imports, newest first (to offer «Riprendi» on an unfinished one).</summary>
|
|
public Task<IReadOnlyList<ImportRun>> ListRunsAsync(CancellationToken ct = default) => _env.Storage.Imports.ListRunsAsync(ct);
|
|
|
|
public Task<ImportRun?> GetRunAsync(long runId, CancellationToken ct = default) => _env.Storage.Imports.GetRunAsync(runId, ct);
|
|
|
|
/// <summary>Step 1: checks a folder. Throws <see cref="ImportSourceException"/> with the reason in Italian.</summary>
|
|
public ImportSourceInfo InspectSource(string path) => Sources.Inspect(path);
|
|
|
|
/// <summary>Step 1 in Docker: the subfolders of <c>/importa</c> (or of one of its subfolders).</summary>
|
|
public IReadOnlyList<SourceFolderChoice> BrowseSources(string? path = null) => Sources.Browse(path);
|
|
|
|
/// <summary>Step 1 → 2: records the import and starts the analysis in the background.</summary>
|
|
/// <exception cref="ImportSourceException">The folder cannot be used.</exception>
|
|
/// <exception cref="InvalidOperationException">Another import job is running.</exception>
|
|
public async Task<ImportRun> StartAsync(string sourcePath, ImportAnalysisOptions? options = null, CancellationToken ct = default)
|
|
{
|
|
EnsureIdle();
|
|
var source = Sources.Inspect(sourcePath);
|
|
var lease = await EnterGateAsync(ct).ConfigureAwait(false);
|
|
try
|
|
{
|
|
var run = await Analyzer.CreateRunAsync(source, options, ct).ConfigureAwait(false);
|
|
StartJob(run.Id, ImportPhase.Analyzing, (progress, token) => Analyzer.AnalyzeAsync(run.Id, progress, token), ref lease);
|
|
return run;
|
|
}
|
|
finally
|
|
{
|
|
lease?.Dispose(); // not handed to a job: the start failed
|
|
}
|
|
}
|
|
|
|
/// <summary>Continues an interrupted analysis or copy in the background.</summary>
|
|
public async Task<ImportRun> ResumeAsync(long runId, CancellationToken ct = default)
|
|
{
|
|
var run = await _env.Storage.Imports.GetRunAsync(runId, ct).ConfigureAwait(false)
|
|
?? throw new KeyNotFoundException($"Importazione {runId} non trovata.");
|
|
if (run.State is not (ImportRunState.Analyzing or ImportRunState.AnalysisInterrupted or ImportRunState.Copying or ImportRunState.CopyInterrupted))
|
|
{
|
|
throw new InvalidOperationException("Questa importazione non è interrotta: non c'è niente da riprendere.");
|
|
}
|
|
|
|
EnsureIdle();
|
|
var lease = await EnterGateAsync(ct).ConfigureAwait(false);
|
|
try
|
|
{
|
|
if (run.State is ImportRunState.Analyzing or ImportRunState.AnalysisInterrupted)
|
|
{
|
|
StartJob(runId, ImportPhase.Analyzing, (progress, token) => Analyzer.AnalyzeAsync(runId, progress, token), ref lease);
|
|
}
|
|
else
|
|
{
|
|
StartJob(runId, ImportPhase.Copying, (progress, token) => Copier.CopyAsync(runId, progress, token), ref lease);
|
|
}
|
|
|
|
return run;
|
|
}
|
|
finally
|
|
{
|
|
lease?.Dispose();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Step 3 → 4: starts the copy in the background (also «importa i rimasti» on a completed import, after a change of
|
|
/// associations or decisions). With <paramref name="mode"/> the mode is set first.
|
|
/// </summary>
|
|
public async Task<ImportRun> StartCopyAsync(long runId, ImportMode? mode = null, CancellationToken ct = default)
|
|
{
|
|
EnsureIdle();
|
|
var lease = await EnterGateAsync(ct).ConfigureAwait(false);
|
|
try
|
|
{
|
|
var run = mode is { } m
|
|
? await Review.SetModeAsync(runId, m, ct).ConfigureAwait(false)
|
|
: await _env.Storage.Imports.GetRunAsync(runId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Importazione {runId} non trovata.");
|
|
if (run.State is not (ImportRunState.Reviewing or ImportRunState.CopyInterrupted or ImportRunState.Completed))
|
|
{
|
|
throw new InvalidOperationException("L'analisi non è finita: riprendila prima di importare.");
|
|
}
|
|
|
|
StartJob(runId, ImportPhase.Copying, (progress, token) => Copier.CopyAsync(runId, progress, token), ref lease);
|
|
return run;
|
|
}
|
|
finally
|
|
{
|
|
lease?.Dispose();
|
|
}
|
|
}
|
|
|
|
/// <summary>«Interrompi»: stops the running job of this import and waits until its state is saved.</summary>
|
|
public async Task InterruptAsync(long runId)
|
|
{
|
|
Job? job;
|
|
lock (_gate)
|
|
{
|
|
job = _job is { RunId: var id } j && id == runId ? j : null;
|
|
}
|
|
|
|
if (job is null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
await job.Cancellation.CancelAsync().ConfigureAwait(false);
|
|
await job.Task.ConfigureAwait(false);
|
|
}
|
|
|
|
/// <summary>Waits for the running job of this import (if any) to end, however it ends; returns the import.</summary>
|
|
public async Task<ImportRun?> WaitAsync(long runId, CancellationToken ct = default)
|
|
{
|
|
Job? job;
|
|
lock (_gate)
|
|
{
|
|
job = _job is { RunId: var id } j && id == runId ? j : null;
|
|
}
|
|
|
|
if (job is not null)
|
|
{
|
|
await job.Task.WaitAsync(ct).ConfigureAwait(false);
|
|
}
|
|
|
|
return await _env.Storage.Imports.GetRunAsync(runId, ct).ConfigureAwait(false);
|
|
}
|
|
|
|
/// <summary>The progress of an import: live while its job runs, otherwise from the database.</summary>
|
|
public async Task<ImportProgress> GetProgressAsync(long runId)
|
|
{
|
|
lock (_gate)
|
|
{
|
|
if (_job is { RunId: var id, Task.IsCompleted: false } && id == runId && _current is { } current && current.RunId == runId)
|
|
{
|
|
return current;
|
|
}
|
|
}
|
|
|
|
var run = await _env.Storage.Imports.GetRunAsync(runId).ConfigureAwait(false)
|
|
?? throw new KeyNotFoundException($"Importazione {runId} non trovata.");
|
|
var phase = run.State switch
|
|
{
|
|
ImportRunState.Analyzing or ImportRunState.AnalysisInterrupted => ImportPhase.Analyzing,
|
|
ImportRunState.Copying or ImportRunState.CopyInterrupted => ImportPhase.Copying,
|
|
_ => ImportPhase.Finished,
|
|
};
|
|
return await Analyzer.SnapshotAsync(runId, phase, null).ConfigureAwait(false);
|
|
}
|
|
|
|
// Step 3, delegated to the review (see ImportReview).
|
|
public Task<ImportReviewSummary> GetReviewAsync(long runId, CancellationToken ct = default) => Review.GetSummaryAsync(runId, ct);
|
|
|
|
public Task SetFolderTargetAsync(long runId, string folder, FolderTarget target, CancellationToken ct = default) => Review.SetFolderTargetAsync(runId, folder, target, ct);
|
|
|
|
public Task<ImportRun> SetModeAsync(long runId, ImportMode mode, CancellationToken ct = default) => Review.SetModeAsync(runId, mode, ct);
|
|
|
|
public Task<IReadOnlyList<DuplicateCase>> ListDuplicatesAsync(long runId, bool pendingOnly = true, long afterPairId = 0, int limit = 50, CancellationToken ct = default) =>
|
|
Review.ListDuplicatesAsync(runId, pendingOnly, afterPairId, limit, ct);
|
|
|
|
public Task<int> DecideAsync(long runId, long pairId, DuplicateDecision decision, DecisionScope scope = DecisionScope.ThisPair, CancellationToken ct = default) =>
|
|
Review.DecideAsync(runId, pairId, decision, scope, ct);
|
|
|
|
public Task<ImportPlan> GetPlanAsync(long runId, CancellationToken ct = default) => Review.GetPlanAsync(runId, ct);
|
|
|
|
// Step 4.
|
|
public Task<ImportReport> GetReportAsync(long runId, CancellationToken ct = default) => Reports.GetReportAsync(runId, ct);
|
|
|
|
public Task WriteCsvAsync(long runId, Stream destination, CancellationToken ct = default) => Reports.WriteCsvAsync(runId, destination, ct);
|
|
|
|
/// <summary>
|
|
/// «Annulla l'importazione»: stops its job; if nothing was copied yet the import disappears with its records,
|
|
/// otherwise it becomes «annullata» and its pending duplicates are withdrawn. Files are never touched.
|
|
/// </summary>
|
|
public async Task DiscardAsync(long runId, CancellationToken ct = default)
|
|
{
|
|
await InterruptAsync(runId).ConfigureAwait(false);
|
|
var run = await _env.Storage.Imports.GetRunAsync(runId, ct).ConfigureAwait(false);
|
|
if (run is null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var summary = await _env.Storage.Imports.GetSummaryAsync(runId, ct).ConfigureAwait(false);
|
|
if (summary.ByState[ImportFileState.Copied] + summary.ByState[ImportFileState.Moved] == 0)
|
|
{
|
|
await _env.Storage.Imports.DeleteRunAsync(runId, ct).ConfigureAwait(false);
|
|
}
|
|
else
|
|
{
|
|
await _env.Storage.Imports.RemovePendingPairsAsync(runId, ct).ConfigureAwait(false);
|
|
await _env.Storage.Imports.UpdateRunAsync(run with { State = ImportRunState.Cancelled, CompletedAt = _env.Clock.Now }, ct).ConfigureAwait(false);
|
|
}
|
|
|
|
await ImportRunSettings.ClearAsync(_env.Storage.Settings, runId, ct).ConfigureAwait(false);
|
|
}
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
Job? job;
|
|
lock (_gate)
|
|
{
|
|
job = _job;
|
|
}
|
|
|
|
if (job is not null)
|
|
{
|
|
await job.Cancellation.CancelAsync().ConfigureAwait(false);
|
|
await job.Task.ConfigureAwait(false);
|
|
job.Cancellation.Dispose();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The quick refusals, before anything is read or recorded: an import job runs, or a long work that does not give way
|
|
/// holds the gate (an automatic copy does give way: <see cref="EnterGateAsync"/> displaces it).
|
|
/// </summary>
|
|
private void EnsureIdle()
|
|
{
|
|
if (ActiveRunId is not null)
|
|
{
|
|
throw new InvalidOperationException("C'è già un'importazione al lavoro: aspetta che finisca o interrompila.");
|
|
}
|
|
|
|
if (_env.Gate?.BusyFirm is { } busy)
|
|
{
|
|
throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Import, busy));
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Takes the long-work gate before anything is recorded and outside <see cref="_gate"/> (tappa E5, D6): a yielding
|
|
/// automatic copy is stopped and awaited (at most <see cref="LongWorkGate.YieldWait"/>, real time), and meanwhile a
|
|
/// second start is refused at once. Null without a gate (tests).
|
|
/// </summary>
|
|
private async Task<IDisposable?> EnterGateAsync(CancellationToken ct)
|
|
{
|
|
if (_env.Gate is not { } gate)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var entry = await gate.EnterAsync(LongWorkKind.Import, ct).ConfigureAwait(false);
|
|
return entry.BusyWith is { } busy
|
|
? throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Import, busy))
|
|
: entry.Lease;
|
|
}
|
|
|
|
/// <summary>Starts the job; on success it owns <paramref name="held"/> (set to null here) and releases it when it ends.</summary>
|
|
private void StartJob(long runId, ImportPhase phase, Func<IProgress<ImportProgress>, CancellationToken, Task> work, ref IDisposable? held)
|
|
{
|
|
lock (_gate)
|
|
{
|
|
if (_job is { Task.IsCompleted: false })
|
|
{
|
|
throw new InvalidOperationException("C'è già un'importazione al lavoro: aspetta che finisca o interrompila.");
|
|
}
|
|
|
|
var lease = held;
|
|
held = null;
|
|
_job?.Cancellation.Dispose();
|
|
var cancellation = new CancellationTokenSource();
|
|
var reporter = new Reporter(this);
|
|
_current = new ImportProgress(runId, phase, 0, 0, 0, 0, null, new Dictionary<ImportOutcome, int>(), 0, _env.Clock.Now);
|
|
var task = Task.Run(async () =>
|
|
{
|
|
try
|
|
{
|
|
await work(reporter, cancellation.Token).ConfigureAwait(false);
|
|
}
|
|
catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
|
|
{
|
|
// Interrupted: the state was saved by the analysis or the copy.
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
LastJobError = ImportAnalyzer.ErrorText(ex); // also stored with the import when possible
|
|
}
|
|
finally
|
|
{
|
|
try
|
|
{
|
|
Publish(await Analyzer.SnapshotAsync(runId, ImportPhase.Finished, null).ConfigureAwait(false), force: true);
|
|
}
|
|
catch (Exception ex) when (ex is not OutOfMemoryException)
|
|
{
|
|
// The database is closing: nothing to publish.
|
|
}
|
|
finally
|
|
{
|
|
lease?.Dispose();
|
|
}
|
|
}
|
|
});
|
|
_job = new Job(runId, phase, cancellation, task);
|
|
}
|
|
}
|
|
|
|
private void Publish(ImportProgress 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(long RunId, ImportPhase Phase, CancellationTokenSource Cancellation, Task Task);
|
|
|
|
private sealed class Reporter(ImportService owner) : IProgress<ImportProgress>
|
|
{
|
|
private ImportPhase? _phase;
|
|
|
|
public void Report(ImportProgress value)
|
|
{
|
|
var phaseChanged = _phase != value.Phase;
|
|
_phase = value.Phase;
|
|
owner.Publish(value, phaseChanged);
|
|
}
|
|
}
|
|
}
|