using System.Diagnostics; using System.Security.Cryptography; using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Core.Export; using Febe.Core.Library; using Febe.Tests.Export.Support; using Febe.Tests.Support; namespace Febe.Tests.Export; /// /// The automatic export's worker (tappa E5, WP5, design §4.4), with the acceptance tests of §15: «Tolto» and «Superato» /// are never copied again by themselves; an unreachable destination is paused and a later round resumes it; nothing is /// copied during an engine session. Passes are driven one by one () or /// through the loop with a . Only the library and folders of the temporary bed are touched; /// nothing contacts Instagram. /// [TestClass] public sealed class AutoExportWorkerTests { private static readonly TimeSpan Patience = TimeSpan.FromSeconds(30); public TestContext TestContext { get; set; } = null!; /// /// §15: a «Tolto» (A, found missing by «Controlla le copie»), a «Superato» (B, replaced the real way, its new file /// signalled by its journal line) and a copy deleted without «Controlla le copie» (C) are never written again by /// rounds or signal passes; «Copia di nuovo» by hand still writes A. /// [TestMethod] public async Task RemovedAndSupersededAreNeverCopiedAgainByTheAutomaticExport() { var ct = TestContext.CancellationToken; await using var bed = await ExportTestBed.CreateAsync(); var a = await bed.PostAsync(bed.Luca, "a01", 1); var b = await bed.PostAsync(bed.Luca, "b01", 2); var c = await bed.PostAsync(bed.Luca, "c01", 3); var usb = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct); var worker = Worker(bed); Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: true, ct)); await bed.Service.WaitAsync(ct); foreach (var post in new[] { a, b, c }) { Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0]))); } await MakeRemovedAsync(bed, usb, a, ct); var signals = bed.Signal.Count; var newB = await ReplaceAsync(bed, bed.Luca, b, scene: 9, ct); Assert.IsGreaterThan(signals, bed.Signal.Count, "the new file's journal line signals the automatic export"); File.Delete(bed.GeneralCopy(bed.Luca, c.Media[0])); var copies = await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct); var runs = (await bed.Db.Exports.ListRunsAsync(ct)).Count; for (var i = 0; i < 3; i++) { bed.Clock.Now += TimeSpan.FromHours(1); Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round: true, ct)); Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round: false, ct)); } Assert.HasCount(copies.Count, await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct), "no new copy row"); Assert.HasCount(runs, await bed.Db.Exports.ListRunsAsync(ct), "no new run"); Assert.IsEmpty((await bed.Db.Exports.ListCopiesBySha256Async(newB, ct)).Where(c => c.SourceSha256 == newB), "the replacement of a «Superato» is not copied"); Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, a.Media[0]))); Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, c.Media[0]))); // Control: «Copia di nuovo» by hand writes A. await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([a.Media[0].Id]), CopyAgain: true), ct); Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, a.Media[0]))); } /// The same through the loop: the start-up round copies, then hours of rounds and a signal write nothing. [TestMethod] public async Task RemovedAndSupersededStayAsTheyAreThroughTheLoop() { var ct = TestContext.CancellationToken; GatedClock? clock = null; await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new GatedClock((ManualClock)env.Clock) }); var a = await bed.PostAsync(bed.Luca, "a01", 1); var b = await bed.PostAsync(bed.Luca, "b01", 2); var usb = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct); var worker = Worker(bed, clock); var loop = worker.RunAsync(ct); await WaitUntilAsync(() => Task.FromResult(File.Exists(bed.GeneralCopy(bed.Luca, b.Media[0]))), ct); await IdleAsync(bed, worker, clock!, ct); await MakeRemovedAsync(bed, usb, a, ct); await ReplaceAsync(bed, bed.Luca, b, scene: 9, ct); var copies = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Count; var runs = (await bed.Db.Exports.ListRunsAsync(ct)).Count; await IdleAsync(bed, worker, clock!, ct); var passes = worker.Passes; clock!.Advance(TimeSpan.FromMinutes(2)); // the settle of the signal await WaitUntilAsync(() => Task.FromResult(worker.Passes > passes), ct); await IdleAsync(bed, worker, clock, ct); for (var i = 0; i < 2; i++) { passes = worker.Passes; clock.Advance(TimeSpan.FromHours(1)); await WaitUntilAsync(() => Task.FromResult(worker.Passes > passes), ct); await IdleAsync(bed, worker, clock, ct); } Assert.AreEqual(copies, (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Count); Assert.AreEqual(runs, (await bed.Db.Exports.ListRunsAsync(ct)).Count); Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, a.Media[0]))); await worker.StopAsync(); await loop; } /// /// «Solo i nuovi» from before the replacement: the new file of B is new and due, and only its old copy's /// «Superato» keeps it from being copied; a new post saved after the switch is copied. /// [TestMethod] public async Task SupersededReplacementIsNotCopiedEvenWhenItIsNew() { var ct = TestContext.CancellationToken; await using var bed = await ExportTestBed.CreateAsync(); var b = await bed.PostAsync(bed.Luca, "b01", 2); var usb = await bed.GeneralAsync(ct: ct); await bed.CopyAccountAsync(bed.Luca, ct: ct); bed.Clock.Now += TimeSpan.FromMinutes(1); usb = await TurnOnAsync(bed, usb, onlyNew: true, ct); Assert.IsNotNull(usb.AutomaticSince); bed.Clock.Now += TimeSpan.FromMinutes(1); var newB = await ReplaceAsync(bed, bed.Luca, b, scene: 9, ct); var fresh = await bed.PostAsync(bed.Luca, "n01", 5); var worker = Worker(bed); Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct)); await bed.Service.WaitAsync(ct); Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, fresh.Media[0])), "a new post is copied"); Assert.IsEmpty((await bed.Db.Exports.ListCopiesBySha256Async(newB, ct)).Where(c => c.SourceSha256 == newB), "the replacement of a «Superato» is never copied by itself"); Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round: true, ct)); } /// /// §15: an unreachable folder pauses the automatic run (one event, nothing created at the root); a round an hour /// later finds it still away (no new event, no new run); once it is back the next round clears the pause and resumes /// the same run, which completes with no .part left. /// [TestMethod] public async Task AnUnreachableDestinationPausesAndTheRoundResumesIt() { var ct = TestContext.CancellationToken; await using var bed = await ExportTestBed.CreateAsync(); var post = await bed.PostAsync(bed.Luca, "u01", 1, 2); var usb = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct); Directory.Move(bed.Usb, bed.Usb + "-staccata"); var worker = Worker(bed); Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct)); await bed.Service.WaitAsync(ct); var run = (await bed.Db.Exports.ListRunsAsync(ct)).Single(); Assert.AreEqual((ExportRunOrigin.Automatic, ExportRunState.Paused), (run.Origin, run.State)); Assert.IsNotNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt); Assert.AreEqual(1, await PauseEventsAsync(bed, ct)); Assert.IsFalse(Directory.Exists(bed.Usb), "the root is never created"); bed.Clock.Now += TimeSpan.FromHours(1); Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round: true, ct)); Assert.AreEqual(1, await PauseEventsAsync(bed, ct), "still away: no new event"); Assert.HasCount(1, await bed.Db.Exports.ListRunsAsync(ct), "no new run while paused"); Assert.IsFalse(Directory.Exists(bed.Usb)); Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round: false, ct), "a signal pass leaves a paused folder alone"); Directory.Move(bed.Usb + "-staccata", bed.Usb); bed.Clock.Now += TimeSpan.FromHours(1); Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: true, ct)); await bed.Service.WaitAsync(ct); Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt); Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State, "the same run resumed"); Assert.HasCount(1, await bed.Db.Exports.ListRunsAsync(ct)); Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[1]))); Assert.IsEmpty(Fingerprint.Temporaries(bed.Usb)); Assert.AreEqual(1, await PauseEventsAsync(bed, ct)); } /// The same through the loop: the start-up round pauses, an hour later still away, then back: resumed. [TestMethod] public async Task AnUnreachableDestinationIsResumedByALaterRoundOfTheLoop() { var ct = TestContext.CancellationToken; GatedClock? clock = null; await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new GatedClock((ManualClock)env.Clock) }); var post = await bed.PostAsync(bed.Luca, "u01", 1); var usb = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct); Directory.Move(bed.Usb, bed.Usb + "-staccata"); var worker = Worker(bed, clock); var loop = worker.RunAsync(ct); await WaitUntilAsync(async () => (await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt is not null, ct); await IdleAsync(bed, worker, clock!, ct); var passes = worker.Passes; clock!.Advance(TimeSpan.FromHours(1)); await WaitUntilAsync(() => Task.FromResult(worker.Passes > passes), ct); await IdleAsync(bed, worker, clock, ct); Assert.IsNotNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt); Assert.AreEqual(1, await PauseEventsAsync(bed, ct)); Directory.Move(bed.Usb + "-staccata", bed.Usb); clock.Advance(TimeSpan.FromHours(1)); await WaitUntilAsync(() => Task.FromResult(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0]))), ct); await IdleAsync(bed, worker, clock, ct); Assert.AreEqual(ExportRunState.Completed, (await bed.Db.Exports.ListRunsAsync(ct)).Single().State); Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt); var status = await worker.StatusAsync(ct); Assert.AreEqual((true, true, clock.Now, clock.Now + TimeSpan.FromHours(1)), (status.Running, status.AnyAutomatic, status.LastRound, status.NextRound)); await worker.StopAsync(); await loop; } /// /// §15: (a) a signal during a session starts nothing and the status says why; (b) at its end a pass copies; /// (c) a job that meets a session waits between files, an import displaces it, and once both are over a pass resumes /// it. No library file is opened during a session. /// [TestMethod] public async Task NoCopyDuringAnEngineSession() { var ct = TestContext.CancellationToken; HeldExportFileSystem? held = null; SessionRecordingFileSystem? files = null; await using var bed = await ExportTestBed.CreateAsync(env => { var library = env.Layout().Root; held = new HeldExportFileSystem(p => p.EndsWith("_3.jpg", StringComparison.Ordinal)); files = new SessionRecordingFileSystem(env.Session, held, p => p.StartsWith(library, StringComparison.Ordinal)); return env with { FileSystem = files, Clock = new WaitingClock(env.Clock) }; }); var usb = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct); var worker = Worker(bed); // (a) A signal during a session. bed.Session.InSession = true; var first = await bed.PostAsync(bed.Luca, "s01", 1); Assert.AreEqual(AutoExportPass.Waiting, await worker.RunOnceAsync(round: false, ct)); Assert.AreEqual(AutoExportText.InSession, (await worker.StatusAsync(ct)).Waiting); Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct), "no run while the engine is in session"); // (b) The session ends: one pass copies. bed.Session.InSession = false; Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct)); await bed.Service.WaitAsync(ct); Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, first.Media[0]))); // (c) A job of six files; the session starts while the third is read. var post = await bed.PostAsync(bed.Luca, "s02", 2, 3, 4, 5, 6, 7); Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct)); await held!.Reached.Task.WaitAsync(Patience, ct); bed.Session.InSession = true; held.Release(); await WaitUntilAsync(async () => (await bed.Service.GetProgressAsync(ct)).Phase == ExportPhase.WaitingForSession, ct); var run = (await bed.Db.Exports.ListRunsAsync(ct)).OrderBy(r => r.Id).Last(); var import = await bed.Gate.EnterAsync(LongWorkKind.Import, ct); Assert.IsNotNull(import.Lease, "Alberto's import displaces the automatic copy waiting for the session"); await bed.Service.WaitAsync(ct); var displaced = await bed.RunAsync(run.Id, ct); Assert.AreEqual(ExportRunState.Interrupted, displaced.State); Assert.IsNull(displaced.LastError, "displaced, not failed: any pass resumes it"); Assert.AreEqual(AutoExportPass.Waiting, await worker.RunOnceAsync(round: false, ct)); import.Lease!.Dispose(); Assert.AreEqual(AutoExportPass.Waiting, await worker.RunOnceAsync(round: false, ct), "still in session"); bed.Session.InSession = false; Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct)); await bed.Service.WaitAsync(ct); Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State, "the same run resumed"); foreach (var media in post.Media) { Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, media)), media.RelativePath); } Assert.AreEqual(0, files!.Violations, "no library file opened during a session"); Assert.IsNull(bed.Gate.Busy); Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt); } /// /// An entry whose journal line is still to write is not copied; once the line is written (which signals) it is. /// [TestMethod] public async Task ANewFileIsCopiedOnlyAfterItsJournalLine() { var ct = TestContext.CancellationToken; await using var bed = await ExportTestBed.CreateAsync(); await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct); var worker = Worker(bed); var entry = Make.Entry(bed.Luca.Id, "j01", Make.T0.AddDays(-1)); var file = ExportTestBed.Photo(1, 4); var added = await bed.Db.Entries.AddAsync(entry, [file.Media], ct); var media = added.Stored.Media.Single(); await bed.Library.Ingest.SaveMediaAsync(bed.Luca, added.Stored.Entry, media, new MediaContent { Content = new MemoryStream(file.Bytes), Extension = file.Extension }, null, ct); var journal = AccountJournal.PathFor(bed.Library.Layout.AccountFolder(bed.Luca)); var signals = bed.Signal.Count; await using (new FileStream(journal, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)) { Assert.IsFalse(await bed.Library.Ingest.TryAppendJournalAsync(added.Stored.Entry.Id, ct)); } Assert.AreEqual(signals, bed.Signal.Count, "no line, no signal"); CollectionAssert.AreEqual(new[] { added.Stored.Entry.Id }, (await LibraryIngest.PendingJournalEntriesAsync(bed.Db.Settings, ct)).ToArray()); Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round: true, ct), "held until its line is written"); Assert.AreEqual(0, await bed.Library.Ingest.AppendPendingJournalAsync(ct)); Assert.IsGreaterThan(signals, bed.Signal.Count, "the delayed line signals when it is written"); Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct)); await bed.Service.WaitAsync(ct); var stored = (await bed.Db.Entries.GetWithMediaAsync(added.Stored.Entry.Id, ct))!.Media.Single(); Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, stored))); } /// «Solo i nuovi» leaves the files saved before the switch; «Copia anche quelli già in libreria» copies them. [TestMethod] public async Task OnlyNewSkipsFilesSavedBeforeTheSwitch_AlsoAnswerCopiesThem() { var ct = TestContext.CancellationToken; await using var bed = await ExportTestBed.CreateAsync(); var old = await bed.PostAsync(bed.Luca, "o01", 1); var usb = await bed.GeneralAsync(ct: ct); bed.Clock.Now += TimeSpan.FromMinutes(1); usb = await TurnOnAsync(bed, usb, onlyNew: true, ct); bed.Clock.Now += TimeSpan.FromMinutes(1); var fresh = await bed.PostAsync(bed.Luca, "o02", 2); var worker = Worker(bed); Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: true, ct)); await bed.Service.WaitAsync(ct); Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, fresh.Media[0]))); Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, old.Media[0])), "saved before the switch"); Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round: true, ct)); // Off, then on with «Copia anche quelli già in libreria». usb = (await bed.Service.Destinations.UpdateAsync(usb.Id, Spec(usb) with { Automatic = false }, ct)).Destination; await TurnOnAsync(bed, usb, onlyNew: false, ct); Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct)); await bed.Service.WaitAsync(ct); Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, old.Media[0]))); } /// Answer 50: every round tries every «Non riuscito» again, whatever the error; a signal pass leaves it. [TestMethod] public async Task EveryRoundRetriesTheFailedCopies_ASignalPassDoesNot() { var ct = TestContext.CancellationToken; await using var bed = await ExportTestBed.CreateAsync(); var post = await bed.PostAsync(bed.Luca, "f01", 1); var usb = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, 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 = ExportText.Note(ExportText.Notes.PathTooLong), }, ct); var worker = Worker(bed); Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round: false, ct)); Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: true, ct), "even a «percorso troppo lungo»"); await bed.Service.WaitAsync(ct); Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0]))); } /// /// One unfinished automatic run per destination: one stopped by an error is resumed only by the round, and meanwhile /// the destination gets no other automatic run. /// [TestMethod] public async Task AnErroredAutomaticRunIsResumedOnlyByTheRound_AtMostOneUnfinishedRunPerDestination() { 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, "e01", 1); var usb = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct); var run = await UnfinishedAutomaticRunAsync(bed, held, usb, "Errore di lettura o scrittura", ct); var later = await bed.PostAsync(bed.Luca, "e02", 2); var worker = Worker(bed); Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round: false, ct)); Assert.HasCount(1, await bed.Db.Exports.ListRunsAsync(ct), "no second automatic run for the destination"); Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: true, ct)); await bed.Service.WaitAsync(ct); Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State); // The round resumed the run only: the next pass looks for the new files. Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct)); await bed.Service.WaitAsync(ct); Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, later.Media[0]))); Assert.HasCount(2, await bed.Db.Exports.ListRunsAsync(ct)); } /// /// The start-up round resumes the automatic runs the last stop left «interrotto» (RecoverAsync), never a run of /// Alberto's; and a manual «In pausa» stays paused when the round finds its folder back (answer 48). /// [TestMethod] public async Task TheStartupRoundResumesInterruptedAutomaticRunsButNotManualOnes() { 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, "r01", 1); await bed.PostAsync(bed.Marta, "r02", 2); var usb = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct); var own = await bed.OwnAsync(bed.Marta, "marta-nas", ct: ct); var automatic = await UnfinishedAutomaticRunAsync(bed, held, usb, null, ct, ExportRunState.Running); // A manual copy into Marta's folder paused because the folder went away. Directory.Move(bed.Temp.Combine("marta-nas"), bed.Temp.Combine("marta-nas-via")); var manual = (await bed.CopyAccountAsync(bed.Marta, ct: ct)).Runs.Single(); Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(manual.Id, ct)).State); Directory.Move(bed.Temp.Combine("marta-nas-via"), bed.Temp.Combine("marta-nas")); Assert.AreEqual(1, await bed.Service.RecoverAsync(ct), "the stop left the automatic run «in corso»"); var worker = Worker(bed); Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: true, ct)); await bed.Service.WaitAsync(ct); Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(automatic.Id, ct)).State); Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0]))); Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(own.Id, ct))!.PausedAt, "the round found the folder back"); Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(manual.Id, ct)).State, "a manual «In pausa» stays Alberto's"); } /// «Interrompi» on an automatic copy holds the copies (at least an hour, answer 53); «Riprendi ora» releases them. [TestMethod] public async Task InterruptHoldsUntilAtLeastAnHour_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 }); var post = await bed.PostAsync(bed.Luca, "h01", 1, 2); await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct); var worker = Worker(bed); Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct)); await held.Reached.Task.WaitAsync(Patience, ct); var until = await bed.Service.InterruptAsync(ct); Assert.IsNotNull(until); Assert.IsGreaterThanOrEqualTo(bed.Clock.Now + TimeSpan.FromHours(1), until.Value); held.Release(); Assert.AreEqual(AutoExportPass.Held, await worker.RunOnceAsync(round: true, ct)); Assert.AreEqual(until, (await worker.StatusAsync(ct)).HeldUntil); bed.Clock.Now += TimeSpan.FromMinutes(59); Assert.AreEqual(AutoExportPass.Held, await worker.RunOnceAsync(round: true, ct)); var signals = bed.Signal.Count; await worker.ResumeNowAsync(ct); Assert.IsTrue(bed.Signal.Count > signals, "«Riprendi ora» wakes the worker at once"); Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct)); await bed.Service.WaitAsync(ct); Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[1]))); Assert.AreEqual(ExportRunState.Completed, (await bed.Db.Exports.ListRunsAsync(ct)).Single().State, "the interrupted run resumed"); } /// An import, a rebuild, a job of Alberto's and «Cerca i video fermi» come first: the worker waits and says why. [TestMethod] public async Task TheWorkerWaitsForAnImportAManualJobAndTheStillVideoSearch() { 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, "w01", 1); await bed.PostAsync(bed.Marta, "w02", 2); var usb = await bed.GeneralAsync(ct: ct); var stills = false; var worker = Worker(bed, other: () => stills); await TurnOnAsync(bed, usb, onlyNew: false, ct); Assert.IsTrue(bed.Gate.TryEnter(LongWorkKind.Import, out var import, out _)); await AssertWaitingAsync(worker, AutoExportText.LongWork(LongWorkKind.Import), ct); import.Dispose(); Assert.IsTrue(bed.Gate.TryEnter(LongWorkKind.Rebuild, out var rebuild, out _)); await AssertWaitingAsync(worker, "Copie automatiche: aspettano la fine della ricostruzione.", ct); rebuild.Dispose(); stills = true; await AssertWaitingAsync(worker, AutoExportText.StillVideos, ct); stills = false; await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Media([post.Media[0].Id])), ct); await held.Reached.Task.WaitAsync(Patience, ct); await AssertWaitingAsync(worker, AutoExportText.ManualJob, ct); held.Release(); await bed.Service.WaitAsync(ct); Assert.IsEmpty((await bed.Db.Exports.ListRunsAsync(ct)).Where(r => r.Origin == ExportRunOrigin.Automatic), "nothing started while waiting"); Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct)); Assert.IsNull((await worker.StatusAsync(ct)).Waiting); await bed.Service.WaitAsync(ct); } /// A destination retired, or switched off, is never copied into, and its automatic runs are cancelled at the round. [TestMethod] public async Task RetiredAndSwitchedOffDestinationsAreNeverAutomatic() { 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.Marta, "x01", 1); await bed.PostAsync(bed.Luca, "x02", 2); var own = await TurnOnAsync(bed, await bed.OwnAsync(bed.Marta, "marta-nas", ct: ct), onlyNew: false, ct); var usb = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct); var run = await UnfinishedAutomaticRunAsync(bed, held, usb, null, ct); await bed.Db.Exports.UpdateDestinationAsync(usb with { Automatic = false, AutomaticSince = null }, ct); await bed.Service.Destinations.RetireAsync(own.Id, ct); var worker = Worker(bed); Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round: true, ct)); Assert.AreEqual(ExportRunState.Cancelled, (await bed.RunAsync(run.Id, ct)).State, "a ghost automatic run is cancelled by the round"); Assert.HasCount(1, await bed.Db.Exports.ListRunsAsync(ct)); Assert.IsEmpty(Directory.GetFiles(bed.Usb, "*.jpg", SearchOption.AllDirectories)); Assert.IsEmpty(Directory.GetFiles(bed.Temp.Combine("marta-nas"), "*.jpg", SearchOption.AllDirectories)); Assert.IsFalse((await worker.StatusAsync(ct)).AnyAutomatic); } /// /// After a non-urgent signal the pass waits for the settle (two minutes after the last file); an urgent one («Riprendi /// ora», a destination turned on) needs no wait. /// [TestMethod] public async Task AnUrgentSignalSkipsTheSettle() { var ct = TestContext.CancellationToken; GatedClock? clock = null; await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new GatedClock((ManualClock)env.Clock) }); await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct); var worker = Worker(bed, clock); var loop = worker.RunAsync(ct); await IdleAsync(bed, worker, clock!, ct); var asked = clock!.Asked; var post = await bed.PostAsync(bed.Luca, "g01", 1); var due = await clock.WaitForDelayAsync(asked, ct); Assert.AreEqual(clock.Now + TimeSpan.FromMinutes(2), due, "the settle"); var second = await bed.PostAsync(bed.Luca, "g02", 2); await clock.WaitForDelayAsync(asked + 1, ct); clock.Advance(TimeSpan.FromMinutes(1)); await Task.Delay(50, ct); Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0])), "two minutes after the last file, not the first"); Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct)); bed.Signal.Signal(urgent: true); await WaitUntilAsync(() => Task.FromResult(File.Exists(bed.GeneralCopy(bed.Luca, second.Media[0]))), ct); Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0]))); await worker.StopAsync(); await loop; } /// A file saved while a pass's job is at work is copied by a pass after it: the signal is not lost. [TestMethod] public async Task ASignalDuringAPassIsNotLost() { var ct = TestContext.CancellationToken; GatedClock? clock = null; var held = new HeldExportFileSystem(p => p.EndsWith("_1.jpg", StringComparison.Ordinal) && p.Contains("p01", StringComparison.Ordinal)); await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new GatedClock((ManualClock)env.Clock), FileSystem = held }); await bed.PostAsync(bed.Luca, "p01", 1); await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct); var worker = Worker(bed, clock); var started = clock!.Now; var loop = worker.RunAsync(ct); await held.Reached.Task.WaitAsync(Patience, ct); await SleepingAsync(clock, ct); var asked = clock.Asked; var during = await bed.PostAsync(bed.Luca, "p02", 2); Assert.AreEqual(clock.Now + TimeSpan.FromMinutes(2), await clock.WaitForDelayAsync(asked, ct), "the settle"); clock.Advance(TimeSpan.FromMinutes(2)); held.Release(); await WaitUntilAsync(() => Task.FromResult(File.Exists(bed.GeneralCopy(bed.Luca, during.Media[0]))), ct); await IdleAsync(bed, worker, clock, ct); Assert.HasCount(2, await bed.Db.Exports.ListRunsAsync(ct)); Assert.AreEqual(started, (await worker.StatusAsync(ct)).LastRound, "copied by a signal pass, not by a round"); await worker.StopAsync(); await loop; } /// /// A job displaced by Alberto's work is resumed by the loop once that work is over, without waiting for the round /// (answer 49: «riparte da sola dopo»). /// [TestMethod] public async Task AJobDisplacedByAnImportResumesWhenTheImportEnds() { var ct = TestContext.CancellationToken; GatedClock? clock = null; var held = new HeldExportFileSystem(p => p.EndsWith("_1.jpg", StringComparison.Ordinal)); await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new GatedClock((ManualClock)env.Clock), FileSystem = held }); var post = await bed.PostAsync(bed.Luca, "i01", 1, 2); await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct); var worker = Worker(bed, clock); var started = clock!.Now; var loop = worker.RunAsync(ct); await held.Reached.Task.WaitAsync(Patience, ct); var import = await bed.Gate.EnterAsync(LongWorkKind.Import, ct); Assert.IsNotNull(import.Lease); await bed.Service.WaitAsync(ct); held.Release(); var run = (await bed.Db.Exports.ListRunsAsync(ct)).Single(); Assert.AreEqual(ExportRunState.Interrupted, (await bed.RunAsync(run.Id, ct)).State); await WaitUntilAsync(async () => (await worker.StatusAsync(ct)).Waiting == AutoExportText.LongWork(LongWorkKind.Import), ct); await IdleAsync(bed, worker, clock, ct); import.Lease!.Dispose(); clock.Advance(TimeSpan.FromSeconds(5)); // the poll await WaitUntilAsync(async () => (await bed.RunAsync(run.Id, ct)).State == ExportRunState.Completed, ct); Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[1]))); Assert.AreEqual(started, (await worker.StatusAsync(ct)).LastRound, "resumed when the import ended, not by a round"); await worker.StopAsync(); await loop; } /// /// A job that ends normally starts no other by itself: a file that is in the database but no longer on disk gives a /// run at the round, not a run after every run. /// [TestMethod] public async Task AFinishedJobStartsNoOtherByItself() { var ct = TestContext.CancellationToken; GatedClock? clock = null; await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new GatedClock((ManualClock)env.Clock) }); var post = await bed.PostAsync(bed.Luca, "m01", 1); File.Delete(bed.LibraryFile(bed.Luca, post.Media[0])); await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct); var worker = Worker(bed, clock); var loop = worker.RunAsync(ct); await WaitUntilAsync(async () => (await bed.Db.Exports.ListRunsAsync(ct)).Count == 1, ct); await IdleAsync(bed, worker, clock!, ct); var passes = worker.Passes; clock!.Advance(TimeSpan.FromMinutes(5)); await IdleAsync(bed, worker, clock, ct); Assert.AreEqual(passes, worker.Passes, "no pass between rounds"); Assert.HasCount(1, await bed.Db.Exports.ListRunsAsync(ct)); await worker.StopAsync(); await loop; } /// After a sleep of the PC the clock jumps: the round runs once, and the next is an hour after it. [TestMethod] public async Task ALateWakeAfterSleepRunsTheRound() { var ct = TestContext.CancellationToken; GatedClock? clock = null; await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new GatedClock((ManualClock)env.Clock) }); await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct); var worker = Worker(bed, clock); var loop = worker.RunAsync(ct); await IdleAsync(bed, worker, clock!, ct); Assert.AreEqual(clock!.Now + TimeSpan.FromMinutes(5), clock.Pending.Single(), "never sleeps longer than five minutes"); var passes = worker.Passes; clock.Advance(TimeSpan.FromHours(3)); await WaitUntilAsync(() => Task.FromResult(worker.Passes > passes), ct); await IdleAsync(bed, worker, clock, ct); Assert.AreEqual(passes + 1, worker.Passes, "one round, not three"); var status = await worker.StatusAsync(ct); Assert.AreEqual((clock.Now, clock.Now + TimeSpan.FromHours(1)), (status.LastRound, status.NextRound)); await worker.StopAsync(); await loop; } /// An error of a pass is logged by type and the loop goes on; StopAsync ends it, and RunAsync does not throw. [TestMethod] public async Task TheWorkerNeverThrowsOutOfRunAsync_StopAsyncEndsTheLoop() { var ct = TestContext.CancellationToken; GatedClock? clock = null; await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new GatedClock((ManualClock)env.Clock) }); var logged = new List(); var worker = new AutoExportWorker(Environment(bed, clock) with { Service = _ => throw new IOException("percorso segreto"), Log = message => { lock (logged) { logged.Add(message); } }, }); var loop = worker.RunAsync(ct); await WaitUntilAsync(() => Task.FromResult(Count(logged) == 1), ct); await clock!.WaitForDelayAsync(0, ct); clock.Advance(TimeSpan.FromHours(1)); await WaitUntilAsync(() => Task.FromResult(Count(logged) == 2), ct); Assert.IsTrue(logged.All(m => m.Contains(nameof(IOException), StringComparison.Ordinal) && !m.Contains("segreto", StringComparison.Ordinal)), string.Join(" | ", logged)); Assert.IsTrue(worker.Running); await worker.StopAsync(); await loop.WaitAsync(Patience, ct); Assert.IsFalse(worker.Running); Assert.IsFalse((await worker.StatusAsync(ct)).Running); await Assert.ThrowsExactlyAsync(async () => { var again = worker.RunAsync(ct); var twice = worker.RunAsync(ct); try { await twice; } finally { await worker.StopAsync(); await again; } }); } // Helpers ------------------------------------------------------------------------------------------------------- private static AutoExportEnvironment Environment(ExportTestBed bed, IClock? clock = null, Func? other = null) => new() { Storage = bed.Db, Clock = clock ?? bed.Environment.Clock, Service = _ => Task.FromResult(bed.Service), Signal = bed.Signal, Session = bed.Session, Gate = bed.Gate, OtherWorkRunning = other ?? (() => false), }; private static AutoExportWorker Worker(ExportTestBed bed, IClock? clock = null, Func? other = null) => new(Environment(bed, clock, other)); /// «Automatica» on through the destinations (the dialog's answer: «Solo i nuovi» or «Copia anche quelli…»). private static async Task TurnOnAsync(ExportTestBed bed, ExportDestination destination, bool onlyNew, CancellationToken ct) => (await bed.Service.Destinations.UpdateAsync(destination.Id, Spec(destination) with { Automatic = true, OnlyNew = onlyNew }, ct)).Destination; private static DestinationSpec Spec(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); /// Deletes the copy of a post's first file and runs «Controlla le copie»: it becomes «Tolto». private static async Task MakeRemovedAsync(ExportTestBed bed, ExportDestination usb, EntryWithMedia post, CancellationToken ct) { File.Delete(bed.GeneralCopy(bed.Luca, post.Media[0])); await bed.Service.CheckCopiesAsync(usb.Id, ct); await bed.Service.WaitAsync(ct); var copy = (await bed.Db.Exports.ListCopiesBySha256Async(post.Media[0].Sha256!, ct)).Single(); Assert.AreEqual(ExportCopyState.Removed, copy.State); } /// /// Replaces a post's first library file the real way (ImportCopier's order): new bytes, the record, the supersession of /// the old copies, the journal line (which signals). Returns the new SHA-256. /// private static async Task ReplaceAsync(ExportTestBed bed, Account account, EntryWithMedia post, int scene, CancellationToken ct) { var media = post.Media[0]; var bytes = ExportTestBed.Photo(1, scene).Bytes; await File.WriteAllBytesAsync(bed.LibraryFile(account, media), bytes, ct); var sha = Convert.ToHexStringLower(SHA256.HashData(bytes)); await bed.Db.Media.MarkStoredAsync(media.Id, new StoredFile(media.RelativePath!, bytes.Length, sha, null, 96, 120, null, false), MediaState.Downloaded, bed.Clock.Now, ct); Assert.AreEqual(1, await ExportSupersession.FileChangedAsync(bed.Db, account.Id, media.Sha256, sha, bed.Clock.Now, ct)); Assert.IsTrue(await bed.Library.Ingest.TryAppendJournalAsync(post.Entry.Id, ct)); return sha; } /// /// An automatic run of the destination left unfinished: started, stopped while it reads its first file (held), then /// recorded with and ; nothing was copied. /// private static async Task UnfinishedAutomaticRunAsync(ExportTestBed bed, HeldExportFileSystem held, ExportDestination destination, string? error, CancellationToken ct, ExportRunState state = ExportRunState.Interrupted) { var start = await bed.Service.TryStartAutomaticAsync(new ExportSelection.Automatic([new(destination.Id, destination.AutomaticSince)], [], Round: true), ct); Assert.AreEqual(AutoExportStartOutcome.Started, start.Outcome); await held.Reached.Task.WaitAsync(Patience, ct); Assert.IsTrue(await bed.Service.InterruptAutomaticAsync(ct)); await bed.Service.WaitAsync(ct); held.Release(); var run = await bed.RunAsync(start.Runs.Single().Id, ct); Assert.AreEqual(ExportRunState.Interrupted, run.State); run = run with { State = state, LastError = error }; await bed.Db.Exports.UpdateRunAsync(run, ct); Assert.IsEmpty(await bed.Db.Exports.ListCopiesAsync(destination.Id, ct: ct)); return run; } private static async Task PauseEventsAsync(ExportTestBed bed, CancellationToken ct) => (await bed.Db.Events.ListAsync(new() { Limit = 100 }, ct)).Count(e => e.Code == ExportPause.PausedEventCode); private static async Task AssertWaitingAsync(AutoExportWorker worker, string because, CancellationToken ct) { Assert.AreEqual(AutoExportPass.Waiting, await worker.RunOnceAsync(round: true, ct), because); Assert.AreEqual(because, (await worker.StatusAsync(ct)).Waiting); } /// Waits until no job runs and the worker sleeps on the clock after its last pass. private static async Task IdleAsync(ExportTestBed bed, AutoExportWorker worker, GatedClock clock, CancellationToken ct) { var watch = Stopwatch.StartNew(); while (true) { await bed.Service.WaitAsync(ct); var passes = worker.Passes; var asked = clock.Asked; if (!bed.Service.IsBusy && clock.Pending.Count > 0) { await Task.Delay(50, ct); if (worker.Passes == passes && clock.Asked == asked && !bed.Service.IsBusy && clock.Pending.Count > 0) { return; } } if (watch.Elapsed > Patience) { Assert.Fail("il lavoratore non si è fermato ad aspettare"); } await Task.Delay(10, ct); } } /// Waits until a delay waits on the clock and nothing more is asked for a moment (the worker sleeps). private static async Task SleepingAsync(GatedClock clock, CancellationToken ct) { var watch = Stopwatch.StartNew(); while (true) { var asked = clock.Asked; if (clock.Pending.Count > 0) { await Task.Delay(50, ct); if (clock.Asked == asked && clock.Pending.Count > 0) { return; } } if (watch.Elapsed > Patience) { Assert.Fail("il lavoratore non dorme"); } await Task.Delay(10, ct); } } private static int Count(List list) { lock (list) { return list.Count; } } private static async Task WaitUntilAsync(Func> done, CancellationToken ct) { var watch = Stopwatch.StartNew(); while (!await done()) { if (watch.Elapsed > Patience) { Assert.Fail("non è arrivato"); } await Task.Delay(10, ct); } } }