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>
576 lines
30 KiB
C#
576 lines
30 KiB
C#
using Febe.Core.Abstractions;
|
|
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;
|
|
|
|
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. 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
|
|
{
|
|
public TestContext TestContext { get; set; } = null!;
|
|
|
|
[TestMethod]
|
|
public void TheGateLetsOneLongJobRunAtATime()
|
|
{
|
|
var gate = new LongWorkGate();
|
|
Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var lease, out _));
|
|
Assert.AreEqual(LongWorkKind.Import, gate.Busy);
|
|
Assert.IsFalse(gate.TryEnter(LongWorkKind.Export, out _, out var busy));
|
|
Assert.AreEqual(LongWorkKind.Import, busy);
|
|
Assert.AreEqual(
|
|
"C'è un'importazione al lavoro: aspetta che finisca o interrompila, poi copia.",
|
|
LongWorkGate.BusyMessage(LongWorkKind.Export, busy!.Value));
|
|
|
|
lease.Dispose();
|
|
Assert.IsNull(gate.Busy);
|
|
Assert.IsTrue(gate.TryEnter(LongWorkKind.Rebuild, out var rebuild, out _));
|
|
lease.Dispose(); // a second dispose of the old lease releases nothing
|
|
Assert.AreEqual(LongWorkKind.Rebuild, gate.Busy);
|
|
rebuild.Dispose();
|
|
}
|
|
|
|
[TestMethod]
|
|
public void AForegroundLeasePreemptsTheBackgroundOneAndBusyIgnoresIt()
|
|
{
|
|
var gate = new LongWorkGate();
|
|
Assert.IsTrue(gate.TryEnterBackground(out var background));
|
|
Assert.IsNull(gate.Busy, "Busy ignores the background lease");
|
|
Assert.IsTrue(gate.BackgroundRunning);
|
|
Assert.IsFalse(gate.TryEnterBackground(out _));
|
|
|
|
Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var import, out _));
|
|
Assert.IsTrue(background.Preempted.IsCancellationRequested);
|
|
Assert.IsTrue(background.IsPreempted);
|
|
Assert.IsFalse(background.TryBeginCommit(out _), "no commit once pre-empted");
|
|
Assert.IsFalse(gate.BackgroundRunning);
|
|
Assert.AreEqual(LongWorkKind.Import, gate.Busy);
|
|
background.Dispose();
|
|
|
|
Assert.IsFalse(gate.TryEnterBackground(out _), "the background waits for the foreground");
|
|
import.Dispose();
|
|
Assert.IsTrue(gate.TryEnterBackground(out var again));
|
|
again.Dispose();
|
|
Assert.IsFalse(gate.BackgroundRunning);
|
|
Assert.IsTrue(gate.TryEnter(LongWorkKind.Export, out var export, out _));
|
|
export.Dispose();
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task AForegroundLeaseWaitsForACommit()
|
|
{
|
|
var gate = new LongWorkGate();
|
|
Assert.IsTrue(gate.TryEnterBackground(out var background));
|
|
Assert.IsTrue(background.TryBeginCommit(out var commit));
|
|
var entering = Task.Run(() => gate.TryEnter(LongWorkKind.Rebuild, out var lease, out _) ? lease : null, TestContext.CancellationToken);
|
|
while (!background.Preempted.IsCancellationRequested)
|
|
{
|
|
await Task.Yield();
|
|
}
|
|
|
|
Assert.IsFalse(entering.IsCompleted, "the rebuild waits for the commit");
|
|
commit.Dispose();
|
|
var rebuild = await entering;
|
|
Assert.IsNotNull(rebuild);
|
|
rebuild.Dispose();
|
|
background.Dispose();
|
|
|
|
// A commit that does not end in time: the foreground job is refused with its own message.
|
|
var quick = new LongWorkGate { CommitWait = TimeSpan.FromMilliseconds(20) };
|
|
Assert.IsTrue(quick.TryEnterBackground(out var slow));
|
|
Assert.IsTrue(slow.TryBeginCommit(out var held));
|
|
Assert.IsFalse(quick.TryEnter(LongWorkKind.Export, out _, out var busy));
|
|
Assert.AreEqual(LongWorkKind.LibraryConversion, busy);
|
|
Assert.IsNull(quick.Busy);
|
|
held.Dispose();
|
|
slow.Dispose();
|
|
}
|
|
|
|
[TestMethod]
|
|
public void NewKindsHaveTheirOwnMessages()
|
|
{
|
|
Assert.AreEqual(
|
|
"La conversione della libreria sta salvando un file: riprova fra un attimo.",
|
|
LongWorkGate.BusyMessage(LongWorkKind.Import, LongWorkKind.LibraryConversion));
|
|
Assert.AreEqual(
|
|
"Si sta preparando uno zip di fotogrammi: aspetta che finisca, poi importa.",
|
|
LongWorkGate.BusyMessage(LongWorkKind.Import, LongWorkKind.FrameDownload));
|
|
Assert.AreEqual(
|
|
"C'è un'importazione al lavoro: aspetta che finisca o interrompila, poi scarica i fotogrammi.",
|
|
LongWorkGate.BusyMessage(LongWorkKind.FrameDownload, LongWorkKind.Import));
|
|
Assert.AreEqual(
|
|
"La ricostruzione del database è in corso: aspetta che finisca.",
|
|
LongWorkGate.BusyMessage(LongWorkKind.FrameDownload, LongWorkKind.Rebuild));
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task AnImportDoesNotStartWhileTheGateIsHeld()
|
|
{
|
|
using var temp = new TempFolder();
|
|
await using var bed = await ImportTestBed.CreateAsync(temp);
|
|
var gate = new LongWorkGate();
|
|
await using var service = new ImportService(bed.Environment with { Gate = gate });
|
|
Assert.IsTrue(gate.TryEnter(LongWorkKind.Export, out var lease, out _));
|
|
|
|
var refused = await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => service.StartAsync(bed.Source, ct: TestContext.CancellationToken));
|
|
Assert.StartsWith("C'è una copia nelle cartelle esterne al lavoro", refused.Message);
|
|
Assert.IsEmpty(await bed.Library.Db.Imports.ListRunsAsync(TestContext.CancellationToken));
|
|
|
|
lease.Dispose();
|
|
var run = await service.StartAsync(bed.Source, ct: TestContext.CancellationToken);
|
|
await service.WaitAsync(run.Id, TestContext.CancellationToken);
|
|
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()
|
|
{
|
|
const string content = """
|
|
22 1 8:1 / / rw,relatime shared:1 - ext4 /dev/sda1 rw
|
|
40 22 8:17 /backup/foto /esporta/usb rw,noatime master:3 - vfat /dev/sdb1 rw
|
|
41 22 0:50 / /esporta/nas\040rete ro,relatime - cifs //nas/copie rw
|
|
bad line
|
|
""";
|
|
var mounts = MountInfoTable.Parse(content);
|
|
Assert.HasCount(3, mounts);
|
|
Assert.AreEqual("/esporta/nas rete", mounts[2].MountPoint);
|
|
Assert.IsTrue(mounts[2].ReadOnly);
|
|
Assert.AreEqual("/backup/foto", MountInfoTable.FindContaining(mounts, "/esporta/usb/Febe")!.Root);
|
|
Assert.AreEqual("vfat", MountInfoTable.FindContaining(mounts, "/esporta/usb")!.FileSystemType);
|
|
Assert.AreEqual("/", MountInfoTable.FindContaining(mounts, "/esporta/usbx")!.MountPoint);
|
|
|
|
var o = ExportRootOptions.Docker("/esporta", declared: true, new ProcMountInfo(() => content));
|
|
Assert.IsFalse(ExportRoots.Evaluate(o with { Declared = false }).Active);
|
|
Assert.IsFalse(ExportRoots.Evaluate(ExportRootOptions.Docker("/esporta", declared: true, new ProcMountInfo(() => "22 1 8:1 / / rw - ext4 /dev/sda1 rw"))).Active);
|
|
if (!OperatingSystem.IsWindows())
|
|
{
|
|
// Docker paths are Linux paths: on Windows "/esporta" becomes a drive path the table cannot hold.
|
|
Assert.IsTrue(ExportRoots.Evaluate(o).Active);
|
|
Assert.IsNull(ExportRoots.MountProblem(o, "/esporta/usb/Febe"));
|
|
Assert.Contains("sola lettura", ExportRoots.MountProblem(o, "/esporta/nas rete/x")!);
|
|
Assert.IsNotNull(ExportRoots.MountProblem(o, "/esporta/altro"));
|
|
}
|
|
|
|
Assert.AreEqual(ExportFolderProblemKind.ParentSegment, Assert.ThrowsExactly<ExportFolderException>(() => ExportRoots.Resolve(o, "usb/../../etc")).Kind);
|
|
Assert.AreEqual(ExportFolderProblemKind.ExportRootItself, Assert.ThrowsExactly<ExportFolderException>(() => ExportRoots.Resolve(o, ".")).Kind);
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task TheFolderCheckRefusesOverlapsAndLeavesNoProbe()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
using var temp = new TempFolder();
|
|
var library = temp.Combine("libreria");
|
|
var data = temp.Combine("dati");
|
|
var outside = temp.Combine("copie");
|
|
Directory.CreateDirectory(Path.Combine(library, "marta.demo"));
|
|
Directory.CreateDirectory(data);
|
|
Directory.CreateDirectory(outside);
|
|
var context = new ExportFolderContext(
|
|
[new(data, ProtectedFolderKind.Data, null), new(library, ProtectedFolderKind.Library, null), new(Path.Combine(library, "marta.demo"), ProtectedFolderKind.Account, "marta.demo")],
|
|
ExportRootOptions.AnyFolder);
|
|
var check = new ExportFolderCheck(new ProcMountInfo(() => null));
|
|
|
|
var accepted = await check.CheckAsync(outside, context, ct);
|
|
Assert.IsTrue(accepted.Accepted, accepted.Problem?.Message);
|
|
Assert.IsEmpty(Directory.GetFileSystemEntries(outside));
|
|
Assert.AreEqual(ExportFolderProblemKind.InsideProtected, (await check.CheckAsync(Path.Combine(library, "marta.demo"), context with { Protected = context.Protected.Take(2).ToList() }, ct)).Problem!.Kind);
|
|
Assert.AreEqual(ExportFolderProblemKind.SameAsProtected, (await check.CheckAsync(data, context, ct)).Problem!.Kind);
|
|
Assert.AreEqual(ExportFolderProblemKind.ContainsProtected, (await check.CheckAsync(temp.Path, context, ct)).Problem!.Kind);
|
|
Assert.AreEqual(ExportFolderProblemKind.Missing, (await check.CheckAsync(temp.Combine("non-esiste"), context, ct)).Problem!.Kind);
|
|
Assert.AreEqual(ExportFolderProblemKind.NotFullyQualified, (await check.CheckAsync("relativa", context, ct)).Problem!.Kind);
|
|
Assert.AreEqual(ExportFolderProblemKind.RootOfDisk, (await check.CheckAsync(Path.GetPathRoot(temp.Path)!, context, ct)).Problem!.Kind);
|
|
Assert.IsFalse(Directory.Exists(temp.Combine("non-esiste")));
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task TheSafeWriterNeverCreatesAMissingRoot()
|
|
{
|
|
using var temp = new TempFolder();
|
|
var root = temp.Combine("disco-assente");
|
|
using var source = new MemoryStream([1, 2, 3]);
|
|
await Assert.ThrowsExactlyAsync<ExportRootMissingException>(() => new SafeFileWriter().SaveAsync(
|
|
source, root, "a/b.jpg", new SafeWriteOptions { RequireExistingRoot = true, VerifyFromDisk = true }, TestContext.CancellationToken));
|
|
Assert.IsFalse(Directory.Exists(root));
|
|
|
|
Directory.CreateDirectory(root);
|
|
source.Position = 0;
|
|
var saved = await new SafeFileWriter().SaveAsync(source, root, "a/b.jpg", new SafeWriteOptions { RequireExistingRoot = true, VerifyFromDisk = true }, TestContext.CancellationToken);
|
|
Assert.AreEqual("a/b.jpg", saved.RelativePath);
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task DestinationsAreCheckedAndTheSwitchIsOnByDefault()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
using var temp = new TempFolder();
|
|
await using var library = await TestLibrary.CreateAsync(temp);
|
|
var account = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100"), ct);
|
|
var env = new ExportEnvironment { Storage = library.Db, Layout = () => library.Layout, DataFolder = library.Data.Root, Clock = library.Clock, Root = ExportRootOptions.AnyFolder with { Mounts = new ProcMountInfo(() => null) } };
|
|
var destinations = new ExportDestinations(env);
|
|
var usb = temp.Combine("usb");
|
|
Directory.CreateDirectory(usb);
|
|
|
|
Assert.IsTrue((await destinations.ResolveAsync(account.Id, ct)) is { Enabled: true, HasDestination: false });
|
|
await Assert.ThrowsExactlyAsync<ExportFolderException>(() => destinations.CreateAsync(Spec(library.Layout.Root), ct));
|
|
await Assert.ThrowsExactlyAsync<ArgumentException>(() => destinations.CreateAsync(Spec(usb) with { ContentTypes = ContentTypes.None }, ct));
|
|
await Assert.ThrowsExactlyAsync<ArgumentException>(() => destinations.CreateAsync(Spec(usb) with { NamingScheme = "{inesistente}" }, ct));
|
|
|
|
var saved = await destinations.CreateAsync(Spec(usb) with { Label = " Disco USB " }, ct);
|
|
Assert.AreEqual("Disco USB", saved.Destination.Label);
|
|
var all = await destinations.ResolveAllAsync(ct);
|
|
Assert.AreEqual(saved.Destination.Id, all[account.Id].Destination!.Id);
|
|
Assert.IsTrue(all[account.Id].Exports);
|
|
|
|
await destinations.SetAccountEnabledAsync(account.Id, false, ct);
|
|
Assert.IsFalse((await destinations.ResolveAsync(account.Id, ct)).Exports);
|
|
|
|
var run = await library.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = saved.Destination.Id, StartedAt = library.Clock.Now }, ct);
|
|
await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => destinations.RetireAsync(saved.Destination.Id, ct));
|
|
await library.Db.Exports.UpdateRunAsync(run with { State = ExportRunState.Cancelled }, ct);
|
|
await destinations.RetireAsync(saved.Destination.Id, ct);
|
|
Assert.IsTrue(Directory.Exists(usb));
|
|
Assert.IsFalse((await destinations.ResolveAsync(account.Id, ct)).HasDestination);
|
|
Assert.IsEmpty(await destinations.RecheckAsync(null, ct));
|
|
|
|
static DestinationSpec Spec(string path) => new(ExportScope.General, null, path, null, ContentTypes.All, null, null, null);
|
|
}
|
|
}
|