Files
Febe/tests/Febe.Tests/Export/ExportServiceAutomaticTests.cs
T
Alby96andClaude Opus 5.5 0ff748db6f E5: una partenza automatica non ferma la conversione per un file che manca
HasAutomaticCandidatesAsync guarda solo la base dati: un file registrato
ma assente dal disco faceva prendere il cancello a ogni passata, e la
conversione della libreria si fermava per niente, prima che il piano lo
scartasse. Ora, dopo l'EXISTS, la partenza scorre i file dovuti fino al
primo presente sul disco e solo allora prende il cancello.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 21:16:35 +01:00

1117 lines
63 KiB
C#

using System.Diagnostics;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Storage;
using Febe.Tests.Codecs.Containers;
using Febe.Tests.Export.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Export;
/// <summary>
/// The service side of the automatic export (tappa E5, WP3, design §4.3): automatic starts that never throw because Febe
/// is busy and record only files to write; Alberto's work that displaces them; changes of destination serialised with
/// them; the copier's safety net; «Interrompi» and its hold (answer 53); the probe of a space pause; the bounded stop.
/// Only the library and folders of the temporary bed are touched; nothing contacts Instagram.
/// </summary>
[TestClass]
public sealed class ExportServiceAutomaticTests
{
private static readonly TimeSpan Patience = TimeSpan.FromSeconds(30);
public TestContext TestContext { get; set; } = null!;
/// <summary>An automatic job records only the files it writes: no «già copiato», no «Tolto», one run per destination.</summary>
[TestMethod]
public async Task TryStartAutomaticRecordsOnlyFilesToCopy_NoAlreadyCopiedItems()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var post = await bed.PostAsync(bed.Luca, "a01", 1, 2, 3);
var usb = await bed.GeneralAsync(ct: ct);
await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([post.Media[0].Id, post.Media[1].Id])), ct);
File.Delete(bed.GeneralCopy(bed.Luca, post.Media[1]));
await bed.Service.CheckCopiesAsync(usb.Id, ct);
await bed.Service.WaitAsync(ct);
var auto = await TurnOnAsync(bed, usb, ct);
var start = await bed.Service.TryStartAutomaticAsync(Selection(auto, round: false), ct);
await bed.Service.WaitAsync(ct);
Assert.AreEqual(AutoExportStartOutcome.Started, start.Outcome);
var run = start.Runs.Single();
Assert.AreEqual((ExportRunOrigin.Automatic, ExportRunKind.Copy, ExportRunState.Completed), (run.Origin, run.Kind, (await bed.RunAsync(run.Id, ct)).State));
var items = await bed.ItemsAsync(run.Id, ct);
Assert.AreEqual(post.Media[2].Id, items.Single().MediaId, "only the file not copied: not the copied one, not the «Tolto» one");
Assert.AreEqual(ExportItemState.Copied, items.Single().State);
Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[1])), "«Tolto» is never copied again by itself");
// Nothing left: no lease, no run.
var again = await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct);
Assert.AreEqual(AutoExportStartOutcome.NothingToDo, again.Outcome);
Assert.HasCount(2, await bed.Db.Exports.ListRunsAsync(ct), "«Controlla le copie» has no run");
}
/// <summary>
/// With «Copia anche quelli già in libreria» an automatic round copies exactly what «Copia in…» of the whole library
/// would write, folder by folder (two folders, a type not taken, an account switched off, copied, «Tolto», «Non
/// riuscito», the same bytes twice).
/// </summary>
[TestMethod]
public async Task AutomaticAllCopiesExactlyWhatCopyInWouldWrite()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var anna = await bed.Db.Accounts.AddAsync(Make.Account("anna.demo", "300"), ct);
var a = await bed.PostAsync(bed.Luca, "m01", 1, 2);
var b = await bed.PostAsync(bed.Luca, "m02", 3);
var c = await bed.PostAsync(bed.Luca, "m03", 4);
var d = await bed.PostAsync(bed.Luca, "m04", 5);
await bed.PostAsync(bed.Luca, "m05", 1);
await bed.PostAsync(bed.Marta, "m06", 6, 7);
await bed.PostAsync(anna, "m07", 8);
var usb = await bed.GeneralAsync(ct: ct);
var own = await bed.OwnAsync(bed.Marta, "marta-nas", ContentTypes.PostPhotos, ct);
await bed.Service.Destinations.SetAccountEnabledAsync(anna.Id, false, ct);
await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([b.Media[0].Id, c.Media[0].Id])), ct);
File.Delete(bed.GeneralCopy(bed.Luca, c.Media[0]));
await bed.Service.CheckCopiesAsync(usb.Id, ct);
await bed.Service.WaitAsync(ct);
await bed.Db.Exports.AddCopyAsync(
new ExportCopy
{
DestinationId = usb.Id,
AccountId = bed.Luca.Id,
MediaId = d.Media[0].Id,
SourceSha256 = d.Media[0].Sha256!,
Variant = ExportVariant.Whole,
State = ExportCopyState.Failed,
CopiedAt = Make.T0,
LastError = "Errore di lettura o scrittura: prova",
},
ct);
var general = await TurnOnAsync(bed, usb, ct);
var marta = await TurnOnAsync(bed, own, ct);
var planned = await PlannedWritesAsync(bed, ct);
var start = await bed.Service.TryStartAutomaticAsync(new ExportSelection.Automatic([Scope(general), Scope(marta)], [], Round: true), ct);
await bed.Service.WaitAsync(ct);
Assert.AreEqual(AutoExportStartOutcome.Started, start.Outcome);
CollectionAssert.AreEquivalent(new[] { usb.Id, own.Id }, start.Runs.Select(r => r.DestinationId).ToArray());
foreach (var run in start.Runs)
{
var items = await bed.ItemsAsync(run.Id, ct);
Assert.IsTrue(items.All(i => i.State == ExportItemState.Copied), string.Join(", ", items.Select(i => i.State)));
var written = items.Select(i => (i.AccountId!.Value, i.SourceSha256!)).ToHashSet();
Assert.IsTrue(planned[run.DestinationId].SetEquals(written), $"{run.DestinationId}: {string.Join(", ", written)}");
}
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, a.Media[1])));
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, d.Media[0])), "«Non riuscito» is retried by the round");
Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, c.Media[0])), "«Tolto» stays «Tolto»");
Assert.IsFalse(Directory.Exists(Path.Combine(bed.Usb, "anna.demo")), "«Esporta questo account» off");
Assert.AreEqual(AutoExportStartOutcome.NothingToDo, (await bed.Service.TryStartAutomaticAsync(new ExportSelection.Automatic([Scope(general), Scope(marta)], [], Round: true), ct)).Outcome);
}
/// <summary>
/// «Una copia sola»: the same bytes of two accounts, both new, are one file to write; the second is not even recorded
/// as «già copiato» (the skip list of D5), and the next pass finds nothing.
/// </summary>
[TestMethod]
public async Task WithOneCopyOnlyTheSameBytesOfTwoAccountsAreOneItem()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct);
var luca = await bed.PostAsync(bed.Luca, "o01", 1);
await bed.PostAsync(bed.Marta, "o02", 1);
var usb = await bed.GeneralAsync(ct: ct);
var auto = await TurnOnAsync(bed, usb, ct);
var start = await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct);
await bed.Service.WaitAsync(ct);
var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single();
Assert.AreEqual((luca.Media[0].Id, ExportItemState.Copied), (item.MediaId!.Value, item.State));
Assert.AreEqual(AutoExportStartOutcome.NothingToDo, (await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct)).Outcome);
}
/// <summary>A «Non riuscito» waits for the recovery round, and every round retries it whatever the error (answer 50).</summary>
[TestMethod]
public async Task AFailedCopyIsRetriedByTheRoundNotByASignalPass()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var post = await bed.PostAsync(bed.Luca, "f01", 1);
var usb = await bed.GeneralAsync(ct: ct);
await bed.Db.Exports.AddCopyAsync(
new ExportCopy
{
DestinationId = usb.Id,
AccountId = bed.Luca.Id,
MediaId = post.Media[0].Id,
SourceSha256 = post.Media[0].Sha256!,
Variant = ExportVariant.Whole,
State = ExportCopyState.Failed,
CopiedAt = Make.T0,
LastError = "Più grande di 4 GB",
},
ct);
var auto = await TurnOnAsync(bed, usb, ct);
Assert.AreEqual(AutoExportStartOutcome.NothingToDo, (await bed.Service.TryStartAutomaticAsync(Selection(auto, round: false), ct)).Outcome);
Assert.AreEqual(AutoExportStartOutcome.Started, (await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct)).Outcome);
await bed.Service.WaitAsync(ct);
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0])));
}
/// <summary>A busy Febe gives Busy, never an exception, and records nothing; Held while «Interrompi» holds.</summary>
[TestMethod]
public async Task TryStartAutomaticReturnsBusyInsteadOfThrowing()
{
var ct = TestContext.CancellationToken;
var held = new HeldExportFileSystem(p => p.EndsWith("_1.jpg", StringComparison.Ordinal));
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
var post = await bed.PostAsync(bed.Luca, "b01", 1, 2);
var usb = await bed.GeneralAsync(ct: ct);
var auto = await TurnOnAsync(bed, usb, ct);
var selection = Selection(auto, round: true);
// A job of Alberto's.
await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Media([post.Media[0].Id])), ct);
await held.Reached.Task.WaitAsync(Patience, ct);
await AssertBusyAsync(bed, selection, null, ct);
held.Release();
await bed.Service.WaitAsync(ct);
var runs = (await bed.Db.Exports.ListRunsAsync(ct)).Count;
// An import holding the gate.
Assert.IsTrue(bed.Gate.TryEnter(LongWorkKind.Import, out var import, out _));
await AssertBusyAsync(bed, selection, LongWorkKind.Import, ct);
import.Dispose();
// An engine session.
bed.Session.InSession = true;
await AssertBusyAsync(bed, selection, null, ct);
bed.Session.InSession = false;
// A change of destination in progress.
var changing = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var inside = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var change = bed.Service.ChangeDestinationAsync<bool>(usb.Id, async token =>
{
inside.TrySetResult();
await changing.Task.WaitAsync(token);
return true;
}, ct);
await inside.Task.WaitAsync(Patience, ct);
await AssertBusyAsync(bed, selection, null, ct);
changing.SetResult();
await change;
// «Interrompi» holds.
bed.Service.HoldAutomatic(bed.Clock.Now.AddMinutes(30));
Assert.AreEqual(AutoExportStartOutcome.Held, (await bed.Service.TryStartAutomaticAsync(selection, ct)).Outcome);
Assert.AreEqual(AutoExportStartOutcome.Held, (await bed.Service.TryResumeAutomaticAsync([1], ct)).Outcome);
bed.Service.ReleaseAutomaticHold();
Assert.HasCount(runs, await bed.Db.Exports.ListRunsAsync(ct), "nothing was recorded while busy");
Assert.IsNull(bed.Gate.Busy, "no lease left behind");
Assert.AreEqual(AutoExportStartOutcome.Started, (await bed.Service.TryStartAutomaticAsync(selection, ct)).Outcome);
held.Release();
await bed.Service.WaitAsync(ct);
}
/// <summary>
/// Nothing to copy takes no lease, so the library conversion is not pre-empted for nothing; something to copy takes
/// a yielding lease, which pre-empts it like any lease.
/// </summary>
[TestMethod]
public async Task NothingToDoTakesNoLease_TheLibraryConversionIsNotPreempted()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var usb = await bed.GeneralAsync(ct: ct);
var auto = await TurnOnAsync(bed, usb, ct);
Assert.IsTrue(bed.Gate.TryEnterBackground(out var conversion));
Assert.AreEqual(AutoExportStartOutcome.NothingToDo, (await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct)).Outcome);
Assert.IsFalse(conversion.IsPreempted);
Assert.IsTrue(bed.Gate.BackgroundRunning);
// A file the database has and the disk has not: the plan leaves it out, so it takes no lease either.
var gone = await bed.PostAsync(bed.Luca, "m01", 2);
File.Delete(bed.LibraryFile(bed.Luca, gone.Media[0]));
Assert.AreEqual(AutoExportStartOutcome.NothingToDo, (await bed.Service.TryStartAutomaticAsync(Selection(auto, round: false), ct)).Outcome);
Assert.AreEqual(AutoExportStartOutcome.NothingToDo, (await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct)).Outcome);
Assert.IsFalse(conversion.IsPreempted);
Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct));
await bed.PostAsync(bed.Luca, "n01", 1);
Assert.AreEqual(AutoExportStartOutcome.Started, (await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct)).Outcome);
Assert.IsTrue(conversion.IsPreempted);
await bed.Service.WaitAsync(ct);
conversion.Dispose();
}
/// <summary>
/// Under its lease the start reads the destinations again: one switched off, paused, with another «da quando», or
/// with an unfinished automatic run is left out.
/// </summary>
[TestMethod]
public async Task TryStartAutomaticDropsADestinationTurnedOffMeanwhile()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
await bed.PostAsync(bed.Luca, "d01", 1);
await bed.PostAsync(bed.Marta, "d02", 2);
var usb = await bed.GeneralAsync(ct: ct);
var own = await bed.OwnAsync(bed.Marta, "marta-nas", ct: ct);
var general = await TurnOnAsync(bed, usb, ct);
var marta = await TurnOnAsync(bed, own, ct);
var selection = new ExportSelection.Automatic([Scope(general), Scope(marta)], [], Round: true);
// Switched off after the worker read it (directly in the store: the service is not told).
await bed.Db.Exports.UpdateDestinationAsync(general with { Automatic = false }, ct);
var start = await bed.Service.TryStartAutomaticAsync(selection, ct);
await bed.Service.WaitAsync(ct);
CollectionAssert.AreEqual(new[] { own.Id }, start.Runs.Select(r => r.DestinationId).ToArray());
// Another «da quando», or a pause: left out too.
await bed.PostAsync(bed.Luca, "d03", 3);
await bed.PostAsync(bed.Marta, "d04", 4);
await bed.Db.Exports.UpdateDestinationAsync(general with { AutomaticSince = Make.T0.AddDays(-30) }, ct);
await bed.Db.Exports.SetDestinationPausedAsync(own.Id, bed.Clock.Now, "Non risponde.", ct);
Assert.AreEqual(AutoExportStartOutcome.NothingToDo, (await bed.Service.TryStartAutomaticAsync(selection, ct)).Outcome);
Assert.HasCount(1, await bed.Db.Exports.ListRunsAsync(ct));
// An unfinished automatic run of the destination: it is resumed, not planned again.
await bed.Db.Exports.ClearDestinationPauseAsync(own.Id, ct);
await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = own.Id, Origin = ExportRunOrigin.Automatic, State = ExportRunState.Interrupted, StartedAt = bed.Clock.Now }, ct);
Assert.AreEqual(AutoExportStartOutcome.NothingToDo, (await bed.Service.TryStartAutomaticAsync(selection, ct)).Outcome);
Assert.HasCount(2, await bed.Db.Exports.ListRunsAsync(ct));
}
/// <summary>
/// «Copia in…» while an automatic job copies is not refused: it displaces the automatic job (answer 49), whose run
/// becomes «interrotto» without an error and resumes by itself afterwards.
/// </summary>
[TestMethod]
public async Task AManualStartPreemptsTheAutomaticJob()
{
var ct = TestContext.CancellationToken;
var held = new HeldExportFileSystem(p => p.EndsWith("_2.jpg", StringComparison.Ordinal));
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
var post = await bed.PostAsync(bed.Luca, "p01", 1, 2, 3);
var other = await bed.PostAsync(bed.Marta, "p02", 4);
var usb = await bed.GeneralAsync(ct: ct);
var auto = await TurnOnAsync(bed, usb, ct);
await bed.Service.Destinations.SetAccountEnabledAsync(bed.Marta.Id, false, ct);
var start = await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct);
await held.Reached.Task.WaitAsync(Patience, ct);
Assert.IsTrue(bed.Service.AutomaticRunning);
Assert.IsTrue(bed.Gate.HeldByYielding);
Assert.IsNull(bed.Gate.BusyFirm);
await bed.Service.Destinations.SetAccountEnabledAsync(bed.Marta.Id, true, ct);
var manual = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Media([other.Media[0].Id])), ct);
var automaticRun = await bed.RunAsync(start.Runs.Single().Id, ct);
Assert.AreEqual((ExportRunState.Interrupted, null), (automaticRun.State, automaticRun.LastError), "displaced, not failed");
Assert.IsFalse(bed.Service.AutomaticRunning);
await bed.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(manual.Runs.Single().Id, ct)).State);
// The next pass resumes it where it was.
held.Release();
var resumed = await bed.Service.TryResumeAutomaticAsync([automaticRun.Id], ct);
Assert.AreEqual(AutoExportStartOutcome.Started, resumed.Outcome);
await bed.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(automaticRun.Id, ct)).State);
Assert.IsTrue(post.Media.All(m => File.Exists(bed.GeneralCopy(bed.Luca, m))));
}
/// <summary>Alberto's work that arrives while an automatic start plans: the runs recorded so far become «annullato».</summary>
[TestMethod]
public async Task AManualStartDuringAnAutomaticPlanCancelsThePartialRuns()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var post = await bed.PostAsync(bed.Luca, "q01", 1);
var usb = await bed.GeneralAsync(ct: ct);
var auto = await TurnOnAsync(bed, usb, ct);
var planning = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
bed.Service.AutomaticRunRecorded = async token =>
{
planning.TrySetResult();
await Task.Delay(Timeout.Infinite, token);
};
var automatic = bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct);
await planning.Task.WaitAsync(Patience, ct);
Assert.IsTrue(bed.Service.AutomaticRunning);
var partial = (await bed.Db.Exports.ListUnfinishedRunsAsync(ct)).Single();
bed.Service.AutomaticRunRecorded = null;
var manual = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Media([post.Media[0].Id])), ct);
Assert.AreEqual(AutoExportStartOutcome.Busy, (await automatic).Outcome);
Assert.AreEqual(ExportRunState.Cancelled, (await bed.RunAsync(partial.Id, ct)).State);
await bed.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunOrigin.Manual, (await bed.RunAsync(manual.Runs.Single().Id, ct)).Origin);
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(manual.Runs.Single().Id, ct)).State);
}
/// <summary>An import takes the gate from an automatic job; while it runs the automatic export only gets Busy.</summary>
[TestMethod]
public async Task AnImportPreemptsTheAutomaticJobThroughTheGate()
{
var ct = TestContext.CancellationToken;
var held = new HeldExportFileSystem(p => p.EndsWith("_1.jpg", StringComparison.Ordinal));
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
await bed.PostAsync(bed.Luca, "i01", 1, 2);
var usb = await bed.GeneralAsync(ct: ct);
var auto = await TurnOnAsync(bed, usb, ct);
var start = await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct);
await held.Reached.Task.WaitAsync(Patience, ct);
var entry = await bed.Gate.EnterAsync(LongWorkKind.Import, ct);
Assert.IsNotNull(entry.Lease);
await bed.Service.WaitAsync(ct);
var run = await bed.RunAsync(start.Runs.Single().Id, ct);
Assert.AreEqual((ExportRunState.Interrupted, null), (run.State, run.LastError));
var busy = await bed.Service.TryResumeAutomaticAsync([run.Id], ct);
Assert.AreEqual((AutoExportStartOutcome.Busy, LongWorkKind.Import), (busy.Outcome, busy.BusyWith));
entry.Lease.Dispose();
held.Release();
Assert.AreEqual(AutoExportStartOutcome.Started, (await bed.Service.TryResumeAutomaticAsync([run.Id], ct)).Outcome);
await bed.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State);
}
/// <summary>
/// Switching «Automatica» off stops its automatic job at once and cancels its automatic runs (answer 52): the files
/// copied stay, a run Alberto started is not touched.
/// </summary>
[TestMethod]
public async Task ChangeDestinationStopsAndCancelsItsAutomaticRuns_ManualRunsStay()
{
var ct = TestContext.CancellationToken;
var held = new HeldExportFileSystem(p => p.EndsWith("_2.jpg", StringComparison.Ordinal));
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
var post = await bed.PostAsync(bed.Luca, "c01", 1, 2, 3);
var manualPost = await bed.PostAsync(bed.Marta, "c02", 4, 5);
var usb = await bed.GeneralAsync(ct: ct);
// A run of Alberto's, interrupted on its second file.
var manual = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Media([.. manualPost.Media.Select(m => m.Id)])), ct);
await held.Reached.Task.WaitAsync(Patience, ct);
Assert.IsNull(await bed.Service.InterruptAsync(ct), "a manual job holds nothing");
var auto = await TurnOnAsync(bed, usb, ct);
var start = await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct);
Assert.AreEqual(AutoExportStartOutcome.Started, start.Outcome, "the manual run is on Marta's files, the automatic one on Luca's");
await WaitForCopyAsync(bed.GeneralCopy(bed.Luca, post.Media[0]), ct);
var spec = Spec(bed, auto) with { Automatic = false };
await bed.Service.ChangeDestinationAsync(usb.Id, token => bed.Service.Destinations.UpdateAsync(usb.Id, spec, token), ct);
Assert.IsFalse(bed.Service.IsBusy);
var automaticRun = await bed.RunAsync(start.Runs.Single().Id, ct);
Assert.AreEqual((ExportRunState.Cancelled, ExportText.AutomaticTurnedOff), (automaticRun.State, automaticRun.LastError));
Assert.AreEqual(ExportRunState.Interrupted, (await bed.RunAsync(manual.Runs.Single().Id, ct)).State);
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0])), "what was copied stays");
Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[2])));
Assert.IsEmpty(Fingerprint.Temporaries(bed.Usb));
held.Release();
}
/// <summary>A change that fails (here a type list left empty) leaves the stopped automatic run «interrotto», to be resumed.</summary>
[TestMethod]
public async Task AFailedUpdateLeavesAutomaticRunsInterruptedNotCancelled()
{
var ct = TestContext.CancellationToken;
var held = new HeldExportFileSystem(p => p.EndsWith("_1.jpg", StringComparison.Ordinal));
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
await bed.PostAsync(bed.Luca, "u01", 1, 2);
var usb = await bed.GeneralAsync(ct: ct);
var auto = await TurnOnAsync(bed, usb, ct);
var start = await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct);
await held.Reached.Task.WaitAsync(Patience, ct);
var bad = Spec(bed, auto) with { ContentTypes = ContentTypes.None };
await Assert.ThrowsExactlyAsync<ArgumentException>(() => bed.Service.ChangeDestinationAsync(usb.Id, token => bed.Service.Destinations.UpdateAsync(usb.Id, bad, token), ct));
var run = await bed.RunAsync(start.Runs.Single().Id, ct);
Assert.AreEqual((ExportRunState.Interrupted, null), (run.State, run.LastError));
Assert.IsTrue((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.Automatic);
held.Release();
Assert.AreEqual(AutoExportStartOutcome.Started, (await bed.Service.TryResumeAutomaticAsync([run.Id], ct)).Outcome);
await bed.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State);
}
/// <summary>
/// No automatic job starts between the stop and the update of a change (engineering A5); a change of folder and
/// «Togli la cartella» are not refused because of automatic runs, which become «annullato».
/// </summary>
[TestMethod]
public async Task NoAutomaticJobStartsDuringADestinationChange()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
await bed.PostAsync(bed.Luca, "x01", 1);
var usb = await bed.GeneralAsync(ct: ct);
var auto = await TurnOnAsync(bed, usb, ct);
var interrupted = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, Origin = ExportRunOrigin.Automatic, State = ExportRunState.Interrupted, StartedAt = bed.Clock.Now }, ct);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var inside = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var other = bed.Temp.Combine("nuovo-disco");
Directory.CreateDirectory(other);
var change = bed.Service.ChangeDestinationAsync(usb.Id, async token =>
{
inside.TrySetResult();
await release.Task.WaitAsync(token);
return await bed.Service.Destinations.UpdateAsync(usb.Id, Spec(bed, auto) with { Path = other }, token);
}, ct);
await inside.Task.WaitAsync(Patience, ct);
Assert.AreEqual(AutoExportStartOutcome.Busy, (await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct)).Outcome);
Assert.AreEqual(AutoExportStartOutcome.Busy, (await bed.Service.TryResumeAutomaticAsync([interrupted.Id], ct)).Outcome);
Assert.HasCount(1, await bed.Db.Exports.ListRunsAsync(ct));
release.SetResult();
var moved = (await change).Destination;
// The folder changed although an automatic run was unfinished there: that run is cancelled, the new folder is new.
Assert.AreEqual((ExportRunState.Cancelled, ExportText.RetiredDestination), ((await bed.RunAsync(interrupted.Id, ct)).State, (await bed.RunAsync(interrupted.Id, ct)).LastError));
Assert.IsTrue(moved.Automatic);
var started = await bed.Service.TryStartAutomaticAsync(new ExportSelection.Automatic([Scope(moved)], [], Round: true), ct);
Assert.AreEqual(AutoExportStartOutcome.Started, started.Outcome);
await bed.Service.WaitAsync(ct);
// «Togli la cartella» with an unfinished automatic run.
var again = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = moved.Id, Origin = ExportRunOrigin.Automatic, State = ExportRunState.Paused, StartedAt = bed.Clock.Now }, ct);
await bed.Service.ChangeDestinationAsync(moved.Id, async token =>
{
await bed.Service.Destinations.RetireAsync(moved.Id, token);
return true;
}, ct);
Assert.AreEqual(ExportRunState.Cancelled, (await bed.RunAsync(again.Id, ct)).State);
}
/// <summary>
/// The copier's safety net (D7.5): an automatic run whose destination is no longer automatic stops at its next group
/// (or at its start), «annullato»; the files done stay.
/// </summary>
[TestMethod]
public async Task AnAutomaticRunWhoseDestinationIsNoLongerAutomaticIsCancelledAtTheNextGroup()
{
var ct = TestContext.CancellationToken;
var held = new HeldExportFileSystem(p => p.EndsWith("_2.jpg", StringComparison.Ordinal));
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held, GroupFiles = 1 });
var post = await bed.PostAsync(bed.Luca, "g01", 1, 2, 3);
var usb = await bed.GeneralAsync(ct: ct);
var auto = await TurnOnAsync(bed, usb, ct);
var start = await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct);
await held.Reached.Task.WaitAsync(Patience, ct);
// Switched off without telling the service (the store directly): the copy in progress finishes, the next does not start.
await bed.Db.Exports.UpdateDestinationAsync(auto with { Automatic = false, AutomaticSince = null }, ct);
held.Release();
await bed.Service.WaitAsync(ct);
var run = await bed.RunAsync(start.Runs.Single().Id, ct);
Assert.AreEqual((ExportRunState.Cancelled, ExportText.AutomaticTurnedOff), (run.State, run.LastError));
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0])));
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[1])), "the file being written finishes");
Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[2])));
Assert.AreEqual(1, (await bed.ItemsAsync(run.Id, ct)).Count(i => i.State == ExportItemState.Pending));
// At the start of a run: «Riprendi» of an automatic run whose folder is off cancels it.
var later = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, Origin = ExportRunOrigin.Automatic, State = ExportRunState.Interrupted, StartedAt = bed.Clock.Now }, ct);
await bed.Service.ResumeAsync([later.Id], ct);
await bed.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Cancelled, (await bed.RunAsync(later.Id, ct)).State);
}
/// <summary>An account removed: its own folder is no longer automatic, and its automatic runs are cancelled by the round.</summary>
[TestMethod]
public async Task CancelOrphanAutomaticRunsAfterAccountRemoval()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var own = await bed.OwnAsync(bed.Marta, "marta-nas", ct: ct);
var general = await bed.GeneralAsync(ct: ct);
await TurnOnAsync(bed, own, ct);
await TurnOnAsync(bed, general, ct);
var orphan = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = own.Id, Origin = ExportRunOrigin.Automatic, State = ExportRunState.Paused, StartedAt = bed.Clock.Now }, ct);
var kept = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = general.Id, Origin = ExportRunOrigin.Automatic, State = ExportRunState.Interrupted, StartedAt = bed.Clock.Now }, ct);
var manual = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = own.Id, State = ExportRunState.Interrupted, StartedAt = bed.Clock.Now }, ct);
await bed.Db.Accounts.DeleteAsync(bed.Marta.Id, ct);
Assert.AreEqual(1, await bed.Service.CancelOrphanAutomaticRunsAsync(ct));
var cancelled = await bed.RunAsync(orphan.Id, ct);
Assert.AreEqual((ExportRunState.Cancelled, ExportText.AutomaticTurnedOff), (cancelled.State, cancelled.LastError));
Assert.AreEqual(ExportRunState.Interrupted, (await bed.RunAsync(kept.Id, ct)).State);
Assert.AreEqual(ExportRunState.Interrupted, (await bed.RunAsync(manual.Id, ct)).State, "a run of Alberto's stays his");
Assert.AreEqual(0, await bed.Service.CancelOrphanAutomaticRunsAsync(ct));
}
/// <summary>
/// The progress tells the kind and origin of the run being worked on: an automatic run resumed by hand stays
/// «automatica» (but runs as Alberto's job), a manual run is «manuale», «Controlla le copie» has none.
/// </summary>
[TestMethod]
public async Task ProgressKindAndOriginComeFromTheRun()
{
var ct = TestContext.CancellationToken;
var held = new HeldExportFileSystem(p => p.EndsWith("_1.jpg", StringComparison.Ordinal));
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
var post = await bed.PostAsync(bed.Luca, "k01", 1);
var usb = await bed.GeneralAsync(ct: ct);
var auto = await TurnOnAsync(bed, usb, ct);
var start = await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct);
await held.Reached.Task.WaitAsync(Patience, ct);
var now = await WaitUntilAsync(() => bed.Service.GetProgressAsync(ct), p => p.Origin is not null, ct);
Assert.AreEqual((ExportRunKind.Copy, ExportRunOrigin.Automatic), (now.Kind!.Value, now.Origin!.Value));
Assert.IsTrue(await bed.Service.InterruptAutomaticAsync(ct));
Assert.IsNull(bed.Service.AutomaticHeldUntil, "stopped without «Interrompi»: nothing held");
await bed.Service.ResumeAsync([start.Runs[0].Id], ct);
Assert.IsFalse(bed.Service.AutomaticRunning, "resumed by hand: Alberto's job");
now = await WaitUntilAsync(() => bed.Service.GetProgressAsync(ct), p => p.Origin is not null, ct);
Assert.AreEqual(ExportRunOrigin.Automatic, now.Origin);
held.Release();
await bed.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunOrigin.Automatic, (await bed.Service.GetProgressAsync(ct)).Origin, "the snapshot of the newest run");
var second = await bed.PostAsync(bed.Luca, "k02", 2);
await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Media([second.Media[0].Id])), ct);
await bed.Service.WaitAsync(ct);
var manual = await bed.Service.GetProgressAsync(ct);
Assert.AreEqual((ExportRunKind.Copy, ExportRunOrigin.Manual), (manual.Kind!.Value, manual.Origin!.Value));
var check = new List<ExportProgress>();
bed.Service.ProgressChanged += (_, p) => { lock (check) { check.Add(p); } };
await bed.Service.CheckCopiesAsync(usb.Id, ct);
await bed.Service.WaitAsync(ct);
lock (check)
{
Assert.IsTrue(check.Count > 0 && check.All(p => p.Kind is null && p.Origin is null && p.RunId is null));
}
}
/// <summary>
/// «Interrompi» of an automatic copy holds the automatic copies at least an hour (answer 53); «Riprendi ora»
/// releases them; «Interrompi» of a job of Alberto's holds nothing.
/// </summary>
[TestMethod]
public async Task InterruptOfAnAutomaticJobHoldsTheAutomaticCopies_ResumeNowReleases()
{
var ct = TestContext.CancellationToken;
var held = new HeldExportFileSystem(p => p.EndsWith("_1.jpg", StringComparison.Ordinal));
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
await bed.PostAsync(bed.Luca, "h01", 1);
var usb = await bed.GeneralAsync(ct: ct);
var auto = await TurnOnAsync(bed, usb, ct);
var start = await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct);
await held.Reached.Task.WaitAsync(Patience, ct);
var until = await bed.Service.InterruptAsync(ct);
Assert.AreEqual(bed.Clock.Now.AddHours(1), until);
Assert.AreEqual(until, bed.Service.AutomaticHeldUntil);
Assert.AreEqual(ExportRunState.Interrupted, (await bed.RunAsync(start.Runs[0].Id, ct)).State);
Assert.AreEqual(AutoExportStartOutcome.Held, (await bed.Service.TryResumeAutomaticAsync([start.Runs[0].Id], ct)).Outcome);
Assert.AreEqual(
$"Copia automatica interrotta: quello che è stato copiato resta; riprende da sola {Core.Engine.ItalianText.AtDay(until!.Value, bed.Clock.Now, bed.Clock.LocalZone)}.",
ExportText.AutomaticInterrupted(until.Value, bed.Clock.Now, bed.Clock.LocalZone));
// A longer hold wins; the hour passes; «Riprendi ora».
Assert.AreEqual(until.Value.AddHours(1), bed.Service.HoldAutomatic(until.Value.AddHours(1)));
Assert.AreEqual(until.Value.AddHours(1), bed.Service.HoldAutomatic(until.Value));
bed.Clock.Now = until.Value.AddHours(1);
Assert.IsNull(bed.Service.AutomaticHeldUntil);
bed.Service.HoldAutomatic(bed.Clock.Now.AddHours(1));
bed.Service.ReleaseAutomaticHold();
Assert.IsNull(bed.Service.AutomaticHeldUntil);
held.Release();
Assert.AreEqual(AutoExportStartOutcome.Started, (await bed.Service.TryResumeAutomaticAsync([start.Runs[0].Id], ct)).Outcome);
await bed.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(start.Runs[0].Id, ct)).State);
}
/// <summary>
/// «Esporta questo account» turned off stops the automatic job at once (its run «interrotto», no error), and the run
/// resumed with the switch read again skips the account's files: none of them is written after the switch.
/// </summary>
[TestMethod]
public async Task TurningAnAccountOffStopsTheAutomaticJobAndItsFilesAreSkipped()
{
var ct = TestContext.CancellationToken;
var held = new HeldExportFileSystem(p => p.EndsWith("_1.jpg", StringComparison.Ordinal) && p.Contains("l01", StringComparison.Ordinal));
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
var first = await bed.PostAsync(bed.Luca, "l01", 1);
var second = await bed.PostAsync(bed.Luca, "l02", 2);
var auto = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), ct);
var run = (await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct)).Runs.Single();
await held.Reached.Task.WaitAsync(Patience, ct);
await bed.Service.SetAccountExportEnabledAsync(bed.Luca.Id, enabled: false, ct);
Assert.IsFalse(bed.Service.IsBusy, "the automatic job was stopped");
var stopped = await bed.RunAsync(run.Id, ct);
Assert.AreEqual((ExportRunState.Interrupted, (string?)null), (stopped.State, stopped.LastError));
held.Release();
Assert.AreEqual(AutoExportStartOutcome.Started, (await bed.Service.TryResumeAutomaticAsync([run.Id], ct)).Outcome);
await bed.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State);
Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, first.Media[0])));
Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, second.Media[0])));
Assert.IsEmpty(await bed.Db.Exports.ListCopiesAsync(auto.Id, ct: ct));
}
/// <summary>
/// With «Una copia sola» the backlog is each folder's own figure: the same content of two accounts, due in two
/// automatic folders, counts once in each; the job writes it once (the other is «Già copiato»), and then both
/// figures are 0 (pinned behaviour, IExportStore.CountAutomaticBacklogAsync).
/// </summary>
[TestMethod]
public async Task WithOneCopyOnlyEachFolderCountsItsOwnBacklog()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct);
await bed.PostAsync(bed.Marta, "c01", 31);
await bed.PostAsync(bed.Luca, "c02", 31);
var general = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), ct);
var own = await TurnOnAsync(bed, await bed.OwnAsync(bed.Luca, "luca-nas", ct: ct), ct);
var generalQuery = new ExportBacklogQuery(ExportScope.General, null, ContentTypes.All, general.Id, null);
var ownQuery = new ExportBacklogQuery(ExportScope.Account, bed.Luca.Id, ContentTypes.All, own.Id, null);
Assert.AreEqual(1, (await bed.Db.Exports.CountAutomaticBacklogAsync(generalQuery, ct)).Files);
Assert.AreEqual(1, (await bed.Db.Exports.CountAutomaticBacklogAsync(ownQuery, ct)).Files);
var start = await bed.Service.TryStartAutomaticAsync(new ExportSelection.Automatic([Scope(general), Scope(own)], [], Round: true), ct);
Assert.AreEqual(AutoExportStartOutcome.Started, start.Outcome);
await bed.Service.WaitAsync(ct);
var copies = (await bed.Db.Exports.ListCopiesAsync(general.Id, ct: ct)).Concat(await bed.Db.Exports.ListCopiesAsync(own.Id, ct: ct)).ToList();
Assert.HasCount(1, copies, "written once");
Assert.AreEqual(0, (await bed.Db.Exports.CountAutomaticBacklogAsync(generalQuery, ct)).Files);
Assert.AreEqual(0, (await bed.Db.Exports.CountAutomaticBacklogAsync(ownQuery, ct)).Files);
}
/// <summary>
/// «Annulla» of an automatic run keeps automatic starts away until the run is «annullato»: the worker's resume of the
/// same run in that moment is refused (Busy), so the run stays «annullato» and nothing is copied.
/// </summary>
[TestMethod]
public async Task DiscardOfAnAutomaticRunCannotRaceItsResume()
{
var ct = TestContext.CancellationToken;
var held = new HeldExportFileSystem(p => p.EndsWith("_1.jpg", StringComparison.Ordinal));
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
var post = await bed.PostAsync(bed.Luca, "d01", 1);
var auto = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), ct);
var run = (await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct)).Runs.Single();
await held.Reached.Task.WaitAsync(Patience, ct);
Assert.IsTrue(await bed.Service.InterruptAutomaticAsync(ct));
await bed.Service.WaitAsync(ct);
held.Release();
Assert.AreEqual(ExportRunState.Interrupted, (await bed.RunAsync(run.Id, ct)).State);
var reached = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var go = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
bed.Service.DiscardChecked = async token =>
{
reached.TrySetResult();
await go.Task.WaitAsync(token);
};
var discard = bed.Service.DiscardAsync(run.Id, ct);
await reached.Task.WaitAsync(Patience, ct);
Assert.AreEqual(AutoExportStartOutcome.Busy, (await bed.Service.TryResumeAutomaticAsync([run.Id], ct)).Outcome);
go.SetResult();
await discard;
await bed.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Cancelled, (await bed.RunAsync(run.Id, ct)).State);
Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0])));
bed.Service.DiscardChecked = null;
Assert.AreEqual(AutoExportStartOutcome.NothingToDo, (await bed.Service.TryResumeAutomaticAsync([run.Id], ct)).Outcome, "after «Annulla» the gate is open again");
}
/// <summary>
/// The answer to «Interrompi» says the time as the rest of the interface: «all'1:20», and «domani alle 0:30» when the
/// hold goes past midnight (decisioni.md, 4 December 2026).
/// </summary>
[TestMethod]
public void TheInterruptAnswerSaysTheTimeAsElsewhere()
{
var zone = TestZones.Rome;
var night = new DateTimeOffset(2026, 12, 4, 0, 20, 0, TimeSpan.FromHours(1));
Assert.AreEqual(
"Copia automatica interrotta: quello che è stato copiato resta; riprende da sola all'1:20.",
ExportText.AutomaticInterrupted(night.AddHours(1), night, zone));
var evening = new DateTimeOffset(2026, 12, 4, 23, 30, 0, TimeSpan.FromHours(1));
Assert.AreEqual(
"Copia automatica interrotta: quello che è stato copiato resta; riprende da sola domani alle 0:30.",
ExportText.AutomaticInterrupted(evening.AddHours(1), evening, zone));
var afternoon = new DateTimeOffset(2026, 12, 4, 15, 10, 0, TimeSpan.FromHours(1));
Assert.AreEqual(
"Copia automatica interrotta: quello che è stato copiato resta; riprende da sola alle 16:10.",
ExportText.AutomaticInterrupted(afternoon.AddHours(1), afternoon, zone));
}
/// <summary>
/// The automatic export resumes only automatic runs: a manual «In pausa» stays Alberto's even when its folder
/// answers again (answer 48); «Riprova» resumes it.
/// </summary>
[TestMethod]
public async Task AManualPausedRunIsNotResumedByTheAutomaticExport()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
await bed.PostAsync(bed.Luca, "w01", 1);
var usb = await bed.GeneralAsync(ct: ct);
await TurnOnAsync(bed, usb, ct);
Directory.Move(bed.Usb, bed.Usb + "-via");
var start = await bed.CopyAccountAsync(bed.Luca, ct: ct);
var run = start.Runs.Single();
Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(run.Id, ct)).State);
Directory.Move(bed.Usb + "-via", bed.Usb);
Assert.IsNull(await bed.Service.ProbeDestinationAsync(usb.Id, ct));
Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
Assert.AreEqual(AutoExportStartOutcome.NothingToDo, (await bed.Service.TryResumeAutomaticAsync([run.Id], ct)).Outcome);
Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(run.Id, ct)).State);
var retry = await bed.Service.RetryDestinationAsync(usb.Id, ct);
await bed.Service.WaitAsync(ct);
Assert.AreEqual(run.Id, retry.Resumed.Single().Id);
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State);
}
/// <summary>
/// A destination paused because its disk is full stays paused at each probe until the next file of its paused job
/// fits with the margin (D11): one pause event, no resume meanwhile; unmeasurable space clears as before.
/// </summary>
[TestMethod]
public async Task ProbeKeepsASpacePauseUntilTheNextFileFits()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var post = await bed.PostAsync(bed.Luca, "s01", 1);
var usb = await bed.GeneralAsync(ct: ct);
var auto = await TurnOnAsync(bed, usb, ct);
bed.Disk.Free = ExportSpace.Margin / 2;
var start = await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct);
await bed.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(start.Runs[0].Id, ct)).State);
Assert.IsNotNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
var bytes = post.Media[0].Bytes!.Value;
bed.Disk.Free = ExportSpace.Margin + bytes - 1;
var problem = await bed.Service.ProbeDestinationAsync(usb.Id, ct);
Assert.IsNotNull(problem);
StringAssert.StartsWith(problem, "Su Disco USB restano");
StringAssert.Contains(problem, "per il prossimo file");
var stored = (await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!;
Assert.AreEqual(problem, stored.LastError);
Assert.IsNotNull(stored.PausedAt);
Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(start.Runs[0].Id, ct)).State);
Assert.AreEqual(1, (await bed.Db.Events.ListAsync(new() { Limit = 100 }, ct)).Count(e => e.Code == ExportPause.PausedEventCode));
bed.Disk.Free = ExportSpace.Margin + bytes;
Assert.IsNull(await bed.Service.ProbeDestinationAsync(usb.Id, ct));
Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
// Unmeasurable space: cleared, as before E5.
await bed.Db.Exports.SetDestinationPausedAsync(usb.Id, bed.Clock.Now, "Pieno.", ct);
bed.Disk.Free = null;
Assert.IsNull(await bed.Service.ProbeDestinationAsync(usb.Id, ct));
Assert.AreEqual(1, (await bed.Db.Events.ListAsync(new() { Limit = 100 }, ct)).Count(e => e.Code == ExportPause.PausedEventCode));
}
/// <summary>
/// D11 with a converted file: the probe measures the file the copy writes, which the copier measured when it paused,
/// not the library file. A PNG that becomes a smaller JPG resumes as soon as the JPG fits.
/// </summary>
[TestMethod]
public async Task ProbeMeasuresTheConvertedFileTheJobWrites()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
using var picture = TestImages.Scene(7, 320, 240);
var post = await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "c01", Make.T0.AddDays(-1)), [new TestFile(Make.Photo(1), TestImages.Png(picture), ".png")]);
var usb = await bed.GeneralAsync(ct: ct);
await bed.Service.Destinations.UpdateAsync(usb.Id, Spec(bed, usb) with { PhotoFormat = ExportFormat.Jpg }, ct);
bed.Disk.Free = ExportSpace.Margin / 2;
var run = (await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([post.Media[0].Id])), ct)).Runs.Single();
Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(run.Id, ct)).State);
var item = (await bed.ItemsAsync(run.Id, ct)).Single();
var jpg = bed.Service.Copier.SpaceNeeded(run.Id, item.Id);
Assert.IsNotNull(jpg);
Assert.IsLessThan(post.Media[0].Bytes!.Value, jpg.Value, "the JPG is smaller than its PNG");
bed.Disk.Free = ExportSpace.Margin + jpg.Value - 1;
StringAssert.Contains((await bed.Service.RetryDestinationAsync(usb.Id, ct)).Problem, "per il prossimo file");
bed.Disk.Free = ExportSpace.Margin + jpg.Value;
var retry = await bed.Service.RetryDestinationAsync(usb.Id, ct);
await bed.Service.WaitAsync(ct);
Assert.IsNull(retry.Problem);
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State);
Assert.AreEqual(1, (await bed.Db.Events.ListAsync(new() { Limit = 100 }, ct)).Count(e => e.Code == ExportPause.PausedEventCode));
}
/// <summary>
/// D11 with a frames job: the room asked is the frame's, never the whole video's; after a restart (the measure is in
/// memory) the frame's size is not known and only the margin counts, without a size in the reason.
/// </summary>
[TestMethod]
public async Task ProbeOfAFramesJobMeasuresTheFrameNotTheVideo()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var video = (await bed.Library.SaveAsync(
bed.Marta,
Make.Entry(bed.Marta.Id, "f01", Make.T0.AddDays(-2)),
[new TestFile(Make.Video(1) with { Duration = null }, TestVideos.Mp4(ElementaryStream.Load("BA1_Sony_D")), ".mp4")])).Media[0];
var usb = await bed.GeneralAsync(ct: ct);
bed.Disk.Free = ExportSpace.Margin / 2;
var request = new ExportJobRequest(new ExportSelection.Media([video.Id]), Frames: new ExportFramesRequest(FrameMode.At, TimeSpan.Zero, null, null, ExportFormat.Jpg));
var run = (await bed.CopyAsync(request, ct)).Runs.Single();
Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(run.Id, ct)).State);
var frame = bed.Service.Copier.SpaceNeeded(run.Id, (await bed.ItemsAsync(run.Id, ct)).Single().Id);
Assert.IsNotNull(frame);
bed.Disk.Free = ExportSpace.Margin + frame.Value - 1;
Assert.IsNotNull(await bed.Service.ProbeDestinationAsync(usb.Id, ct));
// After a restart: the video's size does not count (it would ask for more than a frame needs).
await using var restarted = new ExportService(bed.Environment);
bed.Disk.Free = ExportSpace.Margin - 1;
var problem = await restarted.ProbeDestinationAsync(usb.Id, ct);
StringAssert.Contains(problem, "per il prossimo file serve più spazio");
bed.Disk.Free = ExportSpace.Margin;
Assert.IsNull(await restarted.ProbeDestinationAsync(usb.Id, ct));
Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(run.Id, ct)).State, "the probe resumes nothing");
}
/// <summary>The end of Febe stops the job and waits until its states are saved.</summary>
[TestMethod]
public async Task DisposeAwaitsARunningJob()
{
var ct = TestContext.CancellationToken;
var held = new HeldExportFileSystem(p => p.EndsWith("_1.jpg", StringComparison.Ordinal));
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
await bed.PostAsync(bed.Luca, "z01", 1);
await bed.GeneralAsync(ct: ct);
var service = new ExportService(bed.Environment);
var start = await service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Luca.Id)), ct);
await held.Reached.Task.WaitAsync(Patience, ct);
await service.DisposeAsync();
Assert.IsFalse(service.IsBusy);
Assert.AreEqual(ExportRunState.Interrupted, (await bed.RunAsync(start.Runs[0].Id, ct)).State);
}
/// <summary>A copy stuck in a read that ignores cancellation (a dead share) does not keep Febe from closing (D7.10).</summary>
[TestMethod]
public async Task DisposeDoesNotWaitForeverForAStuckCopy()
{
var ct = TestContext.CancellationToken;
var stuck = new StuckExportFileSystem(p => p.EndsWith("_1.jpg", StringComparison.Ordinal));
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = stuck });
await bed.PostAsync(bed.Luca, "z02", 1);
await bed.GeneralAsync(ct: ct);
var service = new ExportService(bed.Environment) { StopWait = TimeSpan.FromMilliseconds(300) };
var start = await service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Luca.Id)), ct);
await stuck.Reached.Task.WaitAsync(Patience, ct);
var watch = Stopwatch.StartNew();
await service.DisposeAsync();
Assert.IsLessThan(TimeSpan.FromSeconds(10), watch.Elapsed);
Assert.IsTrue(service.IsBusy, "the job is still stuck");
Assert.AreEqual(ExportRunState.Running, (await bed.RunAsync(start.Runs[0].Id, ct)).State, "RecoverAsync makes it «interrotto» at the next start");
stuck.Release();
await service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Interrupted, (await bed.RunAsync(start.Runs[0].Id, ct)).State);
}
/// <summary>
/// An automatic run that copied, adopted and failed nothing leaves no event (answer 54); one that copied writes
/// «Copia automatica in … finita».
/// </summary>
[TestMethod]
public async Task AnAutomaticRunThatDidNothingWritesNoEvent()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var gone = await bed.PostAsync(bed.Luca, "e01", 1);
var usb = await bed.GeneralAsync(ct: ct);
var auto = await TurnOnAsync(bed, usb, ct);
Assert.AreEqual(AutoExportStartOutcome.Started, (await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct)).Outcome);
await bed.Service.WaitAsync(ct);
var completed = (await bed.Db.Events.ListAsync(new() { Limit = 100 }, ct)).Single(e => e.Code == "esportazione-completata");
Assert.AreEqual("Copia automatica in Disco USB finita: 1 file copiato.", completed.Message);
Assert.AreEqual(EventSeverity.Success, completed.Severity);
// A run whose only file left the library meanwhile: «non presente», nothing copied, no second event.
var empty = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, Origin = ExportRunOrigin.Automatic, State = ExportRunState.Interrupted, StartedAt = bed.Clock.Now }, ct);
await bed.Db.Exports.AddItemsAsync(
[new ExportItem { RunId = empty.Id, MediaId = gone.Media[0].Id, AccountId = bed.Luca.Id, SourceSha256 = gone.Media[0].Sha256, State = ExportItemState.Pending }],
ct);
File.Delete(bed.LibraryFile(bed.Luca, gone.Media[0]));
Assert.AreEqual(AutoExportStartOutcome.Started, (await bed.Service.TryResumeAutomaticAsync([empty.Id], ct)).Outcome);
await bed.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(empty.Id, ct)).State);
Assert.AreEqual(ExportItemState.Missing, (await bed.ItemsAsync(empty.Id, ct)).Single().State);
Assert.HasCount(1, (await bed.Db.Events.ListAsync(new() { Limit = 100 }, ct)).Where(e => e.Code == "esportazione-completata"));
}
/// <summary>The planner refuses an automatic selection outside the automatic export, and «Copia in…» cannot claim to be automatic.</summary>
[TestMethod]
public async Task TheAutomaticSelectionIsTheAutomaticExportsAlone()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var usb = await bed.GeneralAsync(ct: ct);
var selection = new ExportSelection.Automatic([new(usb.Id, null)], [], Round: true);
Assert.ThrowsExactly<ArgumentException>(() => ExportPlanner.Validate(new ExportJobRequest(selection)));
Assert.ThrowsExactly<ArgumentException>(() => ExportPlanner.Validate(new ExportJobRequest(selection, CopyAgain: true, Origin: ExportRunOrigin.Automatic)));
Assert.ThrowsExactly<ArgumentException>(() => ExportPlanner.Validate(new ExportJobRequest(new ExportSelection.Account(bed.Luca.Id), Origin: ExportRunOrigin.Automatic)));
ExportPlanner.Validate(new ExportJobRequest(selection, Origin: ExportRunOrigin.Automatic));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => bed.Service.StartAsync(new ExportJobRequest(selection, Origin: ExportRunOrigin.Automatic), ct));
Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct));
}
// Helpers -------------------------------------------------------------------------------------------------------
/// <summary>«Automatica» on with «Copia anche quelli già in libreria» (no «da quando»), through the destinations.</summary>
private static async Task<ExportDestination> TurnOnAsync(ExportTestBed bed, ExportDestination destination, CancellationToken ct)
{
var spec = Spec(bed, destination) with { Automatic = true, OnlyNew = false };
return (await bed.Service.Destinations.UpdateAsync(destination.Id, spec, ct)).Destination;
}
private static DestinationSpec Spec(ExportTestBed bed, ExportDestination d) =>
new(d.Scope, d.AccountId, d.RootPath, d.Label, d.ContentTypes, d.NamingScheme, d.HighlightNamingScheme, d.ProfileNamingScheme, d.Automatic, d.AutomaticSince is not null, d.PhotoFormat, d.VideoFormat);
private static ExportSelection.AutomaticScope Scope(ExportDestination d) => new(d.Id, d.AutomaticSince);
private static ExportSelection.Automatic Selection(ExportDestination d, bool round) => new([Scope(d)], [], round);
private static async Task AssertBusyAsync(ExportTestBed bed, ExportSelection.Automatic selection, LongWorkKind? with, CancellationToken ct)
{
var start = await bed.Service.TryStartAutomaticAsync(selection, ct);
Assert.AreEqual((AutoExportStartOutcome.Busy, with), (start.Outcome, start.BusyWith));
Assert.IsEmpty(start.Runs);
var resume = await bed.Service.TryResumeAutomaticAsync([1, 2, 3], ct);
Assert.AreEqual(AutoExportStartOutcome.Busy, resume.Outcome);
}
/// <summary>The planner's «da scrivere» of «Copia in…» of the whole library, per destination: (account, SHA-256).</summary>
private static async Task<Dictionary<long, HashSet<(long, string)>>> PlannedWritesAsync(ExportTestBed bed, CancellationToken ct)
{
var effective = await bed.Service.Destinations.ResolveAllAsync(ct);
var settings = await ExportSettings.LoadAsync(bed.Db.Settings, ct);
var writes = new Dictionary<long, HashSet<(long, string)>>();
var request = new ExportJobRequest(new ExportSelection.Filter(new LibraryFilter(), MosaicMode.Grouped));
await foreach (var file in bed.Service.Planner.EnumerateAsync(request, effective, settings, ct))
{
if (file.Action == PlannedCopy.Write)
{
if (!writes.TryGetValue(file.DestinationId!.Value, out var set))
{
writes[file.DestinationId.Value] = set = [];
}
set.Add((file.Candidate.AccountId, file.Candidate.Sha256!));
}
}
return writes;
}
private static async Task WaitForCopyAsync(string path, CancellationToken ct)
{
var watch = Stopwatch.StartNew();
while (!File.Exists(path))
{
if (watch.Elapsed > Patience)
{
Assert.Fail($"{Path.GetFileName(path)} non copiato");
}
await Task.Delay(10, ct);
}
}
private static async Task<T> WaitUntilAsync<T>(Func<Task<T>> read, Func<T, bool> done, CancellationToken ct)
{
var watch = Stopwatch.StartNew();
while (true)
{
var value = await read();
if (done(value))
{
return value;
}
if (watch.Elapsed > Patience)
{
Assert.Fail($"non è arrivato: {value}");
}
await Task.Delay(10, ct);
}
}
/// <summary>The real file system, but reading a chosen file never ends, whatever the token says, until <see cref="Release"/>.</summary>
private sealed class StuckExportFileSystem(Func<string, bool> sticks) : IExportFileSystem
{
private readonly IExportFileSystem _inner = ExportFileSystem.Instance;
private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TaskCompletionSource Reached { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public void Release() => _release.TrySetResult();
public Stream OpenRead(string path)
{
var stream = _inner.OpenRead(path);
if (!sticks(path))
{
return stream;
}
Reached.TrySetResult();
return new StuckStream(stream, _release.Task);
}
public Task<string> ComputeSha256Async(string path, CancellationToken ct) => _inner.ComputeSha256Async(path, ct);
public bool FileExists(string path) => _inner.FileExists(path);
public long? FileLength(string path) => _inner.FileLength(path);
private sealed class StuckStream(Stream inner, Task release) : ReadOnlyStream(inner)
{
private readonly Stream _inner = inner;
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
await release; // ignores the token, as a read on a share that went away
cancellationToken.ThrowIfCancellationRequested();
return await _inner.ReadAsync(buffer, cancellationToken);
}
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
}
}
}