E4: la ricerca dei video fermi riprova chi era troppo lento e non trattiene la chiusura

«Avviala dalla selezione» mandava a una selezione che saltava il video; un file in due account si cercava solo nel
primo; un avvio di video già in coda sembrava una ricerca nuova; una lettura ferma bloccava la chiusura di Febe.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-01 18:57:57 +01:00
1 parent 9277e0a18c
commit 6dcaf30db6
10 files changed
+293 -30

No files matched your search

@@ -1,11 +1,14 @@
using System.Net;
using System.Text.Json;
using Febe.App;
using Febe.Core.Abstractions;
using Febe.Core.Alerts;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Library;
using Febe.Core.Library.StillVideos;
using Febe.Core.Storage;
using Febe.Data;
using Febe.Desktop.Core;
using Febe.Tests.Desktop.Support;
using Febe.Tests.Support;
@@ -216,6 +219,85 @@ public sealed class DesktopCompositionTests
Assert.IsFalse((await again.JsonAsync(HttpMethod.Get, "/api/settings/general")).GetProperty("canChangeDataFolder").GetBoolean(), "with --dati the command line decides");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task ClosingFebeEndsTheSearchForStillVideos()
{
// «Cerca i video fermi» waiting for a long work (tappa E4): a stop ends it before the database closes.
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
var account = await bed.App.Database.Accounts.AddAsync(Make.Account("marta.demo", "100"), ct);
var video = (await bed.App.Database.Entries.AddAsync(
Make.Entry(account.Id, "1", Make.T0), [Make.Stored(Make.Video(), Make.Sha(1), "post/a.mp4")], ct)).Stored.Media[0];
var service = bed.App.Web!.Services.GetRequiredService<StillVideoService>();
Assert.IsTrue(bed.App.Web.Services.GetRequiredService<LongWorkGate>().TryEnter(LongWorkKind.Import, out var import, out _));
using (import)
{
var started = await bed.JsonAsync(HttpMethod.Post, "/api/still-videos/start", $$"""{"mediaIds":[{{video.Id}}]}""");
Assert.AreEqual((true, 1), (started.GetProperty("running").GetBoolean(), started.GetProperty("added").GetInt32()));
await DesktopTestBed.WaitUntilAsync(() => service.Progress.Waiting is not null, TimeSpan.FromSeconds(10), "la ricerca aspetta");
Assert.IsFalse(service.Job.IsCompleted);
await bed.StopAsync();
}
Assert.IsTrue(service.Job.IsCompletedSuccessfully, "ended with Febe, not after it");
Assert.IsFalse(service.Progress.Running);
await using var database = await FebeDatabase.OpenAsync(bed.Folders.DefaultDataFolder, ct);
Assert.IsNull(await database.VideoAnalyses.GetAsync(Make.Sha(1), ct), "nothing stored");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
[DataRow(false)]
[DataRow(true)]
public async Task ClosingFebeGivesUpTheVideoAtWorkAndNeverWaitsWithoutAnEnd(bool stuck)
{
// A read stuck on a library that does not answer (stuck) must not keep the engine and the browser from closing;
// one that ends is waited for, and stores nothing.
var ct = TestContext.CancellationToken;
var begun = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
using var release = new ManualResetEventSlim();
var hooks = new FebeAppHooks
{
StillVideoAnalyser = (_, _, token) =>
{
begun.TrySetResult();
if (stuck)
{
release.Wait(TimeSpan.FromSeconds(40), CancellationToken.None);
}
else
{
token.WaitHandle.WaitOne(TimeSpan.FromSeconds(40));
Thread.Sleep(1000);
}
return new StillVideoResult(VideoAnalysisOutcome.Moving, null, null, 2, 0, false, 12, 1, 0);
},
};
await using var bed = await DesktopTestBed.StartAsync(hooks: hooks);
var account = await bed.App.Database.Accounts.AddAsync(Make.Account("marta.demo", "100"), ct);
byte[] bytes = [1, 2, 3, 4];
var sha = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(bytes));
var video = (await bed.App.Database.Entries.AddAsync(
Make.Entry(account.Id, "1", Make.T0), [Make.Stored(Make.Video(), sha, "post/a.mp4")], ct)).Stored.Media[0];
var path = bed.App.Library!.FullPath(account, "post/a.mp4");
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
await File.WriteAllBytesAsync(path, bytes, ct);
var service = bed.App.Web!.Services.GetRequiredService<StillVideoService>();
await bed.JsonAsync(HttpMethod.Post, "/api/still-videos/start", $$"""{"mediaIds":[{{video.Id}}]}""");
await begun.Task.WaitAsync(TimeSpan.FromSeconds(20), ct);
await bed.StopAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(30), ct);
Assert.AreEqual(!stuck, service.Job.IsCompleted);
release.Set();
await service.Job.WaitAsync(TimeSpan.FromSeconds(10), ct);
await using var database = await FebeDatabase.OpenAsync(bed.Folders.DefaultDataFolder, ct);
Assert.IsNull(await database.VideoAnalyses.GetAsync(sha, ct), "nothing stored");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task TheAlertsOfTheEngineBecomeWindowsNotifications()
@@ -52,7 +52,8 @@ internal sealed class DesktopTestBed : IAsyncDisposable
/// <param name="temp">The folder of «AppData» and «Immagini»; null: a new one, deleted with the bed.</param>
/// <param name="locations">The registry values of the Data folder.</param>
/// <param name="adjust">Options the command line cannot give (the debugging port of Edge).</param>
public static async Task<DesktopTestBed> StartAsync(string[]? args = null, FakeDesktopShell? shell = null, TempFolder? temp = null, MemoryLocationStore? locations = null, Func<DesktopOptions, DesktopOptions>? adjust = null)
/// <param name="hooks">The fakes of the composition.</param>
public static async Task<DesktopTestBed> StartAsync(string[]? args = null, FakeDesktopShell? shell = null, TempFolder? temp = null, MemoryLocationStore? locations = null, Func<DesktopOptions, DesktopOptions>? adjust = null, FebeAppHooks? hooks = null)
{
var ownsTemp = temp is null;
temp ??= new TempFolder("desktop");
@@ -67,7 +68,7 @@ internal sealed class DesktopTestBed : IAsyncDisposable
var folders = new DesktopFolders(temp.Combine("AppData", "Local"), temp.Combine("Immagini"));
var platform = new DesktopPlatform(options, shell, locations, dataFolderFixed: options.DataFolder is not null);
var app = await FebeApp.StartAsync(options.AppOptions(options.DataFolder ?? folders.DefaultDataFolder, folders), platform, new FebeAppHooks { ShutdownTimeout = TimeSpan.FromSeconds(1) });
var app = await FebeApp.StartAsync(options.AppOptions(options.DataFolder ?? folders.DefaultDataFolder, folders), platform, (hooks ?? new FebeAppHooks()) with { ShutdownTimeout = TimeSpan.FromSeconds(1) });
return new DesktopTestBed(temp, ownsTemp, shell, locations, platform, app);
}
@@ -137,6 +137,92 @@ public sealed class StillVideoServiceTests
Assert.IsNull(await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct), "only the job's budget is final");
}
[TestMethod]
public async Task PastItsBudgetTheViewerSendsToTheSelectionOnlyAVideoItWouldAnalyse()
{
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(6));
using var service = new StillVideoService(Environment(library) with { ViewerBudget = TimeSpan.Zero });
var selection = new ExportSelection.Account(account.Id);
foreach (var (row, kind) in new (VideoAnalysis, StillVideoAnswerKind)[]
{
(new(video.Sha256!, StillVideoAnalyzer.Algorithm, VideoAnalysisOutcome.Moving, Make.T0), StillVideoAnswerKind.TooSlowKept),
(new(video.Sha256!, StillVideoAnalyzer.Algorithm, VideoAnalysisOutcome.NotAnalyzable, Make.T0, null, VideoAnalysisNotes.Unreadable), StillVideoAnswerKind.TooSlowKept),
(new(video.Sha256!, StillVideoAnalyzer.Algorithm, VideoAnalysisOutcome.NotAnalyzable, Make.T0, null, VideoAnalysisNotes.TooSlow), StillVideoAnswerKind.TooSlow),
})
{
await library.Db.VideoAnalyses.SetAsync(row, ct);
var answer = await service.AnalyseNowAsync(video.Id, ct);
Assert.AreEqual(kind, answer.Kind, row.ToString());
Assert.AreEqual(
kind == StillVideoAnswerKind.TooSlow ? "L'analisi richiede troppo tempo: avviala dalla selezione" : "L'analisi richiede troppo tempo: resta l'esito di prima",
answer.Message);
Assert.AreEqual(row, await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct), "what was found before stays");
var plan = await service.PlanAsync(selection, ct);
Assert.AreEqual(kind == StillVideoAnswerKind.TooSlow ? (1, 0) : (0, 1), (plan.ToAnalyse, plan.AlreadyAnalysed), "the advice leads somewhere");
}
}
[TestMethod]
public async Task AFileThatCannotBeReadNowStoresNothing()
{
// A share that goes while the analysis reads: not «Non analizzabile» for ever, the video is to be analysed again.
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(6));
var selection = new ExportSelection.Account(account.Id);
foreach (var error in new Exception[] { new IOException("rete"), new UnauthorizedAccessException("accesso") })
{
using var service = new StillVideoService(Environment(library) with
{
Analyser = (path, _, token) =>
{
using var stream = new FailingStream(File.ReadAllBytes(path), error);
return StillVideoAnalyzer.Analyse(stream, token);
},
});
var answer = await service.AnalyseNowAsync(video.Id, ct);
Assert.AreEqual((StillVideoAnswerKind.FileMissing, StillVideoText.FileMissing), (answer.Kind, answer.Message), error.GetType().Name);
await service.StartAsync(selection, ct);
await service.Job.WaitAsync(Patience, ct);
Assert.AreEqual((1, 1, 0), (service.Progress.Done, service.Progress.Skipped, service.Progress.NotAnalyzable), error.GetType().Name);
Assert.IsNull(await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct));
Assert.AreEqual(1, (await service.PlanAsync(selection, ct)).ToAnalyse);
}
}
[TestMethod]
public async Task AVideoInTwoAccountsIsAnalysedFromTheFileThatIsThere()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var bytes = StillVideo(6);
var (marta, first) = await SaveVideoAsync(library, "1", bytes);
var luca = await library.Db.Accounts.AddAsync(Make.Account("luca.demo", "200"), ct);
var second = (await library.SaveAsync(luca, Make.Entry(luca.Id, "2", Make.T0.AddMinutes(2)), [new TestFile(Make.Video(1), bytes, ".mp4")])).Media[0];
Assert.AreEqual(first.Sha256, second.Sha256);
File.Delete(library.Layout.FullPath(marta, first.RelativePath!));
var calls = new ConcurrentQueue<string>();
using var service = new StillVideoService(Environment(library) with { Analyser = Counting(calls) });
var selection = new ExportSelection.Entries([first.EntryId, second.EntryId]);
Assert.AreEqual(1, (await service.PlanAsync(selection, ct)).ToAnalyse);
await service.StartAsync(selection, ct);
await service.Job.WaitAsync(Patience, ct);
Assert.AreEqual((1, 1, 0), (service.Progress.Done, service.Progress.Still, service.Progress.Skipped));
Assert.AreEqual(library.Layout.FullPath(luca, second.RelativePath!), calls.Single());
Assert.AreEqual(VideoAnalysisOutcome.Still, (await library.Db.VideoAnalyses.GetAsync(first.Sha256!, ct))!.Outcome);
}
[TestMethod]
public async Task TheJobCountsAnalysesOncePerFileAndSkipsWhatIsDone()
{
@@ -165,7 +251,7 @@ public sealed class StillVideoServiceTests
Assert.AreEqual("2 video da analizzare · 1 già analizzato · la foto si salta · 1 video non presente in libreria", StillVideoText.PlanSummary(plan));
var started = await service.StartAsync(selection, ct);
Assert.AreEqual((true, 2), (started.Running, started.Total));
Assert.AreEqual((true, 2, 2), (started.Running, started.Total, started.Added));
await service.Job.WaitAsync(Patience, ct);
var progress = service.Progress;
@@ -304,9 +390,19 @@ public sealed class StillVideoServiceTests
await service.Job.WaitAsync(Patience, ct);
var row = await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct);
Assert.AreEqual((VideoAnalysisOutcome.NotAnalyzable, VideoAnalysisNotes.TooSlow), (row!.Outcome, row.Note), "the job's budget is final (answer 44)");
Assert.AreEqual((VideoAnalysisOutcome.NotAnalyzable, VideoAnalysisNotes.TooSlow), (row!.Outcome, row.Note), "past the job's budget it is said (answer 44)");
Assert.AreEqual(1, service.Progress.NotAnalyzable);
Assert.AreEqual("Analizzato 1 video: 0 fermi, 0 in movimento, 1 non analizzabile", StillVideoText.Summary(service.Progress));
Assert.AreEqual(1, service.Progress.Done, "once a start");
// It is no analysis of the video: the next start tries again (an idle machine may have the time).
using var later = new StillVideoService(Environment(library));
var plan = await later.PlanAsync(new ExportSelection.Account(account.Id), ct);
Assert.AreEqual((1, 0), (plan.ToAnalyse, plan.AlreadyAnalysed));
await later.StartAsync(new ExportSelection.Account(account.Id), ct);
await later.Job.WaitAsync(Patience, ct);
Assert.AreEqual(1, later.Progress.Still);
Assert.AreEqual(VideoAnalysisOutcome.Still, (await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct))!.Outcome);
}
[TestMethod]
@@ -328,9 +424,10 @@ public sealed class StillVideoServiceTests
release.Task.Wait(ct);
return 0;
}, ct);
await busy.Task;
await busy.Task.WaitAsync(Patience, ct);
await service.StartAsync(new ExportSelection.Account(account.Id), ct);
await UntilAsync(() => service.Progress.CurrentMediaId == video.Id, ct);
await Task.Delay(500, ct); // the time an analysis that did not wait would take to begin (the file is hashed first)
Assert.IsEmpty(calls, "no decode while a conversion holds the throttle");
release.SetResult();
@@ -353,7 +450,9 @@ public sealed class StillVideoServiceTests
await service.StartAsync(new ExportSelection.Media([first.Id]), ct);
await blocker.Started.Task.WaitAsync(Patience, ct);
var added = await service.StartAsync(new ExportSelection.Media([first.Id, second.Id]), ct);
Assert.AreEqual((true, 2), (added.Running, added.Total), "the video in progress is not queued twice");
Assert.AreEqual((true, 2, 1), (added.Running, added.Total, added.Added), "the video in progress is not queued twice");
var none = await service.StartAsync(new ExportSelection.Media([second.Id]), ct);
Assert.AreEqual((true, 2, 0), (none.Running, none.Total, none.Added), "all queued already: the page says that, not that a search started");
blocker.Release();
await service.Job.WaitAsync(Patience, ct);
@@ -520,7 +619,9 @@ public sealed class StillVideoServiceTests
var one = service.AnalyseNowAsync(first.Id, closed.Token);
await blocker.Started.Task.WaitAsync(Patience, ct);
var two = service.AnalyseNowAsync(second.Id, ct);
await Task.Delay(500, ct); // the time an analysis that did not wait would take to begin (the file is hashed first)
Assert.IsFalse(two.IsCompleted, "the second waits for the first");
Assert.AreEqual(1, Volatile.Read(ref most), "and is not analysed meanwhile");
// The page that asked the first closed: its request ends, nothing is stored, and the second is answered.
await closed.CancelAsync();
@@ -673,6 +774,13 @@ public sealed class StillVideoServiceTests
return StillVideoAnalyzer.Analyse(stream, budget == Timeout.InfiniteTimeSpan ? TimeSpan.MaxValue : budget, ct);
}
/// <summary>A stream that cannot be read past its half, as a file on a share that went.</summary>
private sealed class FailingStream(byte[] data, Exception error) : MemoryStream(data)
{
public override int Read(byte[] buffer, int offset, int count) =>
Position + count > Length / 2 ? throw error : base.Read(buffer, offset, count);
}
private static async Task UntilAsync(Func<bool> condition, CancellationToken ct)
{
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);