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

+12 -2
View File
@@ -42,6 +42,9 @@ namespace Febe.App;
/// </summary>
public sealed class FebeApp : IAsyncDisposable
{
/// <summary>How long a stop waits for «Cerca i video fermi» to give up the video it analyses.</summary>
private static readonly TimeSpan StillVideosWait = TimeSpan.FromSeconds(5);
private readonly FebeAppOptions _options;
private readonly IFebePlatform _platform;
private readonly CancellationTokenSource _lifetime = new();
@@ -362,6 +365,11 @@ public sealed class FebeApp : IAsyncDisposable
s.AddSingleton(new LibraryConversionQueue(Database, Clock));
s.AddSingleton(exportRoot);
s.AddSingleton<IExportDisk>(hooks.ExportDisk ?? new SystemExportDisk(exportRoot.Mounts));
if (hooks.StillVideoAnalyser is { } analyser)
{
s.AddSingleton(analyser);
}
s.AddSingleton<IEngineSessionState>(sessionState);
s.AddSingleton<IFebeStorage>(Database);
s.AddSingleton(library);
@@ -945,12 +953,14 @@ public sealed class FebeApp : IAsyncDisposable
await Quietly(() => web.StopAsync()).ConfigureAwait(false);
// «Cerca i video fermi» (tappa E4): the job gives up the video it analyses (nothing stored for it) and ends
// before the database closes; it does not resume at the next start (answer 41).
// before the database closes; it does not resume at the next start (answer 41). Not waited for without an end:
// a read stuck on a library that does not answer (a network folder) must not keep the engine and the browser
// from closing in time, and its result would not be stored anyway.
await Quietly(async () =>
{
var stills = web.Services.GetRequiredService<StillVideoService>();
stills.Dispose();
await stills.Job.ConfigureAwait(false);
await stills.Job.WaitAsync(StillVideosWait).ConfigureAwait(false);
}).ConfigureAwait(false);
}
+3
View File
@@ -176,4 +176,7 @@ public sealed record FebeAppHooks
/// <summary>Fake free space and file size limit of the export folders.</summary>
public IExportDisk? ExportDisk { get; init; }
/// <summary>Fake analysis of «Video fermi» (a file that does not answer while Febe closes).</summary>
public Func<string, TimeSpan, CancellationToken, StillVideoResult>? StillVideoAnalyser { get; init; }
}
@@ -73,6 +73,11 @@ public enum StillVideoAnswerKind
/// <summary>Past <see cref="StillVideoEnvironment.ViewerBudget"/> (503): nothing stored.</summary>
TooSlow,
/// <summary>
/// As <see cref="TooSlow"/>, on a video with a result the selection would skip: that result stays (503).
/// </summary>
TooSlowKept,
}
/// <summary>The answer to «È un video fermo?» from the viewer.</summary>
@@ -90,6 +95,7 @@ public sealed record StillVideoAnswer(StillVideoAnswerKind Kind, VideoAnalysis?
StillVideoAnswerKind.FileMissing => StillVideoText.FileMissing,
StillVideoAnswerKind.SourceChanged => StillVideoText.SourceChanged,
StillVideoAnswerKind.TooSlow => StillVideoText.TooSlow,
StillVideoAnswerKind.TooSlowKept => StillVideoText.TooSlowKept,
_ => null,
};
}
@@ -99,7 +105,10 @@ public sealed record StillVideoAnswer(StillVideoAnswerKind Kind, VideoAnalysis?
/// analysed once.
/// </summary>
/// <param name="ToAnalyse">Videos in the library with no result of the current algorithm.</param>
/// <param name="AlreadyAnalysed">Videos in the library with a result of the current algorithm (skipped).</param>
/// <param name="AlreadyAnalysed">
/// Videos in the library with a result of the current algorithm (skipped); one whose analysis took too long counts among
/// those to analyse.
/// </param>
/// <param name="PhotosSkipped">Photos of the selection (skipped).</param>
/// <param name="Missing">Videos of the selection not in the library (not downloaded, deleted, file not recorded).</param>
public sealed record StillVideoPlan(int ToAnalyse, int AlreadyAnalysed, int PhotosSkipped, int Missing)
@@ -119,6 +128,7 @@ public sealed record StillVideoPlan(int ToAnalyse, int AlreadyAnalysed, int Phot
/// <param name="Stopped">True once «Interrompi» ended the job.</param>
/// <param name="Waiting">Why the job waits now (an engine session, a long work, the viewer), or null.</param>
/// <param name="CurrentMediaId">The library file analysed now, or null.</param>
/// <param name="Added">Of the answer of a start: the videos it added to the job (those already queued are not); else 0.</param>
public sealed record StillVideoProgress(
bool Running,
int Total,
@@ -129,7 +139,8 @@ public sealed record StillVideoProgress(
int Skipped,
bool Stopped,
string? Waiting,
long? CurrentMediaId);
long? CurrentMediaId,
int Added = 0);
/// <summary>
/// «È un video fermo?» (spec §4.10, tappa E4, D5): only on request, never in the background over the library.
@@ -142,8 +153,8 @@ public sealed record StillVideoProgress(
/// <see cref="LongWorkGate"/> (it takes no lease, so it never blocks them: a video being analysed when one starts is
/// given up and analysed again after). Each video within <see cref="StillVideoEnvironment.JobBudget"/>, inside the
/// <see cref="ConversionThrottle"/>; past it «Non analizzabile» (TooSlow) is stored. Videos with a result of the current
/// algorithm are skipped, so a job ended by «Interrompi» or by closing Febe is not resumed by itself: started again, it
/// goes on where it was.</item>
/// algorithm are skipped, but for those whose analysis took too long (a start tries them again, once): so a job ended by
/// «Interrompi» or by closing Febe is not resumed by itself: started again, it goes on where it was.</item>
/// </list>
/// Results go to <c>video_analysis</c> by SHA-256 of the file (checked against the record first), with
/// <see cref="StillVideoAnalyzer.Algorithm"/>.
@@ -290,17 +301,17 @@ public sealed class StillVideoService : IDisposable
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
return new StillVideoAnswer(StillVideoAnswerKind.TooSlow, null, null, account.Id);
return await TooSlowAsync(sha, account.Id).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// The file went between the check and the analysis.
// The file went between the check and the analysis, or stopped being readable during it.
return new StillVideoAnswer(StillVideoAnswerKind.FileMissing, null, null, account.Id);
}
if (result is { Outcome: VideoAnalysisOutcome.NotAnalyzable, Note: VideoAnalysisNotes.TooSlow })
{
return new StillVideoAnswer(StillVideoAnswerKind.TooSlow, null, null, account.Id);
return await TooSlowAsync(sha, account.Id).ConfigureAwait(false);
}
var analysis = result.ToAnalysis(sha, _env.Clock.Now);
@@ -314,6 +325,24 @@ public sealed class StillVideoService : IDisposable
}
}
/// <summary>
/// The answer past the budget of the viewer: «avviala dalla selezione» only for a video the selection would analyse.
/// </summary>
private async Task<StillVideoAnswer> TooSlowAsync(string sha, long accountId)
{
var kept = await _env.Storage.VideoAnalyses.GetAsync(sha, CancellationToken.None).ConfigureAwait(false);
return new StillVideoAnswer(kept is not null && IsSettled(kept) ? StillVideoAnswerKind.TooSlowKept : StillVideoAnswerKind.TooSlow, null, null, accountId);
}
/// <summary>
/// Whether the job skips a video with this result: one of the current algorithm, unless its analysis took too long
/// (it is not an analysis of the video: another moment, or an idle machine, may give one).
/// </summary>
private static bool IsSettled(VideoAnalysis analysis) =>
analysis.Algorithm >= StillVideoAnalyzer.Algorithm
&& !(analysis.Outcome == VideoAnalysisOutcome.NotAnalyzable
&& (analysis.Note ?? string.Empty).Split(' ').Contains(VideoAnalysisNotes.TooSlow, StringComparer.Ordinal));
// ------------------------------------------------------------------------------------------------- job
/// <summary>The counts of the confirmation of «Cerca i video fermi» for <paramref name="selection"/>.</summary>
@@ -325,7 +354,7 @@ public sealed class StillVideoService : IDisposable
/// <summary>
/// Starts «Cerca i video fermi» for <paramref name="selection"/>, or adds its videos to the job already running (a
/// video already queued is not queued twice). Returns the job as it is then.
/// video already queued is not queued twice). Returns the job as it is then, with how many videos were added.
/// </summary>
public async Task<StillVideoProgress> StartAsync(ExportSelection selection, CancellationToken ct = default)
{
@@ -347,12 +376,14 @@ public sealed class StillVideoService : IDisposable
_jobStop = new CancellationTokenSource();
}
var added = 0;
foreach (var item in items)
{
if (_queued.Add(item.Sha256))
{
_queue.AddLast(item);
_total++;
added++;
}
}
@@ -362,7 +393,7 @@ public sealed class StillVideoService : IDisposable
_loop = Task.Run(LoopAsync);
}
return Snapshot();
return Snapshot() with { Added = added };
}
}
@@ -481,7 +512,7 @@ public sealed class StillVideoService : IDisposable
var token = itemSource.Token;
var storage = _env.Storage;
var sha = item.Sha256;
if (await storage.VideoAnalyses.GetAsync(sha, token).ConfigureAwait(false) is { } existing && existing.Algorithm >= StillVideoAnalyzer.Algorithm)
if (await storage.VideoAnalyses.GetAsync(sha, token).ConfigureAwait(false) is { } existing && IsSettled(existing))
{
// Analysed meanwhile (from the viewer, or under another entry of the same file).
Settle(item, existing.Outcome);
@@ -549,20 +580,40 @@ public sealed class StillVideoService : IDisposable
}
}
/// <summary>The library file of <paramref name="item"/> on disk, if it is still the same file in the library.</summary>
/// <summary>
/// The library file of <paramref name="item"/> on disk, if it is still the same file in the library; otherwise another
/// file of the library with the same bytes (the same video under another entry or account).
/// </summary>
private async Task<string?> PathAsync(JobItem item, CancellationToken ct)
{
var storage = _env.Storage;
var media = await storage.Media.GetAsync(item.MediaId, ct).ConfigureAwait(false);
if (media is null || media.Kind != MediaKind.Video || !EntryStateRules.IsPresent(media.State)
|| !string.Equals(media.Sha256?.ToLowerInvariant(), item.Sha256, StringComparison.Ordinal))
if (media is not null && media.Kind == MediaKind.Video && EntryStateRules.IsPresent(media.State)
&& string.Equals(media.Sha256?.ToLowerInvariant(), item.Sha256, StringComparison.Ordinal)
&& await storage.Entries.GetAsync(media.EntryId, ct).ConfigureAwait(false) is { } entry
&& await ResolveAsync(media, entry.AccountId, ct).ConfigureAwait(false) is { } path)
{
return null;
return path;
}
var entry = await storage.Entries.GetAsync(media.EntryId, ct).ConfigureAwait(false);
var account = entry is null ? null : await storage.Accounts.GetAsync(entry.AccountId, ct).ConfigureAwait(false);
return account is null ? null : _env.Resolve(account, media);
foreach (var location in await storage.Media.FindBySha256Async(item.Sha256, ct).ConfigureAwait(false))
{
if (location.Media.Kind == MediaKind.Video && EntryStateRules.IsPresent(location.Media.State)
&& await ResolveAsync(location.Media, location.Entry.AccountId, ct).ConfigureAwait(false) is { } other)
{
return other;
}
}
return null;
}
/// <summary>The path of a library file that is really on the disk, or null.</summary>
private async Task<string?> ResolveAsync(Media media, long accountId, CancellationToken ct)
{
var account = await _env.Storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false);
var path = account is null ? null : _env.Resolve(account, media);
return path is not null && File.Exists(path) ? path : null;
}
/// <summary>
@@ -743,7 +794,7 @@ public sealed class StillVideoService : IDisposable
var found = await storage.VideoAnalyses.GetManyAsync(chunk.Select(i => i.Sha256).ToList(), ct).ConfigureAwait(false);
foreach (var item in chunk)
{
if (found.TryGetValue(item.Sha256, out var analysis) && analysis.Algorithm >= StillVideoAnalyzer.Algorithm)
if (found.TryGetValue(item.Sha256, out var analysis) && IsSettled(analysis))
{
already++;
}
@@ -8,6 +8,9 @@ public static class StillVideoText
/// <summary>The analysis from the viewer did not end within its budget (answer 43): nothing is stored.</summary>
public const string TooSlow = "L'analisi richiede troppo tempo: avviala dalla selezione";
/// <summary>As <see cref="TooSlow"/>, when the video has a result the selection would skip: that result stays.</summary>
public const string TooSlowKept = "L'analisi richiede troppo tempo: resta l'esito di prima";
/// <summary>The file asked for is not in the database.</summary>
public const string NotFound = "File non trovato.";
+4 -2
View File
@@ -393,7 +393,8 @@ public sealed record StillVideosPlanDto(int Videos, int ToAnalyse, int AlreadyAn
/// <paramref name="Done"/> of <paramref name="Total"/> settled as <paramref name="Still"/>, <paramref name="Moving"/>,
/// <paramref name="NotAnalyzable"/> or <paramref name="Skipped"/> (file gone or changed); <paramref name="Stopped"/>:
/// ended by «Interrompi»; <paramref name="Waiting"/>: why it waits now; <paramref name="CurrentMediaId"/>: the file analysed
/// now; <paramref name="Summary"/>: «Analizzati 28 video: 3 fermi, 24 in movimento, 1 non analizzabile».
/// now; <paramref name="Summary"/>: «Analizzati 28 video: 3 fermi, 24 in movimento, 1 non analizzabile»;
/// <paramref name="Added"/>: in the answer of start, the videos it added to the job (0 when all were queued already).
/// </summary>
public sealed record StillVideosProgressDto(
bool Running,
@@ -406,4 +407,5 @@ public sealed record StillVideosProgressDto(
bool Stopped,
string? Waiting,
long? CurrentMediaId,
string Summary);
string Summary,
int Added);
+3 -2
View File
@@ -34,7 +34,7 @@ public static class StillVideosApi
StillVideoAnswerKind.Analysed => ApiHttp.Json(Dto(answer.Analysis!, clock), FebeJsonContext.Default.StillVideoDto),
StillVideoAnswerKind.NotAVideo => throw new BadRequestException(answer.Message!),
StillVideoAnswerKind.SourceChanged => throw new ApiStatusException(409, answer.Message!),
StillVideoAnswerKind.TooSlow => throw new ApiStatusException(503, answer.Message!),
StillVideoAnswerKind.TooSlow or StillVideoAnswerKind.TooSlowKept => throw new ApiStatusException(503, answer.Message!),
_ => throw new NotFoundException(answer.Message ?? StillVideoText.NotFound),
};
});
@@ -122,7 +122,8 @@ public static class StillVideosApi
p.Stopped,
p.Waiting,
p.CurrentMediaId,
StillVideoText.Summary(p));
StillVideoText.Summary(p),
p.Added);
/// <summary>Exactly one selection, as «Copia in…» and «Fotogrammi…» take it.</summary>
private static ExportSelection Selection(StillVideosSelectionRequest body, IClock clock)
+2
View File
@@ -4,6 +4,7 @@ using Febe.Core.Alerts;
using Febe.Core.Engine;
using Febe.Core.Export;
using Febe.Core.Import;
using Febe.Core.Library;
using Febe.Core.Library.Conversion;
using Febe.Core.Library.StillVideos;
using Febe.Core.Storage;
@@ -123,6 +124,7 @@ public static class FebeWeb
Session = sp.GetRequiredService<IEngineSessionState>(),
// The demo serves one moving file for the videos it has no still file for: their SHA-256 is never that file's.
VerifySource = !options.Demo,
Analyser = sp.GetService<Func<string, TimeSpan, CancellationToken, StillVideoResult>>(), // tests only
Changed = accountId => changes.Publish(new LibraryChange(clock.Now, accountId, "fermi")),
Log = logger is null ? null : message => logger.LogWarning("{Message}", message),
});