diff --git a/src/Titano.App/Infrastructure/AppServices.cs b/src/Titano.App/Infrastructure/AppServices.cs index 0f2a9571..6bfa8c9d 100644 --- a/src/Titano.App/Infrastructure/AppServices.cs +++ b/src/Titano.App/Infrastructure/AppServices.cs @@ -31,12 +31,17 @@ namespace Titano.App.Infrastructure; /// , 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 (BRIEF §7: polling, no file-system watchers). The render node runs while -/// the user offers this PC () and a server session is open. +/// the user offers this PC () and a server session is open (never in capture +/// mode). Renders and the render node use hardware encoders as Settings › Rendering allows +/// (). Disposal never needs the UI thread, which waits for it. /// public sealed class AppServices : IAsyncDisposable { public static readonly TimeSpan ScanInterval = TimeSpan.FromMinutes(10); + /// The quick preview preset: the one render "Hardware for previews only" leaves on the GPU. + private const string PreviewPresetId = "720p-preview"; + private static readonly Lazy Http = new(() => new HttpClient { Timeout = TimeSpan.FromSeconds(20) }); private readonly CancellationTokenSource _stopping = new(); private readonly Dictionary _scans = []; @@ -136,11 +141,18 @@ public sealed class AppServices : IAsyncDisposable UpdateRenderNode(); } - /// Starts or stops the render node to match the opt-in and the server session (BRIEF §14.7). + /// Starts, restarts or stops the render node to match the opt-in, the server session and the trusted certificates (BRIEF §14.7). public void UpdateRenderNode() => - _renderNode.Update(Settings.RenderNodeOptIn && _server.IsConnected && Processing is not null && _server.Flow is { Address: { } address, Token: { } token } - ? new RenderNodeSession(address, token) - : null); + _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))); + + /// Settings › Rendering: whether a render of may use hardware encoders. + public static bool AllowsHardware(HardwarePreference preference, string presetId) => preference switch + { + HardwarePreference.PreferHardware => true, + HardwarePreference.HardwareForPreviews => presetId.Equals(PreviewPresetId, StringComparison.OrdinalIgnoreCase), + _ => false, + }; /// Opens (or creates) the index at , migrates it and starts the job engine. public async Task OpenAsync(string databasePath, CancellationToken ct = default) @@ -169,33 +181,36 @@ public sealed class AppServices : IAsyncDisposable Thumbnails = new ThumbnailService(database, Settings.ThumbnailMemoryItems); } + /// 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. public async ValueTask DisposeAsync() { - await _stopping.CancelAsync(); - await _polling; + await _stopping.CancelAsync().ConfigureAwait(false); + await _polling.ConfigureAwait(false); _stopping.Dispose(); _server.PropertyChanged -= OnServerChanged; - await _renderNode.DisposeAsync(); + 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); } - /// Reopens the last archive (relinking a moved one, finishing interrupted renames) and rescans it periodically. + /// Reopens the last archive (relinking a moved one, finishing interrupted renames) and rescans it periodically, + /// off the UI thread (disposal waits for it there). 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) { @@ -222,12 +237,14 @@ public sealed class AppServices : IAsyncDisposable UpdateRenderNode(); } - /// 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). + /// 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). 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 @@ -243,12 +260,12 @@ public sealed class AppServices : IAsyncDisposable /// The render node of : this PC's encoders (Media Foundation, then managed), downloads and /// outputs in the cache folder within its size limit. /// - private IAsyncDisposable StartRenderNode(RenderNodeSession session) + private IRenderNode StartRenderNode(RenderNodeSession session) { 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(_server.Fingerprints), $"Titano ({System.Environment.MachineName})") + var client = new TitanoClient(session.Address, new CertificatePinning(session.TrustedFingerprints), $"Titano ({System.Environment.MachineName})") { Token = session.Token, }; @@ -263,8 +280,10 @@ public sealed class AppServices : IAsyncDisposable } /// A started node and the client it owns. - private sealed class RunningNode(RenderNodeClient node, TitanoClient client) : IAsyncDisposable + private sealed class RunningNode(RenderNodeClient node, TitanoClient client) : IRenderNode { + public Task Completion => node.Completion; + public async ValueTask DisposeAsync() { await node.DisposeAsync().ConfigureAwait(false); diff --git a/src/Titano.App/Infrastructure/RenderNodeHost.cs b/src/Titano.App/Infrastructure/RenderNodeHost.cs index 18c4e9ad..5b21c6c7 100644 --- a/src/Titano.App/Infrastructure/RenderNodeHost.cs +++ b/src/Titano.App/Infrastructure/RenderNodeHost.cs @@ -2,20 +2,45 @@ using Titano.Core.Diagnostics; namespace Titano.App.Infrastructure; -/// The server session a render node works for: a change of either value means another node. -public sealed record RenderNodeSession(Uri Address, string Token); +/// +/// 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. +/// +public sealed record RenderNodeSession(Uri Address, string Token, IReadOnlyCollection TrustedFingerprints, bool Hardware) +{ + /// + /// The session a node should run for, or null when it should be off: the user offers this PC + /// (), a server session is open and signed in. + /// + public static RenderNodeSession? For(bool offered, bool connected, Uri? address, string? token, IReadOnlyCollection 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); +} + +/// A started render node. +public interface IRenderNode : IAsyncDisposable +{ + /// Completes when the node has stopped, by itself (refused by the server) or when disposed. + Task Completion { get; } +} /// /// Keeps this PC's render node (BRIEF §14.7) in line with "Offer this PC as render node" and the server session: -/// starts the node for the wanted session, restarts it for another session 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. +/// 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. /// -public sealed class RenderNodeHost(Func start) : IAsyncDisposable +public sealed class RenderNodeHost(Func start) : IAsyncDisposable { private readonly Lock _gate = new(); private Task _switching = Task.CompletedTask; - private (RenderNodeSession Session, IAsyncDisposable Node)? _running; + private (RenderNodeSession Session, IRenderNode Node)? _running; private bool _disposed; /// The session the node runs for; null when it is off. @@ -66,9 +91,10 @@ public sealed class RenderNodeHost(Func sta private async Task SwitchAsync(RenderNodeSession? wanted) { - (RenderNodeSession Session, IAsyncDisposable Node)? running; + (RenderNodeSession Session, IRenderNode Node)? running; lock (_gate) running = _running; - if (running?.Session == wanted) return; + // 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; diff --git a/tests/Titano.App.Tests/Infrastructure/AppServicesTests.cs b/tests/Titano.App.Tests/Infrastructure/AppServicesTests.cs new file mode 100644 index 00000000..9d2268d2 --- /dev/null +++ b/tests/Titano.App.Tests/Infrastructure/AppServicesTests.cs @@ -0,0 +1,53 @@ +using System.IO; +using Titano.App.Infrastructure; +using Titano.App.Tests.Uploader; +using Titano.Core.Model; +using Titano.Data; +using Titano.Data.Archiving; +using Titano.Testing; + +namespace Titano.App.Tests.Infrastructure; + +public sealed class AppServicesTests +{ + /// Dialogs that answer like a user who cancels everything. + private sealed class NoDialogs : IAppDialogs + { + public string? PickFolder(string title, string? initialFolder = null) => null; + public string? PickJsonFile(string title) => null; + public bool Confirm(ConfirmRequest request) => false; + public bool SignIn(string server, string? username, Func> signIn) => false; + } + + [Test] + [WindowsOnly] + public void ExitStopsPollingAndTheEngineWhileTheUiThreadWaits() + { + var environment = AppEnvironment.ForCapture(); + try + { + SingleThreadedContext.Run(async () => + { + var root = Path.Combine(environment.DataDirectory, "archive"); + await using (var setup = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(environment.DataDirectory, "setup.db")))) + await new ArchiveService(setup).CreateAsync(root, "Exit"); + var services = new AppServices(environment, new AppSettings { Language = "en", LastArchivePath = root }, () => { }, new NoDialogs()); + await services.OpenAsync(environment.DatabasePath); + // The archive was reopened and its first rescan queued: polling now waits for the next one. + var until = DateTime.UtcNow + TimeSpan.FromSeconds(30); + while ((await services.Database!.Jobs.ListAsync(null, JobKind.Scan)).Items.Count == 0) + { + Assert.True(DateTime.UtcNow < until, "no rescan queued"); + await Task.Delay(50); + } + + // App.OnExit blocks the UI thread until the services stop: nothing they await may continue on it. + Assert.True(services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(10)), "services stopped"); + }); + } + finally + { + environment.DeleteCaptureData(); + } + } +} diff --git a/tests/Titano.App.Tests/Server/RenderNodeHostTests.cs b/tests/Titano.App.Tests/Server/RenderNodeHostTests.cs index b600272e..c3711e3c 100644 --- a/tests/Titano.App.Tests/Server/RenderNodeHostTests.cs +++ b/tests/Titano.App.Tests/Server/RenderNodeHostTests.cs @@ -6,7 +6,7 @@ namespace Titano.App.Tests.Server; public sealed class RenderNodeHostTests { - private static readonly RenderNodeSession Nas = new(new Uri("https://nas.local:8443/"), "token-a"); + private static readonly RenderNodeSession Nas = new(new Uri("https://nas.local:8443/"), "token-a", ["AA:BB", "CC:DD"], Hardware: true); /// Records the nodes it starts; fails the first starts. private sealed class Nodes @@ -14,7 +14,7 @@ public sealed class RenderNodeHostTests public List<(RenderNodeSession Session, Node Node)> Started { get; } = []; public int Failures { get; set; } - public IAsyncDisposable Start(RenderNodeSession session) + public IRenderNode Start(RenderNodeSession session) { if (Failures-- > 0) throw new IOException("cache folder unavailable"); var node = new Node(); @@ -23,13 +23,21 @@ public sealed class RenderNodeHostTests } } - private sealed class Node : IAsyncDisposable + private sealed class Node : IRenderNode { + private readonly TaskCompletionSource _completion = new(); + public bool Stopped { get; private set; } + public Task Completion => _completion.Task; + + /// The server refused the node (signed out, no render-node right): it ends by itself. + public void Refuse() => _completion.TrySetResult(); + public ValueTask DisposeAsync() { Stopped = true; + _completion.TrySetResult(); return ValueTask.CompletedTask; } } @@ -46,6 +54,11 @@ public sealed class RenderNodeHostTests Assert.Equal(Nas, host.Session); Assert.Count(1, nodes.Started); + // An equal session (fingerprints in another order) keeps the node. + host.Update(Nas with { TrustedFingerprints = ["CC:DD", "AA:BB"] }); + await host.Switching; + Assert.Count(1, nodes.Started); + // A new token (signed in again) is another session: the old node stops before the new one starts. var renewed = Nas with { Token = "token-b" }; host.Update(renewed); @@ -53,10 +66,53 @@ public sealed class RenderNodeHostTests Assert.True(nodes.Started[0].Node.Stopped, "old node stopped"); Assert.Equal((renewed, false), (nodes.Started[1].Session, nodes.Started[1].Node.Stopped)); + // A forgotten certificate or another hardware choice also needs a new node. + host.Update(renewed with { TrustedFingerprints = [] }); + await host.Switching; + host.Update(renewed with { TrustedFingerprints = [], Hardware = false }); + await host.Switching; + Assert.Count(4, nodes.Started); + Assert.True(nodes.Started[2].Node.Stopped, "replaced again"); + host.Update(null); await host.Switching; Assert.Null(host.Session); - Assert.True(nodes.Started[1].Node.Stopped, "stopped when no longer wanted"); + Assert.True(nodes.Started[3].Node.Stopped, "stopped when no longer wanted"); + } + + [Test] + public async Task ANodeThatStoppedItselfIsStartedAgainByTheNextUpdate() + { + var nodes = new Nodes(); + await using var host = new RenderNodeHost(nodes.Start); + host.Update(Nas); + await host.Switching; + + nodes.Started[0].Node.Refuse(); + host.Update(Nas); + await host.Switching; + Assert.Count(2, nodes.Started); + Assert.Equal((Nas, false), (host.Session, nodes.Started[1].Node.Stopped)); + } + + [Test] + public void TheNodeIsWantedOnlyWhenOfferedAndSignedIn() + { + var address = new Uri("https://nas.local:8443/"); + Assert.Equal(Nas, RenderNodeSession.For(offered: true, connected: true, address, "token-a", ["AA:BB", "CC:DD"], hardware: true)); + Assert.Null(RenderNodeSession.For(offered: false, connected: true, address, "token-a", [], hardware: true)); + Assert.Null(RenderNodeSession.For(offered: true, connected: false, address, "token-a", [], hardware: true)); + Assert.Null(RenderNodeSession.For(offered: true, connected: true, address, null, [], hardware: true)); // signed out + Assert.Null(RenderNodeSession.For(offered: true, connected: true, null, "token-a", [], hardware: true)); + } + + [Test] + public void HardwarePreferenceDecidesPerPreset() + { + Assert.True(AppServices.AllowsHardware(HardwarePreference.PreferHardware, "4k-hevc")); + Assert.False(AppServices.AllowsHardware(HardwarePreference.SoftwareOnly, "720p-preview")); + Assert.True(AppServices.AllowsHardware(HardwarePreference.HardwareForPreviews, "720p-preview")); + Assert.False(AppServices.AllowsHardware(HardwarePreference.HardwareForPreviews, "4k-hevc10-archive")); } [Test]