Files
Chronos/src/Titano.App/Server/SyncHost.cs
T
Claude 25653c052b feat(app): server sync table, conflict resolution, sync options and Library sync glyphs
SyncHost runs the sync agent of the signed-in session and gives transfer jobs
their connection; the Server screen lists every sequence of this PC and of the
server with its state and actions (upload, download originals, open with
proxies, keep mine / take server / save both, pause, resume), filter chips,
search, Upload all local and the comparison footer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-02 22:53:24 +00:00

138 lines
6.6 KiB
C#

using System.IO;
using Titano.App.Infrastructure;
using Titano.Core.Diagnostics;
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Sync;
using Titano.Protocol.Client;
namespace Titano.App.Server;
/// <summary>Makes the sync connection of a signed-in session.</summary>
public delegate ISyncRemote SyncRemoteFactory(Uri address, string token, IReadOnlyCollection<string> trustedFingerprints);
/// <summary>
/// This PC's sync with the signed-in server (BRIEF §4.4, §14.5): the <see cref="SyncService"/> of the index, the
/// connection of upload and download jobs (<see cref="ISyncConnector"/>) and a <see cref="SyncAgent"/> that keeps the
/// table current while a session is open, started and stopped in order as the session changes. Options come from
/// <see cref="AppSettings.SyncSettingsAutomatically"/> and <see cref="AppSettings.KeepProxiesOffline"/>.
/// </summary>
public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDisposable
{
/// <summary>How long a job resumed at start waits for the saved session to be restored.</summary>
private static readonly TimeSpan RestoreWait = TimeSpan.FromSeconds(30);
private Task _switch = Task.CompletedTask;
private Credentials? _credentials;
private (SyncAgent Agent, ISyncRemote Remote, Credentials Credentials)? _running;
/// <summary>Connections over <see cref="TitanoClient"/>; screenshots substitute a fake server.</summary>
public SyncRemoteFactory RemoteFactory { get; set; } = (address, token, trusted) =>
new TitanoSyncRemote(new TitanoClient(address, new CertificatePinning(trusted), $"Titano ({Environment.MachineName})") { Token = token }, ownsClient: true);
/// <summary>The engine; null until the index is open.</summary>
public SyncService? Service { get; private set; }
/// <summary>The background comparison of the signed-in server; null while signed out.</summary>
public SyncAgent? Agent => _running?.Agent;
/// <summary>The agent's connection, for the table's own calls (conflict resolution); null while signed out.</summary>
public ISyncRemote? Remote => _running?.Remote;
/// <summary>Key of the signed-in server (<see cref="SyncService.ServerKey"/>); null while signed out.</summary>
public string? Server => Volatile.Read(ref _credentials) is { } c ? SyncService.ServerKey(c.Address) : null;
public SyncPolicy Policy => new(services.Settings.SyncSettingsAutomatically, services.Settings.KeepProxiesOffline);
/// <summary>The agent started, stopped or compared, or the table of the signed-in server changed (any thread).</summary>
public event Action? Changed;
/// <summary>Creates the engine over the open index; the proxy cache lives in the client's cache folder.</summary>
public SyncService Open(TitanoDatabase database, Titano.Data.Archiving.ArchiveService archives, Titano.Data.Archiving.ArchiveServiceOptions options)
{
var cache = CacheStore.Folder(services.Environment, services.Settings);
Service = new SyncService(database, archives, new SyncOptions { Archive = options, ProxyCacheDirectory = Path.Combine(cache, "proxies") });
Service.Changed += server =>
{
if (server == Server) Changed?.Invoke();
};
return Service;
}
/// <summary>Follows the server session (UI thread): starts the agent for a new sign-in, stops it on sign-out.</summary>
public void Update()
{
var session = services.Server;
Credentials? wanted = session.IsConnected && session.Flow is { Address: { } address, Token: { } token }
? new Credentials(address, token, session.Fingerprints)
: null;
Volatile.Write(ref _credentials, wanted);
_switch = SwitchAsync(_switch, wanted);
}
/// <summary>Compares again soon (an option changed, an edit on this PC).</summary>
public void RequestRefresh() => Agent?.RequestRefresh();
/// <summary>The archive downloaded originals go to when a sequence has no local copy: the one this PC works with.</summary>
public async Task<Archive?> CurrentArchiveAsync(CancellationToken ct = default)
{
if (services.Database is not { } db) return null;
var archives = await db.Archives.ListAsync(ct);
if (services.Settings.LastArchivePath is { Length: > 0 } root)
{
var full = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar);
if (archives.FirstOrDefault(a => string.Equals(Path.GetFullPath(a.RootPath).TrimEnd(Path.DirectorySeparatorChar), full, StringComparison.OrdinalIgnoreCase))
is { } current) return current;
}
return archives.Count == 1 ? archives[0] : null;
}
public async ValueTask<ISyncRemote?> ConnectAsync(string server, CancellationToken cancellationToken)
{
// A job resumed at start runs before the saved session is restored: give the restore a moment.
var until = DateTime.UtcNow + RestoreWait;
while (Volatile.Read(ref _credentials) is null && services.Settings.ProtectedToken is not null && DateTime.UtcNow < until)
await Task.Delay(500, cancellationToken);
if (Volatile.Read(ref _credentials) is not { } c || SyncService.ServerKey(c.Address) != server) return null;
CacheStore.Prepare(CacheStore.Folder(services.Environment, services.Settings));
return RemoteFactory(c.Address, c.Token, c.Fingerprints);
}
public async ValueTask DisposeAsync()
{
Volatile.Write(ref _credentials, null);
await _switch;
await StopAsync();
}
private async Task SwitchAsync(Task previous, Credentials? wanted)
{
await previous;
if (_running is { } running && wanted is { } same && running.Credentials.Address == same.Address && running.Credentials.Token == same.Token) return;
await StopAsync();
if (wanted is not { } start || Service is not { } service)
{
Changed?.Invoke();
return;
}
var remote = RemoteFactory(start.Address, start.Token, start.Fingerprints);
var agent = new SyncAgent(service, remote, () => Policy, services.Engine);
agent.Changed += () => Changed?.Invoke();
agent.Start();
_running = (agent, remote, start);
Log.Info("sync", $"Comparing with {remote.Server}");
Changed?.Invoke();
}
private async Task StopAsync()
{
if (_running is not { } running) return;
_running = null;
await running.Agent.DisposeAsync();
running.Remote.Dispose();
Changed?.Invoke();
}
private sealed record Credentials(Uri Address, string Token, IReadOnlyCollection<string> Fingerprints);
}