E2: correzioni della revisione delle copie esterne
- Nome libero scelto prima di scrivere, libero sul disco e nel database; una riga orfana sul nome diventa «Tolto» (guardando il suo percorso, anche se differisce solo per le maiuscole): prima la copia finiva «Non riuscito» con il file già scritto, o toglieva la copia buona. - «Controlla le copie» rilegge la radice e riguarda i file mancanti; con il disco staccato si ferma e mette in pausa senza segnare nulla. - Su Linux lo spostamento sul nome finale non sostituisce mai un file (renameat2 RENAME_NOREPLACE, poi link e unlink). - Le copie in coda di un lavoro interrotto diventano «Interrotta» e si riprendono; il permesso dei lavori lunghi si tiene già nel piano. - «Superato» con il file di nuovo in libreria: filtro, piano e «Copia di nuovo» d'accordo; l'adozione ravviva la riga invece di fallire. - «Una copia sola» con una regola sola in filtro, piano, visualizzatore e copiatore (solo copie di un altro account in cartelle in uso). - Controllo della cartella per identità vera (percorso finale, realpath, dispositivo di mountinfo): riconosce collegamenti e bind mount di una sottocartella della libreria. - Sfoglia delle cartelle con tempi massimi; «Nessuna cartella» solo se non ce n'è; «In copia…» nel visualizzatore; numero e fuoco stabili in «Copia di nuovo anche…»; una sola lettura per volta nella Dashboard. - Prove dell'interfaccia indipendenti dall'ora e dal file scelto; prove nuove in ExportReviewTests, ExportFolderCheckTests, ExportRootTests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
28c7f814b1
commit
36ad5c6f9d
28 files changed
+1314
-112
No files matched your search
@@ -637,7 +637,7 @@ public sealed class ExportConstraintTests
|
||||
var lookupsE2 = new (string Name, string Sql, (string, object?)[] Parameters, bool SortAllowed)[]
|
||||
{
|
||||
("FindReplacedCopyAsync", ExportStore.ReplacedCopySql, [("@h", Make.Sha(5008)), ("@d", w.General), ("@a", w.Marta)], false),
|
||||
("FindCopiedElsewhereAsync", ExportStore.CopiedElsewhereSql, [("@h", Make.Sha(17)), ("@v", "Whole"), ("@f", "Original")], true),
|
||||
("FindCopiedElsewhereAsync", ExportStore.CopiedElsewhereSql, [("@h", Make.Sha(17)), ("@v", "Whole"), ("@f", "Original"), ("@a", w.Marta)], true),
|
||||
("GetCopyStatesAsync", ExportStore.CopyStatesSql(shas), Shas(("@d", w.General)), false),
|
||||
("GetCopyStatesAsync (sostituiti)", ExportStore.ReplacedStatesSql(shas), Shas(("@d", w.General)), false),
|
||||
};
|
||||
|
||||
@@ -100,7 +100,7 @@ public sealed class ExportCopiesFilterTests
|
||||
Assert.AreEqual(ExportCopyState.Copied, (await db.Exports.GetCopyStatesAsync(w.Own, [(w.Marta, Make.Sha(1))], ct))[(w.Marta, Make.Sha(1))]);
|
||||
Assert.IsNotNull(await db.Exports.FindReplacedCopyAsync(w.General, w.Luca, Make.Sha(1), ct));
|
||||
Assert.IsNull(await db.Exports.FindReplacedCopyAsync(w.Own, w.Luca, Make.Sha(1), ct));
|
||||
Assert.AreEqual(copy.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original, ct))!.Id);
|
||||
Assert.AreEqual(copy.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original, ct: ct))!.Id);
|
||||
|
||||
var byAccount = await db.Exports.ListCandidatesAsync(new ExportSelection.Account(w.Marta), 0, 10, ct);
|
||||
Assert.AreEqual(w.MartaMedia, byAccount.Single().MediaId);
|
||||
|
||||
@@ -178,6 +178,68 @@ public sealed class ExportFolderCheckTests
|
||||
Assert.IsEmpty(Fingerprint.Temporaries(temp.Path));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ALinkToAFolderInsideTheLibraryIsRecognised()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
using var temp = new TempFolder();
|
||||
var library = temp.Combine("libreria");
|
||||
var inner = Path.Combine(library, "copie", "usb");
|
||||
Directory.CreateDirectory(inner);
|
||||
|
||||
// Not an account folder: a plain folder deep in the library, reached by a link (a junction or a symbolic link
|
||||
// where the test may make one, else the «\\?\» form of its path on Windows).
|
||||
var alias = temp.Combine("alias-copie");
|
||||
try
|
||||
{
|
||||
Directory.CreateSymbolicLink(alias, inner);
|
||||
}
|
||||
catch (Exception ex) when (OperatingSystem.IsWindows() && ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
alias = @"\\?\" + Path.GetFullPath(inner);
|
||||
}
|
||||
|
||||
Assert.IsFalse(ExportPaths.IsSameOrInside(alias, library), "the text must not tell");
|
||||
var guarded = new ExportFolderContext([new(Path.GetFullPath(library), ProtectedFolderKind.Library, null)], ExportRootOptions.AnyFolder);
|
||||
var verdict = await Check().CheckAsync(alias, guarded, ct);
|
||||
Assert.AreEqual(ExportFolderProblemKind.InsideProtected, verdict.Problem!.Kind);
|
||||
StringAssert.Contains(verdict.Problem.Message, "è dentro la cartella della libreria");
|
||||
Assert.IsEmpty(Fingerprint.Temporaries(temp.Path));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ABindMountOfAFolderOfTheLibraryIsRecognised()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
using var temp = new TempFolder();
|
||||
|
||||
// Docker on Unraid: -v /mnt/user/Febe:/libreria and -v /mnt/user/Febe/copie:/esporta/usb. Two folders that no
|
||||
// path and no probe relate, on the same device, the second showing a folder inside the first.
|
||||
var library = temp.Combine("libreria");
|
||||
var usb = temp.Combine("esporta", "usb");
|
||||
var nas = temp.Combine("esporta", "nas");
|
||||
var other = temp.Combine("esporta", "altro");
|
||||
foreach (var folder in new[] { library, usb, nas, Path.Combine(nas, "Febe", "lib"), other })
|
||||
{
|
||||
Directory.CreateDirectory(folder);
|
||||
}
|
||||
|
||||
string Real(string path) => FolderIdentity.RealPath(path)!;
|
||||
var mounts = new FixedMounts(
|
||||
new ExportMount(Real(library), "/Febe", "fuse.shfs", false, "0:51"),
|
||||
new ExportMount(Real(usb), "/Febe/copie", "fuse.shfs", false, "0:51"),
|
||||
new ExportMount(Real(nas), "/condivisa", "cifs", false, "0:60"),
|
||||
new ExportMount(Real(Path.Combine(nas, "Febe", "lib")), "/Febe", "fuse.shfs", false, "0:51"), // the library again, below the NAS
|
||||
new ExportMount(Real(other), "/Altro", "fuse.shfs", false, "0:51"));
|
||||
var check = new ExportFolderCheck(mounts);
|
||||
var guarded = new ExportFolderContext([new(Path.GetFullPath(library), ProtectedFolderKind.Library, null)], ExportRootOptions.AnyFolder with { Mounts = mounts });
|
||||
|
||||
Assert.AreEqual(ExportFolderProblemKind.InsideProtected, (await check.CheckAsync(usb, guarded, ct)).Problem!.Kind);
|
||||
Assert.AreEqual(ExportFolderProblemKind.ContainsProtected, (await check.CheckAsync(nas, guarded, ct)).Problem!.Kind, "a mount below the candidate shows the library");
|
||||
Assert.IsTrue((await check.CheckAsync(other, guarded, ct)).Accepted, "another folder of the same device is not the library");
|
||||
Assert.IsEmpty(Fingerprint.Temporaries(temp.Path));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheProbeIsWrittenOnlyInTheCandidate()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,381 @@
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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]);
|
||||
}
|
||||
|
||||
/// <summary>A Copied row of a whole original (any SHA-256 given by its seed) at a path, with no file behind it.</summary>
|
||||
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,
|
||||
};
|
||||
|
||||
/// <summary>The plan of the account, its counts, its marks and the «Copie» filter tell the same.</summary>
|
||||
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<long[]> EntriesAsync(FebeDatabase db, LibraryCopiesFilter filter, CancellationToken ct) =>
|
||||
[.. (await db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = new LibraryFilter { Copies = filter } }, ct)).Tiles.Select(t => t.EntryId)];
|
||||
|
||||
/// <summary>The real file system; once <see cref="Root"/> is set, the first look for a file in it takes the disk away.</summary>
|
||||
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<string> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The clock of the export; while <see cref="Watching"/>, 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,8 @@ namespace Febe.Tests.Export;
|
||||
[TestClass]
|
||||
public sealed class ExportRootTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestMethod]
|
||||
public void DesktopHasNoRootAndIsActive()
|
||||
{
|
||||
@@ -183,6 +185,32 @@ public sealed class ExportRootTests
|
||||
Assert.AreEqual(ExportFolderProblemKind.NotFullyQualified, Kind(() => ExportRoots.Browse(ExportRootOptions.AnyFolder, "usb")));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task ADeadShareBelowTheRootDoesNotBlockThePicker()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
using var temp = new TempFolder();
|
||||
var root = temp.Combine("esporta");
|
||||
Directory.CreateDirectory(Path.Combine(root, "nas", "Febe"));
|
||||
Directory.CreateDirectory(Path.Combine(root, "usb", "Febe"));
|
||||
var o = ExportRootOptions.Docker(root, declared: true, new FixedMounts(Mount(root))) with { ShownAs = "/esporta" };
|
||||
|
||||
// The NAS behind /esporta/nas is off: a look into it never answers.
|
||||
using var dead = new ManualResetEventSlim();
|
||||
bool Look(string folder) => Path.GetFileName(folder) == "nas" ? dead.Wait(Timeout.Infinite, ct) : Directory.EnumerateDirectories(folder).Any();
|
||||
var started = System.Diagnostics.Stopwatch.StartNew();
|
||||
var top = await ExportRoots.BrowseAsync(o, null, TimeSpan.FromMilliseconds(300), Look, ct);
|
||||
Assert.IsLessThan(TimeSpan.FromSeconds(10), started.Elapsed);
|
||||
CollectionAssert.AreEqual(new[] { "nas", "usb" }, top.Select(c => c.Name).ToArray());
|
||||
Assert.IsFalse(top[0].HasSubfolders, "the dead share is shown, without the arrow");
|
||||
Assert.IsTrue(top[1].HasSubfolders, "the healthy one is listed as usual");
|
||||
dead.Set();
|
||||
|
||||
var missing = await Assert.ThrowsExactlyAsync<ExportFolderException>(() => ExportRoots.BrowseAsync(o, "assente", TimeSpan.FromSeconds(5), ct));
|
||||
Assert.AreEqual(ExportFolderProblemKind.Missing, missing.Kind);
|
||||
}
|
||||
|
||||
internal static ExportMount Mount(string point, string root = "/", string type = "ext4", bool readOnly = false) =>
|
||||
new(Path.GetFullPath(point), root, type, readOnly);
|
||||
|
||||
|
||||
@@ -85,7 +85,8 @@ public sealed class MountInfoTests
|
||||
Assert.IsNull(MountInfoTable.FindContaining([], "/esporta"));
|
||||
|
||||
var proc = new ProcMountInfo(() => content);
|
||||
Assert.AreEqual(new ExportMount("/esporta/usb", "/", "exfat", false), proc.FindContaining("/esporta/usb/a"));
|
||||
Assert.AreEqual(new ExportMount("/esporta/usb", "/", "exfat", false, "8:49"), proc.FindContaining("/esporta/usb/a"));
|
||||
Assert.AreEqual("8:17", MountInfoTable.FindContaining(mounts, "/esporta")!.Device); // the device, for the identity test
|
||||
Assert.HasCount(4, proc.All());
|
||||
}
|
||||
}
|
||||
@@ -135,11 +135,20 @@ public sealed class ExportInterfaceTests
|
||||
using var temp = new TempFolder("esporta-selezione-ui");
|
||||
await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path));
|
||||
|
||||
// The three newest entries of the demo have four files still to copy.
|
||||
// The newest entries of marta.demo (general folder) with a file still to copy. The demo places its entries by the
|
||||
// hour it is built (decision of 26 November 2026), so how many files they have is asked of the plan, not assumed.
|
||||
await ui.OpenAsync(new Uri(demo.Address, "/libreria"));
|
||||
await ui.WaitAsync("document.querySelectorAll('.mosaico .tess').length >= 3", "il mosaico");
|
||||
await ui.WaitAsync("document.querySelector('.mosaico .tess') !== null", "il mosaico");
|
||||
var marta = (await ui.EvalAsync("fetch('/api/accounts').then((r) => r.json()).then((j) => j.accounts.find((a) => a.username === 'marta.demo').id)")).GetInt64();
|
||||
await ui.OpenAsync(new Uri(demo.Address, $"/libreria?copie=non-copiati&account={marta}"));
|
||||
await ui.WaitAsync("document.querySelectorAll('.mosaico .tess').length >= 1 && [...document.querySelectorAll('.mosaico .tess')].every((t) => t.dataset.id)", "il mosaico dei non ancora copiati");
|
||||
Assert.IsTrue((await ui.EvalAsync(ClickText(".strumenti", ".btn", "Seleziona"))).GetBoolean());
|
||||
await ui.EvalAsync("[...document.querySelectorAll('.mosaico .tess')].slice(0, 3).forEach((t) => t.click())");
|
||||
var files = (await ui.EvalAsync(
|
||||
"fetch('/api/export/plan', { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, "
|
||||
+ "body: JSON.stringify({ entryIds: [...document.querySelectorAll('.mosaico .tess')].slice(0, 3).map((t) => Number(t.dataset.id)), copyAgain: false }) })"
|
||||
+ ".then((r) => r.json()).then((j) => j.files)")).GetInt32();
|
||||
Assert.IsGreaterThan(0, files, "«Non ancora copiati» has files to copy");
|
||||
const string CopyIn = "[...document.querySelectorAll('.salva button')].find((b) => b.textContent.includes('Copia in'))";
|
||||
await ui.WaitAsync($"({CopyIn}) && !({CopyIn}).disabled", "«Copia in…» nella barra della scelta");
|
||||
await ui.EvalAsync($"({CopyIn}).click()");
|
||||
@@ -147,10 +156,10 @@ public sealed class ExportInterfaceTests
|
||||
const string Dialog = "document.querySelector('.dialogo.copia-in')";
|
||||
await ui.WaitAsync($"{Dialog}?.querySelector('.riepilogo-copia') != null", "il riepilogo");
|
||||
var summary = (await ui.EvalAsync($"{Dialog}.querySelector('.riepilogo-copia').textContent")).GetString()!;
|
||||
StringAssert.StartsWith(summary, "4 file", summary);
|
||||
StringAssert.StartsWith(summary, $"{files} file", summary);
|
||||
StringAssert.Contains(summary, "circa", "lo spazio");
|
||||
StringAssert.Contains((await ui.EvalAsync($"{Dialog}.querySelector('.destinazioni-copia').textContent")).GetString(), "In Disco USB");
|
||||
Assert.AreEqual("Copia 4 file", (await ui.EvalAsync($"{Dialog}.querySelector('footer .btn.primo').textContent.trim()")).GetString());
|
||||
Assert.AreEqual($"Copia {files} file", (await ui.EvalAsync($"{Dialog}.querySelector('footer .btn.primo').textContent.trim()")).GetString());
|
||||
|
||||
await ui.EvalAsync($"{Dialog}.querySelector('footer .btn.primo').click()");
|
||||
await ui.WaitAsync($"{Dialog} === null", "il dialogo si chiude");
|
||||
@@ -160,7 +169,7 @@ public sealed class ExportInterfaceTests
|
||||
// The job is in the Dashboard tab, finished: the demo copies at once.
|
||||
await ui.EvalAsync("document.querySelector('.brevi .breve a.breve-link').click()");
|
||||
await ui.WaitAsync("location.pathname === '/dashboard/esportazione' && document.querySelector('.esportazione-dashboard .elenco-attivita li') !== null", "la linguetta «Esportazione»");
|
||||
await ui.WaitAsync("document.querySelector('.esportazione-dashboard .elenco-attivita li').textContent.includes('4 di 4 file')", "il lavoro di 4 file " + ui.Report());
|
||||
await ui.WaitAsync($"document.querySelector('.esportazione-dashboard .elenco-attivita li').textContent.includes('{files} di {files} file')", $"il lavoro di {files} file " + ui.Report());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -223,7 +232,17 @@ public sealed class ExportInterfaceTests
|
||||
await ui.WaitAsync("document.querySelector('.strumenti .modo-mosaico [data-value=files]') !== null && document.querySelector('.mosaico .tess') !== null", "la Libreria con «Tolti o superati»");
|
||||
await ui.EvalAsync("document.querySelector('.strumenti .modo-mosaico [data-value=files]').click()");
|
||||
await ui.WaitAsync("document.querySelector('.strumenti .modo-mosaico [aria-checked=true]').dataset.value === 'files' && document.querySelector('.mosaico .tess') !== null", "«Tutte le foto»");
|
||||
await ui.EvalAsync("document.querySelector('.mosaico .tess').click()");
|
||||
|
||||
// The first of those files that is on disk (the demo shares the bytes of a picture with a video that has no file,
|
||||
// and which comes first depends on the hour the demo is built): «Copia in…» is offered only for a file on disk.
|
||||
var target = (await ui.EvalAsync(
|
||||
"(async () => { const j = await (await fetch('/api/library?mode=files&copies=removedOrSuperseded&limit=1000')).json(); "
|
||||
+ "for (const tile of j.tiles) { if (!tile.cover) continue; const e = await (await fetch('/api/entries/' + tile.id)).json(); "
|
||||
+ "const m = e.media.find((x) => x.id === tile.cover.mediaId); if (m && m.available) return tile.cover.mediaId; } return 0; })()")).GetInt64();
|
||||
Assert.IsGreaterThan(0L, target, "a «tolto o superato» file on disk");
|
||||
var tile = $"document.querySelector('.mosaico .tess[data-id=\"{target}\"]')";
|
||||
await ui.WaitAsync($"{tile} !== null", "la tessera del file");
|
||||
await ui.EvalAsync($"{tile}.click()");
|
||||
|
||||
await ui.WaitAsync("document.querySelector('.vis .riga-copia') !== null", "le righe «Copia» del visualizzatore " + ui.Report());
|
||||
var row = (await ui.EvalAsync("document.querySelector('.vis .riga-copia').textContent")).GetString()!;
|
||||
|
||||
Reference in new issue
Block a user