Importazione e dati: «Tieni il più grande» per gruppi, righe di _febe.jsonl mai perse, ricostruzione robusta (import-1, import-2, library-1, journal-1, rebuild-1, rebuild-2, rebuild-3, backup-1)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-14 00:53:10 +00:00
1 parent 78c92eb2a4
commit 628fe5db2b
13 files changed
+1145 -95

No files matched your search

@@ -0,0 +1,175 @@
using System.Security.Cryptography;
using Febe.Core.Domain;
using Febe.Core.Import;
using Febe.Core.Library;
using Febe.Tests.Import.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Import;
/// <summary>«Tieni il più grande» when the source file is larger: it replaces the library file (rule 12, spec §9.3).</summary>
[TestClass]
public sealed class ImportReplacementTests
{
/// <summary>
/// Two versions of the same photo in the source (the original and a smaller export), both paired with one smaller
/// library file and both decided «Tieni il più grande»: only the largest takes its place, whatever the order of
/// the files, and with «Sposta» the larger original is never lost.
/// </summary>
[TestMethod]
[DataRow(ImportMode.Copy, true)]
[DataRow(ImportMode.Move, true)]
[DataRow(ImportMode.Copy, false)]
[DataRow(ImportMode.Move, false)]
public async Task TwoSourceFilesPairedWithTheSameLibraryFileLeaveOnlyTheLargest(ImportMode mode, bool largestFirst)
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
var (marta, library) = await bed.AccountWithPhotoAsync("marta.demo", "60", ImportTestFiles.Resized(60, 800, 600, 400, 300, 70));
var largest = ImportTestFiles.Photo(60, 800, 600, 92);
var export = ImportTestFiles.Resized(60, 800, 600, 600, 450, 80);
var largestPath = bed.Write(largestFirst ? "marta.demo/1-originale.jpg" : "marta.demo/2-originale.jpg", largest);
var exportPath = bed.Write(largestFirst ? "marta.demo/2-esportata.jpg" : "marta.demo/1-esportata.jpg", export);
var run = await bed.AnalyzeAsync();
await bed.Review.SetModeAsync(run.Id, mode);
var cases = await bed.Review.ListDuplicatesAsync(run.Id);
Assert.HasCount(2, cases);
Assert.IsTrue(cases.All(c => c.Existing.MediaId == library.Media[0].Id), "Both source files are paired with the library file.");
Assert.AreEqual(2, await bed.Review.DecideAsync(run.Id, cases[0].Pair.Id, DuplicateDecision.KeepLarger, DecisionScope.AllPending));
var plan = await bed.Review.GetPlanAsync(run.Id);
Assert.AreEqual(1, plan.ToReplace, "One library file, one replacement.");
Assert.AreEqual(1, plan.ToImport);
await bed.Copier.CopyAsync(run.Id);
var media = (await bed.Library.Db.Media.GetAsync(library.Media[0].Id))!;
var largestSha = Sha(largest);
Assert.AreEqual(largestSha, media.Sha256, "The library keeps the largest version.");
Assert.AreEqual((800, 600), (media.Width, media.Height));
var onDisk = bed.Library.Layout.FullPath(marta, media.RelativePath!);
Assert.AreEqual(largestSha, Sha(File.ReadAllBytes(onDisk)), "The record points to a file that exists and holds the largest version.");
var folder = bed.Library.Layout.AccountFolder(marta);
Assert.HasCount(1, Directory.GetFiles(folder, "*.jpg", SearchOption.AllDirectories), "One version in the library: no leftovers.");
var files = await bed.FilesAsync(run.Id);
var winner = files.Single(f => f.Sha256 == largestSha);
Assert.AreEqual(mode == ImportMode.Move ? ImportFileState.Moved : ImportFileState.Copied, winner.State, winner.LastError);
StringAssert.StartsWith(winner.LastError, ImportText.NoteReplaced);
Assert.AreEqual(media.RelativePath, winner.DestinationPath);
var loser = files.Single(f => f.Sha256 == Sha(export));
Assert.AreEqual(ImportFileState.Skipped, loser.State, "The smaller export never takes the place of the original.");
Assert.AreEqual(ImportText.NoteLargerInSource, loser.LastError);
Assert.AreEqual(mode == ImportMode.Copy, File.Exists(largestPath), "With «Sposta» the original goes only once its copy is verified.");
Assert.IsTrue(File.Exists(exportPath), "A skipped file is never deleted, not even with «Sposta».");
CollectionAssert.AreEqual(mode == ImportMode.Move ? new[] { largestPath } : Array.Empty<string>(), bed.FileSystem.Deleted);
var journal = await AccountJournal.ReadAsync(folder);
Assert.AreEqual(media.RelativePath, journal.Lines.Last(l => l.Entry.Id == "60").Files!.Single().Path);
// Running the copy again changes nothing.
await bed.Copier.CopyAsync(run.Id);
Assert.AreEqual(largestSha, (await bed.Library.Db.Media.GetAsync(media.Id))!.Sha256);
Assert.HasCount(1, Directory.GetFiles(folder, "*.jpg", SearchOption.AllDirectories));
}
/// <summary>
/// The plan compares sizes before the copy starts; the copy looks again at the file in the library right before
/// replacing it, and a larger file that arrived meanwhile stays.
/// </summary>
[TestMethod]
public async Task AReplacementNeverRemovesALargerFileThatArrivedMeanwhile()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
var (marta, library) = await bed.AccountWithPhotoAsync("marta.demo", "62", ImportTestFiles.Resized(62, 800, 600, 400, 300, 70));
bed.Write("marta.demo/a-altra.jpg", ImportTestFiles.Photo(63));
var candidate = bed.Write("marta.demo/b-grande.jpg", ImportTestFiles.Photo(62, 800, 600, 92));
var run = await bed.AnalyzeAsync();
var pair = (await bed.Review.ListDuplicatesAsync(run.Id)).Single();
await bed.Review.DecideAsync(run.Id, pair.Pair.Id, DuplicateDecision.KeepLarger);
Assert.AreEqual(1, (await bed.Review.GetPlanAsync(run.Id)).ToReplace);
// Right after the first file, a larger version of the photo takes the place of the library file.
var huge = ImportTestFiles.Photo(62, 1600, 1200, 92);
var hugeRelative = "post/arrivata-nel-frattempo.jpg";
var hugePath = bed.Library.Layout.FullPath(marta, hugeRelative);
var swapped = false;
var progress = new SyncProgress(p =>
{
if (swapped || p.Phase != ImportPhase.Copying || p.CurrentFile != "marta.demo/a-altra.jpg")
{
return;
}
swapped = true;
Directory.CreateDirectory(Path.GetDirectoryName(hugePath)!);
File.WriteAllBytes(hugePath, huge);
bed.Library.Db.Media.MarkStoredAsync(
library.Media[0].Id,
new StoredFile(hugeRelative, huge.Length, Sha(huge), null, 1600, 1200, null, false),
MediaState.Downloaded,
bed.Library.Clock.Now).GetAwaiter().GetResult();
});
await bed.Copier.CopyAsync(run.Id, progress);
Assert.IsTrue(swapped);
var media = (await bed.Library.Db.Media.GetAsync(library.Media[0].Id))!;
Assert.AreEqual(Sha(huge), media.Sha256, "The larger file stays in the library.");
Assert.IsTrue(File.Exists(hugePath));
var file = await bed.FileAsync(run.Id, "marta.demo/b-grande.jpg");
Assert.AreEqual(ImportFileState.Skipped, file.State);
Assert.AreEqual(ImportText.NoteLibraryLarger, file.LastError);
Assert.IsTrue(File.Exists(candidate));
}
/// <summary>
/// An imported entry without Instagram id (with only a code, or with nothing but its file) whose file is replaced
/// by a larger one: after losing the database the rebuild finds one entry with the new file, on every run.
/// </summary>
[TestMethod]
[DataRow(false)]
[DataRow(true)]
public async Task AReplacedImportedFileIsOneEntryAfterARebuild(bool withCode)
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
var marta = await bed.Library.Db.Accounts.AddAsync(Make.Account("marta.demo", "900"));
var name = withCode ? "2026-10-10_18-22-05_DBx3kQ2_1.jpg" : "IMG_0001.jpg";
var small = bed.Write("marta.demo/" + name, ImportTestFiles.Resized(64, 800, 600, 400, 300, 70));
await bed.Copier.CopyAsync((await bed.AnalyzeAsync()).Id);
var first = (await bed.Library.Db.Entries.ListByAccountAsync(marta.Id)).Single();
Assert.AreEqual(withCode ? "DBx3kQ2" : null, first.Code);
Assert.IsNull(first.InstagramId);
File.Delete(small);
bed.Write("marta.demo/originali/" + name, ImportTestFiles.Photo(64, 800, 600, 92));
var run = await bed.AnalyzeAsync();
var pair = (await bed.Review.ListDuplicatesAsync(run.Id)).Single();
await bed.Review.DecideAsync(run.Id, pair.Pair.Id, DuplicateDecision.KeepLarger);
await bed.Copier.CopyAsync(run.Id);
var replaced = (await bed.Library.Db.Media.ListByEntryAsync(first.Id)).Single();
Assert.AreEqual((800, 600), (replaced.Width, replaced.Height), "Replaced by the larger file.");
await bed.Library.LoseDatabaseAsync();
var rebuilder = new LibraryRebuilder(bed.Library.Db, bed.Library.Layout, bed.Library.Clock);
var report = await rebuilder.RebuildAsync();
Assert.AreEqual(1, report.EntriesCreated, string.Join("; ", report.Notes));
Assert.AreEqual(0, report.FilesMissing, "The replaced file is not reported as missing.");
var account = (await bed.Library.Db.Accounts.FindByInstagramIdAsync("900"))!;
var entry = (await bed.Library.Db.Entries.ListByAccountAsync(account.Id)).Single();
Assert.AreEqual(replaced.RelativePath, (await bed.Library.Db.Media.ListByEntryAsync(entry.Id)).Single().RelativePath);
Assert.AreEqual(0, (await rebuilder.RebuildAsync()).EntriesCreated, "A second run adds nothing.");
Assert.HasCount(1, await bed.Library.Db.Entries.ListByAccountAsync(account.Id));
}
private static string Sha(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes));
private sealed class SyncProgress(Action<ImportProgress> report) : IProgress<ImportProgress>
{
public void Report(ImportProgress value) => report(value);
}
}
@@ -89,6 +89,35 @@ public sealed class MediaReaderTests
Assert.IsNull(Mp4Reader.Read(new MemoryStream("not a movie at all"u8.ToArray()), Now));
}
/// <summary>
/// A 64-bit box size close to 2^63 overflows «offset + size»: the reader must stop on it, not walk backwards
/// forever (the analysis would hang and every «Riprendi» would hit the same file again).
/// </summary>
[TestMethod]
public void AHugeSixtyFourBitBoxSizeEndsTheReadingInsteadOfLooping()
{
static byte[] Box(string type, params byte[][] parts) =>
[.. BigEndian((uint)(8 + parts.Sum(p => p.Length))), .. Encoding.ASCII.GetBytes(type), .. parts.SelectMany(p => p)];
static byte[] BigEndian(uint value) => [(byte)(value >> 24), (byte)(value >> 16), (byte)(value >> 8), (byte)value];
byte[] huge = [0, 0, 0, 1, .. "xxxx"u8, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF8];
var ftyp = Box("ftyp", "isom"u8.ToArray(), [0, 0, 2, 0]);
// Inside moov: a valid «free» box, then the damaged one.
byte[] insideMoov = [.. ftyp, .. Box("moov", Box("free"), huge)];
// At the top level, after ftyp.
byte[] topLevel = [.. ftyp, .. huge, .. new byte[32]];
foreach (var (name, bytes) in new[] { ("moov", insideMoov), ("primo livello", topLevel) })
{
var reading = Task.Run(() => Mp4Reader.Read(new MemoryStream(bytes), Now));
Assert.IsTrue(reading.Wait(TimeSpan.FromSeconds(10)), $"{name}: la lettura deve finire.");
var info = reading.Result;
Assert.IsNull(info?.CreatedAt, name);
Assert.IsNull(info?.Width, name);
}
}
[TestMethod]
public void AnMp4MadeByFfmpegCarriesItsCreationTime()
{
+79 -2
View File
@@ -52,9 +52,14 @@ public sealed class DailyBackupTests
}
await File.WriteAllTextAsync(Path.Combine(folder, "appunti.txt"), "non toccare");
await File.WriteAllTextAsync(Path.Combine(folder, "febe-2026-10-13.sqlite.abcd1234.part"), "copia interrotta");
var clock = new ManualClock(LibraryTimes.Noon(today));
var interrupted = Path.Combine(folder, "febe-2026-10-12.sqlite.abcd1234.part");
await File.WriteAllTextAsync(interrupted, "copia interrotta");
File.SetLastWriteTimeUtc(interrupted, clock.Now.UtcDateTime.AddDays(-1));
var writing = Path.Combine(folder, "febe-2026-10-13.sqlite.ef567890.part");
await File.WriteAllTextAsync(writing, "copia in corso");
File.SetLastWriteTimeUtc(writing, clock.Now.UtcDateTime.AddMinutes(-2));
var backup = new DailyBackup(db.Maintenance, clock, folder);
var result = await backup.RunAsync();
@@ -64,9 +69,81 @@ public sealed class DailyBackupTests
Assert.AreEqual(today, kept[0]);
Assert.AreEqual(today.AddDays(-6), kept[^1]);
Assert.HasCount(5, result.Removed); // four old copies and the interrupted one
Assert.IsFalse(File.Exists(interrupted));
Assert.IsTrue(File.Exists(writing), "A temporary copy written minutes ago may belong to a copy still running.");
Assert.IsTrue(File.Exists(Path.Combine(folder, "appunti.txt")));
}
/// <summary>
/// «Fai una copia adesso» clicked twice, or clicked while the 3:20 copy runs: the copies take turns, and neither
/// one removes the temporary file of the other.
/// </summary>
[TestMethod]
public async Task TwoCopiesAtTheSameTimeBothSucceed()
{
using var temp = new TempFolder();
var folder = temp.Combine("dati", "copie");
var clock = new ManualClock(LibraryTimes.Noon(new DateOnly(2026, 10, 13)));
var database = new SlowBackups();
var first = new DailyBackup(database, clock, folder).RunNowAsync();
await database.FirstStarted.Task.WaitAsync(TimeSpan.FromSeconds(10));
var second = new DailyBackup(database, clock, folder).RunNowAsync();
await Task.WhenAny(second, Task.Delay(500)); // without turns, the second copy finishes here and its retention runs
database.ReleaseFirst.SetResult();
var results = await Task.WhenAll(first, second).WaitAsync(TimeSpan.FromSeconds(10));
Assert.IsTrue(results.All(r => r.Created is not null));
Assert.AreEqual(1, database.MaxConcurrent, "One copy of a folder at a time.");
Assert.HasCount(1, Directory.GetFiles(folder, "*.sqlite"));
Assert.IsEmpty(Directory.GetFiles(folder, "*.part"));
}
/// <summary>VACUUM INTO stand-in: the first copy waits until the test lets it finish.</summary>
private sealed class SlowBackups : Core.Storage.IDatabaseMaintenance
{
private int _calls;
private int _running;
private int _max;
public TaskCompletionSource FirstStarted { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TaskCompletionSource ReleaseFirst { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public int MaxConcurrent => Volatile.Read(ref _max);
public string DatabasePath => "febe.sqlite";
public int SchemaVersion => 1;
public async Task BackupToAsync(string destinationFile, CancellationToken ct = default)
{
var running = Interlocked.Increment(ref _running);
int seen;
while ((seen = Volatile.Read(ref _max)) < running && Interlocked.CompareExchange(ref _max, running, seen) != seen)
{
}
try
{
await File.WriteAllTextAsync(destinationFile, "copia", ct);
if (Interlocked.Increment(ref _calls) == 1)
{
FirstStarted.SetResult();
await ReleaseFirst.Task.WaitAsync(ct);
}
}
finally
{
Interlocked.Decrement(ref _running);
}
}
public Task<bool> CheckIntegrityAsync(CancellationToken ct = default) => Task.FromResult(true);
public Task OptimizeAsync(CancellationToken ct = default) => Task.CompletedTask;
}
[TestMethod]
public void RecognizesOnlyItsOwnFileNames()
{
@@ -0,0 +1,152 @@
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Downloads;
using Febe.Core.Domain;
using Febe.Core.Import;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Tests.Collection.Support;
using Febe.Tests.Import.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Library;
/// <summary>
/// Every saved entry gets its <c>_febe.jsonl</c> line (spec §8.5), also when the journal cannot be written at that moment
/// (a sync client holding it, a network share that dropped) and when the last file of an entry to settle is not stored.
/// A file already in the library is never treated as «nothing written».
/// </summary>
[TestClass]
public sealed class JournalBacklogTests
{
[TestMethod]
public async Task ADownloadedFileStaysInTheLibraryWhenTheJournalIsBusyAndItsLineFollows()
{
using var temp = new TempFolder("giornale");
await using var lib = await TestLibrary.CreateAsync(temp);
var account = await lib.Db.Accounts.AddAsync(Make.Account("marta.prova", "1001"));
await lib.SaveAsync(account, Make.Entry(account.Id, "prima", Make.T0.AddDays(-1)), [TestFile.Photo(1, 3)]);
var entryId = await AddAsync(lib.Db, account, "p1", Make.Photo() with { SourceUrl = "https://cdn.esempio/1.jpg" });
var queue = Queue(lib, temp, _ => (FetchOutcome.Completed, TestFile.PhotoBytes(21, 64, 80)));
var journal = AccountJournal.PathFor(lib.Layout.AccountFolder(account));
DownloadReport report;
await using (new FileStream(journal, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
report = await queue.RunOnceAsync(CancellationToken.None);
}
Assert.AreEqual(1, report.Stored, report.ToString());
var media = (await lib.Db.Media.ListByEntryAsync(entryId)).Single();
Assert.AreEqual(MediaState.Downloaded, media.State, "The file is in the library: it is not to download again.");
Assert.IsTrue(File.Exists(lib.Layout.FullPath(account, media.RelativePath!)));
Assert.AreEqual(EntryState.Downloaded, (await lib.Db.Entries.GetAsync(entryId))!.State, "It stays visible in the library.");
Assert.AreEqual(entryId.ToString(System.Globalization.CultureInfo.InvariantCulture), await lib.Db.Settings.GetAsync(LibraryIngest.PendingJournalKey));
Assert.IsTrue((await lib.Db.Events.ListAfterAsync(0)).Any(e => e.Code == "giornale-in-sospeso"));
Assert.IsFalse((await AccountJournal.ReadAsync(lib.Layout.AccountFolder(account))).Lines.Any(l => l.Entry.Id == "p1"));
// The next pass writes the line, even with nothing to download.
await queue.RunOnceAsync(CancellationToken.None);
var line = (await AccountJournal.ReadAsync(lib.Layout.AccountFolder(account))).Lines.Single(l => l.Entry.Id == "p1");
Assert.AreEqual(media.RelativePath, line.Files!.Single().Path);
Assert.IsNull(await lib.Db.Settings.GetAsync(LibraryIngest.PendingJournalKey));
// So a rebuild after losing the database finds it, without downloading anything.
await lib.LoseDatabaseAsync();
await new LibraryRebuilder(lib.Db, lib.Layout, lib.Clock).RebuildAsync();
var again = await lib.Db.Accounts.FindByInstagramIdAsync("1001");
Assert.AreEqual(EntryState.Downloaded, (await lib.Db.Entries.FindAsync(again!.Id, EntryKind.Post, "p1"))!.State);
}
[TestMethod]
public async Task AnEntryGetsItsLineAlsoWhenItsLastFileIsSkippedOrFails()
{
using var temp = new TempFolder("giornale");
await using var lib = await TestLibrary.CreateAsync(temp);
var account = await lib.Db.Accounts.AddAsync(Make.Account("marta.prova", "1001") with { Limits = new AccountLimits { MaxVideoBytes = 1000 } });
var tooLarge = await AddAsync(lib.Db, account, "p2", Make.Photo(1) with { SourceUrl = "https://cdn.esempio/p2.jpg" }, Make.Video(2) with { SourceUrl = "https://cdn.esempio/grande.mp4" });
var refused = await AddAsync(lib.Db, account, "p3", Make.Photo(1) with { SourceUrl = "https://cdn.esempio/p3.jpg" }, Make.Photo(2) with { SourceUrl = "https://cdn.esempio/altrove.jpg" });
var queue = Queue(lib, temp, uri => uri.AbsolutePath switch
{
"/grande.mp4" => (FetchOutcome.Completed, new byte[5000]),
"/altrove.jpg" => (FetchOutcome.HostNotAllowed, null),
"/p2.jpg" => (FetchOutcome.Completed, TestFile.PhotoBytes(31, 64, 80)),
_ => (FetchOutcome.Completed, TestFile.PhotoBytes(32, 64, 80)),
});
var report = await queue.RunOnceAsync(CancellationToken.None);
Assert.AreEqual(2, report.Stored, report.ToString());
Assert.AreEqual(1, report.Skipped);
Assert.AreEqual(1, report.Failed);
var lines = (await AccountJournal.ReadAsync(lib.Layout.AccountFolder(account))).Lines;
foreach (var (id, entryId) in new[] { ("p2", tooLarge), ("p3", refused) })
{
var stored = (await lib.Db.Media.ListByEntryAsync(entryId)).Single(m => m.Position == 1);
var line = lines.SingleOrDefault(l => l.Entry.Id == id);
Assert.IsNotNull(line, $"{id}: the entry is settled with a file in the library, so it has its line.");
Assert.AreEqual(stored.RelativePath, line.Files!.Single().Path);
}
}
[TestMethod]
public async Task AnImportedFileStaysCopiedWhenTheJournalIsBusyAndItsLineFollows()
{
using var temp = new TempFolder("giornale");
await using var bed = await ImportTestBed.CreateAsync(temp);
var (marta, _) = await bed.AccountWithPhotoAsync("marta.demo", "300", ImportTestFiles.Photo(30));
bed.Write("marta.demo/nuova.jpg", ImportTestFiles.Photo(31));
var run = await bed.AnalyzeAsync();
var folder = bed.Library.Layout.AccountFolder(marta);
await using (new FileStream(AccountJournal.PathFor(folder), FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
await bed.Copier.CopyAsync(run.Id);
}
var file = await bed.FileAsync(run.Id, "marta.demo/nuova.jpg");
Assert.AreEqual(ImportFileState.Copied, file.State, file.LastError);
Assert.IsNotNull(file.EntryId);
Assert.AreEqual(MediaState.Imported, (await bed.Library.Db.Media.ListByEntryAsync(file.EntryId.Value)).Single().State);
Assert.IsFalse((await AccountJournal.ReadAsync(folder)).Lines.Any(l => l.Files?.Any(f => f.Path == file.DestinationPath) == true));
// Any later copy (or download pass) writes the line that is still missing.
await bed.Copier.CopyAsync(run.Id);
Assert.IsTrue((await AccountJournal.ReadAsync(folder)).Lines.Any(l => l.Files?.Any(f => f.Path == file.DestinationPath) == true));
Assert.IsNull(await bed.Library.Db.Settings.GetAsync(LibraryIngest.PendingJournalKey));
Assert.AreEqual(ImportFileState.Copied, (await bed.FileAsync(run.Id, "marta.demo/nuova.jpg")).State);
}
private static DownloadQueue Queue(TestLibrary lib, TempFolder temp, Func<Uri, (FetchOutcome Outcome, byte[]? Bytes)> answer) =>
new(lib.Db, lib.Ingest, new TableFetcher(answer), new FakeDataBudget(), lib.Clock, new SeededRandom(1),
new DownloadOptions { StagingFolder = temp.Combine("dati", "temporanei"), MaxConcurrent = 1 });
private static async Task<long> AddAsync(IFebeStorage db, Account account, string id, params Media[] media)
{
var entry = Make.Entry(account.Id, id, Make.T0.AddHours(-1));
var added = await db.Entries.AddAsync(entry, media.Select(m => m with { SourceSeenAt = Make.T0 }).ToList());
return added.Stored.Entry.Id;
}
/// <summary>A file fetcher answering from a table: no network at all.</summary>
private sealed class TableFetcher(Func<Uri, (FetchOutcome Outcome, byte[]? Bytes)> answer) : IFileFetcher
{
public async Task<FetchResult> FetchAsync(Uri address, Stream destination, FetchOptions? options, CancellationToken ct)
{
var (outcome, bytes) = answer(address);
if (bytes is null)
{
return new FetchResult(outcome, 0, null, "errore di prova");
}
if (options?.MaxBytes is { } max && bytes.Length > max)
{
await destination.WriteAsync(bytes.AsMemory(0, (int)max), ct);
return new FetchResult(FetchOutcome.TooLarge, max, 200, "troppo grande");
}
await destination.WriteAsync(bytes, ct);
return new FetchResult(outcome, bytes.Length, 200, null);
}
}
}
@@ -0,0 +1,169 @@
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Tests.Support;
namespace Febe.Tests.Library;
/// <summary>
/// «Ricostruisci il database dalla libreria» (spec §8.5) on libraries that changed after their files were saved: files
/// removed or replaced by Alberto's choices, files that cannot be read. The rebuild respects the choices, never stops
/// on one file, and a second run adds nothing.
/// </summary>
[TestClass]
public sealed class LibraryRebuildRecoveryTests
{
/// <summary>One file of a series removed by «Tieni quello in libreria» stays removed, not «file mancante».</summary>
[TestMethod]
public async Task AFileOfASeriesRemovedByADuplicateDecisionStaysRemoved()
{
using var temp = new TempFolder("ricostruzione");
await using var lib = await TestLibrary.CreateAsync(temp);
var account = await lib.Db.Accounts.AddAsync(Make.Account("doppie.prova", "500"));
await lib.SaveAsync(account, Make.Entry(account.Id, "100", Make.T0.AddDays(-3)), [TestFile.Photo(1, 41, 1080, 1350)]);
var series = await lib.SaveAsync(account, Make.Entry(account.Id, "200", Make.T0), [TestFile.Photo(1, 41, 720, 900), TestFile.Photo(2, 77, 1080, 1080)]);
var review = new DownloadDuplicateReview(lib.Db, lib.Layout, lib.Journal, lib.Clock, lib.Thumbnails, lib.Index);
var pair = (await review.ListAsync()).Single(c => c.Candidate.EntryId == series.Entry.Id);
Assert.AreEqual(1, (await review.DecideAsync(pair.Pair.Id, DuplicateDecision.KeepExisting)).FilesRemoved);
var before = (await lib.Db.Entries.GetWithMediaAsync(series.Entry.Id))!;
await lib.LoseDatabaseAsync();
var rebuilder = new LibraryRebuilder(lib.Db, lib.Layout, lib.Clock, lib.Thumbnails);
var report = await rebuilder.RebuildAsync();
Assert.AreEqual(0, report.FilesMissing, string.Join("; ", report.Notes));
var accountAgain = (await lib.Db.Accounts.FindByInstagramIdAsync("500"))!;
var entry = (await lib.Db.Entries.FindAsync(accountAgain.Id, EntryKind.Post, "200"))!;
var media = await lib.Db.Media.ListByEntryAsync(entry.Id);
Assert.AreEqual(MediaState.Deleted, media.Single(m => m.Position == 1).State, "Alberto's removal is respected: never looked for or downloaded again.");
Assert.AreEqual(MediaState.Downloaded, media.Single(m => m.Position == 2).State);
Assert.AreEqual(before.Media.Single(m => m.Position == 2).RelativePath, media.Single(m => m.Position == 2).RelativePath);
Assert.AreEqual(before.Entry.State, entry.State);
var again = await rebuilder.RebuildAsync();
Assert.AreEqual(0, again.EntriesCreated);
}
/// <summary>
/// A journal written before replacements closed the old file: an imported entry without identifier appears twice,
/// once with the file that was replaced. Only the entry with its file comes back, on every run.
/// </summary>
[TestMethod]
public async Task AnEntryWithoutIdentifierWhoseFileWasReplacedComesBackOnce()
{
using var temp = new TempFolder("ricostruzione");
await using var lib = await TestLibrary.CreateAsync(temp);
var account = await lib.Db.Accounts.AddAsync(Make.Account("marta.demo", "600"));
var folder = lib.Layout.AccountFolder(account);
var bytes = TestFile.PhotoBytes(5, 800, 600);
Directory.CreateDirectory(Path.Combine(folder, "importati"));
await File.WriteAllBytesAsync(Path.Combine(folder, "importati", "IMG_1 (2).jpg"), bytes);
var entry = new Entry
{
AccountId = account.Id,
Kind = EntryKind.Post,
PublishedAt = Make.T0.AddDays(-400),
Provenance = Provenance.Imported,
DiscoveredAt = Make.T0,
};
Media Imported(string path, string sha) => Make.Photo() with { State = MediaState.Imported, RelativePath = path, Sha256 = sha, Bytes = 100 };
await lib.Journal.AppendSavedAsync(folder, account, entry, [Imported("importati/IMG_1.jpg", Make.Sha(1))]);
await lib.Journal.AppendSavedAsync(folder, account, entry, [Imported("importati/IMG_1 (2).jpg", Make.Sha(2))]);
await lib.LoseDatabaseAsync();
var rebuilder = new LibraryRebuilder(lib.Db, lib.Layout, lib.Clock);
var report = await rebuilder.RebuildAsync();
Assert.AreEqual(1, report.EntriesCreated);
Assert.AreEqual(1, report.FilesMissing, "The old file is reported...");
Assert.IsTrue(report.Notes.Any(n => n.Contains("importati/IMG_1.jpg", StringComparison.Ordinal) && n.Contains("non ripristinato", StringComparison.Ordinal)));
var accountAgain = (await lib.Db.Accounts.FindByInstagramIdAsync("600"))!;
var entries = await lib.Db.Entries.ListByAccountAsync(accountAgain.Id);
Assert.HasCount(1, entries, "...but not restored as an entry of its own.");
Assert.AreEqual("importati/IMG_1 (2).jpg", (await lib.Db.Media.ListByEntryAsync(entries[0].Id)).Single().RelativePath);
var again = await rebuilder.RebuildAsync();
Assert.AreEqual(0, again.EntriesCreated, "A second run adds nothing.");
Assert.HasCount(1, await lib.Db.Entries.ListByAccountAsync(accountAgain.Id));
}
/// <summary>A remembered deletion of an imported entry without identifier is not added again by every run.</summary>
[TestMethod]
public async Task ARememberedDeletionWithoutIdentifierIsRestoredOnce()
{
using var temp = new TempFolder("ricostruzione");
await using var lib = await TestLibrary.CreateAsync(temp);
var account = await lib.Db.Accounts.AddAsync(Make.Account("marta.demo", "700"));
var imported = await lib.SaveAsync(account, Make.Entry(account.Id, "x", Make.T0.AddDays(-300)) with { InstagramId = null, Code = null, Provenance = Provenance.Imported }, [TestFile.Photo(1, 9)]);
await new LibraryDeletion(lib.Db, lib.Layout, lib.Journal, lib.Clock).DeleteAsync(imported.Entry.Id, DeletionMode.Remember);
await lib.LoseDatabaseAsync();
var rebuilder = new LibraryRebuilder(lib.Db, lib.Layout, lib.Clock);
Assert.AreEqual(1, (await rebuilder.RebuildAsync()).EntriesDeleted);
var again = await rebuilder.RebuildAsync();
Assert.AreEqual(0, again.EntriesCreated);
var accountAgain = (await lib.Db.Accounts.FindByInstagramIdAsync("700"))!;
var entries = await lib.Db.Entries.ListByAccountAsync(accountAgain.Id);
Assert.HasCount(1, entries);
Assert.AreEqual(EntryState.Deleted, entries[0].State);
Assert.AreEqual(imported.Media[0].Sha256, (await lib.Db.Media.ListByEntryAsync(entries[0].Id)).Single().Sha256, "The SHA-256 is remembered: an import does not bring it back.");
}
/// <summary>
/// A file that cannot be read (here: held exclusively by another program) and an unreadable journal do not stop
/// the rebuild of everything else; the file stays linked as the journal recorded it.
/// </summary>
[TestMethod]
public async Task AnUnreadableFileOrJournalDoesNotStopTheRebuild()
{
using var temp = new TempFolder("ricostruzione");
await using var lib = await TestLibrary.CreateAsync(temp);
var marta = await lib.Db.Accounts.AddAsync(Make.Account("marta.demo", "800"));
var luca = await lib.Db.Accounts.AddAsync(Make.Account("luca.demo", "801"));
var zoe = await lib.Db.Accounts.AddAsync(Make.Account("zoe.demo", "802"));
var locked = await lib.SaveAsync(marta, Make.Entry(marta.Id, "a1", Make.T0.AddDays(-2)), [TestFile.Photo(1, 11)]);
var fine = await lib.SaveAsync(marta, Make.Entry(marta.Id, "a2", Make.T0.AddDays(-1)), [TestFile.Photo(1, 12)]);
await lib.SaveAsync(luca, Make.Entry(luca.Id, "b1", Make.T0), [TestFile.Photo(1, 13)]);
await lib.SaveAsync(zoe, Make.Entry(zoe.Id, "c1", Make.T0), [TestFile.Photo(1, 14)]);
await lib.LoseDatabaseAsync();
var lockedPath = lib.Layout.FullPath(marta, locked.Media[0].RelativePath!);
var report = await WhileHeldAsync(
[lockedPath, AccountJournal.PathFor(lib.Layout.AccountFolder(luca))],
() => new LibraryRebuilder(lib.Db, lib.Layout, lib.Clock, lib.Thumbnails).RebuildAsync());
Assert.AreEqual(1, report.FilesUnreadable, string.Join("; ", report.Notes));
Assert.AreEqual(2, report.FilesVerified, "The other files of the folder and of the following folders are verified.");
Assert.IsTrue(report.Notes.Any(n => n.Contains("luca.demo", StringComparison.Ordinal) && n.Contains("_febe.jsonl", StringComparison.Ordinal)));
var martaAgain = (await lib.Db.Accounts.FindByInstagramIdAsync("800"))!;
var restored = (await lib.Db.Media.ListByEntryAsync((await lib.Db.Entries.FindAsync(martaAgain.Id, EntryKind.Post, "a1"))!.Id)).Single();
Assert.AreEqual(MediaState.Downloaded, restored.State, "The file is where the journal says: linked again, not to be downloaded.");
Assert.AreEqual(locked.Media[0].RelativePath, restored.RelativePath);
Assert.AreEqual(locked.Media[0].Sha256, restored.Sha256);
StringAssert.Contains(restored.LastError, "illeggibile");
Assert.IsNotNull(await lib.Db.Entries.FindAsync(martaAgain.Id, EntryKind.Post, "a2"));
Assert.IsNotNull(await lib.Db.Accounts.FindByInstagramIdAsync("802"), "The folders after the unreadable one are rebuilt too.");
Assert.IsNull(await lib.Db.Accounts.FindByInstagramIdAsync("801"), "The folder with the unreadable journal waits for the next run.");
var later = await new LibraryRebuilder(lib.Db, lib.Layout, lib.Clock, lib.Thumbnails).RebuildAsync();
Assert.AreEqual(1, later.EntriesCreated, "Once readable, the skipped folder is rebuilt.");
_ = fine;
}
/// <summary>Runs <paramref name="action"/> while other handles hold the files with no sharing at all.</summary>
private static async Task<T> WhileHeldAsync<T>(IReadOnlyList<string> paths, Func<Task<T>> action)
{
var handles = paths.Select(p => new FileStream(p, FileMode.Open, FileAccess.ReadWrite, FileShare.None)).ToList();
try
{
return await action();
}
finally
{
foreach (var handle in handles)
{
await handle.DisposeAsync();
}
}
}
}