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:
53 files changed
+2412
-291
No files matched your search
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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:<folder></c>, the last folder indexed.
|
||||
/// <see cref="JobKind.Rebuild"/>. Checkpoint: <c>after:<folder></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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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>());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user