using System.Diagnostics; using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Core.Library; using Febe.Core.Storage; namespace Febe.Core.Export; /// /// 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 (), 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 once; «Riprendi» is always Alberto's. /// public sealed class ExportService : IAsyncDisposable { private const string BusyText = "C'è già una copia al lavoro: aspetta che finisca o interrompila."; /// A frames request over . 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); } /// Progress of the running job, at most four times a second and at every change of phase (pool thread). public event EventHandler? ProgressChanged; /// The job ended, however it ended (pool thread): the interface refreshes tiles and filter. public event EventHandler? JobFinished; public ExportDestinations Destinations { get; } public ExportPlanner Planner { get; } public ExportCopier Copier { get; } public ExportReports Reports { get; } /// The runs of the running job; empty when idle (and for «Controlla le copie», which has none). public IReadOnlyList ActiveRunIds { get { lock (_gate) { return _job is { Task.IsCompleted: false } job ? job.RunIds : []; } } } /// A job is running. public bool IsBusy { get { lock (_gate) { return _starting || _job is { Task.IsCompleted: false }; } } } /// The last error of a background job that could not be stored with its run (normally null). public string? LastJobError { get; private set; } /// /// After a restart: a job that was running becomes «interrotto» (paused and interrupted ones stay), and the /// .part files of unfinished jobs are removed in the background, only in their items' folders. Never resumes /// by itself. Returns how many jobs became interrupted. /// public async Task 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; } /// The plan of a «Copia in…», for its dialog (database only, plus whether each destination answers). public Task PlanAsync(ExportJobRequest request, CancellationToken ct = default) => Planner.PlanAsync(request, ct); /// /// «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. /// /// A copy, an import or a rebuild is running. /// /// 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). /// public async Task 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 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(); var pending = new List(); 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(); Func>? 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); } /// /// The keys of a new job: cleared first (a run id can be used again after DeleteRunAsync), 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. /// 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); } } /// /// 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). /// private async Task 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 } } /// /// «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). /// public async Task> ResumeAsync(IReadOnlyList? runIds = null, CancellationToken ct = default) { EnsureIdle(); var unfinished = await _env.Storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false); List 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; } /// «Interrompi»: stops the running job and waits until its states are saved. 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); } /// /// «Annulla»: an unfinished job becomes «annullato» (the running job is interrupted first when it holds it). Our /// .part files in its folders go; no other file is touched, and the copies made stay. /// 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); } } /// /// «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. /// 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)); } /// /// «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». /// /// No such destination. /// The destination was retired. public async Task 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)); } /// The progress of the running job, or a snapshot of the newest job. public async Task 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(), _env.Clock.Now) : await SnapshotAsync(newest, ct).ConfigureAwait(false); } /// Waits for the running job (if any) to end, however it ends. 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 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 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(), _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(); 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); } /// The root of the destination is there, asked within the folder-check time (a dead share must not block). private async Task 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; } } /// The disk went away during «Controlla le copie»: nothing is «Tolto» because of that, the destination pauses. 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 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 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 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); /// Runs of a stopped job that were never reached and are still recorded as running become «interrotto». private async Task InterruptQueuedAsync(IEnumerable 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. } } } /// Starts a job; is a lease of the gate already taken (the job owns it once started). private void StartJob(IReadOnlyList runIds, Func, 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(), _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 RunIds, CancellationTokenSource Cancellation, Task Task); /// A lease of the long-work gate on its way from to the job. private sealed class LeaseHolder { public IDisposable? Lease { get; set; } } private sealed class Reporter(ExportService owner) : IProgress { 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); } } }