diff --git a/src/Febe.Core/Export/AutoExportWorker.cs b/src/Febe.Core/Export/AutoExportWorker.cs index eff6805..c7a813c 100644 --- a/src/Febe.Core/Export/AutoExportWorker.cs +++ b/src/Febe.Core/Export/AutoExportWorker.cs @@ -236,12 +236,21 @@ public sealed class AutoExportWorker /// (those stopped with an error only at the round); else a job over every automatic destination not paused. /// /// A recovery round: «Non riuscito» copies are tried again too (answer 50). - public async Task RunOnceAsync(bool round, CancellationToken ct = default) + public Task RunOnceAsync(bool round, CancellationToken ct = default) => RunOnceAsync(round, recover: round, ct); + + /// + /// One pass. does the round's recovery work (orphan runs cancelled, paused destinations + /// tried again, runs stopped by an error resumed); only chooses the round's selection, which + /// tries «Non riuscito» again. The pass that follows a round's resume looks for files as the round would, but never + /// redoes its recovery: a run that fails or pauses again waits for the next real round instead of being resumed at + /// once, again and again (engineering B4). + /// + internal async Task RunOnceAsync(bool round, bool recover, CancellationToken ct = default) { await _pass.WaitAsync(ct).ConfigureAwait(false); try { - return await PassAsync(round, ct).ConfigureAwait(false); + return await PassAsync(round, recover, ct).ConfigureAwait(false); } finally { @@ -250,11 +259,11 @@ public sealed class AutoExportWorker } } - private async Task PassAsync(bool round, CancellationToken ct) + private async Task PassAsync(bool round, bool recover, CancellationToken ct) { var service = await ServiceAsync(ct).ConfigureAwait(false); var exports = _env.Storage.Exports; - if (round) + if (recover) { // Ghost runs: of a destination retired, switched off, or of an account removed (engineering A10). await service.CancelOrphanAutomaticRunsAsync(ct).ConfigureAwait(false); @@ -281,7 +290,7 @@ public sealed class AutoExportWorker } var destinations = await exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false); - if (round && destinations.Any(d => d.PausedAt is not null)) + if (recover && destinations.Any(d => d.PausedAt is not null)) { foreach (var paused in destinations.Where(d => d.PausedAt is not null)) { @@ -289,7 +298,8 @@ public sealed class AutoExportWorker try { // Answers again: the pause goes (no event); still not: it stays, with no new event (D10, D11). - await service.ProbeDestinationAsync(paused.Id, ct).ConfigureAwait(false); + // Room is measured for the automatic runs it would resume, not for a paused job of Alberto's. + await service.ProbeDestinationAsync(paused.Id, forAutomatic: true, ct).ConfigureAwait(false); } catch (Exception ex) when (ex is KeyNotFoundException or InvalidOperationException) { @@ -305,7 +315,7 @@ public sealed class AutoExportWorker .Where(r => r.Origin == ExportRunOrigin.Automatic) .ToList(); var resumable = unfinished - .Where(r => r.Kind == ExportRunKind.Copy && usable.ContainsKey(r.DestinationId) && (round || r.LastError is null)) + .Where(r => r.Kind == ExportRunKind.Copy && usable.ContainsKey(r.DestinationId) && (recover || r.LastError is null)) .Select(r => r.Id) .ToList(); if (resumable.Count > 0) @@ -439,7 +449,7 @@ public sealed class AutoExportWorker var pass = AutoExportPass.Idle; try { - pass = await RunOnceAsync(isRound || followUpRound, ct).ConfigureAwait(false); + pass = await RunOnceAsync(isRound || followUpRound, recover: isRound, ct).ConfigureAwait(false); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { diff --git a/src/Febe.Core/Export/ExportService.cs b/src/Febe.Core/Export/ExportService.cs index c7176e4..1941692 100644 --- a/src/Febe.Core/Export/ExportService.cs +++ b/src/Febe.Core/Export/ExportService.cs @@ -165,6 +165,9 @@ public sealed partial class ExportService : IAsyncDisposable /// Tests only: awaited after each run an automatic plan records, to act in the middle of a plan. internal Func? AutomaticRunRecorded { get; set; } + /// Tests only: awaited by «Annulla» after it looked at the running job, before it writes «annullato». + internal Func? DiscardChecked { get; set; } + /// /// After a restart: a job that was running becomes «interrotto» (paused and interrupted ones stay), and the /// .part files of unfinished jobs are removed in the background, only in their items' folders. Never resumes @@ -271,6 +274,7 @@ public sealed partial class ExportService : IAsyncDisposable } var frameItems = 0; + var accounts = new Dictionary(); try { await foreach (var file in Planner.EnumerateAsync(request, effective, settings, ct, lengthOf).ConfigureAwait(false)) @@ -288,6 +292,13 @@ public sealed partial class ExportService : IAsyncDisposable continue; } + // A library file the database has but the disk has not cannot be written: recorded, it would end + // «Mancante» in a new automatic run at every pass while it stays missing (answer 54: only files to write). + if (scopes is not null && !await SourceIsThereAsync(file.Candidate, accounts, ct).ConfigureAwait(false)) + { + continue; + } + if (!runs.TryGetValue(destination, out var run)) { run = await exports.CreateRunAsync( @@ -407,6 +418,19 @@ public sealed partial class ExportService : IAsyncDisposable } } + /// Whether the library file of a planned copy is on disk now (its account looked up once per plan). + private async Task SourceIsThereAsync(ExportCandidate candidate, Dictionary accounts, CancellationToken ct) + { + if (!accounts.TryGetValue(candidate.AccountId, out var account)) + { + account = await _env.Storage.Accounts.GetAsync(candidate.AccountId, ct).ConfigureAwait(false); + accounts[candidate.AccountId] = account; + } + + var media = account is null ? null : await _env.Storage.Media.GetAsync(candidate.MediaId, ct).ConfigureAwait(false); + return media is not null && _env.ResolveSourcePath(account!, media) is not null; + } + /// /// The length of a video the library does not know, from its headers (only the library file, never the /// destination); null when it cannot be read now (the job then gives it one instant, and the copy tells). @@ -598,26 +622,49 @@ public sealed partial class ExportService : IAsyncDisposable /// /// «Annulla»: an unfinished job becomes «annullato» (the running job is interrupted first when it holds it). Our - /// .part files in its folders go; no other file is touched, and the copies made stay. + /// .part files in its folders go; no other file is touched, and the copies made stay. Automatic starts stay + /// away for the whole operation, so the worker cannot resume the run between the check and the «annullato». /// public async Task DiscardAsync(long runId, CancellationToken ct = default) { - if (ActiveRunIds.Contains(runId)) + lock (_gate) { - await StopAsync(automaticOnly: false, destinationId: null, ct).ConfigureAwait(false); // not «Interrompi»: nothing is held + _changeRequests++; } - var run = await _env.Storage.Exports.GetRunAsync(runId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Lavoro di copia {runId} non trovato."); - if (run.State is ExportRunState.Completed or ExportRunState.Cancelled) + try { - return; - } + // An automatic resume checks the change requests under the lock where it sets the job: one that passed that + // check before this point is the running job now, and it is stopped here. + if (ActiveRunIds.Contains(runId)) + { + await StopAsync(automaticOnly: false, destinationId: null, ct).ConfigureAwait(false); // not «Interrompi»: nothing is held + } - await _env.Storage.Exports.UpdateRunAsync(run with { State = ExportRunState.Cancelled, CompletedAt = _env.Clock.Now }, CancellationToken.None).ConfigureAwait(false); - await ExportRunSettings.ClearAsync(_env.Storage.Settings, runId, CancellationToken.None).ConfigureAwait(false); - if (await _env.Storage.Exports.GetDestinationAsync(run.DestinationId, ct).ConfigureAwait(false) is { } destination) + if (DiscardChecked is { } checkedHook) + { + await checkedHook(ct).ConfigureAwait(false); + } + + var run = await _env.Storage.Exports.GetRunAsync(runId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Lavoro di copia {runId} non trovato."); + if (run.State is ExportRunState.Completed or ExportRunState.Cancelled) + { + return; + } + + await _env.Storage.Exports.UpdateRunAsync(run with { State = ExportRunState.Cancelled, CompletedAt = _env.Clock.Now }, CancellationToken.None).ConfigureAwait(false); + await ExportRunSettings.ClearAsync(_env.Storage.Settings, runId, CancellationToken.None).ConfigureAwait(false); + if (await _env.Storage.Exports.GetDestinationAsync(run.DestinationId, ct).ConfigureAwait(false) is { } destination) + { + await ExportLeftovers.CleanAsync(_env, run, destination, ct).ConfigureAwait(false); + } + } + finally { - await ExportLeftovers.CleanAsync(_env, run, destination, ct).ConfigureAwait(false); + lock (_gate) + { + _changeRequests--; + } } } @@ -694,7 +741,16 @@ public sealed partial class ExportService : IAsyncDisposable /// /// No such destination. /// The destination was retired. - public async Task ProbeDestinationAsync(long destinationId, CancellationToken ct = default) + public Task ProbeDestinationAsync(long destinationId, CancellationToken ct = default) => + ProbeDestinationAsync(destinationId, forAutomatic: false, ct); + + /// + /// The probe as ; with + /// (the recovery round) the room is measured for the paused automatic jobs the round would resume + /// (), so a small paused job of Alberto's does not clear a + /// pause that the automatic job would hit again at once, with a new event each time. + /// + public async Task ProbeDestinationAsync(long destinationId, bool forAutomatic, CancellationToken ct = default) { var exports = _env.Storage.Exports; var destination = await exports.GetDestinationAsync(destinationId, ct).ConfigureAwait(false) @@ -706,7 +762,7 @@ public sealed partial class ExportService : IAsyncDisposable var problem = await Copier.CheckDestinationAsync(destination, ct).ConfigureAwait(false); if (problem is null - && await exports.GetFirstPendingBytesAsync(destinationId, ct).ConfigureAwait(false) is { } bytes + && await (forAutomatic ? exports.GetAutomaticPendingBytesAsync(destinationId, ct) : exports.GetFirstPendingBytesAsync(destinationId, ct)).ConfigureAwait(false) is { } bytes && await FreeBytesAsync(destination, ct).ConfigureAwait(false) is { } free && free < bytes + ExportSpace.Margin) { @@ -1317,6 +1373,31 @@ public sealed partial class ExportService : IAsyncDisposable } } + /// + /// «Esporta questo account» (spec §4.10). Turned off, it is serialised with the automatic copies as a change of + /// destination: an automatic start being planned and the automatic job are stopped (their runs «interrotto», no + /// error), and the next pass resumes them with the switch read again, so the account's remaining files are skipped + /// (as answer 52 for «Automatica»). Manual runs are left as they are. Turned on, it only signals the automatic export. + /// + /// No such account. + public async Task SetAccountExportEnabledAsync(long accountId, bool enabled, CancellationToken ct = default) + { + if (enabled) + { + await Destinations.SetAccountEnabledAsync(accountId, enabled, ct).ConfigureAwait(false); + return; + } + + await ChangeDestinationAsync( + null, + async token => + { + await Destinations.SetAccountEnabledAsync(accountId, enabled, token).ConfigureAwait(false); + return true; + }, + ct).ConfigureAwait(false); + } + /// /// The unfinished automatic runs whose destination is retired, gone, or no longer automatic (switched off, its /// account removed) become «annullato» with the reason (D7, engineering A10): nothing would ever resume them. The diff --git a/src/Febe.Core/Library/StillVideos/StillVideoService.cs b/src/Febe.Core/Library/StillVideos/StillVideoService.cs index c22e7ab..8e79bea 100644 --- a/src/Febe.Core/Library/StillVideos/StillVideoService.cs +++ b/src/Febe.Core/Library/StillVideos/StillVideoService.cs @@ -679,7 +679,11 @@ public sealed class StillVideoService : IDisposable stop.ThrowIfCancellationRequested(); } - /// Why the job may not analyse now, but for the viewer: an engine session or a long work. + /// + /// Why the job may not analyse now, but for the viewer: an engine session or a long work. An automatic copy that took + /// the gate after the search started is asked to stop at every look (§16 answer 49: the search comes first), not + /// only at the start, so the search never waits behind a whole automatic job. + /// private string? BackgroundReason() { if (_env.Session.InSession) @@ -687,7 +691,17 @@ public sealed class StillVideoService : IDisposable return StillVideoText.InSession; } - return _env.Gate?.Busy is not null ? StillVideoText.LongWork : null; + if (_env.Gate is not { } gate) + { + return null; + } + + if (gate.HeldByYielding) + { + gate.CancelYielding(); + } + + return gate.Busy is not null ? StillVideoText.LongWork : null; } /// Counts (with its outcome, or as left out) and takes it off the front of the queue. diff --git a/src/Febe.Core/Storage/IExportStore.cs b/src/Febe.Core/Storage/IExportStore.cs index 36853f3..fcef94e 100644 --- a/src/Febe.Core/Storage/IExportStore.cs +++ b/src/Febe.Core/Storage/IExportStore.cs @@ -291,6 +291,14 @@ public interface IExportStore /// Task GetFirstPendingBytesAsync(long destinationId, CancellationToken ct = default); + /// + /// The room the recovery round of the automatic export needs before it clears a pause (tappa E5, D11): the largest + /// of the library files of the first items still «In attesa» of the destination's paused automatic copy jobs, the + /// ones the round resumes; without such a job, as . A paused job of Alberto's + /// never clears the pause for an automatic one: it waits for «Riprendi» or «Riprova» (answer 48). + /// + Task GetAutomaticPendingBytesAsync(long destinationId, CancellationToken ct = default); + /// Jobs for the Dashboard: newest first, at most . Task> ListRecentRunsAsync(int limit, CancellationToken ct = default); diff --git a/src/Febe.Data/Stores/ExportStore.cs b/src/Febe.Data/Stores/ExportStore.cs index ad92d44..c63a99a 100644 --- a/src/Febe.Data/Stores/ExportStore.cs +++ b/src/Febe.Data/Stores/ExportStore.cs @@ -1376,6 +1376,32 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore c => c.Command(FirstPendingBytesSql).With("@d", destinationId).ExecuteScalar() is long bytes ? bytes : (long?)null, ct); + /// + /// The largest bytes among the first pending items of the paused automatic copy jobs of a destination (@d); NULL + /// without such a job (the caller then falls back on ). + /// + internal const string AutomaticPendingBytesSql = """ + SELECT max(m.bytes), count(*) FROM export_run r + JOIN media m ON m.id = (SELECT i.media_id FROM export_item i WHERE i.run_id = r.id AND i.state = 'Pending' ORDER BY i.id LIMIT 1) + WHERE r.destination_id = @d AND r.state = 'Paused' AND r.kind = 'Copy' AND r.origin = 'Automatic' + """; + + public Task GetAutomaticPendingBytesAsync(long destinationId, CancellationToken ct = default) => + db.ReadAsync( + c => + { + using (var reader = c.Command(AutomaticPendingBytesSql).With("@d", destinationId).ExecuteReader()) + { + if (reader.Read() && reader.GetInt64(1) > 0) + { + return reader.IsDBNull(0) ? (long?)null : reader.GetInt64(0); + } + } + + return c.Command(FirstPendingBytesSql).With("@d", destinationId).ExecuteScalar() is long bytes ? bytes : (long?)null; + }, + ct); + public Task> ListRecentRunsAsync(int limit, CancellationToken ct = default) => db.ReadAsync>( c => ReadAll(c.Command(RecentRunsSql).With("@limit", (long)Math.Clamp(limit, 1, 1000)), ReadRun), diff --git a/src/Febe.Web/Api/AccountsApi.cs b/src/Febe.Web/Api/AccountsApi.cs index e08db03..1cb2340 100644 --- a/src/Febe.Web/Api/AccountsApi.cs +++ b/src/Febe.Web/Api/AccountsApi.cs @@ -58,7 +58,7 @@ public static class AccountsApi var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.SwitchRequest).ConfigureAwait(false); var account = await GetAsync(storage, id, ct).ConfigureAwait(false); var service = await exports.GetAsync(ct).ConfigureAwait(false); - await service.Destinations.SetAccountEnabledAsync(id, body.Value, ct).ConfigureAwait(false); + await service.SetAccountExportEnabledAsync(id, body.Value, ct).ConfigureAwait(false); changes.Publish(new LibraryChange(clock.Now, id, "export")); return ApiHttp.Message(body.Value ? $"{ItalianText.Handle(account.Username)} si copia nelle cartelle di esportazione." diff --git a/src/Febe.Web/Api/StillVideosApi.cs b/src/Febe.Web/Api/StillVideosApi.cs index 50cf2fd..b0d1262 100644 --- a/src/Febe.Web/Api/StillVideosApi.cs +++ b/src/Febe.Web/Api/StillVideosApi.cs @@ -137,7 +137,10 @@ public static class StillVideosApi return ExportApi.Request(new CopyJobRequestDto(body.MediaIds, body.EntryIds, body.Query, body.Mode, body.AccountId), clock).Selection; } - /// Why the job would wait now (the dialog says it), or null. + /// + /// Why the job would wait now (the dialog says it), or null. An automatic copy is not a reason: the search makes it + /// give way at once (§16 answer 49). + /// private static string? Waiting(LongWorkGate gate, IEngineSessionState session) => - session.InSession ? StillVideoText.InSession : gate.Busy is not null ? StillVideoText.LongWork : null; + session.InSession ? StillVideoText.InSession : gate.BusyFirm is not null ? StillVideoText.LongWork : null; } diff --git a/tests/Febe.Tests/Export/AutoExportWorkerTests.cs b/tests/Febe.Tests/Export/AutoExportWorkerTests.cs index af0485c..2582a48 100644 --- a/tests/Febe.Tests/Export/AutoExportWorkerTests.cs +++ b/tests/Febe.Tests/Export/AutoExportWorkerTests.cs @@ -405,6 +405,95 @@ public sealed class AutoExportWorkerTests Assert.HasCount(2, await bed.Db.Exports.ListRunsAsync(ct)); } + /// + /// 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. + /// + [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; + } + + /// + /// 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). + /// + [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)); + } + /// /// 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 } /// - /// 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. /// [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; } + /// + /// 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. + /// + [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]))); + } + /// After a sleep of the PC the clock jumps: the round runs once, and the next is an hour after it. [TestMethod] public async Task ALateWakeAfterSleepRunsTheRound() diff --git a/tests/Febe.Tests/Export/ExportServiceAutomaticTests.cs b/tests/Febe.Tests/Export/ExportServiceAutomaticTests.cs index e2bd715..70754a3 100644 --- a/tests/Febe.Tests/Export/ExportServiceAutomaticTests.cs +++ b/tests/Febe.Tests/Export/ExportServiceAutomaticTests.cs @@ -635,6 +635,75 @@ public sealed class ExportServiceAutomaticTests Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(start.Runs[0].Id, ct)).State); } + /// + /// «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. + /// + [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)); + } + + /// + /// «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. + /// + [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"); + } + /// /// 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. diff --git a/tests/Febe.Tests/Export/Support/ExportTestBed.cs b/tests/Febe.Tests/Export/Support/ExportTestBed.cs index ee25923..17bde92 100644 --- a/tests/Febe.Tests/Export/Support/ExportTestBed.cs +++ b/tests/Febe.Tests/Export/Support/ExportTestBed.cs @@ -472,6 +472,36 @@ internal sealed class CorruptingExportFileSystem(Func corrupts) : public long? FileLength(string path) => _inner.FileLength(path); } +/// +/// The real file system, but opening a chosen file throws an error that is not an (a decoder +/// or conversion bug on one file): the run stops «interrotto» with the error. Counts the failures. +/// +internal sealed class FailingExportFileSystem(Func fails) : IExportFileSystem +{ + private readonly IExportFileSystem _inner = ExportFileSystem.Instance; + private int _failures; + + /// How many times a failing file was opened. + 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 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); +} + /// A read-only wrapper stream. internal abstract class ReadOnlyStream(Stream inner) : Stream { diff --git a/tests/Febe.Tests/Library/StillVideoServiceTests.cs b/tests/Febe.Tests/Library/StillVideoServiceTests.cs index 60fe022..0f2f6f2 100644 --- a/tests/Febe.Tests/Library/StillVideoServiceTests.cs +++ b/tests/Febe.Tests/Library/StillVideoServiceTests.cs @@ -323,6 +323,37 @@ public sealed class StillVideoServiceTests Assert.AreEqual(VideoAnalysisOutcome.Still, (await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct))!.Outcome); } + /// + /// An automatic copy that takes the gate after the search started (in the moment between the worker's look and its + /// start) is asked to stop at the search's next look, not waited for to the end (§16 answer 49). + /// + [TestMethod] + public async Task AnAutomaticCopyThatStartsAfterTheSearchIsAskedToStop() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var (account, video) = await SaveVideoAsync(library, "1", StillVideo(13)); + var session = new FakeSessionState { InSession = true }; + var gate = new LongWorkGate(); + var calls = new ConcurrentQueue(); + using var service = new StillVideoService(Environment(library, gate) with { Session = session, Analyser = Counting(calls) }); + + await service.StartAsync(new ExportSelection.Account(account.Id), ct); + await UntilAsync(() => service.Progress.Waiting == StillVideoText.InSession, ct); + Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out var yield, out _)); + Assert.IsFalse(yield.IsCancellationRequested); + + session.InSession = false; + await UntilAsync(() => yield.IsCancellationRequested, ct); + Assert.IsEmpty(calls); + + automatic.Dispose(); + await service.Job.WaitAsync(Patience, ct); + Assert.HasCount(1, calls); + Assert.AreEqual(VideoAnalysisOutcome.Still, (await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct))!.Outcome); + } + [TestMethod] public async Task ASessionThatStartsDuringAnAnalysisMakesTheJobGiveWay() { diff --git a/tests/Febe.Tests/Web/StillVideosApiTests.cs b/tests/Febe.Tests/Web/StillVideosApiTests.cs index 46471ed..fae6a23 100644 --- a/tests/Febe.Tests/Web/StillVideosApiTests.cs +++ b/tests/Febe.Tests/Web/StillVideosApiTests.cs @@ -311,6 +311,20 @@ public sealed class StillVideosApiTests Assert.AreEqual("2 video da analizzare · 1 già analizzato · la foto si salta", plan.Str("summary")); Assert.AreEqual(JsonValueKind.Null, plan.GetProperty("waiting").ValueKind); + // An automatic copy is no reason to wait: the search makes it give way at once (answer 49); an import is. + var gate = server.App.Services.GetRequiredService(); + Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out _, out _)); + using (automatic) + { + Assert.AreEqual(JsonValueKind.Null, (await server.SendJsonAsync(HttpMethod.Post, "/api/still-videos/plan", selection)).Body.GetProperty("waiting").ValueKind); + } + + Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var import, out _)); + using (import) + { + Assert.AreEqual(StillVideoText.LongWork, (await server.SendJsonAsync(HttpMethod.Post, "/api/still-videos/plan", selection)).Body.Str("waiting")); + } + // During an engine session it waits, and says so (answer 41); «Interrompi» ends it with nothing stored. session.InSession = true; Assert.AreEqual(StillVideoText.InSession, (await server.SendJsonAsync(HttpMethod.Post, "/api/still-videos/plan", selection)).Body.Str("waiting"));