E5: il giro non si ripete a vuoto e le copie automatiche cedono davvero

Il passaggio che segue la ripresa di un giro non rifà il lavoro di
recupero (prova delle cartelle in pausa, ripresa dei lavori fermati da
un errore): un lavoro che si ferma di nuovo aspetta il giro dopo invece
di essere ripreso all'infinito senza dormire. Il giro misura lo spazio
per il lavoro automatico che riprenderebbe, non per una pausa di Alberto,
così una pausa per spazio non va e viene con un evento nuovo ogni volta.
«Annulla» tiene lontane le partenze automatiche finché il lavoro è
annullato; «Esporta questo account» spento ferma subito la copia
automatica; «Cerca i video fermi» chiede di fermarsi a una copia
automatica partita dopo di lei; un file che manca sul disco non crea
più un lavoro automatico a ogni passaggio.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-04 19:42:27 +01:00
1 parent 93f7978d9e
commit 309f4d0402
12 files changed
+436 -32

No files matched your search

@@ -405,6 +405,95 @@ public sealed class AutoExportWorkerTests
Assert.HasCount(2, await bed.Db.Exports.ListRunsAsync(ct));
}
/// <summary>
/// A run that a round resumes and that stops on the same error again waits for the next round: the pass that follows
/// the round's resume looks for files but does not resume it again (engineering B4), so with the clock still the
/// loop makes the round and its follow-up, and the file is opened once.
/// </summary>
[TestMethod]
public async Task ARoundResumeThatFailsAgainWaitsForTheNextRound()
{
var ct = TestContext.CancellationToken;
GatedClock? clock = null;
var files = new FailingExportFileSystem(p => p.EndsWith("_1.jpg", StringComparison.Ordinal) && p.Contains("x01", StringComparison.Ordinal));
await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new GatedClock((ManualClock)env.Clock), FileSystem = files });
await bed.PostAsync(bed.Luca, "x01", 1);
await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct);
var worker = Worker(bed, clock);
var loop = worker.RunAsync(ct);
await WaitUntilAsync(async () => (await bed.Db.Exports.ListRunsAsync(ct)) is [{ LastError: not null }], ct);
await IdleAsync(bed, worker, clock!, ct);
Assert.AreEqual(ExportRunState.Interrupted, (await bed.Db.Exports.ListRunsAsync(ct)).Single().State);
var passes = worker.Passes;
var failures = files.Failures;
clock!.Advance(TimeSpan.FromHours(1));
await WaitUntilAsync(() => Task.FromResult(files.Failures > failures), ct);
await IdleAsync(bed, worker, clock, ct);
Assert.AreEqual(failures + 1, files.Failures, "the round resumed the run once");
Assert.IsLessThanOrEqualTo(passes + 2, worker.Passes, "the round and the pass after its resume, no more");
var run = (await bed.Db.Exports.ListRunsAsync(ct)).Single();
Assert.AreEqual(ExportRunState.Interrupted, run.State);
Assert.IsNotNull(run.LastError);
await worker.StopAsync();
await loop;
}
/// <summary>
/// The round measures room for the automatic run it would resume, not for a small paused job of Alberto's: with room
/// for the manual job's file but not for the automatic one's, the pause stays and no new pause event is written
/// (D10, D11); with room for both, the automatic run resumes and the manual one stays «In pausa» (answer 48).
/// </summary>
[TestMethod]
public async Task TheRoundKeepsASpacePauseUntilTheAutomaticRunsNextFileFits()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var big = await bed.Library.SaveAsync(bed.Luca, Make.Entry(bed.Luca.Id, "k01", Make.T0.AddDays(-1)), [TestFile.Photo(1, 3, 400, 500)]);
var small = await bed.PostAsync(bed.Marta, "k02", 4);
var bigBytes = big.Media[0].Bytes!.Value;
var smallBytes = small.Media[0].Bytes!.Value;
Assert.IsGreaterThan(smallBytes, bigBytes);
var usb = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct);
// Alberto's job of the small file pauses for space; the pause is cleared; the automatic run pauses on the big one.
bed.Disk.Free = ExportSpace.Margin / 2;
var manual = (await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([small.Media[0].Id])), ct)).Runs.Single();
Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(manual.Id, ct)).State);
bed.Disk.Free = null;
Assert.IsNull(await bed.Service.ProbeDestinationAsync(usb.Id, ct));
bed.Disk.Free = ExportSpace.Margin / 2;
var worker = Worker(bed);
Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct));
await bed.Service.WaitAsync(ct);
var automatic = (await bed.Db.Exports.ListRunsAsync(ct)).Single(r => r.Origin == ExportRunOrigin.Automatic);
Assert.AreEqual(ExportRunState.Paused, automatic.State);
var events = await PauseEventsAsync(bed, ct);
bed.Disk.Free = ExportSpace.Margin + smallBytes;
for (var i = 0; i < 3; i++)
{
bed.Clock.Now += TimeSpan.FromHours(1);
Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round: true, ct));
Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round: true, recover: false, ct));
}
Assert.AreEqual(events, await PauseEventsAsync(bed, ct), "no new pause event at each round");
Assert.IsNotNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(automatic.Id, ct)).State);
bed.Disk.Free = null;
bed.Clock.Now += TimeSpan.FromHours(1);
Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: true, ct));
await bed.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(automatic.Id, ct)).State);
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, big.Media[0])));
Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(manual.Id, ct)).State, "a manual «In pausa» stays Alberto's");
Assert.AreEqual(events, await PauseEventsAsync(bed, ct));
}
/// <summary>
/// The start-up round resumes the automatic runs the last stop left «interrotto» (RecoverAsync), never a run of
/// Alberto's; and a manual «In pausa» stays paused when the round finds its folder back (answer 48).
@@ -630,22 +719,22 @@ public sealed class AutoExportWorkerTests
}
/// <summary>
/// A job that ends normally starts no other by itself: a file that is in the database but no longer on disk gives a
/// run at the round, not a run after every run.
/// A job that ends normally starts no other by itself: a failed copy, tried again only by the round, gives no pass
/// between rounds.
/// </summary>
[TestMethod]
public async Task AFinishedJobStartsNoOtherByItself()
{
var ct = TestContext.CancellationToken;
GatedClock? clock = null;
await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new GatedClock((ManualClock)env.Clock) });
var post = await bed.PostAsync(bed.Luca, "m01", 1);
File.Delete(bed.LibraryFile(bed.Luca, post.Media[0]));
var corrupt = new CorruptingExportFileSystem(p => p.Contains("m01", StringComparison.Ordinal));
await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new GatedClock((ManualClock)env.Clock), FileSystem = corrupt });
await bed.PostAsync(bed.Luca, "m01", 1);
await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct);
var worker = Worker(bed, clock);
var loop = worker.RunAsync(ct);
await WaitUntilAsync(async () => (await bed.Db.Exports.ListRunsAsync(ct)).Count == 1, ct);
await WaitUntilAsync(async () => (await bed.Db.Exports.ListRunsAsync(ct)) is [{ State: ExportRunState.Completed }], ct);
await IdleAsync(bed, worker, clock!, ct);
var passes = worker.Passes;
clock!.Advance(TimeSpan.FromMinutes(5));
@@ -656,6 +745,35 @@ public sealed class AutoExportWorkerTests
await loop;
}
/// <summary>
/// A file the database has but the disk has not is never recorded by the automatic export (answer 54: only files to
/// write): rounds and signal passes find nothing to do, and no run with a «Mancante» piles up.
/// </summary>
[TestMethod]
public async Task AFileMissingOnDiskGivesNoAutomaticRun()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var post = await bed.PostAsync(bed.Luca, "m02", 1);
File.Delete(bed.LibraryFile(bed.Luca, post.Media[0]));
await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: false, ct);
var worker = Worker(bed);
foreach (var round in new[] { true, false, false, true })
{
bed.Clock.Now += TimeSpan.FromHours(1);
Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round, ct));
}
Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct));
// Back on disk: the next pass copies it.
await File.WriteAllBytesAsync(bed.LibraryFile(bed.Luca, post.Media[0]), ExportTestBed.Photo(1, 1).Bytes, ct);
Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct));
await bed.Service.WaitAsync(ct);
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0])));
}
/// <summary>After a sleep of the PC the clock jumps: the round runs once, and the next is an hour after it.</summary>
[TestMethod]
public async Task ALateWakeAfterSleepRunsTheRound()
@@ -635,6 +635,75 @@ public sealed class ExportServiceAutomaticTests
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(start.Runs[0].Id, ct)).State);
}
/// <summary>
/// «Esporta questo account» turned off stops the automatic job at once (its run «interrotto», no error), and the run
/// resumed with the switch read again skips the account's files: none of them is written after the switch.
/// </summary>
[TestMethod]
public async Task TurningAnAccountOffStopsTheAutomaticJobAndItsFilesAreSkipped()
{
var ct = TestContext.CancellationToken;
var held = new HeldExportFileSystem(p => p.EndsWith("_1.jpg", StringComparison.Ordinal) && p.Contains("l01", StringComparison.Ordinal));
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
var first = await bed.PostAsync(bed.Luca, "l01", 1);
var second = await bed.PostAsync(bed.Luca, "l02", 2);
var auto = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), ct);
var run = (await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct)).Runs.Single();
await held.Reached.Task.WaitAsync(Patience, ct);
await bed.Service.SetAccountExportEnabledAsync(bed.Luca.Id, enabled: false, ct);
Assert.IsFalse(bed.Service.IsBusy, "the automatic job was stopped");
var stopped = await bed.RunAsync(run.Id, ct);
Assert.AreEqual((ExportRunState.Interrupted, (string?)null), (stopped.State, stopped.LastError));
held.Release();
Assert.AreEqual(AutoExportStartOutcome.Started, (await bed.Service.TryResumeAutomaticAsync([run.Id], ct)).Outcome);
await bed.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State);
Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, first.Media[0])));
Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, second.Media[0])));
Assert.IsEmpty(await bed.Db.Exports.ListCopiesAsync(auto.Id, ct: ct));
}
/// <summary>
/// «Annulla» of an automatic run keeps automatic starts away until the run is «annullato»: the worker's resume of the
/// same run in that moment is refused (Busy), so the run stays «annullato» and nothing is copied.
/// </summary>
[TestMethod]
public async Task DiscardOfAnAutomaticRunCannotRaceItsResume()
{
var ct = TestContext.CancellationToken;
var held = new HeldExportFileSystem(p => p.EndsWith("_1.jpg", StringComparison.Ordinal));
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
var post = await bed.PostAsync(bed.Luca, "d01", 1);
var auto = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), ct);
var run = (await bed.Service.TryStartAutomaticAsync(Selection(auto, round: true), ct)).Runs.Single();
await held.Reached.Task.WaitAsync(Patience, ct);
Assert.IsTrue(await bed.Service.InterruptAutomaticAsync(ct));
await bed.Service.WaitAsync(ct);
held.Release();
Assert.AreEqual(ExportRunState.Interrupted, (await bed.RunAsync(run.Id, ct)).State);
var reached = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var go = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
bed.Service.DiscardChecked = async token =>
{
reached.TrySetResult();
await go.Task.WaitAsync(token);
};
var discard = bed.Service.DiscardAsync(run.Id, ct);
await reached.Task.WaitAsync(Patience, ct);
Assert.AreEqual(AutoExportStartOutcome.Busy, (await bed.Service.TryResumeAutomaticAsync([run.Id], ct)).Outcome);
go.SetResult();
await discard;
await bed.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Cancelled, (await bed.RunAsync(run.Id, ct)).State);
Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Luca, post.Media[0])));
bed.Service.DiscardChecked = null;
Assert.AreEqual(AutoExportStartOutcome.NothingToDo, (await bed.Service.TryResumeAutomaticAsync([run.Id], ct)).Outcome, "after «Annulla» the gate is open again");
}
/// <summary>
/// The automatic export resumes only automatic runs: a manual «In pausa» stays Alberto's even when its folder
/// answers again (answer 48); «Riprova» resumes it.
@@ -472,6 +472,36 @@ internal sealed class CorruptingExportFileSystem(Func<string, bool> corrupts) :
public long? FileLength(string path) => _inner.FileLength(path);
}
/// <summary>
/// The real file system, but opening a chosen file throws an error that is not an <see cref="IOException"/> (a decoder
/// or conversion bug on one file): the run stops «interrotto» with the error. Counts the failures.
/// </summary>
internal sealed class FailingExportFileSystem(Func<string, bool> fails) : IExportFileSystem
{
private readonly IExportFileSystem _inner = ExportFileSystem.Instance;
private int _failures;
/// <summary>How many times a failing file was opened.</summary>
public int Failures => Volatile.Read(ref _failures);
public Stream OpenRead(string path)
{
if (fails(path))
{
Interlocked.Increment(ref _failures);
throw new InvalidDataException("guasto di prova");
}
return _inner.OpenRead(path);
}
public Task<string> ComputeSha256Async(string path, CancellationToken ct) => _inner.ComputeSha256Async(path, ct);
public bool FileExists(string path) => _inner.FileExists(path);
public long? FileLength(string path) => _inner.FileLength(path);
}
/// <summary>A read-only wrapper stream.</summary>
internal abstract class ReadOnlyStream(Stream inner) : Stream
{