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();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user