using System.IO; using Titano.App.Editor; using Titano.App.Infrastructure; using Titano.Core.Diagnostics; using Titano.Core.Model; using Titano.Data; using Titano.Data.Jobs; 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 (), a that keeps the /// table current while a session is open, started and stopped in order as the session changes, the /// for metered connections, the connections of editors of server sequences /// () and the Export "Sync" of finished renders (). 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; private JobEngine? _renders; /// 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); /// Connections of editors of server sequences over ; screenshots substitute a fake server. public RemoteSequenceApiFactory EditorFactory { get; set; } = (address, token, trusted) => new TitanoRemoteSequenceApi(new TitanoClient(address, new CertificatePinning(trusted), $"Titano ({Environment.MachineName})") { Token = token }); /// 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; /// The options, and whether the account may change server sequences (without it this PC's edits are not sent). public SyncPolicy Policy => new(services.Settings.SyncSettingsAutomatically, services.Settings.KeepProxiesOffline, Allows(Permissions.Edit)); /// The signed-in account may send files (originals, renders) to the server. public bool CanUpload => Allows(Permissions.Upload); /// The signed-in account may queue renders on the server. public bool CanRender => Allows(Permissions.Render); /// Pauses uploads while the connection is metered and the option is on. public UploadHold Uploads { get; } = new(services); /// 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); if (services.Engine is not { } engine) return; Uploads.Attach(engine); if (ReferenceEquals(_renders, engine)) return; if (_renders is not null) _renders.JobChanged -= OnJobChanged; _renders = engine; engine.JobChanged += OnJobChanged; } /// A connection for the editor of a sequence of the signed-in server; null while signed out. public IRemoteSequenceApi? ConnectEditor() => Volatile.Read(ref _credentials) is { } c ? EditorFactory(c.Address, c.Token, c.Fingerprints) : null; /// Compares now, once the session switch in progress settled; null while signed out. public async Task RefreshAsync(CancellationToken ct = default) { await _switch; return Agent is { } agent ? await agent.RefreshAsync(ct) : null; } /// 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); Uploads.Dispose(); if (_renders is not null) _renders.JobChanged -= OnJobChanged; await _switch; await StopAsync(); } private bool Allows(Permissions permission) => services.Server.User is { } user && (user.Permissions & (long)permission) != 0; /// /// Export "Sync": a render of this PC that asked for it is sent to the server once done (), /// also when it ends while the session is down: the send is queued for the saved session's server and waits for it. /// private void OnJobChanged(Job job) { if (job is not { Kind: JobKind.Render, State: JobState.Done } || Service is not { } service || services.Database is not { } db || _renders is not { } engine) return; var signedIn = Server; _ = SendRenderAsync(new ExportSync(db, service, engine), job, signedIn ?? SavedServer(), signedIn is null || CanUpload); } /// Key of the server of the saved session (Disconnect keeps it); null without one. private string? SavedServer() => services.Server.HasSavedSession && ServerAddress.TryParse(services.Settings.ServerUrl, out var address) ? SyncService.ServerKey(address) : null; private static async Task SendRenderAsync(ExportSync exports, Job job, string? server, bool canUpload) { try { switch (await exports.SendAsync(job, server, canUpload)) { case { Send: { } send }: Log.Info("sync", $"{job.TargetLabel} will be sent to the server (job {send.Id})"); break; case { Gate: var gate }: Log.Warning("sync", $"{job.TargetLabel} asked to be sent to the server but was not ({gate})"); break; } } catch (Exception ex) when (ex is not OutOfMemoryException) { // Nobody awaits this: the render itself succeeded, and the send can be asked for again on the Server screen. Log.Warning("sync", $"The render {job.TargetLabel} could not be queued for the server", ex); } } 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); }