using Chronos.Data.Projects; using System.Collections.Concurrent; using System.IO; using System.Net; using System.Net.Http; using System.Text.Json; using Chronos.Core.Advice; using Chronos.Core.Analysis; using Chronos.Core.Analysis.Deep; using Chronos.Core.Diagnostics; using Chronos.Core.Imaging; using Chronos.Core.Localization; using Chronos.Core.Model; using Chronos.Core.Project; using Chronos.Core.Render; using Chronos.Data.Archiving.Jobs; using Chronos.Data.Jobs; using Chronos.Data.Sync; using Chronos.Protocol; using Chronos.Protocol.Client; namespace Chronos.App.Editor; /// /// A server sequence opened with proxies (BRIEF §4.4, §14.5 "edit with proxies, render where the originals are"): /// frames and thumbnails from this PC's proxy cache (), the project from the /// server's settings with their version, the deep analysis from the server's report. Saves send the settings with the /// version they were made from; a 409 (someone changed them meanwhile) reads the server's settings and merges again /// () when the two changes touch different settings. A setting both changed to different /// values is a conflict the user settles (BRIEF §14.5 "explicit conflict prompt"): , /// and nothing is sent until the editor's next save names the server's settings as its basis. Nothing is written to a /// local archive. Analyses and renders are server jobs; their state and progress come from the server's events. /// Project settings name frames by position, so the cached frames must be the server's: a load that finds other frames /// throws , and frames that change on the server while the sequence is open make /// it (read-only, nothing saved or rendered). Saves name the frames version the editor's frames /// are at, so the server refuses one made against frames it no longer has even before its event arrives. /// public sealed class RemoteSequenceSource : ISequenceSource { private const int SaveAttempts = 3; private readonly RemoteSequence _remote; private readonly IRemoteSequenceApi _api; private readonly IRenderFrameSource _frames; private readonly IFrameSource _pixels; private readonly ServerJobs _jobs; private readonly bool _noEditRight; private readonly int _serverFormat; private Stored? _stored; private int _framesVersion = -1; private int _outdated; private int _disposed; /// The account may look at the sequence but not change it (no Edit right on the server). /// /// The highest settings format the server reads (; an older server's 1): settings /// that need more are never sent to it (owner review 1, phase 4), it would store them and then fail every render of them. /// public RemoteSequenceSource(RemoteSequence remote, IRemoteSequenceApi api, ImageDecoder decoder, bool readOnly = false, int serverFormat = ProjectSettings.CurrentVersion) { ArgumentNullException.ThrowIfNull(remote); ArgumentNullException.ThrowIfNull(api); ArgumentNullException.ThrowIfNull(decoder); _remote = remote; _api = api; _noEditRight = readOnly; _serverFormat = serverFormat; _frames = remote.OpenFrames(decoder); _pixels = (IFrameSource)_frames; _jobs = new ServerJobs(api, remote.Sequence.Id, remote.Sequence.DisplayTitle, job => JobChanged?.Invoke(job), OnEventAsync, OnReconnectedAsync); } public bool IsRemote => true; public bool IsReadOnly => _noEditRight || IsOutdated; public bool IsOutdated => Volatile.Read(ref _outdated) == 1; public event Action? ReadOnlyChanged; public event Action? JobChanged; /// The server sequence's id. public Guid Id => _remote.Sequence.Id; public async Task LoadAsync(CancellationToken cancellationToken) { var dto = await Call(() => _api.GetSequenceAsync(Id, cancellationToken)); var manifest = await Call(() => _api.GetManifestAsync(Id, cancellationToken)); if (!SameFrames(manifest)) throw Outdated(); Volatile.Write(ref _framesVersion, manifest.FramesVersion); var report = await Call(() => _api.GetAnalysisReportAsync(Id, cancellationToken)); return await Task.Run(() => { var project = Parse(manifest.SettingsJson); Volatile.Write(ref _stored, new Stored(project, manifest.SettingsVersion)); var frames = _remote.Frames; var sequence = _remote.Sequence with { Title = dto.Title, Tags = dto.Tags, Rating = dto.Rating, Notes = dto.Notes, Status = (SequenceStatus)dto.Status, RenderedCount = dto.RenderedCount, HeroFrameId = dto.HeroFrameId, WarningCount = dto.WarningCount, PreviewOnlyCount = dto.PreviewOnlyCount, SettingsJson = manifest.SettingsJson, SettingsVersion = manifest.SettingsVersion, UpdatedAt = dto.UpdatedAt, }; var context = SequenceContext.FromFrames(frames); var renders = manifest.Renders.OrderByDescending(r => r.Created).Select(r => new Render { Id = r.Id, SequenceId = Id, PresetName = r.PresetName, OutputPath = string.Empty, Codec = r.Codec, Width = r.Width, Height = r.Height, Fps = r.Fps, DurationSeconds = r.DurationSeconds, Bytes = r.Bytes, Created = r.Created, ProducedBy = r.ProducedBy, Sha256 = r.Sha256, Kind = r.Kind, }).ToList(); var (deep, otherFrames) = Report(report, frames.Count); return new SequenceContent(sequence, frames, project, LightAnalyzer.Analyze(frames), deep, context.SourceWidth, context.SourceHeight, null, renders, []) { DeepOfOtherFrames = otherFrames, }; }, cancellationToken); } /// Read from the server's manifest: a sequence whose frames are not this PC's becomes outdated. public async Task FramesCurrentAsync(CancellationToken cancellationToken) { if (IsOutdated) return false; return Compare(await Call(() => _api.GetManifestAsync(Id, cancellationToken))); } public async ValueTask DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken) { if ((uint)index >= (uint)_remote.Frames.Count) return null; // The loader decodes synchronously: an async delegate keeps a superseded decode's cancellation in user code (R4). return await Task.Run(async () => await _pixels.LoadAsync(index, maxLongEdge, cancellationToken).ConfigureAwait(false), cancellationToken); } public async Task SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(project); ArgumentNullException.ThrowIfNull(basis); for (var attempt = 1; ; attempt++) { var (stored, version) = Volatile.Read(ref _stored) ?? throw new InvalidOperationException("LoadAsync first."); var changedThere = !ProjectMerge.SameValues(stored, basis); var merged = changedThere ? ProjectMerge.Merge(basis, project, stored) : project; if (ProjectMerge.SameValues(merged, stored)) return merged; if (IsOutdated) throw new ProxiesOutdatedException(Loc.L("Editor.Error.FramesChanged")); if (_noEditRight) throw new EditorException(Loc.L("Editor.Error.RemoteReadOnly")); // A turn, a mirror, a straighten or a look needs format 2, which an older server cannot read: kept here (the // toast says why) until the edit is undone or the server is updated. if (ServerJobs.NeedsNewerServer(merged.WrittenFormat, _serverFormat) is { } newer) throw new EditorException(newer); if (changedThere && ProjectMerge.Conflicts(basis, project, stored) is { Count: > 0 } conflicts) throw new ProjectConflictException(Loc.L("Editor.Error.SaveConflict"), stored, conflicts); var hero = merged.HeroFrame == stored.HeroFrame ? (Guid?)null : HeroFrameId(merged); // The positions name the frames this editor holds: the server refuses them (409 frames_conflict) once its // frames changed, also before its event says so. A server that predates the check ignores it. var request = new UpdateSequenceRequest(null, null, null, null, merged.ToJson(), version, hero, Volatile.Read(ref _framesVersion)); try { var updated = await Call(() => _api.UpdateSequenceAsync(Id, request, cancellationToken)); Volatile.Write(ref _stored, new Stored(merged, updated.SettingsVersion)); return merged; } catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.Conflict) { // Changed on the server since this editor read it, its settings or its frames: other frames make the // editor outdated (its proxies are not the server's), otherwise the edit merges again on top of the // server's settings, at the frames version they are at. var manifest = await Call(() => _api.GetManifestAsync(Id, cancellationToken)); if (!SameFrames(manifest)) throw Outdated(); if (attempt == SaveAttempts) throw new EditorException(Loc.L("Editor.Error.SaveConflict"), ex); Volatile.Write(ref _framesVersion, manifest.FramesVersion); Volatile.Write(ref _stored, new Stored(Parse(manifest.SettingsJson), manifest.SettingsVersion)); } } } /// /// The server queues every job at the user's priority; another priority ("Add to queue") is set right after. A /// render embeds the project, whose frame positions mean nothing once the frames changed: refused while outdated. /// public Task SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(request); if (request.Kind == JobKind.Render && IsOutdated) throw new ProxiesOutdatedException(Loc.L("Editor.Error.FramesChanged")); return _jobs.SubmitAsync(request, cancellationToken); } public Task> ListJobsAsync(CancellationToken cancellationToken) => _jobs.ListAsync(cancellationToken); public Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken) => _jobs.CancelAsync(jobId, cancellationToken); public Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken) => _jobs.RetryAsync(jobId, cancellationToken); public async ValueTask DisposeAsync() { if (Interlocked.Exchange(ref _disposed, 1) == 1) return; try { // Stops following the events, and closes the connection. await _jobs.DisposeAsync(); } finally { if (_frames is IAsyncDisposable frames) await frames.DisposeAsync(); } } /// The server's events besides the jobs': frames added or removed on the server make the sequence outdated. private async Task OnEventAsync(ServerEvent e, CancellationToken cancellationToken) { if (e is SequenceChangedEvent changed && changed.SequenceId == Id && changed.FramesVersion != Volatile.Read(ref _framesVersion)) await CheckFramesAsync(cancellationToken).ConfigureAwait(false); } /// A frames change announced while the event socket was down is found now rather than at the next save. private async Task OnReconnectedAsync(CancellationToken cancellationToken) { if (Volatile.Read(ref _framesVersion) >= 0) await CheckFramesAsync(cancellationToken).ConfigureAwait(false); } /// Frames added or removed on the server: whether this PC's frames are still the sequence's. private async Task CheckFramesAsync(CancellationToken cancellationToken) { try { Compare(await _api.GetManifestAsync(Id, cancellationToken).ConfigureAwait(false)); } catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or JsonException || (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested)) { Log.Info("editor", $"The frames of {_remote.Sequence.DisplayTitle} could not be compared: {ex.Message}"); } } /// /// Takes the server's frames as lists them: their frames version when they are this PC's /// (saves name it), outdated otherwise. Returns whether they are. /// private bool Compare(SequenceManifest manifest) { if (!SameFrames(manifest)) { MarkOutdated(); return false; } Volatile.Write(ref _framesVersion, manifest.FramesVersion); return true; } /// The server's frames are the cached ones, in the same order (frame positions in the project mean the same frames). private bool SameFrames(SequenceManifest manifest) => manifest.Frames.OrderBy(f => f.Index).Select(f => f.Id).SequenceEqual(_remote.Frames.Select(f => f.Id)); /// The frames changed on the server: from now on the project is only shown. private ProxiesOutdatedException Outdated() { MarkOutdated(); return new ProxiesOutdatedException(Loc.L("Editor.Error.FramesChanged")); } private void MarkOutdated() { if (Interlocked.Exchange(ref _outdated, 1) == 1) return; Log.Info("editor", $"The frames of {_remote.Sequence.DisplayTitle} changed on the server; its proxies are out of date"); ReadOnlyChanged?.Invoke(); } /// The frame of the project's hero, or (the first frame shows) without one. private Guid HeroFrameId(ProjectSettings project) => project.HeroFrame is { } hero && (uint)hero < (uint)_remote.Frames.Count ? _remote.Frames[hero].Id : Guid.Empty; /// The settings are not a project or come from a newer Chronos. private static ProjectSettings Parse(string? json) { if (string.IsNullOrWhiteSpace(json)) return new ProjectSettings(); try { return ProjectSettings.FromJson(json); } catch (Exception ex) when (ex is JsonException or InvalidDataException) { throw new EditorException(Loc.L("Editor.Error.Project"), ex); } } /// The server's deep report when it describes the frames this PC has; whether one of another number of frames came instead. private (DeepAnalysisReport? Report, bool OtherFrames) Report(string? json, int frameCount) { if (json is null) return (null, false); try { var report = DeepAnalysisReport.FromJson(json); return report.FrameCount == frameCount ? (report, false) : (null, true); } catch (Exception ex) when (ex is JsonException or InvalidDataException) { Log.Warning("editor", $"The analysis of {_remote.Sequence.DisplayTitle} on the server cannot be read", ex); return (null, false); } } /// A sequence deleted on the server reads as gone, like a local one removed from the index. private static Task Call(Func> call) => ServerJobs.Call(call); /// The server's settings as last read or written, with the version a save must name. private sealed record Stored(ProjectSettings Project, int Version); } /// /// Settings the editor changed were changed to other values on the server meanwhile (BRIEF §14.5): nothing is saved /// until the user keeps the editor's values or takes the server's (). /// /// The server's project now. /// The settings both changed: the editor's value, then the server's. public sealed class ProjectConflictException(string message, ProjectSettings server, IReadOnlyList differences) : IOException(message) { public ProjectSettings Server { get; } = server; public IReadOnlyList Differences { get; } = differences; } /// /// The proxies of a server sequence are for frames the server no longer has (added or removed since they were fetched): /// they must be fetched again before the sequence can be edited. /// public sealed class ProxiesOutdatedException(string message) : EditorException(message);