E2: motore delle copie esterne (porta, destinazioni, piano, copia)

Prima metà della tappa E2 «Copie esterne» (#58), parte Core e Data:

- porta del lavoro lungo: importazione, copia e ricostruzione mai insieme;
- radice /esporta in Docker con mountinfo, controllo delle cartelle con
  il file di prova, destinazioni con «Esporta questo account» acceso se
  Alberto non ha mai scelto (decisione del 27/11/2026);
- filtro «Copie», segni delle tessere e conteggi dell'account sui soli
  file dovuti (D3);
- percorsi «Come la libreria», segmento dell'account nella cartella
  generale, 240 caratteri, storia in evidenza;
- piano di «Copia in…», un lavoro per destinazione, copia in .part con
  SHA-256 riletto dal disco, nome libero, mai sovrascrivere, adozione
  per percorso, pausa della destinazione su prova, spazio e FAT32,
  attesa fuori dalle sessioni del motore, ripresa e recupero;
- .part rimossi solo nelle cartelle degli elementi di lavori non finiti;
- «Tolto» e «Superato» (agganci in importazione, scaricamenti,
  doppioni e ricostruzione), mai ricopiati da soli;
- rapporti e testi in italiano, prove del lavoro di copia.

Interfaccia, API e composizione restano alla parte successiva.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-27 10:55:29 +01:00
1 parent 213b89a618
commit a112c92893
41 files changed
+5370 -27

No files matched your search

@@ -0,0 +1,124 @@
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Storage;
using Febe.Data;
using Febe.Tests.Data;
using Febe.Tests.Support;
namespace Febe.Tests.Export;
/// <summary>
/// The «Copie» filter, the tile marks, the account counts and the store lookups of tappa E2 on a small real database
/// (decision D3: only due files count). WP5 of tappa E2 adds the full set and the timings over 200,000 entries.
/// </summary>
[TestClass]
public sealed class ExportCopiesFilterTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public async Task TheCopiesFilterSplitsDueFilesIntoCopiedNotCopiedAndRemoved()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await ExportWorld.CreateAsync(db);
// A post of marta.demo with two photos: only the first is copied («Copiato in parte»).
var pair = await db.Entries.AddAsync(
Make.Entry(w.Marta, "777", Make.T0.AddDays(1)),
[Make.Stored(Make.Photo(1), Make.Sha(2), "post/b1.jpg"), Make.Stored(Make.Photo(2), Make.Sha(3), "post/b2.jpg")],
ct);
var pairEntry = pair.Stored.Entry.Id;
// Marta's own folder has her shared post and the first photo of the pair; luca.demo's tagged post was copied
// in the general folder and then removed from it.
await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own), ct);
await db.Exports.AddCopyAsync(w.WholeCopy("b1.jpg", destination: w.Own, media: pair.Stored.Media[0].Id) with { SourceSha256 = Make.Sha(2), CopySha256 = Make.Sha(2) }, ct);
var removed = await db.Exports.AddCopyAsync(
w.WholeCopy("luca.demo/a.jpg", destination: w.General, account: w.Luca, media: w.LucaMedia) with { State = ExportCopyState.Removed },
ct);
Assert.IsTrue(AreSame([w.MartaEntry], await EntriesAsync(db, LibraryCopiesFilter.Copied, ct)));
Assert.IsTrue(AreSame([pairEntry], await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct)));
Assert.IsTrue(AreSame([w.LucaEntry], await EntriesAsync(db, LibraryCopiesFilter.RemovedOrSuperseded, ct)));
Assert.AreEqual(new LibraryTotals(1, 1), await db.Entries.GetLibraryTotalsAsync(new LibraryFilter { Copies = LibraryCopiesFilter.Copied }, ct));
Assert.AreEqual(1, (await db.Entries.CountLibraryByDayAsync(new LibraryFilter { Copies = LibraryCopiesFilter.NotCopied }, TestZones.Rome, ct: ct)).Sum(d => d.Count));
// «Tutte le foto» judges each file: the copied photo of the pair is «Copiato», the other «Non ancora copiato».
var copiedFiles = await FilesAsync(db, LibraryCopiesFilter.Copied, ct);
Assert.IsTrue(AreSame([w.MartaMedia, pair.Stored.Media[0].Id], copiedFiles));
Assert.IsTrue(AreSame([pair.Stored.Media[1].Id], await FilesAsync(db, LibraryCopiesFilter.NotCopied, ct)));
Assert.AreEqual(2, (await db.Entries.CountLibraryByDayAsync(new LibraryFilter { Copies = LibraryCopiesFilter.Copied }, TestZones.Rome, MosaicMode.Files, ct)).Sum(d => d.Count));
Assert.AreEqual(2, (await db.Entries.CountLibraryByDayAsync(new LibraryFilter { Copies = LibraryCopiesFilter.Copied, AccountIds = [w.Marta] }, TestZones.Rome, MosaicMode.Files, ct)).Sum(d => d.Count));
Assert.AreEqual(0, (await db.Entries.CountLibraryByDayAsync(new LibraryFilter { Copies = LibraryCopiesFilter.Copied, AccountIds = [w.Luca] }, TestZones.Rome, MosaicMode.Files, ct)).Sum(d => d.Count));
var marks = await db.Exports.GetEntryMarksAsync([w.MartaEntry, w.LucaEntry, pairEntry], ct);
Assert.AreEqual(ExportMark.Copied, marks[w.MartaEntry]);
Assert.AreEqual(ExportMark.None, marks[w.LucaEntry]);
Assert.AreEqual(ExportMark.Partly, marks[pairEntry]);
var fileMarks = await db.Exports.GetFileMarksAsync([.. pair.Stored.Media.Select(m => m.Id)], ct);
Assert.AreEqual(ExportMark.Copied, fileMarks[pair.Stored.Media[0].Id]);
Assert.AreEqual(ExportMark.None, fileMarks[pair.Stored.Media[1].Id]);
Assert.AreEqual(new ExportAccountCounts(3, 1, 0, 0), await db.Exports.CountAccountFilesAsync(w.Marta, ct));
Assert.AreEqual(new ExportAccountCounts(1, 0, 1, 0), await db.Exports.CountAccountFilesAsync(w.Luca, ct));
// «Esporta questo account» off: marta.demo has no due files any more.
await db.Exports.SetAccountExportEnabledAsync(w.Marta, false, ct);
Assert.IsEmpty(await EntriesAsync(db, LibraryCopiesFilter.Copied, ct));
Assert.IsEmpty(await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct));
Assert.AreEqual(new ExportAccountCounts(0, 0, 0, 0), await db.Exports.CountAccountFilesAsync(w.Marta, ct));
Assert.IsFalse((await db.Exports.GetEntryMarksAsync([w.MartaEntry], ct)).ContainsKey(w.MartaEntry));
var switches = await db.Exports.ListAccountExportSwitchesAsync(ct);
Assert.IsFalse(switches[w.Marta]);
Assert.IsFalse(switches.ContainsKey(w.Luca));
// «Controlla le copie» turns a Copied row into Removed.
Assert.AreEqual(1, await db.Exports.MarkCopiesRemovedAsync([removed.Id, (await db.Exports.FindCurrentCopyAsync(new ExportCopyIdentity(w.Own, w.Marta, Make.Sha(1), ExportVariant.Whole, ExportFormat.Original, null), ct))!.Id], Make.T0.AddDays(2), ct));
}
[TestMethod]
public async Task TheStoreAnswersThePlannerLookups()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await ExportWorld.CreateAsync(db);
var copy = await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own), ct);
await db.Exports.AddCopyAsync(
w.WholeCopy("luca.demo/old.jpg", destination: w.General, account: w.Luca, media: w.LucaMedia) with
{
SourceSha256 = Make.Sha(9),
CopySha256 = Make.Sha(9),
State = ExportCopyState.Superseded,
SupersededBySha256 = Make.Sha(1),
},
ct);
var states = await db.Exports.GetCopyStatesAsync(w.General, [(w.Luca, Make.Sha(1)), (w.Marta, Make.Sha(1))], ct);
Assert.AreEqual(ExportCopyState.Superseded, states[(w.Luca, Make.Sha(1))]);
Assert.IsFalse(states.ContainsKey((w.Marta, Make.Sha(1))));
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);
var byAccount = await db.Exports.ListCandidatesAsync(new ExportSelection.Account(w.Marta), 0, 10, ct);
Assert.AreEqual(w.MartaMedia, byAccount.Single().MediaId);
Assert.AreEqual(EntryKind.Post, byAccount[0].EntryKind);
var byFilter = await db.Exports.ListCandidatesAsync(new ExportSelection.Filter(new LibraryFilter(), MosaicMode.Files), 0, 10, ct);
Assert.HasCount(2, byFilter);
Assert.AreEqual(w.LucaMedia, (await db.Exports.ListCandidatesAsync(new ExportSelection.Entries([w.LucaEntry, w.MartaEntry]), w.MartaMedia, 10, ct)).Single().MediaId);
Assert.AreEqual(w.MartaMedia, (await db.Exports.ListCandidatesAsync(new ExportSelection.Media([w.MartaMedia, w.LucaMedia]), 0, 1, ct)).Single().MediaId);
var run = await db.Exports.CreateRunAsync(new ExportRun { DestinationId = w.General, StartedAt = Make.T0 }, ct);
Assert.AreEqual(run.Id, (await db.Exports.ListRecentRunsAsync(5, ct)).Single().Id);
}
private static async Task<List<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)];
private static async Task<List<long>> FilesAsync(FebeDatabase db, LibraryCopiesFilter filter, CancellationToken ct) =>
[.. (await db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = new LibraryFilter { Copies = filter }, Mode = MosaicMode.Files }, ct)).Tiles.Select(t => t.CoverMediaId!.Value)];
private static bool AreSame(IEnumerable<long> expected, IEnumerable<long> actual) => expected.Order().SequenceEqual(actual.Order());
}
@@ -0,0 +1,358 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
using Febe.Tests.Support;
namespace Febe.Tests.Export;
/// <summary>
/// The copy job of tappa E2 (WP1b) on a real library and real folders: paths, never overwriting, adoption by path,
/// «Tolto» and «Copia di nuovo», pause of a missing destination, engine sessions, leftovers and «Superato». WP5 adds
/// the full set.
/// </summary>
[TestClass]
public sealed class ExportCopyJobTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public async Task ACopyGoesUnderTheAccountSegmentAndIsNotWrittenTwice()
{
var ct = TestContext.CancellationToken;
await using var w = await World.CreateAsync();
var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "777", Make.T0.AddDays(-1)), [TestFile.Photo(1, 1), TestFile.Photo(2, 2)]);
var usb = await w.GeneralAsync(ct);
var plan = await w.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct);
Assert.AreEqual(2, plan.Files);
Assert.AreEqual(usb.Id, plan.Destinations.Single().DestinationId);
Assert.IsNull(plan.Destinations.Single().Problem);
var start = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct);
await w.Service.WaitAsync(ct);
var run = (await w.Library.Db.Exports.GetRunAsync(start.Runs.Single().Id, ct))!;
Assert.AreEqual(ExportRunState.Completed, run.State, run.LastError);
foreach (var media in post.Media)
{
var copied = Path.Combine(w.Usb, "marta.demo", LibraryLayout.ToPlatform(media.RelativePath!));
Assert.IsTrue(File.Exists(copied), copied);
CollectionAssert.AreEqual(await File.ReadAllBytesAsync(w.Library.Layout.FullPath(w.Marta, media.RelativePath!), ct), await File.ReadAllBytesAsync(copied, ct));
}
Assert.IsEmpty(Directory.GetFiles(w.Usb, "*.part", SearchOption.AllDirectories));
var report = await w.Service.Reports.BuildAsync(run.Id, ct);
Assert.AreEqual(2, report.ByState[ExportItemState.Copied]);
Assert.AreEqual(2, report.Accounts.Single().Copied);
// Nothing is written twice: the plan says «già copiati», a second job finds them.
var again = await w.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct);
Assert.AreEqual(0, again.Files);
Assert.AreEqual(2, again.AlreadyCopied);
var second = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Entries([post.Entry.Id])), ct);
await w.Service.WaitAsync(ct);
Assert.AreEqual(2, (await w.Library.Db.Exports.GetRunSummaryAsync(second.Runs.Single().Id, ct)).ByState[ExportItemState.AlreadyCopied]);
Assert.HasCount(2, Directory.GetFiles(w.Usb, "*", SearchOption.AllDirectories));
}
[TestMethod]
public async Task ARemovedCopyIsNotCopiedAgainUnlessAsked()
{
var ct = TestContext.CancellationToken;
await using var w = await World.CreateAsync();
var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "778", Make.T0.AddDays(-1)), [TestFile.Photo(1, 3)]);
await w.GeneralAsync(ct);
var request = new ExportJobRequest(new ExportSelection.Account(w.Marta.Id));
await w.Service.StartAsync(request, ct);
await w.Service.WaitAsync(ct);
var copy = Path.Combine(w.Usb, "marta.demo", LibraryLayout.ToPlatform(post.Media[0].RelativePath!));
File.Delete(copy); // Alberto removed it from the disk
var skipped = await w.Service.StartAsync(request, ct);
await w.Service.WaitAsync(ct);
var item = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = skipped.Runs.Single().Id }, ct)).Single();
Assert.AreEqual(ExportItemState.Skipped, item.State);
Assert.AreEqual(ExportText.Notes.Removed, item.Note);
Assert.IsFalse(File.Exists(copy));
var plan = await w.Service.PlanAsync(request, ct);
Assert.AreEqual((0, 1), (plan.Files, plan.RemovedOrSuperseded));
var again = await w.Service.StartAsync(request with { CopyAgain = true }, ct);
await w.Service.WaitAsync(ct);
Assert.AreEqual(1, again.Plan.Files);
Assert.AreEqual(ExportItemState.Copied, (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = again.Runs.Single().Id }, ct)).Single().State);
Assert.IsTrue(File.Exists(copy));
}
[TestMethod]
public async Task AFileAlreadyThereIsAdoptedAndAnotherFileIsNeverOverwritten()
{
var ct = TestContext.CancellationToken;
await using var w = await World.CreateAsync();
var first = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "779", Make.T0.AddDays(-1)), [TestFile.Photo(1, 4)]);
var second = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "780", Make.T0.AddDays(-2)), [TestFile.Photo(1, 5)]);
await w.GeneralAsync(ct);
var same = Path.Combine(w.Usb, "marta.demo", LibraryLayout.ToPlatform(first.Media[0].RelativePath!));
var other = Path.Combine(w.Usb, "marta.demo", LibraryLayout.ToPlatform(second.Media[0].RelativePath!));
Directory.CreateDirectory(Path.GetDirectoryName(same)!);
Directory.CreateDirectory(Path.GetDirectoryName(other)!);
File.Copy(w.Library.Layout.FullPath(w.Marta, first.Media[0].RelativePath!), same);
await File.WriteAllBytesAsync(other, [1, 2, 3], ct); // something else with that name
var start = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct);
await w.Service.WaitAsync(ct);
var items = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = start.Runs.Single().Id }, ct)).ToDictionary(i => i.MediaId!.Value);
Assert.AreEqual(ExportItemState.Adopted, items[first.Media[0].Id].State);
Assert.AreEqual(ExportItemState.Copied, items[second.Media[0].Id].State);
Assert.AreEqual(ExportText.Notes.NameTaken, items[second.Media[0].Id].Note);
CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, await File.ReadAllBytesAsync(other, ct));
var renamed = Path.Combine(w.Usb, LibraryLayout.ToPlatform(items[second.Media[0].Id].RelativePath!));
StringAssert.EndsWith(renamed, " (2).jpg");
Assert.IsTrue(File.Exists(renamed));
Assert.AreEqual(ExportCopyOrigin.Adopted, (await w.Library.Db.Exports.GetCopyAsync(items[first.Media[0].Id].CopyId!.Value, ct))!.Origin);
}
[TestMethod]
public async Task AMissingDestinationPausesAndIsNeverCreated()
{
var ct = TestContext.CancellationToken;
await using var w = await World.CreateAsync();
await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "781", Make.T0.AddDays(-1)), [TestFile.Photo(1, 6)]);
var usb = await w.GeneralAsync(ct);
Directory.Delete(w.Usb); // the disk was unplugged
var plan = await w.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct);
Assert.IsNotNull(plan.Destinations.Single().Problem);
var start = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct);
await w.Service.WaitAsync(ct);
var run = (await w.Library.Db.Exports.GetRunAsync(start.Runs.Single().Id, ct))!;
Assert.AreEqual(ExportRunState.Paused, run.State);
Assert.IsFalse(Directory.Exists(w.Usb));
var paused = (await w.Library.Db.Exports.GetDestinationAsync(usb.Id, ct))!;
Assert.IsNotNull(paused.PausedAt);
Assert.Contains("non è raggiungibile", paused.LastError!);
Assert.AreEqual(ExportItemState.Pending, (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = run.Id }, ct)).Single().State);
// The disk is back: «Riprendi» clears the pause and copies.
Directory.CreateDirectory(w.Usb);
await w.Service.ResumeAsync(null, ct);
await w.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Completed, (await w.Library.Db.Exports.GetRunAsync(run.Id, ct))!.State);
Assert.IsNull((await w.Library.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
}
[TestMethod]
public async Task CopiesWaitForTheEngineSessionAndForSpace()
{
var ct = TestContext.CancellationToken;
var session = new CountedSession(3);
var disk = new FakeDisk();
await using var w = await World.CreateAsync(session, disk);
await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "782", Make.T0.AddDays(-1)), [TestFile.Photo(1, 7)]);
await w.GeneralAsync(ct);
var before = w.Library.Clock.Now;
disk.Free = 1000; // less than the file plus 64 MB
var start = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct);
await w.Service.WaitAsync(ct);
var run = (await w.Library.Db.Exports.GetRunAsync(start.Runs.Single().Id, ct))!;
Assert.AreEqual(ExportRunState.Paused, run.State);
Assert.Contains("margine di 64 MB", run.LastError!);
Assert.AreEqual(w.Library.Clock.Now, before + TimeSpan.FromSeconds(15)); // three polls of 5 s while the session ran
disk.Free = null;
disk.Max = 10; // a FAT32 disk, with a tiny limit for the test
await w.Service.ResumeAsync([run.Id], ct);
await w.Service.WaitAsync(ct);
var item = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = run.Id }, ct)).Single();
Assert.AreEqual(ExportItemState.Failed, item.State);
Assert.AreEqual(ExportText.Notes.TooLargeForFileSystem, item.Note);
Assert.AreEqual(ExportRunState.Completed, (await w.Library.Db.Exports.GetRunAsync(run.Id, ct))!.State);
Assert.AreEqual(ExportCopyState.Failed, (await w.Library.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!.State);
}
[TestMethod]
public async Task LeftoversGoOnlyInTheFoldersOfAnUnfinishedJob()
{
var ct = TestContext.CancellationToken;
await using var w = await World.CreateAsync();
var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "783", Make.T0.AddDays(-1)), [TestFile.Photo(1, 8)]);
var usb = await w.GeneralAsync(ct);
var relative = "marta.demo/" + post.Media[0].RelativePath;
var folder = Path.GetDirectoryName(Path.Combine(w.Usb, LibraryLayout.ToPlatform(relative)))!;
Directory.CreateDirectory(folder);
var leftover = Path.Combine(folder, ".febe-0123456789ab.part");
var elsewhere = Path.Combine(w.Usb, ".febe-ba9876543210.part");
await File.WriteAllBytesAsync(leftover, [9], ct);
await File.WriteAllBytesAsync(elsewhere, [9], ct);
// A job interrupted after it recorded the target path.
var run = await w.Library.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, State = ExportRunState.Running, StartedAt = w.Library.Clock.Now }, ct);
await w.Library.Db.Exports.AddItemsAsync([new ExportItem { RunId = run.Id, MediaId = post.Media[0].Id, AccountId = w.Marta.Id, SourceSha256 = post.Media[0].Sha256 }], ct);
var item = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = run.Id }, ct)).Single();
await w.Library.Db.Exports.UpdateItemsAsync([item with { RelativePath = relative }], ct);
Assert.AreEqual(1, await w.Service.RecoverAsync(ct));
await w.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Interrupted, (await w.Library.Db.Exports.GetRunAsync(run.Id, ct))!.State);
Assert.IsFalse(File.Exists(leftover));
Assert.IsTrue(File.Exists(elsewhere)); // the root holds no item: never cleaned
await w.Service.ResumeAsync(null, ct);
await w.Service.WaitAsync(ct);
Assert.AreEqual(ExportItemState.Copied, (await w.Library.Db.Exports.GetItemAsync(item.Id, ct))!.State);
}
[TestMethod]
public async Task ASwitchedOffAccountIsSkippedWhenAJobResumes()
{
var ct = TestContext.CancellationToken;
await using var w = await World.CreateAsync();
var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "786", Make.T0.AddDays(-1)), [TestFile.Photo(1, 11)]);
var usb = await w.GeneralAsync(ct);
var run = await w.Library.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, State = ExportRunState.Interrupted, StartedAt = w.Library.Clock.Now }, ct);
await w.Library.Db.Exports.AddItemsAsync([new ExportItem { RunId = run.Id, MediaId = post.Media[0].Id, AccountId = w.Marta.Id, SourceSha256 = post.Media[0].Sha256 }], ct);
await w.Service.Destinations.SetAccountEnabledAsync(w.Marta.Id, false, ct);
await w.Service.ResumeAsync([run.Id], ct);
await w.Service.WaitAsync(ct);
var item = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = run.Id }, ct)).Single();
Assert.AreEqual((ExportItemState.Skipped, ExportText.Notes.NotExported), (item.State, item.Note));
Assert.IsEmpty(Directory.GetFiles(w.Usb, "*", SearchOption.AllDirectories));
}
[TestMethod]
public async Task AChangedLibraryFileSupersedesItsCopies()
{
var ct = TestContext.CancellationToken;
await using var w = await World.CreateAsync();
var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "784", Make.T0.AddDays(-1)), [TestFile.Photo(1, 9)]);
await w.GeneralAsync(ct);
var request = new ExportJobRequest(new ExportSelection.Account(w.Marta.Id));
await w.Service.StartAsync(request, ct);
await w.Service.WaitAsync(ct);
// «Tieni il più grande» put another file in the slot.
var oldSha = post.Media[0].Sha256!;
var newSha = Make.Sha(4242);
await w.Library.Db.Media.MarkStoredAsync(post.Media[0].Id, new StoredFile(post.Media[0].RelativePath!, 10, newSha, null, 1, 1, null, false), MediaState.Downloaded, w.Library.Clock.Now, ct);
Assert.AreEqual(0, await ExportSupersession.FileChangedAsync(w.Library.Db, w.Marta.Id, newSha, newSha, w.Library.Clock.Now, ct));
Assert.AreEqual(1, await ExportSupersession.FileChangedAsync(w.Library.Db, w.Marta.Id, oldSha, newSha, w.Library.Clock.Now, ct));
var copies = await w.Library.Db.Exports.ListCopiesBySha256Async(newSha, ct);
Assert.AreEqual(ExportCopyState.Superseded, copies.Single().State);
Assert.AreEqual(1, (await w.Service.PlanAsync(request, ct)).RemovedOrSuperseded);
}
[TestMethod]
public async Task AnExportDoesNotStartWhileAnImportHoldsTheGate()
{
var ct = TestContext.CancellationToken;
var gate = new LongWorkGate();
await using var w = await World.CreateAsync(gate: gate);
await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "785", Make.T0.AddDays(-1)), [TestFile.Photo(1, 10)]);
await w.GeneralAsync(ct);
Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var lease, out _));
var refused = await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct));
Assert.StartsWith("C'è un'importazione al lavoro", refused.Message);
Assert.IsEmpty(await w.Library.Db.Exports.ListRunsAsync(ct));
lease.Dispose();
}
[TestMethod]
public void PathsFollowTheLibraryTheAccountSegmentAndTheHighlightRule()
{
var naming = LibraryNaming.Default;
var account = Make.Account("marta.demo") with { Id = 1 };
var general = new ExportDestination { Id = 1, Scope = ExportScope.General, RootPath = Path.GetTempPath(), ContentTypes = ContentTypes.All, CreatedAt = Make.T0 };
var story = Make.Entry(1, "9001", Make.T0, EntryKind.Story);
var media = Make.Stored(Make.Photo(), Make.Sha(1), "storie/2026/x.jpg");
var asStory = ExportPaths.Segments(general, naming, account, story, media, "Estate", inHighlight: true, TestZones.Rome);
Assert.AreEqual("marta.demo", asStory[0]);
Assert.AreEqual("storie", asStory[1]);
var onlyHighlights = general with { Scope = ExportScope.Account, AccountId = 1, ContentTypes = ContentTypes.Highlights };
var asHighlight = ExportPaths.Segments(onlyHighlights, naming, account, story, media, "Estate", inHighlight: true, TestZones.Rome);
CollectionAssert.AreEqual(new[] { "evidenza", "Estate" }, asHighlight.Take(2).ToArray());
var imported = media with { RelativePath = "importati/IMG_0001.JPG" };
CollectionAssert.AreEqual(new[] { "marta.demo", "importati", "IMG_0001.JPG" }, ExportPaths.Segments(general, naming, account, story, imported, null, false, TestZones.Rome).ToArray());
var renamed = ExportPaths.Segments(general with { NamingScheme = @"{anno}\{codice}_{n}" }, naming, account, story, imported, null, false, TestZones.Rome);
CollectionAssert.AreEqual(new[] { "marta.demo", "2026", "9001_1.jpg" }, renamed.ToArray());
var deep = general with { RootPath = Path.Combine(Path.GetTempPath(), new string('d', 150)) };
var fitted = ExportPaths.RelativePathFor(deep, ["marta.demo", new string('x', 120) + ".jpg"]);
Assert.IsLessThanOrEqualTo(240, Path.TrimEndingDirectorySeparator(deep.RootPath).Length + 1 + fitted.Length);
StringAssert.EndsWith(fitted, ".jpg");
}
private sealed class CountedSession(int polls) : IEngineSessionState
{
private int _left = polls;
public bool InSession => Interlocked.Decrement(ref _left) >= 0;
}
private sealed class FakeDisk : IExportDisk
{
public long? Free { get; set; }
public long? Max { get; set; }
public long? FreeBytes(string root) => Free;
public long? MaxFileBytes(string root) => Max;
}
private sealed class World : IAsyncDisposable
{
private readonly TempFolder _temp;
private World(TempFolder temp, TestLibrary library, ExportService service, Account marta)
{
_temp = temp;
Library = library;
Service = service;
Marta = marta;
Usb = temp.Combine("usb");
Directory.CreateDirectory(Usb);
}
public TestLibrary Library { get; }
public ExportService Service { get; }
public Account Marta { get; }
public string Usb { get; }
public static async Task<World> CreateAsync(IEngineSessionState? session = null, IExportDisk? disk = null, LongWorkGate? gate = null)
{
var temp = new TempFolder();
var library = await TestLibrary.CreateAsync(temp);
var marta = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100"));
var env = new ExportEnvironment
{
Storage = library.Db,
Layout = () => library.Layout,
DataFolder = library.Data.Root,
Clock = library.Clock,
Root = ExportRootOptions.AnyFolder with { Mounts = new ProcMountInfo(() => null) },
Disk = disk ?? new FakeDisk(),
Session = session ?? NoEngineSession.Instance,
Gate = gate,
};
return new World(temp, library, new ExportService(env), marta);
}
public async Task<ExportDestination> GeneralAsync(CancellationToken ct) =>
(await Service.Destinations.CreateAsync(new DestinationSpec(ExportScope.General, null, Usb, "Disco USB", ContentTypes.All, null, null, null), ct)).Destination;
public async ValueTask DisposeAsync()
{
await Service.DisposeAsync();
await Library.DisposeAsync();
_temp.Dispose();
}
}
}
@@ -0,0 +1,172 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Import;
using Febe.Core.Library;
using Febe.Tests.Import.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Export;
/// <summary>
/// The shared pieces of tappa E2 (WP1a): the gate of long work, the mount table, the export root in Docker, the folder
/// check with its probe, the destinations with «Esporta questo account» on by default. WP5 adds the full set.
/// </summary>
[TestClass]
public sealed class ExportFoundationTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public void TheGateLetsOneLongJobRunAtATime()
{
var gate = new LongWorkGate();
Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var lease, out _));
Assert.AreEqual(LongWorkKind.Import, gate.Busy);
Assert.IsFalse(gate.TryEnter(LongWorkKind.Export, out _, out var busy));
Assert.AreEqual(LongWorkKind.Import, busy);
Assert.AreEqual(
"C'è un'importazione al lavoro: aspetta che finisca o interrompila, poi copia.",
LongWorkGate.BusyMessage(LongWorkKind.Export, busy!.Value));
lease.Dispose();
Assert.IsNull(gate.Busy);
Assert.IsTrue(gate.TryEnter(LongWorkKind.Rebuild, out var rebuild, out _));
lease.Dispose(); // a second dispose of the old lease releases nothing
Assert.AreEqual(LongWorkKind.Rebuild, gate.Busy);
rebuild.Dispose();
}
[TestMethod]
public async Task AnImportDoesNotStartWhileTheGateIsHeld()
{
using var temp = new TempFolder();
await using var bed = await ImportTestBed.CreateAsync(temp);
var gate = new LongWorkGate();
await using var service = new ImportService(bed.Environment with { Gate = gate });
Assert.IsTrue(gate.TryEnter(LongWorkKind.Export, out var lease, out _));
var refused = await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => service.StartAsync(bed.Source, ct: TestContext.CancellationToken));
Assert.StartsWith("C'è una copia nelle cartelle esterne al lavoro", refused.Message);
Assert.IsEmpty(await bed.Library.Db.Imports.ListRunsAsync(TestContext.CancellationToken));
lease.Dispose();
var run = await service.StartAsync(bed.Source, ct: TestContext.CancellationToken);
await service.WaitAsync(run.Id, TestContext.CancellationToken);
Assert.IsNull(gate.Busy); // the job's lease went with it
}
[TestMethod]
public void MountInfoGivesRootMountPointAndType()
{
const string content = """
22 1 8:1 / / rw,relatime shared:1 - ext4 /dev/sda1 rw
40 22 8:17 /backup/foto /esporta/usb rw,noatime master:3 - vfat /dev/sdb1 rw
41 22 0:50 / /esporta/nas\040rete ro,relatime - cifs //nas/copie rw
bad line
""";
var mounts = MountInfoTable.Parse(content);
Assert.HasCount(3, mounts);
Assert.AreEqual("/esporta/nas rete", mounts[2].MountPoint);
Assert.IsTrue(mounts[2].ReadOnly);
Assert.AreEqual("/backup/foto", MountInfoTable.FindContaining(mounts, "/esporta/usb/Febe")!.Root);
Assert.AreEqual("vfat", MountInfoTable.FindContaining(mounts, "/esporta/usb")!.FileSystemType);
Assert.AreEqual("/", MountInfoTable.FindContaining(mounts, "/esporta/usbx")!.MountPoint);
var o = ExportRootOptions.Docker("/esporta", declared: true, new ProcMountInfo(() => content));
Assert.IsFalse(ExportRoots.Evaluate(o with { Declared = false }).Active);
Assert.IsFalse(ExportRoots.Evaluate(ExportRootOptions.Docker("/esporta", declared: true, new ProcMountInfo(() => "22 1 8:1 / / rw - ext4 /dev/sda1 rw"))).Active);
if (!OperatingSystem.IsWindows())
{
// Docker paths are Linux paths: on Windows "/esporta" becomes a drive path the table cannot hold.
Assert.IsTrue(ExportRoots.Evaluate(o).Active);
Assert.IsNull(ExportRoots.MountProblem(o, "/esporta/usb/Febe"));
Assert.Contains("sola lettura", ExportRoots.MountProblem(o, "/esporta/nas rete/x")!);
Assert.IsNotNull(ExportRoots.MountProblem(o, "/esporta/altro"));
}
Assert.AreEqual(ExportFolderProblemKind.ParentSegment, Assert.ThrowsExactly<ExportFolderException>(() => ExportRoots.Resolve(o, "usb/../../etc")).Kind);
Assert.AreEqual(ExportFolderProblemKind.ExportRootItself, Assert.ThrowsExactly<ExportFolderException>(() => ExportRoots.Resolve(o, "/")).Kind);
}
[TestMethod]
public async Task TheFolderCheckRefusesOverlapsAndLeavesNoProbe()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
var library = temp.Combine("libreria");
var data = temp.Combine("dati");
var outside = temp.Combine("copie");
Directory.CreateDirectory(Path.Combine(library, "marta.demo"));
Directory.CreateDirectory(data);
Directory.CreateDirectory(outside);
var context = new ExportFolderContext(
[new(data, ProtectedFolderKind.Data, null), new(library, ProtectedFolderKind.Library, null), new(Path.Combine(library, "marta.demo"), ProtectedFolderKind.Account, "marta.demo")],
ExportRootOptions.AnyFolder);
var check = new ExportFolderCheck(new ProcMountInfo(() => null));
var accepted = await check.CheckAsync(outside, context, ct);
Assert.IsTrue(accepted.Accepted, accepted.Problem?.Message);
Assert.IsEmpty(Directory.GetFileSystemEntries(outside));
Assert.AreEqual(ExportFolderProblemKind.InsideProtected, (await check.CheckAsync(Path.Combine(library, "marta.demo"), context with { Protected = context.Protected.Take(2).ToList() }, ct)).Problem!.Kind);
Assert.AreEqual(ExportFolderProblemKind.SameAsProtected, (await check.CheckAsync(data, context, ct)).Problem!.Kind);
Assert.AreEqual(ExportFolderProblemKind.ContainsProtected, (await check.CheckAsync(temp.Path, context, ct)).Problem!.Kind);
Assert.AreEqual(ExportFolderProblemKind.Missing, (await check.CheckAsync(temp.Combine("non-esiste"), context, ct)).Problem!.Kind);
Assert.AreEqual(ExportFolderProblemKind.NotFullyQualified, (await check.CheckAsync("relativa", context, ct)).Problem!.Kind);
Assert.AreEqual(ExportFolderProblemKind.RootOfDisk, (await check.CheckAsync(Path.GetPathRoot(temp.Path)!, context, ct)).Problem!.Kind);
Assert.IsFalse(Directory.Exists(temp.Combine("non-esiste")));
}
[TestMethod]
public async Task TheSafeWriterNeverCreatesAMissingRoot()
{
using var temp = new TempFolder();
var root = temp.Combine("disco-assente");
using var source = new MemoryStream([1, 2, 3]);
await Assert.ThrowsExactlyAsync<ExportRootMissingException>(() => new SafeFileWriter().SaveAsync(
source, root, "a/b.jpg", new SafeWriteOptions { RequireExistingRoot = true, VerifyFromDisk = true }, TestContext.CancellationToken));
Assert.IsFalse(Directory.Exists(root));
Directory.CreateDirectory(root);
source.Position = 0;
var saved = await new SafeFileWriter().SaveAsync(source, root, "a/b.jpg", new SafeWriteOptions { RequireExistingRoot = true, VerifyFromDisk = true }, TestContext.CancellationToken);
Assert.AreEqual("a/b.jpg", saved.RelativePath);
}
[TestMethod]
public async Task DestinationsAreCheckedAndTheSwitchIsOnByDefault()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var account = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100"), ct);
var env = new ExportEnvironment { Storage = library.Db, Layout = () => library.Layout, DataFolder = library.Data.Root, Clock = library.Clock, Root = ExportRootOptions.AnyFolder with { Mounts = new ProcMountInfo(() => null) } };
var destinations = new ExportDestinations(env);
var usb = temp.Combine("usb");
Directory.CreateDirectory(usb);
Assert.IsTrue((await destinations.ResolveAsync(account.Id, ct)) is { Enabled: true, HasDestination: false });
await Assert.ThrowsExactlyAsync<ExportFolderException>(() => destinations.CreateAsync(Spec(library.Layout.Root), ct));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => destinations.CreateAsync(Spec(usb) with { ContentTypes = ContentTypes.None }, ct));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => destinations.CreateAsync(Spec(usb) with { NamingScheme = "{inesistente}" }, ct));
var saved = await destinations.CreateAsync(Spec(usb) with { Label = " Disco USB " }, ct);
Assert.AreEqual("Disco USB", saved.Destination.Label);
var all = await destinations.ResolveAllAsync(ct);
Assert.AreEqual(saved.Destination.Id, all[account.Id].Destination!.Id);
Assert.IsTrue(all[account.Id].Exports);
await destinations.SetAccountEnabledAsync(account.Id, false, ct);
Assert.IsFalse((await destinations.ResolveAsync(account.Id, ct)).Exports);
var run = await library.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = saved.Destination.Id, StartedAt = library.Clock.Now }, ct);
await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => destinations.RetireAsync(saved.Destination.Id, ct));
await library.Db.Exports.UpdateRunAsync(run with { State = ExportRunState.Cancelled }, ct);
await destinations.RetireAsync(saved.Destination.Id, ct);
Assert.IsTrue(Directory.Exists(usb));
Assert.IsFalse((await destinations.ResolveAsync(account.Id, ct)).HasDestination);
Assert.IsEmpty(await destinations.RecheckAsync(null, ct));
static DestinationSpec Spec(string path) => new(ExportScope.General, null, path, null, ContentTypes.All, null, null, null);
}
}