using System.Diagnostics; using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Core.Storage; namespace Febe.Core.Import; /// /// 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 or /// and stops them with . Every state lives in the database: /// after a restart call once, then continues where it stopped. /// See src/Febe.Core/Import/LEGGIMI.md. /// 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); } /// /// 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. /// public event EventHandler? ProgressChanged; /// Step 1: checking sources. public ImportSources Sources { get; } public ImportAnalyzer Analyzer { get; } public ImportCopier Copier { get; } public ImportReview Review { get; } public ImportReports Reports { get; } /// The import whose job is running, if any. public long? ActiveRunId { get { lock (_gate) { return _job is { Task.IsCompleted: false } job ? job.RunId : null; } } } /// The last error of a background job that could not be stored with the import (normally null). public string? LastJobError { get; private set; } /// /// 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. /// public async Task 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; } /// Imports, newest first (to offer «Riprendi» on an unfinished one). public Task> ListRunsAsync(CancellationToken ct = default) => _env.Storage.Imports.ListRunsAsync(ct); public Task GetRunAsync(long runId, CancellationToken ct = default) => _env.Storage.Imports.GetRunAsync(runId, ct); /// Step 1: checks a folder. Throws with the reason in Italian. public ImportSourceInfo InspectSource(string path) => Sources.Inspect(path); /// Step 1 in Docker: the subfolders of /importa (or of one of its subfolders). public IReadOnlyList BrowseSources(string? path = null) => Sources.Browse(path); /// Step 1 → 2: records the import and starts the analysis in the background. /// The folder cannot be used. /// Another import job is running. public async Task 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 } } /// Continues an interrupted analysis or copy in the background. public async Task 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(); } } /// /// 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 the mode is set first. /// public async Task 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(); } } /// «Interrompi»: stops the running job of this import and waits until its state is saved. 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); } /// Waits for the running job of this import (if any) to end, however it ends; returns the import. public async Task 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); } /// The progress of an import: live while its job runs, otherwise from the database. public async Task 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 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 SetModeAsync(long runId, ImportMode mode, CancellationToken ct = default) => Review.SetModeAsync(runId, mode, ct); public Task> ListDuplicatesAsync(long runId, bool pendingOnly = true, long afterPairId = 0, int limit = 50, CancellationToken ct = default) => Review.ListDuplicatesAsync(runId, pendingOnly, afterPairId, limit, ct); public Task DecideAsync(long runId, long pairId, DuplicateDecision decision, DecisionScope scope = DecisionScope.ThisPair, CancellationToken ct = default) => Review.DecideAsync(runId, pairId, decision, scope, ct); public Task GetPlanAsync(long runId, CancellationToken ct = default) => Review.GetPlanAsync(runId, ct); // Step 4. public Task 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); /// /// «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. /// 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(); } } /// /// 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: displaces it). /// 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)); } } /// /// Takes the long-work gate before anything is recorded and outside (tappa E5, D6): a yielding /// automatic copy is stopped and awaited (at most , real time), and meanwhile a /// second start is refused at once. Null without a gate (tests). /// private async Task 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; } /// Starts the job; on success it owns (set to null here) and releases it when it ends. private void StartJob(long runId, ImportPhase phase, Func, 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(), 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 { private ImportPhase? _phase; public void Report(ImportProgress value) { var phaseChanged = _phase != value.Phase; _phase = value.Phase; owner.Publish(value, phaseChanged); } } }