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:
1 parent
9277e0a18c
commit
6dcaf30db6
10 files changed
+293
-30
No files matched your search
+12
-2
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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.";
|
||||
|
||||
|
||||
@@ -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);
|
||||
@@ -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)
|
||||
|
||||
@@ -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),
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user