using System.Diagnostics;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Storage;
using Febe.Tests.Export.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Export;
///
/// 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.
///
[TestClass]
public sealed class ExportServiceAutomaticTests
{
private static readonly TimeSpan Patience = TimeSpan.FromSeconds(30);
public TestContext TestContext { get; set; } = null!;
/// An automatic job records only the files it writes: no «già copiato», no «Tolto», one run per destination.
[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");
}
///
/// 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).
///
[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);
}
///
/// «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.
///
[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);
}
/// A «Non riuscito» waits for the recovery round, and every round retries it whatever the error (answer 50).
[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])));
}
/// A busy Febe gives Busy, never an exception, and records nothing; Held while «Interrompi» holds.
[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(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);
}
///
/// 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.
///
[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);
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();
}
///
/// 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.
///
[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));
}
///
/// «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.
///
[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))));
}
/// Alberto's work that arrives while an automatic start plans: the runs recorded so far become «annullato».
[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);
}
/// An import takes the gate from an automatic job; while it runs the automatic export only gets Busy.
[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);
}
///
/// 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.
///
[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();
}
/// A change that fails (here a type list left empty) leaves the stopped automatic run «interrotto», to be resumed.
[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(() => 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);
}
///
/// 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».
///
[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);
}
///
/// 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.
///
[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);
}
/// An account removed: its own folder is no longer automatic, and its automatic runs are cancelled by the round.
[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));
}
///
/// 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.
///
[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();
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));
}
}
///
/// «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.
///
[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 alle {Core.Engine.ItalianText.Clock(until!.Value, bed.Clock.LocalZone)}.",
ExportText.AutomaticInterrupted(until.Value, 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);
}
///
/// 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.
///
[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);
}
///
/// 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.
///
[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));
}
/// The end of Febe stops the job and waits until its states are saved.
[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);
}
/// A copy stuck in a read that ignores cancellation (a dead share) does not keep Febe from closing (D7.10).
[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);
}
///
/// An automatic run that copied, adopted and failed nothing leaves no event (answer 54); one that copied writes
/// «Copia automatica in … finita».
///
[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"));
}
/// The planner refuses an automatic selection outside the automatic export, and «Copia in…» cannot claim to be automatic.
[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(() => ExportPlanner.Validate(new ExportJobRequest(selection)));
Assert.ThrowsExactly(() => ExportPlanner.Validate(new ExportJobRequest(selection, CopyAgain: true, Origin: ExportRunOrigin.Automatic)));
Assert.ThrowsExactly(() => ExportPlanner.Validate(new ExportJobRequest(new ExportSelection.Account(bed.Luca.Id), Origin: ExportRunOrigin.Automatic)));
ExportPlanner.Validate(new ExportJobRequest(selection, Origin: ExportRunOrigin.Automatic));
await Assert.ThrowsExactlyAsync(() => bed.Service.StartAsync(new ExportJobRequest(selection, Origin: ExportRunOrigin.Automatic), ct));
Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct));
}
// Helpers -------------------------------------------------------------------------------------------------------
/// «Automatica» on with «Copia anche quelli già in libreria» (no «da quando»), through the destinations.
private static async Task 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);
}
/// The planner's «da scrivere» of «Copia in…» of the whole library, per destination: (account, SHA-256).
private static async Task>> 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>();
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 WaitUntilAsync(Func> read, Func 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);
}
}
/// The real file system, but reading a chosen file never ends, whatever the token says, until .
private sealed class StuckExportFileSystem(Func 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 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 ReadAsync(Memory 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();
}
}
}