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

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

No files matched your search

+63 -51
View File
@@ -31,12 +31,17 @@ namespace Titano.App.Infrastructure;
/// <see cref="CreateJobHandlers"/>, thumbnails, the server session, the render node, the encoder inventory and the
/// update check. Started after the window shows, stopped when the app exits. The last archive is reopened at start and
/// rescanned every <see cref="ScanInterval"/> (BRIEF §7: polling, no file-system watchers). The render node runs while
/// the user offers this PC (<see cref="AppSettings.RenderNodeOptIn"/>) and a server session is open.
/// the user offers this PC (<see cref="AppSettings.RenderNodeOptIn"/>) and a server session is open (never in capture
/// mode). Renders and the render node use hardware encoders as Settings › Rendering allows
/// (<see cref="AllowsHardware(HardwarePreference, string)"/>). Disposal never needs the UI thread, which waits for it.
/// </summary>
public sealed class AppServices : IAsyncDisposable
{
public static readonly TimeSpan ScanInterval = TimeSpan.FromMinutes(10);
/// <summary>The quick preview preset: the one render "Hardware for previews only" leaves on the GPU.</summary>
private const string PreviewPresetId = "720p-preview";
private static readonly Lazy<HttpClient> Http = new(() => new HttpClient { Timeout = TimeSpan.FromSeconds(20) });
/// <summary>Update packages are large: their download fails when it stalls (<see cref="UpdateDownload.IdleTimeout"/>), never after a fixed total time.</summary>
@@ -44,9 +49,8 @@ public sealed class AppServices : IAsyncDisposable
private readonly CancellationTokenSource _stopping = new();
private readonly Dictionary<Guid, Guid> _scans = [];
private Task _polling = Task.CompletedTask;
private readonly RenderNodeHost _renderNode;
private ServerSession _server = null!;
private Task _nodeSwitch = Task.CompletedTask;
private (RenderNodeClient Node, TitanoClient Client, Uri Address, string Token)? _node;
public AppServices(AppEnvironment environment, AppSettings settings, Action saveSettings, IAppDialogs dialogs)
{
@@ -54,6 +58,7 @@ public sealed class AppServices : IAsyncDisposable
Settings = settings;
SaveSettingsAction = saveSettings;
Dialogs = dialogs;
_renderNode = new RenderNodeHost(StartRenderNode);
ArchiveSetup = new EngineArchiveSetup(this);
Server = new ServerSession(settings, saveSettings, new TitanoServerApiFactory(), new DpapiTokenProtector());
Encoders = new MediaFoundationInventory();
@@ -145,8 +150,18 @@ public sealed class AppServices : IAsyncDisposable
UpdateRenderNode();
}
/// <summary>Starts or stops the render node to match the opt-in and the server session (BRIEF §14.7); switches run in order.</summary>
public void UpdateRenderNode() => _nodeSwitch = SwitchRenderNodeAsync(_nodeSwitch);
/// <summary>Starts, restarts or stops the render node to match the opt-in, the server session and the trusted certificates (BRIEF §14.7).</summary>
public void UpdateRenderNode() =>
_renderNode.Update(RenderNodeSession.For(Settings.RenderNodeOptIn && Processing is not null && !Environment.IsCapture, _server.IsConnected,
_server.Flow.Address, _server.Flow.Token, _server.Fingerprints, AllowsHardware(Settings.HardwareEncoding, ExportResolver.CustomId)));
/// <summary>Settings › Rendering: whether a render of <paramref name="presetId"/> may use hardware encoders.</summary>
public static bool AllowsHardware(HardwarePreference preference, string presetId) => preference switch
{
HardwarePreference.PreferHardware => true,
HardwarePreference.HardwareForPreviews => presetId.Equals(PreviewPresetId, StringComparison.OrdinalIgnoreCase),
_ => false,
};
/// <summary>Opens (or creates) the index at <paramref name="databasePath"/>, migrates it and starts the job engine.</summary>
public async Task OpenAsync(string databasePath, CancellationToken ct = default)
@@ -175,34 +190,36 @@ public sealed class AppServices : IAsyncDisposable
Thumbnails = new ThumbnailService(database, Settings.ThumbnailMemoryItems);
}
/// <summary>Stops polling, the render node and the engine, then closes the index. The app's exit waits for this on the UI
/// thread, so nothing here continues on it.</summary>
public async ValueTask DisposeAsync()
{
await _stopping.CancelAsync();
await _polling;
await _stopping.CancelAsync().ConfigureAwait(false);
await _polling.ConfigureAwait(false);
_stopping.Dispose();
_server.PropertyChanged -= OnServerChanged;
await _nodeSwitch;
await StopRenderNodeAsync();
await _renderNode.DisposeAsync().ConfigureAwait(false);
(Jobs as IDisposable)?.Dispose();
if (Engine is not null) await Engine.DisposeAsync();
if (Engine is not null) await Engine.DisposeAsync().ConfigureAwait(false);
Thumbnails?.Dispose();
Server.Dispose();
if (Database is not null) await Database.DisposeAsync();
if (Database is not null) await Database.DisposeAsync().ConfigureAwait(false);
}
/// <summary>Reopens the last archive (relinking a moved one, finishing interrupted renames) and rescans it periodically.</summary>
/// <summary>Reopens the last archive (relinking a moved one, finishing interrupted renames) and rescans it periodically,
/// off the UI thread (disposal waits for it there).</summary>
private async Task PollAsync(string root, CancellationToken ct)
{
try
{
if (Archives is null) return;
var archive = await Task.Run(() => Archives.OpenAsync(root, ct), ct);
var archive = await Task.Run(() => Archives.OpenAsync(root, ct), ct).ConfigureAwait(false);
using var timer = new PeriodicTimer(ScanInterval);
do
{
if (ArchiveService.GetAvailability(archive) == ArchiveAvailability.Online) await QueueScanAsync(archive, full: false, ct);
if (ArchiveService.GetAvailability(archive) == ArchiveAvailability.Online) await QueueScanAsync(archive, full: false, ct).ConfigureAwait(false);
}
while (await timer.WaitForNextTickAsync(ct));
while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false));
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
@@ -229,12 +246,14 @@ public sealed class AppServices : IAsyncDisposable
UpdateRenderNode();
}
/// <summary>Media Foundation (hardware first, software H.264) then managed encoders; frames spill into the cache folder
/// within the memory budget of Settings › Rendering (Auto: a quarter of the installed memory).</summary>
/// <summary>Media Foundation (hardware first, software H.264; hardware as Settings › Rendering allows) then managed
/// encoders; frames spill into the cache folder within the memory budget of Settings › Rendering (Auto: a quarter of
/// the installed memory).</summary>
private ProcessingOptions ProcessingOptions(ArchiveServiceOptions archive) => new()
{
Archive = archive,
Encoders = [new MediaFoundationEncoderProvider(), new ManagedEncoderProvider()],
AllowsHardware = presetId => AllowsHardware(Settings.HardwareEncoding, presetId),
Host = EncoderHost.Client,
ProducedBy = System.Environment.MachineName,
FrameWindow = new FrameWindowOptions
@@ -246,45 +265,38 @@ public sealed class AppServices : IAsyncDisposable
private void OnServerChanged(object? sender, PropertyChangedEventArgs e) => UpdateRenderNode();
/// <summary>Waits for the previous switch, then runs the node for the current session, or stops it.</summary>
private async Task SwitchRenderNodeAsync(Task previous)
/// <summary>
/// The render node of <paramref name="session"/>: this PC's encoders (Media Foundation, then managed), downloads and
/// outputs in the cache folder within its size limit.
/// </summary>
private IRenderNode StartRenderNode(RenderNodeSession session)
{
await previous;
var flow = _server.Flow;
(ProcessingService Engine, Uri Address, string Token)? wanted =
Settings.RenderNodeOptIn && _server.IsConnected && Processing is { } processing && flow.Address is { } address && flow.Token is { } token
? (processing, address, token)
: null;
if (_node is { } running && wanted is { } same && running.Address == same.Address && running.Token == same.Token) return;
await StopRenderNodeAsync();
if (wanted is not { } start) return;
try
var processing = Processing ?? throw new InvalidOperationException("The index is not open.");
var cache = CacheStore.Folder(Environment, Settings);
CacheStore.Prepare(cache);
var client = new TitanoClient(session.Address, new CertificatePinning(session.TrustedFingerprints), $"Titano ({System.Environment.MachineName})")
{
var cache = CacheStore.Folder(Environment, Settings);
CacheStore.Prepare(cache);
var client = new TitanoClient(start.Address, new CertificatePinning(_server.Fingerprints), $"Titano ({System.Environment.MachineName})") { Token = start.Token };
var node = new RenderNodeClient(client, start.Engine.Options, new RenderNodeOptions
{
ClientName = System.Environment.MachineName,
CacheDirectory = Path.Combine(cache, "render-node"),
CacheLimitBytes = Settings.CacheLimitGb * (1L << 30),
});
node.Start();
_node = (node, client, start.Address, start.Token);
Log.Info("render-node", $"Offering this PC as render node to {start.Address}");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
Token = session.Token,
};
var node = new RenderNodeClient(client, processing.Options, new RenderNodeOptions
{
Log.Warning("render-node", "The render node could not start", ex);
}
ClientName = System.Environment.MachineName,
CacheDirectory = Path.Combine(cache, "render-node"),
CacheLimitBytes = Settings.CacheLimitGb * (1L << 30),
});
node.Start();
return new RunningNode(node, client);
}
private async Task StopRenderNodeAsync()
/// <summary>A started node and the client it owns.</summary>
private sealed class RunningNode(RenderNodeClient node, TitanoClient client) : IRenderNode
{
if (_node is not { } running) return;
_node = null;
await running.Node.DisposeAsync();
running.Client.Dispose();
Log.Info("render-node", "Render node stopped");
public Task Completion => node.Completion;
public async ValueTask DisposeAsync()
{
await node.DisposeAsync().ConfigureAwait(false);
client.Dispose();
}
}
}
@@ -0,0 +1,124 @@
using Titano.Core.Diagnostics;
namespace Titano.App.Infrastructure;
/// <summary>
/// What a render node runs with: the server session (address and token), the certificates it may trust and whether it
/// offers hardware encoders. A change of any of them means another node.
/// </summary>
public sealed record RenderNodeSession(Uri Address, string Token, IReadOnlyCollection<string> TrustedFingerprints, bool Hardware)
{
/// <summary>
/// The session a node should run for, or null when it should be off: the user offers this PC
/// (<paramref name="offered"/>), a server session is open and signed in.
/// </summary>
public static RenderNodeSession? For(bool offered, bool connected, Uri? address, string? token, IReadOnlyCollection<string> trustedFingerprints,
bool hardware) =>
offered && connected && address is not null && token is not null ? new RenderNodeSession(address, token, trustedFingerprints, hardware) : null;
public bool Equals(RenderNodeSession? other) =>
other is not null && Address == other.Address && Token == other.Token && Hardware == other.Hardware
&& TrustedFingerprints.Order(StringComparer.Ordinal).SequenceEqual(other.TrustedFingerprints.Order(StringComparer.Ordinal), StringComparer.Ordinal);
public override int GetHashCode() => HashCode.Combine(Address, Token, Hardware, TrustedFingerprints.Count);
}
/// <summary>A started render node.</summary>
public interface IRenderNode : IAsyncDisposable
{
/// <summary>Completes when the node has stopped, by itself (refused by the server) or when disposed.</summary>
Task Completion { get; }
}
/// <summary>
/// Keeps this PC's render node (BRIEF §14.7) in line with "Offer this PC as render node" and the server session:
/// <see cref="Update"/> starts the node for the wanted session, restarts it for another session or when it stopped by
/// itself, and stops it when none is wanted. Switches run one after the other, off the caller's thread, and never fail:
/// a node that cannot start is logged and stays off until the next update.
/// </summary>
public sealed class RenderNodeHost(Func<RenderNodeSession, IRenderNode> start) : IAsyncDisposable
{
private readonly Lock _gate = new();
private Task _switching = Task.CompletedTask;
private (RenderNodeSession Session, IRenderNode Node)? _running;
private bool _disposed;
/// <summary>The session the node runs for; null when it is off.</summary>
public RenderNodeSession? Session
{
get
{
lock (_gate) return _running?.Session;
}
}
/// <summary>Completes when every switch requested so far has run.</summary>
public Task Switching
{
get
{
lock (_gate) return _switching;
}
}
/// <summary>Runs the node for <paramref name="wanted"/>, or stops it when null.</summary>
public void Update(RenderNodeSession? wanted)
{
lock (_gate)
{
if (_disposed) return;
var previous = _switching;
_switching = Task.Run(async () =>
{
await previous.ConfigureAwait(false);
await SwitchAsync(wanted).ConfigureAwait(false);
});
}
}
/// <summary>Stops the node after the pending switches; later updates are ignored.</summary>
public async ValueTask DisposeAsync()
{
Task pending;
lock (_gate)
{
_disposed = true;
pending = _switching;
}
await pending.ConfigureAwait(false);
await SwitchAsync(null).ConfigureAwait(false);
}
private async Task SwitchAsync(RenderNodeSession? wanted)
{
(RenderNodeSession Session, IRenderNode Node)? running;
lock (_gate) running = _running;
// A node the server refused has stopped by itself: the same session starts it again (the right may be granted now).
if (running?.Session == wanted && running?.Node.Completion.IsCompleted != true) return;
if (running is { } old)
{
lock (_gate) _running = null;
try
{
await old.Node.DisposeAsync().ConfigureAwait(false);
Log.Info("render-node", "Render node stopped");
}
catch (Exception ex)
{
// A node that fails to stop is gone anyway; the next one must still be able to start.
Log.Warning("render-node", "The render node did not stop cleanly", ex);
}
}
if (wanted is null) return;
try
{
var node = start(wanted);
lock (_gate) _running = (wanted, node);
Log.Info("render-node", $"Offering this PC as render node to {wanted.Address}");
}
catch (Exception ex)
{
Log.Warning("render-node", "The render node could not start", ex);
}
}
}