Titano: editor, import/archive screens, analysis and render jobs, server sync — in progress #2
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) });
|
||||
private readonly CancellationTokenSource _stopping = new();
|
||||
private readonly Dictionary<Guid, Guid> _scans = [];
|
||||
@@ -136,11 +141,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).</summary>
|
||||
/// <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(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)));
|
||||
|
||||
/// <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)
|
||||
@@ -169,33 +181,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 _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);
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
@@ -222,12 +237,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
|
||||
@@ -243,12 +260,12 @@ public sealed class AppServices : IAsyncDisposable
|
||||
/// 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 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
|
||||
}
|
||||
|
||||
/// <summary>A started node and the client it owns.</summary>
|
||||
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);
|
||||
|
||||
@@ -2,20 +2,45 @@ using Titano.Core.Diagnostics;
|
||||
|
||||
namespace Titano.App.Infrastructure;
|
||||
|
||||
/// <summary>The server session a render node works for: a change of either value means another node.</summary>
|
||||
public sealed record RenderNodeSession(Uri Address, string Token);
|
||||
/// <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 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.
|
||||
/// <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, IAsyncDisposable> start) : IAsyncDisposable
|
||||
public sealed class RenderNodeHost(Func<RenderNodeSession, IRenderNode> 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;
|
||||
|
||||
/// <summary>The session the node runs for; null when it is off.</summary>
|
||||
@@ -66,9 +91,10 @@ public sealed class RenderNodeHost(Func<RenderNodeSession, IAsyncDisposable> 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;
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
using System.IO;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Tests.Uploader;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Data.Archiving;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.App.Tests.Infrastructure;
|
||||
|
||||
public sealed class AppServicesTests
|
||||
{
|
||||
/// <summary>Dialogs that answer like a user who cancels everything.</summary>
|
||||
private sealed class NoDialogs : IAppDialogs
|
||||
{
|
||||
public string? PickFolder(string title, string? initialFolder = null) => null;
|
||||
public string? PickJsonFile(string title) => null;
|
||||
public bool Confirm(ConfirmRequest request) => false;
|
||||
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void ExitStopsPollingAndTheEngineWhileTheUiThreadWaits()
|
||||
{
|
||||
var environment = AppEnvironment.ForCapture();
|
||||
try
|
||||
{
|
||||
SingleThreadedContext.Run(async () =>
|
||||
{
|
||||
var root = Path.Combine(environment.DataDirectory, "archive");
|
||||
await using (var setup = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(environment.DataDirectory, "setup.db"))))
|
||||
await new ArchiveService(setup).CreateAsync(root, "Exit");
|
||||
var services = new AppServices(environment, new AppSettings { Language = "en", LastArchivePath = root }, () => { }, new NoDialogs());
|
||||
await services.OpenAsync(environment.DatabasePath);
|
||||
// The archive was reopened and its first rescan queued: polling now waits for the next one.
|
||||
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
|
||||
while ((await services.Database!.Jobs.ListAsync(null, JobKind.Scan)).Items.Count == 0)
|
||||
{
|
||||
Assert.True(DateTime.UtcNow < until, "no rescan queued");
|
||||
await Task.Delay(50);
|
||||
}
|
||||
|
||||
// App.OnExit blocks the UI thread until the services stop: nothing they await may continue on it.
|
||||
Assert.True(services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(10)), "services stopped");
|
||||
});
|
||||
}
|
||||
finally
|
||||
{
|
||||
environment.DeleteCaptureData();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
/// <summary>Records the nodes it starts; fails the first <see cref="Failures"/> starts.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>The server refused the node (signed out, no render-node right): it ends by itself.</summary>
|
||||
public void Refuse() => _completion.TrySetResult();
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
Stopped = true;
|
||||
_completion.TrySetResult();
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
Reference in new issue
Block a user