Files
Febe/tests/Febe.Tests/Library/StillVideoServiceTests.cs
T
Alby96andClaude Opus 5.5 309f4d0402 E5: il giro non si ripete a vuoto e le copie automatiche cedono davvero
Il passaggio che segue la ripresa di un giro non rifà il lavoro di
recupero (prova delle cartelle in pausa, ripresa dei lavori fermati da
un errore): un lavoro che si ferma di nuovo aspetta il giro dopo invece
di essere ripreso all'infinito senza dormire. Il giro misura lo spazio
per il lavoro automatico che riprenderebbe, non per una pausa di Alberto,
così una pausa per spazio non va e viene con un evento nuovo ogni volta.
«Annulla» tiene lontane le partenze automatiche finché il lavoro è
annullato; «Esporta questo account» spento ferma subito la copia
automatica; «Cerca i video fermi» chiede di fermarsi a una copia
automatica partita dopo di lei; un file che manca sul disco non crea
più un lavoro automatico a ogni passaggio.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 19:42:27 +01:00

910 lines
48 KiB
C#

using System.Collections.Concurrent;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
using Febe.Core.Library.Conversion;
using Febe.Core.Library.StillVideos;
using Febe.Tests.Codecs.Containers;
using Febe.Tests.Export.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Library;
/// <summary>
/// «È un video fermo?» from the viewer and «Cerca i video fermi» from a selection (tappa E4, D5, answers 41 and 43): the
/// service over a real database and library, with videos the tests build (<see cref="PcmVideos"/>), a fake engine
/// session and a real <see cref="LongWorkGate"/> and <see cref="ConversionThrottle"/>.
/// </summary>
[TestClass]
public sealed class StillVideoServiceTests
{
private static readonly TimeSpan Patience = TimeSpan.FromSeconds(30);
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public async Task TheViewerAnalysesStoresAndTellsTheLibrary()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var (account, still) = await SaveVideoAsync(library, "1", StillVideo(1, audio: true));
var (_, moving) = await SaveVideoAsync(library, "2", MovingVideo());
var changed = new ConcurrentQueue<long?>();
using var service = new StillVideoService(Environment(library) with { Changed = changed.Enqueue });
var answer = await service.AnalyseNowAsync(still.Id, ct);
Assert.AreEqual(StillVideoAnswerKind.Analysed, answer.Kind);
Assert.IsNull(answer.Message);
Assert.IsTrue(answer.Result!.HasAudio);
var row = await library.Db.VideoAnalyses.GetAsync(still.Sha256!, ct);
Assert.IsNotNull(row);
Assert.AreEqual((VideoAnalysisOutcome.Still, StillVideoAnalyzer.Algorithm, library.Clock.Now), (row.Outcome, row.Algorithm, row.AnalyzedAt));
Assert.IsNotNull(row.FrameAt, "the frame «Salva il fotogramma» saves");
Assert.AreEqual(answer.Analysis, row);
CollectionAssert.AreEqual(new long?[] { account.Id }, changed.ToArray());
Assert.AreEqual(VideoAnalysisOutcome.Moving, (await service.AnalyseNowAsync(moving.Id, ct)).Analysis!.Outcome);
Assert.AreEqual(VideoAnalysisOutcome.Moving, (await library.Db.VideoAnalyses.GetAsync(moving.Sha256!, ct))!.Outcome);
// «Analizza di nuovo»: the viewer analyses again what is already analysed.
library.Clock.Now += TimeSpan.FromHours(1);
Assert.AreEqual(StillVideoAnswerKind.Analysed, (await service.AnalyseNowAsync(still.Id, ct)).Kind);
Assert.AreEqual(library.Clock.Now, (await library.Db.VideoAnalyses.GetAsync(still.Sha256!, ct))!.AnalyzedAt);
}
[TestMethod]
public async Task TheViewerRunsDuringAnEngineSessionAndWhileALongWorkRuns()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var (_, video) = await SaveVideoAsync(library, "1", StillVideo(2));
var gate = new LongWorkGate();
Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var import, out _));
using (import)
{
using var service = new StillVideoService(Environment(library, gate) with { Session = new FakeSessionState { InSession = true } });
Assert.AreEqual(StillVideoAnswerKind.Analysed, (await service.AnalyseNowAsync(video.Id, ct)).Kind, "like a frame preview (answer 43)");
}
}
[TestMethod]
public async Task APhotoAMissingFileAndAnUnknownIdAreAnsweredAndNothingIsStored()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var account = await AccountAsync(library);
var photo = (await library.SaveAsync(account, Make.Entry(account.Id, "1", Make.T0), [TestFile.Photo(1, 3, 64, 48)])).Media[0];
var (_, video) = await SaveVideoAsync(library, "2", StillVideo(3));
File.Delete(library.Layout.FullPath(account, video.RelativePath!));
using var service = new StillVideoService(Environment(library));
var answers = new[]
{
await service.AnalyseNowAsync(photo.Id, ct),
await service.AnalyseNowAsync(video.Id, ct),
await service.AnalyseNowAsync(9999, ct),
};
CollectionAssert.AreEqual(
new[] { StillVideoAnswerKind.NotAVideo, StillVideoAnswerKind.FileMissing, StillVideoAnswerKind.NotFound },
answers.Select(a => a.Kind).ToArray());
Assert.AreEqual(StillVideoText.FileMissing, answers[1].Message);
Assert.IsNull(await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct));
}
[TestMethod]
public async Task AChangedFileIsNotAnalysedExceptInTheDemo()
{
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(4));
await File.WriteAllBytesAsync(library.Layout.FullPath(account, video.RelativePath!), StillVideo(5), ct);
var calls = new ConcurrentQueue<string>();
using (var service = new StillVideoService(Environment(library) with { Analyser = Counting(calls) }))
{
var answer = await service.AnalyseNowAsync(video.Id, ct);
Assert.AreEqual((StillVideoAnswerKind.SourceChanged, StillVideoText.SourceChanged), (answer.Kind, answer.Message));
}
Assert.IsEmpty(calls, "the bytes are checked before the analysis");
Assert.IsNull(await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct));
// The demo's files are shared and never have the recorded SHA-256 (D14).
using var demo = new StillVideoService(Environment(library) with { VerifySource = false });
Assert.AreEqual(StillVideoAnswerKind.Analysed, (await demo.AnalyseNowAsync(video.Id, ct)).Kind);
}
[TestMethod]
public async Task PastItsBudgetTheViewerStoresNothing()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var (_, video) = await SaveVideoAsync(library, "1", StillVideo(6));
using var service = new StillVideoService(Environment(library) with { ViewerBudget = TimeSpan.Zero });
var answer = await service.AnalyseNowAsync(video.Id, ct);
Assert.AreEqual(StillVideoAnswerKind.TooSlow, answer.Kind);
Assert.AreEqual("L'analisi richiede troppo tempo: avviala dalla selezione", answer.Message);
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()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var account = await AccountAsync(library);
var (_, first) = await SaveVideoAsync(library, "1", StillVideo(7));
// The same file under a second entry (an import with «Tieni entrambi», say).
var second = (await library.Db.Entries.AddAsync(
Make.Entry(account.Id, "2", Make.T0.AddMinutes(2)), [Make.Stored(Make.Video(1), first.Sha256!, first.RelativePath!)], ct)).Stored.Media[0];
var (_, moving) = await SaveVideoAsync(library, "3", MovingVideo());
var (_, done) = await SaveVideoAsync(library, "4", StillVideo(8));
var waiting = await library.Db.Entries.AddAsync(Make.Entry(account.Id, "5", Make.T0.AddMinutes(5)), [Make.Video(1)], ct); // not downloaded
var photo = await library.SaveAsync(account, Make.Entry(account.Id, "6", Make.T0.AddMinutes(6)), [TestFile.Photo(1, 4, 64, 48)]);
await library.Db.VideoAnalyses.SetAsync(new VideoAnalysis(done.Sha256!, StillVideoAnalyzer.Algorithm, VideoAnalysisOutcome.Moving, Make.T0), ct);
Assert.AreEqual(first.Sha256, second.Sha256);
var calls = new ConcurrentQueue<string>();
var changed = new ConcurrentQueue<long?>();
using var service = new StillVideoService(Environment(library) with { Analyser = Counting(calls), Changed = changed.Enqueue });
var selection = new ExportSelection.Entries([first.EntryId, second.EntryId, moving.EntryId, done.EntryId, waiting.Stored.Entry.Id, photo.Entry.Id]);
var plan = await service.PlanAsync(selection, ct);
Assert.AreEqual((2, 1, 1, 1, 4), (plan.ToAnalyse, plan.AlreadyAnalysed, plan.PhotosSkipped, plan.Missing, plan.Videos));
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, 2), (started.Running, started.Total, started.Added));
await service.Job.WaitAsync(Patience, ct);
var progress = service.Progress;
Assert.AreEqual((false, 2, 2, 1, 1, 0, 0, false), (progress.Running, progress.Total, progress.Done, progress.Still, progress.Moving, progress.NotAnalyzable, progress.Skipped, progress.Stopped));
Assert.IsNull(progress.CurrentMediaId);
Assert.AreEqual("Analizzati 2 video: 1 fermo, 1 in movimento", StillVideoText.Summary(progress));
Assert.HasCount(2, calls, "the shared file is analysed once");
Assert.AreEqual(VideoAnalysisOutcome.Still, (await library.Db.VideoAnalyses.GetAsync(first.Sha256!, ct))!.Outcome);
Assert.AreEqual(VideoAnalysisOutcome.Moving, (await library.Db.VideoAnalyses.GetAsync(moving.Sha256!, ct))!.Outcome);
Assert.AreEqual(Make.T0, (await library.Db.VideoAnalyses.GetAsync(done.Sha256!, ct))!.AnalyzedAt, "an analysed video is skipped");
Assert.HasCount(2, changed);
Assert.AreEqual(0, (await service.PlanAsync(selection, ct)).ToAnalyse);
Assert.IsFalse((await service.StartAsync(selection, ct)).Running, "nothing left to analyse");
}
[TestMethod]
public async Task TheJobWaitsForAnEngineSessionAndForALongWork()
{
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(10));
var session = new FakeSessionState { InSession = true };
var gate = new LongWorkGate();
var calls = new ConcurrentQueue<string>();
using var service = new StillVideoService(Environment(library, gate) with { Session = session, Analyser = Counting(calls) });
await service.StartAsync(new ExportSelection.Account(account.Id), ct);
await UntilAsync(() => service.Progress.Waiting == StillVideoText.InSession, ct);
Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var import, out _), "the job holds no lease: an import starts at once");
session.InSession = false;
await UntilAsync(() => service.Progress.Waiting == StillVideoText.LongWork, ct);
Assert.IsEmpty(calls);
Assert.IsTrue(service.Progress.Running);
import.Dispose();
await service.Job.WaitAsync(Patience, ct);
Assert.HasCount(1, calls);
Assert.AreEqual(VideoAnalysisOutcome.Still, (await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct))!.Outcome);
}
[TestMethod]
public async Task AStartAsksAnAutomaticCopyToStopAndWaitsUntilItLetsGo()
{
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(12));
var empty = await library.Db.Accounts.AddAsync(Make.Account("luca.demo", "200"));
var gate = new LongWorkGate();
var calls = new ConcurrentQueue<string>();
using var service = new StillVideoService(Environment(library, gate) with { Analyser = Counting(calls) });
Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out var yield, out _));
// Nothing to search: the copy goes on.
Assert.IsFalse((await service.StartAsync(new ExportSelection.Account(empty.Id), ct)).Running);
Assert.IsFalse(yield.IsCancellationRequested);
// «Cerca i video fermi» comes first (§16 answer 49): the copy is asked to stop, and the job waits for the gate.
await service.StartAsync(new ExportSelection.Account(account.Id), ct);
Assert.IsTrue(yield.IsCancellationRequested);
await UntilAsync(() => service.Progress.Waiting == StillVideoText.LongWork, ct);
Assert.IsEmpty(calls);
automatic.Dispose();
await service.Job.WaitAsync(Patience, ct);
Assert.HasCount(1, calls);
Assert.AreEqual(VideoAnalysisOutcome.Still, (await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct))!.Outcome);
}
/// <summary>
/// An automatic copy that takes the gate after the search started (in the moment between the worker's look and its
/// start) is asked to stop at the search's next look, not waited for to the end (§16 answer 49).
/// </summary>
[TestMethod]
public async Task AnAutomaticCopyThatStartsAfterTheSearchIsAskedToStop()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var (account, video) = await SaveVideoAsync(library, "1", StillVideo(13));
var session = new FakeSessionState { InSession = true };
var gate = new LongWorkGate();
var calls = new ConcurrentQueue<string>();
using var service = new StillVideoService(Environment(library, gate) with { Session = session, Analyser = Counting(calls) });
await service.StartAsync(new ExportSelection.Account(account.Id), ct);
await UntilAsync(() => service.Progress.Waiting == StillVideoText.InSession, ct);
Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out var yield, out _));
Assert.IsFalse(yield.IsCancellationRequested);
session.InSession = false;
await UntilAsync(() => yield.IsCancellationRequested, ct);
Assert.IsEmpty(calls);
automatic.Dispose();
await service.Job.WaitAsync(Patience, ct);
Assert.HasCount(1, calls);
Assert.AreEqual(VideoAnalysisOutcome.Still, (await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct))!.Outcome);
}
[TestMethod]
public async Task ASessionThatStartsDuringAnAnalysisMakesTheJobGiveWay()
{
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(11));
var session = new FakeSessionState();
var blocker = new Blocker(library.Layout.FullPath(account, video.RelativePath!));
using var service = new StillVideoService(Environment(library) with { Session = session, Analyser = blocker.Analyse });
await service.StartAsync(new ExportSelection.Account(account.Id), ct);
await blocker.Started.Task.WaitAsync(Patience, ct);
session.InSession = true;
await blocker.Cancelled.Task.WaitAsync(Patience, ct);
await UntilAsync(() => service.Progress.Waiting == StillVideoText.InSession && service.Progress.CurrentMediaId is null, ct);
Assert.IsNull(await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct), "a video given up stores nothing");
session.InSession = false;
await service.Job.WaitAsync(Patience, ct);
Assert.AreEqual(2, blocker.Calls, "analysed again after the session");
Assert.AreEqual(VideoAnalysisOutcome.Still, (await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct))!.Outcome);
}
[TestMethod]
public async Task TheViewerComesBeforeTheJob()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var (account, queued) = await SaveVideoAsync(library, "1", StillVideo(12));
var (_, viewed) = await SaveVideoAsync(library, "2", MovingVideo());
var blocker = new Blocker(library.Layout.FullPath(account, queued.RelativePath!));
using var service = new StillVideoService(Environment(library) with { Analyser = blocker.Analyse });
await service.StartAsync(new ExportSelection.Media([queued.Id]), ct);
await blocker.Started.Task.WaitAsync(Patience, ct);
var answer = await service.AnalyseNowAsync(viewed.Id, ct);
Assert.AreEqual(VideoAnalysisOutcome.Moving, answer.Analysis!.Outcome);
await blocker.Cancelled.Task.WaitAsync(Patience, ct); // the job's video was given up for the viewer
await service.Job.WaitAsync(Patience, ct);
Assert.AreEqual(2, blocker.Calls, "and analysed again after it");
Assert.AreEqual((1, 1), (service.Progress.Done, service.Progress.Still));
Assert.AreEqual(VideoAnalysisOutcome.Still, (await library.Db.VideoAnalyses.GetAsync(queued.Sha256!, ct))!.Outcome);
}
[TestMethod]
public async Task StopStoresNothingAndAStartAgainGoesOnWhereItWas()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var (account, first) = await SaveVideoAsync(library, "1", StillVideo(13));
var (_, second) = await SaveVideoAsync(library, "2", MovingVideo());
var blocker = new Blocker(library.Layout.FullPath(account, first.RelativePath!));
var selection = new ExportSelection.Account(account.Id);
using (var service = new StillVideoService(Environment(library) with { Analyser = blocker.Analyse }))
{
await service.StartAsync(selection, ct);
await blocker.Started.Task.WaitAsync(Patience, ct);
var stopped = service.Stop();
Assert.IsTrue(stopped.Stopped);
await service.Job.WaitAsync(Patience, ct);
var progress = service.Progress;
Assert.AreEqual((false, true, 0, 2), (progress.Running, progress.Stopped, progress.Done, progress.Total));
Assert.IsNull(await library.Db.VideoAnalyses.GetAsync(first.Sha256!, ct), "the video in progress stores nothing");
Assert.IsNull(await library.Db.VideoAnalyses.GetAsync(second.Sha256!, ct), "the queue emptied");
Assert.AreEqual(1, blocker.Calls);
}
// Febe closed (a new service): nothing resumes by itself; started again, the job does it all.
using var again = new StillVideoService(Environment(library));
Assert.IsFalse(again.Progress.Running);
await again.StartAsync(selection, ct);
await again.Job.WaitAsync(Patience, ct);
Assert.AreEqual((2, false), (again.Progress.Done, again.Progress.Stopped));
Assert.AreEqual(2, (await again.PlanAsync(selection, ct)).AlreadyAnalysed);
}
[TestMethod]
public async Task OnlyTheJobStoresTooSlow()
{
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(14));
using var service = new StillVideoService(Environment(library) with { JobBudget = TimeSpan.Zero });
await service.StartAsync(new ExportSelection.Account(account.Id), ct);
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), "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]
public async Task TheJobTakesTurnsWithTheConversions()
{
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(15));
var throttle = new ConversionThrottle();
var calls = new ConcurrentQueue<string>();
using var service = new StillVideoService(Environment(library) with { Throttle = throttle, Analyser = Counting(calls) });
var busy = new TaskCompletionSource();
var release = new TaskCompletionSource();
var conversion = throttle.RunAsync(_ =>
{
busy.SetResult();
release.Task.Wait(ct);
return 0;
}, ct);
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();
await conversion;
await service.Job.WaitAsync(Patience, ct);
Assert.HasCount(1, calls);
}
[TestMethod]
public async Task AJobAskedWhileOneRunsAddsItsVideos()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var (account, first) = await SaveVideoAsync(library, "1", StillVideo(16));
var (_, second) = await SaveVideoAsync(library, "2", MovingVideo());
var blocker = new Blocker(library.Layout.FullPath(account, first.RelativePath!), cancelOnly: false);
using var service = new StillVideoService(Environment(library) with { Analyser = blocker.Analyse });
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, 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);
Assert.AreEqual((2, 1, 1), (service.Progress.Done, service.Progress.Still, service.Progress.Moving));
}
[TestMethod]
[DataRow(LongWorkKind.Import)]
[DataRow(LongWorkKind.Export)]
[DataRow(LongWorkKind.Rebuild)]
[DataRow(LongWorkKind.FrameDownload)]
public async Task TheJobNeverWorksTogetherWithALongWork(LongWorkKind kind)
{
// Answer 41: import, copies and rebuild (and a zip of frames); the one that starts during an analysis is never
// made to wait: the job gives its video up.
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(20));
var gate = new LongWorkGate();
var blocker = new Blocker(library.Layout.FullPath(account, video.RelativePath!));
using var service = new StillVideoService(Environment(library, gate) with { Analyser = blocker.Analyse });
await service.StartAsync(new ExportSelection.Account(account.Id), ct);
await blocker.Started.Task.WaitAsync(Patience, ct);
Assert.IsTrue(gate.TryEnter(kind, out var lease, out _), "the job holds no lease");
using (lease)
{
await blocker.Cancelled.Task.WaitAsync(Patience, ct);
await UntilAsync(() => service.Progress.Waiting == StillVideoText.LongWork && service.Progress.CurrentMediaId is null, ct);
Assert.IsNull(await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct));
Assert.AreEqual((true, 0, 1), (service.Progress.Running, service.Progress.Done, blocker.Calls));
}
await service.Job.WaitAsync(Patience, ct);
Assert.AreEqual((1, 1, 2), (service.Progress.Done, service.Progress.Still, blocker.Calls));
}
[TestMethod]
public async Task AFileGoneOrChangedIsSkippedAndTheJobGoesOn()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var (account, first) = await SaveVideoAsync(library, "1", StillVideo(21));
var (_, gone) = await SaveVideoAsync(library, "2", StillVideo(22));
var (_, changed) = await SaveVideoAsync(library, "3", StillVideo(23));
var (_, replaced) = await SaveVideoAsync(library, "4", StillVideo(24));
var (_, last) = await SaveVideoAsync(library, "5", MovingVideo());
var calls = new ConcurrentQueue<string>();
var blocker = new Blocker(library.Layout.FullPath(account, first.RelativePath!), cancelOnly: false);
using var service = new StillVideoService(Environment(library) with
{
Analyser = (path, budget, token) =>
{
calls.Enqueue(path);
return blocker.Analyse(path, budget, token);
},
});
// While the first one is analysed: a file goes, one changes on disk, one is replaced in the database («Tieni il più
// grande», a rebuild), so that its old analysis would be of another file.
await service.StartAsync(new ExportSelection.Account(account.Id), ct);
await blocker.Started.Task.WaitAsync(Patience, ct);
File.Delete(library.Layout.FullPath(account, gone.RelativePath!));
await File.WriteAllBytesAsync(library.Layout.FullPath(account, changed.RelativePath!), StillVideo(25), ct);
await library.Db.Media.UpdateAsync((await library.Db.Media.GetAsync(replaced.Id, ct))! with { Sha256 = Make.Sha(77) }, ct);
blocker.Release();
await service.Job.WaitAsync(Patience, ct);
var progress = service.Progress;
Assert.AreEqual((5, 5, 1, 1, 0, 3), (progress.Total, progress.Done, progress.Still, progress.Moving, progress.NotAnalyzable, progress.Skipped));
Assert.AreEqual("Analizzati 2 video: 1 fermo, 1 in movimento, 3 saltati", StillVideoText.Summary(progress));
Assert.HasCount(2, calls, "only the files that are the ones recorded are analysed");
foreach (var sha in new[] { gone.Sha256!, changed.Sha256!, replaced.Sha256!, Make.Sha(77) })
{
Assert.IsNull(await library.Db.VideoAnalyses.GetAsync(sha, ct), "nothing is stored for a video left out");
}
Assert.IsNotNull(await library.Db.VideoAnalyses.GetAsync(last.Sha256!, ct));
// Put back, the changed one is analysed when asked again: nothing said it was done.
Assert.AreEqual(3, (await service.PlanAsync(new ExportSelection.Account(account.Id), ct)).ToAnalyse);
}
[TestMethod]
public async Task AnUnexpectedErrorSkipsTheVideoAndTheLogHasNoPath()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var (account, first) = await SaveVideoAsync(library, "1", StillVideo(26));
var (_, second) = await SaveVideoAsync(library, "2", MovingVideo());
var firstPath = library.Layout.FullPath(account, first.RelativePath!);
var log = new ConcurrentQueue<string>();
using var service = new StillVideoService(Environment(library) with
{
Log = log.Enqueue,
Analyser = (path, budget, token) => path == firstPath
? throw new InvalidOperationException("guasto in " + path)
: RealAnalysis(path, budget, token),
});
await service.StartAsync(new ExportSelection.Account(account.Id), ct);
await service.Job.WaitAsync(Patience, ct);
Assert.AreEqual((2, 1, 1), (service.Progress.Done, service.Progress.Moving, service.Progress.Skipped));
Assert.IsNull(await library.Db.VideoAnalyses.GetAsync(first.Sha256!, ct));
Assert.IsNotNull(await library.Db.VideoAnalyses.GetAsync(second.Sha256!, ct));
var line = log.Single();
Assert.AreEqual("Un video non si è potuto analizzare (InvalidOperationException).", line, "the type only: no path, no message (rule 10)");
}
[TestMethod]
public async Task AVideoAnalysedFromTheViewerMeanwhileIsCountedNotAnalysedAgain()
{
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(27));
var session = new FakeSessionState { InSession = true };
var calls = new ConcurrentQueue<string>();
using var service = new StillVideoService(Environment(library) with { Session = session, Analyser = Counting(calls) });
await service.StartAsync(new ExportSelection.Account(account.Id), ct);
await UntilAsync(() => service.Progress.Waiting == StillVideoText.InSession, ct);
Assert.AreEqual(StillVideoAnswerKind.Analysed, (await service.AnalyseNowAsync(video.Id, ct)).Kind, "the viewer does not wait for the session (answer 43)");
session.InSession = false;
await service.Job.WaitAsync(Patience, ct);
Assert.HasCount(1, calls);
Assert.AreEqual((1, 1, 1), (service.Progress.Total, service.Progress.Done, service.Progress.Still));
}
[TestMethod]
public async Task TheViewerAnalysesOneVideoAtATimeAndACancelledRequestStoresNothing()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var (account, first) = await SaveVideoAsync(library, "1", StillVideo(28));
var (_, second) = await SaveVideoAsync(library, "2", MovingVideo());
var blocker = new Blocker(library.Layout.FullPath(account, first.RelativePath!));
var atWork = 0;
var most = 0;
using var service = new StillVideoService(Environment(library) with
{
Analyser = (path, budget, token) =>
{
var now = Interlocked.Increment(ref atWork);
InterlockedMax(ref most, now);
try
{
return blocker.Analyse(path, budget, token);
}
finally
{
Interlocked.Decrement(ref atWork);
}
},
});
using var closed = CancellationTokenSource.CreateLinkedTokenSource(ct);
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();
await Assert.ThrowsAsync<OperationCanceledException>(() => one);
Assert.AreEqual(VideoAnalysisOutcome.Moving, (await two.WaitAsync(Patience, ct)).Analysis!.Outcome);
Assert.IsNull(await library.Db.VideoAnalyses.GetAsync(first.Sha256!, ct));
Assert.AreEqual(1, Volatile.Read(ref most));
Assert.AreEqual(StillVideoAnswerKind.Analysed, (await service.AnalyseNowAsync(first.Id, ct)).Kind, "asked again, it is analysed");
}
[TestMethod]
public async Task AFileKeepsItsAnalysisUnderEveryEntryAndLosesItWhenItIsAnother()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var (account, first) = await SaveVideoAsync(library, "1", StillVideo(29));
using var service = new StillVideoService(Environment(library));
Assert.AreEqual(StillVideoAnswerKind.Analysed, (await service.AnalyseNowAsync(first.Id, ct)).Kind);
// The same file under an entry added later (an import): already analysed, with no work.
var again = (await library.Db.Entries.AddAsync(
Make.Entry(account.Id, "9", Make.T0.AddMinutes(9)), [Make.Stored(Make.Video(1), first.Sha256!, first.RelativePath!)], ct)).Stored;
var plan = await service.PlanAsync(new ExportSelection.Entries([again.Entry.Id]), ct);
Assert.AreEqual((0, 1), (plan.ToAnalyse, plan.AlreadyAnalysed));
// A row of an algorithm newer than this Febe's (a database opened by a later version first): not analysed again.
await library.Db.VideoAnalyses.SetAsync(new VideoAnalysis(first.Sha256!, StillVideoAnalyzer.Algorithm + 1, VideoAnalysisOutcome.Moving, Make.T0), ct);
Assert.AreEqual(0, (await service.PlanAsync(new ExportSelection.Account(account.Id), ct)).ToAnalyse);
// Another file in its place: its SHA-256 has no analysis, so it is to analyse.
await library.Db.Media.UpdateAsync((await library.Db.Media.GetAsync(first.Id, ct))! with { Sha256 = Make.Sha(78) }, ct);
plan = await service.PlanAsync(new ExportSelection.Media([first.Id]), ct);
Assert.AreEqual((1, 0), (plan.ToAnalyse, plan.AlreadyAnalysed));
}
[TestMethod]
public async Task InterrompiWhileItWaitsEndsTheJobAndANewOneStartsFromZero()
{
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(30));
var session = new FakeSessionState { InSession = true };
using var service = new StillVideoService(Environment(library) with { Session = session });
var selection = new ExportSelection.Account(account.Id);
Assert.IsFalse(service.Stop().Stopped, "nothing to stop");
await service.StartAsync(selection, ct);
await UntilAsync(() => service.Progress.Waiting == StillVideoText.InSession, ct);
service.Stop();
await service.Job.WaitAsync(Patience, ct);
Assert.AreEqual((false, true, 1, 0), (service.Progress.Running, service.Progress.Stopped, service.Progress.Total, service.Progress.Done));
Assert.IsNull(service.Progress.Waiting);
session.InSession = false;
var started = await service.StartAsync(selection, ct);
Assert.AreEqual((true, false, 1, 0), (started.Running, started.Stopped, started.Total, started.Done));
await service.Job.WaitAsync(Patience, ct);
Assert.AreEqual((1, 1, false), (service.Progress.Done, service.Progress.Still, service.Progress.Stopped));
Assert.IsNotNull(await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct));
}
[TestMethod]
public async Task ClosingFebeLeavesTheVideoAtWorkAndStoresNothing()
{
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(31));
var blocker = new Blocker(library.Layout.FullPath(account, video.RelativePath!));
var service = new StillVideoService(Environment(library) with { Analyser = blocker.Analyse });
await service.StartAsync(new ExportSelection.Account(account.Id), ct);
await blocker.Started.Task.WaitAsync(Patience, ct);
service.Dispose();
service.Dispose();
await service.Job.WaitAsync(Patience, ct);
Assert.IsFalse(service.Progress.Running);
Assert.IsNull(await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct));
await Assert.ThrowsExactlyAsync<ObjectDisposedException>(() => service.AnalyseNowAsync(video.Id, ct));
await Assert.ThrowsExactlyAsync<ObjectDisposedException>(() => service.StartAsync(new ExportSelection.Account(account.Id), ct));
}
[TestMethod]
public void TheTextsCountInItalian()
{
// The confirmation and the end of the job, one and many (the words of the design, questions 41 and 44).
Assert.AreEqual("28 video da analizzare · 12 già analizzati · le 5 foto si saltano", StillVideoText.PlanSummary(new StillVideoPlan(28, 12, 5, 0)));
Assert.AreEqual("1 video da analizzare · 1 già analizzato · la foto si salta · 1 video non presente in libreria", StillVideoText.PlanSummary(new StillVideoPlan(1, 1, 1, 1)));
Assert.AreEqual("1.200 video da analizzare · 3 video non presenti in libreria", StillVideoText.PlanSummary(new StillVideoPlan(1200, 0, 0, 3)));
StillVideoProgress Ended(int still, int moving, int not, int skipped) => new(false, still + moving + not + skipped, still + moving + not + skipped, still, moving, not, skipped, false, null, null);
Assert.AreEqual("Analizzati 28 video: 3 fermi, 24 in movimento, 1 non analizzabile", StillVideoText.Summary(Ended(3, 24, 1, 0)));
Assert.AreEqual("Analizzato 1 video: 1 fermo, 0 in movimento, 1 saltato", StillVideoText.Summary(Ended(1, 0, 0, 1)));
Assert.AreEqual("Analizzati 2 video: 0 fermi, 0 in movimento, 2 non analizzabili, 2 saltati", StillVideoText.Summary(Ended(0, 0, 2, 2)));
}
// ------------------------------------------------------------------------------------------------- helpers
private static void InterlockedMax(ref int target, int value)
{
int seen;
while ((seen = Volatile.Read(ref target)) < value && Interlocked.CompareExchange(ref target, value, seen) != seen)
{
}
}
private static byte[] StillVideo(int seed, bool audio = false)
{
var photo = PcmVideos.Photo(seed);
return PcmVideos.Mp4(12, _ => photo, audio: audio);
}
private static byte[] MovingVideo() => PcmVideos.Mp4(12, i => PcmVideos.Photo(100 + i));
private static async Task<Core.Domain.Account> AccountAsync(TestLibrary library) =>
await library.Db.Accounts.FindByUsernameAsync("marta.demo") ?? await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100"));
private static async Task<(Core.Domain.Account Account, Media Media)> SaveVideoAsync(TestLibrary library, string id, byte[] bytes)
{
var account = await AccountAsync(library);
var minutes = int.Parse(id, System.Globalization.CultureInfo.InvariantCulture);
var entry = await library.SaveAsync(account, Make.Entry(account.Id, id, Make.T0.AddMinutes(minutes)), [new TestFile(Make.Video(1), bytes, ".mp4")]);
var media = entry.Media[0];
Assert.IsTrue(EntryStateRules.IsPresent(media.State));
return (account, media);
}
private static StillVideoEnvironment Environment(TestLibrary library, LongWorkGate? gate = null) => new()
{
Storage = library.Db,
Resolve = (account, media) => media.RelativePath is { } relative && library.Layout.FullPath(account, relative) is var path && File.Exists(path) ? path : null,
Clock = new PollingClock(library.Clock),
Gate = gate,
Throttle = new ConversionThrottle(),
Poll = TimeSpan.FromMilliseconds(5),
};
/// <summary>The real analysis, counting the files it is given.</summary>
private static Func<string, TimeSpan, CancellationToken, StillVideoResult> Counting(ConcurrentQueue<string> calls) => (path, budget, ct) =>
{
calls.Enqueue(path);
return RealAnalysis(path, budget, ct);
};
private static StillVideoResult RealAnalysis(string path, TimeSpan budget, CancellationToken ct)
{
using var stream = File.OpenRead(path);
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);
limit.CancelAfter(Patience);
while (!condition())
{
await Task.Delay(2, limit.Token);
}
}
/// <summary>
/// An analysis that, the first time it is given <paramref name="path"/>, holds until its token is cancelled (or,
/// with <paramref name="cancelOnly"/> false, until <see cref="Release"/>); every other call is the real analysis.
/// </summary>
private sealed class Blocker(string path, bool cancelOnly = true)
{
private readonly ManualResetEventSlim _release = new();
private int _calls;
public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TaskCompletionSource Cancelled { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public int Calls => Volatile.Read(ref _calls);
public void Release() => _release.Set();
public StillVideoResult Analyse(string file, TimeSpan budget, CancellationToken ct)
{
if (string.Equals(file, path, StringComparison.Ordinal) && Interlocked.Increment(ref _calls) == 1)
{
Started.TrySetResult();
try
{
if (cancelOnly)
{
ct.WaitHandle.WaitOne(Patience);
}
else
{
_release.Wait(Patience, ct);
}
ct.ThrowIfCancellationRequested();
}
catch (OperationCanceledException)
{
Cancelled.TrySetResult();
throw;
}
}
return RealAnalysis(file, budget, ct);
}
}
/// <summary>The library's manual time, with waits that really pass (a few milliseconds), so a polling loop never spins.</summary>
private sealed class PollingClock(ManualClock time) : IClock
{
public DateTimeOffset Now => time.Now;
public TimeZoneInfo LocalZone => time.LocalZone;
public Task Delay(TimeSpan wait, CancellationToken ct) => Task.Delay(wait, ct);
}
}