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

@@ -3,6 +3,7 @@ using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Import;
using Febe.Core.Library;
using Febe.Tests.Export.Support;
using Febe.Tests.Import.Support;
using Febe.Tests.Support;
@@ -10,7 +11,8 @@ namespace Febe.Tests.Export;
/// <summary>
/// The shared pieces of tappa E2 (WP1a): the gate of long work, the mount table, the export root in Docker, the folder
/// check with its probe, the destinations with «Esporta questo account» on by default. WP5 adds the full set.
/// check with its probe, the destinations with «Esporta questo account» on by default. WP5 adds the full set. Tappa E5
/// (WP1) adds the yielding leases of the automatic export and the starters that await them outside their locks.
/// </summary>
[TestClass]
public sealed class ExportFoundationTests
@@ -129,6 +131,334 @@ public sealed class ExportFoundationTests
Assert.IsNull(gate.Busy); // the job's lease went with it
}
// ---------------------------------------------------------------- Yielding leases (tappa E5, D6; §16 answer 49)
[TestMethod]
public void AYieldingLeaseExcludesOthersLikeAnyLease()
{
var gate = new LongWorkGate();
Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out var yield, out var none));
Assert.IsNull(none);
Assert.IsTrue(yield.CanBeCanceled);
Assert.IsFalse(yield.IsCancellationRequested);
Assert.IsFalse(gate.TryEnterYielding(LongWorkKind.Export, out _, out var second, out var busy));
Assert.AreEqual(LongWorkKind.Export, busy);
Assert.IsFalse(second.CanBeCanceled);
Assert.IsFalse(gate.TryEnter(LongWorkKind.Rebuild, out _, out busy));
Assert.AreEqual(LongWorkKind.Export, busy);
automatic.Dispose();
Assert.IsNull(gate.Busy);
Assert.IsFalse(gate.HeldByYielding);
Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var import, out _));
automatic.Dispose(); // a second dispose of the old lease releases nothing
Assert.AreEqual(LongWorkKind.Import, gate.Busy);
import.Dispose();
Assert.ThrowsExactly<ArgumentException>(() => gate.TryEnterYielding(LongWorkKind.LibraryConversion, out _, out _, out _));
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task EnterAsyncDisplacesTheYieldingHolderAndTakesTheGateAtOnce()
{
var ct = TestContext.CancellationToken;
var gate = new LongWorkGate();
Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out var yield, out _));
var entering = gate.EnterAsync(LongWorkKind.Import, TimeSpan.FromSeconds(30), ct);
// The new holder is in place before the copy has let go: nothing can slip in between.
Assert.IsTrue(yield.IsCancellationRequested, "the copy is asked to stop");
Assert.IsFalse(entering.IsCompleted, "the import waits for the copy to let go");
Assert.AreEqual(LongWorkKind.Import, gate.Busy);
Assert.AreEqual(LongWorkKind.Import, gate.BusyFirm);
Assert.IsFalse(gate.HeldByYielding);
Assert.IsFalse(gate.TryEnterYielding(LongWorkKind.Export, out _, out _, out var busy), "the worker cannot start again meanwhile");
Assert.AreEqual(LongWorkKind.Import, busy);
Assert.IsFalse(gate.TryEnter(LongWorkKind.Rebuild, out _, out busy));
Assert.AreEqual(LongWorkKind.Import, busy);
Assert.AreEqual(LongWorkKind.Import, (await gate.EnterAsync(LongWorkKind.Rebuild, TimeSpan.FromSeconds(30), ct)).BusyWith, "a firm holder refuses at once");
automatic.Dispose(); // the copy unwinds: its release does not clear the new holder
var entry = await entering.WaitAsync(TimeSpan.FromSeconds(30), ct);
Assert.IsNull(entry.BusyWith);
Assert.IsNotNull(entry.Lease);
Assert.AreEqual(LongWorkKind.Import, gate.Busy);
entry.Lease.Dispose();
Assert.IsNull(gate.Busy);
// A free gate is taken at once, and so is one whose yielding holder has already let go.
var free = await gate.EnterAsync(LongWorkKind.Rebuild, ct);
Assert.IsNotNull(free.Lease);
Assert.AreEqual(LongWorkKind.Rebuild, gate.Busy);
free.Lease.Dispose();
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task EnterAsyncGivesExportWhenTheYieldingHolderDoesNotReleaseInTime()
{
var ct = TestContext.CancellationToken;
var gate = new LongWorkGate { YieldWait = TimeSpan.FromMilliseconds(100) };
Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var stuck, out var yield, out _));
var watch = System.Diagnostics.Stopwatch.StartNew();
var entry = await gate.EnterAsync(LongWorkKind.Import, ct);
watch.Stop();
Assert.IsNull(entry.Lease);
Assert.AreEqual(LongWorkKind.Export, entry.BusyWith);
Assert.IsTrue(yield.IsCancellationRequested);
Assert.IsLessThan(TimeSpan.FromSeconds(10), watch.Elapsed, "the wait is bounded");
// The copy that has not let go yet keeps the gate: nothing starts over a copy that may still write.
Assert.AreEqual(LongWorkKind.Export, gate.Busy);
Assert.IsTrue(gate.HeldByYielding);
Assert.IsFalse(gate.TryEnter(LongWorkKind.Rebuild, out _, out var busy));
Assert.AreEqual(LongWorkKind.Export, busy);
// The same when the caller gives up (the page went away).
using var gone = new CancellationTokenSource();
var waiting = gate.EnterAsync(LongWorkKind.Rebuild, TimeSpan.FromSeconds(30), gone.Token);
Assert.AreEqual(LongWorkKind.Rebuild, gate.Busy);
await gone.CancelAsync();
await Assert.ThrowsAsync<OperationCanceledException>(() => waiting);
Assert.AreEqual(LongWorkKind.Export, gate.Busy);
Assert.IsTrue(gate.HeldByYielding);
stuck.Dispose();
Assert.IsNull(gate.Busy);
var late = await gate.EnterAsync(LongWorkKind.Import, ct);
Assert.IsNotNull(late.Lease, "once it let go the gate is free");
late.Lease.Dispose();
}
[TestMethod]
public void TryEnterRefusesAYieldingHolderWithoutWaiting()
{
var gate = new LongWorkGate { YieldWait = TimeSpan.FromMinutes(5) };
Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out var yield, out _));
var watch = System.Diagnostics.Stopwatch.StartNew();
Assert.IsFalse(gate.TryEnter(LongWorkKind.Import, out _, out var busy));
watch.Stop();
Assert.AreEqual(LongWorkKind.Export, busy);
Assert.IsLessThan(TimeSpan.FromSeconds(5), watch.Elapsed);
Assert.IsFalse(yield.IsCancellationRequested, "a caller left on TryEnter does not stop the copy");
Assert.IsTrue(gate.HeldByYielding);
automatic.Dispose();
}
[TestMethod]
public void TryEnterYieldingFailsWhileAnyLeaseIsHeldAndPreemptsTheLibraryConversion()
{
var gate = new LongWorkGate();
foreach (var kind in new[] { LongWorkKind.Import, LongWorkKind.Export, LongWorkKind.Rebuild, LongWorkKind.FrameDownload })
{
Assert.IsTrue(gate.TryEnter(kind, out var firm, out _));
Assert.IsFalse(gate.TryEnterYielding(LongWorkKind.Export, out _, out _, out var busy), kind.ToString());
Assert.AreEqual(kind, busy);
firm.Dispose();
}
Assert.IsTrue(gate.TryEnterBackground(out var conversion));
Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out _, out _));
Assert.IsTrue(conversion.Preempted.IsCancellationRequested, "the automatic copy pre-empts the library conversion");
Assert.IsTrue(conversion.IsPreempted);
Assert.IsFalse(gate.BackgroundRunning);
conversion.Dispose();
automatic.Dispose();
// A commit of the conversion is waited for, as with TryEnter.
var quick = new LongWorkGate { CommitWait = TimeSpan.FromMilliseconds(20) };
Assert.IsTrue(quick.TryEnterBackground(out var slow));
Assert.IsTrue(slow.TryBeginCommit(out var commit));
Assert.IsFalse(quick.TryEnterYielding(LongWorkKind.Export, out _, out _, out var committing));
Assert.AreEqual(LongWorkKind.LibraryConversion, committing);
Assert.IsNull(quick.Busy);
commit.Dispose();
slow.Dispose();
}
[TestMethod]
public void TryEnterBackgroundFailsWhileAYieldingLeaseIsHeld()
{
var gate = new LongWorkGate();
Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out _, out _));
Assert.IsFalse(gate.TryEnterBackground(out _), "the library conversion waits for the automatic copy too");
automatic.Dispose();
Assert.IsTrue(gate.TryEnterBackground(out var conversion));
conversion.Dispose();
}
[TestMethod]
public void BusyReportsExportButBusyFirmIsNullForAYieldingHolder()
{
var gate = new LongWorkGate();
Assert.IsNull(gate.BusyFirm);
Assert.IsFalse(gate.HeldByYielding);
Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out _, out _));
Assert.AreEqual(LongWorkKind.Export, gate.Busy, "the conversion and the still-video search keep waiting");
Assert.IsNull(gate.BusyFirm, "a start is not refused: the copy gives way");
Assert.IsTrue(gate.HeldByYielding);
automatic.Dispose();
Assert.IsTrue(gate.TryEnter(LongWorkKind.Export, out var manual, out _));
Assert.AreEqual(LongWorkKind.Export, gate.Busy);
Assert.AreEqual(LongWorkKind.Export, gate.BusyFirm, "a copy started by Alberto does not give way");
Assert.IsFalse(gate.HeldByYielding);
manual.Dispose();
Assert.IsNull(gate.BusyFirm);
}
[TestMethod]
public void CancelYieldingStopsTheHolderWithoutTakingTheGate()
{
var gate = new LongWorkGate();
gate.CancelYielding(); // nothing held: nothing happens
Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var import, out _));
gate.CancelYielding(); // a firm holder is not touched
Assert.AreEqual(LongWorkKind.Import, gate.Busy);
import.Dispose();
Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out var yield, out _));
gate.CancelYielding();
Assert.IsTrue(yield.IsCancellationRequested);
Assert.AreEqual(LongWorkKind.Export, gate.Busy, "the gate stays held until the copy lets go");
Assert.IsTrue(gate.HeldByYielding);
Assert.IsFalse(gate.TryEnterYielding(LongWorkKind.Export, out _, out _, out _));
automatic.Dispose();
Assert.IsNull(gate.Busy);
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task AnImportStartRecordsNothingWhenRefused_AndWaitsOutsideItsLock()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var bed = await ImportTestBed.CreateAsync(temp);
bed.Write("marta.demo/a.jpg", ImportTestFiles.Photo(330, 200, 150));
var gate = new LongWorkGate();
await using var service = new ImportService(bed.Environment with { Gate = gate });
Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out var yield, out _));
var first = service.StartAsync(bed.Source, ct: ct);
Assert.IsTrue(yield.IsCancellationRequested, "the automatic copy is asked to give way");
Assert.IsFalse(first.IsCompleted, "the import waits for the copy to let go");
Assert.AreEqual(LongWorkKind.Import, gate.BusyFirm, "the import holds the gate already");
var active = await Task.Run(() => service.ActiveRunId, ct).WaitAsync(TimeSpan.FromSeconds(10), ct);
Assert.IsNull(active, "the service's own lock is free while it waits");
Assert.IsEmpty(await service.ListRunsAsync(ct), "nothing is recorded before the gate is taken");
// A second start meanwhile is answered at once, and records nothing.
var second = await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => service.StartAsync(bed.Source, ct: ct));
Assert.AreEqual(LongWorkGate.BusyMessage(LongWorkKind.Import, LongWorkKind.Import), second.Message);
Assert.IsFalse(first.IsCompleted);
Assert.IsEmpty(await service.ListRunsAsync(ct));
automatic.Dispose();
var run = await first.WaitAsync(TimeSpan.FromSeconds(30), ct);
await service.WaitAsync(run.Id, ct);
Assert.HasCount(1, await service.ListRunsAsync(ct));
Assert.IsNull(gate.Busy, "the job's lease went with it");
// A copy that does not let go in time: refused with the copy's message, nothing recorded, the copy keeps the gate.
var slow = new LongWorkGate { YieldWait = TimeSpan.FromMilliseconds(100) };
await using var other = new ImportService(bed.Environment with { Gate = slow });
Assert.IsTrue(slow.TryEnterYielding(LongWorkKind.Export, out var stuck, out _, out _));
var refused = await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => other.StartAsync(bed.Source, ct: ct));
Assert.AreEqual(LongWorkGate.BusyMessage(LongWorkKind.Import, LongWorkKind.Export), refused.Message);
Assert.HasCount(1, await other.ListRunsAsync(ct), "a refused import records nothing");
Assert.IsTrue(slow.HeldByYielding);
stuck.Dispose();
// A copy started by Alberto refuses at once, before anything is read or recorded.
Assert.IsTrue(slow.TryEnter(LongWorkKind.Export, out var manual, out _));
var firm = await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => other.StartCopyAsync(run.Id, ImportMode.Copy, ct));
Assert.AreEqual(LongWorkGate.BusyMessage(LongWorkKind.Import, LongWorkKind.Export), firm.Message);
manual.Dispose();
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task TheRebuildStartAwaitsTheYieldOutsideItsLock()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var gate = new LongWorkGate();
var job = new Febe.Web.Library.RebuildJob(
library.Db,
new Febe.Web.Library.FebeLibrary(library.Db, library.Data, library.Layout, library.Clock),
library.Clock,
new Febe.Web.Library.LibraryChanges(),
gate);
Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out var yield, out _));
var starting = job.TryStartAsync(ct);
Assert.IsTrue(yield.IsCancellationRequested, "the automatic copy is asked to give way");
Assert.IsFalse(starting.IsCompleted, "the rebuild waits for the copy to let go");
var running = await Task.Run(() => job.Running, ct).WaitAsync(TimeSpan.FromSeconds(10), ct);
Assert.IsFalse(running, "the job's own lock is free while it waits");
// Meanwhile another «Ricostruisci» is answered at once.
var again = await job.TryStartAsync(ct).WaitAsync(TimeSpan.FromSeconds(10), ct);
Assert.IsFalse(again.Started);
Assert.AreEqual(LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Rebuild), again.Busy);
Assert.IsFalse(job.TryStart(out var busy));
Assert.AreEqual(LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Rebuild), busy);
var signals = AutoExportSignal.Default.Count;
automatic.Dispose();
var started = await starting.WaitAsync(TimeSpan.FromSeconds(30), ct);
Assert.IsTrue(started.Started);
Assert.IsNull(started.Busy);
await job.WaitAsync();
Assert.IsNull(job.State.Error);
Assert.IsNotNull(job.State.Report);
Assert.IsNull(gate.Busy, "the rebuild's lease went with it");
Assert.IsGreaterThan(signals, AutoExportSignal.Default.Count, "a finished rebuild wakes the automatic export");
// A long work that does not give way refuses the rebuild with its message.
Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var import, out _));
var refused = await job.TryStartAsync(ct);
Assert.IsFalse(refused.Started);
Assert.AreEqual(LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Import), refused.Busy);
import.Dispose();
}
[TestMethod]
public async Task TheProbeIsReservedWhileItIsChecked()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
var usb = temp.Combine("usb");
Directory.CreateDirectory(usb);
var survived = new List<bool>();
var check = new ExportFolderCheck(new FixedMounts(), writeProbe: path =>
{
File.WriteAllText(path, "Febe");
// The clean-up of leftovers of another job runs in the same folder meanwhile (tappa E5, D7.12).
SafeFileWriter.CleanupTemporaryFiles(usb);
survived.Add(File.Exists(path));
});
var context = new ExportFolderContext([], ExportRootOptions.AnyFolder with { Mounts = new FixedMounts() });
Assert.IsTrue((await check.CheckAsync(usb, context, ct)).Accepted);
CollectionAssert.AreEqual(new[] { true }, survived, "a live probe is left alone");
Assert.IsEmpty(Directory.GetFileSystemEntries(usb), "the probe is removed after the check");
// Once the check is over, a probe left behind is an ordinary leftover.
var left = Path.Combine(usb, ExportFolderCheck.NewProbeName());
File.WriteAllText(left, "Febe");
Assert.AreEqual(1, SafeFileWriter.CleanupTemporaryFiles(usb));
}
[TestMethod]
public void MountInfoGivesRootMountPointAndType()
{
@@ -294,6 +294,35 @@ public sealed class StillVideoServiceTests
Assert.AreEqual(VideoAnalysisOutcome.Still, (await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct))!.Outcome);
}
[TestMethod]
public async Task AStartAsksAnAutomaticCopyToStopAndWaitsUntilItLetsGo()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var (account, video) = await SaveVideoAsync(library, "1", StillVideo(12));
var empty = await library.Db.Accounts.AddAsync(Make.Account("luca.demo", "200"));
var gate = new LongWorkGate();
var calls = new ConcurrentQueue<string>();
using var service = new StillVideoService(Environment(library, gate) with { Analyser = Counting(calls) });
Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out var yield, out _));
// Nothing to search: the copy goes on.
Assert.IsFalse((await service.StartAsync(new ExportSelection.Account(empty.Id), ct)).Running);
Assert.IsFalse(yield.IsCancellationRequested);
// «Cerca i video fermi» comes first (§16 answer 49): the copy is asked to stop, and the job waits for the gate.
await service.StartAsync(new ExportSelection.Account(account.Id), ct);
Assert.IsTrue(yield.IsCancellationRequested);
await UntilAsync(() => service.Progress.Waiting == StillVideoText.LongWork, ct);
Assert.IsEmpty(calls);
automatic.Dispose();
await service.Job.WaitAsync(Patience, ct);
Assert.HasCount(1, calls);
Assert.AreEqual(VideoAnalysisOutcome.Still, (await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct))!.Outcome);
}
[TestMethod]
public async Task ASessionThatStartsDuringAnAnalysisMakesTheJobGiveWay()
{
@@ -222,6 +222,18 @@ public sealed class ExportFramesApiTests
}
Assert.IsNull(gate.Busy, "no lease is left behind");
// An automatic copy (tappa E5) does not stop «Scarica»: the zip asks it to give way and starts once it has.
Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out var yield, out _));
using (yield.Register(automatic.Dispose))
{
Assert.AreEqual(JsonValueKind.Null, (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", Selection(21))).Body.GetProperty("problem").ValueKind);
Assert.IsFalse(yield.IsCancellationRequested, "the plan alone does not stop the copy");
Assert.IsNotEmpty((await ZipAsync(server, Selection(21))).Entries);
Assert.IsTrue(yield.IsCancellationRequested);
}
Assert.IsNull(gate.Busy, "no lease is left behind");
}
[TestMethod]