feat: owner review 2 phase 5b: the server as a project home (#17)
CI / Build and test (push) Successful in 9m58s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 14m8s
CI / PostgreSQL 16 integration (push) Successful in 8m55s
CI / PostgreSQL 17 integration (push) Successful in 8m50s
CI / Docker image (push) Successful in 57s
Release / Server image (push) Successful in 1m22s

A Chronos Server keeps its sequences' projects, as a PC's archive does: Main and named projects with versions under /api/v1/sequences/{id}/projects, the projects capability and the projectChanged event. The desktop opens a server's sequences in the workspace (proxies downloaded, hash-checked, resumable) with Save version, Sync, conflicts, History, Restore and the project actions against the server. Renders can be of a project version. The admin panel lists a sequence's projects and versions. Strings in all 38 languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #17.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-11-04 14:58:11 +01:00
1 parent 255e149087
commit 81c303f484
325 files changed
+11477 -516

No files matched your search

+290 -16
View File
@@ -19,6 +19,8 @@ using Chronos.Data.Processing;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
using Chronos.Protocol;
using Chronos.Protocol.Client;
using SequenceManifest = Chronos.Protocol.SequenceManifest;
namespace Chronos.App.Editor;
@@ -29,6 +31,27 @@ public interface IProjectRenders
IReadOnlyList<ArchiveJobRequest> RenderRequests(Sequence sequence, ProjectSettings project, ExportSettings export, int sourceWidth, int sourceHeight);
}
/// <summary>
/// A workspace project's home when it is a server (owner review 2, R8, phase 5b): how the source connects for its analyses
/// and renders (<paramref name="connect"/>: a connection the source owns, null while this PC is not signed in to that
/// server, when the project still opens from the workspace and its jobs are refused saying so), and the sign-in it would
/// connect with (<paramref name="session"/>): when that changes (signed in, out, or anew), the source connects again.
/// </summary>
public sealed class WorkspaceServerHome(Func<IRemoteSequenceApi?> connect, Func<object?> session)
{
/// <summary>One connection for good (null: never signed in), as a test or a capture holds it.</summary>
public WorkspaceServerHome(IRemoteSequenceApi? api)
: this(() => api, () => api)
{
}
/// <summary>The sign-in <see cref="Connect"/> would use now; compared by reference.</summary>
public object? Session => session();
/// <summary>A new connection of the current sign-in; null while signed out.</summary>
public IRemoteSequenceApi? Connect() => connect();
}
/// <summary>
/// A workspace project open in the editor (owner review 2, R8: editing happens in the workspace, never inside the
/// library): the frames and pixels of the media the workspace holds (<c>media/media.json</c>, the proxies), the project
@@ -42,6 +65,11 @@ public interface IProjectRenders
/// (<see cref="RenderRequests"/>). The deep report is the home's while its frames are the media's, else the copy the
/// workspace took. A copy job that changed the media (Update media) makes saves made against the frames read before refused
/// (<see cref="FramesChangedException"/>) until the editor has read them again and moved its positions by frame.
/// A project whose home is a server (<see cref="WorkspaceServerHome"/>, phase 5b) is a remote one for the editor: its
/// analyses and renders are the server's jobs (<see cref="ServerJobs"/>), a render of the version the server holds when the
/// project is in step with it (else of the project's portable settings, recording the project), its deep report and renders
/// are read from the server when it can be reached (else the copy the workspace took), and "Update media" is offered when
/// the server's frames moved, or it has the proxy of a frame a thumbnail stands in for.
/// </summary>
public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
{
@@ -51,19 +79,26 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
private readonly ChronosDatabase _db;
private readonly ImageDecoder _decoder;
private readonly JobEngine? _engine;
private readonly WorkspaceServerHome? _server;
private readonly Lock _gate = new();
private readonly List<IRenderFrameSource> _retired = [];
private IRenderFrameSource? _frames;
private IFrameSource? _pixels;
private ServerJobs? _serverJobs;
private IRemoteSequenceApi? _api;
private object? _apiSession;
private bool _connected;
private int _frameCount;
private int _framesVersion = -1;
private Guid[] _frameIds = [];
private HashSet<Guid> _standIns = [];
private FramePhotos _photos = new([]);
private BundleWorkspace? _workspace;
private bool _readOnly;
private int _disposed;
public WorkspaceSequenceSource(WorkspaceSync sync, Guid projectId, ChronosDatabase db, ImageDecoder decoder, JobEngine? engine)
/// <param name="server">The server the project's home is (phase 5b); null for a project of this PC's archive.</param>
public WorkspaceSequenceSource(WorkspaceSync sync, Guid projectId, ChronosDatabase db, ImageDecoder decoder, JobEngine? engine, WorkspaceServerHome? server = null)
{
ArgumentNullException.ThrowIfNull(sync);
ArgumentNullException.ThrowIfNull(db);
@@ -72,7 +107,9 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
_db = db;
_decoder = decoder;
_engine = engine;
_server = server;
ProjectId = projectId;
// This PC's engine runs the copies of the media (Update media), whatever the home.
if (engine is not null) engine.JobChanged += OnJobChanged;
}
@@ -90,7 +127,11 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
/// <summary>The photos of the media read last, in frame order (what positions name).</summary>
public FramePhotos Photos => Volatile.Read(ref _photos);
public bool IsRemote => false;
/// <summary>The project's home is a server (phase 5b): its analyses and renders run there.</summary>
public bool IsServerHome => _server is not null;
/// <summary>A server home's analyses and renders run on the server, as for a server sequence opened with proxies.</summary>
public bool IsRemote => _server is not null;
/// <summary>Settings of a newer Chronos: shown, never saved.</summary>
public bool IsReadOnly => Volatile.Read(ref _readOnly);
@@ -132,6 +173,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
}
if (session is not { Sequence: { } media, Media: { } index }) throw new EditorException(Loc.L("Errors.Workspace.MediaMissing"));
var home = session.Bundle.Workspace!.Home;
if (_server is not null) return await LoadFromServerAsync(session, media, index, home, cancellationToken);
var row = await _db.Sequences.GetAsync(home.SequenceId, cancellationToken);
var archive = row is null ? null : await _db.Archives.GetAsync(row.ArchiveId, cancellationToken);
IReadOnlyList<Render> renders = row is null ? [] : await _db.Renders.ListBySequenceAsync(home.SequenceId, cancellationToken);
@@ -160,6 +202,148 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
}, cancellationToken);
}
/// <summary>
/// A project whose home is a server: the media's frames and the working state as for any workspace project, with what
/// the server says of its sequence when it can be reached (title, camera, tags, renders, and its deep report while its
/// frames are the media's); the copy the workspace took of the report otherwise. The server's jobs are followed from
/// the first read on.
/// </summary>
private async Task<SequenceContent> LoadFromServerAsync(WorkspaceSession session, WorkspaceSequence media, WorkspaceMedia index, BundleHome home,
CancellationToken cancellationToken)
{
var jobs = ServerJobsOf(home.SequenceId, session.Bundle.Sequence.Title ?? media.Sequence.DisplayTitle);
SequenceDto? dto = null;
SequenceManifest? manifest = null;
string? report = null;
if (jobs is not null)
{
try
{
dto = await jobs.Api.GetSequenceAsync(home.SequenceId, cancellationToken);
manifest = await jobs.Api.GetManifestAsync(home.SequenceId, cancellationToken);
// The server's report only while its frames are the ones this workspace holds.
if (manifest.FramesVersion == index.FramesVersion) report = await jobs.Api.GetAnalysisReportAsync(home.SequenceId, cancellationToken);
}
catch (Exception ex) when (ServerProjectHome.IsUnavailable(ex, cancellationToken) || ex is ChronosApiException)
{
// Out of reach (or the sequence gone there): the workspace's own copy opens all the same.
Log.Info("editor", $"The server's view of workspace project {ProjectId} is not read now: {ex.Message}");
}
}
return await Task.Run(() =>
{
var frames = media.Frames;
Swap(media, index, session.Bundle.Workspace!, session.IsReadOnly);
var times = frames.Where(f => f.CapturedAt is not null).Select(f => f.CapturedAt!.Value).Order().ToList();
var sequence = media.Sequence with
{
FrameCount = frames.Count,
FramesVersion = index.FramesVersion,
FirstCapture = times.Count > 0 ? times[0] : null,
LastCapture = times.Count > 0 ? times[^1] : null,
SettingsJson = session.Working.ToJson(),
};
if (dto is not null)
{
sequence = sequence with
{
Title = dto.Title,
CameraMake = dto.CameraMake,
CameraModel = dto.CameraModel,
Lens = dto.Lens,
MedianInterval = dto.MedianInterval,
Tags = dto.Tags,
Rating = dto.Rating,
Notes = dto.Notes,
Status = (SequenceStatus)dto.Status,
RenderedCount = dto.RenderedCount,
WarningCount = dto.WarningCount,
PreviewOnlyCount = dto.PreviewOnlyCount,
OwnerUserId = dto.OwnerUserId,
UpdatedAt = dto.UpdatedAt,
};
}
var renders = manifest?.Renders.OrderByDescending(r => r.Created).Select(r => new Render
{
Id = r.Id,
SequenceId = home.SequenceId,
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,
}).ToList() ?? [];
var (deep, otherFrames) = ServerReport(report, session.Project.AnalysisPath, frames.Count);
var context = SequenceContext.FromFrames(frames);
return new SequenceContent(sequence, frames, session.Working, LightAnalyzer.Analyze(frames), deep, context.SourceWidth, context.SourceHeight, null, renders, [])
{
DeepOfOtherFrames = otherFrames,
};
}, cancellationToken);
}
/// <summary>The server's jobs of the sequence, followed from now on; null while this PC is not signed in to the server.</summary>
private ServerJobs? ServerJobsOf(Guid sequenceId, string title)
{
if (Api() is not { } api) return null;
lock (_gate)
{
if (Volatile.Read(ref _disposed) == 1 || !ReferenceEquals(api, _api)) return null;
return _serverJobs ??= new ServerJobs(api, sequenceId, title, job => JobChanged?.Invoke(job));
}
}
/// <summary>
/// The connection of the sign-in in use now: made at first use, and again once the sign-in changed (the jobs followed
/// on the old one stop with it, so a project opened signed out renders once signed in); null while signed out.
/// </summary>
private IRemoteSequenceApi? Api()
{
if (_server is null) return null;
var session = _server.Session;
IRemoteSequenceApi? api, stale;
ServerJobs? staleJobs;
lock (_gate)
{
if (Volatile.Read(ref _disposed) == 1) return null;
if (_connected && ReferenceEquals(session, _apiSession)) return _api;
(stale, staleJobs) = (_api, _serverJobs);
_serverJobs = null;
_api = api = _server.Connect();
(_apiSession, _connected) = (session, true);
}
// The jobs own their connection.
if (staleJobs is not null) _ = staleJobs.DisposeAsync().AsTask();
else stale?.Dispose();
return api;
}
/// <summary>The server's deep report when it describes these frames, else the copy the workspace took; whether one of another number of frames was read instead.</summary>
private static (DeepAnalysisReport? Report, bool OtherFrames) ServerReport(string? json, string copied, int frameCount)
{
var otherFrames = false;
if (json is not null)
{
try
{
var report = DeepAnalysisReport.FromJson(json);
if (report.FrameCount == frameCount) return (report, false);
otherFrames = true;
}
catch (Exception ex) when (ex is JsonException or InvalidDataException)
{
Log.Warning("editor", "The server's deep report cannot be read; the workspace's copy is shown", ex);
}
}
var (deep, other) = ReadReport(null, false, copied, frameCount);
return (deep, deep is null && (other || otherFrames));
}
/// <remarks>Only a copy job changes the workspace's frames (Update media): its media index is compared with the one read last.</remarks>
public Task<bool> FramesCurrentAsync(CancellationToken cancellationToken) => Task.Run(() =>
{
@@ -175,11 +359,26 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
}
}, cancellationToken);
/// <summary>Whether the home's frames moved past those the workspace holds (frames added or removed there): "Update media" copies them again.</summary>
/// <summary>
/// Whether the home's frames moved past those the workspace holds (frames added or removed there), or a server now has
/// the proxy of a frame a thumbnail stands in for here: "Update media" copies them again. A server out of reach says no.
/// </summary>
public async Task<bool> HomeFramesChangedAsync(CancellationToken cancellationToken)
{
if (Workspace is not { } workspace || MediaFramesVersion < 0) return false;
return await _db.Sequences.GetAsync(workspace.Home.SequenceId, cancellationToken) is { } row && row.FramesVersion != MediaFramesVersion;
if (_server is null) return await _db.Sequences.GetAsync(workspace.Home.SequenceId, cancellationToken) is { } row && row.FramesVersion != MediaFramesVersion;
if (Api() is not { } api) return false;
try
{
if ((await api.GetSequenceAsync(workspace.Home.SequenceId, cancellationToken)).FramesVersion != MediaFramesVersion) return true;
var standIns = Volatile.Read(ref _standIns);
return standIns.Count > 0 && (await api.GetManifestAsync(workspace.Home.SequenceId, cancellationToken)).Frames.Any(f => f.HasProxy && standIns.Contains(f.Id));
}
catch (Exception ex) when (ServerProjectHome.IsUnavailable(ex, cancellationToken) || ex is ChronosApiException)
{
Log.Info("editor", $"The server's frames of workspace project {ProjectId} could not be compared: {ex.Message}");
return false;
}
}
public async ValueTask<ImageBuffer?> DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
@@ -293,27 +492,48 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
private static bool NamesPosition(string path) =>
path is "excludedFrames" or "heroFrame" || path.StartsWith("camera.keyframes", StringComparison.Ordinal) || path.StartsWith("pendingFrames", StringComparison.Ordinal);
/// <remarks>A project whose home is a server queues its analyses and renders there; while this PC is not signed in to it, they are refused saying so.</remarks>
public async Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken)
{
if (_server is not null) return await ServerJobsOrThrow().SubmitAsync(request, cancellationToken);
if (_engine is null) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
var job = await _engine.EnqueueAsync(request, cancellationToken: cancellationToken);
return job.Id;
}
public async Task<IReadOnlyList<Job>> ListJobsAsync(CancellationToken cancellationToken) =>
(await _db.Jobs.ListAsync(null, JobsListed, null, cancellationToken)).Items;
/// <remarks>A server home's jobs are the server's; none are listed while it cannot be reached (the project opens all the same).</remarks>
public async Task<IReadOnlyList<Job>> ListJobsAsync(CancellationToken cancellationToken)
{
if (_server is null) return (await _db.Jobs.ListAsync(null, JobsListed, null, cancellationToken)).Items;
if (Api() is null || Volatile.Read(ref _serverJobs) is not { } jobs) return [];
try
{
return await jobs.ListAsync(cancellationToken);
}
catch (Exception ex) when (ServerProjectHome.IsUnavailable(ex, cancellationToken) || ex is ChronosApiException or EditorException)
{
Log.Info("editor", $"The server's jobs of workspace project {ProjectId} are not read now: {ex.Message}");
return [];
}
}
public Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken) =>
(_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).CancelAsync(jobId, cancellationToken);
public Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken) => _server is not null
? ServerJobsOrThrow().CancelAsync(jobId, cancellationToken)
: (_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).CancelAsync(jobId, cancellationToken);
public Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken) =>
(_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).ResumeAsync(jobId, cancellationToken);
public Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken) => _server is not null
? ServerJobsOrThrow().RetryAsync(jobId, cancellationToken)
: (_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).ResumeAsync(jobId, cancellationToken);
/// <summary>
/// The render at the home (owner review 2, R8: edit with proxies, render where the originals are): one job of this PC's
/// engine per preset, with the project's portable settings (positions parked by photo, placed on the home's frames by
/// the render) and the project recorded on the render; the version too when the settings are those of the last
/// version the home holds (an unsaved working state, or one saved here and not sent yet, renders as it is, without a version).
/// The render at the home (owner review 2, R8: edit with proxies, render where the originals are): one job per preset
/// (of this PC's engine, or the server's), with the project's portable settings (positions parked by photo, placed on
/// the home's frames by the render) and the project recorded on the render; the version too when the settings are those
/// of the last version the home holds (an unsaved working state, or one saved here and not sent yet, renders as it is,
/// without a version). A server home (phase 5b) renders the version it holds when the project is in step with it
/// (nothing saved or sent since its base): the jobs name that version alone and the server renders its settings with
/// the jobs' export; a project out of step renders its portable settings, recording the project only, as a server knows
/// no version of this workspace's that it was not sent.
/// </summary>
public IReadOnlyList<ArchiveJobRequest> RenderRequests(Sequence sequence, ProjectSettings project, ExportSettings export, int sourceWidth, int sourceHeight)
{
@@ -322,8 +542,18 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
ArgumentNullException.ThrowIfNull(export);
var portable = ProjectContent.ToPortable(project with { Export = export }, Photos);
var hash = ProjectContent.Hash(portable);
if (_server is not null)
{
if (InStepWithHome(project) is { } basis)
{
var version = new ProjectVersion { Id = basis.VersionId, ProjectId = ProjectId, Number = basis.Number, SettingsJson = portable, ContentHash = hash };
return [.. ProcessingJobs.RenderVersion(sequence, version, export, sourceWidth, sourceHeight).Select(r => r with { ParametersJson = WithoutSettings(r.ParametersJson) })];
}
var unsent = new ProjectVersion { Id = Guid.Empty, ProjectId = ProjectId, Number = 0, SettingsJson = portable, ContentHash = hash };
return [.. ProcessingJobs.RenderVersion(sequence, unsent, export, sourceWidth, sourceHeight).Select(r => r with { ParametersJson = WithoutVersion(r.ParametersJson) })];
}
var (tipId, tipHash) = Tip();
var version = new ProjectVersion
var tip = new ProjectVersion
{
Id = tipId ?? Guid.Empty,
ProjectId = ProjectId,
@@ -331,29 +561,65 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
SettingsJson = portable,
ContentHash = hash,
};
var requests = ProcessingJobs.RenderVersion(sequence, version, export, sourceWidth, sourceHeight);
var requests = ProcessingJobs.RenderVersion(sequence, tip, export, sourceWidth, sourceHeight);
if (tipId is not null && string.Equals(tipHash, hash, StringComparison.OrdinalIgnoreCase)) return requests;
return [.. requests.Select(r => r with { ParametersJson = WithoutVersion(r.ParametersJson) })];
}
/// <summary>
/// The home's version the project is in step with: its base, when no version waits to be sent and the editor's project
/// (<paramref name="project"/>) holds what the base holds; null otherwise.
/// </summary>
public BundleBase? InStepWithHome(ProjectSettings project)
{
ArgumentNullException.ThrowIfNull(project);
try
{
if (_sync.Unpushed(ProjectId).Count > 0 || Project.ReadBundle().Workspace?.Base is not { } basis) return null;
var working = ProjectContent.ToPortable(project, Photos);
if (string.Equals(ProjectContent.Hash(working), basis.ContentHash, StringComparison.OrdinalIgnoreCase)) return basis;
// Saved before a hash or a conversion at the home named its photos anew: the same choices are in step too.
return Project.Versions().FirstOrDefault(v => v.Id == basis.VersionId) is { } version && ProjectContent.SameChoices(version.SettingsJson, working, Photos)
? basis
: null;
}
catch (Exception ex) when (ex is IOException or InvalidDataException or InvalidOperationException)
{
Log.Warning("editor", $"The versions of workspace project {ProjectId} cannot be read; the render names none", ex);
return null;
}
}
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) == 1) return;
if (_engine is not null) _engine.JobChanged -= OnJobChanged;
List<IRenderFrameSource> sources;
ServerJobs? jobs;
IRemoteSequenceApi? api;
lock (_gate)
{
sources = [.. _retired];
if (_frames is not null) sources.Add(_frames);
_retired.Clear();
(_frames, _pixels) = (null, null);
(jobs, _serverJobs, api, _api) = (_serverJobs, null, _api, null);
}
// The server's connection is the source's: it closes with it, also when no read made the jobs' listener.
if (jobs is not null) await jobs.DisposeAsync();
else api?.Dispose();
foreach (var source in sources)
{
if (source is IAsyncDisposable disposable) await disposable.DisposeAsync();
}
}
/// <summary>The server's jobs of the project's sequence, or why there are none.</summary>
/// <exception cref="EditorException">This PC is not signed in to the server of the project.</exception>
private ServerJobs ServerJobsOrThrow() =>
(Workspace is { } workspace ? ServerJobsOf(workspace.Home.SequenceId, Project.ReadBundle().Sequence.Title ?? string.Empty) : null)
?? throw new EditorException(Loc.L("Editor.Error.SignedOut"));
/// <summary>
/// Takes the media read now: a frame source over them when they differ from those read before (the old one is disposed
/// with this source, as a decode may still read it), their frames and photos, the project's workspace section, and
@@ -375,6 +641,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
_frameIds = ids;
_framesVersion = index.FramesVersion;
_photos = index.Photos;
_standIns = [.. index.Frames.Where(f => f.IsStandIn).Select(f => f.Id)];
_workspace = workspace;
changed = _readOnly != readOnly;
_readOnly = readOnly;
@@ -407,6 +674,13 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
return JsonSerializer.Serialize(parameters with { ProjectVersionId = null }, ProtocolJson.Default.RenderJobParameters);
}
/// <summary>A job of a version the home holds: the home renders that version's settings (with the job's export), so none travel with it.</summary>
private static string? WithoutSettings(string? parametersJson)
{
if (parametersJson is null || JsonSerializer.Deserialize(parametersJson, ProtocolJson.Default.RenderJobParameters) is not { } parameters) return parametersJson;
return JsonSerializer.Serialize(parameters with { SettingsJson = null }, ProtocolJson.Default.RenderJobParameters);
}
/// <summary>
/// The deep report the editor shows: the home's while its frames are the workspace's, else the copy the workspace took;
/// whether one of another number of frames was read instead.