Files
Chronos/src/Titano.App/Infrastructure/AppServices.cs
T
Claude 10a9db9c91 merge: client server mode (sync engine, Server screen sync table and conflicts, Library sync glyphs, render transfers)
Keeps the render node host from the processing branch and disposes the sync
host after it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-03 10:38:05 +00:00

319 lines
15 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.ComponentModel;
using System.IO;
using System.Net.Http;
using System.Reflection;
using Titano.App.About;
using Titano.App.Jobs;
using Titano.App.Library;
using Titano.App.Server;
using Titano.App.Settings;
using Titano.Core.Archiving;
using Titano.Core.Diagnostics;
using Titano.Core.Export;
using Titano.Core.Imaging;
using Titano.Core.Imaging.Decoders;
using Titano.Core.Model;
using Titano.Core.Video.Managed;
using Titano.Core.Windows.MediaFoundation;
using Titano.Core.Windows.Wic;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Data.Jobs;
using Titano.Data.Processing;
using Titano.Protocol.Client;
namespace Titano.App.Infrastructure;
/// <summary>
/// Composition root of local mode (BRIEF §4.4): the SQLite index under the data folder (migrated on open), the
/// archive engine (WIC first, then managed decoders), the analysis and render engine (the same decoders; Media
/// Foundation, then managed encoders), the one <see cref="JobEngine"/> of this PC with the handlers of
/// <see cref="CreateJobHandlers"/>, thumbnails, the server session, the render node, the encoder inventory, the
/// update check and the sync with the signed-in server (<see cref="SyncHost"/>). 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 (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>
private static readonly Lazy<HttpClient> DownloadHttp = new(() => new HttpClient { Timeout = Timeout.InfiniteTimeSpan });
private readonly CancellationTokenSource _stopping = new();
private readonly Dictionary<Guid, Guid> _scans = [];
private Task _polling = Task.CompletedTask;
private readonly RenderNodeHost _renderNode;
private ServerSession _server = null!;
public AppServices(AppEnvironment environment, AppSettings settings, Action saveSettings, IAppDialogs dialogs)
{
Environment = environment;
Settings = settings;
SaveSettingsAction = saveSettings;
Dialogs = dialogs;
_renderNode = new RenderNodeHost(StartRenderNode);
ArchiveSetup = new EngineArchiveSetup(this);
Sync = new SyncHost(this);
Server = new ServerSession(settings, saveSettings, new TitanoServerApiFactory(), new DpapiTokenProtector());
Encoders = new MediaFoundationInventory();
CheckForUpdateAsync = ct => UpdateCheck.FetchAsync(Http.Value, ProductLinks.LatestReleaseApi, VersionText, ct);
DownloadUpdateAsync = (release, progress, ct) =>
UpdateDownload.DownloadAsync(DownloadHttp.Value, release, environment.IsPortable, UpdateDownload.Root(Path.GetTempPath()), VersionText, progress,
UpdateDownload.IdleTimeout, ct);
}
public AppEnvironment Environment { get; }
public AppSettings Settings { get; }
public IAppDialogs Dialogs { get; }
private Action SaveSettingsAction { get; }
/// <summary>First-run and Library archive actions.</summary>
public IArchiveSetup ArchiveSetup { get; set; }
/// <summary>The archive engine; null until the index is open.</summary>
public ArchiveService? Archives { get; private set; }
/// <summary>Analysis and render engine; null until the index is open.</summary>
public ProcessingService? Processing { get; private set; }
public ServerSession Server
{
get => _server;
set
{
if (_server is not null) _server.PropertyChanged -= OnServerChanged;
_server = value;
_server.PropertyChanged += OnServerChanged;
UpdateRenderNode();
Sync.Update();
}
}
/// <summary>Sync with the signed-in server: engine, job connection, background comparison.</summary>
public SyncHost Sync { get; }
public IEncoderInventory Encoders { get; set; }
/// <summary>Latest public release (GitHub Releases API of the releases repository, BRIEF §18).</summary>
public Func<CancellationToken, Task<ReleaseInfo?>> CheckForUpdateAsync { get; set; }
/// <summary>Downloads and verifies the package of a release for this copy (setup, or portable zip; BRIEF §18 P1) and returns its path.</summary>
public Func<ReleaseInfo, IProgress<double>?, CancellationToken, Task<string>> DownloadUpdateAsync { get; set; }
/// <summary>The index; null until <see cref="OpenAsync"/> succeeded.</summary>
public TitanoDatabase? Database { get; private set; }
public JobEngine? Engine { get; private set; }
public IJobQueue? Jobs { get; private set; }
public ThumbnailService? Thumbnails { get; private set; }
/// <summary>Why the index could not be opened; null when it is open.</summary>
public Exception? OpenError { get; private set; }
/// <summary>Node id of this PC's workers.</summary>
public string WorkerId { get; init; } = System.Environment.MachineName;
/// <summary>"0.1.0" (informational version).</summary>
public static string VersionText { get; } =
typeof(AppServices).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0";
/// <summary>The job handlers of this PC's engine — the single registration list; a kind without a handler stays
/// queued (it is never claimed here).</summary>
public static IReadOnlyList<IJobHandler> CreateJobHandlers(AppServices services) =>
[
.. services.Archives?.CreateJobHandlers() ?? [], .. services.Processing?.CreateJobHandlers() ?? [],
.. services.Sync.Service?.CreateJobHandlers(services.Sync) ?? [],
];
/// <summary>Queues a scan of <paramref name="archive"/> unless one is already waiting or running.</summary>
public async Task QueueScanAsync(Archive archive, bool full, CancellationToken ct = default)
{
if (Engine is null || Database is null) return;
Guid previous;
lock (_scans)
{
_scans.TryGetValue(archive.Id, out previous);
}
if (previous != Guid.Empty && await Database.Jobs.GetAsync(previous, ct) is { State: JobState.Queued or JobState.Running }) return;
var job = await Engine.EnqueueAsync(ArchiveJobs.Scan(archive, full), cancellationToken: ct);
lock (_scans)
{
_scans[archive.Id] = job.Id;
}
}
public void SaveSettings()
{
SaveSettingsAction();
UpdateRenderNode();
}
/// <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)
{
try
{
Database = await Task.Run(() => TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(databasePath), ct), ct);
Log.Info("app", $"Index open (schema {Database.SchemaVersion}) at {databasePath}");
}
catch (Exception ex) when (ex is DatabaseException or System.IO.IOException or UnauthorizedAccessException or DllNotFoundException)
{
OpenError = ex;
Log.Error("app", "The index could not be opened", ex);
return;
}
await StartJobsAsync(Database, startEngine: true, ct);
Thumbnails = new ThumbnailService(Database, Settings.ThumbnailMemoryItems);
if (Settings.LastArchivePath is { Length: > 0 } root) _polling = PollAsync(root, _stopping.Token);
}
/// <summary>Uses an already open index (capture, tests) instead of opening one; sample data keeps the engine stopped.</summary>
public async Task AttachAsync(TitanoDatabase database, bool startEngine = true, CancellationToken ct = default)
{
Database = database;
await StartJobsAsync(database, startEngine, ct);
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().ConfigureAwait(false);
await _polling.ConfigureAwait(false);
_stopping.Dispose();
_server.PropertyChanged -= OnServerChanged;
await _renderNode.DisposeAsync().ConfigureAwait(false);
await Sync.DisposeAsync().ConfigureAwait(false);
(Jobs as IDisposable)?.Dispose();
if (Engine is not null) await Engine.DisposeAsync().ConfigureAwait(false);
Thumbnails?.Dispose();
Server.Dispose();
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,
/// 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).ConfigureAwait(false);
using var timer = new PeriodicTimer(ScanInterval);
do
{
if (ArchiveService.GetAvailability(archive) == ArchiveAvailability.Online) await QueueScanAsync(archive, full: false, ct).ConfigureAwait(false);
}
while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false));
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException)
{
Log.Warning("archive", $"The archive at {root} could not be opened", ex);
}
}
private async Task StartJobsAsync(TitanoDatabase database, bool startEngine, CancellationToken ct)
{
var archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateClient(new WicDecoderProvider()) };
Archives = new ArchiveService(database, archive);
Processing = new ProcessingService(database, ProcessingOptions(archive));
Sync.Open(database, Archives, archive);
var handlers = CreateJobHandlers(this);
var kinds = handlers.Select(h => h.Kind).Distinct().ToArray();
Engine = new JobEngine(database, handlers, new JobEngineOptions { WorkerId = WorkerId, Kinds = kinds });
// With no handler the engine must not run: an empty kind list would let workers claim (and fail) every job.
var started = startEngine && handlers.Count > 0;
if (started) await Engine.StartAsync(ct);
Jobs = new EngineJobQueue(database, Engine, started);
Log.Info("jobs", started ? $"Job engine started with {Engine.Options.Workers} worker(s) for {string.Join(", ", kinds)}" : "No job handlers registered; jobs stay queued");
UpdateRenderNode();
Sync.Update();
}
/// <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
{
MemoryBudget = Settings.MemoryBudgetGb is { } gb ? gb * (1L << 30) : GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / 4,
SpillDirectory = CacheStore.Folder(Environment, Settings),
},
};
private void OnServerChanged(object? sender, PropertyChangedEventArgs e)
{
UpdateRenderNode();
Sync.Update();
}
/// <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)
{
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})")
{
Token = session.Token,
};
var node = new RenderNodeClient(client, processing.Options, new RenderNodeOptions
{
ClientName = System.Environment.MachineName,
CacheDirectory = Path.Combine(cache, "render-node"),
CacheLimitBytes = Settings.CacheLimitGb * (1L << 30),
});
node.Start();
return new RunningNode(node, client);
}
/// <summary>A started node and the client it owns.</summary>
private sealed class RunningNode(RenderNodeClient node, TitanoClient client) : IRenderNode
{
public Task Completion => node.Completion;
public async ValueTask DisposeAsync()
{
await node.DisposeAsync().ConfigureAwait(false);
client.Dispose();
}
}
}