E5: il cancello dei lavori lunghi cede il passo ai lavori di Alberto

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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-04 13:39:15 +01:00
1 parent f2568b5d88
commit cfd0ef88d7
11 files changed
+757 -58

No files matched your search

+235 -16
View File
@@ -24,6 +24,14 @@ public enum LongWorkKind
FrameDownload,
}
/// <summary>
/// The answer of <see cref="LongWorkGate.EnterAsync(LongWorkKind, TimeSpan, CancellationToken)"/>: the lease taken, or
/// (with <see cref="Lease"/> null) the kind of work that keeps the gate.
/// </summary>
/// <param name="Lease">The lease, to dispose when the work ends; null when refused.</param>
/// <param name="BusyWith">Who refused the start; null when <paramref name="Lease"/> is set.</param>
public sealed record LongWorkEntry(IDisposable? Lease, LongWorkKind? BusyWith);
/// <summary>
/// Lets only one of import, export, rebuild and frame download run at a time, in both directions. One instance is
/// shared by the whole process (the composition registers it once). A lease is taken when a job starts and disposed when
@@ -34,6 +42,13 @@ public enum LongWorkKind
/// only reads an original and writes its own temporary file, so it simply stops; a commit (one rename and one
/// transaction) is waited for, at most <see cref="CommitWait"/>.
/// </para>
/// <para>
/// The automatic export (tappa E5, D6) takes a <i>yielding</i> lease with <see cref="TryEnterYielding"/>: it excludes the
/// others like any lease, but a foreground <see cref="EnterAsync(LongWorkKind, TimeSpan, CancellationToken)"/> displaces
/// it (Alberto's work always comes first, §16 answer 49). The new lease becomes the holder at once, under the lock, so
/// nothing can take the gate in between; then the yielding work is asked to stop and its release is awaited, in real
/// time, at most a bounded wait. The synchronous <see cref="TryEnter"/> refuses a yielding holder like any other.
/// </para>
/// </summary>
public sealed class LongWorkGate
{
@@ -44,7 +59,16 @@ public sealed class LongWorkGate
/// <summary>How long a foreground <see cref="TryEnter"/> waits for a commit of the background work to end.</summary>
public TimeSpan CommitWait { get; init; } = TimeSpan.FromSeconds(10);
/// <summary>Who holds the gate in the foreground, or null when it is free. The background lease does not count.</summary>
/// <summary>
/// The usual wait of <see cref="EnterAsync(LongWorkKind, TimeSpan, CancellationToken)"/> for a yielding holder to let
/// go (15 s). Real time: a hand-over bound, not engine timing (like <see cref="CommitWait"/>).
/// </summary>
public TimeSpan YieldWait { get; init; } = TimeSpan.FromSeconds(15);
/// <summary>
/// Who holds the gate in the foreground, or null when it is free. The background lease does not count; a yielding
/// holder does (as <see cref="LongWorkKind.Export"/>, say), so work that waits for the gate keeps waiting.
/// </summary>
public LongWorkKind? Busy
{
get
@@ -56,6 +80,33 @@ public sealed class LongWorkGate
}
}
/// <summary>
/// The holder unless it is yielding work: what refuses a foreground start now. Null when the gate is free or held
/// by work that would give way (<see cref="TryEnterYielding"/>).
/// </summary>
public LongWorkKind? BusyFirm
{
get
{
lock (_lock)
{
return _holder is { Yielding: false } holder ? holder.Kind : null;
}
}
}
/// <summary>True while the gate is held by yielding work (the automatic export).</summary>
public bool HeldByYielding
{
get
{
lock (_lock)
{
return _holder is { Yielding: true };
}
}
}
/// <summary>True while the background lease (the conversion for the library) is held and not pre-empted.</summary>
public bool BackgroundRunning
{
@@ -76,24 +127,69 @@ public sealed class LongWorkGate
/// </summary>
public bool TryEnter(LongWorkKind kind, [NotNullWhen(true)] out IDisposable? lease, out LongWorkKind? busyWith)
{
if (kind == LongWorkKind.LibraryConversion)
if (TryTake(kind, yielding: false, out var taken, out busyWith))
{
throw new ArgumentException("La conversione della libreria prende il cancello solo in sottofondo.", nameof(kind));
lease = taken;
return true;
}
lease = null;
return false;
}
/// <summary>
/// Takes the gate for <paramref name="kind"/> as work that yields (the automatic export, tappa E5). Fails, with
/// <paramref name="busyWith"/> set, while any lease is held, a yielding one included. Pre-empts the background lease
/// as <see cref="TryEnter"/> does. <paramref name="yield"/> is cancelled when
/// <see cref="EnterAsync(LongWorkKind, TimeSpan, CancellationToken)"/> or <see cref="CancelYielding"/> asks the work to
/// stop: it must then stop soon and dispose the lease.
/// </summary>
public bool TryEnterYielding(LongWorkKind kind, [NotNullWhen(true)] out IDisposable? lease, out CancellationToken yield, out LongWorkKind? busyWith)
{
if (TryTake(kind, yielding: true, out var taken, out busyWith))
{
lease = taken;
yield = taken.YieldToken;
return true;
}
lease = null;
yield = CancellationToken.None;
return false;
}
/// <summary>
/// Takes the gate for <paramref name="kind"/> in the foreground, waiting at most <see cref="YieldWait"/> for a
/// yielding holder. See <see cref="EnterAsync(LongWorkKind, TimeSpan, CancellationToken)"/>.
/// </summary>
public Task<LongWorkEntry> EnterAsync(LongWorkKind kind, CancellationToken ct = default) => EnterAsync(kind, YieldWait, ct);
/// <summary>
/// Takes the gate for <paramref name="kind"/> in the foreground. A firm holder refuses at once, as
/// <see cref="TryEnter"/> does. A yielding holder is displaced: under the lock the new lease becomes the holder at
/// once (so nothing else can take the gate in between), then, outside it, the yielding work is cancelled and its
/// release awaited, in real time, at most <paramref name="wait"/>. Past the wait the new lease is given up, the
/// yielding work stays the holder until it lets go, and the entry says <see cref="LongWorkKind.Export"/> (its kind).
/// A background lease is pre-empted as with <see cref="TryEnter"/>. Callers await this before taking their own lock.
/// </summary>
/// <exception cref="OperationCanceledException"><paramref name="ct"/> was cancelled during the wait (nothing is held).</exception>
public async Task<LongWorkEntry> EnterAsync(LongWorkKind kind, TimeSpan wait, CancellationToken ct = default)
{
ThrowIfBackground(kind);
ct.ThrowIfCancellationRequested();
Lease taken;
Lease? displaced;
BackgroundLease? preempted;
bool committing;
lock (_lock)
{
if (_holder is { } holder)
if (_holder is { Yielding: false } firm)
{
lease = null;
busyWith = holder.Kind;
return false;
return new LongWorkEntry(null, firm.Kind);
}
taken = new Lease(this, kind);
displaced = _holder;
taken = new Lease(this, kind, yielding: false);
_holder = taken;
preempted = _background;
_background = null;
@@ -104,18 +200,67 @@ public sealed class LongWorkGate
{
// Outside the lock: the token's callbacks run synchronously and may take the gate's lock.
preempted.CancelPreempted();
if (committing && !preempted.WaitForCommit(CommitWait))
if (committing && !await Task.Run(() => preempted.WaitForCommit(CommitWait), CancellationToken.None).ConfigureAwait(false))
{
// A yielding holder pre-empts the background lease itself, so there is none to give back here.
taken.Dispose();
lease = null;
busyWith = LongWorkKind.LibraryConversion;
return false;
return new LongWorkEntry(null, LongWorkKind.LibraryConversion);
}
}
lease = taken;
busyWith = null;
return true;
if (displaced is null)
{
return new LongWorkEntry(taken, null);
}
displaced.CancelYield();
try
{
await displaced.Released.WaitAsync(wait, ct).ConfigureAwait(false);
return new LongWorkEntry(taken, null);
}
catch (Exception ex) when (ex is TimeoutException or OperationCanceledException)
{
lock (_lock)
{
if (displaced.IsReleased)
{
if (ex is TimeoutException)
{
return new LongWorkEntry(taken, null); // it let go just now: the gate is ours after all
}
}
else if (ReferenceEquals(_holder, taken))
{
// Still unwinding (a read stuck on a share that went away): it stays the holder, so nothing else
// starts over a copy that may still write; it was asked to stop and lets go by itself.
_holder = displaced;
}
}
taken.Dispose(); // no longer the holder: releases nothing
if (ex is OperationCanceledException)
{
throw;
}
return new LongWorkEntry(null, displaced.Kind);
}
}
/// <summary>
/// Asks the yielding holder, if any, to stop, without taking the gate («Cerca i video fermi», which takes no lease,
/// §16 answer 49). The gate stays held until that work disposes its lease.
/// </summary>
public void CancelYielding()
{
Lease? holder;
lock (_lock)
{
holder = _holder is { Yielding: true } yielding ? yielding : null;
}
holder?.CancelYield(); // outside the lock: the token's callbacks run synchronously
}
/// <summary>
@@ -162,15 +307,67 @@ public sealed class LongWorkGate
_ => "riprova",
};
private static void ThrowIfBackground(LongWorkKind kind)
{
if (kind == LongWorkKind.LibraryConversion)
{
throw new ArgumentException("La conversione della libreria prende il cancello solo in sottofondo.", nameof(kind));
}
}
/// <summary>The shared body of <see cref="TryEnter"/> and <see cref="TryEnterYielding"/>: any holder refuses.</summary>
private bool TryTake(LongWorkKind kind, bool yielding, [NotNullWhen(true)] out Lease? lease, out LongWorkKind? busyWith)
{
ThrowIfBackground(kind);
Lease taken;
BackgroundLease? preempted;
bool committing;
lock (_lock)
{
if (_holder is { } holder)
{
lease = null;
busyWith = holder.Kind;
return false;
}
taken = new Lease(this, kind, yielding);
_holder = taken;
preempted = _background;
_background = null;
committing = preempted?.MarkPreempted() ?? false;
}
if (preempted is not null)
{
// Outside the lock: the token's callbacks run synchronously and may take the gate's lock.
preempted.CancelPreempted();
if (committing && !preempted.WaitForCommit(CommitWait))
{
taken.Dispose();
lease = null;
busyWith = LongWorkKind.LibraryConversion;
return false;
}
}
lease = taken;
busyWith = null;
return true;
}
private void Release(Lease lease)
{
lock (_lock)
{
lease.IsReleased = true;
if (ReferenceEquals(_holder, lease))
{
_holder = null;
}
}
lease.MarkReleased(); // outside the lock: awaiting EnterAsync calls continue elsewhere anyway
}
private void Release(BackgroundLease lease)
@@ -184,12 +381,34 @@ public sealed class LongWorkGate
}
}
private sealed class Lease(LongWorkGate gate, LongWorkKind kind) : IDisposable
/// <summary>
/// A foreground lease. A yielding one carries the token that asks its work to stop; every lease completes
/// <see cref="Released"/> when disposed, which a displacing <see cref="EnterAsync(LongWorkKind, TimeSpan, CancellationToken)"/> awaits.
/// </summary>
private sealed class Lease(LongWorkGate gate, LongWorkKind kind, bool yielding) : IDisposable
{
// Not disposed, as in BackgroundLease: a displacing caller may cancel it after the lease ended, and without a
// timer it holds nothing but memory.
private readonly CancellationTokenSource? _yield = yielding ? new CancellationTokenSource() : null;
private readonly TaskCompletionSource _released = new(TaskCreationOptions.RunContinuationsAsynchronously);
private int _disposed;
public LongWorkKind Kind { get; } = kind;
public bool Yielding { get; } = yielding;
public CancellationToken YieldToken => _yield?.Token ?? CancellationToken.None;
/// <summary>Completed once the lease is disposed.</summary>
public Task Released => _released.Task;
/// <summary>Under the gate's lock: set when the lease was disposed.</summary>
public bool IsReleased { get; set; }
public void CancelYield() => _yield?.Cancel();
public void MarkReleased() => _released.TrySetResult();
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) == 0)
@@ -350,6 +350,10 @@ public sealed class ExportFolderCheck(IExportMounts mounts, TimeSpan? timeout =
{
var name = NewProbeName();
var probe = Path.Combine(full, name);
// Reserved like the safe writer's own temporary files (tappa E5, D7.12): the clean-up of leftovers in this folder,
// run by a copy or a discard meanwhile, leaves a live probe alone.
using var reservation = SafeFileWriter.ReserveTemporaryFile(probe);
try
{
try
+75 -30
View File
@@ -114,9 +114,17 @@ public sealed class ImportService : IAsyncDisposable
{
EnsureIdle();
var source = Sources.Inspect(sourcePath);
var run = await Analyzer.CreateRunAsync(source, options, ct).ConfigureAwait(false);
StartJob(run.Id, ImportPhase.Analyzing, (progress, token) => Analyzer.AnalyzeAsync(run.Id, progress, token));
return run;
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>
@@ -124,19 +132,30 @@ public sealed class ImportService : IAsyncDisposable
{
var run = await _env.Storage.Imports.GetRunAsync(runId, ct).ConfigureAwait(false)
?? throw new KeyNotFoundException($"Importazione {runId} non trovata.");
switch (run.State)
if (run.State is not (ImportRunState.Analyzing or ImportRunState.AnalysisInterrupted or ImportRunState.Copying or ImportRunState.CopyInterrupted))
{
case ImportRunState.Analyzing or ImportRunState.AnalysisInterrupted:
StartJob(runId, ImportPhase.Analyzing, (progress, token) => Analyzer.AnalyzeAsync(runId, progress, token));
break;
case ImportRunState.Copying or ImportRunState.CopyInterrupted:
StartJob(runId, ImportPhase.Copying, (progress, token) => Copier.CopyAsync(runId, progress, token));
break;
default:
throw new InvalidOperationException("Questa importazione non è interrotta: non c'è niente da riprendere.");
throw new InvalidOperationException("Questa importazione non è interrotta: non c'è niente da riprendere.");
}
return run;
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>
@@ -146,16 +165,24 @@ public sealed class ImportService : IAsyncDisposable
public async Task<ImportRun> StartCopyAsync(long runId, ImportMode? mode = null, CancellationToken ct = default)
{
EnsureIdle();
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))
var lease = await EnterGateAsync(ct).ConfigureAwait(false);
try
{
throw new InvalidOperationException("L'analisi non è finita: riprendila prima di importare.");
}
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));
return run;
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>
@@ -278,6 +305,10 @@ public sealed class ImportService : IAsyncDisposable
}
}
/// <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)
@@ -285,14 +316,32 @@ public sealed class ImportService : IAsyncDisposable
throw new InvalidOperationException("C'è già un'importazione al lavoro: aspetta che finisca o interrompila.");
}
// Checked up front too, so a refused start records nothing; StartJob takes the gate for real.
if (_env.Gate?.Busy is { } busy)
if (_env.Gate?.BusyFirm is { } busy)
{
throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Import, busy));
}
}
private void StartJob(long runId, ImportPhase phase, Func<IProgress<ImportProgress>, CancellationToken, Task> work)
/// <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)
{
@@ -301,12 +350,8 @@ public sealed class ImportService : IAsyncDisposable
throw new InvalidOperationException("C'è già un'importazione al lavoro: aspetta che finisca o interrompila.");
}
IDisposable? lease = null;
if (_env.Gate is { } gate && !gate.TryEnter(LongWorkKind.Import, out lease, out var busy))
{
throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Import, busy!.Value));
}
var lease = held;
held = null;
_job?.Cancellation.Dispose();
var cancellation = new CancellationTokenSource();
var reporter = new Reporter(this);
@@ -151,7 +151,8 @@ public sealed record StillVideoProgress(
/// <item><see cref="StartAsync"/>, «Cerca i video fermi» from a selection (answer 41): a job in memory, one video at a
/// time, never during an engine session and never while an import, a copy, a rebuild or a zip of frames holds the
/// <see cref="LongWorkGate"/> (it takes no lease, so it never blocks them: a video being analysed when one starts is
/// given up and analysed again after). Each video within <see cref="StillVideoEnvironment.JobBudget"/>, inside the
/// given up and analysed again after). An automatic copy is the exception: a start asks it to stop
/// (<see cref="LongWorkGate.CancelYielding"/>, tappa E5), and the job waits only until it has let go. Each video within <see cref="StillVideoEnvironment.JobBudget"/>, inside the
/// <see cref="ConversionThrottle"/>; past it «Non analizzabile» (TooSlow) is stored. Videos with a result of the current
/// algorithm are skipped, but for those whose analysis took too long (a start tries them again, once): so a job ended by
/// «Interrompi» or by closing Febe is not resumed by itself: started again, it goes on where it was.</item>
@@ -360,6 +361,7 @@ public sealed class StillVideoService : IDisposable
{
ObjectDisposedException.ThrowIf(_disposed, this);
var (items, _, _, _) = await CollectAsync(selection, ct).ConfigureAwait(false);
StillVideoProgress started;
lock (_lock)
{
if (!_running || _jobStop.IsCancellationRequested)
@@ -393,8 +395,17 @@ public sealed class StillVideoService : IDisposable
_loop = Task.Run(LoopAsync);
}
return Snapshot() with { Added = added };
started = Snapshot() with { Added = added };
}
if (started.Running)
{
// Alberto's search comes before an automatic copy (§16 answer 49): it is asked to stop, outside the lock (the
// token's callbacks run synchronously), and the job waits for the gate as for any long work.
_env.Gate?.CancelYielding();
}
return started;
}
/// <summary>«Interrompi»: the queue empties, the video being analysed is given up and nothing is stored for it.</summary>