using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Core.Export; using Febe.Core.Library; using Febe.Core.Storage; using Febe.Data; using Febe.Tests.Export.Support; using Febe.Tests.Support; namespace Febe.Tests.Export; /// /// The cases found by the review of tappa E2 (27 November 2026): a stale row on the free name the writer takes, a /// path that differs only in letter case, a superseded copy whose file is back in the library, «Una copia sola» with /// copies of the account itself or of a removed account, a disk unplugged during «Controlla le copie», the later runs of /// an interrupted «Copia in…», and the long-work gate held while a «Copia in…» is planned. /// [TestClass] public sealed class ExportReviewTests { private static readonly TimeSpan Patience = TimeSpan.FromSeconds(30); public TestContext TestContext { get; set; } = null!; [TestMethod] public async Task AStaleRowOnTheFreeNameIsReleasedAndTheCopyRecorded() { var ct = TestContext.CancellationToken; await using var bed = await ExportTestBed.CreateAsync(); var post = await bed.PostAsync(bed.Marta, "970", 40); var usb = await bed.GeneralAsync(ct: ct); var planned = "marta.demo/" + post.Media[0].RelativePath; var numbered = ExportPaths.NumberedName(bed.Usb, planned, 2); // The planned name holds another file (other bytes); the next name is still recorded for a copy of luca.demo // whose file Alberto deleted. var foreign = Path.Combine(bed.Usb, LibraryLayout.ToPlatform(planned)); Directory.CreateDirectory(Path.GetDirectoryName(foreign)!); await File.WriteAllBytesAsync(foreign, [1, 2, 3], ct); var stale = await bed.Db.Exports.AddCopyAsync(StaleCopy(usb.Id, bed.Luca.Id, numbered, 91), ct); var start = await bed.CopyAccountAsync(bed.Marta, ct: ct); var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single(); Assert.AreEqual((ExportItemState.Copied, ExportText.Notes.NameTaken, numbered), (item.State, item.Note, item.RelativePath)); var copy = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!; Assert.AreEqual((ExportCopyState.Copied, numbered), (copy.State, copy.RelativePath)); Assert.AreEqual(ExportCopyState.Removed, (await bed.Db.Exports.GetCopyAsync(stale.Id, ct))!.State, "the stale row is «Tolto»"); CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, await File.ReadAllBytesAsync(foreign, ct), "the other file is untouched"); // A second «Copia in…» writes nothing more. var files = Fingerprint.Of(bed.Usb); var again = await bed.CopyAccountAsync(bed.Marta, ct: ct); Assert.AreEqual((0, 1), (again.Plan.Files, again.Plan.AlreadyCopied)); Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "no duplicate"); } [TestMethod] public async Task APathThatDiffersOnlyInCaseIsNotTakenFromItsCopy() { var ct = TestContext.CancellationToken; await using var bed = await ExportTestBed.CreateAsync(); var post = await bed.PostAsync(bed.Marta, "971", 41); var usb = await bed.GeneralAsync(ct: ct); var planned = "marta.demo/" + post.Media[0].RelativePath; var slash = planned.LastIndexOf('/'); var shouted = planned[..(slash + 1)] + planned[(slash + 1)..].ToUpperInvariant(); Assert.AreNotEqual(planned, shouted); // Another copy is recorded and present under the same name in other letters (a case-sensitive disk keeps both). var other = Path.Combine(bed.Usb, LibraryLayout.ToPlatform(shouted)); Directory.CreateDirectory(Path.GetDirectoryName(other)!); await File.WriteAllBytesAsync(other, [4, 5, 6], ct); var held = await bed.Db.Exports.AddCopyAsync(StaleCopy(usb.Id, bed.Luca.Id, shouted, 92) with { Bytes = 3 }, ct); var start = await bed.CopyAccountAsync(bed.Marta, ct: ct); var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single(); Assert.AreEqual((ExportItemState.Copied, ExportText.Notes.NameTaken), (item.State, item.Note)); Assert.AreEqual(ExportPaths.NumberedName(bed.Usb, planned, 2), item.RelativePath); Assert.AreEqual(ExportCopyState.Copied, (await bed.Db.Exports.GetCopyAsync(held.Id, ct))!.State, "its file is there: not «Tolto»"); CollectionAssert.AreEqual(new byte[] { 4, 5, 6 }, await File.ReadAllBytesAsync(other, ct)); } [TestMethod] public async Task ASupersededCopyOfAFileBackInTheLibraryAgreesAndCanBeCopiedAgain() { var ct = TestContext.CancellationToken; await using var bed = await ExportTestBed.CreateAsync(); var post = await bed.PostAsync(bed.Marta, "972", 42); await bed.GeneralAsync(ct: ct); await bed.CopyAccountAsync(bed.Marta, ct: ct); var media = post.Media[0]; // The copy was superseded by another file; that file went, and this one came back (another entry, with no // change of file that would have revived the row). Assert.AreEqual(1, await bed.Db.Exports.SupersedeCopiesAsync(bed.Marta.Id, media.Sha256!, Make.Sha(77), bed.Clock.Now, ct)); var request = new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)); var plan = await bed.Service.PlanAsync(request, ct); Assert.AreEqual((0, 0, 1), (plan.Files, plan.AlreadyCopied, plan.RemovedOrSuperseded)); Assert.AreEqual(new ExportAccountCounts(1, 0, 1, 0), await bed.Db.Exports.CountAccountFilesAsync(bed.Marta.Id, ct), "the filter says what the plan does"); CollectionAssert.AreEqual(new[] { post.Entry.Id }, await EntriesAsync(bed.Db, LibraryCopiesFilter.RemovedOrSuperseded, ct)); Assert.IsEmpty(await EntriesAsync(bed.Db, LibraryCopiesFilter.NotCopied, ct)); // «Copia di nuovo» finds its own bytes at the path: the row is «Copiato» again, nothing is written. var files = Fingerprint.Of(bed.Usb); var start = await bed.CopyAsync(request with { CopyAgain = true }, ct); var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single(); Assert.AreEqual(ExportItemState.AlreadyCopied, item.State); var copy = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!; Assert.AreEqual((ExportCopyState.Copied, (string?)null), (copy.State, copy.SupersededBySha256)); Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "nothing written"); Assert.AreEqual(new ExportAccountCounts(1, 0, 0, 0), await bed.Db.Exports.CountAccountFilesAsync(bed.Marta.Id, ct)); Assert.AreEqual(1, (await bed.Service.PlanAsync(request, ct)).AlreadyCopied); } [TestMethod] public async Task OneCopyOnlyIgnoresTheAccountsOwnCopyInAnotherFolder() { var ct = TestContext.CancellationToken; await using var bed = await ExportTestBed.CreateAsync(); var post = await bed.PostAsync(bed.Marta, "973", 43); await bed.GeneralAsync(ct: ct); await bed.CopyAccountAsync(bed.Marta, ct: ct); // Her own folder now, the general one still in use for the others. await bed.OwnAsync(bed.Marta, "marta-nas", ct: ct); await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct); await AssertAgreeAsync(bed, bed.Marta, expectedToWrite: 1, ct); Assert.AreEqual(ExportMark.None, (await bed.Db.Exports.GetFileMarksAsync([post.Media[0].Id], ct))[post.Media[0].Id]); } [TestMethod] public async Task OneCopyOnlyIgnoresTheCopyOfARemovedAccount() { var ct = TestContext.CancellationToken; await using var bed = await ExportTestBed.CreateAsync(); var lucas = await bed.PostAsync(bed.Luca, "974", 44); await bed.GeneralAsync(ct: ct); await bed.CopyAccountAsync(bed.Luca, ct: ct); var martas = await bed.PostAsync(bed.Marta, "975", 44); // the same bytes Assert.AreEqual(lucas.Media[0].Sha256, martas.Media[0].Sha256); // luca.demo leaves Febe: his copy stays, without an account. await bed.Db.Accounts.DeleteAsync(bed.Luca.Id, ct); await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct); await AssertAgreeAsync(bed, bed.Marta, expectedToWrite: 1, ct); Assert.AreEqual(ExportMark.None, (await bed.Db.Exports.GetFileMarksAsync([martas.Media[0].Id], ct))[martas.Media[0].Id]); } [TestMethod] public async Task OneCopyOnlyFindsTheOtherAccountsCopyBehindTheAccountsOwnNewerOne() { var ct = TestContext.CancellationToken; await using var bed = await ExportTestBed.CreateAsync(); var lucas = await bed.PostAsync(bed.Luca, "976", 45); await bed.GeneralAsync(ct: ct); await bed.CopyAccountAsync(bed.Luca, ct: ct); // the older copy, of luca.demo var martas = await bed.PostAsync(bed.Marta, "977", 45); await bed.CopyAccountAsync(bed.Marta, ct: ct); // the newer one, hers («Una copia per account») Assert.AreEqual(lucas.Media[0].Sha256, martas.Media[0].Sha256); await bed.OwnAsync(bed.Marta, "marta-nas", ct: ct); await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct); await AssertAgreeAsync(bed, bed.Marta, expectedToWrite: 0, ct); var start = await bed.CopyAccountAsync(bed.Marta, ct: ct); var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single(); Assert.AreEqual((ExportItemState.AlreadyCopied, ExportText.Notes.CopiedForAnotherAccount), (item.State, item.Note)); } [TestMethod] public async Task ADiskUnpluggedDuringTheCheckMarksNothingRemoved() { var ct = TestContext.CancellationToken; var unplug = new UnplugOnCheck(); await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = unplug }); await bed.PostAsync(bed.Marta, "978", 46, 47, 48); var usb = await bed.GeneralAsync(ct: ct); await bed.CopyAccountAsync(bed.Marta, ct: ct); Assert.HasCount(3, await bed.Db.Exports.ListCopiesAsync(usb.Id, ExportCopyState.Copied, ct: ct)); // The disk goes away after the root was found and before the files of the page are looked for. unplug.Root = bed.Usb; await bed.Service.CheckCopiesAsync(usb.Id, ct); await bed.Service.WaitAsync(ct); Assert.IsTrue(unplug.Unplugged); Assert.HasCount(3, await bed.Db.Exports.ListCopiesAsync(usb.Id, ExportCopyState.Copied, ct: ct), "nothing is «Tolto»"); Assert.IsNotNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt, "the destination is paused"); // Plugged in again, the check finds every file. Directory.Move(bed.Usb + "-staccato", bed.Usb); unplug.Root = null; await bed.Service.CheckCopiesAsync(usb.Id, ct); await bed.Service.WaitAsync(ct); Assert.HasCount(3, await bed.Db.Exports.ListCopiesAsync(usb.Id, ExportCopyState.Copied, ct: ct)); } [TestMethod] public async Task InterruptingAJobOfTwoDestinationsLeavesBothResumable() { var ct = TestContext.CancellationToken; string? blocked = null; var gated = new GatedExportFileSystem(p => string.Equals(p, Volatile.Read(ref blocked), StringComparison.Ordinal)); await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = gated }); var martas = await bed.PostAsync(bed.Marta, "979", 49); var lucas = await bed.PostAsync(bed.Luca, "980", 50); await bed.GeneralAsync(ct: ct); await bed.OwnAsync(bed.Luca, "luca-nas", ct: ct); Volatile.Write(ref blocked, bed.LibraryFile(bed.Marta, martas.Media[0])); var start = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Entries([martas.Entry.Id, lucas.Entry.Id])), ct); Assert.HasCount(2, start.Runs); await gated.Reached.Task.WaitAsync(Patience, ct); await bed.Service.InterruptAsync(ct); Assert.IsFalse(bed.Service.IsBusy); foreach (var run in start.Runs) { Assert.AreEqual((ExportRunState.Interrupted, (string?)null), ((await bed.RunAsync(run.Id, ct)).State, (await bed.RunAsync(run.Id, ct)).LastError), $"run {run.Id}"); } // «Riprendi tutte» takes both. Volatile.Write(ref blocked, null); var resumed = await bed.Service.ResumeAsync(ct: ct); Assert.HasCount(2, resumed); await bed.Service.WaitAsync(ct); foreach (var run in start.Runs) { Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State); } } [TestMethod] public async Task TheLongWorkGateIsHeldWhileACopyIsPlanned() { var ct = TestContext.CancellationToken; GateWatchingClock? clock = null; await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new GateWatchingClock(env.Clock, env.Gate!) }); await bed.PostAsync(bed.Marta, "981", 51, 52); await bed.GeneralAsync(ct: ct); clock!.Watching = true; await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct); clock.Watching = false; await bed.Service.WaitAsync(ct); Assert.IsGreaterThan(0, clock.Looks, "the start read the clock while it planned"); Assert.AreEqual(0, clock.Overlaps, "a rebuild could have started while the runs were recorded"); Assert.IsNull(bed.Gate.Busy); // Nothing to copy: the gate is free again at once. var nothing = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Luca.Id)), ct); Assert.IsEmpty(nothing.Runs); Assert.IsNull(bed.Gate.Busy); } [TestMethod] public void TheRenameNeverReplacesAnExistingName() { using var temp = new TempFolder("rename"); var taken = temp.Combine("taken.jpg"); var source = temp.Combine(".febe-0123456789ab.part"); File.WriteAllBytes(taken, [1]); File.WriteAllBytes(source, [2]); if (OperatingSystem.IsWindows()) { // On Windows the move itself refuses an existing name: nothing to do here. Assert.AreEqual(NoReplaceOutcome.Unsupported, NoReplaceRename.TryMove(source, taken)); } else { Assert.AreEqual(NoReplaceOutcome.Taken, NoReplaceRename.TryMove(source, taken)); CollectionAssert.AreEqual(new byte[] { 1 }, File.ReadAllBytes(taken)); Assert.IsTrue(File.Exists(source)); var free = temp.Combine("free.jpg"); Assert.AreEqual(NoReplaceOutcome.Moved, NoReplaceRename.TryMove(source, free)); CollectionAssert.AreEqual(new byte[] { 2 }, File.ReadAllBytes(free)); Assert.IsFalse(File.Exists(source)); } Assert.AreEqual(1, File.ReadAllBytes(taken)[0]); } /// A Copied row of a whole original (any SHA-256 given by its seed) at a path, with no file behind it. private static ExportCopy StaleCopy(long destinationId, long accountId, string path, int seed) => new() { DestinationId = destinationId, AccountId = accountId, SourceSha256 = Make.Sha(seed), Variant = ExportVariant.Whole, Format = ExportFormat.Original, State = ExportCopyState.Copied, RelativePath = path, Bytes = 1, CopySha256 = Make.Sha(seed), CopiedAt = Make.T0, }; /// The plan of the account, its counts, its marks and the «Copie» filter tell the same. private static async Task AssertAgreeAsync(ExportTestBed bed, Account account, int expectedToWrite, CancellationToken ct) { var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(account.Id)), ct); var counts = await bed.Db.Exports.CountAccountFilesAsync(account.Id, ct); Assert.AreEqual(expectedToWrite, plan.Files, "plan"); Assert.AreEqual(plan.Files, counts.NotCopied, "«non ancora copiati» is what «Copia in…» writes"); Assert.AreEqual(plan.AlreadyCopied, counts.Copied, "«copiati» is what «Copia in…» skips as copied"); var filter = new LibraryFilter { Copies = LibraryCopiesFilter.NotCopied, AccountIds = [account.Id] }; Assert.AreEqual(expectedToWrite, (await bed.Db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = filter, Mode = MosaicMode.Files }, ct)).Tiles.Count); var copied = filter with { Copies = LibraryCopiesFilter.Copied }; Assert.AreEqual(plan.AlreadyCopied, (await bed.Db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = copied, Mode = MosaicMode.Files }, ct)).Tiles.Count); } private static async Task EntriesAsync(FebeDatabase db, LibraryCopiesFilter filter, CancellationToken ct) => [.. (await db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = new LibraryFilter { Copies = filter } }, ct)).Tiles.Select(t => t.EntryId)]; /// The real file system; once is set, the first look for a file in it takes the disk away. private sealed class UnplugOnCheck : IExportFileSystem { private int _unplugged; public string? Root { get; set; } public bool Unplugged => Volatile.Read(ref _unplugged) != 0; public Stream OpenRead(string path) => ExportFileSystem.Instance.OpenRead(path); public Task ComputeSha256Async(string path, CancellationToken ct) => ExportFileSystem.Instance.ComputeSha256Async(path, ct); public bool FileExists(string path) { if (Root is { } root && path.StartsWith(root + Path.DirectorySeparatorChar, StringComparison.Ordinal) && Interlocked.Exchange(ref _unplugged, 1) == 0) { Directory.Move(root, root + "-staccato"); } return ExportFileSystem.Instance.FileExists(path); } public long? FileLength(string path) => ExportFileSystem.Instance.FileLength(path); } /// /// The clock of the export; while , each look at the time tries to start a rebuild through the /// long-work gate (and lets it go at once), counting the times it could. /// private sealed class GateWatchingClock(IClock inner, LongWorkGate gate) : IClock { private int _looks; private int _overlaps; private volatile bool _watching; public bool Watching { get => _watching; set => _watching = value; } public int Looks => Volatile.Read(ref _looks); public int Overlaps => Volatile.Read(ref _overlaps); public DateTimeOffset Now { get { if (Watching) { Interlocked.Increment(ref _looks); if (gate.TryEnter(LongWorkKind.Rebuild, out var lease, out _)) { Interlocked.Increment(ref _overlaps); lease.Dispose(); } } return inner.Now; } } public TimeZoneInfo LocalZone => inner.LocalZone; public Task Delay(TimeSpan time, CancellationToken ct) => inner.Delay(time, ct); } }