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

+1
View File
@@ -33,6 +33,7 @@
<data name="Advisor.Finding.WhiteFrames" xml:space="preserve"><value>{0} frames are blown out to white.</value><comment>{0} frame count</comment></data>
<data name="Advisor.Log.AutoUpdated" xml:space="preserve"><value>Automatic values of {0} updated.</value><comment>job log line; {0} sequence title</comment></data>
<data name="Advisor.Log.DeepDone" xml:space="preserve"><value>Deep analysis of {0}: {1} frames, {2} warnings.</value><comment>job log line; {0} sequence title; {1} frame count; {2} warning count</comment></data>
<data name="Advisor.Log.Failed" xml:space="preserve"><value>{0} could not be analysed: {1}</value><comment>long: job log line; {0} sequence title; {1} reason</comment></data>
<data name="Advisor.Log.LightDone" xml:space="preserve"><value>Light analysis of {0}: {1} frames, {2} warnings.</value><comment>job log line; {0} sequence title; {1} frame count; {2} warning count</comment></data>
<data name="Advisor.Log.Presets" xml:space="preserve"><value>Suggested presets: {0}</value><comment>job log line; {0} preset names separated by dots</comment></data>
<data name="Advisor.Log.ProjectUnreadable" xml:space="preserve"><value>The project settings of {0} cannot be read; their automatic values were left as they were.</value><comment>job log line; {0} sequence title</comment></data>
+2
View File
@@ -4,6 +4,7 @@
<resheader name="version"><value>2.0</value></resheader>
<resheader name="reader"><value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<resheader name="writer"><value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<data name="Errors.Analysis.Failed" xml:space="preserve"><value>{0} of {1} sequences could not be analysed; see the job log.</value><comment>long; {0} failed count (2 or more); {1} total count</comment></data>
<data name="Errors.Archive.Open" xml:space="preserve"><value>The archive could not be opened.</value><comment>long</comment></data>
<data name="Errors.Number.Range" xml:space="preserve"><value>Enter a whole number from {0} to {1}.</value></data>
<data name="Errors.Path.Empty" xml:space="preserve"><value>Enter a folder.</value></data>
@@ -13,6 +14,7 @@
<data name="Errors.Path.NotAbsolute" xml:space="preserve"><value>Enter a full path that starts with a drive or a network share.</value></data>
<data name="Errors.Render.Download" xml:space="preserve"><value>{0} could not be downloaded intact.</value><comment>{0} file name</comment></data>
<data name="Errors.Render.Failed" xml:space="preserve"><value>{0} of {1} exports failed; see the job log.</value><comment>{0} failed count; {1} total count</comment></data>
<data name="Errors.Render.NodeBatch" xml:space="preserve"><value>Render nodes send back one file per job; post each preset of a batch as its own job.</value><comment>long</comment></data>
<data name="Errors.Render.NodeSequence" xml:space="preserve"><value>Render nodes send back one file per job; image sequences render where the archive is.</value></data>
<data name="Errors.Render.Parameters" xml:space="preserve"><value>The render job has no valid export settings.</value></data>
<data name="Errors.Render.Sequence" xml:space="preserve"><value>The sequence to render is no longer in the archive.</value></data>
+1
View File
@@ -16,6 +16,7 @@
<data name="Export.Job.Downloading" xml:space="preserve"><value>Downloading frames</value><comment>render node progress stage</comment></data>
<data name="Export.Job.Preparing" xml:space="preserve"><value>Measuring frames</value><comment>job progress stage</comment></data>
<data name="Export.Log.Failed" xml:space="preserve"><value>{0} failed: {1}</value><comment>long: job log line; {0} preset name; {1} reason</comment></data>
<data name="Export.Log.NoRenderNode" xml:space="preserve"><value>No render node can encode {1}; {0} is rendered as {2} instead.</value><comment>long: job log line; {0} preset name; {1} codec asked for; {2} managed codec used</comment></data>
<data name="Export.Log.Rendered" xml:space="preserve"><value>{0} saved as {1}</value><comment>long: job log line; {0} preset name; {1} output file name</comment></data>
<data name="Export.Plan.FrameRateIgnored" xml:space="preserve"><value>Playback rate not understood; the export frame rate is used.</value><comment>long</comment></data>
<data name="Export.Plan.NoCaptureTimes" xml:space="preserve"><value>No capture times: frames are spaced evenly.</value><comment>long</comment></data>
+1
View File
@@ -33,6 +33,7 @@
<data name="Advisor.Finding.WhiteFrames" xml:space="preserve"><value>{0} fotogrammi sono completamente bruciati.</value></data>
<data name="Advisor.Log.AutoUpdated" xml:space="preserve"><value>Valori automatici di {0} aggiornati.</value></data>
<data name="Advisor.Log.DeepDone" xml:space="preserve"><value>Analisi approfondita di {0}: {1} fotogrammi, {2} avvisi.</value></data>
<data name="Advisor.Log.Failed" xml:space="preserve"><value>Impossibile analizzare {0}: {1}</value></data>
<data name="Advisor.Log.LightDone" xml:space="preserve"><value>Analisi rapida di {0}: {1} fotogrammi, {2} avvisi.</value></data>
<data name="Advisor.Log.Presets" xml:space="preserve"><value>Preset suggeriti: {0}</value></data>
<data name="Advisor.Log.ProjectUnreadable" xml:space="preserve"><value>Le impostazioni del progetto di {0} non sono leggibili; i valori automatici sono rimasti invariati.</value></data>
+2
View File
@@ -4,6 +4,7 @@
<resheader name="version"><value>2.0</value></resheader>
<resheader name="reader"><value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<resheader name="writer"><value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<data name="Errors.Analysis.Failed" xml:space="preserve"><value>{0} sequenze su {1} non sono state analizzate; vedi il registro del job.</value></data>
<data name="Errors.Archive.Open" xml:space="preserve"><value>Impossibile aprire l'archivio.</value></data>
<data name="Errors.Number.Range" xml:space="preserve"><value>Inserisci un numero intero da {0} a {1}.</value></data>
<data name="Errors.Path.Empty" xml:space="preserve"><value>Inserisci una cartella.</value></data>
@@ -13,6 +14,7 @@
<data name="Errors.Path.NotAbsolute" xml:space="preserve"><value>Inserisci un percorso completo che inizi con un'unità o una condivisione di rete.</value></data>
<data name="Errors.Render.Download" xml:space="preserve"><value>{0} non è stato scaricato integro.</value></data>
<data name="Errors.Render.Failed" xml:space="preserve"><value>{0} esportazioni su {1} non riuscite; vedi il registro del job.</value></data>
<data name="Errors.Render.NodeBatch" xml:space="preserve"><value>I nodi di rendering restituiscono un file per job; invia ogni preset di un gruppo come job a sé.</value></data>
<data name="Errors.Render.NodeSequence" xml:space="preserve"><value>I nodi di rendering restituiscono un file per job; le sequenze di immagini si renderizzano dove si trova l'archivio.</value></data>
<data name="Errors.Render.Parameters" xml:space="preserve"><value>Il job di rendering non ha impostazioni di esportazione valide.</value></data>
<data name="Errors.Render.Sequence" xml:space="preserve"><value>La sequenza da renderizzare non è più nell'archivio.</value></data>
+1
View File
@@ -16,6 +16,7 @@
<data name="Export.Job.Downloading" xml:space="preserve"><value>Download dei fotogrammi</value></data>
<data name="Export.Job.Preparing" xml:space="preserve"><value>Misura dei fotogrammi</value></data>
<data name="Export.Log.Failed" xml:space="preserve"><value>{0} non riuscito: {1}</value></data>
<data name="Export.Log.NoRenderNode" xml:space="preserve"><value>Nessun nodo di rendering può codificare {1}; {0} viene esportato in {2}.</value></data>
<data name="Export.Log.Rendered" xml:space="preserve"><value>{0} salvato come {1}</value></data>
<data name="Export.Plan.FrameRateIgnored" xml:space="preserve"><value>Velocità di riproduzione non valida; viene usata la frequenza di esportazione.</value></data>
<data name="Export.Plan.NoCaptureTimes" xml:space="preserve"><value>Nessun orario di scatto: fotogrammi distribuiti in modo uniforme.</value></data>
+63 -51
View File
@@ -31,12 +31,17 @@ namespace Titano.App.Infrastructure;
/// <see cref="CreateJobHandlers"/>, thumbnails, the server session, the render node, the encoder inventory and the
/// update check. Started after the window shows, stopped when the app exits. The last archive is reopened at start and
/// rescanned every <see cref="ScanInterval"/> (BRIEF §7: polling, no file-system watchers). The render node runs while
/// the user offers this PC (<see cref="AppSettings.RenderNodeOptIn"/>) and a server session is open.
/// the user offers this PC (<see cref="AppSettings.RenderNodeOptIn"/>) and a server session is open (never in capture
/// mode). Renders and the render node use hardware encoders as Settings › Rendering allows
/// (<see cref="AllowsHardware(HardwarePreference, string)"/>). Disposal never needs the UI thread, which waits for it.
/// </summary>
public sealed class AppServices : IAsyncDisposable
{
public static readonly TimeSpan ScanInterval = TimeSpan.FromMinutes(10);
/// <summary>The quick preview preset: the one render "Hardware for previews only" leaves on the GPU.</summary>
private const string PreviewPresetId = "720p-preview";
private static readonly Lazy<HttpClient> Http = new(() => new HttpClient { Timeout = TimeSpan.FromSeconds(20) });
/// <summary>Update packages are large: their download fails when it stalls (<see cref="UpdateDownload.IdleTimeout"/>), never after a fixed total time.</summary>
@@ -44,9 +49,8 @@ public sealed class AppServices : IAsyncDisposable
private readonly CancellationTokenSource _stopping = new();
private readonly Dictionary<Guid, Guid> _scans = [];
private Task _polling = Task.CompletedTask;
private readonly RenderNodeHost _renderNode;
private ServerSession _server = null!;
private Task _nodeSwitch = Task.CompletedTask;
private (RenderNodeClient Node, TitanoClient Client, Uri Address, string Token)? _node;
public AppServices(AppEnvironment environment, AppSettings settings, Action saveSettings, IAppDialogs dialogs)
{
@@ -54,6 +58,7 @@ public sealed class AppServices : IAsyncDisposable
Settings = settings;
SaveSettingsAction = saveSettings;
Dialogs = dialogs;
_renderNode = new RenderNodeHost(StartRenderNode);
ArchiveSetup = new EngineArchiveSetup(this);
Server = new ServerSession(settings, saveSettings, new TitanoServerApiFactory(), new DpapiTokenProtector());
Encoders = new MediaFoundationInventory();
@@ -145,8 +150,18 @@ public sealed class AppServices : IAsyncDisposable
UpdateRenderNode();
}
/// <summary>Starts or stops the render node to match the opt-in and the server session (BRIEF §14.7); switches run in order.</summary>
public void UpdateRenderNode() => _nodeSwitch = SwitchRenderNodeAsync(_nodeSwitch);
/// <summary>Starts, restarts or stops the render node to match the opt-in, the server session and the trusted certificates (BRIEF §14.7).</summary>
public void UpdateRenderNode() =>
_renderNode.Update(RenderNodeSession.For(Settings.RenderNodeOptIn && Processing is not null && !Environment.IsCapture, _server.IsConnected,
_server.Flow.Address, _server.Flow.Token, _server.Fingerprints, AllowsHardware(Settings.HardwareEncoding, ExportResolver.CustomId)));
/// <summary>Settings › Rendering: whether a render of <paramref name="presetId"/> may use hardware encoders.</summary>
public static bool AllowsHardware(HardwarePreference preference, string presetId) => preference switch
{
HardwarePreference.PreferHardware => true,
HardwarePreference.HardwareForPreviews => presetId.Equals(PreviewPresetId, StringComparison.OrdinalIgnoreCase),
_ => false,
};
/// <summary>Opens (or creates) the index at <paramref name="databasePath"/>, migrates it and starts the job engine.</summary>
public async Task OpenAsync(string databasePath, CancellationToken ct = default)
@@ -175,34 +190,36 @@ public sealed class AppServices : IAsyncDisposable
Thumbnails = new ThumbnailService(database, Settings.ThumbnailMemoryItems);
}
/// <summary>Stops polling, the render node and the engine, then closes the index. The app's exit waits for this on the UI
/// thread, so nothing here continues on it.</summary>
public async ValueTask DisposeAsync()
{
await _stopping.CancelAsync();
await _polling;
await _stopping.CancelAsync().ConfigureAwait(false);
await _polling.ConfigureAwait(false);
_stopping.Dispose();
_server.PropertyChanged -= OnServerChanged;
await _nodeSwitch;
await StopRenderNodeAsync();
await _renderNode.DisposeAsync().ConfigureAwait(false);
(Jobs as IDisposable)?.Dispose();
if (Engine is not null) await Engine.DisposeAsync();
if (Engine is not null) await Engine.DisposeAsync().ConfigureAwait(false);
Thumbnails?.Dispose();
Server.Dispose();
if (Database is not null) await Database.DisposeAsync();
if (Database is not null) await Database.DisposeAsync().ConfigureAwait(false);
}
/// <summary>Reopens the last archive (relinking a moved one, finishing interrupted renames) and rescans it periodically.</summary>
/// <summary>Reopens the last archive (relinking a moved one, finishing interrupted renames) and rescans it periodically,
/// off the UI thread (disposal waits for it there).</summary>
private async Task PollAsync(string root, CancellationToken ct)
{
try
{
if (Archives is null) return;
var archive = await Task.Run(() => Archives.OpenAsync(root, ct), ct);
var archive = await Task.Run(() => Archives.OpenAsync(root, ct), ct).ConfigureAwait(false);
using var timer = new PeriodicTimer(ScanInterval);
do
{
if (ArchiveService.GetAvailability(archive) == ArchiveAvailability.Online) await QueueScanAsync(archive, full: false, ct);
if (ArchiveService.GetAvailability(archive) == ArchiveAvailability.Online) await QueueScanAsync(archive, full: false, ct).ConfigureAwait(false);
}
while (await timer.WaitForNextTickAsync(ct));
while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false));
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
@@ -229,12 +246,14 @@ public sealed class AppServices : IAsyncDisposable
UpdateRenderNode();
}
/// <summary>Media Foundation (hardware first, software H.264) then managed encoders; frames spill into the cache folder
/// within the memory budget of Settings › Rendering (Auto: a quarter of the installed memory).</summary>
/// <summary>Media Foundation (hardware first, software H.264; hardware as Settings › Rendering allows) then managed
/// encoders; frames spill into the cache folder within the memory budget of Settings › Rendering (Auto: a quarter of
/// the installed memory).</summary>
private ProcessingOptions ProcessingOptions(ArchiveServiceOptions archive) => new()
{
Archive = archive,
Encoders = [new MediaFoundationEncoderProvider(), new ManagedEncoderProvider()],
AllowsHardware = presetId => AllowsHardware(Settings.HardwareEncoding, presetId),
Host = EncoderHost.Client,
ProducedBy = System.Environment.MachineName,
FrameWindow = new FrameWindowOptions
@@ -246,45 +265,38 @@ public sealed class AppServices : IAsyncDisposable
private void OnServerChanged(object? sender, PropertyChangedEventArgs e) => UpdateRenderNode();
/// <summary>Waits for the previous switch, then runs the node for the current session, or stops it.</summary>
private async Task SwitchRenderNodeAsync(Task previous)
/// <summary>
/// The render node of <paramref name="session"/>: this PC's encoders (Media Foundation, then managed), downloads and
/// outputs in the cache folder within its size limit.
/// </summary>
private IRenderNode StartRenderNode(RenderNodeSession session)
{
await previous;
var flow = _server.Flow;
(ProcessingService Engine, Uri Address, string Token)? wanted =
Settings.RenderNodeOptIn && _server.IsConnected && Processing is { } processing && flow.Address is { } address && flow.Token is { } token
? (processing, address, token)
: null;
if (_node is { } running && wanted is { } same && running.Address == same.Address && running.Token == same.Token) return;
await StopRenderNodeAsync();
if (wanted is not { } start) return;
try
var processing = Processing ?? throw new InvalidOperationException("The index is not open.");
var cache = CacheStore.Folder(Environment, Settings);
CacheStore.Prepare(cache);
var client = new TitanoClient(session.Address, new CertificatePinning(session.TrustedFingerprints), $"Titano ({System.Environment.MachineName})")
{
var cache = CacheStore.Folder(Environment, Settings);
CacheStore.Prepare(cache);
var client = new TitanoClient(start.Address, new CertificatePinning(_server.Fingerprints), $"Titano ({System.Environment.MachineName})") { Token = start.Token };
var node = new RenderNodeClient(client, start.Engine.Options, new RenderNodeOptions
{
ClientName = System.Environment.MachineName,
CacheDirectory = Path.Combine(cache, "render-node"),
CacheLimitBytes = Settings.CacheLimitGb * (1L << 30),
});
node.Start();
_node = (node, client, start.Address, start.Token);
Log.Info("render-node", $"Offering this PC as render node to {start.Address}");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
Token = session.Token,
};
var node = new RenderNodeClient(client, processing.Options, new RenderNodeOptions
{
Log.Warning("render-node", "The render node could not start", ex);
}
ClientName = System.Environment.MachineName,
CacheDirectory = Path.Combine(cache, "render-node"),
CacheLimitBytes = Settings.CacheLimitGb * (1L << 30),
});
node.Start();
return new RunningNode(node, client);
}
private async Task StopRenderNodeAsync()
/// <summary>A started node and the client it owns.</summary>
private sealed class RunningNode(RenderNodeClient node, TitanoClient client) : IRenderNode
{
if (_node is not { } running) return;
_node = null;
await running.Node.DisposeAsync();
running.Client.Dispose();
Log.Info("render-node", "Render node stopped");
public Task Completion => node.Completion;
public async ValueTask DisposeAsync()
{
await node.DisposeAsync().ConfigureAwait(false);
client.Dispose();
}
}
}
@@ -0,0 +1,124 @@
using Titano.Core.Diagnostics;
namespace Titano.App.Infrastructure;
/// <summary>
/// What a render node runs with: the server session (address and token), the certificates it may trust and whether it
/// offers hardware encoders. A change of any of them means another node.
/// </summary>
public sealed record RenderNodeSession(Uri Address, string Token, IReadOnlyCollection<string> TrustedFingerprints, bool Hardware)
{
/// <summary>
/// The session a node should run for, or null when it should be off: the user offers this PC
/// (<paramref name="offered"/>), a server session is open and signed in.
/// </summary>
public static RenderNodeSession? For(bool offered, bool connected, Uri? address, string? token, IReadOnlyCollection<string> trustedFingerprints,
bool hardware) =>
offered && connected && address is not null && token is not null ? new RenderNodeSession(address, token, trustedFingerprints, hardware) : null;
public bool Equals(RenderNodeSession? other) =>
other is not null && Address == other.Address && Token == other.Token && Hardware == other.Hardware
&& TrustedFingerprints.Order(StringComparer.Ordinal).SequenceEqual(other.TrustedFingerprints.Order(StringComparer.Ordinal), StringComparer.Ordinal);
public override int GetHashCode() => HashCode.Combine(Address, Token, Hardware, TrustedFingerprints.Count);
}
/// <summary>A started render node.</summary>
public interface IRenderNode : IAsyncDisposable
{
/// <summary>Completes when the node has stopped, by itself (refused by the server) or when disposed.</summary>
Task Completion { get; }
}
/// <summary>
/// Keeps this PC's render node (BRIEF §14.7) in line with "Offer this PC as render node" and the server session:
/// <see cref="Update"/> starts the node for the wanted session, restarts it for another session or when it stopped by
/// itself, and stops it when none is wanted. Switches run one after the other, off the caller's thread, and never fail:
/// a node that cannot start is logged and stays off until the next update.
/// </summary>
public sealed class RenderNodeHost(Func<RenderNodeSession, IRenderNode> start) : IAsyncDisposable
{
private readonly Lock _gate = new();
private Task _switching = Task.CompletedTask;
private (RenderNodeSession Session, IRenderNode Node)? _running;
private bool _disposed;
/// <summary>The session the node runs for; null when it is off.</summary>
public RenderNodeSession? Session
{
get
{
lock (_gate) return _running?.Session;
}
}
/// <summary>Completes when every switch requested so far has run.</summary>
public Task Switching
{
get
{
lock (_gate) return _switching;
}
}
/// <summary>Runs the node for <paramref name="wanted"/>, or stops it when null.</summary>
public void Update(RenderNodeSession? wanted)
{
lock (_gate)
{
if (_disposed) return;
var previous = _switching;
_switching = Task.Run(async () =>
{
await previous.ConfigureAwait(false);
await SwitchAsync(wanted).ConfigureAwait(false);
});
}
}
/// <summary>Stops the node after the pending switches; later updates are ignored.</summary>
public async ValueTask DisposeAsync()
{
Task pending;
lock (_gate)
{
_disposed = true;
pending = _switching;
}
await pending.ConfigureAwait(false);
await SwitchAsync(null).ConfigureAwait(false);
}
private async Task SwitchAsync(RenderNodeSession? wanted)
{
(RenderNodeSession Session, IRenderNode Node)? running;
lock (_gate) running = _running;
// A node the server refused has stopped by itself: the same session starts it again (the right may be granted now).
if (running?.Session == wanted && running?.Node.Completion.IsCompleted != true) return;
if (running is { } old)
{
lock (_gate) _running = null;
try
{
await old.Node.DisposeAsync().ConfigureAwait(false);
Log.Info("render-node", "Render node stopped");
}
catch (Exception ex)
{
// A node that fails to stop is gone anyway; the next one must still be able to start.
Log.Warning("render-node", "The render node did not stop cleanly", ex);
}
}
if (wanted is null) return;
try
{
var node = start(wanted);
lock (_gate) _running = (wanted, node);
Log.Info("render-node", $"Offering this PC as render node to {wanted.Address}");
}
catch (Exception ex)
{
Log.Warning("render-node", "The render node could not start", ex);
}
}
}
+9 -8
View File
@@ -105,33 +105,34 @@ public static class ExportNaming
/// <summary>
/// Full output path inside <paramref name="folder"/>: the expanded name plus the codec's extension, or the bare name
/// for image sequences (a folder), made unique against existing files and folders.
/// for image sequences (a folder), made unique against existing files and folders and the paths <paramref name="taken"/>
/// says are being written.
/// </summary>
public static string OutputPath(string folder, string template, ExportNameContext context)
public static string OutputPath(string folder, string template, ExportNameContext context, Func<string, bool>? taken = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(folder);
var name = Expand(template, context).Name;
var extension = VideoCodecInfo.DefaultContainer(context.Codec) == ContainerFormat.ImageSequence ? string.Empty : VideoCodecInfo.FileExtension(context.Codec);
return Unique(folder, name, extension);
return Unique(folder, name, extension, taken);
}
/// <summary>
/// Output path of a project's export: <see cref="ExportSettings.Folder"/> or, when unset, the sequence's exports folder,
/// named by <see cref="ExportSettings.NameTemplate"/>.
/// </summary>
public static string OutputPath(ExportSettings settings, string sequenceExportsFolder, ExportNameContext context)
public static string OutputPath(ExportSettings settings, string sequenceExportsFolder, ExportNameContext context, Func<string, bool>? taken = null)
{
ArgumentNullException.ThrowIfNull(settings);
return OutputPath(string.IsNullOrWhiteSpace(settings.Folder) ? sequenceExportsFolder : settings.Folder, settings.NameTemplate, context);
return OutputPath(string.IsNullOrWhiteSpace(settings.Folder) ? sequenceExportsFolder : settings.Folder, settings.NameTemplate, context, taken);
}
/// <summary>"name.ext", or "name (2).ext", "name (3).ext"… when a file or folder of that name exists.</summary>
public static string Unique(string folder, string name, string extension)
/// <summary>"name.ext", or "name (2).ext", "name (3).ext"… when a file or folder of that name exists or is <paramref name="taken"/>.</summary>
public static string Unique(string folder, string name, string extension, Func<string, bool>? taken = null)
{
for (var n = 1; ; n++)
{
var candidate = Path.Combine(folder, (n == 1 ? name : string.Create(CultureInfo.InvariantCulture, $"{name} ({n})")) + extension);
if (!File.Exists(candidate) && !Directory.Exists(candidate)) return candidate;
if (!File.Exists(candidate) && !Directory.Exists(candidate) && taken?.Invoke(candidate) != true) return candidate;
}
}
+20 -5
View File
@@ -84,6 +84,8 @@ public sealed record ExposureSettings
public double ExposureOffsetEv { get; init; }
/// <summary>Soft highlight knee (linear), null = hard clip at the encoder.</summary>
/// <remarks>Written even when null: a missing value reads back as the default knee, which would turn "off" on.</remarks>
[JsonIgnore(Condition = JsonIgnoreCondition.Never)]
public double? HighlightKnee { get; init; } = 0.9;
}
@@ -187,7 +189,7 @@ public sealed record ProjectSettings
/// keep their defaults. The JSON is laid over the default project first, because generated deserialisation leaves
/// missing init-only members null or false rather than at their initial values.
/// </summary>
/// <exception cref="JsonException">The text is not a JSON object.</exception>
/// <exception cref="JsonException">The text is not a JSON object, or repeats a member.</exception>
/// <exception cref="InvalidDataException">The project was written by a newer Titano.</exception>
public static ProjectSettings FromJson(string json)
{
@@ -196,7 +198,15 @@ public sealed record ProjectSettings
switch (JsonNode.Parse(json, options))
{
case JsonObject given:
Overlay(merged, given);
try
{
Overlay(merged, given);
}
catch (ArgumentException ex)
{
// A parsed object builds its member table on first use and rejects a name given twice (in any casing).
throw new JsonException("A project member is given more than once.", ex);
}
break;
case not null:
throw new JsonException("A project must be a JSON object.");
@@ -207,13 +217,18 @@ public sealed record ProjectSettings
return settings;
}
/// <summary>Copies <paramref name="source"/> into <paramref name="target"/>, merging nested objects; a null never replaces an object.</summary>
/// <summary>
/// Copies <paramref name="source"/> into <paramref name="target"/>, merging nested objects. A null keeps a default that
/// is an object, a list or a text, since none of those members is nullable; elsewhere it clears a nullable value.
/// </summary>
private static void Overlay(JsonObject target, JsonObject source)
{
foreach (var (name, value) in source)
{
if (value is JsonObject child && target[name] is JsonObject existing) Overlay(existing, child);
else if (value is not null || target[name] is not JsonObject) target[name] = value?.DeepClone();
var current = target[name];
if (value is JsonObject child && current is JsonObject section) Overlay(section, child);
else if (value is not null || !(current is JsonObject or JsonArray || current?.GetValueKind() == JsonValueKind.String))
target[name] = value?.DeepClone();
}
}
}
+5 -1
View File
@@ -160,7 +160,11 @@ public sealed class ArchiveIndexer
if (reconcile || File.Exists(sequence.IngestJournalPath))
{
var before = manifest;
manifest = await _writer.UpdateAsync(paths, manifest.Id, folder.RelativeFolder, m => SequenceAdopter.Reconcile(sequence, m, cancellationToken),
// Photos added, gone or back: the light analysis no longer describes the frames, so the scan's follow-up runs it again.
manifest = await _writer.UpdateAsync(paths, manifest.Id, folder.RelativeFolder,
m => SequenceAdopter.Reconcile(sequence, m, cancellationToken) is { } reconciled
? reconciled with { Status = reconciled.Status & ~SequenceStatus.AnalyzedLight }
: null,
cancellationToken).ConfigureAwait(false);
if (!ReferenceEquals(before, manifest)) bytes = null;
}
+1 -1
View File
@@ -48,7 +48,7 @@ public sealed class ArchiveService : IJobHandlerProvider
new ScanJobHandler(_db, Indexer, JobKind.Scan),
new ScanJobHandler(_db, Indexer, JobKind.Rebuild),
new VerifyJobHandler(_db, Verifier),
new ImportJobHandler(Imports),
new ImportJobHandler(_db, Imports),
new ImageJobHandler(_db, Images, JobKind.Thumbs),
new ImageJobHandler(_db, Images, JobKind.Proxies),
new MaintenanceJobHandler(_db, Maintenance),
@@ -143,6 +143,18 @@ public sealed class ImportService
}, progress, cancellationToken).ConfigureAwait(false);
}
/// <summary>The sequences the sessions of an import went into (new or continued), as far as they exist.</summary>
internal async Task<List<Guid>> SequencesOfAsync(ImportJobParameters job, CancellationToken cancellationToken)
{
var ids = new List<Guid>();
foreach (var session in job.Plan.Sessions)
{
if (await _db.Sequences.FindBySessionKeyAsync(job.ArchiveId, session.SessionKey, cancellationToken).ConfigureAwait(false) is { } id
&& !ids.Contains(id)) ids.Add(id);
}
return ids;
}
/// <summary>Dry run of "delete imported": every card file with a recorded import, checked against its archive copy.</summary>
public async Task<ErasePlan> PlanEraseAsync(Archive archive, Guid cardId, string sourceRoot, IProgress<int>? progress = null,
CancellationToken cancellationToken = default)
@@ -4,15 +4,16 @@ using Titano.Core.Import;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data.Jobs;
using Titano.Data.Processing;
namespace Titano.Data.Archiving.Jobs;
/// <summary>
/// <see cref="JobKind.Import"/>: executes the confirmed plan in its parameters; progress in bytes. Checkpoint: the
/// number of plan items done. A removed card fails the job at a batch boundary; resuming it after re-insertion
/// continues there.
/// continues there. The sequences the import went into are then queued for light analysis.
/// </summary>
internal sealed class ImportJobHandler(ImportService imports) : IJobHandler
internal sealed class ImportJobHandler(TitanoDatabase db, ImportService imports) : IJobHandler
{
public JobKind Kind => JobKind.Import;
@@ -29,5 +30,6 @@ internal sealed class ImportJobHandler(ImportService imports) : IJobHandler
.ConfigureAwait(false);
}, p => context.ReportAsync(p.BytesDone, p.BytesTotal, p.Current), context.Cancellation).ConfigureAwait(false);
context.Log(Loc.L("Archive.Log.ImportDone", final.Copied, final.Skipped, final.Failed));
await AnalysisFollowUp.QueueAsync(db, context, await imports.SequencesOfAsync(parameters, context.Cancellation).ConfigureAwait(false)).ConfigureAwait(false);
}
}
@@ -1,6 +1,7 @@
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data.Jobs;
using Titano.Data.Processing;
namespace Titano.Data.Archiving.Jobs;
@@ -15,7 +16,9 @@ internal static class JobArchive
/// <summary>
/// <see cref="JobKind.Scan"/> (incremental, or full with <see cref="ScanParameters.Full"/>) and
/// <see cref="JobKind.Rebuild"/>. Checkpoint: <c>after:&lt;folder&gt;</c>, the last folder indexed.
/// <see cref="JobKind.Rebuild"/>. Checkpoint: <c>after:&lt;folder&gt;</c>, the last folder indexed. When anything was
/// indexed, the sequences without a current light analysis (adopted folders, new sidecars, photos added to a folder) are
/// queued for it.
/// </summary>
internal sealed class ScanJobHandler(TitanoDatabase db, ArchiveIndexer indexer, JobKind kind) : IJobHandler
{
@@ -37,5 +40,9 @@ internal sealed class ScanJobHandler(TitanoDatabase db, ArchiveIndexer indexer,
}, context.Cancellation).ConfigureAwait(false);
foreach (var (folder, error) in summary.Failed) context.Log(Loc.L("Archive.Log.FolderFailed", folder, error));
context.Log(Loc.L("Archive.Log.ScanDone", summary.Folders, summary.Indexed, summary.Adopted, summary.Removed));
// A resumed scan may have indexed its folders before the interruption.
if (summary.Indexed > 0 || resume is not null)
await AnalysisFollowUp.QueueAsync(db, context, await AnalysisFollowUp.UnanalysedAsync(db, archive.Id, context.Cancellation).ConfigureAwait(false))
.ConfigureAwait(false);
}
}
+78 -5
View File
@@ -28,13 +28,22 @@ public sealed record JobEngineOptions
/// <summary>
/// Persistent job queue runner (BRIEF §14.6): N workers claim queued jobs from the database by priority, run the
/// registered handler, checkpoint progress, and survive crashes (running jobs are requeued at start with their
/// checkpoints). Used by the desktop client (local mode) and the server.
/// checkpoints). Used by the desktop client (local mode) and the server. Jobs an <see cref="ISelectiveJobHandler"/>
/// declines stay queued for other claimers.
/// </summary>
public sealed class JobEngine : IAsyncDisposable
{
/// <summary>Queued jobs of selective kinds examined per claim; jobs declined beyond it wait until those ahead leave the queue.</summary>
private const int SelectiveWindow = 100;
/// <summary>Claims lost to other workers before a worker waits for the next poll.</summary>
private const int MaxClaimRaces = 16;
private readonly TitanoDatabase _db;
private readonly Dictionary<JobKind, IJobHandler> _handlers;
private IReadOnlyCollection<JobKind> _kinds = [];
private Dictionary<JobKind, ISelectiveJobHandler> _selective = [];
private IReadOnlyCollection<JobKind> _others = [];
private readonly ConcurrentDictionary<Guid, CancellationTokenSource> _running = new();
private readonly Channel<bool> _wake = Channel.CreateBounded<bool>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite });
private readonly CancellationTokenSource _shutdown = new();
@@ -65,6 +74,8 @@ public sealed class JobEngine : IAsyncDisposable
await _db.Jobs.PurgeHistoryAsync(DateTimeOffset.UtcNow - Options.HistoryRetention, cancellationToken).ConfigureAwait(false);
// Only kinds this engine can run: an empty filter would claim (and fail) every job, render-node work included.
_kinds = [.. (Options.Kinds ?? _handlers.Keys).Where(_handlers.ContainsKey).Distinct()];
_selective = _kinds.Select(k => _handlers[k]).OfType<ISelectiveJobHandler>().ToDictionary(h => h.Kind);
_others = [.. _kinds.Where(k => !_selective.ContainsKey(k))];
if (_kinds.Count == 0)
{
Log.Info("jobs", "No job handlers; this engine claims nothing");
@@ -150,6 +161,9 @@ public sealed class JobEngine : IAsyncDisposable
}
}
/// <summary>True when this engine claims jobs of <paramref name="kind"/> (it has a handler and the kind is not filtered out).</summary>
internal bool Runs(JobKind kind) => _kinds.Contains(kind);
internal void StopJob(Guid id)
{
if (_running.TryGetValue(id, out var cts)) cts.Cancel();
@@ -167,6 +181,7 @@ public sealed class JobEngine : IAsyncDisposable
if (await _db.Jobs.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } job) JobChanged?.Invoke(job);
}
/// <summary>Claims and runs jobs until shutdown. Nothing a job or a handler throws ends the worker.</summary>
private async Task WorkerLoopAsync(string workerId, CancellationToken shutdown)
{
while (!shutdown.IsCancellationRequested)
@@ -174,13 +189,13 @@ public sealed class JobEngine : IAsyncDisposable
Job? job;
try
{
job = await _db.Jobs.ClaimNextAsync(workerId, _kinds, shutdown).ConfigureAwait(false);
job = await ClaimAsync(workerId, shutdown).ConfigureAwait(false);
}
catch (OperationCanceledException)
catch (OperationCanceledException) when (shutdown.IsCancellationRequested)
{
return;
}
catch (DatabaseException ex)
catch (Exception ex)
{
Log.Warning("jobs", "Claiming a job failed", ex);
job = null;
@@ -201,10 +216,68 @@ public sealed class JobEngine : IAsyncDisposable
continue;
}
await RunAsync(job, shutdown).ConfigureAwait(false);
try
{
await RunAsync(job, shutdown).ConfigureAwait(false);
}
catch (Exception ex)
{
// The job's final state could not be stored (also while stopping): it stays running and is requeued at the
// next start. The worker never faults, so disposing the engine never throws.
Log.Error("jobs", $"{job.Kind} job {job.Id} could not be finished", ex);
}
}
}
/// <summary>
/// The next job in claim order (priority, then age). Without selective handlers the database picks it atomically.
/// With them, the first job a selective handler accepts among the first <see cref="SelectiveWindow"/> of its kinds
/// competes with the head of the other kinds: the other kinds are still claimed atomically, the selective job by id.
/// A lost race means another worker took a job, so looking again at once makes progress.
/// </summary>
private async Task<Job?> ClaimAsync(string workerId, CancellationToken cancellationToken)
{
if (_selective.Count == 0) return await _db.Jobs.ClaimNextAsync(workerId, _kinds, cancellationToken).ConfigureAwait(false);
for (var attempt = 0; attempt < MaxClaimRaces; attempt++)
{
Job? candidate = null;
foreach (var queued in await _db.Jobs.ListQueuedAsync(_selective.Keys, SelectiveWindow, cancellationToken).ConfigureAwait(false))
{
if (!await AcceptsAsync(queued, cancellationToken).ConfigureAwait(false)) continue;
candidate = queued;
break;
}
if (candidate is null) return _others.Count > 0 ? await _db.Jobs.ClaimNextAsync(workerId, _others, cancellationToken).ConfigureAwait(false) : null;
if (_others.Count > 0 && (await _db.Jobs.ListQueuedAsync(_others, 1, cancellationToken).ConfigureAwait(false)).FirstOrDefault() is { } head
&& ClaimsBefore(head, candidate))
{
if (await _db.Jobs.ClaimNextAsync(workerId, _others, cancellationToken).ConfigureAwait(false) is { } next) return next;
}
else if (await _db.Jobs.TryClaimAsync(candidate.Id, workerId, cancellationToken).ConfigureAwait(false) is { } claimed)
{
return claimed;
}
}
return null;
}
/// <summary>A job its handler cannot judge is taken, so it fails here with its reason instead of blocking the queue.</summary>
private async ValueTask<bool> AcceptsAsync(Job job, CancellationToken cancellationToken)
{
try
{
return await _selective[job.Kind].AcceptsAsync(job, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (!(ex is OperationCanceledException && cancellationToken.IsCancellationRequested))
{
Log.Warning("jobs", $"{job.Kind} job {job.Id} could not be examined; it is claimed so that it fails with its reason", ex);
return true;
}
}
private static bool ClaimsBefore(Job a, Job b) =>
a.Priority != b.Priority ? a.Priority > b.Priority : a.Created != b.Created ? a.Created < b.Created : a.Id.CompareTo(b.Id) < 0;
private async Task RunAsync(Job job, CancellationToken shutdown)
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(shutdown);
+20
View File
@@ -13,6 +13,17 @@ public interface IJobHandler
Task RunAsync(JobContext context);
}
/// <summary>
/// A handler that runs only some jobs of its kind. The engine leaves the others queued for other claimers and asks again
/// at every claim, so an answer may change while the job waits: the server renders what its managed encoders produce,
/// leaves the rest to render nodes, and takes those too in a managed format once no node can (BRIEF §14.5, §14.7).
/// </summary>
public interface ISelectiveJobHandler : IJobHandler
{
/// <summary>Whether this handler takes <paramref name="job"/> now. A job it cannot read should be taken, so it fails with its reason.</summary>
ValueTask<bool> AcceptsAsync(Job job, CancellationToken cancellationToken);
}
/// <summary>A component that brings several handlers (the archive engine: scan, rebuild, verify, import, images, maintenance).</summary>
public interface IJobHandlerProvider
{
@@ -75,6 +86,15 @@ public sealed class JobContext
return ReportCoreAsync(done, total, Message, force: true);
}
/// <summary>
/// Queues follow-up work on this job's engine for the same user (light analysis after an import); null when the
/// engine has no handler for <paramref name="kind"/>, since nothing here would run it.
/// </summary>
public async Task<Job?> EnqueueFollowUpAsync(JobKind kind, IReadOnlyList<Guid> targets, string? label, string? parametersJson, JobPriority priority) =>
_engine.Runs(kind)
? await _engine.EnqueueAsync(kind, targets, label, parametersJson, priority, Job.CreatedBy, Cancellation).ConfigureAwait(false)
: null;
/// <summary>Appends a line to the job log (the last lines are kept with the job).</summary>
public void Log(string line)
{
@@ -0,0 +1,41 @@
using Titano.Core.Model;
using Titano.Data.Jobs;
using Titano.Data.Repositories;
namespace Titano.Data.Processing;
/// <summary>
/// Light analysis queued after work that brings sequences or frames into the index (card import, adoption, scan), so the
/// advisor's Auto values and recommended preset exist without any user action (BRIEF §1.1, §4.3). Nothing is queued
/// when the engine cannot run light analysis, and a sequence already waiting in a queued light analysis is not queued
/// again (that job runs after the changes that led here).
/// </summary>
internal static class AnalysisFollowUp
{
/// <summary>Queues one light analysis of <paramref name="sequenceIds"/> (labelled like the job that found them).</summary>
public static async Task QueueAsync(TitanoDatabase db, JobContext context, IReadOnlyCollection<Guid> sequenceIds)
{
if (sequenceIds.Count == 0) return;
var waiting = (await db.Jobs.ListQueuedAsync([JobKind.LightAnalyse], 1000, context.Cancellation).ConfigureAwait(false))
.SelectMany(j => j.TargetIds).ToHashSet();
var targets = sequenceIds.Where(id => !waiting.Contains(id)).Distinct().ToList();
if (targets.Count == 0) return;
var request = ProcessingJobs.LightAnalysis(targets, context.Job.TargetLabel);
await context.EnqueueFollowUpAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority).ConfigureAwait(false);
}
/// <summary>Sequences of <paramref name="archiveId"/> without a current light analysis (new, adopted, or with frames a scan added).</summary>
public static async Task<List<Guid>> UnanalysedAsync(TitanoDatabase db, Guid archiveId, CancellationToken cancellationToken)
{
var ids = new List<Guid>();
var query = new SequenceQuery { ArchiveId = archiveId, WithoutStatus = SequenceStatus.AnalyzedLight, Sort = SequenceSort.Oldest, Limit = 1000 };
do
{
var page = await db.Sequences.ListAsync(query, cancellationToken).ConfigureAwait(false);
ids.AddRange(page.Items.Select(s => s.Id));
query = query with { Cursor = page.NextCursor };
}
while (query.Cursor is not null);
return ids;
}
}
@@ -1,5 +1,6 @@
using System.Globalization;
using Titano.Core.Analysis.Deep;
using Titano.Core.Archiving;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data.Jobs;
@@ -8,8 +9,10 @@ namespace Titano.Data.Processing.Jobs;
/// <summary>
/// <see cref="JobKind.LightAnalyse"/> and <see cref="JobKind.DeepAnalyse"/> over the target sequences, one after the
/// other. Progress counts sequences (light) or frames (deep); checkpoint: the number of sequences done. A deep pass
/// interrupted inside a sequence resumes from that sequence's <c>analysis.partial</c>.
/// other. Progress counts sequences (light) or frames (deep). A sequence that cannot be analysed is logged and the
/// others still run; the job then fails, and a retry analyses only the failed ones. An offline archive stops the job at
/// once. Checkpoint: the next target and the failed ones (<c>next[;i,j…]</c>). A deep pass interrupted inside a
/// sequence resumes from that sequence's <c>analysis.partial</c>.
/// </summary>
internal sealed class AnalyseJobHandler(TitanoDatabase db, SequenceAnalyser analyser, JobKind kind) : IJobHandler
{
@@ -19,29 +22,50 @@ internal sealed class AnalyseJobHandler(TitanoDatabase db, SequenceAnalyser anal
{
var deep = kind == JobKind.DeepAnalyse;
var targets = context.Job.TargetIds;
var first = int.TryParse(context.Checkpoint, NumberStyles.None, CultureInfo.InvariantCulture, out var next) ? next : 0;
var (next, retry) = Parse(context.Checkpoint, targets.Count);
// Deep progress is in frames across all targets, so the bar and the ETA cover the whole job.
var frames = new long[targets.Count];
if (deep)
{
for (var i = 0; i < targets.Count; i++)
frames[i] = (await db.Sequences.GetAsync(targets[i], context.Cancellation).ConfigureAwait(false))?.FrameCount ?? 0;
}
var total = deep ? frames.Sum() : targets.Count;
for (var i = first; i < targets.Count; i++)
var units = new long[targets.Count];
for (var i = 0; i < targets.Count; i++)
units[i] = deep ? (await db.Sequences.GetAsync(targets[i], context.Cancellation).ConfigureAwait(false))?.FrameCount ?? 0 : 1;
var total = units.Sum();
var done = Enumerable.Range(0, next).Where(i => !retry.Contains(i)).Sum(i => units[i]);
var failed = new List<int>();
string? failure = null;
int[] order = [.. retry, .. Enumerable.Range(next, targets.Count - next)];
for (var k = 0; k < order.Length; k++)
{
context.Cancellation.ThrowIfCancellationRequested();
var before = deep ? frames[..i].Sum() : i;
var i = order[k];
var before = done;
var chain = new ProgressChain(context.ReportAsync);
var progress = deep ? chain.For<AnalysisProgress>(p => (before + p.Done, total, null)) : null;
var outcome = await analyser.AnalyseAsync(targets[i], deep, progress, context.Cancellation).ConfigureAwait(false);
await chain.FlushAsync().ConfigureAwait(false);
if (outcome is null) context.Log(Loc.L("Archive.Log.SequenceMissing", targets[i]));
else Report(context, outcome, deep);
await context.CheckpointAsync((i + 1).ToString(CultureInfo.InvariantCulture), deep ? before + frames[i] : i + 1, total).ConfigureAwait(false);
try
{
var outcome = await analyser.AnalyseAsync(targets[i], deep, progress, context.Cancellation).ConfigureAwait(false);
await chain.FlushAsync().ConfigureAwait(false);
if (outcome is null) context.Log(Loc.L("Archive.Log.SequenceMissing", targets[i]));
else Report(context, outcome, deep);
}
catch (Exception ex) when (ex is not (OperationCanceledException or ArchiveOfflineException))
{
await chain.FlushAsync().ConfigureAwait(false);
Core.Diagnostics.Log.Warning("processing", $"Analysis of sequence {targets[i]} failed", ex);
failure = Loc.L("Advisor.Log.Failed", await TitleAsync(targets[i], context.Cancellation).ConfigureAwait(false), ex.Message);
context.Log(failure);
failed.Add(i);
}
done += units[i];
next = int.Max(next, i + 1);
// Failed targets of an earlier attempt not retried yet stay listed.
await context.CheckpointAsync(Format(next, [.. failed, .. retry.Skip(k + 1)]), done, total).ConfigureAwait(false);
}
// One failure is the job's error as it was logged; several are counted (the log names each).
if (failed.Count > 0) throw new InvalidOperationException(failed.Count == 1 ? failure : Loc.L("Errors.Analysis.Failed", failed.Count, targets.Count));
}
private async Task<string> TitleAsync(Guid sequenceId, CancellationToken cancellationToken) =>
(await db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false))?.DisplayTitle ?? sequenceId.ToString();
private static void Report(JobContext context, AnalysisOutcome outcome, bool deep)
{
var title = outcome.Sequence.DisplayTitle;
@@ -50,4 +74,23 @@ internal sealed class AnalyseJobHandler(TitanoDatabase db, SequenceAnalyser anal
if (outcome.SettingsUnreadable) context.Log(Loc.L("Advisor.Log.ProjectUnreadable", title));
if (outcome.Presets.Count > 0) context.Log(Loc.L("Advisor.Log.Presets", string.Join(" · ", outcome.Presets.Select(p => p.DisplayName()))));
}
/// <summary>Next target and the failed targets to retry first; a missing or unreadable checkpoint starts over.</summary>
internal static (int Next, IReadOnlyList<int> Retry) Parse(string? checkpoint, int count)
{
var parts = checkpoint?.Split(';');
if (parts is not ([_] or [_, _]) || !int.TryParse(parts[0], NumberStyles.None, CultureInfo.InvariantCulture, out var next) || next > count) return (0, []);
var retry = new List<int>();
foreach (var item in parts.Length == 2 ? parts[1].Split(',') : [])
{
if (!int.TryParse(item, NumberStyles.None, CultureInfo.InvariantCulture, out var index) || index >= next) return (0, []);
if (!retry.Contains(index)) retry.Add(index);
}
return (next, retry);
}
internal static string Format(int next, IReadOnlyCollection<int> failed) =>
failed.Count == 0
? next.ToString(CultureInfo.InvariantCulture)
: string.Create(CultureInfo.InvariantCulture, $"{next};{string.Join(',', failed.Order())}");
}
@@ -0,0 +1,88 @@
using Titano.Core.Diagnostics;
using Titano.Core.Export;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Video;
using Titano.Data.Jobs;
using Titano.Protocol;
namespace Titano.Data.Processing.Jobs;
/// <summary>
/// <see cref="JobKind.Render"/> on the server (BRIEF §4.4, §14.5, §14.7): it takes the jobs whose every output (the preset
/// and each batch preset) its managed encoders produce, and runs them like a client does. Jobs that need a platform
/// encoder (MP4) wait for render nodes while <see cref="ProcessingOptions.AwaitsRenderNode"/> says one may take them;
/// after that the server takes them too, writes each output it cannot encode as MJPEG in AVI at the same size and frame
/// rate, and says so in the job log. A job it started (it left a checkpoint) resumes here, and jobs whose parameters
/// cannot be read are taken, so they fail with their reason instead of waiting for a claimer that never comes.
/// </summary>
internal sealed class ManagedRenderJobHandler(RenderJobHandler render, ProcessingOptions options) : ISelectiveJobHandler
{
/// <summary>The managed preset whose values stand in for an output only a render node could make.</summary>
private const string FallbackPresetId = "mjpeg-avi";
private readonly EncoderCapability[] _capabilities = [.. options.Encoders.SelectMany(e => e.Capabilities)];
public JobKind Kind => JobKind.Render;
public async ValueTask<bool> AcceptsAsync(Job job, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(job);
RenderJobParameters parameters;
try
{
parameters = ProcessingJobs.ReadParameters(job.ParametersJson);
// Most jobs are decided by the main codec, before the export is read.
if (Produces(parameters.Codec) && RenderJobHandler.Targets(ProcessingJobs.ReadExport(parameters.PresetJson), parameters.PresetName).All(t => Produces(t.Export)))
return true;
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
return true;
}
if (job.Checkpoint is not null) return true;
if (options.AwaitsRenderNode is not { } awaits) return false;
try
{
return !await awaits(job, parameters, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
// Unknown whether a node could take it: the job keeps waiting rather than losing its format.
Log.Warning("processing", $"Render job {job.Id}: render node availability unknown", ex);
return false;
}
}
public Task RunAsync(JobContext context) =>
render.RunAsync(context, target => Produces(target.Export) ? target : Fallback(context, target));
/// <summary>The output as MJPEG in AVI with the managed preset's quality, at the size and frame rate asked for.</summary>
private static ExportTarget Fallback(JobContext context, ExportTarget target)
{
var mjpeg = ExportResolver.FromPreset(ExportPresets.Find(FallbackPresetId)!);
context.Log(Loc.L("Export.Log.NoRenderNode", target.PresetName, ExportNaming.CodecLabel(target.Export.Codec), ExportNaming.CodecLabel(mjpeg.Codec)));
return target with
{
Export = target.Export with
{
PresetId = ExportResolver.CustomId,
NameKey = null,
Codec = mjpeg.Codec,
Profile = mjpeg.Profile,
BitDepth = mjpeg.BitDepth,
BitRate = 0,
BitsPerPixel = 0,
Quality = mjpeg.Quality,
RateControl = mjpeg.RateControl,
Encoder = null,
},
};
}
private bool Produces(string codec) =>
_capabilities.Any(c => string.Equals(ProcessingJobs.CodecName(c.Codec), codec, StringComparison.OrdinalIgnoreCase));
private bool Produces(ResolvedExport export) =>
_capabilities.Any(c => c.Codec == export.Codec && export.Width <= c.MaxWidth && export.Height <= c.MaxHeight);
}
@@ -1,3 +1,5 @@
using System.Buffers.Binary;
using System.Security.Cryptography;
using Titano.Core.Archiving;
using Titano.Core.Export;
using Titano.Core.Localization;
@@ -13,15 +15,20 @@ namespace Titano.Data.Processing.Jobs;
/// <c>RenderJobParameters</c> whose preset JSON is the export section of a project (preset, overrides, name template,
/// folder, batch). The project is the embedded one or the sequence's own; frames flagged missing, corrupt, excluded or
/// undecodable are left out. The preset and every batch preset render after one preparation pass into the sequence's
/// <c>exports/</c> (or the export folder), named by the template, and each finished output is recorded at once.
/// Checkpoint: the batch entries recorded and the output being written, so a crashed attempt's leftovers are removed and
/// only unfinished entries render again. A failed entry fails the job after the others ran; retrying renders it alone.
/// <c>exports/</c> (or the export folder, never on a server), named by the template without taking a name another render
/// of this process is writing, and each finished output is recorded at once (its row id derives from the job and the
/// entry, so every attempt knows what is recorded). Checkpoint: the entries recorded and the output being written, so a
/// crashed attempt's leftovers are removed and only unfinished entries render again. A failed entry fails the job after
/// the others ran; retrying renders it alone.
/// </summary>
internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions options) : IJobHandler
{
public JobKind Kind => JobKind.Render;
public async Task RunAsync(JobContext context)
public Task RunAsync(JobContext context) => RunAsync(context, target => target);
/// <summary>Runs the job with each output still to render passed through <paramref name="adapt"/> (the server's managed stand-ins).</summary>
internal async Task RunAsync(JobContext context, Func<ExportTarget, ExportTarget> adapt)
{
var cancellation = context.Cancellation;
var (parameters, export) = ProcessingJobs.ReadRender(context.Job.ParametersJson);
@@ -31,19 +38,28 @@ internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions opti
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var folder = paths.Sequence(sequence.Folder);
// A server writes only inside its archive (BRIEF §14.2): an export folder chosen on a client means nothing there.
if (options.Host == EncoderHost.Server) export = export with { Folder = null };
var project = (parameters.SettingsJson is { } embedded ? ProjectStore.Parse(embedded) : ProjectStore.Read(sequence, folder)) with { Export = export };
var settingsJson = project.ToJson();
using var names = new OutputNames();
var all = Targets(export, parameters.PresetName);
var resume = RenderCheckpoint.Parse(context.Checkpoint);
var done = resume.Done.ToList();
if (resume is { Pending: { } pending, PendingOutput: { } output })
// A crash after a render row was written but before the checkpoint: that entry is finished.
for (var i = 0; i < all.Count; i++)
{
// A crash after the render row was written but before the checkpoint: that entry is finished.
var recorded = await db.Renders.ListBySequenceAsync(sequence.Id, cancellation).ConfigureAwait(false);
if (recorded.Any(r => r.OutputPath == Stored(paths, output))) done.Add(pending);
else Discard(output);
if (!done.Contains(i) && await db.Renders.GetAsync(RenderId(context.Job.Id, i), cancellation).ConfigureAwait(false) is not null) done.Add(i);
}
var targets = Targets(export, parameters.PresetName).Select((t, i) => (i, t)).Where(t => !done.Contains(t.i)).ToList();
if (resume is { Pending: { } pending, PendingOutput: { } output } && !done.Contains(pending) && names.TryReserve(output))
{
// Unless another render recorded that name since (the output did not exist yet when it chose it).
var recorded = await db.Renders.ListBySequenceAsync(sequence.Id, cancellation).ConfigureAwait(false);
Discard(output, keepOutput: recorded.Any(r => r.OutputPath == Stored(paths, output)));
names.Release(output); // free again for the entry's new attempt
}
var targets = all.Select((t, i) => (i, t)).Where(t => !done.Contains(t.i)).Select(t => (t.i, adapt(t.t))).ToList();
if (targets.Count == 0) return;
var frames = await SequenceFrames.LoadAsync(db, archive, sequence, parameters.UseProxies, cancellation).ConfigureAwait(false);
@@ -52,17 +68,22 @@ internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions opti
{
outcomes = await render.RenderAllAsync(
targets,
(target, setup) => ExportNaming.OutputPath(project.Export, folder.Exports, SequenceRender.NameContext(sequence, target, setup)),
(target, setup) => names.Reserve(taken => ExportNaming.OutputPath(project.Export, folder.Exports, SequenceRender.NameContext(sequence, target, setup), taken)),
(index, path) => context.CheckpointAsync(new RenderCheckpoint(done, index, path).ToJson(), context.Done, context.Total),
async (index, target, result) =>
{
// The output is complete: record it even if the job is being cancelled, so it is never orphaned.
var entity = result.ToEntity(sequence.Id, target.PresetName, settingsJson, options.ProducedBy) with { OutputPath = Stored(paths, result.OutputPath) };
var entity = result.ToEntity(sequence.Id, target.PresetName, settingsJson, options.ProducedBy) with
{
Id = RenderId(context.Job.Id, index),
OutputPath = Stored(paths, result.OutputPath),
};
await db.Renders.InsertAsync(entity, CancellationToken.None).ConfigureAwait(false);
done.Add(index);
await context.CheckpointAsync(new RenderCheckpoint(done, null, null).ToJson(), context.Done, context.Total).ConfigureAwait(false);
context.Log(Loc.L("Export.Log.Rendered", target.PresetName, Path.GetFileName(result.OutputPath)));
foreach (var remark in SequenceRender.Remarks(result)) context.Log(remark);
await options.NotifyAsync(sequence.Id, ProcessingOptions.RenderedChange, CancellationToken.None).ConfigureAwait(false);
},
context.ReportAsync,
cancellation).ConfigureAwait(false);
@@ -74,18 +95,12 @@ internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions opti
}
/// <summary>The job's preset, then every other preset of the batch with its own values.</summary>
internal static List<ExportTarget> Targets(ExportSettings export, string presetName)
{
var main = ExportResolver.Resolve(export);
var targets = new List<ExportTarget> { new(main, presetName) };
foreach (var id in export.Batch.Distinct(StringComparer.OrdinalIgnoreCase))
{
if (id.Equals(main.BasePresetId, StringComparison.OrdinalIgnoreCase)) continue;
var resolved = ExportResolver.Resolve(new ExportSettings { Preset = new Auto<string>().WithManual(id) });
targets.Add(new ExportTarget(resolved, ProcessingJobs.PresetName(resolved)));
}
return targets;
}
internal static List<ExportTarget> Targets(ExportSettings export, string presetName) =>
[
new(ExportResolver.Resolve(export), presetName),
.. ProcessingJobs.BatchPresets(export).Select(id => ExportResolver.Resolve(ProcessingJobs.BatchExport(export, id)))
.Select(resolved => new ExportTarget(resolved, ProcessingJobs.PresetName(resolved))),
];
/// <summary>Archive-relative for outputs inside the archive (like the server's renders), absolute otherwise.</summary>
private static string Stored(ArchivePaths paths, string output)
@@ -94,15 +109,32 @@ internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions opti
return relative.StartsWith("..", StringComparison.Ordinal) || Path.IsPathRooted(relative) ? output : relative;
}
/// <summary>
/// The id of the render row of entry <paramref name="index"/> of a job: the same in every attempt, so a resumed job
/// finds what it recorded (a name-based UUID, version 8).
/// </summary>
internal static Guid RenderId(Guid jobId, int index)
{
Span<byte> name = stackalloc byte[20];
jobId.TryWriteBytes(name, bigEndian: true, out _);
BinaryPrimitives.WriteInt32BigEndian(name[16..], index);
Span<byte> hash = stackalloc byte[SHA256.HashSizeInBytes];
SHA256.HashData(name, hash);
hash[6] = (byte)((hash[6] & 0x0F) | 0x80);
hash[8] = (byte)((hash[8] & 0x3F) | 0x80);
return new Guid(hash[..16], bigEndian: true);
}
/// <summary>
/// Removes what an interrupted attempt left of <paramref name="output"/>: the encoder's hidden temporary file or
/// folder, and an output that was completed but never recorded (it renders again under the same name).
/// </summary>
private static void Discard(string output)
private static void Discard(string output, bool keepOutput)
{
var parent = Path.GetDirectoryName(output);
if (parent is null || !Directory.Exists(parent)) return;
foreach (var leftover in Directory.EnumerateFileSystemEntries(parent, "." + Path.GetFileName(output) + ".*.tmp").Append(output))
var leftovers = Directory.EnumerateFileSystemEntries(parent, "." + Path.GetFileName(output) + ".*.tmp");
foreach (var leftover in keepOutput ? leftovers : leftovers.Append(output))
{
if (Directory.Exists(leftover)) Directory.Delete(leftover, recursive: true);
else if (File.Exists(leftover)) File.Delete(leftover);
+55
View File
@@ -0,0 +1,55 @@
using System.Collections.Concurrent;
namespace Titano.Data.Processing;
/// <summary>
/// The output paths the renders of this process are writing. Encoders write to a hidden temporary file and rename it over
/// the output when they finish, so two renders that picked the same free name (the same preset queued twice) would
/// overwrite each other: a render reserves each name it picks until it ends.
/// </summary>
internal sealed class OutputNames : IDisposable
{
private static readonly ConcurrentDictionary<string, byte> Writing = new(StringComparer.OrdinalIgnoreCase);
private readonly List<string> _mine = [];
/// <summary>A path from <paramref name="pick"/>, given the test for paths other renders are writing, reserved for this render.</summary>
public string Reserve(Func<Func<string, bool>, string> pick)
{
while (true)
{
var path = pick(p => Writing.ContainsKey(Key(p)));
// Another render may have taken the same name since: pick again.
if (TryReserve(path)) return path;
}
}
/// <summary>Reserves <paramref name="path"/> for this render; false when another render is writing it.</summary>
public bool TryReserve(string path)
{
var key = Key(path);
if (!Writing.TryAdd(key, 0)) return false;
lock (_mine) _mine.Add(key);
return true;
}
/// <summary>Gives back a path this render reserved, so it can be picked again.</summary>
public void Release(string path)
{
var key = Key(path);
lock (_mine)
{
if (_mine.Remove(key)) Writing.TryRemove(key, out _);
}
}
public void Dispose()
{
lock (_mine)
{
foreach (var key in _mine) Writing.TryRemove(key, out _);
_mine.Clear();
}
}
private static string Key(string path) => Path.GetFullPath(path);
}
+67 -7
View File
@@ -36,14 +36,65 @@ public static class ProcessingJobs
{
ArgumentNullException.ThrowIfNull(sequence);
ArgumentNullException.ThrowIfNull(export);
var resolved = ExportResolver.Resolve(export);
var name = PresetName(resolved);
var parameters = new RenderJobParameters(name, JsonSerializer.Serialize(export, ProcessingJson.Default.ExportSettings), CodecName(resolved.Codec),
resolved.Width > 0 ? resolved.Width : sourceWidth, resolved.Height > 0 ? resolved.Height : sourceHeight, useProxies, project?.ToJson());
return new ArchiveJobRequest(JobKind.Render, [sequence.Id], $"{sequence.DisplayTitle} → {name}",
var parameters = Parameters(export, sourceWidth, sourceHeight, project?.ToJson(), useProxies);
return new ArchiveJobRequest(JobKind.Render, [sequence.Id], $"{sequence.DisplayTitle} → {parameters.PresetName}",
JsonSerializer.Serialize(parameters, ProtocolJson.Default.RenderJobParameters), JobPriority.User);
}
/// <summary>
/// A posted render job as one job per preset, as <see cref="RenderEach"/> makes them (a render node uploads one file
/// per job): the job itself when it has no batch; otherwise its own preset, then each batch preset with its own values,
/// all with the job's project and proxy choice. <paramref name="sourceWidth"/>×<paramref name="sourceHeight"/> stands in
/// for a batch preset without a fixed size.
/// </summary>
/// <exception cref="InvalidDataException">The preset JSON is not an export section.</exception>
public static IReadOnlyList<RenderJobParameters> Split(RenderJobParameters parameters, int sourceWidth, int sourceHeight)
{
ArgumentNullException.ThrowIfNull(parameters);
var export = ReadExport(parameters.PresetJson);
var batch = BatchPresets(export).ToList();
if (batch.Count == 0) return [parameters];
return
[
parameters with { PresetJson = JsonSerializer.Serialize(export with { Batch = [] }, ProcessingJson.Default.ExportSettings) },
.. batch.Select(id => Parameters(BatchExport(export, id), sourceWidth, sourceHeight, parameters.SettingsJson, parameters.UseProxies)),
];
}
/// <summary>
/// One <see cref="Render"/> job per preset of <paramref name="export"/>: its preset, then each batch preset with its
/// own values. For a server: a render node uploads one file per job, so a batch must not travel as one job.
/// </summary>
public static IReadOnlyList<ArchiveJobRequest> RenderEach(Sequence sequence, ExportSettings export, int sourceWidth, int sourceHeight,
ProjectSettings? project = null, bool useProxies = false)
{
ArgumentNullException.ThrowIfNull(export);
return
[
Render(sequence, export with { Batch = [] }, sourceWidth, sourceHeight, project, useProxies),
.. BatchPresets(export).Select(id => Render(sequence, BatchExport(export, id), sourceWidth, sourceHeight, project, useProxies)),
];
}
/// <summary>The batch presets of an export besides its own, each once (blank entries of a hand-written batch are skipped).</summary>
internal static IEnumerable<string> BatchPresets(ExportSettings export)
{
var main = ExportResolver.Resolve(export).BasePresetId;
return export.Batch.Where(id => !string.IsNullOrWhiteSpace(id)).Distinct(StringComparer.OrdinalIgnoreCase)
.Where(id => !id.Equals(main, StringComparison.OrdinalIgnoreCase));
}
/// <summary>A batch preset rendered with its own values, named and placed like the export it belongs to.</summary>
internal static ExportSettings BatchExport(ExportSettings export, string presetId) =>
new() { Preset = new Auto<string>().WithManual(presetId), NameTemplate = export.NameTemplate, Folder = export.Folder };
private static RenderJobParameters Parameters(ExportSettings export, int sourceWidth, int sourceHeight, string? settingsJson, bool useProxies)
{
var resolved = ExportResolver.Resolve(export);
return new RenderJobParameters(PresetName(resolved), JsonSerializer.Serialize(export, ProcessingJson.Default.ExportSettings), CodecName(resolved.Codec),
resolved.Width > 0 ? resolved.Width : sourceWidth, resolved.Height > 0 ? resolved.Height : sourceHeight, useProxies, settingsJson);
}
/// <summary>Codec name in job parameters and render-node capabilities ("h264", "hevc", "mjpeg", "pngsequence"…).</summary>
public static string CodecName(VideoCodec codec) => codec.ToString().ToLowerInvariant();
@@ -57,11 +108,20 @@ public static class ProcessingJobs
/// <summary>The parameters of a render job and the export they select.</summary>
/// <exception cref="InvalidDataException">The job has no valid render parameters.</exception>
internal static (RenderJobParameters Parameters, ExportSettings Export) ReadRender(string? parametersJson)
{
var parameters = ReadParameters(parametersJson);
return (parameters, ReadExport(parameters.PresetJson));
}
/// <summary>The protocol record of a render job, without reading its export.</summary>
/// <exception cref="InvalidDataException">The job has no valid render parameters.</exception>
internal static RenderJobParameters ReadParameters(string? parametersJson)
{
try
{
if (parametersJson is { Length: > 0 } && JsonSerializer.Deserialize(parametersJson, ProtocolJson.Default.RenderJobParameters) is { } parameters)
return (parameters, ReadExport(parameters.PresetJson));
if (parametersJson is { Length: > 0 } && JsonSerializer.Deserialize(parametersJson, ProtocolJson.Default.RenderJobParameters)
is { PresetName.Length: > 0, PresetJson.Length: > 0, Codec.Length: > 0 } parameters)
return parameters;
}
catch (JsonException ex)
{
@@ -1,10 +1,12 @@
using Titano.Core.Analysis.Deep;
using Titano.Core.Export;
using Titano.Core.Imaging;
using Titano.Core.Model;
using Titano.Core.Render;
using Titano.Core.Video;
using Titano.Core.Video.Managed;
using Titano.Data.Archiving;
using Titano.Protocol;
namespace Titano.Data.Processing;
@@ -15,15 +17,41 @@ namespace Titano.Data.Processing;
/// </summary>
public sealed record ProcessingOptions
{
/// <summary><see cref="SequenceChanged"/> after a render was recorded.</summary>
public const string RenderedChange = "renders";
/// <summary><see cref="SequenceChanged"/> after the advisor changed the project.</summary>
public const string SettingsChange = "settings";
/// <summary>Decoders, lease owner and lease timing for the sidecar and project writes.</summary>
public ArchiveServiceOptions Archive { get; init; } = new();
/// <summary>Encoder providers in priority order.</summary>
public IReadOnlyList<IVideoEncoderProvider> Encoders { get; init; } = [new ManagedEncoderProvider()];
/// <summary>The server delegates platform codecs to render nodes and never runs them itself.</summary>
/// <summary>
/// Whether a render of the given preset (its base preset id) may use hardware encoders (Settings › Rendering); when
/// not, it gets only the software ones. Asked at every render, so a changed preference applies to the next one.
/// </summary>
public Func<string, bool> AllowsHardware { get; init; } = _ => true;
/// <summary>
/// Told after a job changed a sequence: <see cref="RenderedChange"/> (a render was recorded) or
/// <see cref="SettingsChange"/> (the advisor changed Auto values). A server tells its connected clients (BRIEF §14.3).
/// A failure is logged and never fails the job.
/// </summary>
public Func<Guid, string, CancellationToken, Task>? SequenceChanged { get; init; }
/// <summary>The server delegates platform codecs to render nodes (<see cref="AwaitsRenderNode"/>).</summary>
public EncoderHost Host { get; init; } = EncoderHost.Client;
/// <summary>
/// Server: whether a queued render job that needs a platform encoder still waits for a render node (BRIEF §14.7). Once
/// it does not, the server renders it itself, every output only a node could make as MJPEG in AVI at the same size and
/// frame rate, and says so in the job log. Null: such jobs always wait for a node.
/// </summary>
public Func<Job, RenderJobParameters, CancellationToken, Task<bool>>? AwaitsRenderNode { get; init; }
/// <summary>Recorded with every render this host produces (client or server name).</summary>
public string ProducedBy { get; init; } = Environment.MachineName;
@@ -34,6 +62,24 @@ public sealed record ProcessingOptions
public RenderOptions Render { get; init; } = RenderOptions.Default;
/// <summary>Tells <see cref="SequenceChanged"/>; a failure is logged, never passed on to the job.</summary>
internal async Task NotifyAsync(Guid sequenceId, string change, CancellationToken cancellationToken)
{
if (SequenceChanged is null) return;
try
{
await SequenceChanged(sequenceId, change, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
Core.Diagnostics.Log.Warning("processing", $"The {change} change of sequence {sequenceId} could not be announced", ex);
}
}
/// <summary><see cref="Encoders"/> without their hardware encoders, for renders <see cref="AllowsHardware"/> keeps off them.</summary>
internal IReadOnlyList<IVideoEncoderProvider> SoftwareEncoders =>
[.. Encoders.Select(e => e.Capabilities.Any(c => c.Hardware) ? new SoftwareEncoderProvider(e) : e)];
/// <summary>
/// Encoders the advisor may count on: this machine's on a client; none listed on the server (render nodes can
/// produce any codec, so the advisor rules none out).
@@ -1,3 +1,4 @@
using Titano.Core.Export;
using Titano.Core.Model;
using Titano.Data.Archiving;
using Titano.Data.Jobs;
@@ -8,8 +9,9 @@ namespace Titano.Data.Processing;
/// <summary>
/// The analysis and render engine of a host (BRIEF §4.3, §10, §11): job handlers for light analysis, deep analysis and
/// renders over the archive in the index, built with the host's decoders and encoders (<see cref="ProcessingOptions"/>).
/// Register it on the <see cref="JobEngine"/> next to the archive engine; a server engine leaves render jobs to render
/// nodes. Create jobs with <see cref="ProcessingJobs"/>.
/// Register it on the <see cref="JobEngine"/> next to the archive engine. A client renders every job it is given; a
/// server takes the renders its managed encoders produce and leaves the others to render nodes until none can take them
/// (<see cref="ProcessingOptions.AwaitsRenderNode"/>). Create jobs with <see cref="ProcessingJobs"/>.
/// </summary>
public sealed class ProcessingService : IJobHandlerProvider
{
@@ -28,10 +30,14 @@ public sealed class ProcessingService : IJobHandlerProvider
public ProcessingOptions Options { get; }
/// <summary>Handlers for <see cref="JobKind.LightAnalyse"/>, <see cref="JobKind.DeepAnalyse"/> and <see cref="JobKind.Render"/>.</summary>
public IReadOnlyList<IJobHandler> CreateJobHandlers() =>
[
new AnalyseJobHandler(_db, _analyser, JobKind.LightAnalyse),
new AnalyseJobHandler(_db, _analyser, JobKind.DeepAnalyse),
new RenderJobHandler(_db, Options),
];
public IReadOnlyList<IJobHandler> CreateJobHandlers()
{
var render = new RenderJobHandler(_db, Options);
return
[
new AnalyseJobHandler(_db, _analyser, JobKind.LightAnalyse),
new AnalyseJobHandler(_db, _analyser, JobKind.DeepAnalyse),
Options.Host == EncoderHost.Server ? new ManagedRenderJobHandler(render, Options) : render,
];
}
}
+115 -40
View File
@@ -36,16 +36,23 @@ public sealed record RenderNodeOptions
/// <summary>Concurrent frame downloads.</summary>
public int Downloads { get; init; } = 4;
/// <summary>Retries of a frame download cut by the network or a busy server, each resuming the partial file.</summary>
public int DownloadRetries { get; init; } = 5;
/// <summary>Wait before the first retry; it doubles with each further one.</summary>
public TimeSpan RetryDelay { get; init; } = TimeSpan.FromSeconds(1);
}
/// <summary>
/// "Offer this PC as render node" (BRIEF §14.7): registers this machine's single-file encoders with the server,
/// heart-beats, claims one render job at a time that it can encode, downloads the frames it needs (originals
/// hash-verified into a content-addressed cache, or proxies when the job asks), renders the job's preset with the
/// host's encoders and uploads the output, which the server files as a render of the sequence. Progress goes to the
/// server; a job cancelled or reassigned there stops here; a failure is reported with its reason. Stopping abandons
/// the job in flight without reporting it, so the server requeues it once the heartbeats stop. Image sequences are
/// not offered: the protocol uploads one file per job.
/// hash-verified into a content-addressed cache, or proxies when the job asks; a dropped download resumes), renders the
/// job's preset with the host's encoders and uploads the output, which the server files as a render of the sequence.
/// Progress and render remarks go to the server; a job cancelled or reassigned there stops here; a failure is reported
/// with its reason. Stopping abandons the job in flight without reporting it: the server requeues it when the node
/// registers again or its heartbeats stop. Image sequences are not offered and batches are refused: the protocol uploads
/// one file per job.
/// </summary>
public sealed class RenderNodeClient : IAsyncDisposable
{
@@ -65,14 +72,22 @@ public sealed class RenderNodeClient : IAsyncDisposable
_options = options;
}
/// <summary>The encoders this node offers: every single-file capability of the host's providers.</summary>
/// <summary>
/// The encoders this node offers, each with its largest output: every single-file capability of the host's
/// providers, hardware ones only when the user lets renders use them (<see cref="ProcessingOptions.AllowsHardware"/>).
/// </summary>
public IReadOnlyList<NodeEncoder> Encoders =>
[
.. _processing.Encoders.SelectMany(p => p.Capabilities)
.Where(c => VideoCodecInfo.DefaultContainer(c.Codec) != ContainerFormat.ImageSequence)
.Select(c => new NodeEncoder(ProcessingJobs.CodecName(c.Codec), c.Name, c.Hardware, c.SupportsTenBit)),
.Where(c => VideoCodecInfo.DefaultContainer(c.Codec) != ContainerFormat.ImageSequence
&& (!c.Hardware || _processing.AllowsHardware(ExportResolver.CustomId)))
.Select(c => new NodeEncoder(ProcessingJobs.CodecName(c.Codec), c.Name, c.Hardware, c.SupportsTenBit, c.MaxWidth, c.MaxHeight)),
];
/// <summary>Completes when the node has stopped: asked to, or refused by the server (signed out, no render-node right,
/// changed certificate), which only the user can change.</summary>
public Task Completion => _running;
/// <summary>Starts registering, heart-beating and claiming in the background.</summary>
public void Start() => _running = Task.Run(() => RunAsync(_stopping.Token));
@@ -92,9 +107,10 @@ public sealed class RenderNodeClient : IAsyncDisposable
/// <summary>Registers this node (again) and returns its id.</summary>
public async Task<Guid> RegisterAsync(CancellationToken cancellationToken)
{
var capabilities = _processing.Encoders.SelectMany(p => p.Capabilities).ToList();
var request = new RegisterNodeRequest(_options.ClientName, Encoders, capabilities.Count > 0 ? capabilities.Max(c => c.MaxWidth) : 0,
capabilities.Count > 0 ? capabilities.Max(c => c.MaxHeight) : 0);
// Each encoder carries its own limit; the node-wide one (for servers that read only that) is the largest offered.
var encoders = Encoders;
var request = new RegisterNodeRequest(_options.ClientName, encoders, encoders.Select(e => e.MaxWidth).DefaultIfEmpty().Max(),
encoders.Select(e => e.MaxHeight).DefaultIfEmpty().Max());
var node = await _client.RegisterNodeAsync(request, cancellationToken).ConfigureAwait(false);
_nodeId = node.Id;
return node.Id;
@@ -148,20 +164,20 @@ public sealed class RenderNodeClient : IAsyncDisposable
{
break;
}
catch (TitanoApiException ex) when (ex.Status is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
catch (Exception ex) when (ex is TitanoApiException { Status: HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden } or UntrustedCertificateException)
{
// Signed out, or the account lacks the render-node right: nothing to retry until the user acts.
// Signed out, no render-node right, or a changed certificate: nothing to retry until the user acts.
Log.Warning(LogCategory, "The server refused this render node", ex);
break;
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound && _nodeId is not null)
{
_nodeId = null; // removed on the server: register again
_nodeId = null; // removed on the server: register again at once
continue;
}
catch (Exception ex)
{
// Server unreachable or busy: the node keeps trying until it is stopped.
// Server unreachable, busy or without the render-node routes: the node keeps trying until it is stopped.
Log.Warning(LogCategory, "Render node cycle failed; retrying", ex);
}
try
@@ -193,8 +209,9 @@ public sealed class RenderNodeClient : IAsyncDisposable
{
_nodeId = null;
}
catch (Exception ex) when (ex is TitanoApiException or HttpRequestException or IOException or UntrustedCertificateException)
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
{
// Unreachable or refusing: the claim loop decides whether to go on; beating must not stop the node.
Log.Warning(LogCategory, "Heartbeat failed", ex);
}
}
@@ -210,6 +227,8 @@ public sealed class RenderNodeClient : IAsyncDisposable
var resolved = ExportResolver.Resolve(export);
var target = new ExportTarget(resolved, ProcessingJobs.PresetName(resolved));
if (target.Export.Container == ContainerFormat.ImageSequence) throw new InvalidOperationException(Loc.L("Errors.Render.NodeSequence"));
// One output per job: a server splits batches into one job per preset when they are posted.
if (ProcessingJobs.BatchPresets(export).Any()) throw new InvalidOperationException(Loc.L("Errors.Render.NodeBatch"));
var project = ProjectStore.Parse(claimed.SettingsJson) with { Export = export };
var sequence = ToSequence(await _client.GetSequenceAsync(claimed.SequenceId, cancellationToken).ConfigureAwait(false));
@@ -224,7 +243,12 @@ public sealed class RenderNodeClient : IAsyncDisposable
[(0, target)],
(t, setup) => ExportNaming.OutputPath(work, project.Export.NameTemplate, SequenceRender.NameContext(sequence, t, setup)),
(_, _) => ValueTask.CompletedTask,
(_, t, result) => new ValueTask(UploadAsync(reporter.NodeId, claimed.Job.Id, t, result, cancellationToken)),
async (_, t, result) =>
{
// Remarks first: completing the upload ends the job on the server.
foreach (var remark in SequenceRender.Remarks(result)) await reporter.LogAsync(remark).ConfigureAwait(false);
await UploadAsync(reporter.NodeId, claimed.Job.Id, t, result, cancellationToken).ConfigureAwait(false);
},
reporter.ReportAsync,
cancellationToken).ConfigureAwait(false);
}
@@ -257,34 +281,44 @@ public sealed class RenderNodeClient : IAsyncDisposable
/// <summary>
/// The files of the job's frames: originals verified against their SHA-256 into the content-addressed cache (reused
/// across jobs), or proxies into the job folder when the job asks for them and the server has them.
/// across jobs, fetched once per content), or proxies into the job folder when the job asks for them and the server
/// has them.
/// </summary>
private async Task<Dictionary<Guid, string>> DownloadAsync(ClaimedJob claimed, string work, NodeReporter reporter, CancellationToken cancellationToken)
{
var files = new Dictionary<Guid, string>();
var done = 0;
await reporter.ReportAsync(0, claimed.Frames.Count, Loc.L("Export.Job.Downloading")).ConfigureAwait(false);
await Parallel.ForEachAsync(claimed.Frames, new ParallelOptions { MaxDegreeOfParallelism = _options.Downloads, CancellationToken = cancellationToken },
async (frame, ct) =>
var total = claimed.Frames.Count;
await reporter.ReportAsync(0, total, Loc.L("Export.Job.Downloading")).ConfigureAwait(false);
var downloads = claimed.Frames.GroupBy(f => claimed.UseProxies && f.HasProxy ? f.Id.ToString("N") : f.Sha256.ToLowerInvariant()).ToList();
await Parallel.ForEachAsync(downloads, new ParallelOptions { MaxDegreeOfParallelism = _options.Downloads, CancellationToken = cancellationToken },
async (frames, ct) =>
{
var frame = frames.First();
var path = claimed.UseProxies && frame.HasProxy
? await DownloadProxyAsync(frame, work, ct).ConfigureAwait(false)
: await DownloadOriginalAsync(frame, ct).ConfigureAwait(false);
lock (files) files[frame.Id] = path;
await reporter.ReportAsync(Interlocked.Increment(ref done), claimed.Frames.Count, null).ConfigureAwait(false);
lock (files)
{
foreach (var f in frames) files[f.Id] = path;
}
await reporter.ReportAsync(Interlocked.Add(ref done, frames.Count()), total, null).ConfigureAwait(false);
}).ConfigureAwait(false);
return files;
}
/// <summary>A proxy into the job folder (regenerable, so not cached); the original when the server has none for the frame.</summary>
/// <summary>
/// A proxy into the job folder (regenerable, so neither cached nor hashed: the server keeps no hash of it, and a retry
/// fetches it whole, since a proxy rebuilt meanwhile must not be resumed from the old one); the original when the server
/// has none for the frame.
/// </summary>
private async Task<string> DownloadProxyAsync(ManifestFrame frame, string work, CancellationToken cancellationToken)
{
var path = Path.Combine(work, "proxies", frame.Id.ToString("N") + ".jpg");
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
try
{
await using (var file = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
await _client.DownloadFrameAsync(frame.Id, "proxy", file, null, cancellationToken).ConfigureAwait(false);
await FetchAsync(frame, "proxy", path, resume: false, cancellationToken).ConfigureAwait(false);
return path;
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
@@ -309,8 +343,8 @@ public sealed class RenderNodeClient : IAsyncDisposable
var part = path + ".part";
for (var attempt = 1; ; attempt++)
{
await using (var file = new FileStream(part, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
await _client.DownloadFrameAsync(frame.Id, "original", file, null, cancellationToken).ConfigureAwait(false);
// A part as long as the file was complete when the last attempt stopped: only its hash is left to check.
if (!File.Exists(part) || new FileInfo(part).Length < frame.Size) await FetchAsync(frame, "original", part, resume: true, cancellationToken).ConfigureAwait(false);
if (await TitanoClient.HashFileAsync(part, cancellationToken).ConfigureAwait(false) == sha)
{
File.Move(part, path, overwrite: true);
@@ -321,6 +355,34 @@ public sealed class RenderNodeClient : IAsyncDisposable
}
}
/// <summary>
/// Fetches a frame resource into <paramref name="path"/>. A dropped connection or a busy server is retried (up to
/// <see cref="RenderNodeOptions.DownloadRetries"/> times, the wait doubling from <see cref="RenderNodeOptions.RetryDelay"/>);
/// with <paramref name="resume"/> (a download its hash verifies) each attempt appends to what the last one left,
/// otherwise it starts over.
/// </summary>
private async Task FetchAsync(ManifestFrame frame, string kind, string path, bool resume, CancellationToken cancellationToken)
{
for (var attempt = 0; ; attempt++)
{
try
{
await using var file = new FileStream(path, resume ? FileMode.OpenOrCreate : FileMode.Create, FileAccess.ReadWrite, FileShare.None);
await _client.DownloadFrameAsync(frame.Id, kind, file, null, cancellationToken).ConfigureAwait(false);
return;
}
catch (Exception ex) when (attempt < _options.DownloadRetries && !cancellationToken.IsCancellationRequested && IsTransient(ex))
{
Log.Info(LogCategory, $"Download of {frame.FileName} ({kind}) interrupted, resuming: {ex.Message}");
await Task.Delay(_options.RetryDelay * (1 << attempt), cancellationToken).ConfigureAwait(false);
}
}
}
/// <summary>Failures a later attempt can get past: the network, a busy server, a timeout (not a cancellation of ours).</summary>
private static bool IsTransient(Exception ex) =>
ex is HttpRequestException or IOException or OperationCanceledException or TitanoApiException { IsTransient: true };
private async Task ReportFailureAsync(Guid nodeId, Guid jobId, string error, CancellationToken cancellationToken)
{
try
@@ -406,7 +468,7 @@ public sealed class RenderNodeClient : IAsyncDisposable
/// <summary>
/// Progress of the job in flight to the server, at most every interval (and at the end). A refusal (409) means the
/// job was cancelled or given to another node: <see cref="Lost"/> is set and the job's token cancelled.
/// job was cancelled or given to another node: the job's token is cancelled.
/// </summary>
private sealed class NodeReporter(TitanoClient client, Guid nodeId, Guid jobId, TimeSpan interval, CancellationTokenSource job)
{
@@ -414,28 +476,41 @@ public sealed class RenderNodeClient : IAsyncDisposable
private readonly SemaphoreSlim _gate = new(1, 1);
private TimeSpan _last = TimeSpan.MinValue;
private long _lastDone;
private long _lastTotal;
private string? _lastMessage;
public Guid NodeId => nodeId;
public bool Lost { get; private set; }
/// <summary>Progress, sent at most every interval; a stage message is sent when it changes.</summary>
public ValueTask ReportAsync(long done, long total, string? message) => SendAsync(done, total, message, remark: false);
public async ValueTask ReportAsync(long done, long total, string? message)
/// <summary>A line for the job's log on the server, sent with the progress last reported.</summary>
public ValueTask LogAsync(string line) => SendAsync(0, 0, line, remark: true);
private async ValueTask SendAsync(long done, long total, string? message, bool remark)
{
await _gate.WaitAsync(CancellationToken.None).ConfigureAwait(false);
try
{
var now = _clock.Elapsed;
var line = message is not null && message != _lastMessage ? message : null;
if (line is null && done < total && now - _last < interval) return;
double? rate = _last == TimeSpan.MinValue || done < _lastDone ? null : (done - _lastDone) / double.Max((now - _last).TotalSeconds, 1e-3);
(_last, _lastDone) = (now, done);
if (line is not null) _lastMessage = line;
await client.ReportNodeProgressAsync(nodeId, jobId, new NodeProgress(done, total, rate, line), job.Token).ConfigureAwait(false);
NodeProgress progress;
if (remark)
{
progress = new NodeProgress(_lastDone, _lastTotal, null, message);
}
else
{
var now = _clock.Elapsed;
var line = message is not null && message != _lastMessage ? message : null;
if (line is null && done < total && now - _last < interval) return;
double? rate = _last == TimeSpan.MinValue || done < _lastDone ? null : (done - _lastDone) / double.Max((now - _last).TotalSeconds, 1e-3);
(_last, _lastDone, _lastTotal) = (now, done, total);
if (line is not null) _lastMessage = line;
progress = new NodeProgress(done, total, rate, line);
}
await client.ReportNodeProgressAsync(nodeId, jobId, progress, job.Token).ConfigureAwait(false);
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict)
{
Lost = true;
await job.CancelAsync().ConfigureAwait(false);
}
catch (Exception ex) when (ex is TitanoApiException or HttpRequestException or IOException)
+23 -14
View File
@@ -44,13 +44,14 @@ internal sealed class SequenceAnalyser(TitanoDatabase db, ProcessingOptions opti
? await AnalyseDeepAsync(frames, metadata, folder, progress, cancellationToken).ConfigureAwait(false)
: ReadReport(folder, frames.Count);
var context = SequenceContext.FromFrames(frames.Frames, options.AdvisorCodecs);
var advice = Advisor.Recommend(light, report, context);
var warnings = advice.Findings.Count(f => f.Severity >= FindingSeverity.Warning);
bool changed, unreadable = false;
try
{
changed = await projects.UpdateAsync(paths, sequence, settings => Advisor.Apply(settings, advice), cancellationToken).ConfigureAwait(false);
// The frame rate follows the user's "fit to N seconds" when one is set (BRIEF §10.3).
changed = await projects.UpdateAsync(paths, sequence,
settings => Advisor.Apply(settings, Advisor.Recommend(light, report, context with { TargetDurationSeconds = settings.Timing.FitToSeconds })),
cancellationToken).ConfigureAwait(false);
}
catch (InvalidDataException ex)
{
@@ -58,18 +59,26 @@ internal sealed class SequenceAnalyser(TitanoDatabase db, ProcessingOptions opti
(changed, unreadable) = (false, true);
}
var set = SequenceStatus.AnalyzedLight | (report is null ? SequenceStatus.None : SequenceStatus.AnalyzedDeep)
| (warnings > 0 ? SequenceStatus.HasWarnings : SequenceStatus.None);
// Without a current report (none, or made before frames were added) the deep status no longer holds.
var clear = (report is null ? SequenceStatus.AnalyzedDeep : SequenceStatus.None) | (warnings > 0 ? SequenceStatus.None : SequenceStatus.HasWarnings);
var summary = deep && report is not null ? AnalysisSummary.From(report).ToJson() : null;
await writer.UpdateAsync(paths, sequence.Id, sequence.Folder, m =>
if (changed) await options.NotifyAsync(sequence.Id, ProcessingOptions.SettingsChange, cancellationToken).ConfigureAwait(false);
int warnings;
// Under the sequence lock, which a deep pass of the same sequence also takes to record its report: a light pass
// then either sees that report or runs before it is recorded, and never clears what it recorded.
await using (await writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
{
var status = (m.Status | set) & ~clear;
return status == m.Status ? null : m with { Status = status, UpdatedAt = DateTimeOffset.UtcNow };
}, cancellationToken).ConfigureAwait(false);
await db.Sequences.RecordAnalysisAsync(sequence.Id, set, clear, warnings, summary, cancellationToken).ConfigureAwait(false);
await indexer.RecordStampsAsync(archive, folder, sequence.Id, cancellationToken).ConfigureAwait(false);
report ??= ReadReport(folder, frames.Count);
warnings = Advisor.Recommend(light, report, context).Findings.Count(f => f.Severity >= FindingSeverity.Warning);
var set = SequenceStatus.AnalyzedLight | (report is null ? SequenceStatus.None : SequenceStatus.AnalyzedDeep)
| (warnings > 0 ? SequenceStatus.HasWarnings : SequenceStatus.None);
// Without a current report (none, or made before frames were added) the deep status no longer holds.
var clear = (report is null ? SequenceStatus.AnalyzedDeep : SequenceStatus.None) | (warnings > 0 ? SequenceStatus.None : SequenceStatus.HasWarnings);
var manifest = SequenceWriter.ReadLocked(folder, sequence.Id);
var status = (manifest.Status | set) & ~clear;
if (status != manifest.Status) ManifestStore.WriteSequence(folder.ManifestPath, manifest with { Status = status, UpdatedAt = DateTimeOffset.UtcNow });
var summary = deep && report is not null ? AnalysisSummary.From(report).ToJson() : null;
await db.Sequences.RecordAnalysisAsync(sequence.Id, set, clear, warnings, summary, cancellationToken).ConfigureAwait(false);
await indexer.RecordStampsAsync(archive, folder, sequence.Id, cancellationToken).ConfigureAwait(false);
}
var presets = deep ? SequencePresets.Generate(light, report, context) : [];
return new AnalysisOutcome(sequence, frames.Count, warnings, changed, unreadable, presets);
+16 -5
View File
@@ -19,12 +19,14 @@ internal sealed record TargetOutcome(ExportTarget Target, RenderResult? Result,
/// frames that cannot be rendered excluded, and the pipeline with the host's encoders. Targets share one preparation
/// pass; each is named once its encoder (and so its codec and size) is known, and failures of one target do not stop
/// the others. Outputs are written by the encoder sessions to temporary names and renamed on completion, so a
/// cancelled or failed target leaves nothing behind.
/// cancelled or failed target leaves nothing behind. A target gets the hardware encoders only when the user allows them
/// for its preset (<see cref="ProcessingOptions.AllowsHardware"/>).
/// </summary>
internal sealed class SequenceRender : IAsyncDisposable
{
private readonly SequenceFrameSource _source;
private readonly RenderPipeline _pipeline;
private readonly ProcessingOptions _processing;
private readonly Dictionary<bool, RenderPipeline> _pipelines = [];
private readonly RenderOptions _options;
/// <param name="analysis">The sequence's deep report, when current: its luminance spares the preparation a decode pass.</param>
@@ -32,7 +34,7 @@ internal sealed class SequenceRender : IAsyncDisposable
{
var metadata = frames.LightFrames();
_source = new SequenceFrameSource(frames, metadata, options.Archive.Decoder, options.FrameWindow);
_pipeline = new RenderPipeline(options.Encoders, options.Host);
_processing = options;
_options = options.Render;
Input = new RenderInput
{
@@ -46,7 +48,7 @@ internal sealed class SequenceRender : IAsyncDisposable
public RenderInput Input { get; }
/// <summary>Encoder, geometry and plan of an export before its output is named.</summary>
public RenderSetup Setup(ResolvedExport export) => _pipeline.Setup(Input, new RenderTarget(export, ExportNaming.FallbackName), _options);
public RenderSetup Setup(ResolvedExport export) => Pipeline(export).Setup(Input, new RenderTarget(export, ExportNaming.FallbackName), _options);
/// <summary>
/// Prepares the sequence once and renders every target. <paramref name="name"/> gives the output path of a target
@@ -97,7 +99,7 @@ internal sealed class SequenceRender : IAsyncDisposable
await starting(index, output).ConfigureAwait(false);
try
{
var result = await _pipeline.RenderAsync(Input, corrections, new RenderTarget(target.Export, output), _options,
var result = await Pipeline(target.Export).RenderAsync(Input, corrections, new RenderTarget(target.Export, output), _options,
Stage(chain, done, setup.Plan.Frames.Count, total, target.PresetName), cancellationToken).ConfigureAwait(false);
await chain.FlushAsync().ConfigureAwait(false);
await finished(index, target, result).ConfigureAwait(false);
@@ -134,6 +136,15 @@ internal sealed class SequenceRender : IAsyncDisposable
public ValueTask DisposeAsync() => _source.DisposeAsync();
/// <summary>The pipeline with the encoders <paramref name="export"/> may use.</summary>
private RenderPipeline Pipeline(ResolvedExport export)
{
var hardware = _processing.AllowsHardware(export.BasePresetId);
if (!_pipelines.TryGetValue(hardware, out var pipeline))
_pipelines[hardware] = pipeline = new RenderPipeline(hardware ? _processing.Encoders : _processing.SoftwareEncoders, _processing.Host);
return pipeline;
}
private static string Reason(RenderSetup setup)
{
if (setup.Plan.Frames.Count == 0) return Loc.L("Export.Render.NoFrames");
@@ -0,0 +1,30 @@
using Titano.Core.Video;
namespace Titano.Data.Processing;
/// <summary>
/// The software encoders of a provider, for renders the user keeps off the GPU (Settings › Rendering): hardware
/// capabilities are hidden, so the encoder selector falls back as on a PC without them (HEVC → software H.264), and an
/// encode opens the software encoder by name, ignoring a hardware one named in the export.
/// </summary>
internal sealed class SoftwareEncoderProvider(IVideoEncoderProvider inner) : IVideoEncoderProvider
{
public string Name => inner.Name;
public IReadOnlyList<EncoderCapability> Capabilities { get; } = [.. inner.Capabilities.Where(c => !c.Hardware)];
public bool CanEncode(EncodeSettings settings) => Software(settings) is not null;
public IVideoEncoderSession Open(EncodeSettings settings) =>
inner.Open(Software(settings) ?? throw new NotSupportedException($"No software encoder of {inner.Name} accepts {settings.Codec} {settings.Width}×{settings.Height}"));
/// <summary>The settings naming the first software encoder that accepts them; null when none does.</summary>
private EncodeSettings? Software(EncodeSettings settings)
{
var named = settings.EncoderName is { } name && Capabilities.Any(c => c.Name == name);
return Capabilities
.Where(c => c.Codec == settings.Codec && (!named || c.Name == settings.EncoderName))
.Select(c => settings with { EncoderName = c.Name, PreferHardware = false })
.FirstOrDefault(inner.CanEncode);
}
}
+10 -6
View File
@@ -39,9 +39,7 @@ public sealed class JobRepository
/// </summary>
public Task<Job?> ClaimNextAsync(string workerId, IReadOnlyCollection<JobKind>? kinds = null, CancellationToken cancellationToken = default)
{
var kindFilter = kinds is { Count: > 0 }
? " AND kind IN (" + string.Join(", ", kinds.Select(k => ((int)k).ToString(CultureInfo.InvariantCulture))) + ")"
: string.Empty;
var kindFilter = kinds is { Count: > 0 } ? $" AND kind IN ({KindList(kinds)})" : string.Empty;
var pick = $"SELECT id FROM jobs WHERE state = {(int)JobState.Queued}{kindFilter} ORDER BY priority DESC, created, id LIMIT 1";
var claim = $"UPDATE jobs SET state = {(int)JobState.Running}, node_id = $1, started = $2, finished = NULL, error = NULL, attempts = attempts + 1";
DbParam[] args = [workerId, DateTimeOffset.UtcNow];
@@ -130,9 +128,13 @@ public sealed class JobRepository
/// <summary>Queued jobs of one kind in claim order (highest priority, then oldest).</summary>
public Task<IReadOnlyList<Job>> ListQueuedAsync(JobKind kind, int limit = 50, CancellationToken cancellationToken = default) =>
_db.ListAsync(
$"SELECT {Columns} FROM jobs WHERE state = {(int)JobState.Queued} AND kind = $1 ORDER BY priority DESC, created, id LIMIT $2",
[(int)kind, Cursor.ClampLimit(limit)], Map, cancellationToken);
ListQueuedAsync([kind], limit, cancellationToken);
/// <summary>Queued jobs of the given kinds in claim order (highest priority, then oldest).</summary>
public Task<IReadOnlyList<Job>> ListQueuedAsync(IReadOnlyCollection<JobKind> kinds, int limit = 50, CancellationToken cancellationToken = default) =>
kinds.Count == 0 ? Task.FromResult<IReadOnlyList<Job>>([]) : _db.ListAsync(
$"SELECT {Columns} FROM jobs WHERE state = {(int)JobState.Queued} AND kind IN ({KindList(kinds)}) ORDER BY priority DESC, created, id LIMIT $1",
[Cursor.ClampLimit(limit)], Map, cancellationToken);
/// <summary>Running jobs claimed by <paramref name="nodeId"/>.</summary>
public Task<IReadOnlyList<Job>> ListRunningByNodeAsync(string nodeId, CancellationToken cancellationToken = default) =>
@@ -193,6 +195,8 @@ public sealed class JobRepository
return new JobCounts(row.GetInt32(0), row.GetInt32(1), row.GetInt32(2), row.GetInt32(3), row.GetInt32(4));
}, cancellationToken);
private static string KindList(IEnumerable<JobKind> kinds) => string.Join(", ", kinds.Select(k => ((int)k).ToString(CultureInfo.InvariantCulture)));
private static Job Map(DbRow r) => new()
{
Id = r.GetGuid(0),
+9 -2
View File
@@ -22,10 +22,17 @@ public sealed record JobDto(
/// <summary><c>POST /api/v1/jobs</c>: kind = render, deep-analyse, proxies, thumbs, verify, scan, rebuild, maintenance…</summary>
public sealed record CreateJobRequest(string Kind, IReadOnlyList<Guid> Target, string? ParametersJson);
/// <summary><c>POST /api/v1/nodes/register</c>: a client offers its GPU encoders (BRIEF §14.7).</summary>
/// <summary>
/// <c>POST /api/v1/nodes/register</c>: a client offers its GPU encoders (BRIEF §14.7). <see cref="MaxWidth"/> ×
/// <see cref="MaxHeight"/> is the largest output of any of them, for encoders that announce no limit of their own.
/// </summary>
public sealed record RegisterNodeRequest(string ClientName, IReadOnlyList<NodeEncoder> Encoders, int MaxWidth, int MaxHeight);
public sealed record NodeEncoder(string Codec, string Name, bool Hardware, bool TenBit);
/// <summary>
/// One encoder of a render node. <see cref="MaxWidth"/> × <see cref="MaxHeight"/> is its largest output (0 = not announced:
/// the node's own limit applies), so jobs go only to a node with an encoder of their codec that takes their size.
/// </summary>
public sealed record NodeEncoder(string Codec, string Name, bool Hardware, bool TenBit, int MaxWidth = 0, int MaxHeight = 0);
public sealed record RenderNodeDto(Guid Id, string ClientName, string Username, IReadOnlyList<NodeEncoder> Encoders, DateTimeOffset LastHeartbeat, string State);
+32 -6
View File
@@ -1,6 +1,7 @@
using System.Text.Json;
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Processing;
using Titano.Protocol;
using Titano.Server.Jobs;
using Titano.Server.Security;
@@ -9,8 +10,8 @@ using Titano.Server.Storage;
namespace Titano.Server.Api;
/// <summary>
/// <c>/api/v1/jobs</c> (BRIEF §14.6): queue and history, creation, cancel, pause, resume, retry and priority. Changes
/// reach WebSocket clients as <c>jobState</c> and <c>jobProgress</c> events.
/// <c>/api/v1/jobs</c> (BRIEF §14.6): queue and history, creation (a render batch becomes one job per preset), cancel,
/// pause, resume, retry and priority. Changes reach WebSocket clients as <c>jobState</c> and <c>jobProgress</c> events.
/// </summary>
public static class JobEndpoints
{
@@ -88,21 +89,46 @@ public static class JobEndpoints
targets = ids;
label = titles.Count == 1 ? titles[0] : string.Join(", ", titles.Take(3)) + (titles.Count > 3 ? " …" : string.Empty);
}
List<(string Label, string? Parameters)> queue = [(label, request.ParametersJson)];
if (kind == JobKind.Render)
{
if (ParseRender(request.ParametersJson) is not { } render) return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson");
label = $"{label} → {render.PresetName}";
// A batch becomes one job per preset: a render node uploads one file per job (BRIEF §14.7).
IReadOnlyList<RenderJobParameters> each;
try
{
var (width, height) = await SourceSizeAsync(db, targets[0], render, ct);
each = ProcessingJobs.Split(render, width, height);
}
catch (InvalidDataException)
{
return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson");
}
queue = each.Count == 1
? [($"{label} → {render.PresetName}", request.ParametersJson)]
: [.. each.Select(p => ($"{label} → {p.PresetName}", (string?)JsonSerializer.Serialize(p, ProtocolJson.Default.RenderJobParameters)))];
}
else if (request.ParametersJson is not null && !IsJsonObject(request.ParametersJson))
{
return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson");
}
var job = await host.Engine.EnqueueAsync(kind, targets, label, request.ParametersJson, JobPriority.User, caller.Id, ct);
await audit.WriteAsync(caller, context, "job_created", "job", job.Id.ToString(), $"{JobWire.Kind(kind)} · {label}");
return Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted);
Job? first = null;
foreach (var (jobLabel, parameters) in queue)
{
var job = await host.Engine.EnqueueAsync(kind, targets, jobLabel, parameters, JobPriority.User, caller.Id, ct);
await audit.WriteAsync(caller, context, "job_created", "job", job.Id.ToString(), $"{JobWire.Kind(kind)} · {jobLabel}");
first ??= job;
}
return Results.Json(Dto.Job(first!), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted);
}
/// <summary>The oriented size of the sequence's first frame (what a preset without a fixed size renders at), else the job's size.</summary>
private static async Task<(int Width, int Height)> SourceSizeAsync(TitanoDatabase db, Guid sequenceId, RenderJobParameters render, CancellationToken ct) =>
(await db.Frames.ListBySequenceAsync(sequenceId, limit: 1, cancellationToken: ct)).FirstOrDefault() is { Width: > 0, Height: > 0 } frame
? frame.Orientation is >= 5 and <= 8 ? (frame.Height, frame.Width) : (frame.Width, frame.Height)
: (render.Width, render.Height);
private static async Task<IResult> PriorityAsync(HttpContext context, Caller caller, Guid id, JobPriorityRequest request, TitanoDatabase db, JobEngineHost host)
{
if (!JobWire.TryParsePriority(request.Priority, out var priority)) return ApiErrors.BadRequest(context, "invalid_priority");
+5 -3
View File
@@ -12,8 +12,9 @@ namespace Titano.Server.Jobs;
/// <summary>
/// Hosts the server's <see cref="JobEngine"/> (BRIEF §14.6) with the <see cref="IJobHandler"/>s registered in DI (directly or
/// through <see cref="IJobHandlerProvider"/>s) and
/// relays its state changes and progress as WebSocket events. Render jobs are never run here: render nodes claim them
/// (BRIEF §14.7). On shutdown running jobs stay marked running and are requeued from their checkpoints at the next start.
/// relays its state changes and progress as WebSocket events. Render jobs run here only when the registered render
/// handler accepts them (<see cref="ISelectiveJobHandler"/>: managed formats, and MP4 jobs no render node can take);
/// render nodes claim the others (BRIEF §14.5, §14.7). On shutdown running jobs stay marked running and are requeued from their checkpoints at the next start.
/// </summary>
public sealed class JobEngineHost : IHostedService
{
@@ -30,7 +31,8 @@ public sealed class JobEngineHost : IHostedService
{
_db = db;
_events = events;
var local = handlers.Concat(providers.SelectMany(p => p.CreateJobHandlers())).Where(h => h.Kind != JobKind.Render).ToList();
// A render handler must be selective: a plain one would take the jobs that need a render node's encoder.
var local = handlers.Concat(providers.SelectMany(p => p.CreateJobHandlers())).Where(h => h.Kind != JobKind.Render || h is ISelectiveJobHandler).ToList();
_kinds = [.. local.Select(h => h.Kind)];
// Without handlers no worker starts: an engine with an empty kind list would claim every kind.
Workers = _kinds.Count == 0 ? 0 : options.Workers;
@@ -0,0 +1,42 @@
using System.Diagnostics;
using Titano.Core.Model;
using Titano.Data;
using Titano.Protocol;
using Titano.Server.Api;
using Titano.Server.Configuration;
namespace Titano.Server.Jobs;
/// <summary>
/// Whether a queued render job that needs a platform encoder still waits for a render node (BRIEF §14.7); once it does
/// not, the server's own engine renders it in a managed format. A job waits at least as long as a node may stay silent
/// (<see cref="ServerOptions.NodeTimeoutSeconds"/>), so a node that is restarting or reconnecting takes it back, and
/// then as long as an online node can encode its codec at its size. The server's render handler asks for every queued
/// job it examines, so the online nodes are read at most once a second.
/// </summary>
public sealed class RenderNodeAvailability(TitanoDatabase db, ServerOptions options, TimeProvider time)
{
private static readonly TimeSpan SnapshotAge = TimeSpan.FromSeconds(1);
private Snapshot? _snapshot;
public async Task<bool> AwaitsNodeAsync(Job job, RenderJobParameters parameters, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(job);
ArgumentNullException.ThrowIfNull(parameters);
var now = time.GetUtcNow();
var timeout = TimeSpan.FromSeconds(options.NodeTimeoutSeconds);
if (now - job.Created < timeout) return true;
var snapshot = Volatile.Read(ref _snapshot);
if (snapshot is null || Stopwatch.GetElapsedTime(snapshot.Read) >= SnapshotAge)
{
var online = await db.RenderNodes.ListOnlineAsync(now - timeout, cancellationToken);
snapshot = new Snapshot(Stopwatch.GetTimestamp(), [.. online.Select(Dto.Capabilities).OfType<RegisterNodeRequest>()]);
Volatile.Write(ref _snapshot, snapshot);
}
return snapshot.Nodes.Any(node => RenderNodeService.CanEncode(node, parameters));
}
/// <summary>What the online nodes announced, and when it was read (a <see cref="Stopwatch"/> timestamp).</summary>
private sealed record Snapshot(long Read, IReadOnlyList<RegisterNodeRequest> Nodes);
}
+1 -19
View File
@@ -47,26 +47,8 @@ public sealed class RenderNodeMonitor(TitanoDatabase db, ServerOptions options,
{
await db.RenderNodes.SetStateAsync(node.Id, RenderNodeService.Offline, cancellationToken);
events.Publish(new NodeStateEvent(node.Id, node.ClientName, RenderNodeService.Offline));
var key = RenderNodeService.NodeKey(node);
var lost = await db.Jobs.ListRunningByNodeAsync(key, cancellationToken);
foreach (var job in lost)
{
var line = RenderNodeService.AppendLog(job.LogTail, $"Render node {node.ClientName} stopped responding.");
if (job.Attempts >= MaxAttempts)
{
await db.Jobs.FinishNodeJobAsync(job.Id, key, JobState.Failed, $"Lost its render node {job.Attempts} times.", line, cancellationToken);
}
else
{
await db.Jobs.UpdateNodeProgressAsync(job.Id, key, job.ProgressDone, job.ProgressTotal, null, null, line, cancellationToken);
}
}
var requeued = await db.Jobs.RequeueRunningAsync(key, cancellationToken);
var requeued = await RenderNodeService.ReleaseJobsAsync(db, jobs, node, $"Render node {node.ClientName} stopped responding.", cancellationToken);
logger.LogWarning("Render node {Node} is offline; {Count} job(s) back in the queue", node.ClientName, requeued);
foreach (var job in lost)
{
if (await db.Jobs.GetAsync(job.Id, cancellationToken) is { } current) jobs.Publish(current);
}
}
}
}
+43 -9
View File
@@ -41,16 +41,17 @@ public sealed class RenderNodeService(
return Outcome<RenderNodeDto>.Fail(400, "bad_request", "encoders");
var existing = (await db.RenderNodes.ListAsync(cancellationToken)).FirstOrDefault(n => n.UserId == caller.Id && n.ClientName == name);
var id = existing?.Id ?? Guid.CreateVersion7();
var running = await db.Jobs.ListRunningByNodeAsync(id.ToString(), cancellationToken);
// A node registers when it starts, holding no job: what the server still lists as running on it was abandoned
// by its previous run (stopped, restarted or crashed within the heartbeat timeout) and goes back to the queue.
if (existing is not null) await ReleaseJobsAsync(db, jobs, existing, $"Render node {name} restarted.", cancellationToken);
var node = new RenderNode
{
Id = id,
Id = existing?.Id ?? Guid.CreateVersion7(),
UserId = caller.Id,
ClientName = name,
CapabilitiesJson = JsonSerializer.Serialize(request with { ClientName = name }, ProtocolJson.Default.RegisterNodeRequest),
LastHeartbeat = time.GetUtcNow(),
State = running.Count > 0 ? Busy : Idle,
State = Idle,
};
await db.RenderNodes.RegisterAsync(node, cancellationToken);
events.Publish(new NodeStateEvent(node.Id, node.ClientName, node.State));
@@ -71,6 +72,9 @@ public sealed class RenderNodeService(
var capabilities = Dto.Capabilities(node);
foreach (var queued in await db.Jobs.ListQueuedAsync(JobKind.Render, 50, cancellationToken))
{
// A render the server's own engine started (it left a checkpoint) resumes there: only it knows that attempt's
// leftovers and the batch entries it recorded.
if (queued.Checkpoint is not null) continue;
if (JobEndpoints.ParseRender(queued.ParametersJson) is not { } parameters || capabilities is null || !CanEncode(capabilities, parameters)) continue;
if (await db.Jobs.TryClaimAsync(queued.Id, NodeKey(node), cancellationToken) is not { } job) continue;
jobs.Publish(job);
@@ -182,6 +186,31 @@ public sealed class RenderNodeService(
/// <summary>Running-job owner key stored in <c>jobs.node_id</c>.</summary>
public static string NodeKey(RenderNode node) => node.Id.ToString();
/// <summary>
/// Gives the jobs running on <paramref name="node"/> back to the queue with <paramref name="reason"/> in their log
/// (checkpoint and progress kept); a job that already lost its node <see cref="RenderNodeMonitor.MaxAttempts"/> times
/// fails instead. Returns how many went back.
/// </summary>
internal static async Task<int> ReleaseJobsAsync(TitanoDatabase db, JobEngineHost jobs, RenderNode node, string reason, CancellationToken cancellationToken)
{
var key = NodeKey(node);
var lost = await db.Jobs.ListRunningByNodeAsync(key, cancellationToken);
foreach (var job in lost)
{
var line = AppendLog(job.LogTail, reason);
if (job.Attempts >= RenderNodeMonitor.MaxAttempts)
await db.Jobs.FinishNodeJobAsync(job.Id, key, JobState.Failed, $"Lost its render node {job.Attempts} times.", line, cancellationToken);
else
await db.Jobs.UpdateNodeProgressAsync(job.Id, key, job.ProgressDone, job.ProgressTotal, null, null, line, cancellationToken);
}
var requeued = await db.Jobs.RequeueRunningAsync(key, cancellationToken);
foreach (var job in lost)
{
if (await db.Jobs.GetAsync(job.Id, cancellationToken) is { } current) jobs.Publish(current);
}
return requeued;
}
private async Task<RenderNode?> OwnedNodeAsync(Caller caller, Guid nodeId, CancellationToken cancellationToken) =>
await db.RenderNodes.GetAsync(nodeId, cancellationToken) is { } node && node.UserId == caller.Id ? node : null;
@@ -221,11 +250,16 @@ public sealed class RenderNodeService(
}
}
/// <summary>The node has an encoder for the job's codec and handles its resolution (0 = no announced limit).</summary>
private static bool CanEncode(RegisterNodeRequest node, RenderJobParameters job) =>
node.Encoders.Any(e => string.Equals(e.Codec, job.Codec, StringComparison.OrdinalIgnoreCase))
&& (node.MaxWidth <= 0 || job.Width <= node.MaxWidth)
&& (node.MaxHeight <= 0 || job.Height <= node.MaxHeight);
/// <summary>
/// The node has an encoder for the job's codec that handles its resolution: the encoder's own limit, else the node's
/// (0 = no announced limit).
/// </summary>
internal static bool CanEncode(RegisterNodeRequest node, RenderJobParameters job) =>
node.Encoders.Any(e => string.Equals(e.Codec, job.Codec, StringComparison.OrdinalIgnoreCase)
&& Fits(job.Width, e.MaxWidth > 0 ? e.MaxWidth : node.MaxWidth)
&& Fits(job.Height, e.MaxHeight > 0 ? e.MaxHeight : node.MaxHeight));
private static bool Fits(int size, int limit) => limit <= 0 || size <= limit;
internal static string? AppendLog(string? tail, string? line)
{
+9 -2
View File
@@ -26,15 +26,22 @@ switch (command.Command)
case ServerCommand.UninstallService when OperatingSystem.IsWindows():
return ServiceAction(ServiceInstaller.Uninstall, $"Removed the {WindowsServiceHost.ServiceName} service.");
case ServerCommand.Service when OperatingSystem.IsWindows():
if (WindowsServiceHost.Run(() => ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments], ArchiveModule.Register))) return 0;
if (WindowsServiceHost.Run(() => ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments], RegisterModules))) return 0;
await Console.Error.WriteLineAsync("--service is used by the Service Control Manager; start the service with 'sc start TitanoServer'.");
return 1;
default:
var app = ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments], ArchiveModule.Register);
var app = ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments], RegisterModules);
await app.RunAsync();
return 0;
}
// The archive engine, then analysis and managed rendering over it.
static void RegisterModules(IServiceCollection services)
{
ArchiveModule.Register(services);
ProcessingModule.Register(services);
}
static int ServiceAction(Action action, string done)
{
try
+2 -3
View File
@@ -7,8 +7,8 @@ namespace Titano.Server.Storage;
/// <summary>
/// The archive engine behind the server (BRIEF §7, §14.4): ingest of verified uploads, lookup of proxies and
/// thumbnails, and its job handlers (scan, rebuild, verify, import, thumbnails, proxies, maintenance), plus the
/// analysis handlers of <see cref="ProcessingModule"/>. Decoding is managed only (BRIEF §4.2).
/// thumbnails, and its job handlers (scan, rebuild, verify, import, thumbnails, proxies, maintenance). Decoding is
/// managed only (BRIEF §4.2).
/// </summary>
public static class ArchiveModule
{
@@ -22,6 +22,5 @@ public static class ArchiveModule
services.AddSingleton<IArchiveIngest>(sp => sp.GetRequiredService<ArchiveService>().Ingest);
services.AddSingleton<IJobHandlerProvider>(sp => sp.GetRequiredService<ArchiveService>());
services.AddSingleton<IFrameAssetLocator, ArchiveAssetLocator>();
ProcessingModule.Register(services);
}
}
+27 -9
View File
@@ -5,26 +5,44 @@ using Titano.Data;
using Titano.Data.Archiving;
using Titano.Data.Jobs;
using Titano.Data.Processing;
using Titano.Protocol;
using Titano.Server.Configuration;
using Titano.Server.Events;
using Titano.Server.Jobs;
namespace Titano.Server.Storage;
/// <summary>
/// Analysis and render engine of the server (BRIEF §4.2, §10, §14.6): light and deep analysis job handlers with managed
/// decoders, so the light analysis queued after uploads runs here. Its render handler is registered too, but the job
/// engine host never runs render jobs: render nodes claim them (BRIEF §14.7).
/// Analysis and render engine of the server (BRIEF §4.2, §10, §14.5, §14.6): light and deep analysis with managed
/// decoders (the light analysis queued after uploads runs here) and renders with managed encoders only. The render
/// handler takes the jobs whose every output a managed encoder produces (AVI MJPEG, image sequences, GIF, APNG); MP4
/// jobs wait for render nodes until none can take them (<see cref="RenderNodeAvailability"/>), and then render here as
/// MJPEG in AVI with a line in the job log (BRIEF §14.7). Renders recorded and Auto values changed here reach connected
/// clients as <c>sequenceChanged</c> events (§14.3).
/// </summary>
public static class ProcessingModule
{
public static void Register(IServiceCollection services)
{
services.AddSingleton(sp => new ProcessingService(sp.GetRequiredService<TitanoDatabase>(), new ProcessingOptions
services.AddSingleton<RenderNodeAvailability>();
services.AddSingleton(sp =>
{
Archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = ArchiveModule.Owner },
Encoders = [new ManagedEncoderProvider()],
Host = EncoderHost.Server,
ProducedBy = sp.GetRequiredService<ServerOptions>().ServerName,
}));
var db = sp.GetRequiredService<TitanoDatabase>();
var events = sp.GetRequiredService<EventHub>();
return new ProcessingService(db, new ProcessingOptions
{
Archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = ArchiveModule.Owner },
Encoders = [new ManagedEncoderProvider()],
Host = EncoderHost.Server,
AwaitsRenderNode = sp.GetRequiredService<RenderNodeAvailability>().AwaitsNodeAsync,
ProducedBy = sp.GetRequiredService<ServerOptions>().ServerName,
SequenceChanged = async (id, change, ct) =>
{
if (await db.Sequences.GetAsync(id, ct) is { } sequence)
events.Publish(new SequenceChangedEvent(id, change, sequence.FramesVersion, sequence.SettingsVersion));
},
});
});
services.AddSingleton<IJobHandlerProvider>(sp => sp.GetRequiredService<ProcessingService>());
}
}
@@ -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;
}
}