Files
Chronos/src/Titano.App/Server/SyncHost.cs
T
Claude 757695f037 fix(editor): server jobs, stale proxies and read-only accounts in the remote editor
- A server sequence whose cached frames are no longer the server's (a load, a 409
  merge or a frames change event finds other frame ids) turns read-only and says
  why; opening it, or a sequence without cached proxies, queues the proxy
  download and opens it when done. Signed out reads "Connect to the server".
- Server jobs show queued, running (with a bar), paused and analysing glyphs in
  the header with Cancel; a failed or cancelled one raises a toast with Retry.
  Progress alone no longer refreshes the whole editor.
- The server job list is read by state and kind to its last page; "Add to queue"
  sets the job's priority; the event listener survives any failure and always
  releases its frames and connection.
- An account that may render but not edit picks the preset to render without
  changing the project; preset cards and their batch boxes say why they wait.
- Export tab of a server sequence: no local encoder, notices or folder; no Jobs
  history link. Sync at 12 px beside a folder that keeps 96 px and trims.
- Restore's Undo puts back the project from before the restore, only while that
  restore is the editor's last change.
- Export "Sync" of a render that ends while the session is down is queued for the
  saved session's server; skips are logged; sync follows the engine before it
  starts.
- Capture: sequence-remote-export, -running and -readonly, and
  sequence-export-copies.

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

216 lines
11 KiB
C#

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;
/// <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"/>), a <see cref="SyncAgent"/> that keeps the
/// table current while a session is open, started and stopped in order as the session changes, the
/// <see cref="UploadHold"/> for metered connections, the connections of editors of server sequences
/// (<see cref="ConnectEditor"/>) and the Export "Sync" of finished renders (<see cref="ExportSync"/>). Options come from
/// <see cref="AppSettings.SyncSettingsAutomatically"/>, <see cref="AppSettings.KeepProxiesOffline"/> and
/// <see cref="AppSettings.PauseUploadsOnMetered"/>.
/// </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;
private JobEngine? _renders;
/// <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>Connections of editors of server sequences over <see cref="TitanoClient"/>; screenshots substitute a fake server.</summary>
public RemoteSequenceApiFactory EditorFactory { get; set; } = (address, token, trusted) =>
new TitanoRemoteSequenceApi(new TitanoClient(address, new CertificatePinning(trusted), $"Titano ({Environment.MachineName})") { Token = token });
/// <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;
/// <summary>The options, and whether the account may change server sequences (without it this PC's edits are not sent).</summary>
public SyncPolicy Policy => new(services.Settings.SyncSettingsAutomatically, services.Settings.KeepProxiesOffline, Allows(Permissions.Edit));
/// <summary>The signed-in account may send files (originals, renders) to the server.</summary>
public bool CanUpload => Allows(Permissions.Upload);
/// <summary>The signed-in account may queue renders on the server.</summary>
public bool CanRender => Allows(Permissions.Render);
/// <summary>Pauses uploads while the connection is metered and the option is on.</summary>
public UploadHold Uploads { get; } = new(services);
/// <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);
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;
}
/// <summary>A connection for the editor of a sequence of the signed-in server; null while signed out.</summary>
public IRemoteSequenceApi? ConnectEditor() =>
Volatile.Read(ref _credentials) is { } c ? EditorFactory(c.Address, c.Token, c.Fingerprints) : null;
/// <summary>Compares now, once the session switch in progress settled; null while signed out.</summary>
public async Task<SyncSnapshot?> RefreshAsync(CancellationToken ct = default)
{
await _switch;
return Agent is { } agent ? await agent.RefreshAsync(ct) : null;
}
/// <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);
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;
/// <summary>
/// Export "Sync": a render of this PC that asked for it is sent to the server once done (<see cref="ExportSync"/>),
/// also when it ends while the session is down: the send is queued for the saved session's server and waits for it.
/// </summary>
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);
}
/// <summary>Key of the server of the saved session (Disconnect keeps it); null without one.</summary>
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<string> Fingerprints);
}