merge: analysis and render jobs, render node client and server managed fallback

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-03 10:34:30 +00:00
commit 8396aada66
53 files changed
+2412 -291

No files matched your search

@@ -0,0 +1,53 @@
using System.IO;
using Titano.App.Infrastructure;
using Titano.App.Tests.Uploader;
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Testing;
namespace Titano.App.Tests.Infrastructure;
public sealed class AppServicesTests
{
/// <summary>Dialogs that answer like a user who cancels everything.</summary>
private sealed class NoDialogs : IAppDialogs
{
public string? PickFolder(string title, string? initialFolder = null) => null;
public string? PickJsonFile(string title) => null;
public bool Confirm(ConfirmRequest request) => false;
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
}
[Test]
[WindowsOnly]
public void ExitStopsPollingAndTheEngineWhileTheUiThreadWaits()
{
var environment = AppEnvironment.ForCapture();
try
{
SingleThreadedContext.Run(async () =>
{
var root = Path.Combine(environment.DataDirectory, "archive");
await using (var setup = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(environment.DataDirectory, "setup.db"))))
await new ArchiveService(setup).CreateAsync(root, "Exit");
var services = new AppServices(environment, new AppSettings { Language = "en", LastArchivePath = root }, () => { }, new NoDialogs());
await services.OpenAsync(environment.DatabasePath);
// The archive was reopened and its first rescan queued: polling now waits for the next one.
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
while ((await services.Database!.Jobs.ListAsync(null, JobKind.Scan)).Items.Count == 0)
{
Assert.True(DateTime.UtcNow < until, "no rescan queued");
await Task.Delay(50);
}
// App.OnExit blocks the UI thread until the services stop: nothing they await may continue on it.
Assert.True(services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(10)), "services stopped");
});
}
finally
{
environment.DeleteCaptureData();
}
}
}
@@ -0,0 +1,146 @@
using System.IO;
using Titano.App.Infrastructure;
using Titano.Testing;
namespace Titano.App.Tests.Server;
public sealed class RenderNodeHostTests
{
private static readonly RenderNodeSession Nas = new(new Uri("https://nas.local:8443/"), "token-a", ["AA:BB", "CC:DD"], Hardware: true);
/// <summary>Records the nodes it starts; fails the first <see cref="Failures"/> starts.</summary>
private sealed class Nodes
{
public List<(RenderNodeSession Session, Node Node)> Started { get; } = [];
public int Failures { get; set; }
public IRenderNode Start(RenderNodeSession session)
{
if (Failures-- > 0) throw new IOException("cache folder unavailable");
var node = new Node();
Started.Add((session, node));
return node;
}
}
private sealed class Node : IRenderNode
{
private readonly TaskCompletionSource _completion = new();
public bool Stopped { get; private set; }
public Task Completion => _completion.Task;
/// <summary>The server refused the node (signed out, no render-node right): it ends by itself.</summary>
public void Refuse() => _completion.TrySetResult();
public ValueTask DisposeAsync()
{
Stopped = true;
_completion.TrySetResult();
return ValueTask.CompletedTask;
}
}
[Test]
public async Task TheNodeFollowsTheWantedSession()
{
var nodes = new Nodes();
await using var host = new RenderNodeHost(nodes.Start);
host.Update(Nas);
host.Update(Nas);
await host.Switching;
Assert.Equal(Nas, host.Session);
Assert.Count(1, nodes.Started);
// An equal session (fingerprints in another order) keeps the node.
host.Update(Nas with { TrustedFingerprints = ["CC:DD", "AA:BB"] });
await host.Switching;
Assert.Count(1, nodes.Started);
// A new token (signed in again) is another session: the old node stops before the new one starts.
var renewed = Nas with { Token = "token-b" };
host.Update(renewed);
await host.Switching;
Assert.True(nodes.Started[0].Node.Stopped, "old node stopped");
Assert.Equal((renewed, false), (nodes.Started[1].Session, nodes.Started[1].Node.Stopped));
// A forgotten certificate or another hardware choice also needs a new node.
host.Update(renewed with { TrustedFingerprints = [] });
await host.Switching;
host.Update(renewed with { TrustedFingerprints = [], Hardware = false });
await host.Switching;
Assert.Count(4, nodes.Started);
Assert.True(nodes.Started[2].Node.Stopped, "replaced again");
host.Update(null);
await host.Switching;
Assert.Null(host.Session);
Assert.True(nodes.Started[3].Node.Stopped, "stopped when no longer wanted");
}
[Test]
public async Task ANodeThatStoppedItselfIsStartedAgainByTheNextUpdate()
{
var nodes = new Nodes();
await using var host = new RenderNodeHost(nodes.Start);
host.Update(Nas);
await host.Switching;
nodes.Started[0].Node.Refuse();
host.Update(Nas);
await host.Switching;
Assert.Count(2, nodes.Started);
Assert.Equal((Nas, false), (host.Session, nodes.Started[1].Node.Stopped));
}
[Test]
public void TheNodeIsWantedOnlyWhenOfferedAndSignedIn()
{
var address = new Uri("https://nas.local:8443/");
Assert.Equal(Nas, RenderNodeSession.For(offered: true, connected: true, address, "token-a", ["AA:BB", "CC:DD"], hardware: true));
Assert.Null(RenderNodeSession.For(offered: false, connected: true, address, "token-a", [], hardware: true));
Assert.Null(RenderNodeSession.For(offered: true, connected: false, address, "token-a", [], hardware: true));
Assert.Null(RenderNodeSession.For(offered: true, connected: true, address, null, [], hardware: true)); // signed out
Assert.Null(RenderNodeSession.For(offered: true, connected: true, null, "token-a", [], hardware: true));
}
[Test]
public void HardwarePreferenceDecidesPerPreset()
{
Assert.True(AppServices.AllowsHardware(HardwarePreference.PreferHardware, "4k-hevc"));
Assert.False(AppServices.AllowsHardware(HardwarePreference.SoftwareOnly, "720p-preview"));
Assert.True(AppServices.AllowsHardware(HardwarePreference.HardwareForPreviews, "720p-preview"));
Assert.False(AppServices.AllowsHardware(HardwarePreference.HardwareForPreviews, "4k-hevc10-archive"));
}
[Test]
public async Task ANodeThatCannotStartIsRetriedByTheNextUpdate()
{
var nodes = new Nodes { Failures = 1 };
await using var host = new RenderNodeHost(nodes.Start);
host.Update(Nas);
await host.Switching;
Assert.Null(host.Session);
host.Update(Nas);
await host.Switching;
Assert.Equal(Nas, host.Session);
}
[Test]
public async Task DisposingStopsTheNodeAndIgnoresLaterUpdates()
{
var nodes = new Nodes();
var host = new RenderNodeHost(nodes.Start);
host.Update(Nas);
await host.DisposeAsync();
Assert.True(nodes.Started.Single().Node.Stopped, "stopped on exit");
host.Update(Nas);
await host.Switching;
Assert.Count(1, nodes.Started);
}
}
@@ -59,6 +59,68 @@ public sealed class ProjectSettingsTests
public void NewerVersionIsRefused() =>
Assert.Throws<InvalidDataException>(() => ProjectSettings.FromJson("{\"version\": 99}"));
[Test]
public void MissingMembersKeepTheirDefaults()
{
var defaults = new ProjectSettings().ToJson();
Assert.Equal(defaults, ProjectSettings.FromJson("{}").ToJson());
Assert.Equal(defaults, ProjectSettings.FromJson("null").ToJson());
// An API client's partial edit: one manual value, a section given as null, keys in another casing.
var partial = ProjectSettings.FromJson(
"""{ "Exposure": { "deflicker": { "isAuto": false, "manual": false } }, "motion": null, "export": { "preset": { "isAuto": false, "manual": "4k-hevc" } } }""");
Assert.False(partial.Exposure.Deflicker.Resolve(true));
Assert.True(partial.Exposure.HolyGrail.IsAuto);
Assert.Equal(0.9, partial.Exposure.HighlightKnee);
Assert.True(partial.Motion.Stabilize.IsAuto);
Assert.Equal("4k-hevc", partial.Export.Preset.Resolve("1080p-h264"));
Assert.Equal("{date} {title} - {preset}", partial.Export.NameTemplate);
Assert.SequenceEqual(new[] { 0.0, 1.0 }, partial.Timing.RemapCurve.Select(p => p.X));
Assert.Equal(9, partial.Stack.Length);
Assert.Equal(ProjectSettings.CurrentVersion, partial.Version);
// An explicit null clears a nullable value; arrays are replaced, not merged.
var cleared = ProjectSettings.FromJson("""{ "exposure": { "highlightKnee": null }, "timing": { "remapCurve": [ { "x": 0, "y": 0.5 } ] } }""");
Assert.Null(cleared.Exposure.HighlightKnee);
Assert.Equal(1, cleared.Timing.RemapCurve.Count);
}
[Test]
public void NullHighlightKneeSurvivesTheRoundTrip()
{
// "No knee, hard clip" must not come back as the default knee when the project is rewritten.
var off = new ProjectSettings { Exposure = new ExposureSettings { HighlightKnee = null } };
Assert.Contains("\"highlightKnee\": null", off.ToJson());
Assert.Null(ProjectSettings.FromJson(off.ToJson()).Exposure.HighlightKnee);
Assert.Equal(0.9, ProjectSettings.FromJson(new ProjectSettings().ToJson()).Exposure.HighlightKnee);
}
[Test]
public void NullListsAndTextsKeepTheirDefaults()
{
var project = ProjectSettings.FromJson(
"""{ "excludedFrames": null, "export": { "batch": null, "nameTemplate": null }, "timing": { "remapCurve": null }, "camera": { "keyframes": null } }""");
Assert.Count(0, project.ExcludedFrames);
Assert.Count(0, project.Export.Batch);
Assert.Equal("{date} {title} - {preset}", project.Export.NameTemplate);
Assert.Count(2, project.Timing.RemapCurve);
Assert.Count(0, project.Camera.Keyframes);
// Nullable members without a default still clear.
Assert.Null(ProjectSettings.FromJson("""{ "export": { "folder": null }, "heroFrame": null }""").HeroFrame);
}
[Test]
public void DuplicateKeysAreAJsonError()
{
Assert.Throws<System.Text.Json.JsonException>(() => ProjectSettings.FromJson("""{ "version": 1, "version": 1 }"""));
Assert.Throws<System.Text.Json.JsonException>(() => ProjectSettings.FromJson("""{ "Export": {}, "export": {} }"""));
Assert.Throws<System.Text.Json.JsonException>(() => ProjectSettings.FromJson("""{ "export": { "batch": [], "Batch": [] } }"""));
}
[Test]
public void ProjectMustBeAnObject() =>
Assert.Throws<System.Text.Json.JsonException>(() => ProjectSettings.FromJson("[1, 2]"));
[Test]
public void BuiltInPresetIdsAreUnique() =>
Assert.Equal(ExportPresets.BuiltIn.Count, ExportPresets.BuiltIn.Select(p => p.Id).Distinct().Count());
@@ -80,11 +80,11 @@ internal sealed class ArchiveFixture : IAsyncDisposable
}
/// <summary>Queues a job directly with a checkpoint, as a crashed earlier attempt would have left it.</summary>
public async Task<Job> EnqueueWithCheckpointAsync(JobEngine engine, Titano.Data.Archiving.Jobs.ArchiveJobRequest request, string checkpoint)
public async Task<Job> EnqueueWithCheckpointAsync(JobEngine engine, Titano.Data.Archiving.Jobs.ArchiveJobRequest request, string checkpoint, Guid? id = null)
{
var job = new Job
{
Id = Guid.CreateVersion7(),
Id = id ?? Guid.CreateVersion7(),
Kind = request.Kind,
TargetIds = request.Targets,
ParametersJson = request.ParametersJson,
@@ -27,6 +27,37 @@ public sealed class JobEngineTests(TestContext context)
}
}
/// <summary>Takes only jobs whose parameters say they are its own.</summary>
private sealed class SelectiveHandler(JobKind kind) : ISelectiveJobHandler
{
public const string Mine = """{"mine":true}""";
public JobKind Kind => kind;
public ValueTask<bool> AcceptsAsync(Job job, CancellationToken cancellationToken) => ValueTask.FromResult(job.ParametersJson == Mine);
public Task RunAsync(JobContext c) => Task.CompletedTask;
}
/// <summary>Cannot judge jobs without parameters (as a render handler with a malformed preset) and fails them when run.</summary>
private sealed class FragileHandler(JobKind kind) : ISelectiveJobHandler
{
public JobKind Kind => kind;
public ValueTask<bool> AcceptsAsync(Job job, CancellationToken cancellationToken) =>
job.ParametersJson?.Length > 0 ? ValueTask.FromResult(true) : throw new ArgumentNullException(nameof(job));
public Task RunAsync(JobContext c) =>
c.Job.ParametersJson is null ? throw new InvalidDataException("no parameters") : Task.CompletedTask;
}
private sealed class CallbackHandler(JobKind kind, Func<JobContext, Task> run) : IJobHandler
{
public JobKind Kind => kind;
public Task RunAsync(JobContext context) => run(context);
}
private async Task<TitanoDatabase> OpenAsync() =>
await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(), "jobs.db")), context.Cancellation);
@@ -159,6 +190,68 @@ public sealed class JobEngineTests(TestContext context)
Assert.Equal(JobKind.Render, pending[0].Kind);
}
[Test]
public async Task SelectiveHandlersLeaveDeclinedJobsQueuedWithoutHoldingUpOthers()
{
await using var db = await OpenAsync();
await using var engine = new JobEngine(db, [new SelectiveHandler(JobKind.Render), new CountingHandler(JobKind.Thumbs, 1)],
new JobEngineOptions { Workers = 1, WorkerId = "t", PollInterval = TimeSpan.FromMilliseconds(50) });
var declined = await engine.EnqueueAsync(JobKind.Render, [], parametersJson: """{"mine":false}""", priority: JobPriority.User);
var thumbs = await engine.EnqueueAsync(JobKind.Thumbs, [], priority: JobPriority.Background);
var accepted = await engine.EnqueueAsync(JobKind.Render, [], parametersJson: SelectiveHandler.Mine, priority: JobPriority.User);
await engine.StartAsync();
var render = await WaitForStateAsync(db, accepted.Id, JobState.Done, TimeSpan.FromSeconds(10));
var other = await WaitForStateAsync(db, thumbs.Id, JobState.Done, TimeSpan.FromSeconds(10));
Assert.True(render.Started <= other.Started, "claim order: priority first, across selective and other kinds");
await Task.Delay(200);
var waiting = (await db.Jobs.GetAsync(declined.Id))!;
Assert.Equal((JobState.Queued, (string?)null), (waiting.State, waiting.NodeId));
}
[Test]
public async Task ASelectiveHandlerThatThrowsDoesNotStopTheWorkers()
{
await using var db = await OpenAsync();
await using var engine = new JobEngine(db, [new FragileHandler(JobKind.Render), new CountingHandler(JobKind.Thumbs, 1)],
new JobEngineOptions { Workers = 2, WorkerId = "t", PollInterval = TimeSpan.FromMilliseconds(50) });
var broken = await engine.EnqueueAsync(JobKind.Render, [], priority: JobPriority.User);
await engine.StartAsync();
var failed = await WaitForStateAsync(db, broken.Id, JobState.Failed, TimeSpan.FromSeconds(10));
Assert.Equal("no parameters", failed.Error);
// The workers are still there for every kind.
var thumbs = await engine.EnqueueAsync(JobKind.Thumbs, []);
var render = await engine.EnqueueAsync(JobKind.Render, [], parametersJson: "{}");
await WaitForStateAsync(db, thumbs.Id, JobState.Done, TimeSpan.FromSeconds(10));
await WaitForStateAsync(db, render.Id, JobState.Done, TimeSpan.FromSeconds(10));
}
[Test]
public async Task FollowUpsAreQueuedOnlyForKindsTheEngineRuns()
{
await using var db = await OpenAsync();
var target = Guid.CreateVersion7();
Job? thumbs = null, light = null;
var scan = new CallbackHandler(JobKind.Scan, async c =>
{
thumbs = await c.EnqueueFollowUpAsync(JobKind.Thumbs, [target], "Roof", null, JobPriority.Background);
light = await c.EnqueueFollowUpAsync(JobKind.LightAnalyse, [target], "Roof", null, JobPriority.Background);
});
await using var engine = new JobEngine(db, [scan, new CountingHandler(JobKind.Thumbs, 1)],
new JobEngineOptions { Workers = 1, WorkerId = "t", PollInterval = TimeSpan.FromMilliseconds(50) });
await engine.StartAsync();
var user = Guid.CreateVersion7();
var job = await engine.EnqueueAsync(JobKind.Scan, [], createdBy: user);
await WaitForStateAsync(db, job.Id, JobState.Done, TimeSpan.FromSeconds(10));
Assert.Null(light);
var followUp = await WaitForStateAsync(db, Assert.NotNull(thumbs).Id, JobState.Done, TimeSpan.FromSeconds(10));
Assert.Equal((user, JobPriority.Background, "Roof"), (followUp.CreatedBy!.Value, followUp.Priority, followUp.TargetLabel!));
Assert.SequenceEqual([target], followUp.TargetIds);
Assert.Empty((await db.Jobs.ListAsync(null, JobKind.LightAnalyse)).Items);
}
[Test]
public async Task HandlerFailureMarksJobFailedWithMessage()
{
@@ -0,0 +1,120 @@
using Titano.Core.Archiving;
using Titano.Core.Diagnostics.Synthetic;
using Titano.Core.Import;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Data.Archiving;
using Titano.Data.Tests.Archiving;
using Titano.Testing;
namespace Titano.Data.Tests.Processing;
/// <summary>New sequences get their light analysis (and so their Auto values) without any user action (BRIEF §1.1).</summary>
[Category("processing")]
public sealed class AnalysisFollowUpTests(TestContext context)
{
[Test]
public async Task AnAdoptingScanQueuesLightAnalysisOfTheNewSequencesOnly()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
fx.Write(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 12 }), "Roof");
await fx.StartEngineAsync(withArchive: true);
var scan = await fx.EnqueueAsync(ArchiveJobs.Scan(fx.Archive.Archive, full: true));
await fx.WaitForAsync(scan.Id, JobState.Done);
var light = Assert.NotNull(await SingleLightJobAsync(fx));
await fx.WaitForAsync(light.Id, JobState.Done);
var sequence = (await fx.Db.Sequences.GetAsync(light.TargetIds.Single(), fx.Ct))!;
Assert.Equal("Roof", sequence.Folder);
Assert.True(sequence.Status.HasFlag(SequenceStatus.AnalyzedLight), "analysed");
Assert.True(ProjectSettings.FromJson(await File.ReadAllTextAsync(fx.Folder(sequence).ProjectPath, fx.Ct)).Timing.Mode.HasAdvice, "advised");
// Scans that find nothing new queue nothing more.
foreach (var full in new[] { false, true })
{
var again = await fx.EnqueueAsync(ArchiveJobs.Scan(fx.Archive.Archive, full));
await fx.WaitForAsync(again.Id, JobState.Done);
}
Assert.Equal(light.Id, (await SingleLightJobAsync(fx))?.Id);
}
[Test]
public async Task AnImportQueuesLightAnalysisOfTheSequencesItFilled()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var card = context.CreateTempDirectory("card");
Photos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), ArchiveFixture.Start, 10);
var plan = await fx.Archive.Service.PlanImportAsync(fx.Archive.Archive.Id, card, new ImportOptions(), null, null, fx.Ct);
await fx.StartEngineAsync(withArchive: true);
var import = await fx.Engine.EnqueueAsync(ArchiveJobs.Import(fx.Archive.Archive, plan, null), createdBy: Guid.CreateVersion7(), cancellationToken: fx.Ct);
await fx.WaitForAsync(import.Id, JobState.Done);
var light = Assert.NotNull(await SingleLightJobAsync(fx));
await fx.WaitForAsync(light.Id, JobState.Done);
var sequenceId = await fx.Db.Sequences.FindBySessionKeyAsync(fx.Archive.Archive.Id, plan.Sessions.Single().SessionKey, fx.Ct);
Assert.SequenceEqual([Assert.NotNull(sequenceId)], light.TargetIds);
Assert.Equal(import.CreatedBy, light.CreatedBy);
Assert.Equal(JobPriority.Background, light.Priority);
Assert.True((await fx.Db.Sequences.GetAsync(sequenceId.Value, fx.Ct))!.Status.HasFlag(SequenceStatus.AnalyzedLight), "analysed");
}
[Test]
public async Task PhotosAddedToAnAnalysedFolderAreAnalysedAgain()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 12 }), "Roof");
await fx.StartEngineAsync(withArchive: true);
var first = await fx.EnqueueAsync(Titano.Data.Processing.ProcessingJobs.LightAnalysis([sequence.Id]));
await fx.WaitForAsync(first.Id, JobState.Done);
// The camera kept shooting into the folder: the next scan indexes the new photos and analyses the sequence again.
fx.Write(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 18 }), "Roof", first: 12);
var scan = await fx.EnqueueAsync(ArchiveJobs.Scan(fx.Archive.Archive));
await fx.WaitForAsync(scan.Id, JobState.Done);
var again = (await fx.Db.Jobs.ListAsync(null, JobKind.LightAnalyse, cancellationToken: fx.Ct)).Items.Single(j => j.Id != first.Id);
await fx.WaitForAsync(again.Id, JobState.Done);
var analysed = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.Equal(18, analysed.FrameCount);
Assert.True(analysed.Status.HasFlag(SequenceStatus.AnalyzedLight), "analysed again");
Assert.True(ManifestStore.ReadSequence(fx.Folder(sequence).ManifestPath).Status.HasFlag(SequenceStatus.AnalyzedLight), "sidecar status");
}
[Test]
public async Task ASequenceWaitingForLightAnalysisIsNotQueuedAgain()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 12 }), "Roof");
// Queued before the scan, which runs first (user priority) and finds the sequence not analysed yet.
var waiting = await QueueAsync(fx, Titano.Data.Processing.ProcessingJobs.LightAnalysis([sequence.Id]));
var scan = await QueueAsync(fx, ArchiveJobs.Scan(fx.Archive.Archive, full: true));
await fx.StartEngineAsync(withArchive: true);
await fx.WaitForAsync(scan.Id, JobState.Done);
await fx.WaitForAsync(waiting.Id, JobState.Done);
Assert.Equal(waiting.Id, (await SingleLightJobAsync(fx))?.Id);
}
/// <summary>Queues a job before the engine starts.</summary>
private static async Task<Job> QueueAsync(ProcessingFixture fx, Titano.Data.Archiving.Jobs.ArchiveJobRequest request)
{
var job = new Job
{
Id = Guid.CreateVersion7(),
Kind = request.Kind,
TargetIds = request.Targets,
TargetLabel = request.Label,
ParametersJson = request.ParametersJson,
Priority = request.Priority,
State = JobState.Queued,
Created = DateTimeOffset.UtcNow,
};
await fx.Db.Jobs.EnqueueAsync(job, fx.Ct);
return job;
}
private static async Task<Job?> SingleLightJobAsync(ProcessingFixture fx) =>
(await fx.Db.Jobs.ListAsync(null, JobKind.LightAnalyse, cancellationToken: fx.Ct)).Items.SingleOrDefault();
}
@@ -5,6 +5,7 @@ using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Data.Processing;
using Titano.Data.Processing.Jobs;
using Titano.Data.Repositories;
using Titano.Testing;
@@ -29,7 +30,12 @@ public sealed class AnalysisJobTests(TestContext context)
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Flickering());
var manual = new ProjectSettings();
manual = manual with { Timing = manual.Timing with { FrameRate = manual.Timing.FrameRate.WithManual("25") } };
// The user's frame rate, and the highlight knee turned off (hard clip).
manual = manual with
{
Timing = manual.Timing with { FrameRate = manual.Timing.FrameRate.WithManual("25") },
Exposure = manual.Exposure with { HighlightKnee = null },
};
await fx.Db.Sequences.EditAsync(sequence.Id, new SequenceEdit { SettingsJson = manual.ToJson() }, null, fx.Ct);
await fx.StartEngineAsync();
@@ -39,6 +45,7 @@ public sealed class AnalysisJobTests(TestContext context)
var folder = fx.Folder(sequence);
var project = ProjectSettings.FromJson(await File.ReadAllTextAsync(folder.ProjectPath, fx.Ct));
Assert.Equal((false, "25"), (project.Timing.FrameRate.IsAuto, project.Timing.FrameRate.Resolve("30")));
Assert.Null(project.Exposure.HighlightKnee);
Assert.True(project.Timing.Mode.HasAdvice, "timing mode advised");
Assert.True(project.Timing.FrameRate.HasAdvice, "the advice is kept next to the manual frame rate");
var row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
@@ -105,6 +112,55 @@ public sealed class AnalysisJobTests(TestContext context)
Assert.Contains(Loc.L("Advisor.Log.Presets", string.Empty), done.LogTail);
}
[Test]
public async Task ASequenceThatFailsDoesNotStopTheOthersAndARetryRedoesOnlyIt()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var a = await fx.AddAsync(Flickering(10), "A");
var b = await fx.AddAsync(Flickering(10), "B");
var c = await fx.AddAsync(Flickering(10), "C");
// B's sidecar is gone for a while: its status cannot be recorded.
var sidecar = fx.Folder(b).ManifestPath;
var saved = await File.ReadAllBytesAsync(sidecar, fx.Ct);
File.Delete(sidecar);
await fx.StartEngineAsync();
var job = await fx.EnqueueAsync(ProcessingJobs.LightAnalysis([a.Id, b.Id, c.Id]));
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
Assert.True(failed.Error!.StartsWith(Loc.L("Advisor.Log.Failed", b.DisplayTitle, string.Empty), StringComparison.Ordinal), failed.Error);
Assert.Equal("3;1", failed.Checkpoint);
Assert.SequenceEqual([true, false, true], await AnalysedAsync(fx, a, b, c));
await File.WriteAllBytesAsync(sidecar, saved, fx.Ct);
await fx.Engine.ResumeAsync(job.Id, fx.Ct);
var done = await fx.WaitForAsync(job.Id, JobState.Done);
Assert.SequenceEqual([true, true, true], await AnalysedAsync(fx, a, b, c));
Assert.Equal((3L, 3L), (done.ProgressDone, done.ProgressTotal));
// The retry analysed B alone.
var lightOfA = Loc.L("Advisor.Log.LightDone", a.DisplayTitle, 10, 0).Split(',')[0];
Assert.Equal(1, done.LogTail!.Split('\n').Count(line => line.Contains(lightOfA, StringComparison.Ordinal)));
}
[Test]
public void AnalysisCheckpointsKeepTheFailedTargets()
{
Assert.Equal("3", AnalyseJobHandler.Format(3, []));
Assert.Equal("4;0,2", AnalyseJobHandler.Format(4, [2, 0]));
var (next, retry) = AnalyseJobHandler.Parse("4;0,2", 5);
Assert.Equal(4, next);
Assert.SequenceEqual([0, 2], retry);
Assert.Equal(2, AnalyseJobHandler.Parse("2", 5).Next);
// Anything else starts over: no checkpoint, beyond the targets, a failed target not yet reached, garbage.
foreach (var text in new[] { null, "6", "2;3", "2;x", "a" }) Assert.Equal(0, AnalyseJobHandler.Parse(text, 5).Next);
}
private static async Task<List<bool>> AnalysedAsync(ProcessingFixture fx, params Sequence[] sequences)
{
var analysed = new List<bool>();
foreach (var s in sequences) analysed.Add((await fx.Db.Sequences.GetAsync(s.Id, fx.Ct))!.Status.HasFlag(SequenceStatus.AnalyzedLight));
return analysed;
}
[Test]
public async Task LightAnalysisAfterNewFramesDropsTheStaleDeepStatus()
{
@@ -0,0 +1,83 @@
using Titano.Core.Export;
using Titano.Core.Video;
using Titano.Core.Video.Managed;
using Titano.Data.Processing;
using Titano.Protocol.Client;
using Titano.Testing;
namespace Titano.Data.Tests.Processing;
/// <summary>Settings › Rendering "Software only" and "Hardware for previews only" keep renders off the GPU encoders.</summary>
[Category("processing")]
public sealed class HardwarePolicyTests
{
/// <summary>A PC with GPU HEVC and H.264 encoders and the software H.264 encoder; records what it opens.</summary>
private sealed class GpuProvider : IVideoEncoderProvider
{
public List<EncodeSettings> Opened { get; } = [];
public string Name => "gpu";
public IReadOnlyList<EncoderCapability> Capabilities { get; } =
[
new(VideoCodec.Hevc, "GPU HEVC", true, 8192, 8192, true),
new(VideoCodec.H264, "GPU H.264", true, 4096, 4096, false),
new(VideoCodec.H264, "Software H.264", false, 4096, 2304, false),
];
public bool CanEncode(EncodeSettings settings) =>
Capabilities.Any(c => c.Codec == settings.Codec && (settings.EncoderName is null || settings.EncoderName == c.Name)
&& settings.Width <= c.MaxWidth && settings.Height <= c.MaxHeight);
public IVideoEncoderSession Open(EncodeSettings settings)
{
Opened.Add(settings);
throw new NotSupportedException("recorded");
}
}
private static EncodeSettings Hevc4k(string? encoder = null) => new()
{
OutputPath = "out.mp4",
Codec = VideoCodec.Hevc,
Width = 3840,
Height = 2160,
FrameRate = new Rational(30, 1),
BitRate = 40_000_000,
EncoderName = encoder,
};
[Test]
public void SoftwareOnlyFallsBackToTheSoftwareEncoder()
{
var gpu = new GpuProvider();
var options = new ProcessingOptions { Encoders = [gpu, new ManagedEncoderProvider()], AllowsHardware = _ => false };
var selection = EncoderSelector.Select(Hevc4k(), options.SoftwareEncoders, EncoderHost.Client);
Assert.True(selection.IsReady, "software H.264 instead");
Assert.Equal((VideoCodec.H264, "Software H.264"), (selection.Settings.Codec, selection.Capability!.Name));
Assert.Contains(selection.Notices, n => n.Key == EncoderNotices.FallbackToH264);
Assert.Throws<NotSupportedException>(() => selection.Open());
Assert.Equal(("Software H.264", false), (gpu.Opened.Single().EncoderName, gpu.Opened.Single().PreferHardware));
// A GPU encoder named in the export is not used either.
var named = EncoderSelector.Select(Hevc4k("GPU H.264") with { Codec = VideoCodec.H264, Width = 1920, Height = 1080 }, options.SoftwareEncoders, EncoderHost.Client);
Assert.Equal("Software H.264", named.Capability?.Name);
Assert.True(options.SoftwareEncoders[1] is ManagedEncoderProvider, "managed encoders are untouched");
}
[Test]
public void ARenderNodeOffersGpuEncodersOnlyWhenRendersMayUseThem()
{
using var client = new TitanoClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "studio-pc");
var nodeOptions = new RenderNodeOptions { ClientName = "studio-pc", CacheDirectory = Path.GetTempPath() };
string[] Offered(Func<string, bool> allows) =>
[
.. new RenderNodeClient(client, new ProcessingOptions { Encoders = [new GpuProvider()], AllowsHardware = allows }, nodeOptions).Encoders
.Select(e => e.Name),
];
Assert.SequenceEqual(["GPU HEVC", "GPU H.264", "Software H.264"], Offered(_ => true));
Assert.SequenceEqual(["Software H.264"], Offered(id => id == "720p-preview"));
}
}
@@ -23,16 +23,17 @@ internal sealed class ProcessingFixture : IAsyncDisposable
private JobEngine? _engine;
private ProcessingFixture(ArchiveFixture archive, GateDecoder decoder)
private ProcessingFixture(ArchiveFixture archive, GateDecoder decoder, Func<ProcessingOptions, ProcessingOptions>? configure)
{
Archive = archive;
Decoder = decoder;
Processing = new ProcessingService(archive.Db, new ProcessingOptions
var options = new ProcessingOptions
{
Archive = new ArchiveServiceOptions { Decoder = new ImageDecoder([decoder]), Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) },
DeepAnalysis = DeepOptions,
ProducedBy = "test-pc",
});
};
Processing = new ProcessingService(archive.Db, configure?.Invoke(options) ?? options);
}
public ArchiveFixture Archive { get; }
@@ -43,13 +44,15 @@ internal sealed class ProcessingFixture : IAsyncDisposable
public JobEngine Engine => _engine ?? throw new InvalidOperationException("Start the engine first.");
public static async Task<ProcessingFixture> CreateAsync(TestContext context) => new(await ArchiveFixture.CreateAsync(context), new GateDecoder());
/// <param name="configure">Changes to the processing options (a server's host and render-node check).</param>
public static async Task<ProcessingFixture> CreateAsync(TestContext context, Func<ProcessingOptions, ProcessingOptions>? configure = null) =>
new(await ArchiveFixture.CreateAsync(context), new GateDecoder(), configure);
/// <summary>A started engine with the processing handlers (one worker, fast checkpoints).</summary>
public async Task<JobEngine> StartEngineAsync()
/// <summary>A started engine with the processing handlers, and the archive's when asked (one worker unless asked, fast checkpoints).</summary>
public async Task<JobEngine> StartEngineAsync(bool withArchive = false, int workers = 1)
{
_engine = new JobEngine(Db, Processing.CreateJobHandlers(),
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
_engine = new JobEngine(Db, [.. withArchive ? Archive.Service.CreateJobHandlers() : [], .. Processing.CreateJobHandlers()],
new JobEngineOptions { Workers = workers, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
await _engine.StartAsync(Ct);
return _engine;
}
@@ -61,6 +64,15 @@ internal sealed class ProcessingFixture : IAsyncDisposable
/// <summary>Writes frames <paramref name="first"/>… of <paramref name="sequence"/> as JPEGs with their Exif into
/// <paramref name="folder"/> (adopted in place) and indexes the archive.</summary>
public async Task<Sequence> AddAsync(SyntheticSequence sequence, string folder = "Synthetic", int first = 0)
{
Write(sequence, folder, first);
await Archive.ScanAsync(ScanMode.Full);
var location = (await Db.Sequences.ListLocationsAsync(Archive.Archive.Id, Ct)).Single(l => l.Folder == folder);
return (await Db.Sequences.GetAsync(location.Id, Ct))!;
}
/// <summary>Writes frames <paramref name="first"/>… of <paramref name="sequence"/> as JPEGs with their Exif into <paramref name="folder"/>.</summary>
public void Write(SyntheticSequence sequence, string folder = "Synthetic", int first = 0)
{
var directory = Path.Combine(Archive.Paths.Root, folder);
Directory.CreateDirectory(directory);
@@ -70,9 +82,6 @@ internal sealed class ProcessingFixture : IAsyncDisposable
var exif = ExifWriter.BuildJpegApp1(sequence.Metadata[i]);
File.WriteAllBytes(Path.Combine(directory, FileName(i)), JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 95, App1Segments = [exif[4..]] }));
}
await Archive.ScanAsync(ScanMode.Full);
var location = (await Db.Sequences.ListLocationsAsync(Archive.Archive.Id, Ct)).Single(l => l.Folder == folder);
return (await Db.Sequences.GetAsync(location.Id, Ct))!;
}
public static string FileName(int index) => $"IMG_{index + 1:0000}.JPG";
@@ -6,6 +6,8 @@ using Titano.Core.Imaging.Decoders;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Core.Video;
using Titano.Data.Jobs;
using Titano.Data.Processing;
using Titano.Testing;
@@ -24,6 +26,9 @@ public sealed class RenderJobTests(TestContext context)
NameTemplate = "clip-{codec}",
};
/// <summary>HEVC (a render node's codec) at the size of <see cref="Mjpeg"/>.</summary>
private static readonly ExportSettings Hevc = Mjpeg with { Preset = new Auto<string>().WithManual("4k-hevc") };
private static SyntheticSequence Scene() => SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = Frames, StartEv = 0.5, EndEv = -0.5 });
[Test]
@@ -125,18 +130,13 @@ public sealed class RenderJobTests(TestContext context)
Directory.CreateDirectory(exports);
var recorded = Encoding.ASCII.GetBytes("RIFF recorded before the crash");
await File.WriteAllBytesAsync(output, recorded, fx.Ct);
await fx.Db.Renders.InsertAsync(new Render
{
Id = Guid.CreateVersion7(),
SequenceId = sequence.Id,
PresetName = "MJPEG",
OutputPath = "Synthetic/exports/clip-MJPEG.avi",
Created = DateTimeOffset.UtcNow,
}, fx.Ct);
// The crash came after the job recorded its first entry and before its checkpoint said so.
var jobId = Guid.CreateVersion7();
await fx.Db.Renders.InsertAsync(RecordedRender(sequence, Titano.Data.Processing.Jobs.RenderJobHandler.RenderId(jobId, 0)), fx.Ct);
await fx.StartEngineAsync();
var job = await fx.Archive.EnqueueWithCheckpointAsync(fx.Engine, ProcessingJobs.Render(sequence, Mjpeg with { Batch = ["gif-preview"] }, 96, 64),
new RenderCheckpoint([], 0, output).ToJson());
new RenderCheckpoint([], 0, output).ToJson(), jobId);
await fx.WaitForAsync(job.Id, JobState.Done);
var kept = await File.ReadAllBytesAsync(output, fx.Ct);
@@ -145,6 +145,164 @@ public sealed class RenderJobTests(TestContext context)
Assert.Count(2, await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct));
}
[Test]
public async Task ARenderResumedAfterAnotherRecordedItsNameKeepsThatOutput()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Scene());
var exports = fx.Folder(sequence).Exports;
var output = Path.Combine(exports, "clip-MJPEG.avi");
Directory.CreateDirectory(exports);
// While this job waited to resume, another render of the same preset finished under the name it had chosen.
var other = Encoding.ASCII.GetBytes("RIFF another render's output");
await File.WriteAllBytesAsync(output, other, fx.Ct);
await fx.Db.Renders.InsertAsync(RecordedRender(sequence, Guid.CreateVersion7()), fx.Ct);
await fx.StartEngineAsync();
var job = await fx.Archive.EnqueueWithCheckpointAsync(fx.Engine, ProcessingJobs.Render(sequence, Mjpeg, 96, 64), new RenderCheckpoint([], 0, output).ToJson());
await fx.WaitForAsync(job.Id, JobState.Done);
var kept = await File.ReadAllBytesAsync(output, fx.Ct);
Assert.BytesEqual(other, kept);
Assert.SequenceEqual(["clip-MJPEG (2).avi", "clip-MJPEG.avi"], Entries(exports));
Assert.Count(2, await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct));
}
[Test]
public async Task ConcurrentRendersOfOnePresetKeepBothOutputs()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Scene());
await fx.StartEngineAsync(workers: 2);
var first = await fx.EnqueueAsync(ProcessingJobs.Render(sequence, Mjpeg, 96, 64));
var second = await fx.EnqueueAsync(ProcessingJobs.Render(sequence, Mjpeg, 96, 64));
await fx.WaitForAsync(first.Id, JobState.Done);
await fx.WaitForAsync(second.Id, JobState.Done);
Assert.SequenceEqual(["clip-MJPEG (2).avi", "clip-MJPEG.avi"], Entries(fx.Folder(sequence).Exports));
var renders = await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct);
Assert.Equal(2, renders.Select(r => r.OutputPath).Distinct().Count());
}
[Test]
public void ANameBeingWrittenIsNotPickedAgain()
{
var folder = context.CreateTempDirectory("exports");
var name = new ExportNameContext { Date = new DateTime(2026, 6, 1), Title = "Roof", PresetName = "MJPEG", Codec = VideoCodec.Mjpeg };
using var a = new OutputNames();
using var b = new OutputNames();
var first = a.Reserve(taken => ExportNaming.OutputPath(folder, "{title}", name, taken));
var second = b.Reserve(taken => ExportNaming.OutputPath(folder, "{title}", name, taken));
Assert.Equal((Path.Combine(folder, "Roof.avi"), Path.Combine(folder, "Roof (2).avi")), (first, second));
Assert.False(b.TryReserve(first), "held by the first render");
a.Dispose();
using var c = new OutputNames();
Assert.Equal(first, c.Reserve(taken => ExportNaming.OutputPath(folder, "{title}", name, taken)));
}
[Test]
public void RenderRowIdsAreStablePerJobAndEntry()
{
var job = Guid.CreateVersion7();
var id = Titano.Data.Processing.Jobs.RenderJobHandler.RenderId(job, 0);
Assert.Equal(id, Titano.Data.Processing.Jobs.RenderJobHandler.RenderId(job, 0));
Assert.NotEqual(id, Titano.Data.Processing.Jobs.RenderJobHandler.RenderId(job, 1));
Assert.NotEqual(id, Titano.Data.Processing.Jobs.RenderJobHandler.RenderId(Guid.CreateVersion7(), 0));
Assert.Equal(8, id.Version);
}
[Test]
public async Task AServerTakesOnlyTheRendersItsManagedEncodersProduce()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var server = new ProcessingService(fx.Db, new ProcessingOptions { Host = EncoderHost.Server, AwaitsRenderNode = (_, _, _) => Task.FromResult(true) });
var handler = Assert.NotNull(server.CreateJobHandlers().Single(h => h.Kind == JobKind.Render) as ISelectiveJobHandler);
var sequence = new Sequence { Id = Guid.CreateVersion7(), ArchiveId = Guid.CreateVersion7(), Folder = "Synthetic" };
Job Job(ExportSettings export) => new() { Id = Guid.CreateVersion7(), Kind = JobKind.Render, ParametersJson = ProcessingJobs.Render(sequence, export, 96, 64).ParametersJson };
async Task<bool> AcceptsAsync(string? parametersJson) =>
await handler.AcceptsAsync(new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Render, ParametersJson = parametersJson }, fx.Ct);
Assert.True(await handler.AcceptsAsync(Job(Mjpeg with { Batch = ["png-sequence", "gif-preview"] }), fx.Ct), "managed outputs only");
Assert.False(await handler.AcceptsAsync(Job(Hevc), fx.Ct), "HEVC waits for a render node");
Assert.False(await handler.AcceptsAsync(Job(Mjpeg with { Batch = ["1080p-h264"] }), fx.Ct), "one MP4 in the batch");
Assert.True(await handler.AcceptsAsync(Job(Hevc) with { Checkpoint = """{"done":[],"pending":0}""" }, fx.Ct), "started here: resumes here");
Assert.True(await AcceptsAsync("{}"), "unreadable: fails with its reason");
Assert.True(await AcceptsAsync(WithPreset("""{"preset":{},"Preset":{}}""")), "a member given twice: fails with its reason");
Assert.True(await AcceptsAsync(WithPreset("""{"preset":{"isAuto":false,"manual":"mjpeg-avi"},"batch":null}""")), "a null batch is no batch");
var client = new ProcessingService(fx.Db).CreateJobHandlers().Single(h => h.Kind == JobKind.Render);
Assert.False(client is ISelectiveJobHandler, "a client renders whatever it is given");
}
[Test]
public async Task AServerTakesMp4JobsOnceNoRenderNodeCanAndOnlyThen()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = new Sequence { Id = Guid.CreateVersion7(), ArchiveId = Guid.CreateVersion7(), Folder = "Synthetic" };
var job = new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Render, ParametersJson = ProcessingJobs.Render(sequence, Hevc, 96, 64).ParametersJson };
async Task<bool> AcceptsAsync(Func<Job, Titano.Protocol.RenderJobParameters, CancellationToken, Task<bool>>? awaits)
{
var server = new ProcessingService(fx.Db, new ProcessingOptions { Host = EncoderHost.Server, AwaitsRenderNode = awaits });
return await ((ISelectiveJobHandler)server.CreateJobHandlers().Single(h => h.Kind == JobKind.Render)).AcceptsAsync(job, fx.Ct);
}
Titano.Protocol.RenderJobParameters? asked = null;
Assert.True(await AcceptsAsync((_, p, _) => { asked = p; return Task.FromResult(false); }), "no node can take it");
Assert.Equal(("hevc", 96, 64), (asked!.Codec, asked.Width, asked.Height));
Assert.False(await AcceptsAsync(null), "without a node check, MP4 jobs always wait");
Assert.False(await AcceptsAsync((_, _, _) => throw new InvalidOperationException("database unreachable")), "unknown: keeps waiting");
}
[Test]
public async Task AServerRendersAsMjpegWhatNoRenderNodeTookAndSaysSo()
{
await using var fx = await ProcessingFixture.CreateAsync(context, o => o with { Host = EncoderHost.Server, AwaitsRenderNode = (_, _, _) => Task.FromResult(false) });
var sequence = await fx.AddAsync(Scene());
await fx.StartEngineAsync();
var request = ProcessingJobs.Render(sequence, Hevc, 96, 64);
var job = await fx.WaitForAsync((await fx.EnqueueAsync(request)).Id, JobState.Done);
var avi = await File.ReadAllBytesAsync(Path.Combine(fx.Folder(sequence).Exports, "clip-MJPEG.avi"), fx.Ct);
Assert.Equal(("RIFF", "AVI "), (Encoding.ASCII.GetString(avi, 0, 4), Encoding.ASCII.GetString(avi, 8, 4)));
var render = (await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct)).Single();
var preset = Loc.L("Export.Preset.Custom");
Assert.Equal((preset, "Mjpeg", 96, 64), (render.PresetName, render.Codec, render.Width, render.Height));
Assert.Contains(Loc.L("Export.Log.NoRenderNode", preset, "HEVC", "MJPEG"), job.LogTail);
}
[Test]
public void ABatchForAServerBecomesOneJobPerPreset()
{
var sequence = new Sequence { Id = Guid.CreateVersion7(), ArchiveId = Guid.CreateVersion7(), Folder = "Synthetic", Title = "Roof" };
var jobs = ProcessingJobs.RenderEach(sequence, Mjpeg with { Batch = ["mjpeg-avi", "gif-preview", "GIF-preview", "4k-hevc"] }, 96, 64);
var parameters = jobs.Select(j => System.Text.Json.JsonSerializer.Deserialize(j.ParametersJson!, Titano.Protocol.ProtocolJson.Default.RenderJobParameters)!).ToList();
Assert.SequenceEqual(["mjpeg", "gif", "hevc"], parameters.Select(p => p.Codec));
Assert.True(jobs.All(j => j.Kind == JobKind.Render && j.Targets.SequenceEqual([sequence.Id])), "render jobs of the sequence");
Assert.True(parameters.All(p => ProcessingJobs.ReadExport(p.PresetJson).Batch.Count == 0), "no job carries a batch");
Assert.Equal((3840, 2160), (parameters[2].Width, parameters[2].Height));
// A posted batch written by hand may hold blank entries: they name no preset.
var posted = System.Text.Json.JsonSerializer.Deserialize(WithPreset("""{"preset":{"isAuto":false,"manual":"mjpeg-avi"},"batch":[null," ","gif-preview"]}"""),
Titano.Protocol.ProtocolJson.Default.RenderJobParameters)!;
Assert.SequenceEqual(["mjpeg", "gif"], ProcessingJobs.Split(posted, 96, 64).Select(p => p.Codec));
}
/// <summary>MJPEG job parameters whose preset JSON is <paramref name="presetJson"/>.</summary>
private static string WithPreset(string presetJson) => System.Text.Json.JsonSerializer.Serialize(
new Titano.Protocol.RenderJobParameters("MJPEG", presetJson, "mjpeg", 96, 64, false, null), Titano.Protocol.ProtocolJson.Default.RenderJobParameters);
private static Render RecordedRender(Sequence sequence, Guid id) => new()
{
Id = id,
SequenceId = sequence.Id,
PresetName = "MJPEG",
OutputPath = "Synthetic/exports/clip-MJPEG.avi",
Created = DateTimeOffset.UtcNow,
};
private static List<string> Entries(string folder) =>
Directory.Exists(folder) ? [.. Directory.EnumerateFileSystemEntries(folder).Select(e => Path.GetFileName(e)).Order(StringComparer.Ordinal)] : [];
@@ -59,6 +59,28 @@ public abstract class JobRepositoryTests(TestContext context) : RepositoryTest(c
Assert.SequenceEqual([oldUser.Id, normal.Id, oldBackground.Id], order);
}
[Test]
public async Task SelectiveClaimersListQueuedKindsInClaimOrderAndClaimById()
{
var db = await OpenTitanoAsync(multiConnection: true);
var oldBackground = TestData.Job(JobKind.Render, JobPriority.Background, TestData.Now.AddMinutes(-10));
var newUser = TestData.Job(JobKind.Thumbs, JobPriority.User, TestData.Now);
var oldUser = TestData.Job(JobKind.Render, JobPriority.User, TestData.Now.AddMinutes(-1));
var otherKind = TestData.Job(JobKind.Scan, JobPriority.User, TestData.Now.AddMinutes(-20));
foreach (var job in new[] { oldBackground, newUser, oldUser, otherKind }) await db.Jobs.EnqueueAsync(job, Ct);
var queued = await db.Jobs.ListQueuedAsync([JobKind.Render, JobKind.Thumbs], 10, Ct);
Assert.SequenceEqual([oldUser.Id, newUser.Id, oldBackground.Id], queued.Select(j => j.Id));
Assert.Count(1, await db.Jobs.ListQueuedAsync([JobKind.Render, JobKind.Thumbs], 1, Ct));
Assert.Empty(await db.Jobs.ListQueuedAsync([], 10, Ct));
// Workers racing for the same listed job: exactly one gets it, and it leaves the listing.
var claims = await Task.WhenAll(Enumerable.Range(0, 6).Select(w => Task.Run(() => db.Jobs.TryClaimAsync(oldUser.Id, "worker-" + w, Ct))));
var claimed = Assert.NotNull(claims.SingleOrDefault(c => c is not null));
Assert.Equal((JobState.Running, 1), (claimed.State, claimed.Attempts));
Assert.SequenceEqual([newUser.Id, oldBackground.Id], (await db.Jobs.ListQueuedAsync([JobKind.Render, JobKind.Thumbs], 10, Ct)).Select(j => j.Id));
}
[Test]
public async Task ConcurrentClaimersNeverShareAJob()
{
@@ -1,14 +1,17 @@
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Diagnostics.Synthetic;
using Titano.Core.Export;
using Titano.Core.Imaging.Decoders;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Data.Archiving;
using Titano.Data.Processing;
using Titano.Protocol;
using Titano.Protocol.Client;
using Titano.Server.Jobs;
using Titano.Testing;
namespace Titano.Server.Tests.Jobs;
@@ -84,16 +87,248 @@ public sealed class RenderNodeClientTests(TestContext context)
var id = await node.RegisterAsync(context.Cancellation);
var registered = (await client.ListNodesAsync(context.Cancellation)).Single(n => n.Id == id);
Assert.SequenceEqual(["apng", "gif", "mjpeg"], registered.Encoders.Select(e => e.Codec).Order(StringComparer.Ordinal));
// Each encoder announces its own largest output, so the server matches job sizes per codec.
Assert.True(registered.Encoders.All(e => (e.MaxWidth, e.MaxHeight) == (65535, 65535)), "per-encoder limits");
}
private static RenderNodeClient Node(TitanoClient client, string cache) =>
new(client, new ProcessingOptions { Archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer() } },
new RenderNodeOptions { ClientName = "studio-pc", CacheDirectory = cache, ProgressInterval = TimeSpan.Zero });
[Test]
public async Task AStartedNodeRegistersBeatsClaimsAndStopsCleanly()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
var sequenceId = await UploadSequenceAsync(editor, Photos());
// A posted batch becomes one job per preset, so each output travels back on its own.
var job = await CreateRenderAsync(server, editor, sequenceId, Mjpeg with { Batch = ["gif-preview"] });
var gif = (await server.Database.Jobs.ListAsync(JobState.Queued, JobKind.Render)).Items.Single(j => j.Id != job.Id);
private static async Task<JobDto> CreateRenderAsync(TestServer server, HttpClient editor, Guid sequenceId)
using var client = new TitanoClient(server.HttpBase, new CertificatePinning([]), "studio-pc") { Token = token };
var cache = context.CreateTempDirectory("node");
// Claims only when started and after each job: between them only heartbeats reach the server.
var node = Node(client, cache, poll: TimeSpan.FromMinutes(5), heartbeat: TimeSpan.FromMilliseconds(100));
node.Start();
await JobApiTests.WaitForAsync(editor, job.Id, "done");
await JobApiTests.WaitForAsync(editor, gif.Id, "done");
// Past the claim that found the queue empty, only heartbeats move the node's last sign of life.
await Task.Delay(300);
var beat = (await server.Database.RenderNodes.ListAsync()).Single().LastHeartbeat;
await Task.Delay(400);
Assert.Greater((await server.Database.RenderNodes.ListAsync()).Single().LastHeartbeat.Ticks, beat.Ticks);
await node.DisposeAsync();
Assert.True(node.Completion.IsCompleted, "stopped");
Assert.SequenceEqual(["gif", "mjpeg"], (await server.Database.Renders.ListBySequenceAsync(sequenceId)).Select(r => r.Codec!).Order(StringComparer.Ordinal));
Assert.False(Directory.EnumerateFileSystemEntries(Path.Combine(cache, "jobs")).Any(), "job folder removed");
}
[Test]
public async Task ANodeRestartedDuringAJobDoesNotLeaveItRunning()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
var sequenceId = await UploadSequenceAsync(editor, Photos());
var job = await CreateRenderAsync(server, editor, sequenceId);
var cache = context.CreateTempDirectory("node");
// The first run stops while downloading (sign-out, exit): the job is still running on the server.
var held = new HoldDownloads(new SocketsHttpHandler());
using (var slow = new TitanoClient(server.HttpBase, new CertificatePinning([]), "studio-pc", held) { Token = token })
{
await using var first = Node(slow, cache);
using var stopping = new CancellationTokenSource();
var run = first.RunOnceAsync(stopping.Token);
await held.Holding.Task.WaitAsync(TimeSpan.FromSeconds(30));
Assert.Equal("running", (await JobApiTests.GetAsync(editor, job.Id)).State);
await stopping.CancelAsync();
Assert.True(await run, "the job was claimed");
}
Assert.Equal("running", (await JobApiTests.GetAsync(editor, job.Id)).State);
// Started again within the heartbeat timeout under the same name: registering gives the job back to the queue.
using var client = new TitanoClient(server.HttpBase, new CertificatePinning([]), "studio-pc") { Token = token };
await using var second = Node(client, cache);
Assert.True(await second.RunOnceAsync(context.Cancellation), "the abandoned job was claimed again");
var done = await JobApiTests.GetAsync(editor, job.Id);
Assert.Equal("done", done.State);
Assert.Contains("Render node studio-pc restarted.", done.LogTail);
Assert.Count(1, await server.Database.Renders.ListBySequenceAsync(sequenceId));
}
[Test]
public async Task ADroppedDownloadIsResumedNotFailed()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
var sequenceId = await UploadSequenceAsync(editor, Photos());
var job = await CreateRenderAsync(server, editor, sequenceId);
var cut = new CutFirst("original", new SocketsHttpHandler());
using var client = new TitanoClient(server.HttpBase, new CertificatePinning([]), "studio-pc", cut) { Token = token };
await using var node = Node(client, context.CreateTempDirectory("node"));
Assert.True(await node.RunOnceAsync(context.Cancellation), "a job was claimed");
Assert.Equal("done", (await JobApiTests.GetAsync(editor, job.Id)).State);
Assert.Equal(1, cut.Cuts);
Assert.Equal(1, cut.Resumed);
}
[Test]
public async Task ADroppedProxyIsFetchedWholeAgain()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
var photos = Photos();
var sequence = (await server.Database.Sequences.GetAsync(await UploadSequenceAsync(editor, photos)))!;
// The archive has proxies of every frame (the test locator serves <folder>/proxies/NNNN.jpg).
var proxies = Path.Combine(server.Options.ArchivePath, sequence.Folder, "proxies");
Directory.CreateDirectory(proxies);
foreach (var frame in await server.Database.Frames.ListBySequenceAsync(sequence.Id))
await File.WriteAllBytesAsync(Path.Combine(proxies, $"{frame.Index:D4}.jpg"), photos[frame.Index]);
await server.Database.Sequences.UpsertAsync(sequence with { Status = sequence.Status | SequenceStatus.ProxiesBuilt });
var job = await JobApiTests.CreateAsync(editor, "render", sequence.Id, ProcessingJobs.Render(sequence, Mjpeg, 96, 64, useProxies: true).ParametersJson);
var cut = new CutFirst("proxy", new SocketsHttpHandler());
using var client = new TitanoClient(server.HttpBase, new CertificatePinning([]), "studio-pc", cut) { Token = token };
var cache = context.CreateTempDirectory("node");
await using var node = Node(client, cache);
Assert.True(await node.RunOnceAsync(context.Cancellation), "a job was claimed");
Assert.Equal("done", (await JobApiTests.GetAsync(editor, job.Id)).State);
// Nothing verifies a proxy against a hash, so a retry never appends to what the dropped attempt left.
Assert.Equal((1, 0), (cut.Cuts, cut.Resumed));
Assert.False(Directory.Exists(Path.Combine(cache, "originals")), "no original needed");
}
[Test]
public async Task ANodeLeavesARenderTheServerStartedToTheServer()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
var sequenceId = await UploadSequenceAsync(editor, Photos());
var job = await CreateRenderAsync(server, editor, sequenceId);
// The server's own engine was rendering it when it crashed: its checkpoint names its leftovers.
Assert.NotNull(await server.Database.Jobs.TryClaimAsync(job.Id, "server:test#0"));
Assert.True(await server.Database.Jobs.UpdateProgressAsync(job.Id, 3, 12, null, null, """{"done":[],"pending":0}""", null));
await server.Database.Jobs.RequeueRunningAsync("server:test");
using var client = new TitanoClient(server.HttpBase, new CertificatePinning([]), "studio-pc") { Token = token };
await using var node = Node(client, context.CreateTempDirectory("node"));
Assert.False(await node.RunOnceAsync(context.Cancellation), "nothing for the node");
Assert.Equal("queued", (await JobApiTests.GetAsync(editor, job.Id)).State);
}
[Test]
public async Task ANodeRefusesABatchItCannotSendBack()
{
await using var server = await TestServer.StartAsync(context);
var (editor, user, token) = await server.UserAsync("alberto", "editor", renderNode: true);
var sequence = (await server.Database.Sequences.GetAsync(await UploadSequenceAsync(editor, Photos())))!;
// Queued as one job (an older server did not split batches).
var request = ProcessingJobs.Render(sequence, Mjpeg with { Batch = ["gif-preview"] }, 96, 64);
var job = await server.Services.GetRequiredService<JobEngineHost>().Engine
.EnqueueAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority, user.Id);
using var client = new TitanoClient(server.HttpBase, new CertificatePinning([]), "studio-pc") { Token = token };
await using var node = Node(client, context.CreateTempDirectory("node"));
Assert.True(await node.RunOnceAsync(context.Cancellation), "a job was claimed");
var failed = await JobApiTests.GetAsync(editor, job.Id);
Assert.Equal(("failed", Loc.L("Errors.Render.NodeBatch")), (failed.State, failed.Error));
Assert.Empty(await server.Database.Renders.ListBySequenceAsync(sequence.Id));
}
[Test]
public async Task ADownloadThatEndedBeforeItsCheckIsVerifiedNotFetchedAgain()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, token) = await server.UserAsync("alberto", "editor", renderNode: true);
var photos = Photos();
var sequenceId = await UploadSequenceAsync(editor, photos);
await CreateRenderAsync(server, editor, sequenceId, Mjpeg);
// A crash after the last byte arrived but before the hash check left a complete part file.
var cache = context.CreateTempDirectory("node");
var sha = Uploads.Sha(photos[0]);
var part = Path.Combine(cache, "originals", sha[..2], sha + ".jpg.part");
Directory.CreateDirectory(Path.GetDirectoryName(part)!);
await File.WriteAllBytesAsync(part, photos[0]);
using var client = new TitanoClient(server.HttpBase, new CertificatePinning([]), "studio-pc") { Token = token };
await using var node = Node(client, cache);
Assert.True(await node.RunOnceAsync(context.Cancellation), "a job was claimed");
Assert.Count(1, await server.Database.Renders.ListBySequenceAsync(sequenceId));
Assert.FileMissing(part);
Assert.FileExists(part[..^".part".Length]);
}
private static RenderNodeClient Node(TitanoClient client, string cache, TimeSpan? poll = null, TimeSpan? heartbeat = null) =>
new(client, new ProcessingOptions { Archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer() } },
new RenderNodeOptions
{
ClientName = "studio-pc",
CacheDirectory = cache,
ProgressInterval = TimeSpan.Zero,
PollInterval = poll ?? TimeSpan.FromSeconds(10),
HeartbeatInterval = heartbeat ?? TimeSpan.FromSeconds(30),
RetryDelay = TimeSpan.FromMilliseconds(10),
});
/// <summary>Holds every frame download until the request is cancelled.</summary>
private sealed class HoldDownloads(HttpMessageHandler inner) : DelegatingHandler(inner)
{
public TaskCompletionSource Holding { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.RequestUri!.AbsolutePath.StartsWith("/api/v1/frames/", StringComparison.Ordinal))
{
Holding.TrySetResult();
await Task.Delay(Timeout.Infinite, cancellationToken);
}
return await base.SendAsync(request, cancellationToken);
}
}
/// <summary>Drops the connection halfway through the first resource of <paramref name="kind"/> it serves; counts the downloads resumed with a range.</summary>
private sealed class CutFirst(string kind, HttpMessageHandler inner) : DelegatingHandler(inner)
{
private int _cuts;
private int _resumed;
public int Cuts => _cuts;
public int Resumed => _resumed;
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Headers.Range is not null) Interlocked.Increment(ref _resumed);
var response = await base.SendAsync(request, cancellationToken);
if (!request.RequestUri!.AbsolutePath.EndsWith("/" + kind, StringComparison.Ordinal) || Interlocked.CompareExchange(ref _cuts, 1, 0) != 0)
return response;
var body = await response.Content.ReadAsByteArrayAsync(cancellationToken);
var content = new StreamContent(new CutStream(body, body.Length / 2));
foreach (var header in response.Content.Headers) content.Headers.TryAddWithoutValidation(header.Key, header.Value);
response.Content = content;
return response;
}
}
/// <summary>The first <c>cut</c> bytes, then a reset connection.</summary>
private sealed class CutStream(byte[] data, int cut) : MemoryStream(data, 0, cut)
{
public override int Read(byte[] buffer, int offset, int count) => Check(base.Read(buffer, offset, count));
public override int Read(Span<byte> buffer) => Check(base.Read(buffer));
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) =>
Check(await base.ReadAsync(buffer, cancellationToken));
private static int Check(int read) => read > 0 ? read : throw new IOException("Connection reset by peer");
}
private static async Task<JobDto> CreateRenderAsync(TestServer server, HttpClient editor, Guid sequenceId, ExportSettings? export = null)
{
var sequence = (await server.Database.Sequences.GetAsync(sequenceId))!;
var request = ProcessingJobs.Render(sequence, Mjpeg, 96, 64);
var request = ProcessingJobs.Render(sequence, export ?? Mjpeg, 96, 64);
return await JobApiTests.CreateAsync(editor, "render", sequenceId, request.ParametersJson);
}
@@ -70,6 +70,26 @@ public sealed class RenderNodeTests(TestContext context)
}
}
[Test]
public async Task EachEncoderTakesOnlyJobsWithinItsOwnSizeLimit()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, _) = await server.UserAsync("alberto", "editor", renderNode: true);
var sequence = await JobApiTests.CreateSequenceAsync(editor);
// The software H.264 encoder stops at 4096 px although the node's MJPEG encoder writes far larger frames.
using var registered = await editor.PostAsJsonAsync("/api/v1/nodes/register", new RegisterNodeRequest("studio-pc",
[new NodeEncoder("h264", "H.264 Encoder MFT", false, false, 4096, 2304), new NodeEncoder("mjpeg", "Managed MJPEG", false, false, 65535, 65535)],
65535, 65535), ProtocolJson.Default.RegisterNodeRequest);
var node = await registered.ReadAsync(ProtocolJson.Default.RenderNodeDto);
Assert.Equal((4096, 2304), (node.Encoders[0].MaxWidth, node.Encoders[0].MaxHeight));
await JobApiTests.CreateAsync(editor, "render", sequence, H264Job(6144, 3456));
using (var none = await editor.PostAsync($"/api/v1/nodes/{node.Id}/claim", null)) await none.ExpectAsync(HttpStatusCode.NoContent);
var uhd = await JobApiTests.CreateAsync(editor, "render", sequence, H264Job(3840, 2160));
using var claim = await editor.PostAsync($"/api/v1/nodes/{node.Id}/claim", null);
Assert.Equal(uhd.Id, (await claim.ReadAsync(ProtocolJson.Default.ClaimedJob)).Job.Id);
}
[Test]
public async Task TheOutputUploadBecomesARenderAndFinishesTheJob()
{
@@ -123,6 +143,10 @@ public sealed class RenderNodeTests(TestContext context)
await foreign.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
}
private static string H264Job(int width, int height) => JsonSerializer.Serialize(
new RenderJobParameters("H.264", """{"preset":{"isAuto":false,"manual":"4k-h264"}}""", "h264", width, height, UseProxies: false, null),
ProtocolJson.Default.RenderJobParameters);
private static async Task<RenderNodeDto> RegisterAsync(HttpClient client, string name, string codec, int maxWidth)
{
using var response = await client.PostAsJsonAsync("/api/v1/nodes/register",
@@ -1,32 +1,47 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using Titano.Core.Archiving;
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Diagnostics.Synthetic;
using Titano.Core.Metadata;
using Titano.Core.Model;
using Titano.Core.Localization;
using Titano.Core.Project;
using Titano.Data.Processing;
using Titano.Protocol;
using Titano.Server.Events;
using Titano.Server.Jobs;
using Titano.Server.Storage;
using Titano.Server.Tests.Jobs;
using Titano.Testing;
namespace Titano.Server.Tests.Storage;
/// <summary>The production composition: frames committed by the archive engine are light-analysed by the processing handlers.</summary>
/// <summary>
/// The production composition: frames committed by the archive engine are light-analysed by the processing handlers,
/// and the server renders the managed formats itself.
/// </summary>
[Category("processing")]
public sealed class ProcessingModuleTests(TestContext context)
{
private const int Frames = 10;
/// <summary>The registrations of Program.cs.</summary>
private static void Production(IServiceCollection services)
{
ArchiveModule.Register(services);
ProcessingModule.Register(services);
}
[Test]
public async Task UploadedFramesAreLightAnalysedAndAdvised()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
await using var server = await TestServer.StartAsync(context, services: Production);
using var events = server.Services.GetRequiredService<EventHub>().Subscribe();
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var scene = SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 10, StartEv = 0.5, EndEv = -0.5 });
Guid sequenceId = default;
for (var i = 0; i < scene.Count; i++)
{
using var image = scene.Render(i);
var exif = ExifWriter.BuildJpegApp1(scene.Metadata[i]);
var photo = JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [exif[4..]] });
sequenceId = (await Uploads.UploadAsync(editor, photo, $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
}
var sequenceId = await UploadSceneAsync(editor);
// The commits queue a light analysis; its handler comes from the processing module.
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
@@ -34,7 +49,7 @@ public sealed class ProcessingModuleTests(TestContext context)
while (true)
{
sequence = (await server.Database.Sequences.GetAsync(sequenceId))!;
if (sequence.Status.HasFlag(SequenceStatus.AnalyzedLight) && sequence.FrameCount == scene.Count
if (sequence.Status.HasFlag(SequenceStatus.AnalyzedLight) && sequence.FrameCount == Frames
&& !await server.Database.Jobs.IsQueuedAsync(JobKind.LightAnalyse, sequenceId)) break;
Assert.True(DateTime.UtcNow < until, $"not analysed: {sequence.Status}, {sequence.FrameCount} frames");
await Task.Delay(100);
@@ -44,5 +59,155 @@ public sealed class ProcessingModuleTests(TestContext context)
var folder = new ArchivePaths(server.Options.ArchivePath).Sequence(sequence.Folder);
Assert.FileExists(folder.ProjectPath);
Assert.True(ManifestStore.ReadSequence(folder.ManifestPath).Status.HasFlag(SequenceStatus.AnalyzedLight), "sidecar status");
// Connected clients learn that the Auto values changed (BRIEF §14.3).
Assert.Contains(Drain(events), e => e is SequenceChangedEvent { Change: "settings" } changed && changed.SequenceId == sequenceId);
}
[Test]
public async Task TheServerRendersManagedFormatsAndLeavesMp4ToRenderNodes()
{
await using var server = await TestServer.StartAsync(context, services: Production);
using var events = server.Services.GetRequiredService<EventHub>().Subscribe();
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var sequence = (await server.Database.Sequences.GetAsync(await UploadSceneAsync(editor)))!;
// A client's export folder means nothing on the server: the output still goes to the sequence's exports.
var avi = new ExportSettings
{
Preset = new Auto<string>().WithManual("mjpeg-avi"),
Overrides = new ExportOverrides { Width = 96, Height = 64 },
NameTemplate = "clip",
Folder = context.CreateTempDirectory("elsewhere"),
};
var hevc = new ExportSettings { Preset = new Auto<string>().WithManual("4k-hevc") };
var mp4 = await JobApiTests.CreateAsync(editor, "render", sequence.Id, ProcessingJobs.Render(sequence, hevc, 96, 64).ParametersJson);
var managed = await JobApiTests.CreateAsync(editor, "render", sequence.Id, ProcessingJobs.Render(sequence, avi, 96, 64).ParametersJson);
var done = await JobApiTests.WaitForAsync(editor, managed.Id, "done");
Assert.Equal(JobEngineHost.WorkerId, done.NodeId?.Split('#')[0]);
var render = (await server.Database.Renders.ListBySequenceAsync(sequence.Id)).Single();
Assert.Equal(($"{sequence.Folder}/exports/clip.avi", server.Options.ServerName, "Mjpeg"), (render.OutputPath, render.ProducedBy, render.Codec));
Assert.FileExists(Path.Combine(server.Options.ArchivePath, render.OutputPath));
Assert.Empty(Directory.EnumerateFileSystemEntries(avi.Folder));
var waiting = await JobApiTests.GetAsync(editor, mp4.Id);
Assert.Equal(("queued", (string?)null), (waiting.State, waiting.NodeId));
Assert.Contains(Drain(events), e => e is SequenceChangedEvent { Change: "renders" } changed && changed.SequenceId == sequence.Id);
}
[Test]
public async Task Mp4JobsNoRenderNodeCanTakeAreRenderedAsMjpegAndTheLogSaysSo()
{
var clock = new ManualTimeProvider();
await using var server = await TestServer.StartAsync(context, o => o.NodeTimeoutSeconds = 60, s =>
{
Production(s);
s.AddSingleton<TimeProvider>(clock);
});
var engine = server.Services.GetRequiredService<JobEngineHost>().Engine;
var (editor, _, _) = await server.UserAsync("alberto", "editor", renderNode: true);
var sequence = (await server.Database.Sequences.GetAsync(await UploadSceneAsync(editor)))!;
var hevc = new ExportSettings
{
Preset = new Auto<string>().WithManual("4k-hevc"),
Overrides = new ExportOverrides { Width = 96, Height = 64 },
NameTemplate = "clip-{codec}",
};
var job = await JobApiTests.CreateAsync(editor, "render", sequence.Id, ProcessingJobs.Render(sequence, hevc, 96, 64).ParametersJson);
// A node that encodes HEVC is online: the job waits for it, however long it has been queued.
using (var registered = await editor.PostAsJsonAsync("/api/v1/nodes/register",
new RegisterNodeRequest("studio-pc", [new NodeEncoder("hevc", "NVENC HEVC", true, true, 8192, 8192)], 8192, 8192), ProtocolJson.Default.RegisterNodeRequest))
await registered.ExpectAsync(HttpStatusCode.OK);
clock.Advance(TimeSpan.FromSeconds(61));
var node = (await server.Database.RenderNodes.ListAsync()).Single();
Assert.True(await server.Database.RenderNodes.HeartbeatAsync(node.Id, "idle", clock.GetUtcNow()));
engine.Wake();
await Task.Delay(1500);
Assert.Equal("queued", (await JobApiTests.GetAsync(editor, job.Id)).State);
// The node goes silent: the server renders the job itself in a managed format.
clock.Advance(TimeSpan.FromSeconds(61));
engine.Wake();
var done = await JobApiTests.WaitForAsync(editor, job.Id, "done");
Assert.Equal(JobEngineHost.WorkerId, done.NodeId?.Split('#')[0]);
var render = (await server.Database.Renders.ListBySequenceAsync(sequence.Id)).Single();
Assert.Equal(($"{sequence.Folder}/exports/clip-MJPEG.avi", "Mjpeg", 96, 64), (render.OutputPath, render.Codec, render.Width, render.Height));
Assert.Contains(Loc.L("Export.Log.NoRenderNode", Loc.L("Export.Preset.Custom"), "HEVC", "MJPEG"), done.LogTail);
}
[Test]
public async Task APostedBatchBecomesOneJobPerPreset()
{
await using var server = await TestServer.StartAsync(context, services: Production);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var sequence = (await server.Database.Sequences.GetAsync(await UploadSceneAsync(editor)))!;
var batch = new ExportSettings
{
Preset = new Auto<string>().WithManual("mjpeg-avi"),
Overrides = new ExportOverrides { Width = 96, Height = 64 },
NameTemplate = "{title} - {codec}",
Batch = ["gif-preview", "1080p-h264"],
};
var main = await JobApiTests.CreateAsync(editor, "render", sequence.Id, ProcessingJobs.Render(sequence, batch, 96, 64).ParametersJson);
var jobs = (await server.Database.Jobs.ListAsync(null, JobKind.Render)).Items;
Assert.Count(3, jobs);
var mp4 = jobs.Single(j => j.TargetLabel!.EndsWith(Loc.L("Export.Preset.1080pShare"), StringComparison.Ordinal));
var gif = jobs.Single(j => j.TargetLabel!.EndsWith(Loc.L("Export.Preset.Gif"), StringComparison.Ordinal));
await JobApiTests.WaitForAsync(editor, main.Id, "done");
await JobApiTests.WaitForAsync(editor, gif.Id, "done");
// The server renders the managed presets; the MP4 one waits for a render node, at the preset's size.
Assert.SequenceEqual(["Gif", "Mjpeg"], (await server.Database.Renders.ListBySequenceAsync(sequence.Id)).Select(r => r.Codec!).Order(StringComparer.Ordinal));
Assert.Equal("queued", (await JobApiTests.GetAsync(editor, mp4.Id)).State);
var parameters = JsonSerializer.Deserialize(mp4.ParametersJson!, ProtocolJson.Default.RenderJobParameters)!;
Assert.Equal(("h264", 1920, 1080), (parameters.Codec, parameters.Width, parameters.Height));
}
[Test]
public async Task RenderJobsThatCannotBeReadNeverStopTheEngine()
{
await using var server = await TestServer.StartAsync(context, services: Production);
var (editor, user, _) = await server.UserAsync("alberto", "editor");
var sequence = (await server.Database.Sequences.GetAsync(await UploadSceneAsync(editor)))!;
const string mjpeg = """{"preset":{"isAuto":false,"manual":"mjpeg-avi"},"overrides":{"width":96,"height":64}""";
// The API refuses a preset that gives a member twice; one already queued fails with its reason.
using (var refused = await editor.PostAsJsonAsync("/api/v1/jobs",
new CreateJobRequest("render", [sequence.Id], Parameters(mjpeg + ""","Preset":{}}""")), ProtocolJson.Default.CreateJobRequest))
await refused.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_parameters");
var engine = server.Services.GetRequiredService<JobEngineHost>().Engine;
var broken = await engine.EnqueueAsync(JobKind.Render, [sequence.Id], "broken", Parameters(mjpeg + ""","Preset":{}}"""), JobPriority.User, user.Id);
var failed = await JobApiTests.WaitForAsync(editor, broken.Id, "failed");
Assert.Equal(Loc.L("Errors.Render.Parameters"), failed.Error);
// The workers carry on: a null batch is no batch.
var fine = await JobApiTests.CreateAsync(editor, "render", sequence.Id, Parameters(mjpeg + ""","batch":null}"""));
await JobApiTests.WaitForAsync(editor, fine.Id, "done");
}
private static string Parameters(string presetJson) =>
JsonSerializer.Serialize(new RenderJobParameters("MJPEG", presetJson, "mjpeg", 96, 64, false, null), ProtocolJson.Default.RenderJobParameters);
private static List<ServerEvent> Drain(EventHub.Subscription events)
{
var drained = new List<ServerEvent>();
while (events.Reader.TryRead(out var e)) drained.Add(e);
return drained;
}
/// <summary>Uploads a synthetic scene with Exif into one new sequence; returns its id.</summary>
private static async Task<Guid> UploadSceneAsync(HttpClient editor)
{
var scene = SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = Frames, StartEv = 0.5, EndEv = -0.5 });
Guid sequenceId = default;
for (var i = 0; i < scene.Count; i++)
{
using var image = scene.Render(i);
var exif = ExifWriter.BuildJpegApp1(scene.Metadata[i]);
var photo = JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [exif[4..]] });
sequenceId = (await Uploads.UploadAsync(editor, photo, $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
}
return sequenceId;
}
}