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:
13 files changed
+1145
-95
No files matched your search
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user