Files
Febe/tests/Febe.Tests/Export/ExportStoreAutomaticTests.cs
T
Alby96andClaude Opus 5.5 c3d9e02e22 E5: il posto per il prossimo file è quello del file che la copia scrive
La sonda di «Riprova» e del giro misurava il file della libreria, mentre
la copia controlla il file che scrive: una foto che diventa un PNG più
grande toglieva la pausa, la copia si fermava di nuovo e ogni ora c'era
un evento «in pausa» in più; un PNG che diventa un JPG più piccolo non
ripartiva mai; per un fotogramma serviva il posto di tutto il video.

Ora la copia ricorda in memoria quanto ha chiesto al disco quando si è
fermata (ExportCopier.SpaceNeeded) e la sonda usa quella misura per il
primo elemento in attesa di ogni lavoro in pausa
(ListNextPendingFilesAsync); senza misura, dopo un riavvio, il file
della libreria e per un fotogramma il solo margine.

Il giro di una cartella automatica guarda solo i lavori automatici che
riprenderebbe, come dice la specifica (§4.10): senza lavori automatici
in pausa basta che la cartella risponda, e una copia grande di Alberto
in pausa non blocca più i file nuovi che ci stanno (risposta 48). In una
cartella non automatica il giro non riprende nulla e misura come
«Riprova».

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 21:16:35 +01:00

661 lines
39 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Storage;
using Febe.Data;
using Febe.Tests.Data;
using Febe.Tests.Export.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Export;
/// <summary>
/// The store side of the automatic export (tappa E5, WP2): the candidates of a pass and of a round, the backlog the
/// question «Solo i nuovi / Copia anche gli N» counts, the candidates of «Riconosci le copie già presenti», the pause
/// writes that do not overwrite each other, and the signal. Database only: no file is copied here, and the planner of
/// «Copia in…» is the reference of what is due and not copied.
/// </summary>
[TestClass]
public sealed class ExportStoreAutomaticTests
{
public TestContext TestContext { get; set; } = null!;
// The automatic candidates --------------------------------------------------------------------------------------
/// <summary>
/// On a mixed library (two folders, a type the own folder does not take, an account switched off, copied, «Tolto»,
/// «Superato», «Non riuscito», the same file twice, a file still to download) the automatic candidates of a round are
/// exactly what «Copia in…» of the whole library would write, folder by folder; outside a round the «Non riuscito»
/// wait for it.
/// </summary>
[TestMethod]
[DataRow(false)]
[DataRow(true)]
public async Task AutomaticCandidatesAreDueNotCopiedAndOfTheirEffectiveDestination(bool oneOnly)
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var w = await MixedAsync(bed, oneOnly, ct);
var planned = await PlannedWritesAsync(bed, new ExportSelection.Filter(new LibraryFilter(), MosaicMode.Grouped), ct);
var general = await KeysAsync(bed, new([new(w.General, null)], [], Round: true), ct);
var own = await KeysAsync(bed, new([new(w.Own, null)], [], Round: true), ct);
Assert.IsTrue(planned[w.General].SetEquals(general), $"cartella generale: {string.Join(", ", general)}");
Assert.IsTrue(planned[w.Own].SetEquals(own), $"cartella di marta: {string.Join(", ", own)}");
var expected = new HashSet<(long, string)> { (w.Luca, Make.Sha(4)), (w.Luca, Make.Sha(8)), (w.Luca, Make.Sha(11)), (w.Luca, Make.Sha(12)) };
if (!oneOnly)
{
expected.Add((w.Luca, Make.Sha(1)));
}
Assert.IsTrue(expected.SetEquals(general), $"cartella generale: {string.Join(", ", general)}");
Assert.IsTrue(new HashSet<(long, string)> { (w.Marta, Make.Sha(9)) }.SetEquals(own));
// Both folders in one selection: each file only for its own folder.
var both = await KeysAsync(bed, new([new(w.General, null), new(w.Own, null)], [], Round: true), ct);
Assert.IsTrue(both.SetEquals(general.Union(own)));
// Outside a round a file whose last copy failed waits for the round (answer 50: the round retries every one).
var pass = await KeysAsync(bed, new([new(w.General, null)], [], Round: false), ct);
Assert.IsTrue(general.Except([(w.Luca, Make.Sha(8))]).ToHashSet().SetEquals(pass));
// A destination not in use gives nothing.
await bed.Service.Destinations.RetireAsync(w.Own, ct);
Assert.IsEmpty(await bed.Db.Exports.ListCandidatesAsync(new ExportSelection.Automatic([new(w.Own, null)], [], true), 0, 100, ct));
Assert.IsFalse(await bed.Db.Exports.HasAutomaticCandidatesAsync(new ExportSelection.Automatic([new(w.Own, null), new(9999, null)], [], true), ct));
}
/// <summary>«Solo i nuovi»: saved in the library at or after the instant of the switch; a file without that time is not new.</summary>
[TestMethod]
public async Task SinceKeepsFilesSavedAtOrAfterIt_NullDownloadedAtIsNotNew()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var general = (await bed.GeneralAsync(ct: ct)).Id;
var since = Make.T0.AddDays(2).AddMilliseconds(500);
await FileAsync(bed, bed.Luca, "before", 1, since.AddMilliseconds(-1), ct: ct);
var at = await FileAsync(bed, bed.Luca, "at", 2, since, ct: ct);
var after = await FileAsync(bed, bed.Luca, "after", 3, since.AddDays(1), ct: ct);
await FileAsync(bed, bed.Luca, "unknown", 4, null, ct: ct);
var candidates = await CandidatesAsync(bed, new([new(general, since)], [], Round: true), ct);
CollectionAssert.AreEquivalent(new[] { at.Media, after.Media }, candidates.Select(c => c.MediaId).ToArray());
Assert.HasCount(4, await CandidatesAsync(bed, new([new(general, null)], [], Round: true), ct), "senza «Solo i nuovi» tutti i file dovuti");
Assert.AreEqual(new ExportBacklog(2, 2000), await bed.Db.Exports.CountAutomaticBacklogAsync(new(ExportScope.General, null, ContentTypes.All, general, since), ct));
}
/// <summary>
/// An entry is copied when it is settled: none of its files is still to download (an expired one never will be, so
/// it does not hold the others).
/// </summary>
[TestMethod]
public async Task EntriesWithAFileToDownloadAreHeld_ExpiredDoesNotHold()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var general = (await bed.GeneralAsync(ct: ct)).Id;
var waiting = await bed.Db.Entries.AddAsync(
Make.Entry(bed.Luca.Id, "waiting", Make.T0),
[Stored(Make.Photo(1), 1), Make.Photo(2)],
ct);
var expired = await bed.Db.Entries.AddAsync(
Make.Entry(bed.Luca.Id, "expired", Make.T0),
[Stored(Make.Photo(1), 2), Make.Photo(2, MediaState.Expired)],
ct);
var candidates = await CandidatesAsync(bed, new([new(general, null)], [], Round: true), ct);
CollectionAssert.AreEqual(new[] { expired.Stored.Media[0].Id }, candidates.Select(c => c.MediaId).ToArray());
// When the second file is saved the entry is settled.
await bed.Db.WriteAsync(
x => x.Command("UPDATE media SET state = 'Downloaded', sha256 = @h, relative_path = 'p/w2.jpg', bytes = 1000 WHERE id = @id")
.With("@h", Make.Sha(3)).With("@id", waiting.Stored.Media[1].Id).ExecuteNonQuery(),
ct);
Assert.HasCount(3, await CandidatesAsync(bed, new([new(general, null)], [], Round: true), ct));
}
/// <summary>An entry whose line of <c>_febe.jsonl</c> is still to be written waits.</summary>
[TestMethod]
public async Task HeldEntryIdsAreLeftOut()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var general = (await bed.GeneralAsync(ct: ct)).Id;
var held = await FileAsync(bed, bed.Luca, "held", 1, ct: ct);
var free = await FileAsync(bed, bed.Luca, "free", 2, ct: ct);
var selection = new ExportSelection.Automatic([new(general, null)], [held.Entry, 424242], Round: true);
CollectionAssert.AreEqual(new[] { free.Media }, (await CandidatesAsync(bed, selection, ct)).Select(c => c.MediaId).ToArray());
Assert.IsTrue(await bed.Db.Exports.HasAutomaticCandidatesAsync(selection, ct));
Assert.IsFalse(await bed.Db.Exports.HasAutomaticCandidatesAsync(selection with { HeldEntryIds = [held.Entry, free.Entry] }, ct));
}
/// <summary>
/// «Tolto» and «Superato» are never copied again by themselves (spec §4.10, §15 E5): neither the file whose copy was
/// removed or superseded, nor the new file that superseded a copy, even when it is new.
/// </summary>
[TestMethod]
public async Task RemovedAndSupersededAreNotCandidates()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var general = (await bed.GeneralAsync(ct: ct)).Id;
var removed = await FileAsync(bed, bed.Luca, "removed", 1, ct: ct);
var replaced = await FileAsync(bed, bed.Luca, "replaced", 2, ct: ct);
var replacement = await FileAsync(bed, bed.Luca, "replacement", 3, Make.T0.AddDays(5), ct: ct);
await CopyAsync(bed, general, bed.Luca, removed.Media, 1, ExportCopyState.Removed, ct: ct);
await CopyAsync(bed, general, bed.Luca, replaced.Media, 2, ExportCopyState.Superseded, supersededBy: 9, ct: ct);
// The old file of an entry whose library file is now sha 3 («Tieni il più grande»): its copy was superseded by it.
await CopyAsync(bed, general, bed.Luca, null, 30, ExportCopyState.Superseded, supersededBy: 3, ct: ct);
foreach (var since in new DateTimeOffset?[] { null, Make.T0.AddDays(1) })
{
var selection = new ExportSelection.Automatic([new(general, since)], [], Round: true);
Assert.IsEmpty(await CandidatesAsync(bed, selection, ct), $"da {since}");
Assert.IsFalse(await bed.Db.Exports.HasAutomaticCandidatesAsync(selection, ct));
}
Assert.AreEqual(new ExportBacklog(0, 0), await bed.Db.Exports.CountAutomaticBacklogAsync(new(ExportScope.General, null, ContentTypes.All, general, null), ct));
// A new folder has no history: there everything is to copy.
Assert.AreEqual(new ExportBacklog(3, 3000), await bed.Db.Exports.CountAutomaticBacklogAsync(new(ExportScope.General, null, ContentTypes.All, null, null), ct));
}
/// <summary>«Una copia sola»: a file copied for another account is not copied again by itself.</summary>
[TestMethod]
public async Task OneOnlyCopiedForAnotherAccountIsNotACandidate()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var general = (await bed.GeneralAsync(ct: ct)).Id;
var marta = await FileAsync(bed, bed.Marta, "post", 1, ct: ct);
var luca = await FileAsync(bed, bed.Luca, "tagged", 1, kind: EntryKind.Tagged, ct: ct);
await CopyAsync(bed, general, bed.Marta, marta.Media, 1, ExportCopyState.Copied, ct: ct);
var selection = new ExportSelection.Automatic([new(general, null)], [], Round: true);
CollectionAssert.AreEqual(new[] { luca.Media }, (await CandidatesAsync(bed, selection, ct)).Select(c => c.MediaId).ToArray(), "una copia per account");
await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct);
Assert.IsEmpty(await CandidatesAsync(bed, selection, ct), "una copia sola");
Assert.IsFalse(await bed.Db.Exports.HasAutomaticCandidatesAsync(selection, ct));
}
/// <summary>
/// Answer 50 of 4 December 2026: every round retries every «Non riuscito», whatever the error (over 4 GB on FAT32, a
/// path too long, a read error); outside a round none.
/// </summary>
[TestMethod]
public async Task FailedCopiesAreCandidatesOfEveryRoundWhateverTheError_OutsideARoundTheyWait()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var general = (await bed.GeneralAsync(ct: ct)).Id;
var notes = new[] { ExportText.Notes.TooLargeForFileSystem, ExportText.Notes.PathTooLong, null };
var run = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = general, State = ExportRunState.Completed, StartedAt = Make.T0 }, ct);
var failed = new List<long>();
for (var i = 0; i < notes.Length; i++)
{
var file = await FileAsync(bed, bed.Luca, $"failed{i}", i + 1, ct: ct);
var copy = await CopyAsync(bed, general, bed.Luca, file.Media, i + 1, ExportCopyState.Failed, ct: ct);
await bed.Db.Exports.AddItemsAsync(
[new ExportItem { RunId = run.Id, MediaId = file.Media, AccountId = bed.Luca.Id, SourceSha256 = Make.Sha(i + 1), State = ExportItemState.Failed, Note = notes[i], CopyId = copy.Id }],
ct);
failed.Add(file.Media);
}
var fresh = await FileAsync(bed, bed.Luca, "fresh", 10, ct: ct);
var round = new ExportSelection.Automatic([new(general, null)], [], Round: true);
CollectionAssert.AreEquivalent(failed.Append(fresh.Media).ToArray(), (await CandidatesAsync(bed, round, ct)).Select(c => c.MediaId).ToArray());
CollectionAssert.AreEqual(new[] { fresh.Media }, (await CandidatesAsync(bed, round with { Round = false }, ct)).Select(c => c.MediaId).ToArray());
Assert.AreEqual(new ExportBacklog(4, 4000), await bed.Db.Exports.CountAutomaticBacklogAsync(new(ExportScope.General, null, ContentTypes.All, general, null), ct));
await bed.Db.WriteAsync(x => x.Command("DELETE FROM media WHERE id = @id").With("@id", fresh.Media).ExecuteNonQuery(), ct);
Assert.IsTrue(await bed.Db.Exports.HasAutomaticCandidatesAsync(round, ct));
Assert.IsFalse(await bed.Db.Exports.HasAutomaticCandidatesAsync(round with { Round = false }, ct));
}
/// <summary>The pre-check of a pass says what the list would give, for each case of the mixed library.</summary>
[TestMethod]
public async Task HasAutomaticCandidatesMatchesTheList()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var w = await MixedAsync(bed, oneOnly: false, ct);
var selections = new List<ExportSelection.Automatic>();
foreach (var scopes in new ExportSelection.AutomaticScope[][]
{
[new(w.General, null)], [new(w.Own, null)], [new(w.General, Make.T0.AddYears(1))], [new(w.Own, null), new(w.General, null)], [],
})
{
selections.Add(new(scopes, [], Round: true));
selections.Add(new(scopes, [], Round: false));
selections.Add(new(scopes, [w.MartaEntry9], Round: true));
}
foreach (var selection in selections)
{
var any = (await CandidatesAsync(bed, selection, ct)).Count > 0;
Assert.AreEqual(any, await bed.Db.Exports.HasAutomaticCandidatesAsync(selection, ct), string.Join(", ", selection.Destinations));
}
}
// The backlog --------------------------------------------------------------------------------------------------
/// <summary>
/// The count of the question «Copia anche gli N» and of the files in more is what the plan of «Copia in…» writes once
/// the change is saved: a wider type for an automatic own folder, an own folder taken away (its files go to the
/// general folder), and the general folder moved to a new folder (no history there). Files and bytes, each file
/// once as the plan counts it.
/// </summary>
[TestMethod]
[DataRow(false)]
[DataRow(true)]
public async Task CountAutomaticBacklogMatchesThePlanner(bool oneOnly)
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var w = await MixedAsync(bed, oneOnly, ct);
var everything = new ExportSelection.Filter(new LibraryFilter(), MosaicMode.Grouped);
// As things are.
var plan = await bed.Service.Planner.PlanAsync(new ExportJobRequest(everything), ct);
Assert.AreEqual(Of(plan, w.General), await Backlog(new(ExportScope.General, null, ContentTypes.All, w.General, null)));
Assert.AreEqual(Of(plan, w.Own), await Backlog(new(ExportScope.Account, bed.Marta.Id, ContentTypes.PostPhotos, w.Own, null)));
// «widen»: marta's own folder takes every type.
var before = Of(plan, w.Own);
var widened = await Backlog(new(ExportScope.Account, bed.Marta.Id, ContentTypes.All, w.Own, null));
var own = (await bed.Db.Exports.GetDestinationAsync(w.Own, ct))!;
await bed.Service.Destinations.UpdateAsync(w.Own, new DestinationSpec(ExportScope.Account, bed.Marta.Id, own.RootPath, null, ContentTypes.All, null, null, null), ct);
plan = await bed.Service.Planner.PlanAsync(new ExportJobRequest(everything), ct);
Assert.AreEqual(Of(plan, w.Own), widened);
Assert.IsGreaterThan(before.Files, widened.Files, "i tipi in più aggiungono file");
// «removeOwn»: marta's files go to the general folder.
var removeOwn = await Backlog(new(ExportScope.General, bed.Marta.Id, ContentTypes.All, w.General, null, IgnoreOwnFolderOfAccount: bed.Marta.Id));
await bed.Service.Destinations.RetireAsync(w.Own, ct);
plan = await bed.Service.Planner.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct);
Assert.AreEqual(Of(plan, w.General), removeOwn);
Assert.IsGreaterThan(0, removeOwn.Files);
// «switchOn» with a new folder: nothing is copied there yet.
var moved = await Backlog(new(ExportScope.General, null, ContentTypes.All, null, null));
var folder = bed.Temp.Combine("usb2");
Directory.CreateDirectory(folder);
var general = (await bed.Service.Destinations.UpdateAsync(w.General, new DestinationSpec(ExportScope.General, null, folder, "Disco nuovo", ContentTypes.All, null, null, null), ct)).Destination;
plan = await bed.Service.Planner.PlanAsync(new ExportJobRequest(everything), ct);
Assert.AreEqual(Of(plan, general.Id), moved);
// A wrong question is refused.
await Assert.ThrowsExactlyAsync<ArgumentException>(() => bed.Db.Exports.CountAutomaticBacklogAsync(new(ExportScope.Account, null, ContentTypes.All, null, null), ct));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => bed.Db.Exports.CountAutomaticBacklogAsync(new(ExportScope.General, null, ContentTypes.All, w.General, null), ct));
Task<ExportBacklog> Backlog(ExportBacklogQuery query) => bed.Db.Exports.CountAutomaticBacklogAsync(query, ct);
static ExportBacklog Of(ExportPlan plan, long destination) =>
plan.Destinations.FirstOrDefault(d => d.DestinationId == destination) is { } d ? new(d.Files, d.Bytes) : new(0, 0);
}
// «Riconosci le copie già presenti» ----------------------------------------------------------------------------
/// <summary>
/// The files «Riconosci» looks for (D13 with answer 51 of 4 December 2026): due files not «Copiato» whose newest row
/// is not «Tolto» («Non riuscito» and «Superato» yes; a «Tolto» stays «Tolto», even after a «Copia di nuovo» that
/// failed it is the newest row that decides), and the frames Febe already recorded with the same rule; frames never
/// recorded are not looked for.
/// </summary>
[TestMethod]
public async Task RecognizeCandidatesAreDueFilesNotCopied_RemovedStaysRemoved_WithFramesThatHaveRows()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var general = (await bed.GeneralAsync(ct: ct)).Id;
var never = await FileAsync(bed, bed.Luca, "never", 1, ct: ct);
var copied = await FileAsync(bed, bed.Luca, "copied", 2, ct: ct);
var removed = await FileAsync(bed, bed.Luca, "removed", 3, ct: ct);
var removedThenFailed = await FileAsync(bed, bed.Luca, "again", 4, ct: ct);
var superseded = await FileAsync(bed, bed.Luca, "superseded", 5, ct: ct);
var failed = await FileAsync(bed, bed.Luca, "failed", 6, ct: ct);
var video = await FileAsync(bed, bed.Luca, "video", 7, video: true, ct: ct);
var otherAccount = await FileAsync(bed, bed.Marta, "marta", 8, ct: ct);
await CopyAsync(bed, general, bed.Luca, copied.Media, 2, ExportCopyState.Copied, ct: ct);
await CopyAsync(bed, general, bed.Luca, removed.Media, 3, ExportCopyState.Removed, ct: ct);
await CopyAsync(bed, general, bed.Luca, removedThenFailed.Media, 4, ExportCopyState.Removed, ct: ct);
await CopyAsync(bed, general, bed.Luca, removedThenFailed.Media, 4, ExportCopyState.Failed, ct: ct);
await CopyAsync(bed, general, bed.Luca, superseded.Media, 5, ExportCopyState.Superseded, supersededBy: 50, ct: ct);
await CopyAsync(bed, general, bed.Luca, failed.Media, 6, ExportCopyState.Failed, ct: ct);
await CopyAsync(bed, general, bed.Luca, video.Media, 7, ExportCopyState.Copied, ct: ct);
// A «Tolto» of marta's own: removed for her only (one copy per account).
await CopyAsync(bed, general, bed.Marta, otherAccount.Media, 8, ExportCopyState.Removed, ct: ct);
// Frames of the video: 1 s failed, 2 s removed, 3 s copied, 4 s an orphan copied (account removed), 5 s an
// orphan removed, 6 s an orphan copied whose identity luca removed himself.
var f1 = await FrameAsync(bed, general, bed.Luca.Id, video.Media, 7, 1, ExportCopyState.Failed, ct);
await FrameAsync(bed, general, bed.Luca.Id, video.Media, 7, 2, ExportCopyState.Removed, ct);
await FrameAsync(bed, general, bed.Luca.Id, video.Media, 7, 3, ExportCopyState.Copied, ct);
var f4 = await FrameAsync(bed, general, null, null, 7, 4, ExportCopyState.Copied, ct);
await FrameAsync(bed, general, null, null, 7, 5, ExportCopyState.Removed, ct);
await FrameAsync(bed, general, null, null, 7, 6, ExportCopyState.Copied, ct);
await FrameAsync(bed, general, bed.Luca.Id, video.Media, 7, 6, ExportCopyState.Removed, ct);
var found = await RecognizeAsync(bed, general, 1000, ct);
var expected = new (long, long?)[]
{
(never.Media, null), (removedThenFailed.Media, null), (superseded.Media, null), (failed.Media, null),
(video.Media, f1), (video.Media, f4),
};
CollectionAssert.AreEqual(expected, found.Select(c => (c.File.MediaId, c.Frame?.Id)).ToArray(), string.Join(", ", found.Select(c => (c.File.MediaId, c.Frame?.FrameAt))));
Assert.AreEqual(TimeSpan.FromSeconds(1), found.Single(c => c.Frame?.Id == f1).Frame!.FrameAt);
// A page at a time by file: a page never ends inside the frames of a file.
var paged = new List<ExportRecognizeCandidate>();
long after = 0;
while (await bed.Db.Exports.ListRecognizeCandidatesAsync(general, after, 1, ct) is { Count: > 0 } page)
{
Assert.AreEqual(1, page.Select(c => c.File.MediaId).Distinct().Count());
paged.AddRange(page);
after = page[^1].File.MediaId;
}
CollectionAssert.AreEqual(expected, paged.Select(c => (c.File.MediaId, c.Frame?.Id)).ToArray());
// «Una copia sola»: a file copied for another account is not looked for.
await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct);
var shared = await FileAsync(bed, bed.Marta, "shared", 1, kind: EntryKind.Tagged, ct: ct);
Assert.IsTrue((await RecognizeAsync(bed, general, 1000, ct)).Any(c => c.File.MediaId == shared.Media), "nessuna copia di luca.demo: si cerca");
await CopyAsync(bed, general, bed.Luca, never.Media, 1, ExportCopyState.Copied, ct: ct);
Assert.IsFalse((await RecognizeAsync(bed, general, 1000, ct)).Any(c => c.File.MediaId == shared.Media || c.File.MediaId == never.Media));
// A destination that is not in use has nothing to recognise.
Assert.IsEmpty(await bed.Db.Exports.ListRecognizeCandidatesAsync(9999, 0, 100, ct));
}
// Pauses -------------------------------------------------------------------------------------------------------
/// <summary>D10: the pause keeps its first instant, takes the latest problem and says only the transition.</summary>
[TestMethod]
public async Task SetDestinationPausedReturnsTrueOnlyOnTheTransition()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var general = (await bed.GeneralAsync(ct: ct)).Id;
var exports = bed.Db.Exports;
Assert.IsTrue(await exports.SetDestinationPausedAsync(general, Make.T0, "Disco non raggiungibile", ct));
Assert.IsFalse(await exports.SetDestinationPausedAsync(general, Make.T0.AddHours(1), "Disco pieno", ct));
var paused = (await exports.GetDestinationAsync(general, ct))!;
Assert.AreEqual((Make.T0, "Disco pieno"), (paused.PausedAt, paused.LastError));
Assert.IsTrue(await exports.ClearDestinationPauseAsync(general, ct));
Assert.IsFalse(await exports.ClearDestinationPauseAsync(general, ct));
Assert.IsNull((await exports.GetDestinationAsync(general, ct))!.PausedAt);
Assert.IsTrue(await exports.SetDestinationPausedAsync(general, Make.T0.AddDays(1), "Di nuovo", ct));
await bed.Service.Destinations.RetireAsync(general, ct);
Assert.IsFalse(await exports.ClearDestinationPauseAsync(general, ct), "una destinazione ritirata resta com'è");
Assert.IsFalse(await exports.SetDestinationPausedAsync(general, Make.T0.AddDays(2), "Altro", ct));
Assert.AreEqual("Di nuovo", (await exports.GetDestinationAsync(general, ct))!.LastError);
Assert.IsFalse(await exports.SetDestinationPausedAsync(9999, Make.T0, "Nessuna", ct));
}
/// <summary>D10: a save of the destination read before a pause (or before its end) does not undo it.</summary>
[TestMethod]
public async Task UpdateDestinationKeepsThePause()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var exports = bed.Db.Exports;
var stale = await bed.GeneralAsync(ct: ct);
await exports.SetDestinationPausedAsync(stale.Id, Make.T0, "Disco non raggiungibile", ct);
await exports.UpdateDestinationAsync(stale with { Label = "Disco nuovo" }, ct);
var stored = (await exports.GetDestinationAsync(stale.Id, ct))!;
Assert.AreEqual(("Disco nuovo", Make.T0, "Disco non raggiungibile"), (stored.Label, stored.PausedAt, stored.LastError));
await exports.ClearDestinationPauseAsync(stale.Id, ct);
await exports.UpdateDestinationAsync(stored with { Label = "Disco" }, ct);
stored = (await exports.GetDestinationAsync(stale.Id, ct))!;
Assert.AreEqual(("Disco", (DateTimeOffset?)null, (string?)null), (stored.Label, stored.PausedAt, stored.LastError));
}
/// <summary>The pause of <see cref="ExportPause"/> writes its event once per transition, through the store's own writes.</summary>
[TestMethod]
public async Task ExportPauseWritesTheEventOncePerTransition()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var general = await bed.GeneralAsync(ct: ct);
var first = await ExportPause.PauseAsync(bed.Environment, general, "Disco non raggiungibile");
var second = await ExportPause.PauseAsync(bed.Environment, general, "Disco pieno");
Assert.AreEqual((first.PausedAt, "Disco pieno"), (second.PausedAt, second.LastError));
Assert.IsNull((await ExportPause.ClearAsync(bed.Environment, general)).PausedAt);
await ExportPause.PauseAsync(bed.Environment, general, "Di nuovo");
var events = (await bed.Db.Events.ListAsync(new() { Limit = 50 }, ct)).Where(e => e.Code == ExportPause.PausedEventCode).ToList();
Assert.HasCount(2, events);
}
/// <summary>
/// D11: the next file still to copy of each paused copy job of a destination, oldest first, with its form; only the
/// automatic jobs when asked.
/// </summary>
[TestMethod]
public async Task NextPendingFilesOfThePausedRuns()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var general = (await bed.GeneralAsync(ct: ct)).Id;
var own = (await bed.OwnAsync(bed.Marta, "marta", ct: ct)).Id;
var a = await FileAsync(bed, bed.Luca, "a", 1, bytes: 111, ct: ct);
var b = await FileAsync(bed, bed.Luca, "b", 2, bytes: 222, ct: ct);
var c = await FileAsync(bed, bed.Luca, "c", 3, bytes: 333, ct: ct);
var d = await FileAsync(bed, bed.Luca, "d", 4, video: true, bytes: 444, ct: ct);
Assert.IsEmpty(await bed.Db.Exports.ListNextPendingFilesAsync(general, automaticOnly: false, ct));
await RunAsync(bed, general, ExportRunState.Interrupted, ct, (c.Media, ExportItemState.Pending));
Assert.IsEmpty(await bed.Db.Exports.ListNextPendingFilesAsync(general, automaticOnly: false, ct), "solo un lavoro in pausa");
var manual = await RunAsync(bed, general, ExportRunState.Paused, ct, (a.Media, ExportItemState.Copied), (b.Media, ExportItemState.Pending), (c.Media, ExportItemState.Pending));
var automatic = await bed.Db.Exports.CreateRunAsync(
new ExportRun { DestinationId = general, Origin = ExportRunOrigin.Automatic, State = ExportRunState.Paused, StartedAt = Make.T0 }, ct);
await bed.Db.Exports.AddItemsAsync(
[new ExportItem { RunId = automatic.Id, MediaId = d.Media, AccountId = bed.Luca.Id, Variant = ExportVariant.Frame, Format = ExportFormat.Png, FrameAt = TimeSpan.Zero }],
ct);
var all = await bed.Db.Exports.ListNextPendingFilesAsync(general, automaticOnly: false, ct);
var items = await bed.Db.Exports.ListItemsAsync(new ExportItemQuery { RunId = manual.Id }, ct);
var frame = (await bed.Db.Exports.ListItemsAsync(new ExportItemQuery { RunId = automatic.Id }, ct)).Single();
CollectionAssert.AreEqual(
new[]
{
new ExportPendingFile(manual.Id, items.Single(i => i.MediaId == b.Media).Id, ExportVariant.Whole, 222),
new ExportPendingFile(automatic.Id, frame.Id, ExportVariant.Frame, 444),
},
all.ToArray());
CollectionAssert.AreEqual(new[] { all[1] }, (await bed.Db.Exports.ListNextPendingFilesAsync(general, automaticOnly: true, ct)).ToArray());
Assert.IsEmpty(await bed.Db.Exports.ListNextPendingFilesAsync(own, automaticOnly: false, ct));
}
// The signal ---------------------------------------------------------------------------------------------------
/// <summary>D4/D8: a signal completes the task taken before it, with its urgency, and is counted; each instance apart.</summary>
[TestMethod]
public async Task TheSignalWakesWhatWasTakenBeforeIt()
{
var signal = new AutoExportSignal();
var other = new AutoExportSignal();
var first = signal.Next();
var elsewhere = other.Next();
Assert.IsFalse(first.IsCompleted);
signal.Signal();
Assert.IsFalse(await first, "non urgente");
var second = signal.Next();
Assert.IsFalse(second.IsCompleted, "un segnale già dato non sveglia il compito preso dopo");
signal.Signal(urgent: true);
Assert.IsTrue(await second);
Assert.AreEqual(2, signal.Count);
Assert.IsFalse(elsewhere.IsCompleted, "un'altra istanza non si sveglia");
Assert.AreEqual(0, other.Count);
}
// Support ------------------------------------------------------------------------------------------------------
/// <summary>The ids of the mixed library of <see cref="MixedAsync"/>.</summary>
private sealed record Mixed(long General, long Own, long Marta, long Luca, long MartaEntry9);
/// <summary>
/// The general folder (every type) and marta's own folder (post photos only); anna.demo switched off. Files (SHA-256
/// n, n × 100 bytes): marta 1 copied in her folder, 2 a video and 3 a story her folder does not take, 9 to copy;
/// luca 4 twice (a post and a tagged post), 5 copied, 6 «Tolto», 7 the file that superseded a copy, 8 «Non
/// riuscito», 1 (copied for marta: «Una copia sola»), 11 a story, 12 a video, and a post still to download; anna 10.
/// </summary>
private static async Task<Mixed> MixedAsync(ExportTestBed bed, bool oneOnly, CancellationToken ct)
{
var general = (await bed.GeneralAsync(ct: ct)).Id;
var own = (await bed.OwnAsync(bed.Marta, "marta", ContentTypes.PostPhotos, ct)).Id;
var anna = await bed.Db.Accounts.AddAsync(Make.Account("anna.demo", "300"), ct);
await bed.Db.Exports.SetAccountExportEnabledAsync(anna.Id, false, ct);
if (oneOnly)
{
await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct);
}
var m1 = await FileAsync(bed, bed.Marta, "m1", 1, bytes: 100, ct: ct);
await FileAsync(bed, bed.Marta, "m2", 2, video: true, bytes: 200, ct: ct);
await FileAsync(bed, bed.Marta, "m3", 3, kind: EntryKind.Story, bytes: 300, ct: ct);
var m9 = await FileAsync(bed, bed.Marta, "m9", 9, bytes: 900, ct: ct);
await FileAsync(bed, bed.Luca, "l4", 4, bytes: 400, ct: ct);
await FileAsync(bed, bed.Luca, "l4t", 4, kind: EntryKind.Tagged, bytes: 400, ct: ct);
var l5 = await FileAsync(bed, bed.Luca, "l5", 5, bytes: 500, ct: ct);
var l6 = await FileAsync(bed, bed.Luca, "l6", 6, bytes: 600, ct: ct);
await FileAsync(bed, bed.Luca, "l7", 7, bytes: 700, ct: ct);
var l8 = await FileAsync(bed, bed.Luca, "l8", 8, bytes: 800, ct: ct);
await FileAsync(bed, bed.Luca, "l1", 1, kind: EntryKind.Tagged, bytes: 100, ct: ct);
await FileAsync(bed, bed.Luca, "l11", 11, kind: EntryKind.Story, bytes: 1100, ct: ct);
await FileAsync(bed, bed.Luca, "l12", 12, video: true, bytes: 1200, ct: ct);
await bed.Db.Entries.AddAsync(Make.Entry(bed.Luca.Id, "todo", Make.T0), [Make.Photo()], ct);
await FileAsync(bed, anna, "a10", 10, bytes: 1000, ct: ct);
await CopyAsync(bed, own, bed.Marta, m1.Media, 1, ExportCopyState.Copied, ct: ct);
await CopyAsync(bed, general, bed.Luca, l5.Media, 5, ExportCopyState.Copied, ct: ct);
await CopyAsync(bed, general, bed.Luca, l6.Media, 6, ExportCopyState.Removed, ct: ct);
await CopyAsync(bed, general, bed.Luca, null, 70, ExportCopyState.Superseded, supersededBy: 7, ct: ct);
await CopyAsync(bed, general, bed.Luca, l8.Media, 8, ExportCopyState.Failed, ct: ct);
return new Mixed(general, own, bed.Marta.Id, bed.Luca.Id, m9.Entry);
}
/// <summary>A file in an entry of its own, saved at <paramref name="savedAt"/>.</summary>
private static async Task<(long Entry, long Media)> FileAsync(
ExportTestBed bed,
Account account,
string code,
int sha,
DateTimeOffset? savedAt = null,
EntryKind kind = EntryKind.Post,
bool video = false,
long bytes = 1000,
CancellationToken ct = default)
{
var media = Stored(video ? Make.Video() : Make.Photo(), sha, video ? $"p/{code}.mp4" : $"p/{code}.jpg") with { Bytes = bytes, DownloadedAt = savedAt };
var added = await bed.Db.Entries.AddAsync(Make.Entry(account.Id, code, Make.T0, kind), [media], ct);
return (added.Stored.Entry.Id, added.Stored.Media[0].Id);
}
private static Media Stored(Media media, int sha, string? path = null) => Make.Stored(media, Make.Sha(sha), path ?? $"p/{sha}.jpg");
/// <summary>A whole copy row (a «Non riuscito» one without file).</summary>
private static Task<ExportCopy> CopyAsync(
ExportTestBed bed, long destination, Account account, long? media, int sha, ExportCopyState state, int? supersededBy = null, CancellationToken ct = default)
{
var written = state != ExportCopyState.Failed;
return bed.Db.Exports.AddCopyAsync(
new ExportCopy
{
DestinationId = destination,
AccountId = account.Id,
MediaId = media,
SourceSha256 = Make.Sha(sha),
Variant = ExportVariant.Whole,
State = state,
SupersededBySha256 = supersededBy is { } by ? Make.Sha(by) : null,
RelativePath = written ? $"{account.Username}/{sha}-{state}.jpg" : null,
Bytes = written ? 1000 : null,
CopySha256 = written ? Make.Sha(sha) : null,
CopiedAt = Make.T0,
StateChangedAt = Make.T0,
},
ct);
}
/// <summary>A PNG frame row at <paramref name="second"/>; without account an orphan (its account was removed).</summary>
private static Task<long> FrameAsync(ExportTestBed bed, long destination, long? account, long? media, int sha, int second, ExportCopyState state, CancellationToken ct) =>
ExportWorld.InsertAsync(bed.Db, "export_copy", new Dictionary<string, object?>
{
["destination_id"] = destination,
["account_id"] = account,
["removed_account_username"] = account is null ? "via.demo" : null,
["media_id"] = media,
["source_sha256"] = Make.Sha(sha),
["variant"] = "Frame",
["format"] = "Png",
["frame_at_ms"] = second * 1000L,
["state"] = state.ToString(),
["origin"] = "Written",
["relative_path"] = state == ExportCopyState.Failed ? null : $"f/{sha}_{second}_{account}_{state}.png",
["bytes"] = state == ExportCopyState.Failed ? null : 10L,
["copy_sha256"] = state == ExportCopyState.Failed ? null : Make.Sha(5000 + second),
["copied_at"] = 0L,
});
private static async Task<ExportRun> RunAsync(ExportTestBed bed, long destination, ExportRunState state, CancellationToken ct, params (long Media, ExportItemState State)[] items)
{
var run = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = destination, State = state, StartedAt = Make.T0 }, ct);
await bed.Db.Exports.AddItemsAsync(
[.. items.Select(i => new ExportItem { RunId = run.Id, MediaId = i.Media, AccountId = bed.Luca.Id, State = i.State })],
ct);
return run;
}
private static Task<IReadOnlyList<ExportCandidate>> CandidatesAsync(ExportTestBed bed, ExportSelection.Automatic selection, CancellationToken ct) =>
bed.Db.Exports.ListCandidatesAsync(selection, 0, 10_000, ct);
private static async Task<HashSet<(long, string)>> KeysAsync(ExportTestBed bed, ExportSelection.Automatic selection, CancellationToken ct)
{
// Two pages at most of one file each first, to see the paging by media id.
var all = new List<ExportCandidate>();
long after = 0;
while (await bed.Db.Exports.ListCandidatesAsync(selection, after, 2, ct) is { Count: > 0 } page)
{
all.AddRange(page);
after = page[^1].MediaId;
}
CollectionAssert.AreEqual((await CandidatesAsync(bed, selection, ct)).ToArray(), all.ToArray(), "a pagine come in una volta");
return all.Select(c => (c.AccountId, c.Sha256!)).ToHashSet();
}
private static async Task<IReadOnlyList<ExportRecognizeCandidate>> RecognizeAsync(ExportTestBed bed, long destination, int limit, CancellationToken ct) =>
await bed.Db.Exports.ListRecognizeCandidatesAsync(destination, 0, limit, ct);
/// <summary>What «Copia in…» of the selection writes, per destination, as (account, SHA-256).</summary>
private static async Task<Dictionary<long, HashSet<(long, string)>>> PlannedWritesAsync(ExportTestBed bed, ExportSelection selection, CancellationToken ct)
{
var effective = await bed.Service.Destinations.ResolveAllAsync(ct);
var settings = await ExportSettings.LoadAsync(bed.Db.Settings, ct);
var writes = new Dictionary<long, HashSet<(long, string)>>();
await foreach (var file in bed.Service.Planner.EnumerateAsync(new ExportJobRequest(selection), effective, settings, ct))
{
if (file.Action == PlannedCopy.Write)
{
if (!writes.TryGetValue(file.DestinationId!.Value, out var set))
{
writes[file.DestinationId.Value] = set = [];
}
set.Add((file.Candidate.AccountId, file.Candidate.Sha256!));
}
}
return writes;
}
}