diff --git a/src/Febe.Core/Export/AutoExportWorker.cs b/src/Febe.Core/Export/AutoExportWorker.cs index c7a813c..83b40a5 100644 --- a/src/Febe.Core/Export/AutoExportWorker.cs +++ b/src/Febe.Core/Export/AutoExportWorker.cs @@ -298,8 +298,9 @@ public sealed class AutoExportWorker try { // Answers again: the pause goes (no event); still not: it stays, with no new event (D10, D11). - // 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); + // In an automatic folder room is measured for the automatic runs it would resume, not for a paused + // job of Alberto's; in another folder the round resumes nothing, so it measures as «Riprova». + await service.ProbeDestinationAsync(paused.Id, forAutomatic: paused.Automatic, ct).ConfigureAwait(false); } catch (Exception ex) when (ex is KeyNotFoundException or InvalidOperationException) { diff --git a/src/Febe.Core/Export/ExportCopier.cs b/src/Febe.Core/Export/ExportCopier.cs index 1851c98..dd6b0a6 100644 --- a/src/Febe.Core/Export/ExportCopier.cs +++ b/src/Febe.Core/Export/ExportCopier.cs @@ -1,3 +1,4 @@ +using System.Collections.Concurrent; using System.Security.Cryptography; using Febe.Core.Codecs.Images; using Febe.Core.Domain; @@ -35,6 +36,18 @@ public sealed partial class ExportCopier(ExportEnvironment env) private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env)); + // What each job paused for space asked of the disk (tappa E5, D11): run id -> (item id, bytes of the output). + private readonly ConcurrentDictionary _spaceNeeds = new(); + + /// + /// What the space check asked for item when it paused job : the + /// length of the file it writes (a converted file, a frame), not of the library file; null when that job did not + /// pause there for space since this copier started. In memory only (tappa E5, D11): after a restart the probe + /// estimates from the library file. + /// + public long? SpaceNeeded(long runId, long itemId) => + _spaceNeeds.TryGetValue(runId, out var need) && need.ItemId == itemId ? need.Bytes : null; + /// /// Runs (or resumes) a job. A destination that does not answer pauses it (returns, does not throw). On cancellation /// the job becomes «interrotto» and is thrown. @@ -66,6 +79,7 @@ public sealed partial class ExportCopier(ExportEnvironment env) run = run with { State = ExportRunState.Running, LastError = null }; await store.UpdateRunAsync(run, none).ConfigureAwait(false); + _spaceNeeds.TryRemove(runId, out _); // it is measured again if the job pauses again var x = new RunContext(run, destination, progress); var recognize = run.Kind == ExportRunKind.Recognize; try @@ -894,6 +908,7 @@ public sealed partial class ExportCopier(ExportEnvironment env) if (_env.Disk.FreeBytes(root) is { } free && free < output.Length + ExportSpace.Margin) { + _spaceNeeds[x.Run.Id] = (item.Id, output.Length); return ItemResult.Paused(ExportText.NoSpace(destination, free, Path.GetFileName(planned), output.Length)); } @@ -970,6 +985,7 @@ public sealed partial class ExportCopier(ExportEnvironment env) { if (IsDiskFull(ex)) { + _spaceNeeds[x.Run.Id] = (item.Id, output.Length); return ItemResult.Paused(_env.Disk.FreeBytes(root) is { } left ? ExportText.NoSpace(destination, left, Path.GetFileName(planned), output.Length) : ExportText.DiskFull(destination)); diff --git a/src/Febe.Core/Export/ExportService.cs b/src/Febe.Core/Export/ExportService.cs index 1941692..ee07805 100644 --- a/src/Febe.Core/Export/ExportService.cs +++ b/src/Febe.Core/Export/ExportService.cs @@ -746,9 +746,11 @@ public sealed partial class ExportService : IAsyncDisposable /// /// 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. + /// (the recovery round of an automatic folder) the room is measured only for the paused automatic jobs the round + /// would resume, the largest of their next files: 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, and a large one does not keep the folder + /// paused for the new files of the automatic export (spec §4.10). Without a paused automatic job there is no room + /// to measure: the folder answers, the pause goes, and Alberto's job waits for «Riprendi» (answer 48). /// public async Task ProbeDestinationAsync(long destinationId, bool forAutomatic, CancellationToken ct = default) { @@ -762,12 +764,12 @@ public sealed partial class ExportService : IAsyncDisposable var problem = await Copier.CheckDestinationAsync(destination, ct).ConfigureAwait(false); if (problem is null - && await (forAutomatic ? exports.GetAutomaticPendingBytesAsync(destinationId, ct) : exports.GetFirstPendingBytesAsync(destinationId, ct)).ConfigureAwait(false) is { } bytes + && await NextFileNeedAsync(destinationId, forAutomatic, ct).ConfigureAwait(false) is { } need && await FreeBytesAsync(destination, ct).ConfigureAwait(false) is { } free - && free < bytes + ExportSpace.Margin) + && free < need.Bytes + ExportSpace.Margin) { // Still too full: resuming would only pause again (engineering B1). Unmeasurable space clears, as before. - problem = ExportText.NoSpaceForNext(destination, free, bytes); + problem = ExportText.NoSpaceForNext(destination, free, need.Known ? need.Bytes : null); } if (problem is not null) @@ -780,6 +782,32 @@ public sealed partial class ExportService : IAsyncDisposable return null; } + /// + /// The room the next file of the destination's paused jobs needs (tappa E5, D11), or null when there is nothing to + /// measure: the oldest paused copy job (the first «Riprova» resumes), or with the + /// largest among the paused automatic ones. Each file counts with what the copier asked of the disk when it paused + /// there (: the converted file or the frame it writes); not measured since the + /// start, with its library file, or nothing for a frame (whose video says nothing of it: only the margin counts). + /// + private async Task<(long Bytes, bool Known)?> NextFileNeedAsync(long destinationId, bool automaticOnly, CancellationToken ct) + { + var files = await _env.Storage.Exports.ListNextPendingFilesAsync(destinationId, automaticOnly, ct).ConfigureAwait(false); + (long Bytes, bool Known)? largest = null; + foreach (var file in automaticOnly ? files : files.Take(1)) + { + (long Bytes, bool Known)? need = Copier.SpaceNeeded(file.RunId, file.ItemId) is { } asked ? (asked, true) + : file.Variant == ExportVariant.Frame ? (0, false) + : file.LibraryBytes is { } bytes ? (bytes, true) + : null; + if (need is { } n && (largest is null || n.Bytes > largest.Value.Bytes)) + { + largest = n; + } + } + + return largest; + } + /// The free space of a destination's disk, asked within the folder-check time; null when not measurable. private async Task FreeBytesAsync(ExportDestination destination, CancellationToken ct) { diff --git a/src/Febe.Core/Export/ExportText.cs b/src/Febe.Core/Export/ExportText.cs index cf4ad3f..ce9f5f9 100644 --- a/src/Febe.Core/Export/ExportText.cs +++ b/src/Febe.Core/Export/ExportText.cs @@ -278,10 +278,12 @@ public static class ExportText /// /// A paused destination still without room for the next file of its paused job (tappa E5, D11): the pause stays. + /// null: the size of that file is not known yet (a frame not measured since the start). /// - public static string NoSpaceForNext(ExportDestination destination, long free, long bytes) => - $"Su {ExportDestinations.Label(destination)} restano {ItalianText.Bytes(free)}: per il prossimo file ({ItalianText.Bytes(bytes)}) serve più spazio, " - + $"con un margine di {ItalianText.Bytes(ExportSpace.Margin)}. Libera spazio, poi riprendi."; + public static string NoSpaceForNext(ExportDestination destination, long free, long? bytes) => + $"Su {ExportDestinations.Label(destination)} restano {ItalianText.Bytes(free)}: per il prossimo file" + + (bytes is { } known ? $" ({ItalianText.Bytes(known)})" : string.Empty) + + $" serve più spazio, con un margine di {ItalianText.Bytes(ExportSpace.Margin)}. Libera spazio, poi riprendi."; /// The event of «Controlla le copie». public static string CheckMessage(int checkedCopies, int removed, ExportDestination destination) diff --git a/src/Febe.Core/Storage/IExportStore.cs b/src/Febe.Core/Storage/IExportStore.cs index eaae541..032d9d5 100644 --- a/src/Febe.Core/Storage/IExportStore.cs +++ b/src/Febe.Core/Storage/IExportStore.cs @@ -294,19 +294,12 @@ public interface IExportStore Task> ListRecognizeCandidatesAsync(long destinationId, long afterMediaId, int limit, CancellationToken ct = default); /// - /// The bytes of the library file of the first item still «In attesa» of the oldest paused copy job of a destination - /// (D11: a pause for space is cleared only when it fits; a «Riconosci» writes nothing); null without such an item or - /// without its size. + /// The first item still «In attesa» of each paused copy job of a destination whose library file is still recorded, + /// oldest job first (tappa E5, D11: a pause for space is cleared only when the next file fits). With + /// only the automatic jobs, the ones the recovery round resumes (a paused job of + /// Alberto's waits for «Riprendi» or «Riprova», answer 48). A «Riconosci» writes nothing, so it is never listed. /// - 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); + Task> ListNextPendingFilesAsync(long destinationId, bool automaticOnly, CancellationToken ct = default); /// Jobs for the Dashboard: newest first, at most . Task> ListRecentRunsAsync(int limit, CancellationToken ct = default); @@ -380,6 +373,13 @@ public sealed record ExportBacklogQuery( /// Files an automatic destination would copy by itself, and their bytes. public sealed record ExportBacklog(int Files, long Bytes); +/// +/// The next item of a paused copy job (): its job, the item, the form +/// it writes and the bytes of its library file (null when not recorded). For a converted file or a frame those bytes are +/// not what the copy writes. +/// +public sealed record ExportPendingFile(long RunId, long ItemId, ExportVariant Variant, long? LibraryBytes); + /// The copy mark of a tile (spec §4.10): «Non ancora copiato», «Copiato in parte», «Copiato». public enum ExportMark { diff --git a/src/Febe.Data/Stores/ExportStore.cs b/src/Febe.Data/Stores/ExportStore.cs index e8d608a..a575211 100644 --- a/src/Febe.Data/Stores/ExportStore.cs +++ b/src/Febe.Data/Stores/ExportStore.cs @@ -1383,44 +1383,25 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore } /// - /// The bytes of the first pending item of the oldest paused copy job of a destination (@d). A paused «Riconosci» - /// writes nothing, so it needs no room (D13 of tappa E5). + /// The first pending item, with a library file still recorded, of each paused copy job of a destination (@d), oldest + /// job first; @automatic = 1 keeps only the automatic jobs. A paused «Riconosci» writes nothing, so it needs no room + /// (D13 of tappa E5). /// - internal const string FirstPendingBytesSql = """ - SELECT m.bytes FROM export_run r JOIN export_item i ON i.run_id = r.id JOIN media m ON m.id = i.media_id - WHERE r.destination_id = @d AND r.state = 'Paused' AND r.kind = 'Copy' AND i.state = 'Pending' - ORDER BY r.id, i.id LIMIT 1 + internal const string NextPendingFilesSql = """ + SELECT r.id, i.id, i.variant, m.bytes FROM export_run r + JOIN export_item i ON i.id = ( + SELECT p.id FROM export_item p JOIN media pm ON pm.id = p.media_id + WHERE p.run_id = r.id AND p.state = 'Pending' ORDER BY p.id LIMIT 1) + JOIN media m ON m.id = i.media_id + WHERE r.destination_id = @d AND r.state = 'Paused' AND r.kind = 'Copy' AND (@automatic = 0 OR r.origin = 'Automatic') + ORDER BY r.id """; - public Task GetFirstPendingBytesAsync(long destinationId, CancellationToken ct = default) => - db.ReadAsync( - 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; - }, + public Task> ListNextPendingFilesAsync(long destinationId, bool automaticOnly, CancellationToken ct = default) => + db.ReadAsync>( + c => ReadAll( + c.Command(NextPendingFilesSql).With("@d", destinationId).With("@automatic", automaticOnly ? 1L : 0L), + r => new ExportPendingFile(r.GetInt64(0), r.GetInt64(1), r.GetEnum(2), r.IsDBNull(3) ? null : r.GetInt64(3))), ct); public Task> ListRecentRunsAsync(int limit, CancellationToken ct = default) => diff --git a/tests/Febe.Tests/Export/AutoExportWorkerTests.cs b/tests/Febe.Tests/Export/AutoExportWorkerTests.cs index bede3b0..a070e3f 100644 --- a/tests/Febe.Tests/Export/AutoExportWorkerTests.cs +++ b/tests/Febe.Tests/Export/AutoExportWorkerTests.cs @@ -531,6 +531,92 @@ public sealed class AutoExportWorkerTests Assert.AreEqual(events, await PauseEventsAsync(bed, ct)); } + /// + /// D11 with a converted file: the round measures the file the automatic run writes (a JPEG that becomes a larger + /// PNG), not the library file. With room for the JPEG only, the pause stays and no event is added at each round; with + /// room for the PNG, the run resumes and ends. + /// + [TestMethod] + public async Task TheRoundMeasuresTheConvertedFileOfTheAutomaticRun() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await bed.Library.SaveAsync(bed.Luca, Make.Entry(bed.Luca.Id, "p01", Make.T0.AddDays(-1)), [TestFile.Photo(1, 3, 200, 250)]); + var usb = await bed.GeneralAsync(ct: ct); + usb = (await bed.Service.Destinations.UpdateAsync(usb.Id, Spec(usb) with { Automatic = true, OnlyNew = false, PhotoFormat = ExportFormat.Png }, ct)).Destination; + var worker = Worker(bed); + bed.Disk.Free = ExportSpace.Margin / 2; + Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct)); + await bed.Service.WaitAsync(ct); + var run = (await bed.Db.Exports.ListRunsAsync(ct)).Single(); + Assert.AreEqual(ExportRunState.Paused, run.State); + var png = bed.Service.Copier.SpaceNeeded(run.Id, (await bed.ItemsAsync(run.Id, ct)).Single().Id); + var jpeg = post.Media[0].Bytes!.Value; + Assert.IsNotNull(png); + Assert.IsGreaterThan(jpeg, png.Value, "the PNG is larger than its JPEG"); + var events = await PauseEventsAsync(bed, ct); + + bed.Disk.Free = ExportSpace.Margin + jpeg + 10; + 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(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(run.Id, ct)).State); + + bed.Disk.Free = ExportSpace.Margin + png.Value; + 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(run.Id, ct)).State); + Assert.AreEqual(events, await PauseEventsAsync(bed, ct)); + } + + /// + /// Spec §4.10: in an automatic folder the round does not measure a paused job of Alberto's. His large copy paused for + /// space does not keep the folder paused for the new files that fit (they are copied, his job stays «In pausa», + /// answer 48); in a folder that is not automatic the round resumes nothing and measures as «Riprova»: the pause stays, + /// with no new event. + /// + [TestMethod] + public async Task APausedJobOfAlbertosDoesNotKeepAnAutomaticFolderPaused() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var bigLuca = await bed.Library.SaveAsync(bed.Luca, Make.Entry(bed.Luca.Id, "b01", Make.T0.AddDays(-1)), [TestFile.Photo(1, 3, 400, 500)]); + var bigMarta = await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "b02", Make.T0.AddDays(-1)), [TestFile.Photo(1, 4, 400, 500)]); + bed.Clock.Now += TimeSpan.FromMinutes(1); + var usb = await TurnOnAsync(bed, await bed.GeneralAsync(ct: ct), onlyNew: true, ct); + var nas = await bed.OwnAsync(bed.Marta, "marta-nas", ct: ct); + bed.Disk.Free = ExportSpace.Margin / 2; + var luca = (await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([bigLuca.Media[0].Id])), ct)).Runs.Single(); + var marta = (await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([bigMarta.Media[0].Id])), ct)).Runs.Single(); + Assert.AreEqual((usb.Id, nas.Id), (luca.DestinationId, marta.DestinationId)); + Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(luca.Id, ct)).State); + Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(marta.Id, ct)).State); + var events = await PauseEventsAsync(bed, ct); + + bed.Clock.Now += TimeSpan.FromMinutes(1); + var small = await bed.PostAsync(bed.Luca, "s01", 5); + var smallBytes = small.Media[0].Bytes!.Value; + Assert.IsGreaterThan(smallBytes, Math.Min(bigLuca.Media[0].Bytes!.Value, bigMarta.Media[0].Bytes!.Value)); + bed.Disk.Free = ExportSpace.Margin + smallBytes + 10; + bed.Clock.Now += TimeSpan.FromHours(1); + var worker = Worker(bed); + Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: true, ct)); + await bed.Service.WaitAsync(ct); + + Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, small.Media[0])), "the new file that fits is copied"); + Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt); + Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(luca.Id, ct)).State, "a manual «In pausa» stays Alberto's"); + Assert.IsNotNull((await bed.Db.Exports.GetDestinationAsync(nas.Id, ct))!.PausedAt, "his file still does not fit there"); + Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(marta.Id, ct)).State); + 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). diff --git a/tests/Febe.Tests/Export/ExportServiceAutomaticTests.cs b/tests/Febe.Tests/Export/ExportServiceAutomaticTests.cs index 9889da7..be2b605 100644 --- a/tests/Febe.Tests/Export/ExportServiceAutomaticTests.cs +++ b/tests/Febe.Tests/Export/ExportServiceAutomaticTests.cs @@ -3,6 +3,7 @@ using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Core.Export; using Febe.Core.Storage; +using Febe.Tests.Codecs.Containers; using Febe.Tests.Export.Support; using Febe.Tests.Support; @@ -826,6 +827,71 @@ public sealed class ExportServiceAutomaticTests Assert.AreEqual(1, (await bed.Db.Events.ListAsync(new() { Limit = 100 }, ct)).Count(e => e.Code == ExportPause.PausedEventCode)); } + /// + /// D11 with a converted file: the probe measures the file the copy writes, which the copier measured when it paused, + /// not the library file. A PNG that becomes a smaller JPG resumes as soon as the JPG fits. + /// + [TestMethod] + public async Task ProbeMeasuresTheConvertedFileTheJobWrites() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + using var picture = TestImages.Scene(7, 320, 240); + var post = await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "c01", Make.T0.AddDays(-1)), [new TestFile(Make.Photo(1), TestImages.Png(picture), ".png")]); + var usb = await bed.GeneralAsync(ct: ct); + await bed.Service.Destinations.UpdateAsync(usb.Id, Spec(bed, usb) with { PhotoFormat = ExportFormat.Jpg }, ct); + bed.Disk.Free = ExportSpace.Margin / 2; + var run = (await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([post.Media[0].Id])), ct)).Runs.Single(); + Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(run.Id, ct)).State); + var item = (await bed.ItemsAsync(run.Id, ct)).Single(); + var jpg = bed.Service.Copier.SpaceNeeded(run.Id, item.Id); + Assert.IsNotNull(jpg); + Assert.IsLessThan(post.Media[0].Bytes!.Value, jpg.Value, "the JPG is smaller than its PNG"); + + bed.Disk.Free = ExportSpace.Margin + jpg.Value - 1; + StringAssert.Contains((await bed.Service.RetryDestinationAsync(usb.Id, ct)).Problem, "per il prossimo file"); + bed.Disk.Free = ExportSpace.Margin + jpg.Value; + var retry = await bed.Service.RetryDestinationAsync(usb.Id, ct); + await bed.Service.WaitAsync(ct); + Assert.IsNull(retry.Problem); + Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State); + Assert.AreEqual(1, (await bed.Db.Events.ListAsync(new() { Limit = 100 }, ct)).Count(e => e.Code == ExportPause.PausedEventCode)); + } + + /// + /// D11 with a frames job: the room asked is the frame's, never the whole video's; after a restart (the measure is in + /// memory) the frame's size is not known and only the margin counts, without a size in the reason. + /// + [TestMethod] + public async Task ProbeOfAFramesJobMeasuresTheFrameNotTheVideo() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var video = (await bed.Library.SaveAsync( + bed.Marta, + Make.Entry(bed.Marta.Id, "f01", Make.T0.AddDays(-2)), + [new TestFile(Make.Video(1) with { Duration = null }, TestVideos.Mp4(ElementaryStream.Load("BA1_Sony_D")), ".mp4")])).Media[0]; + var usb = await bed.GeneralAsync(ct: ct); + bed.Disk.Free = ExportSpace.Margin / 2; + var request = new ExportJobRequest(new ExportSelection.Media([video.Id]), Frames: new ExportFramesRequest(FrameMode.At, TimeSpan.Zero, null, null, ExportFormat.Jpg)); + var run = (await bed.CopyAsync(request, ct)).Runs.Single(); + Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(run.Id, ct)).State); + var frame = bed.Service.Copier.SpaceNeeded(run.Id, (await bed.ItemsAsync(run.Id, ct)).Single().Id); + Assert.IsNotNull(frame); + + bed.Disk.Free = ExportSpace.Margin + frame.Value - 1; + Assert.IsNotNull(await bed.Service.ProbeDestinationAsync(usb.Id, ct)); + + // After a restart: the video's size does not count (it would ask for more than a frame needs). + await using var restarted = new ExportService(bed.Environment); + bed.Disk.Free = ExportSpace.Margin - 1; + var problem = await restarted.ProbeDestinationAsync(usb.Id, ct); + StringAssert.Contains(problem, "per il prossimo file serve più spazio"); + bed.Disk.Free = ExportSpace.Margin; + Assert.IsNull(await restarted.ProbeDestinationAsync(usb.Id, ct)); + Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(run.Id, ct)).State, "the probe resumes nothing"); + } + /// The end of Febe stops the job and waits until its states are saved. [TestMethod] public async Task DisposeAwaitsARunningJob() diff --git a/tests/Febe.Tests/Export/ExportStoreAutomaticTests.cs b/tests/Febe.Tests/Export/ExportStoreAutomaticTests.cs index dc7bf34..fe63d00 100644 --- a/tests/Febe.Tests/Export/ExportStoreAutomaticTests.cs +++ b/tests/Febe.Tests/Export/ExportStoreAutomaticTests.cs @@ -434,9 +434,12 @@ public sealed class ExportStoreAutomaticTests Assert.HasCount(2, events); } - /// D11: the first file still to copy of the oldest paused job of a destination. + /// + /// 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. + /// [TestMethod] - public async Task FirstPendingBytesOfAPausedRun() + public async Task NextPendingFilesOfThePausedRuns() { var ct = TestContext.CancellationToken; await using var bed = await ExportTestBed.CreateAsync(); @@ -445,15 +448,30 @@ public sealed class ExportStoreAutomaticTests 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); - Assert.IsNull(await bed.Db.Exports.GetFirstPendingBytesAsync(general, 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)); - var running = await RunAsync(bed, general, ExportRunState.Interrupted, ct, (c.Media, ExportItemState.Pending)); - Assert.IsNull(await bed.Db.Exports.GetFirstPendingBytesAsync(general, ct), "solo un lavoro in pausa"); - await RunAsync(bed, general, ExportRunState.Paused, ct, (a.Media, ExportItemState.Copied), (b.Media, ExportItemState.Pending), (c.Media, ExportItemState.Pending)); - await RunAsync(bed, general, ExportRunState.Paused, ct, (a.Media, ExportItemState.Pending)); - Assert.AreEqual(222L, await bed.Db.Exports.GetFirstPendingBytesAsync(general, ct)); - Assert.IsNull(await bed.Db.Exports.GetFirstPendingBytesAsync(own, ct)); - Assert.IsNotNull(running); + 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 ---------------------------------------------------------------------------------------------------