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; /// Makes the sync connection of a signed-in session. public delegate ISyncRemote SyncRemoteFactory(Uri address, string token, IReadOnlyCollection trustedFingerprints); /// /// This PC's sync with the signed-in server (BRIEF §4.4, §14.5): the of the index, the /// connection of upload and download jobs () and a that keeps the /// table current while a session is open, started and stopped in order as the session changes. Options come from /// and . /// public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDisposable { /// How long a job resumed at start waits for the saved session to be restored. private static readonly TimeSpan RestoreWait = TimeSpan.FromSeconds(30); private Task _switch = Task.CompletedTask; private Credentials? _credentials; private (SyncAgent Agent, ISyncRemote Remote, Credentials Credentials)? _running; /// Connections over ; screenshots substitute a fake server. public SyncRemoteFactory RemoteFactory { get; set; } = (address, token, trusted) => new TitanoSyncRemote(new TitanoClient(address, new CertificatePinning(trusted), $"Titano ({Environment.MachineName})") { Token = token }, ownsClient: true); /// The engine; null until the index is open. public SyncService? Service { get; private set; } /// The background comparison of the signed-in server; null while signed out. public SyncAgent? Agent => _running?.Agent; /// The agent's connection, for the table's own calls (conflict resolution); null while signed out. public ISyncRemote? Remote => _running?.Remote; /// Key of the signed-in server (); null while signed out. public string? Server => Volatile.Read(ref _credentials) is { } c ? SyncService.ServerKey(c.Address) : null; public SyncPolicy Policy => new(services.Settings.SyncSettingsAutomatically, services.Settings.KeepProxiesOffline); /// The agent started, stopped or compared, or the table of the signed-in server changed (any thread). public event Action? Changed; /// Creates the engine over the open index; the proxy cache lives in the client's cache folder. 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; } /// Follows the server session (UI thread): starts the agent for a new sign-in, stops it on sign-out. 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); } /// Compares again soon (an option changed, an edit on this PC). public void RequestRefresh() => Agent?.RequestRefresh(); /// The archive downloaded originals go to when a sequence has no local copy: the one this PC works with. public async Task 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 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 Fingerprints); }