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

@@ -128,7 +128,7 @@ public sealed class RebuildDialogViewModel : ArchiveDialogViewModel
Archive = archive;
Availability = availability;
Indexed = indexed;
_facts = Facts(null, availability == ArchiveAvailability.Offline ? Loc.L("Archive.Error.Offline", Formatting.LeftToRight(archive.RootPath)) : null);
_facts = Facts(null, availability == ArchiveAvailability.Offline ? Loc.L("Archive.Error.Offline", Formatting.LeftToRight(AppEnvironment.Shown(archive.RootPath))) : null);
RebuildCommand = new AsyncRelayCommand(RebuildAsync, () => !IsBusy && availability == ArchiveAvailability.Online);
}
@@ -181,7 +181,7 @@ public sealed class RebuildDialogViewModel : ArchiveDialogViewModel
return
[
new(Loc.L("Archive.Rebuild.Archive"), Archive.Name),
new(Loc.L("Archive.Rebuild.Root"), Archive.RootPath, IsPath: true),
new(Loc.L("Archive.Rebuild.Root"), AppEnvironment.Shown(Archive.RootPath), IsPath: true),
new(Loc.L("Archive.Rebuild.State"), Loc.L("Archive.Availability." + Availability)),
new(Loc.L("Archive.Rebuild.Indexed"), Loc.Plural("Shell.Status.Sequences", Indexed)),
Count(Loc.L("Archive.Rebuild.Sidecars"), f => f.Sidecar is not null),
+4 -1
View File
@@ -62,6 +62,9 @@ public sealed class SampleData
private SampleData(AppServices services) => _services = services;
/// <summary>What the sample server says it can do (none: an older server, whose sequences open with proxies); tests set it.</summary>
public IReadOnlyList<string> Capabilities { get; set; } = [];
/// <summary>The server-only sequence whose proxies <see cref="CacheProxiesAsync"/> keeps on this PC (Sunrise over Superga).</summary>
public Guid ProxiedSequenceId => _sunrise;
@@ -762,7 +765,7 @@ public sealed class SampleData
{
await Task.Delay(14, ct);
if (!trusted.Contains(ServerFingerprint, StringComparer.OrdinalIgnoreCase)) throw new UntrustedCertificateException(ServerFingerprint);
return new ServerInfo("Studio NAS", "1.3.0", 1, [], ServerFingerprint, [], new ServerLimits(0, 0));
return new ServerInfo("Studio NAS", "1.3.0", 1, sample.Capabilities, ServerFingerprint, [], new ServerLimits(0, 0));
}
public Task<LoginResponse> LoginAsync(string username, string password, CancellationToken ct)
+14 -9
View File
@@ -625,6 +625,8 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
/// </summary>
public async Task RenderAsync(JobPriority priority, bool batch)
{
// A workspace project whose home is a server renders what the server holds: changes not sent are offered to be sent first (phase 5b).
if (Project is { } project && !await project.ReadyToRenderAsync()) return;
// The job embeds the project: its frame positions follow frames inserted since the editor read them first. A server
// sequence whose frames changed is outdated instead, and its toast says so and offers fresh proxies.
await Session.EnsureFramesAsync();
@@ -1074,22 +1076,25 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
private void OnConflictFound(ProjectConflictException conflict) => _dispatcher.BeginInvoke(() =>
{
if (_disposed || Session.Conflict is null) return;
var request = Session.Source is WorkspaceSequenceSource ? LibraryConflictRequest(conflict, Title) : ConflictRequest(conflict, Title, ServerName ?? string.Empty);
var request = Session.Source is WorkspaceSequenceSource workspace ? LibraryConflictRequest(conflict, Title, workspace.IsServerHome) : ConflictRequest(conflict, Title, ServerName ?? string.Empty);
var keepMine = Shell.Services.Dialogs.Confirm(request);
if (!_disposed) Session.ResolveConflict(keepMine);
});
/// <summary>The conflict prompt of a workspace project: what differs (the editor's value, then the library's) and what each choice keeps.</summary>
internal static ConfirmRequest LibraryConflictRequest(ProjectConflictException conflict, string title) => new()
/// <summary>
/// The conflict prompt of a workspace project: what differs (the editor's value, then the home's) and what each choice
/// keeps, worded for a <paramref name="server"/> home (phase 5b) or the library.
/// </summary>
internal static ConfirmRequest LibraryConflictRequest(ProjectConflictException conflict, string title, bool server = false) => new()
{
Heading = Loc.L("Editor.Workspace.Conflict.Title"),
Message = Loc.L("Editor.Workspace.Edited.Message", title),
Detail = string.Join(Environment.NewLine, WorkspaceText.ConflictLines(conflict.Differences, 10)),
DetailToolTip = Loc.L("Tooltips.Editor.Workspace.Differences"),
SafeText = Loc.L("Editor.Workspace.Conflict.TakeHome"),
SafeToolTip = Loc.L("Tooltips.Editor.Workspace.TakeHomeUndo"),
Message = WorkspaceText.ForHome("Editor.Workspace.Edited.Message", server, title),
Detail = string.Join(Environment.NewLine, WorkspaceText.ConflictLines(conflict.Differences, 10, server)),
DetailToolTip = WorkspaceText.ForHome("Tooltips.Editor.Workspace.Differences", server),
SafeText = WorkspaceText.ForHome("Editor.Workspace.Conflict.TakeHome", server),
SafeToolTip = WorkspaceText.ForHome("Tooltips.Editor.Workspace.TakeHomeUndo", server),
ActionText = Loc.L("Server.Sync.Action.KeepMine"),
ActionToolTip = Loc.L("Tooltips.Editor.Workspace.KeepMine"),
ActionToolTip = WorkspaceText.ForHome("Tooltips.Editor.Workspace.KeepMine", server),
IsDestructive = true,
};
+16 -144
View File
@@ -38,17 +38,12 @@ namespace Chronos.App.Editor;
public sealed class RemoteSequenceSource : ISequenceSource
{
private const int SaveAttempts = 3;
private static readonly TimeSpan MinBackoff = TimeSpan.FromSeconds(2);
private static readonly TimeSpan MaxBackoff = TimeSpan.FromMinutes(1);
private readonly RemoteSequence _remote;
private readonly IRemoteSequenceApi _api;
private readonly IRenderFrameSource _frames;
private readonly IFrameSource _pixels;
private readonly ConcurrentDictionary<Guid, Job> _jobs = new();
private readonly ConcurrentDictionary<Guid, byte> _foreign = new();
private readonly CancellationTokenSource _stopping = new();
private readonly Task _listening;
private readonly ServerJobs _jobs;
private readonly bool _noEditRight;
private Stored? _stored;
private int _framesVersion = -1;
@@ -66,8 +61,7 @@ public sealed class RemoteSequenceSource : ISequenceSource
_noEditRight = readOnly;
_frames = remote.OpenFrames(decoder);
_pixels = (IFrameSource)_frames;
var stopping = _stopping.Token;
_listening = Task.Run(() => ListenAsync(stopping), CancellationToken.None);
_jobs = new ServerJobs(api, remote.Sequence.Id, remote.Sequence.DisplayTitle, job => JobChanged?.Invoke(job), OnEventAsync, OnReconnectedAsync);
}
public bool IsRemote => true;
@@ -190,126 +184,44 @@ public sealed class RemoteSequenceSource : ISequenceSource
/// 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.
/// </remarks>
public async Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken)
public Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request);
if (request.Kind == JobKind.Render && IsOutdated) throw new ProxiesOutdatedException(Loc.L("Editor.Error.FramesChanged"));
var dto = await Call(() => _api.CreateJobAsync(new CreateJobRequest(JobWire.Kind(request.Kind), request.Targets, request.ParametersJson), cancellationToken));
if (request.Priority != JobPriority.User) dto = await PrioritiseAsync(dto, request.Priority, cancellationToken);
// The server's events may have reported the job already; its first state never replaces a later one.
if (JobWire.FromDto(dto) is { } job && _jobs.TryAdd(job.Id, job)) JobChanged?.Invoke(job);
return dto.Id;
return _jobs.SubmitAsync(request, cancellationToken);
}
public async Task<IReadOnlyList<Job>> ListJobsAsync(CancellationToken cancellationToken)
{
var active = await Call(() => _api.ListActiveJobsAsync(cancellationToken));
var mine = active.Select(JobWire.FromDto).OfType<Job>().Where(Concerns).ToList();
foreach (var job in mine) _jobs[job.Id] = job;
return mine;
}
public Task<IReadOnlyList<Job>> ListJobsAsync(CancellationToken cancellationToken) => _jobs.ListAsync(cancellationToken);
public async Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken)
{
if (JobWire.FromDto(await _api.CancelJobAsync(jobId, cancellationToken)) is { } job) Publish(job);
}
public Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken) => _jobs.CancelAsync(jobId, cancellationToken);
public async Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken)
{
if (JobWire.FromDto(await _api.RetryJobAsync(jobId, cancellationToken)) is { } job) Publish(job);
}
public Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken) => _jobs.RetryAsync(jobId, cancellationToken);
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) == 1) return;
try
{
await _stopping.CancelAsync();
await _listening;
// Stops following the events, and closes the connection.
await _jobs.DisposeAsync();
}
finally
{
_stopping.Dispose();
if (_frames is IAsyncDisposable frames) await frames.DisposeAsync();
_api.Dispose();
}
}
/// <summary>
/// Follows the server's events until the editor closes, reconnecting with a growing delay (job states lost meanwhile
/// are read back from the jobs, and the frames are compared again). Nothing that fails on the way ends it.
/// </summary>
private async Task ListenAsync(CancellationToken cancellationToken)
{
var failures = 0;
while (true)
{
try
{
await foreach (var e in _api.EventsAsync(cancellationToken).ConfigureAwait(false))
{
failures = 0;
await OnEventAsync(e, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
if (cancellationToken.IsCancellationRequested) return;
Log.Info("editor", $"Events of the server lost for {_remote.Sequence.DisplayTitle}: {ex.Message}");
}
try
{
var delay = Math.Min(MaxBackoff.Ticks, MinBackoff.Ticks << Math.Min(failures++, 10));
await Task.Delay(TimeSpan.FromTicks(delay), cancellationToken).ConfigureAwait(false);
await RefreshTrackedAsync(cancellationToken).ConfigureAwait(false);
// A frames change announced while the socket was down is found now rather than at the next save.
if (Volatile.Read(ref _framesVersion) >= 0) await CheckFramesAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
if (cancellationToken.IsCancellationRequested) return;
Log.Info("editor", $"Jobs of {_remote.Sequence.DisplayTitle} could not be read again: {ex.Message}");
}
}
}
/// <summary>The server's events besides the jobs': frames added or removed on the server make the sequence outdated.</summary>
private async Task OnEventAsync(ServerEvent e, CancellationToken cancellationToken)
{
switch (e)
{
case SequenceChangedEvent changed when changed.SequenceId == Id && changed.FramesVersion != Volatile.Read(ref _framesVersion):
await CheckFramesAsync(cancellationToken).ConfigureAwait(false);
break;
// A late progress event never brings a finished job back to running.
case JobProgressEvent progress when _jobs.TryGetValue(progress.JobId, out var job) && job.State is JobState.Queued or JobState.Running:
Publish(job with
{
State = JobState.Running,
ProgressDone = progress.Done,
ProgressTotal = progress.Total,
ItemsPerSecond = progress.ItemsPerSecond,
Eta = JobEta.FromSeconds(progress.EtaSeconds),
});
break;
case JobStateEvent state when !_foreign.ContainsKey(state.JobId):
await FetchAsync(state.JobId, cancellationToken).ConfigureAwait(false);
break;
}
if (e is SequenceChangedEvent changed && changed.SequenceId == Id && changed.FramesVersion != Volatile.Read(ref _framesVersion))
await CheckFramesAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>Reads a job the events named: tracked when it concerns this sequence, remembered as foreign otherwise.</summary>
private async Task FetchAsync(Guid jobId, CancellationToken cancellationToken)
/// <summary>A frames change announced while the event socket was down is found now rather than at the next save.</summary>
private async Task OnReconnectedAsync(CancellationToken cancellationToken)
{
try
{
if (JobWire.FromDto(await _api.GetJobAsync(jobId, cancellationToken).ConfigureAwait(false)) is { } job && Concerns(job)) Publish(job);
else _foreign[jobId] = 0;
}
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or JsonException
|| (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested))
{
Log.Info("editor", $"Job {jobId} could not be read: {ex.Message}");
}
if (Volatile.Read(ref _framesVersion) >= 0) await CheckFramesAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>Frames added or removed on the server: whether this PC's frames are still the sequence's.</summary>
@@ -326,34 +238,6 @@ public sealed class RemoteSequenceSource : ISequenceSource
}
}
/// <summary>Sets a priority other than the user's on a job the server just queued; the job stays queued if that fails.</summary>
private async Task<JobDto> PrioritiseAsync(JobDto dto, JobPriority priority, CancellationToken cancellationToken)
{
try
{
return await _api.SetJobPriorityAsync(dto.Id, JobWire.Priority(priority), cancellationToken);
}
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException)
{
// Already claimed (409) or refused: the job runs at the user's priority, which is never later than asked.
Log.Info("editor", $"Job {dto.Id} keeps the user's priority on the server: {ex.Message}");
return dto;
}
}
/// <summary>After a lost event socket: the tracked jobs as the server has them now.</summary>
private async Task RefreshTrackedAsync(CancellationToken cancellationToken)
{
foreach (var job in _jobs.Values.Where(j => j.State is JobState.Queued or JobState.Running or JobState.Paused).ToList())
await FetchAsync(job.Id, cancellationToken).ConfigureAwait(false);
}
private void Publish(Job job)
{
_jobs[job.Id] = job;
JobChanged?.Invoke(job);
}
/// <summary>
/// Takes the server's frames as <paramref name="manifest"/> lists them: their frames version when they are this PC's
/// (saves name it), outdated otherwise. Returns whether they are.
@@ -387,8 +271,6 @@ public sealed class RemoteSequenceSource : ISequenceSource
ReadOnlyChanged?.Invoke();
}
private bool Concerns(Job job) => job.TargetIds.Contains(Id) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render;
/// <summary>The frame of the project's hero, or <see cref="Guid.Empty"/> (the first frame shows) without one.</summary>
private Guid HeroFrameId(ProjectSettings project) =>
project.HeroFrame is { } hero && (uint)hero < (uint)_remote.Frames.Count ? _remote.Frames[hero].Id : Guid.Empty;
@@ -424,17 +306,7 @@ public sealed class RemoteSequenceSource : ISequenceSource
}
/// <summary>A sequence deleted on the server reads as gone, like a local one removed from the index.</summary>
private static async Task<T> Call<T>(Func<Task<T>> call)
{
try
{
return await call();
}
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
throw new EditorException(Loc.L("Editor.Error.Missing"), ex);
}
}
private static Task<T> Call<T>(Func<Task<T>> call) => ServerJobs.Call(call);
/// <summary>The server's settings as last read or written, with the version a save must name.</summary>
private sealed record Stored(ProjectSettings Project, int Version);
+225
View File
@@ -0,0 +1,225 @@
using System.Collections.Concurrent;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Protocol;
using Chronos.Protocol.Client;
namespace Chronos.App.Editor;
/// <summary>
/// The analyses and renders of one server sequence as an editor follows them (BRIEF §14.5): queued through the API (the
/// server queues each at the user's priority, another one is set right after), their states and progress taken from the
/// server's events, the jobs followed read again whenever the event socket comes back after a loss (reconnecting with a
/// growing delay; nothing that fails on the way ends it). What a server sequence opened with proxies
/// (<see cref="RemoteSequenceSource"/>) and a workspace project whose home is a server (<see cref="WorkspaceSequenceSource"/>,
/// owner review 2, R8) run on the server. Events of other kinds go to <c>other</c>; <c>reconnected</c> runs after the jobs
/// were read again. Owns the connection: disposing stops listening and disposes it.
/// </summary>
internal sealed class ServerJobs : IAsyncDisposable
{
private static readonly TimeSpan MinBackoff = TimeSpan.FromSeconds(2);
private static readonly TimeSpan MaxBackoff = TimeSpan.FromMinutes(1);
private readonly Guid _sequenceId;
private readonly string _title;
private readonly Action<Job> _changed;
private readonly Func<ServerEvent, CancellationToken, Task>? _other;
private readonly Func<CancellationToken, Task>? _reconnected;
private readonly ConcurrentDictionary<Guid, Job> _jobs = new();
private readonly ConcurrentDictionary<Guid, byte> _foreign = new();
private readonly CancellationTokenSource _stopping = new();
private readonly Task _listening;
private int _disposed;
/// <param name="changed">A job of the sequence changed (any thread).</param>
public ServerJobs(IRemoteSequenceApi api, Guid sequenceId, string title, Action<Job> changed, Func<ServerEvent, CancellationToken, Task>? other = null,
Func<CancellationToken, Task>? reconnected = null)
{
ArgumentNullException.ThrowIfNull(api);
ArgumentNullException.ThrowIfNull(changed);
Api = api;
_sequenceId = sequenceId;
_title = title;
_changed = changed;
_other = other;
_reconnected = reconnected;
var stopping = _stopping.Token;
_listening = Task.Run(() => ListenAsync(stopping), CancellationToken.None);
}
/// <summary>The connection the jobs travel on (the source's other calls use it too).</summary>
public IRemoteSequenceApi Api { get; }
/// <summary>Queues <paramref name="request"/> on the server (its priority set after, when it is not the user's); returns the job id.</summary>
/// <exception cref="EditorException">The sequence is gone from the server.</exception>
public async Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request);
var dto = await Call(() => Api.CreateJobAsync(new CreateJobRequest(JobWire.Kind(request.Kind), request.Targets, request.ParametersJson), cancellationToken));
if (request.Priority != JobPriority.User) dto = await PrioritiseAsync(dto, request.Priority, cancellationToken);
// The server's events may have reported the job already; its first state never replaces a later one.
if (JobWire.FromDto(dto) is { } job && _jobs.TryAdd(job.Id, job)) _changed(job);
return dto.Id;
}
/// <summary>The analyses and renders of the sequence waiting, running or paused on the server, followed from now on.</summary>
public async Task<IReadOnlyList<Job>> ListAsync(CancellationToken cancellationToken)
{
var active = await Call(() => Api.ListActiveJobsAsync(cancellationToken));
var mine = active.Select(JobWire.FromDto).OfType<Job>().Where(Concerns).ToList();
foreach (var job in mine) _jobs[job.Id] = job;
return mine;
}
public async Task CancelAsync(Guid jobId, CancellationToken cancellationToken)
{
if (JobWire.FromDto(await Api.CancelJobAsync(jobId, cancellationToken)) is { } job) Publish(job);
}
public async Task RetryAsync(Guid jobId, CancellationToken cancellationToken)
{
if (JobWire.FromDto(await Api.RetryJobAsync(jobId, cancellationToken)) is { } job) Publish(job);
}
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) == 1) return;
try
{
await _stopping.CancelAsync();
await _listening;
}
finally
{
_stopping.Dispose();
Api.Dispose();
}
}
/// <summary>
/// Follows the server's events until disposed, reconnecting with a growing delay (job states lost meanwhile are read
/// back from the jobs, then <c>reconnected</c> runs). Nothing that fails on the way ends it.
/// </summary>
private async Task ListenAsync(CancellationToken cancellationToken)
{
var failures = 0;
while (true)
{
try
{
await foreach (var e in Api.EventsAsync(cancellationToken).ConfigureAwait(false))
{
failures = 0;
await OnEventAsync(e, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
if (cancellationToken.IsCancellationRequested) return;
Log.Info("editor", $"Events of the server lost for {_title}: {ex.Message}");
}
try
{
var delay = Math.Min(MaxBackoff.Ticks, MinBackoff.Ticks << Math.Min(failures++, 10));
await Task.Delay(TimeSpan.FromTicks(delay), cancellationToken).ConfigureAwait(false);
await RefreshTrackedAsync(cancellationToken).ConfigureAwait(false);
if (_reconnected is not null) await _reconnected(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
if (cancellationToken.IsCancellationRequested) return;
Log.Info("editor", $"Jobs of {_title} could not be read again: {ex.Message}");
}
}
}
private async Task OnEventAsync(ServerEvent e, CancellationToken cancellationToken)
{
switch (e)
{
// A late progress event never brings a finished job back to running.
case JobProgressEvent progress when _jobs.TryGetValue(progress.JobId, out var job) && job.State is JobState.Queued or JobState.Running:
Publish(job with
{
State = JobState.Running,
ProgressDone = progress.Done,
ProgressTotal = progress.Total,
ItemsPerSecond = progress.ItemsPerSecond,
Eta = JobEta.FromSeconds(progress.EtaSeconds),
});
break;
case JobProgressEvent:
break;
case JobStateEvent state:
if (!_foreign.ContainsKey(state.JobId)) await FetchAsync(state.JobId, cancellationToken).ConfigureAwait(false);
break;
default:
if (_other is not null) await _other(e, cancellationToken).ConfigureAwait(false);
break;
}
}
/// <summary>Reads a job the events named: tracked when it concerns this sequence, remembered as foreign otherwise.</summary>
private async Task FetchAsync(Guid jobId, CancellationToken cancellationToken)
{
try
{
if (JobWire.FromDto(await Api.GetJobAsync(jobId, cancellationToken).ConfigureAwait(false)) is { } job && Concerns(job)) Publish(job);
else _foreign[jobId] = 0;
}
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or JsonException
|| (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested))
{
Log.Info("editor", $"Job {jobId} could not be read: {ex.Message}");
}
}
/// <summary>Sets a priority other than the user's on a job the server just queued; the job stays queued if that fails.</summary>
private async Task<JobDto> PrioritiseAsync(JobDto dto, JobPriority priority, CancellationToken cancellationToken)
{
try
{
return await Api.SetJobPriorityAsync(dto.Id, JobWire.Priority(priority), cancellationToken);
}
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException)
{
// Already claimed (409) or refused: the job runs at the user's priority, which is never later than asked.
Log.Info("editor", $"Job {dto.Id} keeps the user's priority on the server: {ex.Message}");
return dto;
}
}
/// <summary>After a lost event socket: the tracked jobs as the server has them now.</summary>
private async Task RefreshTrackedAsync(CancellationToken cancellationToken)
{
foreach (var job in _jobs.Values.Where(j => j.State is JobState.Queued or JobState.Running or JobState.Paused).ToList())
await FetchAsync(job.Id, cancellationToken).ConfigureAwait(false);
}
private void Publish(Job job)
{
_jobs[job.Id] = job;
_changed(job);
}
private bool Concerns(Job job) => job.TargetIds.Contains(_sequenceId) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render;
/// <summary>A sequence deleted on the server reads as gone, like a local one removed from the index.</summary>
internal static async Task<T> Call<T>(Func<Task<T>> call)
{
try
{
return await call();
}
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
throw new EditorException(Loc.L("Editor.Error.Missing"), ex);
}
}
}
+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.
@@ -57,9 +57,68 @@ public sealed class AppEnvironment
return new(paths.DataRoot, paths.IsPortable, isCapture: false, paths.SyncedFolder, paths.PortableSyncRoot, paths.EarlierPortableData);
}
/// <summary>
/// The data folder a capture shows in place of its temporary one (<see cref="Shown"/>): the default data folder of a
/// sample user, so the screenshots show no path of the machine (its temporary folder, its user name).
/// </summary>
public const string SampleDataDirectory = @"C:\Users\Studio\AppData\Local\Chronos";
/// <summary>The folder a capture shows for its sample archive (<c>archive</c> in its data folder), as the sample settings name it.</summary>
public const string SampleArchiveDirectory = @"D:\ChronosArchive";
/// <summary>The temporary data folder of the capture this process runs (the last one made); null outside a capture.</summary>
private static string? _captureData;
/// <summary>A fresh temporary data folder for screenshots and smoke tests; delete it with <see cref="DeleteCaptureData"/>.</summary>
public static AppEnvironment ForCapture() =>
new(Path.Combine(Path.GetTempPath(), "chronos-capture-" + Guid.CreateVersion7().ToString("N")), portable: false, isCapture: true);
public static AppEnvironment ForCapture()
{
var environment = new AppEnvironment(Path.Combine(Path.GetTempPath(), "chronos-capture-" + Guid.CreateVersion7().ToString("N")), portable: false, isCapture: true);
_captureData = environment.DataDirectory;
return environment;
}
/// <summary>
/// A path as the screens show it: one under a capture's temporary data folder as under <see cref="SampleDataDirectory"/>
/// (its sample archive as <see cref="SampleArchiveDirectory"/>), so the screenshots show nothing of the machine; any
/// other as it is. Only for text on screen: a path typed there goes through <see cref="Actual"/>.
/// </summary>
public static string Shown(string path) => Shown(path, _captureData);
/// <summary>A path typed or shown on screen as the one it stands for: <see cref="Shown(string)"/> undone, so a capture never writes outside its temporary folder.</summary>
public static string Actual(string shown) => Actual(shown, _captureData);
/// <summary><see cref="Shown(string)"/> for the capture whose data folder is <paramref name="captureData"/> (none: the path as it is).</summary>
internal static string Shown(string path, string? captureData)
{
foreach (var (actual, shown) in CaptureFolders(captureData))
{
if (Swap(path, actual, shown) is { } swapped) return swapped;
}
return path;
}
/// <summary><see cref="Actual(string)"/> for the capture whose data folder is <paramref name="captureData"/>.</summary>
internal static string Actual(string shown, string? captureData)
{
foreach (var (actual, sample) in CaptureFolders(captureData))
{
if (Swap(shown, sample, actual) is { } swapped) return swapped;
}
return shown;
}
/// <summary>A capture's folders and what the screens show for each, the more specific first.</summary>
private static (string Actual, string Shown)[] CaptureFolders(string? captureData) =>
captureData is null ? [] : [(Path.Combine(captureData, "archive"), SampleArchiveDirectory), (captureData, SampleDataDirectory)];
/// <summary><paramref name="path"/> with its root <paramref name="from"/> replaced by <paramref name="to"/>; null when it is not under it.</summary>
private static string? Swap(string path, string from, string to)
{
if (string.IsNullOrEmpty(path)) return null;
var root = from.TrimEnd(Path.DirectorySeparatorChar);
if (path.TrimEnd(Path.DirectorySeparatorChar).Equals(root, StringComparison.OrdinalIgnoreCase)) return to;
return path.StartsWith(root + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) ? to + path[root.Length..] : null;
}
/// <summary>Removes the temporary data folder of a capture environment (never a real one).</summary>
public void DeleteCaptureData()
@@ -74,6 +74,9 @@ public sealed class AppServices : IAsyncDisposable
Sync = new SyncHost(this);
ScheduleHost = new DesktopScheduleHost(settings, () => Database, () => Archives);
Workspace = new WorkspaceHost(environment, settings, saveSettings, () => Database, () => Archives, () => Engine);
// A server that keeps projects is the home of the workspace projects of its sequences (owner review 2, R8, phase 5b).
Workspace.ServerHomes = Sync.ProjectHome;
Sync.ProjectChanged += Workspace.OnServerProjectChanged;
Server = new ServerSession(settings, saveSettings, new ChronosServerApiFactory(), new DpapiTokenProtector());
Encoders = new MediaFoundationInventory();
Formats = new WicFormatInventory(() => _wic);
@@ -120,7 +123,7 @@ public sealed class AppServices : IAsyncDisposable
/// </summary>
public event Action<Guid>? SequenceReorganized;
/// <summary>The workspace where Edit opens projects (owner review 2, R8), with this PC's archive as their home.</summary>
/// <summary>The workspace where Edit opens projects (owner review 2, R8), with this PC's archive or the signed-in server as their home.</summary>
public WorkspaceHost Workspace { get; }
public IEncoderInventory Encoders { get; set; }
@@ -175,12 +178,13 @@ public sealed class AppServices : IAsyncDisposable
typeof(AppServices).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0";
/// <summary>The job handlers of this PC's engine — the single registration list; a kind without a handler stays
/// queued (it is never claimed here). The workspace copy is the desktop's alone: it writes into this PC's workspace.</summary>
/// queued (it is never claimed here). The workspace copy is the desktop's alone: it writes into this PC's workspace, from
/// this PC's archive or, through the signed-in session, from a server.</summary>
public static IReadOnlyList<IJobHandler> CreateJobHandlers(AppServices services) =>
[
.. services.Archives?.CreateJobHandlers() ?? [], .. services.Processing?.CreateJobHandlers() ?? [],
.. services.Sync.Service?.CreateJobHandlers(services.Sync) ?? [],
.. services.Database is { } db && services.Archives is { } archives ? WorkspaceJobs.CreateHandlers(db, archives) : [],
.. services.Database is { } db && services.Archives is { } archives ? WorkspaceJobs.CreateHandlers(db, archives, services.Sync) : [],
];
/// <summary>
@@ -26,6 +26,7 @@ namespace Chronos.App.Sections;
public sealed class SequencePickerViewModel : LocalizedViewModel
{
private readonly SequenceViewModel _section;
private readonly Dispatcher _dispatcher;
private readonly DispatcherTimer _searchDelay;
private readonly RemoteMerge _merge = new();
private readonly AsyncRelayCommand _open;
@@ -46,8 +47,10 @@ public sealed class SequencePickerViewModel : LocalizedViewModel
public SequencePickerViewModel(SequenceViewModel section)
{
_section = section;
_dispatcher = Dispatcher.CurrentDispatcher;
_searchDelay = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) };
_searchDelay.Tick += (_, _) => _ = ReloadAsync();
section.Shell.Services.Workspace.HomeChanged += OnHomeChanged;
_open = new AsyncRelayCommand(() => (Selected ?? Items.FirstOrDefault()) is { } item ? _section.PickAsync(item) : Task.CompletedTask, () => Items.Count > 0);
OpenItemCommand = new AsyncRelayCommand((p, _) => p is SequenceItem item ? _section.PickAsync(item) : Task.CompletedTask);
OpenProjectCommand = new AsyncRelayCommand((p, _) => (p as WorkspaceProjectItem ?? SelectedProject) is { } item ? _section.PickProjectAsync(item) : Task.CompletedTask);
@@ -172,11 +175,34 @@ public sealed class SequencePickerViewModel : LocalizedViewModel
{
_searchDelay.Stop();
_pager?.Cancel();
_section.Shell.Services.Workspace.HomeChanged -= OnHomeChanged;
// The projects' states still being read stop asking.
_generation++;
base.Dispose();
}
/// <summary>
/// A project's home told it changed there (any thread; phase 5b: a server's <c>projectChanged</c>), or that changes may
/// have been missed: the listed projects it concerns read their state again (Server newer, Deleted).
/// </summary>
private void OnHomeChanged(WorkspaceHomeChange change) => _dispatcher.BeginInvoke(async () =>
{
var generation = _generation;
foreach (var item in WorkspaceItems.Where(i => change.ProjectId is { } id ? i.ProjectId == id
: i.Entry.IsServerHome && string.Equals(i.Entry.Home.Server, change.Server, StringComparison.OrdinalIgnoreCase)).ToList())
{
if (generation != _generation) return;
try
{
item.Status = await Shell.Services.Workspace.StatusAsync(item.ProjectId);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Info("workspace", $"The state of project {item.ProjectId} could not be read: {ex.Message}");
}
}
});
private async Task OpenFromSearchAsync()
{
await SettleAsync();
@@ -271,8 +297,13 @@ public sealed class SequencePickerViewModel : LocalizedViewModel
{
foreach (var entry in (await services.Workspace.ListAsync()).OrderByDescending(e => e.Saved))
{
var row = await db.Sequences.GetAsync(entry.SequenceId);
var item = new WorkspaceProjectItem(entry, row is null ? null : new SequenceItem(row, services.Thumbnails));
var row = entry.IsServerHome ? null : await db.Sequences.GetAsync(entry.SequenceId);
// A server's sequence as the Library lists it (phase 5b), with the server's thumbnail; none while signed out.
var remote = row is null ? Shell.Library.RemoteSequences.FirstOrDefault(s => s.Id == entry.SequenceId) : null;
var sequence = row is not null ? new SequenceItem(row, services.Thumbnails)
: remote is not null ? new SequenceItem(remote, Shell.Library.RemoteThumbnails)
: null;
var item = new WorkspaceProjectItem(entry, sequence);
if (text.Length > 0 && !item.Name.Contains(text, StringComparison.CurrentCultureIgnoreCase)
&& !item.SequenceTitle.Contains(text, StringComparison.CurrentCultureIgnoreCase))
continue;
+5 -5
View File
@@ -123,11 +123,11 @@
<Separator />
<MenuItem Header="{l:Loc Editor.Project.Open}" Command="{Binding Project.OpenProjectCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.Open}" />
<MenuItem Header="{l:Loc Editor.Project.New}" Command="{Binding Project.NewProjectCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.New}" />
<MenuItem Header="{l:Loc Editor.Project.Rename}" Command="{Binding Project.RenameCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.Rename}" />
<MenuItem Header="{l:Loc Editor.Project.Rename}" Command="{Binding Project.RenameCommand}" ToolTip="{Binding Project.RenameToolTip}" />
<MenuItem Header="{l:Loc Editor.Project.Delete}" Command="{Binding Project.DeleteCommand}" ToolTip="{Binding Project.DeleteToolTip}"
ToolTipService.ShowOnDisabled="True" />
<Separator />
<MenuItem Header="{l:Loc Editor.Project.RemoveCopy}" Command="{Binding Project.RemoveCopyCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.RemoveCopy}" />
<MenuItem Header="{l:Loc Editor.Project.RemoveCopy}" Command="{Binding Project.RemoveCopyCommand}" ToolTip="{Binding Project.RemoveCopyToolTip}" />
</ContextMenu>
</Button.ContextMenu>
</Button>
@@ -164,13 +164,13 @@
</StackPanel>
</Grid>
<!-- Owner review 2, R8: the library's frames moved past the workspace's; Update media copies them again (positions follow their photos). -->
<!-- Owner review 2, R8: the home's frames (the library's or the server's) moved past the workspace's; Update media copies them again (positions follow their photos). -->
<Border Grid.Row="1" Style="{StaticResource Border.Card}" Padding="12,6" Margin="0,0,0,8"
Visibility="{Binding Project.HasMediaUpdate, Converter={StaticResource BoolToVisibility}, FallbackValue=Collapsed}">
<DockPanel>
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Compact}" Content="{l:Loc Editor.Workspace.UpdateMedia}" Command="{Binding Project.UpdateMediaCommand}"
ToolTip="{l:Loc Tooltips.Editor.Workspace.UpdateMedia}" ToolTipService.ShowOnDisabled="True" />
<ui:StatusGlyph Kind="Warning" Text="{Binding Project.MediaUpdateText}" ToolTip="{l:Loc Tooltips.Editor.Workspace.MediaChanged}" VerticalAlignment="Center"
ToolTip="{Binding Project.UpdateMediaToolTip}" ToolTipService.ShowOnDisabled="True" />
<ui:StatusGlyph Kind="Warning" Text="{Binding Project.MediaUpdateText}" ToolTip="{Binding Project.MediaChangedToolTip}" VerticalAlignment="Center"
infra:LiveRegion.Text="{Binding Project.MediaUpdateText}" AutomationProperties.LiveSetting="Polite" />
</DockPanel>
</Border>
+152 -24
View File
@@ -14,8 +14,10 @@ using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Protocol.Client;
using Chronos.Ui.Mvvm;
@@ -27,9 +29,11 @@ namespace Chronos.App.Sections;
/// Server screen or its own picker chose into an <see cref="EditorViewModel"/>. A sequence of this PC's archive opens as a
/// project of the workspace (owner review 2, R8: editing never happens inside the library): the project of that sequence
/// opened last here; else, after "Open in workspace" asked which project (Main, another of its home, or a new one) and
/// which media, the project is checked out and its media copied by a job, and it opens once they are here. A server
/// sequence opens with this PC's proxies (the workspace takes server homes in phase 5b), and a capture (sample data
/// without an engine) opens the library as before. The next sequence is read first; only then does the open one close,
/// which media, the project is checked out and its media copied by a job, and it opens once they are here. A sequence of
/// a server that keeps projects opens the same way as a project whose home is that server (phase 5b: its media downloaded
/// into the workspace; a project already there opens from it, the server reachable or not); one of an older server opens
/// with this PC's proxies, and a capture (sample data without an engine) opens the library as before. The next sequence
/// is read first; only then does the open one close,
/// after its last edit is stored. Without a sequence, or after Change sequence, it shows the picker (the editor stays
/// open behind it until another sequence opens). A server sequence whose proxies are missing or out of date fetches them
/// first and opens once they are here, the open sequence staying open meanwhile; a workspace copy is followed the same
@@ -540,9 +544,10 @@ public sealed class SequenceViewModel : SectionViewModel
/// <summary>
/// Where <paramref name="sequenceId"/> lives: this PC's index (opened as a workspace project,
/// <see cref="OpenWorkspaceAsync"/>; in a capture, the library itself), else a sequence of the signed-in server whose
/// proxies this PC keeps (Server screen, "Open with proxies"), edited through the server (BRIEF §14.5), or only shown
/// when the account may not change it. Null when it cannot open yet: its proxies are being fetched
/// <see cref="OpenWorkspaceAsync"/>; in a capture, the library itself), else a server's sequence: a workspace project
/// whose home is that server (<see cref="OpenServerWorkspaceAsync"/>), or, for a server that keeps no projects, one
/// whose proxies this PC keeps (Server screen, "Open with proxies"), edited through the server (BRIEF §14.5), or only
/// shown when the account may not change it. Null when it cannot open yet: its proxies are being fetched
/// (<see cref="FetchProxiesAsync"/>), its workspace copy runs, or the user closed "Open in workspace".
/// </summary>
private async Task<(ISequenceSource Source, string Title)?> OpenSourceAsync(AppServices services, Guid sequenceId)
@@ -557,14 +562,19 @@ public sealed class SequenceViewModel : SectionViewModel
local.HeroChanged += OnHeroChanged;
return (local, row.DisplayTitle);
}
// A workspace project whose sequence left the index (its trash emptied, its folder gone): not a server's sequence to
// fetch; its local copy can only be removed (the picker's Remove local copy).
// A workspace project of this PC's archive whose sequence left the index (its trash emptied, its folder gone): not a
// server's sequence to fetch; its local copy can only be removed (the picker's Remove local copy).
if (_requested is { ProjectId: { } projectId } asked && asked.SequenceId == sequenceId && services.Workspace.IsEnabled
&& await services.Workspace.FindAsync(projectId) is not null)
&& await services.Workspace.FindAsync(projectId) is { IsServerHome: false })
{
_requested = null;
throw new InvalidOperationException(Loc.L("Errors.Workspace.SequenceGone"));
}
// A server sequence (owner review 2, R8, phase 5b): a project of it in the workspace opens from there, the server
// reachable or not; one of a server that keeps projects is checked out (asked which); an older server's opens with
// proxies as before.
if (services.Workspace.IsEnabled && await OpenServerWorkspaceAsync(services, services.Workspace, db, decoder, sequenceId) is { } project)
return project.Opened;
var sync = services.Sync;
if (sync.Server is not { } server || sync.Service is not { } service || sync.ConnectEditor() is not { } api)
throw new InvalidOperationException(Loc.L("Editor.Error.SignedOut"));
@@ -610,7 +620,7 @@ public sealed class SequenceViewModel : SectionViewModel
// with Remove local copy for a damaged one, when nothing else could be chosen (Main asked for, or the home has no
// other project); otherwise "Open in workspace" lists Main as it is, disabled, and offers the others.
WorkspaceEntry? unreadableMain = null;
if (entry is null && request?.ProjectId is null && await UnreadableMainAsync(workspace, row.Id) is { } main)
if (entry is null && request?.ProjectId is null && await UnreadableMainAsync(workspace, WorkspaceHost.ArchiveHome(row.Id)) is { } main)
{
if (request is { Main: true } || (await workspace.HomeProjectsAsync(row.Id)).All(p => p.IsMain))
{
@@ -664,10 +674,10 @@ public sealed class SequenceViewModel : SectionViewModel
return null;
}
/// <summary>The workspace's copy of the sequence's Main when this Chronos cannot read it (damaged, or a newer Chronos's); null otherwise.</summary>
private static async Task<WorkspaceEntry?> UnreadableMainAsync(WorkspaceHost workspace, Guid sequenceId)
/// <summary>The workspace's copy of the Main of <paramref name="home"/>'s sequence when this Chronos cannot read it (damaged, or a newer Chronos's); null otherwise.</summary>
private static async Task<WorkspaceEntry?> UnreadableMainAsync(WorkspaceHost workspace, BundleHome home)
{
if ((await workspace.HomeProjectsAsync(sequenceId)).FirstOrDefault(p => p.IsMain) is not { } main) return null;
if ((await workspace.HomeProjectsAsync(home)).FirstOrDefault(p => p.IsMain) is not { } main) return null;
return await workspace.FindAsync(main.Id) is { IsReadable: false } copy ? copy : null;
}
@@ -689,22 +699,137 @@ public sealed class SequenceViewModel : SectionViewModel
}
/// <summary>
/// "Open in workspace": the projects of the sequence's home, the media, what their copy writes and the room the
/// workspace's drive has; null when closed without a choice. <paramref name="unreadableMain"/>, the copy of Main here
/// this Chronos cannot read, is listed disabled, why in its tooltip.
/// A sequence of a server opens as a project of the workspace whose home is that server (phase 5b): the project asked
/// for, else the one of the sequence opened last here. One the workspace holds the media of opens from there, whether
/// this PC can reach the server or not (its sync, analyses and renders wait for it). Otherwise, signed in to a server
/// that keeps projects, the project is checked out, after "Open in workspace" asked which (when the sequence has none
/// here), and its media downloaded by a job; it opens once they are here. A copy this Chronos cannot read is refused as
/// for this PC's archive. Null when the server keeps no projects, or this PC is not signed in to it: the sequence then
/// opens with proxies as before (or says to connect).
/// </summary>
private async Task<OpenChoice?> AskProjectAsync(WorkspaceHost workspace, Sequence row, WorkspaceEntry? unreadableMain = null)
private async Task<ServerOpen?> OpenServerWorkspaceAsync(AppServices services, WorkspaceHost workspace, ChronosDatabase db, ImageDecoder decoder, Guid remoteId)
{
var projects = await workspace.HomeProjectsAsync(row.Id);
WorkspaceCopyFacts? copy = null;
var request = _requested is { } asked && asked.SequenceId == remoteId ? asked : null;
var entry = request switch
{
{ ProjectId: { } id } => await workspace.FindAsync(id) is { IsServerHome: true } found && found.SequenceId == remoteId ? found : null,
{ Main: true } => (await workspace.ProjectsOfAsync(remoteId)).FirstOrDefault(p => p is { IsMain: true, IsServerHome: true }),
_ => await workspace.LastUsedAsync(remoteId) is { IsServerHome: true } last ? last : null,
};
var sync = services.Sync;
if (entry is { IsReadable: false } unreadable)
{
TakeRequest(remoteId);
throw WorkspaceHost.Unreadable(unreadable);
}
if (entry is { HasMedia: true })
{
TakeRequest(remoteId);
workspace.Remember(remoteId, entry.ProjectId);
// Its analyses and renders travel on a connection of the signed-in session, when that is the project's server:
// made again whenever the sign-in changes, so a project opened signed out renders once signed in.
var server = entry.Home.Server;
var editorHome = new WorkspaceServerHome(() => string.Equals(sync.Server, server, StringComparison.OrdinalIgnoreCase) ? sync.ConnectEditor() : null,
() => sync.Session);
return new ServerOpen((new WorkspaceSequenceSource(workspace.Sync, entry.ProjectId, db, decoder, services.Engine, editorHome), entry.SequenceTitle));
}
// An account that may not edit checks nothing out: it is shown with proxies, read-only, as on an older server.
if (!sync.Policy.CanEdit || sync.ServerHome(remoteId) is not { } home) return null;
TakeRequest(remoteId);
try
{
copy = await workspace.CopyFactsAsync(row.Id);
var reached = workspace.Reachable(home);
var title = (await Task.Run(() => reached.SequenceAsync(CancellationToken.None))).Sequence.Title ?? entry?.SequenceTitle ?? string.Empty;
// No project of the sequence here opens and its Main here cannot be read: refused, or listed disabled, as for this PC's archive.
WorkspaceEntry? unreadableMain = null;
if (entry is null && request?.ProjectId is null && await UnreadableMainAsync(workspace, home) is { } main)
{
if (request is { Main: true } || (await workspace.HomeProjectsAsync(home)).All(p => p.IsMain))
{
RefuseUnreadable(main);
_afterOpen = null;
Shell.KeepSequence(OpenSequenceId);
return new ServerOpen(null);
}
unreadableMain = main;
}
var projectId = entry?.ProjectId ?? request?.ProjectId;
string? newName = null;
if (entry is null && projectId is { } wanted && (await workspace.HomeProjectsAsync(home)).All(p => p.Id != wanted))
{
// A project the server does not have (deleted there, or another server's): the sequence's Main opens instead.
Log.Info("workspace", $"Project {wanted} is not a project of server sequence {remoteId}; its Main opens instead");
projectId = null;
if (_afterOpen is { } pending && pending.Request.SequenceId == remoteId) _afterOpen = (ProjectRequest.MainOf(remoteId), pending.Action);
}
else if (entry is null && projectId is null && request is not { Main: true })
{
if (await AskProjectAsync(workspace, home, title, unreadableMain) is not { } choice)
{
_afterOpen = null;
Shell.KeepSequence(OpenSequenceId);
return new ServerOpen(null);
}
(projectId, newName) = (choice.ProjectId, choice.NewName);
}
WorkspaceCheckout checkout;
try
{
checkout = await workspace.CheckoutAsync(home, projectId, newName);
}
catch (WorkspaceException ex) when (ex.FolderRefused)
{
// Nothing was written: the way on is another workspace folder, offered from the refusal.
Log.Info("workspace", $"Server sequence {remoteId} not checked out: {ex.Message}");
Shell.Notify(Loc.L("Editor.Workspace.OpenFailed"), ex.Message, Loc.L("Editor.Workspace.ChooseFolder"), Loc.L("Tooltips.Editor.Workspace.ChooseFolder"),
() => _ = WorkspaceFolderChange.ChooseAsync(Shell), isError: true);
_afterOpen = null;
Shell.KeepSequence(OpenSequenceId);
return new ServerOpen(null);
}
await FollowCopyAsync(remoteId, title, checkout.Project.Id, checkout.Copy);
return new ServerOpen(null);
}
catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or InvalidOperationException or DatabaseException or UnauthorizedAccessException)
catch (ProjectException ex) when (ex.Reason == ProjectError.SequenceNotFound)
{
// Only shown: the copy measures again before it writes.
Log.Info("workspace", $"The copy of sequence {row.Id} could not be measured: {ex.Message}");
throw new InvalidOperationException(Loc.L("Editor.Error.Missing"), ex);
}
catch (ProjectException ex) when (ex.Reason == ProjectError.SequenceEmpty)
{
throw new InvalidOperationException(Loc.L("Editor.Error.Empty"), ex);
}
catch (HomeUnavailableException ex)
{
// Said of the server, not of this PC's library.
throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.Offline", server: true), ex);
}
}
/// <summary>"Open in workspace" for a sequence of this PC's archive; null when closed without a choice.</summary>
private Task<OpenChoice?> AskProjectAsync(WorkspaceHost workspace, Sequence row, WorkspaceEntry? unreadableMain = null) =>
AskProjectAsync(workspace, WorkspaceHost.ArchiveHome(row.Id), row.DisplayTitle, unreadableMain);
/// <summary>
/// "Open in workspace" for a sequence of <paramref name="home"/> (this PC's archive, or a server): its projects, the
/// media, and for this PC's archive what their copy writes and the room the workspace's drive has; null when closed
/// without a choice. <paramref name="unreadableMain"/>, the copy of Main here this Chronos cannot read, is listed
/// disabled, why in its tooltip.
/// </summary>
private async Task<OpenChoice?> AskProjectAsync(WorkspaceHost workspace, BundleHome home, string title, WorkspaceEntry? unreadableMain)
{
var projects = await workspace.HomeProjectsAsync(home);
WorkspaceCopyFacts? copy = null;
if (home.IsArchive)
{
try
{
copy = await workspace.CopyFactsAsync(home.SequenceId);
}
catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or InvalidOperationException or DatabaseException or UnauthorizedAccessException)
{
// Only shown: the copy measures again before it writes.
Log.Info("workspace", $"The copy of sequence {home.SequenceId} could not be measured: {ex.Message}");
}
}
var unreadable = unreadableMain is { } main
? new Dictionary<Guid, string>
@@ -712,7 +837,7 @@ public sealed class SequenceViewModel : SectionViewModel
[main.ProjectId] = Loc.L(main.Newer ? "Tooltips.Editor.Workspace.State.NewerCopy" : "Tooltips.Editor.Workspace.State.DamagedCopy"),
}
: null;
var dialog = new OpenInWorkspaceDialogViewModel(row.DisplayTitle, projects, d => CloseDialog(d), copy: copy, unreadable: unreadable);
var dialog = new OpenInWorkspaceDialogViewModel(title, projects, d => CloseDialog(d), copy: copy, unreadable: unreadable, server: !home.IsArchive);
// The picker or the open sequence shows behind the dialog meanwhile, not the progress bar.
IsLoading = false;
OpenDialog(dialog);
@@ -888,6 +1013,9 @@ public sealed class SequenceViewModel : SectionViewModel
}
}
/// <summary>What the open of a server sequence as a workspace project came to: its source, or null while it waits (its copy runs, the dialog was closed).</summary>
private sealed record ServerOpen((ISequenceSource Source, string Title)? Opened);
/// <summary>
/// A job an open waits on, with its engine subscription: a server sequence's proxy download, or the workspace copy of a
/// project's media (<see cref="ProjectId"/>: the project that opens when it is done).
+4 -4
View File
@@ -214,7 +214,7 @@
ToolTipService.ShowOnDisabled="True" Height="30" Margin="10,0,0,0" />
</Grid>
<!-- Header; the rows repeat its columns (Server.html: 1.6fr 150px 150px 150px 1.4fr with 10 px gaps). The list always
<!-- Header; the rows repeat its columns (Server.html: 1.6fr 150px 150px 150px 1.4fr with 10 px gaps). The actions column is at least wide enough for a row's three actions (Open with proxies, Download originals and an older server's disabled Open in workspace) on one line. The list always
keeps its 10 px scroll-bar gutter and the header the same on its right, so the columns line up with or without scrolling. -->
<Border Grid.Row="1" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,1" Padding="14,8,24,8">
<Grid>
@@ -223,7 +223,7 @@
<ColumnDefinition Width="160" />
<ColumnDefinition Width="160" />
<ColumnDefinition Width="160" />
<ColumnDefinition Width="1.4*" MinWidth="280" />
<ColumnDefinition Width="1.4*" MinWidth="400" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Header}" Text="{l:Loc Server.Sync.Column.Sequence}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Server.Sync.Column.Local}" Margin="10,0,0,0" />
@@ -247,7 +247,7 @@
<ColumnDefinition Width="160" />
<ColumnDefinition Width="160" />
<ColumnDefinition Width="160" />
<ColumnDefinition Width="1.4*" MinWidth="280" />
<ColumnDefinition Width="1.4*" MinWidth="400" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Title}" ToolTip="{Binding Title}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding LocalText}" ToolTip="{Binding LocalText}" Margin="10,0,0,0" />
@@ -260,7 +260,7 @@
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type srv:SyncRowAction}">
<Button Style="{StaticResource Button.Row}" Content="{Binding Text}" Command="{Binding Command}" ToolTip="{Binding ToolTip}"
AutomationProperties.Name="{Binding AccessibleName}" FontSize="12" Margin="0,2,6,2" />
ToolTipService.ShowOnDisabled="True" AutomationProperties.Name="{Binding AccessibleName}" FontSize="12" Margin="0,2,6,2" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
+13 -12
View File
@@ -169,12 +169,13 @@ public sealed class SettingsViewModel : SectionViewModel
Logs = new LogSettingsRows(_s, Save);
// ---- Workspace ----
WorkspaceRows = new WorkspaceSettingsRows(_s, Save, () => Shell.Services.Workspace.Root, OpenWorkspaceFolder, ChangeWorkspaceFolderAsync);
WorkspaceRows = new WorkspaceSettingsRows(_s, Save, () => AppEnvironment.Shown(Shell.Services.Workspace.Root), OpenWorkspaceFolder, ChangeWorkspaceFolderAsync);
// ---- Storage ----
CacheFolder = new EditableField(CacheStore.Folder(shell.Services.Environment, _s), v => ArchiveLocations.Validate(v), v =>
// A capture shows its folders under a sample data folder; what is typed is taken back to the folder it stands for.
CacheFolder = new EditableField(AppEnvironment.Shown(CacheStore.Folder(shell.Services.Environment, _s)), v => ArchiveLocations.Validate(AppEnvironment.Actual(v)), v =>
{
var full = Path.GetFullPath(v);
var full = Path.GetFullPath(AppEnvironment.Actual(v));
_s.CacheFolder = full.Equals(Shell.Services.Environment.CacheDirectory, StringComparison.OrdinalIgnoreCase) ? null : full;
Save();
_ = UpdateCacheUsageAsync();
@@ -222,8 +223,8 @@ public sealed class SettingsViewModel : SectionViewModel
RedetectCommand = new AsyncRelayCommand(DetectEncodersAsync, () => !_isDetecting && !_isTesting);
SelfTestCommand = new AsyncRelayCommand(SelfTestAsync, () => !_isDetecting && !_isTesting && Encoders.Any(e => e.Row.CanSelfTest));
ClearCacheCommand = new AsyncRelayCommand(ClearCacheAsync);
OpenDataFolderCommand = new RelayCommand(() => ShellActions.Reveal(DataFolder));
OpenLogsCommand = new RelayCommand(() => ShellActions.Reveal(LogsFolder));
OpenDataFolderCommand = new RelayCommand(() => ShellActions.Reveal(Shell.Services.Environment.DataDirectory));
OpenLogsCommand = new RelayCommand(() => ShellActions.Reveal(Shell.Services.Environment.LogDirectory));
ExportDiagnosticsCommand = new AsyncRelayCommand(ExportDiagnosticsAsync);
BackupDatabaseCommand = new AsyncRelayCommand(BackupDatabaseAsync, () => Shell.Services.Database is not null);
RedetectFormatsCommand = new AsyncRelayCommand(() => DetectFormatsAsync(refresh: true), () => !_isDetectingFormats);
@@ -785,8 +786,8 @@ public sealed class SettingsViewModel : SectionViewModel
// ---------------- Advanced ----------------
public string DataFolder => Shell.Services.Environment.DataDirectory;
public string LogsFolder => Shell.Services.Environment.LogDirectory;
public string DataFolder => AppEnvironment.Shown(Shell.Services.Environment.DataDirectory);
public string LogsFolder => AppEnvironment.Shown(Shell.Services.Environment.LogDirectory);
public string PortableText => Loc.L(Shell.Services.Environment.IsPortable ? "Settings.Advanced.PortableOn" : "Settings.Advanced.PortableOff");
/// <summary>Level, retention, size limits and rotation of the log files, and the diagnostics bundle's share of each.</summary>
@@ -877,10 +878,10 @@ public sealed class SettingsViewModel : SectionViewModel
var environment = Shell.Services.Environment;
if (environment.SyncedFolder is not null)
Shell.Notify(Loc.L("Settings.Advanced.DataInOneDrive"), Formatting.LeftToRight(DataFolder), Loc.L("Common.Open"),
Loc.L("Tooltips.Settings.DataInOneDrive"), () => ShellActions.Reveal(DataFolder), isError: true);
Loc.L("Tooltips.Settings.DataInOneDrive"), () => ShellActions.Reveal(Shell.Services.Environment.DataDirectory), isError: true);
else if (environment.PortableSyncRoot is not null)
Shell.Notify(Loc.L("Settings.Advanced.DataOutsideOneDrive"), Formatting.LeftToRight(DataFolder), Loc.L("Common.Open"),
Loc.L("Tooltips.Settings.OpenDataFolder"), () => ShellActions.Reveal(DataFolder));
Loc.L("Tooltips.Settings.OpenDataFolder"), () => ShellActions.Reveal(Shell.Services.Environment.DataDirectory));
if (environment.EarlierPortableData is { } earlier)
Shell.Notify(Loc.L("Settings.Advanced.EarlierData"), Formatting.LeftToRight(earlier), Loc.L("Common.Open"),
Loc.L("Tooltips.Settings.EarlierData"), () => ShellActions.Reveal(earlier));
@@ -1338,7 +1339,7 @@ public sealed class SettingsViewModel : SectionViewModel
{
Heading = Loc.L("Settings.Storage.ClearTitle"),
Message = Loc.L("Settings.Storage.ClearMessage"),
Detail = Formatting.LeftToRight(folder),
Detail = Formatting.LeftToRight(AppEnvironment.Shown(folder)),
DetailToolTip = Loc.L("Tooltips.Settings.CacheFolder"),
SafeText = Loc.L("Settings.Storage.Keep"),
SafeToolTip = Loc.L("Tooltips.Settings.KeepCache"),
@@ -1553,7 +1554,7 @@ public sealed class SettingsViewModel : SectionViewModel
_s.CacheFolder = null;
_s.ThumbnailMemoryItems = defaults.ThumbnailMemoryItems;
_s.CacheLimitGb = defaults.CacheLimitGb;
CacheFolder.Load(CacheStore.Folder(Shell.Services.Environment, _s));
CacheFolder.Load(AppEnvironment.Shown(CacheStore.Folder(Shell.Services.Environment, _s)));
ThumbnailMemory.Load(_s.ThumbnailMemoryItems.ToString(CultureInfo.CurrentCulture));
CacheLimit.Load(_s.CacheLimitGb.ToString(CultureInfo.CurrentCulture));
if (Shell.Services.Thumbnails is { } thumbs) thumbs.Capacity = _s.ThumbnailMemoryItems;
@@ -1670,7 +1671,7 @@ public sealed class SettingsViewModel : SectionViewModel
LoadImportFields();
LoadAnalysisFields();
Parallelism.Load(EffectiveParallelism.ToString(CultureInfo.CurrentCulture));
CacheFolder.Load(CacheStore.Folder(Shell.Services.Environment, _s));
CacheFolder.Load(AppEnvironment.Shown(CacheStore.Folder(Shell.Services.Environment, _s)));
ThumbnailMemory.Load(_s.ThumbnailMemoryItems.ToString(CultureInfo.CurrentCulture));
CacheLimit.Load(_s.CacheLimitGb.ToString(CultureInfo.CurrentCulture));
if (Shell.Services.Thumbnails is { } thumbs) thumbs.Capacity = _s.ThumbnailMemoryItems;
+82 -6
View File
@@ -3,9 +3,12 @@ using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.Core.Diagnostics;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Protocol.Client;
namespace Chronos.App.Server;
@@ -15,23 +18,28 @@ public delegate ISyncRemote SyncRemoteFactory(Uri address, string token, IReadOn
/// <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"/>.
/// connection of upload and download jobs (<see cref="ISyncConnector"/>, also the workspace copies of server projects), 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"/>), the server as the home of workspace projects when it keeps projects (owner review 2, R8,
/// phase 5b: <see cref="ProjectHome"/>, <see cref="ProjectChanged"/>) 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 readonly Lock _gate = new();
private Task _switch = Task.CompletedTask;
private Credentials? _credentials;
private Running? _running;
private JobEngine? _renders;
/// <summary>The client project homes of the session share, made at first use for the credentials it holds.</summary>
private SharedClient? _projects;
/// <summary>Connections over <see cref="ChronosClient"/>; screenshots substitute a fake server.</summary>
public SyncRemoteFactory RemoteFactory { get; set; } = (address, token, trusted) =>
new ChronosSyncRemote(new ChronosClient(address, new CertificatePinning(trusted), $"Chronos ({Environment.MachineName})") { Token = token }, ownsClient: true);
@@ -40,6 +48,10 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
public RemoteSequenceApiFactory EditorFactory { get; set; } = (address, token, trusted) =>
new ChronosRemoteSequenceApi(new ChronosClient(address, new CertificatePinning(trusted), $"Chronos ({Environment.MachineName})") { Token = token });
/// <summary>The client the session's project homes share (<see cref="ProjectHome"/>); tests substitute one of their own.</summary>
public Func<Uri, string, IReadOnlyCollection<string>, ChronosClient> ProjectClientFactory { get; set; } = (address, token, trusted) =>
new ChronosClient(address, new CertificatePinning(trusted), $"Chronos ({Environment.MachineName})") { Token = token };
/// <summary>The engine; null until the index is open.</summary>
public SyncService? Service { get; private set; }
@@ -61,6 +73,38 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
/// <summary>The signed-in account may queue renders on the server.</summary>
public bool CanRender => Allows(Permissions.Render);
/// <summary>
/// The signed-in server keeps its sequences' projects (owner review 2, R8: the <c>projects</c> capability), so Edit opens
/// its sequences as workspace projects; false while signed out and for an older server, whose sequences Edit opens with
/// proxies as before.
/// </summary>
public bool HasProjects =>
services.Server.IsConnected && services.Server.Flow.Info?.Capabilities is { } capabilities && capabilities.Contains(ServerCapabilities.Projects);
/// <summary>The home of a workspace project of server sequence <paramref name="remoteId"/>; null while signed out or when the server keeps no projects.</summary>
public BundleHome? ServerHome(Guid remoteId) => Server is { } server && HasProjects ? new BundleHome(BundleHome.ServerKind, remoteId, null, server) : null;
/// <summary>
/// The project home of a workspace project whose home is a server (<see cref="ServerProjectHome"/> over the session's
/// client); null while signed out, signed in to another server, or when the server keeps no projects: the workspace then
/// shows the project offline and its work waits.
/// </summary>
public IProjectHome? ProjectHome(BundleHome home)
{
ArgumentNullException.ThrowIfNull(home);
if (home.IsArchive || !HasProjects || Volatile.Read(ref _credentials) is not { } credentials
|| !string.Equals(home.Server, SyncService.ServerKey(credentials.Address), StringComparison.OrdinalIgnoreCase))
return null;
return new ServerProjectHome(SessionClient(credentials), home.SequenceId, services.Server.ServerName);
}
/// <summary>
/// A project of a sequence of the signed-in server changed there (the server's key, and its <c>projectChanged</c>), or,
/// with null, changes may have been missed while its events were lost, or the session with that server started or
/// stopped (its projects become reachable, or offline) (any thread).
/// </summary>
public event Action<string, ProjectChangedEvent?>? ProjectChanged;
/// <summary>Pauses uploads while the connection is metered and the option is on.</summary>
public UploadHold Uploads { get; } = new(services);
@@ -96,6 +140,9 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
engine.JobChanged += OnJobChanged;
}
/// <summary>The sign-in <see cref="ConnectEditor"/> uses now (another object once signed in anew); null while signed out.</summary>
public object? Session => Volatile.Read(ref _credentials);
/// <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;
@@ -146,10 +193,31 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
if (_renders is not null) _renders.JobChanged -= OnJobChanged;
await _switch.ConfigureAwait(false);
await StopAsync().ConfigureAwait(false);
lock (_gate)
{
_projects?.Client.Dispose();
_projects = null;
}
}
private bool Allows(Permissions permission) => services.Server.User is { } user && (user.Permissions & (long)permission) != 0;
/// <summary>
/// The client of <paramref name="credentials"/>' session, made once for its address and token: another sign-in replaces
/// it (a call still on the old one fails as a server out of reach, and is tried again on the new one).
/// </summary>
private ChronosClient SessionClient(Credentials credentials)
{
lock (_gate)
{
if (_projects is { } current && current.Address == credentials.Address && current.Token == credentials.Token) return current.Client;
_projects?.Client.Dispose();
var client = ProjectClientFactory(credentials.Address, credentials.Token, credentials.Fingerprints);
_projects = new SharedClient(credentials.Address, credentials.Token, client);
return client;
}
}
/// <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.
@@ -196,7 +264,10 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
await previous.ConfigureAwait(false);
if (Volatile.Read(ref _running) is { } running && wanted is { } same && running.Credentials.Address == same.Address && running.Credentials.Token == same.Token)
return;
var stopped = Volatile.Read(ref _running)?.Remote.Server;
await StopAsync().ConfigureAwait(false);
// The projects of the server left are offline now: their state is read again.
if (stopped is not null) ProjectChanged?.Invoke(stopped, null);
if (wanted is not { } start || Service is not { } service)
{
Changed?.Invoke();
@@ -205,10 +276,12 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
var remote = RemoteFactory(start.Address, start.Token, start.Fingerprints);
var agent = new SyncAgent(service, remote, () => Policy, services.Engine);
agent.Changed += () => Changed?.Invoke();
agent.ProjectChanged += e => ProjectChanged?.Invoke(remote.Server, e);
agent.Start();
Volatile.Write(ref _running, new Running(agent, remote, start));
Log.Info("sync", $"Comparing with {remote.Server}");
Changed?.Invoke();
ProjectChanged?.Invoke(remote.Server, null);
}
private async Task StopAsync()
@@ -221,6 +294,9 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
private sealed record Credentials(Uri Address, string Token, IReadOnlyCollection<string> Fingerprints);
/// <summary>The client project homes share, and the session it was made for.</summary>
private sealed record SharedClient(Uri Address, string Token, ChronosClient Client);
/// <summary>The agent of the signed-in session: one reference, so the UI thread never reads half of a switch.</summary>
private sealed record Running(SyncAgent Agent, ISyncRemote Remote, Credentials Credentials);
}
+27 -6
View File
@@ -8,14 +8,22 @@ using Chronos.Ui.Mvvm;
namespace Chronos.App.Server;
/// <summary>A row button: "Upload", "Keep mine", …; kept while the row offers it, so focus, tooltips and clicks survive updates.</summary>
public sealed class SyncRowAction(SyncAction action, ICommand command) : ObservableObject
public sealed class SyncRowAction : ObservableObject
{
private readonly AsyncRelayCommand _command;
private string _toolTip = string.Empty;
private string _sequence = string.Empty;
private bool _isEnabled = true;
public SyncAction Action { get; } = action;
public SyncRowAction(SyncAction action, Func<Task> execute)
{
Action = action;
_command = new AsyncRelayCommand(execute, () => _isEnabled);
}
public SyncAction Action { get; }
public string Text => Loc.L("Server.Sync.Action." + Action);
public ICommand Command { get; } = command;
public ICommand Command => _command;
public string ToolTip
{
@@ -23,6 +31,16 @@ public sealed class SyncRowAction(SyncAction action, ICommand command) : Observa
set => Set(ref _toolTip, value);
}
/// <summary>The button can be pressed (Open in workspace cannot on a server that keeps no projects; its tooltip says why).</summary>
public bool IsEnabled
{
get => _isEnabled;
set
{
if (Set(ref _isEnabled, value)) _command.RaiseCanExecuteChanged();
}
}
/// <summary>The title of the row's sequence.</summary>
public string Sequence
{
@@ -49,6 +67,7 @@ public sealed class SyncRow : ObservableObject
{
private readonly Func<SyncRow, SyncAction, Task> _act;
private SyncEntry _entry;
private SyncRights _rights;
private IReadOnlyList<SyncRowAction> _actions = [];
public SyncRow(SyncEntry entry, SyncRights rights, Func<SyncRow, SyncAction, Task> act)
@@ -103,22 +122,24 @@ public sealed class SyncRow : ObservableObject
foreach (var action in _actions)
{
action.Relabel();
action.ToolTip = SyncText.ToolTip(_entry, action.Action);
action.ToolTip = SyncText.ToolTip(_entry, action.Action, _rights);
}
RaiseTexts();
}
private void UpdateActions(SyncRights rights)
{
_rights = rights;
var wanted = SyncText.Actions(_entry, rights);
if (!wanted.SequenceEqual(_actions.Select(a => a.Action)))
{
var kept = _actions.ToDictionary(a => a.Action);
Actions = [.. wanted.Select(action => kept.GetValueOrDefault(action) ?? new SyncRowAction(action, new AsyncRelayCommand(() => _act(this, action))))];
Actions = [.. wanted.Select(action => kept.GetValueOrDefault(action) ?? new SyncRowAction(action, () => _act(this, action)))];
}
foreach (var action in _actions)
{
action.ToolTip = SyncText.ToolTip(_entry, action.Action);
action.ToolTip = SyncText.ToolTip(_entry, action.Action, rights);
action.IsEnabled = SyncText.IsEnabled(action.Action, rights);
action.Sequence = Title;
}
}
+7 -1
View File
@@ -171,7 +171,7 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
private SyncHost Host => _shell.Services.Sync;
private SyncRights Rights => _shell.Services.Server.User is { } user ? SyncRights.Of(user.Permissions) : default;
private SyncRights Rights => _shell.Services.Server.User is { } user ? SyncRights.Of(user.Permissions) with { KeepsProjects = Host.HasProjects } : default;
private IEnumerable<SyncEntry> LocalOnly => _entries.Where(e => e.Status == SyncStatus.LocalOnly);
@@ -326,6 +326,12 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
case SyncAction.GetExports:
await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Exports, null);
break;
// Edit opens it as a workspace project of the server: the project opened last, else "Open in workspace" asks (phase 5b).
case SyncAction.OpenInWorkspace when Host.HasProjects:
_shell.OpenSequence(entry.Id);
return;
case SyncAction.OpenInWorkspace:
return;
case SyncAction.OpenWithProxies when entry.Status == SyncStatus.ProxiesOnly && service.OpenRemote(server, entry.Id) is not null:
_shell.OpenSequence(entry.Id);
return;
+22 -4
View File
@@ -33,13 +33,20 @@ public enum SyncAction
SendExports,
Pause,
Resume,
/// <summary>
/// Edit a project of the server's sequence in the workspace (owner review 2, R8, phase 5b): offered disabled by a server
/// that keeps no projects, whose sequences open with proxies as before.
/// </summary>
OpenInWorkspace,
}
/// <summary>What the signed-in account may do (server permission bits).</summary>
/// <summary>What the signed-in account may do (server permission bits), and whether its server keeps projects.</summary>
/// <param name="CanUpload">Send originals, settings and renders (upload and edit rights).</param>
/// <param name="CanFetchOriginals">Download originals (editors and render nodes).</param>
/// <param name="CanEdit">Change the server's copy of a sequence's settings, title, tags, rating and notes.</param>
public readonly record struct SyncRights(bool CanUpload, bool CanFetchOriginals, bool CanEdit)
/// <param name="KeepsProjects">The server keeps its sequences' projects (the <c>projects</c> capability): they open in the workspace.</param>
public readonly record struct SyncRights(bool CanUpload, bool CanFetchOriginals, bool CanEdit, bool KeepsProjects = false)
{
public static SyncRights Of(long permissions) => new(
(permissions & (long)Permissions.Upload) != 0 && (permissions & (long)Permissions.Edit) != 0,
@@ -227,9 +234,16 @@ public static class SyncText
case SyncStatus.LocalOnly when rights.CanUpload:
actions.Add(SyncAction.Upload);
break;
// A server that keeps projects edits its sequences in the workspace; an older one's open with proxies, the
// workspace offered disabled with the reason (phase 5b). An account that may not edit only looks: with proxies.
case SyncStatus.RemoteOnly or SyncStatus.ProxiesOnly when rights is { KeepsProjects: true, CanEdit: true }:
actions.Add(SyncAction.OpenInWorkspace);
if (rights.CanFetchOriginals) actions.Add(SyncAction.DownloadOriginals);
break;
case SyncStatus.RemoteOnly or SyncStatus.ProxiesOnly:
actions.Add(SyncAction.OpenWithProxies);
if (rights.CanFetchOriginals) actions.Add(SyncAction.DownloadOriginals);
if (!rights.KeepsProjects) actions.Add(SyncAction.OpenInWorkspace);
break;
case SyncStatus.LocalAhead when entry.Link is { MissingRemote: > 0 }:
if (rights.CanUpload) actions.Add(SyncAction.Upload);
@@ -265,12 +279,16 @@ public static class SyncText
_ => 0,
};
/// <summary>The tooltip of a row button: what it does and, for transfers, what it moves.</summary>
public static string ToolTip(SyncEntry entry, SyncAction action) => action switch
/// <summary>Whether a row button can be pressed: all can, but Open in workspace on a server that keeps no projects.</summary>
public static bool IsEnabled(SyncAction action, SyncRights rights) => action != SyncAction.OpenInWorkspace || rights.KeepsProjects;
/// <summary>The tooltip of a row button: what it does and, for transfers, what it moves; why not, for one disabled.</summary>
public static string ToolTip(SyncEntry entry, SyncAction action, SyncRights rights = default) => action switch
{
SyncAction.Upload or SyncAction.DownloadOriginals => Loc.L("Tooltips.Server.Sync." + action, Formatting.Bytes(Size(entry, action))),
SyncAction.GetExports => Loc.Plural("Tooltips.Server.Sync.GetExports", entry.Link!.ExportsToGet, Formatting.Bytes(Size(entry, action))),
SyncAction.SendExports => Loc.Plural("Tooltips.Server.Sync.SendExports", entry.Link!.ExportsToSend, Formatting.Bytes(Size(entry, action))),
SyncAction.OpenInWorkspace when !rights.KeepsProjects => Loc.L("Tooltips.Server.Sync.OpenInWorkspace.NoProjects"),
_ => Loc.L("Tooltips.Server.Sync." + action),
};
+154 -36
View File
@@ -9,6 +9,7 @@ using Chronos.Core.Project;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Data.Workspaces;
using Chronos.Protocol;
using Chronos.Ui.Controls;
using Chronos.Ui.Mvvm;
@@ -54,13 +55,19 @@ public interface IWorkspaceUi
/// banner when the home's frames moved past the workspace's. Every operation first stores the editor's last edit; what a
/// pull, a restore or taking the library's values changed comes back into the editor (merged, or as an undo step). A
/// conflict is asked about only when the merge met settings both sides changed, and a choice settles only the conflict
/// shown; one an automatic sync met waits for the dialog open to close. Call from the UI thread.
/// shown; one an automatic sync met waits for the dialog open to close. A project whose home is a server (phase 5b) words
/// its texts for the server, follows what the server tells of it (<see cref="WorkspaceHost.HomeChanged"/>: the chip reads
/// Server newer, or that the server no longer has it, its copy kept here), and renders only what the server holds
/// (<see cref="ReadyToRenderAsync"/>). Call from the UI thread.
/// </summary>
public sealed class ProjectMenuViewModel : LocalizedViewModel
{
/// <summary>How long after the last edit the chip reads the working state again (a little after the editor's save).</summary>
public static readonly TimeSpan StateRefreshDelay = TimeSpan.FromMilliseconds(600);
/// <summary>How long after an analysis ended a change the home tells is taken as its Auto values reaching Main.</summary>
private static readonly TimeSpan AnalysisTake = TimeSpan.FromMinutes(2);
private readonly WorkspaceHost _host;
private readonly WorkspaceSequenceSource _source;
private readonly EditorSession _session;
@@ -82,6 +89,12 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
/// <summary>The conflict dialog asked in the background, until it is closed (one is asked at a time).</summary>
private ConflictDialogViewModel? _asking;
/// <summary>
/// When an analysis of the sequence ended while Sync automatically is on and the home had not told its new Main yet
/// (a server catches up a moment later): the change it tells next is taken.
/// </summary>
private DateTime? _analysisEnded;
public ProjectMenuViewModel(WorkspaceHost host, WorkspaceSequenceSource source, EditorSession session, IWorkspaceUi ui)
{
_host = host;
@@ -99,6 +112,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
RemoveCopyCommand = new AsyncRelayCommand(OpenRemoveCopyAsync);
source.JobChanged += OnJobChanged;
session.ProjectChanged += OnProjectChanged;
host.HomeChanged += OnHomeChanged;
}
public Guid ProjectId => _source.ProjectId;
@@ -107,6 +121,9 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
public bool IsMain => _source.Workspace?.IsMain == true;
/// <summary>The project's home is a server (phase 5b): its texts name the server, its renders are of what the server holds.</summary>
public bool IsServerHome => _source.IsServerHome;
/// <summary>The project's name (Main in the UI language).</summary>
public string Name => _source.Workspace is { } workspace ? WorkspaceText.ProjectName(workspace.Name, workspace.IsMain) : string.Empty;
@@ -114,11 +131,11 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
public bool IsSyncing => _isSyncing;
public string StateText => WorkspaceText.State(_status, _isSyncing);
public string StateText => WorkspaceText.State(_status, _isSyncing, IsServerHome);
public StatusKind StateKind => WorkspaceText.Kind(_status, _isSyncing);
public string StateToolTip => WorkspaceText.StateToolTip(_status, _isSyncing);
public string StateToolTip => WorkspaceText.StateToolTip(_status, _isSyncing, IsServerHome);
/// <summary>The ▾ button: its name, then where the project stands, then what the menu holds.</summary>
public string MenuToolTip => Loc.L("Tooltips.Editor.Project.Menu", Name, StateText);
@@ -136,17 +153,25 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
/// <summary>A copy of the media runs (Update media): the banner says so.</summary>
public bool IsUpdatingMedia => _copyJob != Guid.Empty;
public string MediaUpdateText => Loc.L(IsUpdatingMedia ? "Editor.Workspace.Updating" : "Editor.Workspace.MediaChanged");
public string MediaUpdateText => IsUpdatingMedia ? Loc.L("Editor.Workspace.Updating") : WorkspaceText.ForHome("Editor.Workspace.MediaChanged", IsServerHome);
public string MediaChangedToolTip => WorkspaceText.ForHome("Tooltips.Editor.Workspace.MediaChanged", IsServerHome);
public string UpdateMediaToolTip => WorkspaceText.ForHome("Tooltips.Editor.Workspace.UpdateMedia", IsServerHome);
/// <summary>A version can be saved: the settings are this Chronos's, no conflict waits, the media are here and the library still has the project.</summary>
public bool CanSaveVersion => !_session.IsReadOnly && _status is not { Conflict: not null } and not { MediaRemoved: true } and not { State: WorkspaceState.Gone };
public string SaveVersionToolTip => _session.IsReadOnly ? Loc.L("Errors.Workspace.ReadOnly")
: _status?.State == WorkspaceState.Gone ? Loc.L("Errors.Workspace.DeletedAtHome")
: _status?.State == WorkspaceState.Gone ? WorkspaceText.ForHome("Errors.Workspace.DeletedAtHome", IsServerHome)
: _status?.Conflict is not null ? Loc.L("Errors.Workspace.Conflict")
: Loc.L("Tooltips.Editor.Project.SaveVersion");
public string DeleteToolTip => IsMain ? Loc.L("Errors.Workspace.MainKept") : Loc.L("Tooltips.Editor.Project.Delete");
public string DeleteToolTip => IsMain ? Loc.L("Errors.Workspace.MainKept") : WorkspaceText.ForHome("Tooltips.Editor.Project.Delete", IsServerHome);
public string RenameToolTip => WorkspaceText.ForHome("Tooltips.Editor.Project.Rename", IsServerHome);
public string RemoveCopyToolTip => WorkspaceText.ForHome("Tooltips.Editor.Project.RemoveCopy", IsServerHome);
/// <summary>Save version… (Ctrl+S): the note dialog.</summary>
public ICommand SaveVersionCommand { get; }
@@ -195,6 +220,55 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
await RefreshAsync();
if (_disposed || !_host.Settings.WorkspaceAutoSync || job.Kind is not (JobKind.DeepAnalyse or JobKind.LightAnalyse)) return;
if (_status is { State: WorkspaceState.Behind }) await SyncAsync(quiet: true);
// A server writes the Auto values into Main a moment after its analysis ends: what it tells next is taken then.
else if (IsServerHome) _analysisEnded = DateTime.UtcNow;
}
/// <summary>
/// Before a render (phase 5b): a project whose home is a server renders what the server holds, so changes not saved as a
/// version, or versions not sent, are first offered to be saved and sent (Sync); false when the user kept them here,
/// the server could not take them or no longer has the project, or a conflict waits. A project of this PC's archive
/// renders as it is: true.
/// </summary>
public async Task<bool> ReadyToRenderAsync()
{
if (!IsServerHome) return true;
await StoreEditAsync();
var status = await _host.StatusAsync(ProjectId);
if (_disposed) return false;
Apply(status);
if (status.State is WorkspaceState.Gone or WorkspaceState.Offline or WorkspaceState.Damaged or WorkspaceState.MediaRemoved)
{
_ui.Notify(Loc.L("Editor.Workspace.RenderHeld"), WorkspaceText.StateToolTip(status, server: true), isError: status.State != WorkspaceState.Offline);
return false;
}
if (status.Conflict is not null)
{
AskConflict(status.Conflict);
return false;
}
if (status.Ahead == 0 && !status.Modified && _source.InStepWithHome(_session.Project) is not null) return true;
if (!_ui.Confirm(new ConfirmRequest
{
Heading = Loc.L("Editor.Workspace.SendFirst.Title"),
Message = Loc.L("Editor.Workspace.SendFirst.Message", Name),
SafeText = Loc.L("Editor.Project.Keep"),
SafeToolTip = Loc.L("Tooltips.Editor.Workspace.SendFirst.Keep"),
ActionText = Loc.L("Editor.Workspace.SendFirst.Action"),
ActionToolTip = Loc.L("Tooltips.Editor.Workspace.SendFirst.Action"),
}))
return false;
try
{
await SaveAndSendAsync();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Project {ProjectId} could not be sent before its render", ex);
_ui.Notify(Loc.L("Editor.Workspace.RenderHeld"), WorkspaceText.Failure(ex, server: true), isError: ex is not HomeUnavailableException);
return false;
}
return !_disposed && _source.InStepWithHome(_session.Project) is not null;
}
/// <summary>
@@ -222,7 +296,8 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
{
_ui.Notify(Loc.L("Editor.Workspace.Saved", Formatting.Count(result.Version.Number)), Name);
}
if (result.SyncError is { } error) _ui.Notify(Loc.L("Editor.Workspace.NotSent"), WorkspaceText.Failure(error), isError: error is not HomeUnavailableException);
if (result.SyncError is { } error)
_ui.Notify(Loc.L("Editor.Workspace.NotSent"), WorkspaceText.Failure(error, IsServerHome), isError: error is not HomeUnavailableException);
// Deleted in the library: said once, and no conflict is asked (nothing can be merged with it); the version stays here.
if (result.Status.State == WorkspaceState.Gone) NotifyGone();
else if (result.Status.Conflict is { } conflict) AskConflict(conflict);
@@ -250,8 +325,8 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Project {ProjectId} could not be synced", ex);
_ui.Notify(Loc.L(ex is HomeUnavailableException ? "Editor.Workspace.Offline" : "Editor.Workspace.SyncFailed"), WorkspaceText.Failure(ex),
isError: ex is not HomeUnavailableException);
_ui.Notify(ex is HomeUnavailableException ? WorkspaceText.ForHome("Editor.Workspace.Offline", IsServerHome) : Loc.L("Editor.Workspace.SyncFailed"),
WorkspaceText.Failure(ex, IsServerHome), isError: ex is not HomeUnavailableException);
await RefreshAsync();
}
finally
@@ -288,7 +363,8 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
if (result.Kept is { } kept)
{
if (await _session.TakeOverAsync(kept) is { } step)
_ui.Notify(Loc.L("Editor.Workspace.TookLibrary"), Name, Loc.L("Editor.Workspace.Undo"), Loc.L("Tooltips.Editor.Workspace.UndoTake"), () => step.Undo());
_ui.Notify(WorkspaceText.ForHome("Editor.Workspace.TookLibrary", IsServerHome), Name, Loc.L("Editor.Workspace.Undo"),
WorkspaceText.ForHome("Tooltips.Editor.Workspace.UndoTake", IsServerHome), () => step.Undo());
if (result.Pushed.Count > 0 && IsMain) await _ui.SequenceChangedAsync(SequenceId);
}
else
@@ -307,8 +383,9 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
() => _ = _ui.OpenProjectAsync(sequenceId, copy.Id));
}
/// <summary>The library no longer has the project: nothing more is sent, its work stays here (Remove local copy keeps it aside).</summary>
private void NotifyGone() => _ui.Notify(Loc.L("Editor.Workspace.State.Gone"), Loc.L("Errors.Workspace.DeletedAtHome"));
/// <summary>The home no longer has the project: nothing more is sent, its work stays here (Remove local copy keeps it aside).</summary>
private void NotifyGone() =>
_ui.Notify(WorkspaceText.ForHome("Editor.Workspace.State.Gone", IsServerHome), WorkspaceText.ForHome("Errors.Workspace.DeletedAtHome", IsServerHome));
/// <summary>
/// Restores <paramref name="version"/> as the project, as one undo step (uncommitted changes are saved as a version
@@ -355,6 +432,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
_disposed = true;
_source.JobChanged -= OnJobChanged;
_session.ProjectChanged -= OnProjectChanged;
_host.HomeChanged -= OnHomeChanged;
// A conflict still waiting to be asked belongs to this editor: it is not asked once the editor closed (Sync asks it next time).
if (_asking is { } waiting && !ReferenceEquals(waiting, _ui.Dialog)) waiting.Dispose();
base.Dispose();
@@ -369,12 +447,12 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
private void OpenSaveVersion()
{
if (!CanSaveVersion) return;
_ui.ShowDialog(new SaveVersionDialogViewModel(Name, SaveVersionAsync, _ui.CloseDialog));
_ui.ShowDialog(new SaveVersionDialogViewModel(Name, SaveVersionAsync, _ui.CloseDialog, IsServerHome));
}
private async Task OpenHistoryAsync()
{
var dialog = new HistoryDialogViewModel(Name, v => Task.FromResult(Compare(v)), RestoreAsync, _ui.CloseDialog);
var dialog = new HistoryDialogViewModel(Name, v => Task.FromResult(Compare(v)), RestoreAsync, _ui.CloseDialog, IsServerHome);
_ui.ShowDialog(dialog);
try
{
@@ -389,8 +467,11 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
}
}
/// <summary>The project's home (this PC's archive, or a server).</summary>
private BundleHome Home => _source.Workspace?.Home ?? WorkspaceHost.ArchiveHome(SequenceId);
/// <summary>
/// Open project…: "Open in workspace" over the library's projects of the sequence but the open one (a Save both
/// Open project…: "Open in workspace" over the home's projects of the sequence but the open one (a Save both
/// sibling, another PC's), or a new one; the choice opens in place of this one (checked out and copied when it is not
/// here yet).
/// </summary>
@@ -399,32 +480,34 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
try
{
await StoreEditAsync();
var projects = (await _host.HomeProjectsAsync(SequenceId)).Where(p => p.Id != ProjectId).ToList();
var home = Home;
var projects = (await _host.HomeProjectsAsync(home)).Where(p => p.Id != ProjectId).ToList();
var dialog = new OpenInWorkspaceDialogViewModel(_session.Content.Sequence.DisplayTitle, projects, _ui.CloseDialog,
[.. projects.Select(p => p.Name).Append(_source.Workspace?.Name ?? string.Empty)]);
[.. projects.Select(p => p.Name).Append(_source.Workspace?.Name ?? string.Empty)], server: IsServerHome);
_ui.ShowDialog(dialog);
if (await dialog.Choice is not { } choice || _disposed) return;
var id = choice.ProjectId ?? (await _host.CreateProjectAsync(SequenceId, choice.NewName!, _status?.Base?.VersionId)).Id;
var id = choice.ProjectId ?? (await _host.CreateProjectAsync(home, choice.NewName!, _status?.Base?.VersionId)).Id;
await _ui.OpenProjectAsync(SequenceId, id);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Another project of sequence {SequenceId} could not be opened", ex);
_ui.Notify(Loc.L("Editor.Workspace.OpenFailed"), WorkspaceText.Failure(ex), isError: true);
_ui.Notify(Loc.L("Editor.Workspace.OpenFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
}
}
private async Task OpenNewProjectAsync()
{
var names = await OtherNamesAsync(null);
var home = Home;
_ui.ShowDialog(new ProjectNameDialogViewModel(false, string.Empty, names, async name =>
{
await StoreEditAsync();
// From the open project's last version at the home, so the new one starts where this one is there.
var created = await _host.CreateProjectAsync(SequenceId, name, _status?.Base?.VersionId);
var created = await _host.CreateProjectAsync(home, name, _status?.Base?.VersionId);
_ui.Notify(Loc.L("Editor.Workspace.Created", created.Name), _session.Content.Sequence.DisplayTitle);
_ = _ui.OpenProjectAsync(SequenceId, created.Id);
}, _ui.CloseDialog));
}, _ui.CloseDialog, IsServerHome));
}
private async Task OpenRenameAsync()
@@ -436,7 +519,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
await _session.ReloadAsync();
_ui.Notify(Loc.L("Editor.Workspace.Renamed"), name);
RaiseState();
}, _ui.CloseDialog));
}, _ui.CloseDialog, IsServerHome));
}
private async Task DeleteAsync()
@@ -446,11 +529,11 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
if (!_ui.Confirm(new ConfirmRequest
{
Heading = Loc.L("Editor.Project.DeleteTitle", name),
Message = Loc.L("Editor.Project.DeleteMessage"),
Message = WorkspaceText.ForHome("Editor.Project.DeleteMessage", IsServerHome),
SafeText = Loc.L("Editor.Project.Keep"),
SafeToolTip = Loc.L("Tooltips.Editor.Project.Keep"),
ActionText = Loc.L("Editor.Project.DeleteAction"),
ActionToolTip = Loc.L("Tooltips.Editor.Project.DeleteAction"),
ActionToolTip = WorkspaceText.ForHome("Tooltips.Editor.Project.DeleteAction", IsServerHome),
IsDestructive = true,
}))
return;
@@ -468,7 +551,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Project {ProjectId} was not deleted", ex);
_ui.Notify(Loc.L("Editor.Workspace.DeleteFailed"), WorkspaceText.Failure(ex), isError: true);
_ui.Notify(Loc.L("Editor.Workspace.DeleteFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
}
}
@@ -483,12 +566,12 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
{
await SaveAndSendAsync();
await RemoveAsync(projectId, discard: false);
}, () => RemoveCopyDialogViewModel.ConfirmDiscard(_ui, name), _ui.CloseDialog));
}, () => RemoveCopyDialogViewModel.ConfirmDiscard(_ui, name), _ui.CloseDialog, IsServerHome));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The removal of project {ProjectId} could not be planned", ex);
_ui.Notify(Loc.L("Editor.Workspace.RemoveFailed"), WorkspaceText.Failure(ex), isError: true);
_ui.Notify(Loc.L("Editor.Workspace.RemoveFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
}
}
@@ -504,14 +587,15 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
var result = await _host.SyncAsync(ProjectId);
Apply(result.Status);
await TakeAsync(result);
// Nothing can be sent to a project the library no longer has: only Discard takes the copy, its work kept aside.
if (result.Status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"));
// Nothing can be sent to a project the home no longer has: only Discard takes the copy, its work kept aside.
if (result.Status.State == WorkspaceState.Gone) throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.DeletedAtHome", IsServerHome));
if (result.Status.Conflict is { } conflict)
{
AskConflict(conflict);
throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
}
if (result.Status is { Ahead: > 0 } or { Modified: true, ReadOnly: false }) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
if (result.Status is { Ahead: > 0 } or { Modified: true, ReadOnly: false })
throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.Unsent", IsServerHome));
}
private async Task RemoveAsync(Guid projectId, bool discard)
@@ -520,7 +604,8 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
if (!discard)
{
var status = await _host.StatusAsync(projectId, askHome: false);
if (status is { Ahead: > 0 } or { Conflict: not null } or { Modified: true, ReadOnly: false }) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
if (status is { Ahead: > 0 } or { Conflict: not null } or { Modified: true, ReadOnly: false })
throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.Unsent", IsServerHome));
}
var name = Name;
if (!await _ui.CloseProjectAsync()) return;
@@ -532,7 +617,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
{
try
{
return [.. (await _host.HomeProjectsAsync(SequenceId)).Where(p => p.Id != except).Select(p => p.Name)];
return [.. (await _host.HomeProjectsAsync(Home)).Where(p => p.Id != except).Select(p => p.Name)];
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
@@ -555,7 +640,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The media of project {ProjectId} could not be copied again", ex);
_ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), WorkspaceText.Failure(ex), isError: true);
_ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
}
}
@@ -582,9 +667,9 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
private void AskConflict(WorkspaceConflict conflict, bool background = false)
{
if (background && _asking is { IsClosed: false }) return;
var lines = WorkspaceText.ConflictLines(conflict.Differences, 10);
var lines = WorkspaceText.ConflictLines(conflict.Differences, 10, IsServerHome);
var dialog = new ConflictDialogViewModel(Name, WorkspaceHost.SiblingName(_source.Workspace?.Name ?? Name), lines, choice => ResolveAsync(choice, conflict),
_ui.CloseDialog, conflict.NewerFormat);
_ui.CloseDialog, conflict.NewerFormat, IsServerHome);
if (!background)
{
// Asked now: one still waiting from the background (or showing, which this one replaces) would only repeat an older list.
@@ -669,6 +754,34 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
else _ = CopyEndedAsync(job);
}
/// <summary>
/// The home told that this project changed there, or that changes may have been missed (any thread; phase 5b): where it
/// stands is read again on the menu's thread, so the chip says Server newer, or that the server no longer has it.
/// </summary>
private void OnHomeChanged(WorkspaceHomeChange change)
{
if (_disposed || (change.ProjectId is { } id ? id != ProjectId : !IsServerHome || !string.Equals(change.Server, Home.Server, StringComparison.OrdinalIgnoreCase)))
return;
if (_context is { } context) context.Post(_ => _ = HomeChangedAsync(change), null);
else _ = HomeChangedAsync(change);
}
private async Task HomeChangedAsync(WorkspaceHomeChange change)
{
if (_disposed || _isSyncing) return;
await RefreshAsync();
// An analysis's Auto values reached Main at the server: with Sync automatically they are taken, as after an analysis here.
if (_disposed || _analysisEnded is not { } ended || change.Change != ProjectChanges.Pushed) return;
if (DateTime.UtcNow - ended > AnalysisTake)
{
_analysisEnded = null;
return;
}
if (_status is not { State: WorkspaceState.Behind } || !_host.Settings.WorkspaceAutoSync) return;
_analysisEnded = null;
await SyncAsync(quiet: true);
}
/// <summary>The copy of Update media ended: the editor reads the new frames (its positions follow them), or the toast says why not.</summary>
private async Task CopyEndedAsync(Job job)
{
@@ -682,7 +795,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The new media of project {ProjectId} could not be read", ex);
_ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), WorkspaceText.Failure(ex), isError: true);
_ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
}
await RefreshAsync();
RaiseState();
@@ -718,6 +831,11 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
OnPropertyChanged(nameof(CanSaveVersion));
OnPropertyChanged(nameof(SaveVersionToolTip));
OnPropertyChanged(nameof(DeleteToolTip));
OnPropertyChanged(nameof(IsServerHome));
OnPropertyChanged(nameof(RenameToolTip));
OnPropertyChanged(nameof(RemoveCopyToolTip));
OnPropertyChanged(nameof(MediaChangedToolTip));
OnPropertyChanged(nameof(UpdateMediaToolTip));
_updateMedia.RaiseCanExecuteChanged();
CommandManager.InvalidateRequerySuggested();
}
+74 -28
View File
@@ -53,6 +53,7 @@ public static class ProjectNames
public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
{
private readonly TaskCompletionSource<OpenChoice?> _choice = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly bool _server;
private ProjectOption? _selected;
private bool _isNew;
@@ -61,10 +62,12 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
/// <param name="unreadable">
/// The projects whose copy here this Chronos cannot read (damaged, or a newer Chronos's), with why: listed, never chosen.
/// </param>
/// <param name="server">The sequence's home is a server (phase 5b): the texts name the server.</param>
public OpenInWorkspaceDialogViewModel(string sequenceTitle, IReadOnlyList<SequenceProject> projects, Action<ArchiveDialogViewModel> close,
IReadOnlyList<string>? taken = null, WorkspaceCopyFacts? copy = null, IReadOnlyDictionary<Guid, string>? unreadable = null)
IReadOnlyList<string>? taken = null, WorkspaceCopyFacts? copy = null, IReadOnlyDictionary<Guid, string>? unreadable = null, bool server = false)
: base(close)
{
_server = server;
SequenceTitle = sequenceTitle;
Copy = copy;
CopyFacts = copy is null ? []
@@ -138,6 +141,12 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
public EditableField NewName { get; }
public string ExistingToolTip => WorkspaceText.ForHome("Tooltips.Editor.OpenWorkspace.Existing", _server);
public string ProjectsToolTip => WorkspaceText.ForHome("Tooltips.Editor.OpenWorkspace.Projects", _server);
public string ProxiesToolTip => WorkspaceText.ForHome("Tooltips.Editor.OpenWorkspace.Proxies", _server);
/// <summary>The proxies, the only media this phase copies.</summary>
public bool IsProxies => true;
@@ -176,13 +185,17 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
public sealed class ProjectNameDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<string, Task> _save;
private readonly bool _server;
/// <param name="others">The names of the sequence's other projects (each name is used once).</param>
public ProjectNameDialogViewModel(bool rename, string name, IEnumerable<string> others, Func<string, Task> save, Action<ArchiveDialogViewModel> close)
/// <param name="server">The project's home is a server (phase 5b): the texts name the server.</param>
public ProjectNameDialogViewModel(bool rename, string name, IEnumerable<string> others, Func<string, Task> save, Action<ArchiveDialogViewModel> close,
bool server = false)
: base(close)
{
IsRename = rename;
_save = save;
_server = server;
var taken = others.ToList();
Name = new EditableField(name, n => ProjectNames.Validate(n, taken), _ => { }, () => Loc.L("Tooltips.Editor.ProjectName.Name"));
Name.PropertyChanged += (_, _) =>
@@ -203,7 +216,7 @@ public sealed class ProjectNameDialogViewModel : ArchiveDialogViewModel
public ICommand SaveCommand { get; }
public string SaveToolTip => Name.Error ?? Loc.L(IsRename ? "Tooltips.Editor.ProjectName.Apply" : "Tooltips.Editor.ProjectName.Create");
public string SaveToolTip => Name.Error ?? WorkspaceText.ForHome(IsRename ? "Tooltips.Editor.ProjectName.Apply" : "Tooltips.Editor.ProjectName.Create", _server);
private async Task SaveAsync()
{
@@ -217,7 +230,7 @@ public sealed class ProjectNameDialogViewModel : ArchiveDialogViewModel
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", "Naming a project failed", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
}
finally
{
@@ -233,13 +246,16 @@ public sealed class SaveVersionDialogViewModel : ArchiveDialogViewModel
public const int MaxNoteLength = 200;
private readonly Func<string?, Task> _save;
private readonly bool _server;
private string _note = string.Empty;
public SaveVersionDialogViewModel(string projectName, Func<string?, Task> save, Action<ArchiveDialogViewModel> close)
/// <param name="server">The project's home is a server (phase 5b): the texts name the server.</param>
public SaveVersionDialogViewModel(string projectName, Func<string?, Task> save, Action<ArchiveDialogViewModel> close, bool server = false)
: base(close)
{
ProjectName = projectName;
_save = save;
_server = server;
SaveCommand = new AsyncRelayCommand(SaveAsync, () => !IsBusy);
}
@@ -247,6 +263,8 @@ public sealed class SaveVersionDialogViewModel : ArchiveDialogViewModel
public string Heading => Loc.L("Editor.SaveVersion.Title", ProjectName);
public string SaveToolTip => WorkspaceText.ForHome("Tooltips.Editor.SaveVersion.Save", _server);
public string Note
{
get => _note;
@@ -267,7 +285,7 @@ public sealed class SaveVersionDialogViewModel : ArchiveDialogViewModel
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", "Saving a version failed", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
}
finally
{
@@ -277,10 +295,13 @@ public sealed class SaveVersionDialogViewModel : ArchiveDialogViewModel
}
/// <summary>A version in the History flyout: number, author, time, note, what made it, and Compare and Restore.</summary>
public sealed class HistoryRowViewModel(ProjectVersion version, bool unsent, bool isCurrent, ICommand compare, ICommand restore) : ObservableObject
public sealed class HistoryRowViewModel(ProjectVersion version, bool unsent, bool isCurrent, ICommand compare, ICommand restore, bool server = false) : ObservableObject
{
public ProjectVersion Version { get; } = version;
/// <summary>"Saved here, waiting to be sent to the library" (the server, for a server's project).</summary>
public string NotSentToolTip => WorkspaceText.ForHome("Tooltips.Editor.History.NotSent", server);
public string Number => Formatting.Count(Version.Number);
public string Author => WorkspaceText.Author(Version);
@@ -317,17 +338,20 @@ public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<ProjectVersion, Task<IReadOnlyList<string>>> _compare;
private readonly Func<ProjectVersion, Task> _restore;
private readonly bool _server;
private string? _comparedTitle;
private IReadOnlyList<string> _compared = [];
private bool _isLoaded;
/// <param name="server">The project's home is a server (phase 5b): the texts name the server.</param>
public HistoryDialogViewModel(string projectName, Func<ProjectVersion, Task<IReadOnlyList<string>>> compare, Func<ProjectVersion, Task> restore,
Action<ArchiveDialogViewModel> close)
Action<ArchiveDialogViewModel> close, bool server = false)
: base(close)
{
ProjectName = projectName;
_compare = compare;
_restore = restore;
_server = server;
}
public string ProjectName { get; }
@@ -339,6 +363,11 @@ public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
/// <summary>The home could not be asked: only this PC's versions are listed.</summary>
public bool IsOffline { get; private set; }
/// <summary>"Library offline", or "Server offline" for a server's project.</summary>
public string OfflineText => WorkspaceText.ForHome("Editor.History.Offline", _server);
public string OfflineToolTip => WorkspaceText.ForHome("Tooltips.Editor.History.Offline", _server);
public bool IsEmpty => _isLoaded && Rows.Count == 0;
/// <summary>"Version 3 → now" over the comparison; null before one.</summary>
@@ -355,7 +384,7 @@ public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
{
var current = currentHash is not null && string.Equals(version.ContentHash, currentHash, StringComparison.OrdinalIgnoreCase);
Rows.Add(new HistoryRowViewModel(version, history.Unsent.Contains(version.Id), current,
new AsyncRelayCommand(() => CompareAsync(version), () => !IsBusy), new AsyncRelayCommand(() => RestoreAsync(version), () => !IsBusy)));
new AsyncRelayCommand(() => CompareAsync(version), () => !IsBusy), new AsyncRelayCommand(() => RestoreAsync(version), () => !IsBusy), _server));
}
IsOffline = history.Offline;
_isLoaded = true;
@@ -369,7 +398,7 @@ public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
ArgumentNullException.ThrowIfNull(ex);
_isLoaded = true;
OnPropertyChanged(nameof(IsEmpty));
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
}
public async Task CompareAsync(ProjectVersion version)
@@ -385,7 +414,7 @@ public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Version {version.Number} could not be compared", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
}
}
@@ -403,7 +432,7 @@ public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Version {version.Number} could not be restored", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
IsBusy = false;
}
}
@@ -418,10 +447,12 @@ public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
public sealed class ConflictDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<ConflictChoice, Task> _resolve;
private readonly bool _server;
/// <param name="newerFormat">The library holds a newer Chronos's settings: nothing is merged, Save both is the only choice.</param>
/// <param name="server">The project's home is a server (phase 5b): "Take server's", and the texts name the server.</param>
public ConflictDialogViewModel(string projectName, string siblingName, IReadOnlyList<string> differences, Func<ConflictChoice, Task> resolve,
Action<ArchiveDialogViewModel> close, bool newerFormat = false)
Action<ArchiveDialogViewModel> close, bool newerFormat = false, bool server = false)
: base(close)
{
ProjectName = projectName;
@@ -430,6 +461,7 @@ public sealed class ConflictDialogViewModel : ArchiveDialogViewModel
// The format's number says nothing to the user: the line names the cause.
Differences = newerFormat ? [Loc.L("Editor.Workspace.Conflict.NewerFormat")] : differences;
_resolve = resolve;
_server = server;
KeepMineCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.KeepMine), () => !IsBusy && CanMerge);
TakeHomeCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.TakeServer), () => !IsBusy && CanMerge);
SaveBothCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.SaveBoth), () => !IsBusy);
@@ -446,13 +478,13 @@ public sealed class ConflictDialogViewModel : ArchiveDialogViewModel
/// <summary>The project Save both makes for this workspace's versions.</summary>
public string SiblingName { get; }
public string Heading => Loc.L("Editor.Workspace.Conflict.Title");
public string Heading => WorkspaceText.ForHome("Editor.Workspace.Conflict.Title", _server);
public string Message => Loc.L(IsNewerFormat ? "Editor.Workspace.Conflict.NewerMessage" : "Editor.Workspace.Conflict.Message", ProjectName);
public string Message => WorkspaceText.ForHome(IsNewerFormat ? "Editor.Workspace.Conflict.NewerMessage" : "Editor.Workspace.Conflict.Message", _server, ProjectName);
public IReadOnlyList<string> Differences { get; }
public string DifferencesToolTip => Loc.L(IsNewerFormat ? "Tooltips.Editor.Workspace.NewerFormat" : "Tooltips.Editor.Workspace.Differences");
public string DifferencesToolTip => WorkspaceText.ForHome(IsNewerFormat ? "Tooltips.Editor.Workspace.NewerFormat" : "Tooltips.Editor.Workspace.Differences", _server);
public ICommand KeepMineCommand { get; }
@@ -460,7 +492,14 @@ public sealed class ConflictDialogViewModel : ArchiveDialogViewModel
public ICommand SaveBothCommand { get; }
public string SaveBothToolTip => Loc.L(IsNewerFormat ? "Tooltips.Editor.Workspace.SaveBothNewer" : "Tooltips.Editor.Workspace.SaveBoth", SiblingName);
/// <summary>"Take library's", or "Take server's" for a server's project.</summary>
public string TakeHomeText => WorkspaceText.ForHome("Editor.Workspace.Conflict.TakeHome", _server);
public string TakeHomeToolTip => WorkspaceText.ForHome("Tooltips.Editor.Workspace.TakeHome", _server);
public string KeepMineToolTip => WorkspaceText.ForHome("Tooltips.Editor.Workspace.KeepMine", _server);
public string SaveBothToolTip => WorkspaceText.ForHome(IsNewerFormat ? "Tooltips.Editor.Workspace.SaveBothNewer" : "Tooltips.Editor.Workspace.SaveBoth", _server, SiblingName);
private async Task ResolveAsync(ConflictChoice choice)
{
@@ -475,7 +514,7 @@ public sealed class ConflictDialogViewModel : ArchiveDialogViewModel
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The conflict of '{ProjectName}' could not be settled ({choice})", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
IsBusy = false;
}
}
@@ -493,15 +532,19 @@ public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
private readonly Func<bool, Task> _remove;
private readonly Func<Task> _sendFirst;
private readonly Func<bool> _confirmDiscard;
private readonly bool _server;
/// <param name="confirmDiscard">The typed confirmation Discard changes asks first (<see cref="ConfirmDiscard"/>); true when the user confirmed.</param>
public RemoveCopyDialogViewModel(WorkspaceRemovalPlan plan, Func<bool, Task> remove, Func<Task> sendFirst, Func<bool> confirmDiscard, Action<ArchiveDialogViewModel> close)
/// <param name="server">The project's home is a server (phase 5b): the texts name the server.</param>
public RemoveCopyDialogViewModel(WorkspaceRemovalPlan plan, Func<bool, Task> remove, Func<Task> sendFirst, Func<bool> confirmDiscard, Action<ArchiveDialogViewModel> close,
bool server = false)
: base(close)
{
Plan = plan;
_remove = remove;
_sendFirst = sendFirst;
_confirmDiscard = confirmDiscard;
_server = server;
Facts =
[
new DialogFact(Loc.L("Editor.RemoveCopy.Files"), Formatting.Count(plan.Files)),
@@ -532,19 +575,22 @@ public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
public ICommand DiscardCommand { get; }
/// <summary>What happens to the copy and the project, worded for the project's home.</summary>
public string Message => WorkspaceText.ForHome("Editor.RemoveCopy.Message", _server);
public string RemoveToolTip => Plan.Damaged ? Loc.L("Errors.Workspace.Damaged")
: Plan.Gone ? Loc.L("Errors.Workspace.ProjectGone")
: !Plan.IsSafe ? Loc.L("Errors.Workspace.Unsent")
: Plan.Offline ? Loc.L("Errors.Workspace.Offline")
: Loc.L("Tooltips.Editor.RemoveCopy.Remove");
: Plan.Gone ? WorkspaceText.ForHome("Errors.Workspace.ProjectGone", _server)
: !Plan.IsSafe ? WorkspaceText.ForHome("Errors.Workspace.Unsent", _server)
: Plan.Offline ? WorkspaceText.ForHome("Errors.Workspace.Offline", _server)
: WorkspaceText.ForHome("Tooltips.Editor.RemoveCopy.Remove", _server);
public string SendFirstToolTip => Plan.Damaged ? Loc.L("Errors.Workspace.Damaged")
: Plan.Gone ? Loc.L("Errors.Workspace.ProjectGone")
: Plan.Gone ? WorkspaceText.ForHome("Errors.Workspace.ProjectGone", _server)
: Plan.Conflict ? Loc.L("Errors.Workspace.Conflict")
: Plan.Offline ? Loc.L("Errors.Workspace.Offline")
: Loc.L("Tooltips.Editor.RemoveCopy.SendFirst");
: Plan.Offline ? WorkspaceText.ForHome("Errors.Workspace.Offline", _server)
: WorkspaceText.ForHome("Tooltips.Editor.RemoveCopy.SendFirst", _server);
public string DiscardToolTip => Loc.L("Tooltips.Editor.RemoveCopy.Discard");
public string DiscardToolTip => WorkspaceText.ForHome("Tooltips.Editor.RemoveCopy.Discard", _server);
/// <summary>
/// The typed confirmation of Discard changes (the plan's cross-cutting rule for what Chronos cannot bring back): the
@@ -614,7 +660,7 @@ public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The local copy of project {Plan.ProjectId} was not removed", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
IsBusy = false;
}
}
+10 -10
View File
@@ -45,9 +45,9 @@
</Grid.RowDefinitions>
<TextBlock Text="{l:Loc Editor.OpenWorkspace.Project}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" />
<RadioButton Grid.Column="1" GroupName="Project" Content="{l:Loc Editor.OpenWorkspace.Existing}" IsChecked="{Binding IsExisting}" IsEnabled="{Binding HasProjects}"
ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.Existing}" VerticalAlignment="Center" Margin="0,0,12,0" />
ToolTip="{Binding ExistingToolTip}" VerticalAlignment="Center" Margin="0,0,12,0" />
<ComboBox Grid.Column="2" ItemsSource="{Binding Projects}" SelectedItem="{Binding SelectedProject}" DisplayMemberPath="Label" IsEnabled="{Binding HasProjects}"
ItemContainerStyle="{StaticResource ComboBoxItem.Project}" ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.Projects}" AutomationProperties.Name="{l:Loc Editor.OpenWorkspace.Project}" />
ItemContainerStyle="{StaticResource ComboBoxItem.Project}" ToolTip="{Binding ProjectsToolTip}" AutomationProperties.Name="{l:Loc Editor.OpenWorkspace.Project}" />
<RadioButton Grid.Row="1" Grid.Column="1" GroupName="Project" Content="{l:Loc Editor.OpenWorkspace.New}" IsChecked="{Binding IsNew}"
ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.New}" VerticalAlignment="Center" Margin="0,8,12,0" />
<TextBox Grid.Row="1" Grid.Column="2" Margin="0,8,0,0" Text="{Binding NewName.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
@@ -55,7 +55,7 @@
<TextBlock Grid.Row="2" Text="{l:Loc Editor.OpenWorkspace.Media}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" Margin="0,14,0,0" />
<StackPanel Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" Orientation="Horizontal" Margin="0,14,0,0">
<RadioButton GroupName="Media" Content="{l:Loc Editor.OpenWorkspace.Proxies}" IsChecked="{Binding IsProxies, Mode=OneWay}"
ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.Proxies}" Margin="0,0,16,0" />
ToolTip="{Binding ProxiesToolTip}" Margin="0,0,16,0" />
<RadioButton GroupName="Media" Content="{l:Loc Editor.OpenWorkspace.Originals}" IsEnabled="{Binding CanCopyOriginals}" IsChecked="False"
ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.Originals}" ToolTipService.ShowOnDisabled="True" />
</StackPanel>
@@ -127,7 +127,7 @@
</Grid>
<DockPanel Margin="0,18,0,0">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Editor.SaveVersion.Save}" Command="{Binding SaveCommand}"
ToolTip="{l:Loc Tooltips.Editor.SaveVersion.Save}" IsDefault="True" MinWidth="96" Margin="8,0,0,0" />
ToolTip="{Binding SaveToolTip}" IsDefault="True" MinWidth="96" Margin="8,0,0,0" />
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True" MinWidth="96" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" Margin="0,0,12,0" />
</DockPanel>
@@ -146,7 +146,7 @@
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<DockPanel>
<ui:StatusGlyph DockPanel.Dock="Right" Kind="Offline" Text="{l:Loc Editor.History.Offline}" ToolTip="{l:Loc Tooltips.Editor.History.Offline}" FontSize="12"
<ui:StatusGlyph DockPanel.Dock="Right" Kind="Offline" Text="{Binding OfflineText}" ToolTip="{Binding OfflineToolTip}" FontSize="12"
VerticalAlignment="Center" Visibility="{Binding IsOffline, Converter={StaticResource BoolToVisibility}}" />
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
</DockPanel>
@@ -171,7 +171,7 @@
<TextBlock Grid.Column="3" Style="{StaticResource Text.Cell}" Text="{Binding When}" Margin="12,0,0,0" Foreground="{DynamicResource Brush.TextMuted}"
Typography.NumeralAlignment="Tabular" />
<DockPanel Grid.Column="4" Margin="12,0,0,0">
<ui:StatusGlyph DockPanel.Dock="Right" Kind="Queued" Text="{l:Loc Editor.History.NotSent}" ToolTip="{l:Loc Tooltips.Editor.History.NotSent}" FontSize="12"
<ui:StatusGlyph DockPanel.Dock="Right" Kind="Queued" Text="{l:Loc Editor.History.NotSent}" ToolTip="{Binding NotSentToolTip}" FontSize="12"
VerticalAlignment="Center" Margin="8,0,0,0" Visibility="{Binding IsUnsent, Converter={StaticResource BoolToVisibility}}" />
<ui:StatusGlyph DockPanel.Dock="Right" Kind="Done" Text="{l:Loc Editor.History.Current}" ToolTip="{l:Loc Tooltips.Editor.History.Current}" FontSize="12"
VerticalAlignment="Center" Margin="8,0,0,0" Visibility="{Binding IsCurrent, Converter={StaticResource BoolToVisibility}}" />
@@ -214,7 +214,7 @@
</Border>
</DataTemplate>
<!-- A sync that met settings both sides changed: what differs, then Keep mine, Take the library's, Save both, or Later (only Save both and Later for a newer Chronos's project). -->
<!-- A sync that met settings both sides changed: what differs, then Keep mine, Take the library's (the server's), Save both, or Later (only Save both and Later for a newer Chronos's project). -->
<DataTemplate DataType="{x:Type ws:ConflictDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="560">
<StackPanel>
@@ -234,10 +234,10 @@
MinWidth="96" Margin="0,0,8,8" />
<Button Content="{l:Loc Server.Sync.Action.SaveBoth}" Command="{Binding SaveBothCommand}" ToolTip="{Binding SaveBothToolTip}" MinWidth="96" Margin="0,0,8,8"
Visibility="{Binding CanMerge, Converter={StaticResource BoolToVisibility}}" />
<Button Content="{l:Loc Editor.Workspace.Conflict.TakeHome}" Command="{Binding TakeHomeCommand}" ToolTip="{l:Loc Tooltips.Editor.Workspace.TakeHome}"
<Button Content="{Binding TakeHomeText}" Command="{Binding TakeHomeCommand}" ToolTip="{Binding TakeHomeToolTip}"
MinWidth="96" Margin="0,0,8,8" Visibility="{Binding CanMerge, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Server.Sync.Action.KeepMine}" Command="{Binding KeepMineCommand}"
ToolTip="{l:Loc Tooltips.Editor.Workspace.KeepMine}" IsDefault="{Binding CanMerge, Mode=OneWay}" MinWidth="96" Margin="0,0,0,8"
ToolTip="{Binding KeepMineToolTip}" IsDefault="{Binding CanMerge, Mode=OneWay}" MinWidth="96" Margin="0,0,0,8"
Visibility="{Binding CanMerge, Converter={StaticResource BoolToVisibility}}" />
<!-- A conflict of format: Save both is the only choice that settles it. -->
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Server.Sync.Action.SaveBoth}" Command="{Binding SaveBothCommand}" ToolTip="{Binding SaveBothToolTip}"
@@ -254,7 +254,7 @@
<Border Style="{StaticResource Border.Dialog}" Width="520">
<StackPanel>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
<TextBlock Text="{l:Loc Editor.RemoveCopy.Message}" Margin="0,8,0,0" Foreground="{DynamicResource Brush.TextMuted}" TextWrapping="Wrap" LineHeight="18" />
<TextBlock Text="{Binding Message}" Margin="0,8,0,0" Foreground="{DynamicResource Brush.TextMuted}" TextWrapping="Wrap" LineHeight="18" />
<ItemsControl ItemsSource="{Binding Facts}" Focusable="False" Margin="0,14,0,0" Grid.IsSharedSizeScope="True">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type ar:DialogFact}">
+185 -45
View File
@@ -9,9 +9,11 @@ using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
using Chronos.Protocol;
namespace Chronos.App.Workspace;
@@ -51,6 +53,9 @@ public sealed record WorkspaceEntry(Guid ProjectId, Guid SequenceId, string Name
/// <summary>This Chronos reads its working state: it can open.</summary>
public bool IsReadable => !Damaged && !Newer;
/// <summary>The project's home is a server (phase 5b), not this PC's archive.</summary>
public bool IsServerHome => !Home.IsArchive;
}
/// <summary>What changing the workspace folder to <see cref="Folder"/> does: Edit lists its projects from then on; nothing is moved.</summary>
@@ -71,6 +76,13 @@ public sealed record WorkspaceCopyFacts(long Bytes, long? Free)
public bool TooLittleSpace => Free is { } free && free < Bytes + WorkspaceJobs.CopySpaceReserve;
}
/// <summary>
/// A workspace project's home told that the project changed there (owner review 2, R8, phase 5b: a server's
/// <c>projectChanged</c>): <see cref="Change"/> is one of <c>Protocol.ProjectChanges</c>; null for every project of
/// <see cref="Server"/> when changes may have been missed (its events were lost for a while).
/// </summary>
public sealed record WorkspaceHomeChange(string Server, Guid? ProjectId, string? Change);
/// <summary>A project brought into the workspace and the copy of its media that was queued.</summary>
public sealed record WorkspaceCheckout(SequenceProject Project, Job Copy);
@@ -108,12 +120,14 @@ public sealed record WorkspaceRemovalPlan(Guid ProjectId, string Name, int Files
/// <summary>
/// The workspace of this PC (owner review 2, R8), composed for the desktop: its folder (Settings › Workspace, else
/// <c>workspace</c> under the data folder: <c>%LOCALAPPDATA%\Chronos\workspace</c>, <c>.\data\workspace</c> for a portable
/// copy), the <see cref="WorkspaceStore"/> and <see cref="WorkspaceSync"/> over it, and this PC's archive as the home of
/// its projects (<see cref="ArchiveProjectHome"/>; a server home comes in phase 5b). Every operation runs off the UI thread
/// and returns where the project stands. Nothing a workspace holds is lost: a version is sent before its copy goes, a copy
/// is removed only once the home verifiably holds its head, the work a user chose to discard is kept in
/// <c>&lt;workspace&gt;/.trash</c>, and versions the home holds are pruned past Settings › Workspace › Kept versions only
/// after the home was asked for each. A capture (sample data, no engine) has no workspace: Edit opens the library there.
/// copy), the <see cref="WorkspaceStore"/> and <see cref="WorkspaceSync"/> over it, and the homes of its projects: this PC's
/// archive (<see cref="ArchiveProjectHome"/>) or, from phase 5b, the signed-in server (<see cref="ServerHomes"/>, a
/// <see cref="ServerProjectHome"/>; a project of a server this PC is not signed in to reads as offline, its work waiting
/// here). Every operation runs off the UI thread and returns where the project stands. Nothing a workspace holds is lost: a
/// version is sent before its copy goes, a copy is removed only once the home verifiably holds its head, the work a user
/// chose to discard is kept in <c>&lt;workspace&gt;/.trash</c>, and versions the home holds are pruned past Settings ›
/// Workspace › Kept versions only after the home returned each, a page of its history at a time. A capture (sample data, no
/// engine) has no workspace: Edit opens the library there.
/// </summary>
public sealed class WorkspaceHost
{
@@ -190,17 +204,85 @@ public sealed class WorkspaceHost
public WorkspaceStore Store => Sync.Store;
/// <summary>The home of a workspace project; null for a home this PC cannot reach in this phase (a server, phase 5b).</summary>
/// <summary>
/// The project home of a server home (phase 5b; the desktop's <c>SyncHost.ProjectHome</c>): null while this PC is not
/// signed in to that server, or it keeps no projects. Without it every server home reads as out of reach.
/// </summary>
public Func<BundleHome, IProjectHome?>? ServerHomes { get; set; }
/// <summary>A workspace project's home told that it changed there (any thread): its state is read again.</summary>
public event Action<WorkspaceHomeChange>? HomeChanged;
/// <summary>The home of a workspace project; null for a home this PC cannot reach now (the index not open, a server it is not signed in to).</summary>
public IProjectHome? HomeOf(BundleHome home)
{
ArgumentNullException.ThrowIfNull(home);
return home.IsArchive && _db() is { } db && _archives() is { } archives ? new ArchiveProjectHome(db, archives.Projects, home.SequenceId) : null;
if (!home.IsArchive) return ServerHomes?.Invoke(home);
return _db() is { } db && _archives() is { } archives ? new ArchiveProjectHome(db, archives.Projects, home.SequenceId) : null;
}
/// <summary>The home of a sequence of this PC's archive (<paramref name="sequenceId"/> is in its index).</summary>
public static BundleHome ArchiveHome(Guid sequenceId) => new(BundleHome.ArchiveKind, sequenceId);
/// <summary>The home of a sequence of this PC's archive.</summary>
/// <exception cref="WorkspaceException">The index or the archive engine is not open.</exception>
public IProjectHome HomeOfSequence(Guid sequenceId) =>
HomeOf(new BundleHome(BundleHome.ArchiveKind, sequenceId)) ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
public IProjectHome HomeOfSequence(Guid sequenceId) => Reachable(ArchiveHome(sequenceId));
/// <summary>The home <paramref name="home"/> names, which must be reachable now.</summary>
/// <exception cref="WorkspaceException">The index or the archive engine is not open (this PC's archive).</exception>
/// <exception cref="HomeUnavailableException">This PC is not signed in to the server, or it keeps no projects.</exception>
public IProjectHome Reachable(BundleHome home) =>
HomeOf(home) ?? (home.IsArchive
? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"))
: throw new HomeUnavailableException("This PC is not signed in to the server of the project, or it keeps no projects."));
/// <summary>
/// The signed-in server told that a project changed there (phase 5b), or (<paramref name="change"/> null) that changes
/// may have been missed: projects of this workspace whose home it is are told (<see cref="HomeChanged"/>).
/// </summary>
public void OnServerProjectChanged(string server, ProjectChangedEvent? change)
{
ArgumentNullException.ThrowIfNull(server);
if (change is null)
{
HomeChanged?.Invoke(new WorkspaceHomeChange(server, null, null));
return;
}
// The folder is named by the project's id: only a project this workspace holds, of that server and sequence, is told.
BundleHome home;
try
{
if (!IsAvailable || Store.Find(change.ProjectId)?.ReadBundle().Workspace?.Home is not { IsArchive: false } held || held.SequenceId != change.SequenceId
|| !string.Equals(held.Server, server, StringComparison.OrdinalIgnoreCase))
return;
home = held;
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Info("workspace", $"A change of project {change.ProjectId} on {server} could not be matched: {ex.Message}");
return;
}
if (change.Change != ProjectChanges.Renamed)
{
HomeChanged?.Invoke(new WorkspaceHomeChange(server, change.ProjectId, change.Change));
return;
}
// A rename at the server is written to the copy here before it is told, so the state read again shows the new name.
_ = FollowNameThenTellAsync(server, home, change);
}
private async Task FollowNameThenTellAsync(string server, BundleHome home, ProjectChangedEvent change)
{
try
{
if (HomeOf(home) is { } reached) await Sync.FollowNameAsync(change.ProjectId, reached).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Info("workspace", $"The new name of project {change.ProjectId} on {server} could not be followed: {ex.Message}");
}
HomeChanged?.Invoke(new WorkspaceHomeChange(server, change.ProjectId, change.Change));
}
/// <summary>
/// The projects of the workspace; one whose working state cannot be read is listed as damaged (<see cref="WorkspaceEntry.Damaged"/>),
@@ -307,10 +389,15 @@ public sealed class WorkspaceHost
}
/// <summary>The home's live projects of a sequence, Main first (made from the sequence's settings when it has none yet).</summary>
public Task<IReadOnlyList<SequenceProject>> HomeProjectsAsync(Guid sequenceId, CancellationToken cancellationToken = default)
public Task<IReadOnlyList<SequenceProject>> HomeProjectsAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
HomeProjectsAsync(ArchiveHome(sequenceId), cancellationToken);
/// <summary>The live projects of <paramref name="home"/>'s sequence, Main first (made from the sequence's settings when it has none yet).</summary>
/// <exception cref="HomeUnavailableException">A server home this PC cannot reach now.</exception>
public Task<IReadOnlyList<SequenceProject>> HomeProjectsAsync(BundleHome home, CancellationToken cancellationToken = default)
{
var home = HomeOfSequence(sequenceId);
return Task.Run(() => home.ListAsync(cancellationToken), cancellationToken);
var reached = Reachable(home);
return Task.Run(() => reached.ListAsync(cancellationToken), cancellationToken);
}
/// <summary>
@@ -321,10 +408,22 @@ public sealed class WorkspaceHost
/// <exception cref="ProjectException">The home has no such project, or the name is invalid or taken.</exception>
/// <exception cref="HomeUnavailableException">The archive is offline or busy.</exception>
/// <exception cref="WorkspaceException">The workspace folder lies inside a library: nothing was written, here or at the home.</exception>
public async Task<WorkspaceCheckout> CheckoutAsync(Guid sequenceId, Guid? projectId, string? newName, string media = BundleMedia.Proxies,
public Task<WorkspaceCheckout> CheckoutAsync(Guid sequenceId, Guid? projectId, string? newName, string media = BundleMedia.Proxies,
CancellationToken cancellationToken = default) =>
CheckoutAsync(ArchiveHome(sequenceId), projectId, newName, media, cancellationToken);
/// <summary>
/// Brings a project of <paramref name="home"/>'s sequence (this PC's archive, or the signed-in server) into the workspace
/// and queues the copy of its media, as <see cref="CheckoutAsync(Guid, Guid?, string?, string, CancellationToken)"/>.
/// </summary>
/// <exception cref="ProjectException">The home has no such project, or the name is invalid or taken.</exception>
/// <exception cref="HomeUnavailableException">The home cannot be reached now.</exception>
/// <exception cref="WorkspaceException">The workspace folder lies inside a library: nothing was written, here or at the home.</exception>
public async Task<WorkspaceCheckout> CheckoutAsync(BundleHome home, Guid? projectId, string? newName, string media = BundleMedia.Proxies,
CancellationToken cancellationToken = default)
{
var home = HomeOfSequence(sequenceId);
var reached = Reachable(home);
var sequenceId = home.SequenceId;
var checkout = await Task.Run(async () =>
{
// Refused before anything is written: the copy job would refuse such a folder after the checkout filled it.
@@ -333,21 +432,23 @@ public sealed class WorkspaceHost
SequenceProject project;
if (newName is not null)
{
project = await home.CreateAsync(newName, null, null, cancellationToken).ConfigureAwait(false);
project = await reached.CreateAsync(newName, null, null, cancellationToken).ConfigureAwait(false);
}
else
{
var listed = await home.ListAsync(cancellationToken).ConfigureAwait(false);
var listed = await reached.ListAsync(cancellationToken).ConfigureAwait(false);
project = projectId is { } id
? listed.FirstOrDefault(p => p.Id == id) ?? throw new ProjectException(ProjectError.NotFound, $"The home has no project {id}.")
: listed.First(p => p.IsMain);
// A server's sequence with no photo yet has no projects at all.
: listed.FirstOrDefault(p => p.IsMain) ?? throw new ProjectException(ProjectError.SequenceEmpty, $"Sequence {sequenceId} has no projects yet.");
}
// A copy here this Chronos cannot read (damaged, or a newer Chronos's): nothing is checked out or copied over it.
if (Store.Find(project.Id) is { } here && await EntryOrUnreadableAsync(here, cancellationToken).ConfigureAwait(false) is { IsReadable: false } unreadable)
throw Unreadable(unreadable);
await Sync.CheckoutAsync(home, project.Id, media, cancellationToken).ConfigureAwait(false);
var folder = await Sync.CheckoutAsync(reached, project.Id, media, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project {project.Id} ('{project.Name}') of sequence {sequenceId} checked out into {Store.Root}");
return new WorkspaceCheckout(project, await QueueCopyCoreAsync(sequenceId, project.Id, media, cancellationToken).ConfigureAwait(false));
var title = folder.ReadBundle().Sequence.Title ?? string.Empty;
return new WorkspaceCheckout(project, await QueueCopyCoreAsync(home, project.Id, media, title, cancellationToken).ConfigureAwait(false));
}, cancellationToken);
// Back on the caller's thread (the UI's): the settings are written there.
Remember(sequenceId, checkout.Project.Id);
@@ -361,20 +462,24 @@ public sealed class WorkspaceHost
public Task<Job> QueueCopyAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var bundle = Existing(projectId).ReadBundle();
return await QueueCopyCoreAsync(bundle.Workspace!.Home.SequenceId, projectId, bundle.Workspace.Media.Kind, cancellationToken).ConfigureAwait(false);
return await QueueCopyCoreAsync(bundle.Workspace!.Home, projectId, bundle.Workspace.Media.Kind, bundle.Sequence.Title ?? string.Empty, cancellationToken)
.ConfigureAwait(false);
}, cancellationToken);
/// <summary>
/// Where a project stands. With <paramref name="askHome"/>, against its home's head too: a home that cannot be reached
/// reads as offline; one that answers it no longer has the project or its sequence (the sequence left the index) reads
/// as <see cref="WorkspaceState.Gone"/>, whose local copy can then only be removed (nothing is removed by itself).
/// (a server this PC is not signed in to among them) reads as offline; one that answers it no longer has the project or
/// its sequence (the sequence left the index, the project was deleted there) reads as <see cref="WorkspaceState.Gone"/>,
/// whose local copy can then only be removed (nothing is removed by itself).
/// </summary>
public Task<WorkspaceStatus> StatusAsync(Guid projectId, bool askHome = true, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var project = Existing(projectId);
var home = askHome ? HomeOf(project.ReadBundle().Workspace!.Home) : null;
var named = project.ReadBundle().Workspace!.Home;
var home = askHome ? HomeOf(named) : null;
try
{
if (askHome && home is null && !named.IsArchive) return Offline(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
return await Sync.StatusAsync(projectId, home, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (home is not null && ex is ProjectException or DatabaseException or IOException)
@@ -392,6 +497,13 @@ public sealed class WorkspaceHost
Conflict = gone ? null : local.Conflict,
};
}
static WorkspaceStatus Offline(WorkspaceStatus local) =>
local with
{
Offline = true,
State = local.State is WorkspaceState.MediaRemoved or WorkspaceState.Damaged or WorkspaceState.Conflict ? local.State : WorkspaceState.Offline,
};
}, cancellationToken);
/// <summary>
@@ -542,23 +654,30 @@ public sealed class WorkspaceHost
/// <summary>A new project of the sequence named <paramref name="name"/> from <paramref name="fromVersionId"/> (a version the home holds), else from Main's head.</summary>
/// <exception cref="ProjectException">The name is invalid or taken.</exception>
public Task<SequenceProject> CreateProjectAsync(Guid sequenceId, string name, Guid? fromVersionId, CancellationToken cancellationToken = default)
public Task<SequenceProject> CreateProjectAsync(Guid sequenceId, string name, Guid? fromVersionId, CancellationToken cancellationToken = default) =>
CreateProjectAsync(ArchiveHome(sequenceId), name, fromVersionId, cancellationToken);
/// <summary>A new project of <paramref name="home"/>'s sequence named <paramref name="name"/> from <paramref name="fromVersionId"/>, else from Main's head.</summary>
/// <exception cref="ProjectException">The name is invalid or taken.</exception>
/// <exception cref="HomeUnavailableException">The home cannot be reached now.</exception>
public Task<SequenceProject> CreateProjectAsync(BundleHome home, string name, Guid? fromVersionId, CancellationToken cancellationToken = default)
{
var home = HomeOfSequence(sequenceId);
var reached = Reachable(home);
return Task.Run(async () =>
{
var created = await home.CreateAsync(name, fromVersionId, null, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project '{created.Name}' ({created.Id}) made for sequence {sequenceId}");
var created = await reached.CreateAsync(name, fromVersionId, null, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project '{created.Name}' ({created.Id}) made for sequence {home.SequenceId}");
return created;
}, cancellationToken);
}
/// <summary>Renames a project at its home, then its working state here.</summary>
/// <exception cref="ProjectException">The name is invalid or taken, or the project is gone.</exception>
/// <exception cref="HomeUnavailableException">The home cannot be reached now: the name stays.</exception>
public Task<string> RenameAsync(Guid projectId, string name, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var project = Existing(projectId);
var renamed = await ArchiveProjects(project).RenameAsync(projectId, name, cancellationToken).ConfigureAwait(false);
var renamed = await HomeOfProject(projectId).RenameAsync(projectId, name, cancellationToken).ConfigureAwait(false);
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
var bundle = project.ReadBundle();
@@ -592,8 +711,8 @@ public sealed class WorkspaceHost
var status = (await SendAsync(projectId, home, cancellationToken).ConfigureAwait(false)).Status;
if (status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"));
if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly)) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
await ArchiveProjects(project).DeleteAsync(projectId, cancellationToken).ConfigureAwait(false);
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly)) throw new WorkspaceException(Unsent(workspace.Home));
await home.DeleteAsync(projectId, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project {projectId} ('{workspace.Name}') deleted at its home");
try
{
@@ -624,7 +743,7 @@ public sealed class WorkspaceHost
var status = (await SyncAsync(projectId, cancellationToken).ConfigureAwait(false)).Status;
if (status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"));
if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly)) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly)) throw new WorkspaceException(Unsent(Existing(projectId).ReadBundle().Workspace!.Home));
}
/// <summary>The plan of "Remove local copy": the folder's files and size, and what would not be at the home after it.</summary>
@@ -682,7 +801,7 @@ public sealed class WorkspaceHost
var status = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
// A version saved here that cannot be read may be one the home never had: only discarding keeps it aside.
if (status.Ahead > 0 || status.Damaged > 0 || (status.Modified && !status.ReadOnly) || status.Conflict is not null)
throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
throw new WorkspaceException(Unsent(workspace.Home));
await VerifyHomeAsync(projectId, workspace, cancellationToken).ConfigureAwait(false);
}
await RemoveFolderAsync(project, cancellationToken).ConfigureAwait(false);
@@ -742,7 +861,8 @@ public sealed class WorkspaceHost
/// <summary>The home holds this copy's work: its head and the base this copy was last in step with read back, each matching its hash.</summary>
private async Task VerifyHomeAsync(Guid projectId, BundleWorkspace workspace, CancellationToken cancellationToken)
{
var home = HomeOf(workspace.Home) ?? throw new WorkspaceException(Loc.L("Errors.Workspace.Offline"));
var server = !workspace.Home.IsArchive;
var home = HomeOf(workspace.Home) ?? throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.Offline", server));
ProjectVersion head;
ProjectVersion? basis;
bool held;
@@ -761,13 +881,16 @@ public sealed class WorkspaceHost
}
catch (Exception ex) when (ex is HomeUnavailableException or ProjectException or DatabaseException)
{
throw new WorkspaceException(Loc.L("Errors.Workspace.Offline"), ex);
throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.Offline", server), ex);
}
if (!held || !ProjectContent.Verifies(head.SettingsJson, head.ContentHash) || basis is null || !ProjectContent.Verifies(basis.SettingsJson, basis.ContentHash)
|| (workspace.Base is { } known && !string.Equals(known.ContentHash, basis.ContentHash, StringComparison.OrdinalIgnoreCase)))
throw new WorkspaceException(Loc.L("Errors.Workspace.HomeCheck"));
throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.HomeCheck", server));
}
/// <summary>"Some work is not in the library (on the server) yet": worded for the project's home.</summary>
private static string Unsent(BundleHome home) => WorkspaceText.ForHome("Errors.Workspace.Unsent", !home.IsArchive);
/// <summary>
/// The project's folder taken out of the workspace under its lease: every file and folder in it but the media and the
/// lease (the working state, the versions, the sync state, the exports, and whatever else a Chronos keeps there) moved
@@ -889,25 +1012,42 @@ public sealed class WorkspaceHost
_savePreferences();
}
private async Task<Job> QueueCopyCoreAsync(Guid sequenceId, Guid projectId, string media, CancellationToken cancellationToken)
/// <summary>
/// The copy of a project's media from its home, unless one is waiting or running: a sequence of this PC's archive copied
/// from there, a server's downloaded from it (<paramref name="title"/> labels that job: the index has no row for it).
/// </summary>
private async Task<Job> QueueCopyCoreAsync(BundleHome home, Guid projectId, string media, string title, CancellationToken cancellationToken)
{
var engine = _engine() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
var db = _db() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
Guid known;
lock (_gate) _copies.TryGetValue(projectId, out known);
if (known != Guid.Empty && await db.Jobs.GetAsync(known, cancellationToken).ConfigureAwait(false) is { State: JobState.Queued or JobState.Running } running) return running;
var sequence = await db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false)
?? throw new ProjectException(ProjectError.SequenceNotFound, $"Sequence {sequenceId} is not in the index.");
var job = await engine.EnqueueAsync(WorkspaceJobs.Copy(sequence, Store.Root, projectId, media), cancellationToken: cancellationToken).ConfigureAwait(false);
ArchiveJobRequest request;
if (home.IsArchive)
{
var sequence = await db.Sequences.GetAsync(home.SequenceId, cancellationToken).ConfigureAwait(false)
?? throw new ProjectException(ProjectError.SequenceNotFound, $"Sequence {home.SequenceId} is not in the index.");
request = WorkspaceJobs.Copy(sequence, Store.Root, projectId, media);
}
else
{
request = WorkspaceJobs.CopyFromServer(home.SequenceId, title, home.Server ?? throw new InvalidDataException("A server home names no server."), Store.Root,
projectId, media);
}
var job = await engine.EnqueueAsync(request, cancellationToken: cancellationToken).ConfigureAwait(false);
lock (_gate) _copies[projectId] = job.Id;
return job;
}
private IProjectHome HomeOfProject(Guid projectId) =>
HomeOf(Existing(projectId).ReadBundle().Workspace!.Home) ?? throw new HomeUnavailableException("The project's home cannot be reached from this PC.");
private ProjectService ArchiveProjects(WorkspaceProject project) =>
project.ReadBundle().Workspace!.Home.IsArchive && _archives() is { } archives ? archives.Projects : throw new WorkspaceException(Loc.L("Errors.Workspace.Offline"));
/// <exception cref="HomeUnavailableException">The project's home cannot be reached now.</exception>
private IProjectHome HomeOfProject(Guid projectId)
{
var home = Existing(projectId).ReadBundle().Workspace!.Home;
return HomeOf(home) ?? throw new HomeUnavailableException(home.IsArchive
? "The project's home cannot be reached from this PC."
: "This PC is not signed in to the server of the project, or it keeps no projects.");
}
private WorkspaceProject Existing(Guid projectId) => Store.Find(projectId) ?? throw new WorkspaceException(Loc.L("Errors.Workspace.NotCheckedOut"));
@@ -7,9 +7,10 @@ using Chronos.Ui.Mvvm;
namespace Chronos.App.Workspace;
/// <summary>
/// A project of the workspace in Edit's picker (owner review 2, R8): its name, its sequence (title and thumbnail) and
/// where it stands, a chip read from its home after the list shows. A copy whose working state cannot be read is listed
/// as damaged, one a newer Chronos wrote as such, by the name each is still known by.
/// A project of the workspace in Edit's picker (owner review 2, R8): its name, its sequence (title and thumbnail; a server's
/// as the Library lists it, phase 5b) and where it stands, a chip read from its home after the list shows and again when
/// the home tells it changed. A copy whose working state cannot be read is listed as damaged, one a newer Chronos wrote
/// as such, by the name each is still known by.
/// </summary>
public sealed class WorkspaceProjectItem(WorkspaceEntry entry, SequenceItem? sequence) : ObservableObject
{
@@ -53,7 +54,7 @@ public sealed class WorkspaceProjectItem(WorkspaceEntry entry, SequenceItem? seq
public string StateText => Entry.Newer ? Loc.L("Editor.Workspace.State.NewerCopy")
: Entry.Damaged ? Loc.L("Editor.Workspace.State.Damaged")
: Entry.HasMedia || _status is not null ? WorkspaceText.State(_status) : Loc.L("Editor.Workspace.State.MediaRemoved");
: Entry.HasMedia || _status is not null ? WorkspaceText.State(_status, server: Entry.IsServerHome) : Loc.L("Editor.Workspace.State.MediaRemoved");
public StatusKind StateKind => Entry.Newer ? StatusKind.Warning
: Entry.Damaged ? StatusKind.Error
@@ -61,7 +62,7 @@ public sealed class WorkspaceProjectItem(WorkspaceEntry entry, SequenceItem? seq
public string StateToolTip => Entry.Newer ? Loc.L("Tooltips.Editor.Workspace.State.NewerCopy")
: Entry.Damaged ? Loc.L("Tooltips.Editor.Workspace.State.DamagedCopy")
: Entry.HasMedia || _status is not null ? WorkspaceText.StateToolTip(_status) : Loc.L("Tooltips.Editor.Workspace.State.MediaRemoved");
: Entry.HasMedia || _status is not null ? WorkspaceText.StateToolTip(_status, server: Entry.IsServerHome) : Loc.L("Tooltips.Editor.Workspace.State.MediaRemoved");
/// <summary>"Vertical social · Harbour sunset · In sync": what screen readers hear for the row.</summary>
public string Description => string.Join(Loc.Separator, Name, SequenceTitle, StateText);
+52 -19
View File
@@ -1,27 +1,53 @@
using System.IO;
using System.Net;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.App.Server;
using Chronos.App.Shell;
using Chronos.Core.Archiving;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Data.Workspaces;
using Chronos.Protocol.Client;
using Chronos.Ui.Controls;
namespace Chronos.App.Workspace;
/// <summary>How the workspace's states, projects, versions and failures read in the UI (owner review 2, R8). WPF-free.</summary>
/// <summary>
/// How the workspace's states, projects, versions and failures read in the UI (owner review 2, R8). WPF-free. A text that
/// names the project's home has a form for each: "the library" (this PC's archive) and, with <c>server</c>, "the server"
/// (phase 5b: its key with <see cref="ServerSuffix"/>).
/// </summary>
public static class WorkspaceText
{
/// <summary>The suffix of a text's key in its form for a project whose home is a server.</summary>
public const string ServerSuffix = ".Server";
/// <summary>The project's name; the Main project in the UI language.</summary>
public static string ProjectName(string name, bool isMain) =>
isMain && string.Equals(name, ProjectService.MainName, StringComparison.Ordinal) ? Loc.L("Editor.Project.Main") : name;
/// <summary>The state chip: "In sync", "Not sent", "Conflict"…; "Syncing" while a sync runs.</summary>
public static string State(WorkspaceStatus? status, bool syncing = false) =>
syncing ? Loc.L("Editor.Workspace.State.Syncing") : status is null ? Loc.L("Editor.Workspace.State.Reading") : Loc.L("Editor.Workspace.State." + status.State);
/// <summary>
/// The text of <paramref name="key"/> worded for the project's home: its server form (<see cref="ServerSuffix"/>) when
/// <paramref name="server"/>, the key itself for a text that names no home.
/// </summary>
public static string ForHome(string key, bool server, params object?[] args)
{
ArgumentNullException.ThrowIfNull(key);
var worded = server && Loc.Get(key + ServerSuffix, Loc.Culture) is not null ? key + ServerSuffix : key;
return args.Length == 0 ? Loc.L(worded) : Loc.L(worded, args);
}
/// <summary>
/// The state chip: "In sync", "Not sent", "Conflict"…; "Syncing" while a sync runs; worded for a server's project where
/// the state names the home ("Server newer", "Not on server").
/// </summary>
public static string State(WorkspaceStatus? status, bool syncing = false, bool server = false) =>
syncing ? Loc.L("Editor.Workspace.State.Syncing")
: status is null ? Loc.L("Editor.Workspace.State.Reading")
: ForHome("Editor.Workspace.State." + status.State, server);
public static StatusKind Kind(WorkspaceStatus? status, bool syncing = false) => syncing ? StatusKind.Running : status?.State switch
{
@@ -36,15 +62,16 @@ public static class WorkspaceText
_ => StatusKind.Queued,
};
/// <summary>What the state means and what to do, with the counts behind it.</summary>
public static string StateToolTip(WorkspaceStatus? status, bool syncing = false) => syncing ? Loc.L("Tooltips.Editor.Workspace.State.Syncing")
: status is null ? Loc.L("Tooltips.Editor.Workspace.State.Reading")
/// <summary>What the state means and what to do, with the counts behind it, worded for the project's home.</summary>
public static string StateToolTip(WorkspaceStatus? status, bool syncing = false, bool server = false) =>
syncing ? ForHome("Tooltips.Editor.Workspace.State.Syncing", server)
: status is null ? ForHome("Tooltips.Editor.Workspace.State.Reading", server)
: status.State switch
{
WorkspaceState.Ahead => Loc.L("Tooltips.Editor.Workspace.State.Ahead", Formatting.Count(status.Ahead)),
WorkspaceState.Behind => Loc.L("Tooltips.Editor.Workspace.State.Behind", Formatting.Count(status.Behind)),
WorkspaceState.Offline when status.Ahead > 0 => Loc.L("Tooltips.Editor.Workspace.State.OfflineAhead", Formatting.Count(status.Ahead)),
var state => Loc.L("Tooltips.Editor.Workspace.State." + state),
WorkspaceState.Ahead => ForHome("Tooltips.Editor.Workspace.State.Ahead", server, Formatting.Count(status.Ahead)),
WorkspaceState.Behind => ForHome("Tooltips.Editor.Workspace.State.Behind", server, Formatting.Count(status.Behind)),
WorkspaceState.Offline when status.Ahead > 0 => ForHome("Tooltips.Editor.Workspace.State.OfflineAhead", server, Formatting.Count(status.Ahead)),
var state => ForHome("Tooltips.Editor.Workspace.State." + state, server),
};
/// <summary>"Saved", "Merged", "Restored", "Imported", "Outside change".</summary>
@@ -76,34 +103,40 @@ public static class WorkspaceText
/// One line per setting both sides changed ("Deflicker window 41 here, 33 in the library"), at most <paramref name="max"/>.
/// A conflict of format (<see cref="ProjectMerge.FormatPath"/>) reads as its cause, never as the format's numbers.
/// </summary>
public static IReadOnlyList<string> ConflictLines(IEnumerable<SettingsDifference> differences, int max)
public static IReadOnlyList<string> ConflictLines(IEnumerable<SettingsDifference> differences, int max, bool server = false)
{
ArgumentNullException.ThrowIfNull(differences);
var list = differences.ToList();
if (list.Any(d => d.Path == ProjectMerge.FormatPath)) return [Loc.L("Editor.Workspace.Conflict.NewerFormat")];
return SyncText.Differences(list, max, (label, mine, theirs) => Loc.L("Editor.Workspace.Difference", label, mine, theirs));
return SyncText.Differences(list, max, (label, mine, theirs) => ForHome("Editor.Workspace.Difference", server, label, mine, theirs));
}
/// <summary>One line per setting that differs between now and a version ("Deflicker window 41 now, 33 in that version").</summary>
public static IReadOnlyList<string> CompareLines(IEnumerable<SettingsDifference> differences, int max) =>
SyncText.Differences(differences, max, (label, now, then) => Loc.L("Editor.History.Difference", label, now, then));
/// <summary>Why a workspace operation stopped, as one localized sentence chosen by cause; the exception's own text goes to the log.</summary>
public static string Failure(Exception ex) => ex switch
/// <summary>
/// Why a workspace operation stopped, as one localized sentence chosen by cause and worded for the project's home; the
/// exception's own text goes to the log.
/// </summary>
public static string Failure(Exception ex, bool server = false) => ex switch
{
WorkspaceException or LeaseUnavailableException => ex.Message,
// A library that can be read but not written (a read-only share, a write-protected disk): the work waits here as offline.
HomeUnavailableException { InnerException: ArchiveOfflineException { Availability: ArchiveAvailability.ReadOnly } }
or ArchiveOfflineException { Availability: ArchiveAvailability.ReadOnly } => Loc.L("Errors.Workspace.ReadOnlyHome"),
HomeUnavailableException or ArchiveOfflineException => Loc.L("Errors.Workspace.Offline"),
HomeUnavailableException or ArchiveOfflineException => ForHome("Errors.Workspace.Offline", server),
ProjectException { Reason: ProjectError.NameTaken } => Loc.L("Errors.Workspace.NameTaken"),
ProjectException { Reason: ProjectError.InvalidName } => Loc.L("Errors.Workspace.InvalidName"),
ProjectException { Reason: ProjectError.MainCannotBeDeleted } => Loc.L("Errors.Workspace.MainKept"),
ProjectException => Loc.L("Errors.Workspace.ProjectGone"),
ProjectException => ForHome("Errors.Workspace.ProjectGone", server),
// A version over the size one may be: saved here (refused before anything was written) or sent (the home stored nothing).
ProjectVersionTooLargeException or WorkspaceSyncException { Outcome: PushOutcome.TooLarge } =>
Loc.L("Errors.Workspace.VersionTooLarge", ProjectSidecars.MaxVersionBytes >> 20),
WorkspaceSyncException => Loc.L("Errors.Workspace.Refused"),
ForHome("Errors.Workspace.VersionTooLarge", server, ProjectSidecars.MaxVersionBytes >> 20),
WorkspaceSyncException => ForHome("Errors.Workspace.Refused", server),
// A server's refusal that keeps its meaning: an account that may not change projects there, above all.
ChronosApiException { Status: HttpStatusCode.Forbidden } => Loc.L("Errors.Workspace.Forbidden"),
ChronosApiException api => ErrorText.ForServer(api),
InvalidDataException => Loc.L("Errors.Workspace.Damaged"),
Editor.EditorException => ex.Message,
_ => ArchiveFailures.Cause(ex),
+13 -1
View File
@@ -355,14 +355,26 @@ public sealed class ArchiveIndexer
{
if (await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) is not { } row
|| !Directory.Exists(paths.Sequence(row.Folder).ProjectsDirectory)) return;
ProjectChangeSet? changed = null;
try
{
await using (await _writer.LockAsync(paths, sequenceId, cancellationToken).ConfigureAwait(false))
{
var folder = await SequenceWriter.FolderAsync(_db, paths, row, cancellationToken).ConfigureAwait(false);
if (!SequenceFolders.Holds(folder, sequenceId) || !Directory.Exists(folder.ProjectsDirectory)) return;
await _projects.ReconcileAsync(folder, sequenceId, cancellationToken).ConfigureAwait(false);
// Projects and versions another program wrote, taken in here, are told as a project call's are: the next call
// finds them in the index already and has nothing to tell.
var before = await ProjectService.WatchedAsync(_db, _writer.Options, sequenceId, cancellationToken).ConfigureAwait(false);
try
{
await _projects.ReconcileAsync(folder, sequenceId, cancellationToken).ConfigureAwait(false);
}
finally
{
if (before is not null) changed = await ProjectService.ChangesAsync(_db, sequenceId, before, settingsChanged: false).ConfigureAwait(false);
}
}
if (changed is not null) await ProjectService.TellAsync(_writer.Options, changed).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
@@ -3,6 +3,7 @@ using Chronos.Core.Archiving;
using Chronos.Core.Conversion;
using Chronos.Core.Diagnostics;
using Chronos.Core.Import;
using Chronos.Core.IO;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Naming;
@@ -348,6 +349,65 @@ public sealed class ArchiveService : IJobHandlerProvider
return await write(await _db.Sequences.GetAsync(sequence.Id, cancellationToken).ConfigureAwait(false)).ConfigureAwait(false);
}
/// <summary>
/// Settings a caller writes into the index (<paramref name="edit"/>: the server's <c>PATCH</c>, with its version checks)
/// written into the sequence's <c>project.json</c> too, under its lease, as every other writer of the settings does: so
/// the file never holds settings older than the index's, which the projects would take for the sequence's own when they
/// meet Main (<see cref="ProjectService"/>). <paramref name="settingsJson"/> goes to the file first; when the index then
/// does not take it (a conflict, the sequence gone) or the edit fails, the file is put back as it was. A sequence with no
/// folder yet is edited in the index alone: its first photo writes the file from the index.
/// </summary>
/// <param name="wait">How long the sequence's lease is waited for.</param>
/// <exception cref="ArgumentException">The sequence or its archive is not in the index.</exception>
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only: nothing is written.</exception>
/// <exception cref="LeaseUnavailableException">Another writer held the sequence for longer than <paramref name="wait"/>: nothing is written.</exception>
/// <exception cref="SequenceFolderMovedException">The sequence's folder does not hold it now: nothing is written.</exception>
/// <exception cref="IOException">The file cannot be written: nothing is written.</exception>
public async Task<SequenceEditResult> EditSettingsAsync(Guid sequenceId, string settingsJson, Func<CancellationToken, Task<SequenceEditResult>> edit, TimeSpan wait,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(settingsJson);
ArgumentNullException.ThrowIfNull(edit);
var (archive, sequence) = await LoadSequenceAsync(sequenceId, cancellationToken).ConfigureAwait(false);
if (string.IsNullOrEmpty(sequence.Folder)) return await edit(cancellationToken).ConfigureAwait(false);
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
await using (await _writer.LockAsync(paths, sequenceId, wait, cancellationToken).ConfigureAwait(false))
{
var row = await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) ?? throw Unknown(sequenceId);
var folder = paths.Sequence(row.Folder);
if (string.IsNullOrEmpty(row.Folder) || !SequenceFolders.Holds(folder, sequenceId)) throw new SequenceFolderMovedException();
var previous = File.Exists(folder.ProjectPath) ? AtomicFile.ReadAllText(folder.ProjectPath) : null;
Directory.CreateDirectory(folder.MetaDirectory);
AtomicFile.WriteAllText(folder.ProjectPath, settingsJson);
SequenceEditResult result;
try
{
result = await edit(cancellationToken).ConfigureAwait(false);
}
catch
{
PutBack(folder, previous);
throw;
}
if (result.Outcome != SequenceEditOutcome.Updated) PutBack(folder, previous);
return result;
}
static void PutBack(SequencePaths folder, string? previous)
{
try
{
if (previous is not null) AtomicFile.WriteAllText(folder.ProjectPath, previous);
else File.Delete(folder.ProjectPath);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("archive", $"The project.json of {folder.RelativeFolder} could not be put back after an edit the index did not take", ex);
}
}
}
public Task<IReadOnlyList<DuplicateGroup>> FindDuplicatesAsync(Guid archiveId, CancellationToken cancellationToken = default) =>
Maintenance.FindDuplicatesAsync(archiveId, cancellationToken);
@@ -26,6 +26,16 @@ public sealed record ArchiveServiceOptions
/// </summary>
public bool ImagesAfterScan { get; init; }
/// <summary>
/// The index may hold settings newer than a sequence's <c>project.json</c>: the server, whose <c>PATCH</c> wrote the
/// settings a client sent into the index alone before owner review 2 phase 5b. When the projects meet a sequence whose two
/// copies differ, the index's is never dropped: Main is born with <c>project.json</c>'s as version 1 and the index's as
/// version 2, in force; a Main the sidecars already hold keeps the index's as a version below the settings in force
/// (<see cref="Projects.ProjectService"/>). The desktop, whose every writer writes the file, takes the file alone: its index
/// can be an old copy (a second PC, a backup).
/// </summary>
public bool IndexSettingsMayLead { get; init; }
/// <summary>
/// Photos a pass works on at once, asked at the start of each sequence (owner review 1, R2: one job runs at a time and
/// the host's parallelism decides how many photos it processes at once; Settings › Rendering › Parallelism on the
@@ -62,6 +72,15 @@ public sealed record ArchiveServiceOptions
/// </summary>
public Func<Guid, string, CancellationToken, Task>? SequenceChanged { get; init; }
/// <summary>
/// Told after a call of <see cref="Projects.ProjectService"/> changed a sequence's projects (owner review 2, R8): a project
/// made, renamed or deleted, a new head (a push, settings another path wrote taken as Main's external version, a merge, the
/// versions another program sharing the archive wrote found in the sidecars), and whether the call wrote Main's head into
/// the sequence's settings. Told once per call, after the sequence's lease is let go. A server tells its connected clients
/// (BRIEF §14.3); a failure is logged and never fails the call.
/// </summary>
public Func<Projects.ProjectChangeSet, CancellationToken, Task>? ProjectsChanged { get; init; }
/// <summary>
/// The free bytes a write under a folder of an archive (its root, its staging folder) may count on, as the host counts
/// them: a server takes the tighter of its space volume (owner review 2, R2) and the folder's own volume, the desktop asks
+2 -2
View File
@@ -7,9 +7,9 @@ namespace Chronos.Data.Projects;
/// <summary>
/// The photos of a sequence's frames at its home as project positions name them (owner review 2, R8), with the encodings
/// a conversion joined (R7): a version parked on a photo before its file was converted, or after a conversion was undone,
/// still finds its frame.
/// still finds its frame. A server builds the same for a sequence it is the home of, and sends its aliases to workspaces.
/// </summary>
internal static class HomePhotos
public static class HomePhotos
{
/// <summary>The links between encodings of the sequence's photos: its tombstones of reason "replaced".</summary>
public static async Task<IReadOnlyList<PhotoAlias>> AliasesAsync(ChronosRepositories db, Guid sequenceId, CancellationToken cancellationToken) =>
+37 -3
View File
@@ -13,11 +13,21 @@ public sealed record HomeSequence(BundleArchive Archive, BundleSequence Sequence
/// <summary>
/// Where a sequence's projects live (owner review 2, R8): the side a workspace pushes to and pulls from, "like git". This
/// PC's archive is one (<see cref="ArchiveProjectHome"/>); a server is the other (phase 5b). Every call may throw
/// <see cref="HomeUnavailableException"/> when the home cannot be reached, and <see cref="ProjectException"/> when it refuses.
/// PC's archive is one (<see cref="ArchiveProjectHome"/>); a server is the other (<see cref="ServerProjectHome"/>, phase
/// 5b). Every call may throw <see cref="HomeUnavailableException"/> when the home cannot be reached, and
/// <see cref="ProjectException"/> when it refuses.
/// </summary>
public interface IProjectHome
{
/// <summary>Gives a project another name (1–60 characters, unique among the sequence's live projects whatever the case).</summary>
/// <exception cref="ProjectException">Unknown project, or the name is invalid or taken.</exception>
Task<SequenceProject> RenameAsync(Guid projectId, string name, CancellationToken cancellationToken) =>
throw new NotSupportedException("This home does not rename projects.");
/// <summary>Deletes a project (never Main) into the home's project trash, with all its versions, which stay readable there.</summary>
/// <exception cref="ProjectException">Unknown project, or the Main project.</exception>
Task DeleteAsync(Guid projectId, CancellationToken cancellationToken) => throw new NotSupportedException("This home does not delete projects.");
/// <summary>The sequence and where it is.</summary>
Task<HomeSequence> SequenceAsync(CancellationToken cancellationToken);
@@ -146,13 +156,37 @@ public sealed class ArchiveProjectHome(ChronosDatabase db, ProjectService projec
public Task<HomeFrames> FramesAsync(CancellationToken cancellationToken) => projects.FramesAsync(sequenceId, cancellationToken);
public Task<SequenceProject> RenameAsync(Guid projectId, string name, CancellationToken cancellationToken) =>
Reach(async () =>
{
await Own(projectId, cancellationToken).ConfigureAwait(false);
return await projects.RenameAsync(projectId, name, cancellationToken).ConfigureAwait(false);
});
public Task DeleteAsync(Guid projectId, CancellationToken cancellationToken) =>
Reach(async () =>
{
await Own(projectId, cancellationToken).ConfigureAwait(false);
await projects.DeleteAsync(projectId, cancellationToken).ConfigureAwait(false);
return true;
});
/// <summary>
/// The sequence's frames version (frames added, removed, converted or renamed), with how many of its photos the index has
/// hashed and a checksum of those hashes (a Verify hashes them, or finds other bytes, without another frames version)
/// and how many removals it keeps (a conversion's links).
/// </summary>
public async Task<string?> FramesStampAsync(CancellationToken cancellationToken)
public async Task<string?> FramesStampAsync(CancellationToken cancellationToken) =>
await StampOfAsync(db, sequenceId, cancellationToken).ConfigureAwait(false);
/// <summary>
/// The stamp of a sequence's frames as an index holds them (<see cref="FramesStampAsync"/>): what a server answers for
/// its sequences too (<c>GET …/projects/frames/stamp</c>).
/// </summary>
/// <exception cref="ProjectException">The sequence is not in the index.</exception>
public static async Task<string> StampOfAsync(ChronosDatabase db, Guid sequenceId, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(db);
var row = await db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false)
?? throw new ProjectException(ProjectError.SequenceNotFound, $"Sequence {sequenceId} is not in the index.");
var (hashed, checksum, removals) = await db.Frames.CountNamedAsync(sequenceId, cancellationToken).ConfigureAwait(false);
+246 -20
View File
@@ -27,6 +27,12 @@ public enum ProjectError
/// <summary>The Main project cannot be deleted: it holds the sequence's own settings.</summary>
MainCannotBeDeleted,
/// <summary>
/// The sequence has no folder in its archive yet (made before its first photo, as a server's new sequence is): it keeps
/// no projects until its first photo places it.
/// </summary>
SequenceEmpty,
}
/// <summary>A project operation was refused; nothing was written.</summary>
@@ -79,6 +85,19 @@ public sealed record PushResult(PushOutcome Outcome, ProjectVersion? Version, Pr
/// </summary>
public sealed record HomeFrames(int FramesVersion, IReadOnlyList<Frame> Frames, FramePhotos Photos);
/// <summary>
/// One project a <see cref="ProjectService"/> call changed: <see cref="Change"/> is one of <see cref="Protocol.ProjectChanges"/>
/// (<c>created</c>, <c>renamed</c>, <c>deleted</c>, <c>pushed</c>: a new head), with the project's head after the call.
/// </summary>
public sealed record ProjectChange(Guid ProjectId, string Change, int HeadNumber, Guid? HeadVersionId);
/// <summary>
/// What one <see cref="ProjectService"/> call changed in a sequence's projects (<see cref="ArchiveServiceOptions.ProjectsChanged"/>):
/// the projects, in index order, and whether it wrote Main's head into the sequence's settings (<see cref="SettingsChanged"/>:
/// the sequence's settings version moved, which the code paths that read the sequence's settings want to know).
/// </summary>
public sealed record ProjectChangeSet(Guid SequenceId, IReadOnlyList<ProjectChange> Changes, bool SettingsChanged);
/// <summary>
/// The projects of the sequences of this PC's archives (owner review 2, R8): the home side of a workspace's push and pull.
/// Every operation runs under the sequence's lease and first catches up: the sidecars into the index
@@ -393,6 +412,7 @@ public sealed class ProjectService
ArgumentNullException.ThrowIfNull(version);
if (await _db.Projects.GetAsync(projectId, cancellationToken).ConfigureAwait(false) is not { DeletedAt: null } project) return false;
var (paths, row) = await LocateAsync(project.SequenceId, cancellationToken).ConfigureAwait(false);
if (Unplaced(row)) return false;
if (Availability(paths) == ArchiveAvailability.Offline) throw new ArchiveOfflineException(paths.Root, ArchiveAvailability.Offline);
var folder = paths.Sequence(row.Folder);
if (!SequenceFolders.Holds(folder, project.SequenceId)) throw new SequenceFolderMovedException();
@@ -412,6 +432,20 @@ public sealed class ProjectService
return false;
}
/// <summary>
/// Brings the sequence's projects in step now (see the class remarks: the sidecars into the index, Main made, settings
/// another path wrote appended to Main), as every call does first, but saying why when it cannot: what a host runs soon
/// after it wrote a sequence's settings outside the projects, so Main takes them (and is told, <see
/// cref="ArchiveServiceOptions.ProjectsChanged"/>) before anyone asks.
/// </summary>
/// <exception cref="ProjectException">The sequence is not in the index.</exception>
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only.</exception>
/// <exception cref="LeaseUnavailableException">Another writer held the sequence for longer than a read waits.</exception>
/// <exception cref="SequenceFolderMovedException">The sequence's folder does not hold it.</exception>
/// <exception cref="ProjectsUnreadableException">The index has no Main and a project record cannot be read now (it may be Main's).</exception>
public Task CatchUpAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
UnderLeaseAsync(sequenceId, (_, _) => Task.FromResult(true), cancellationToken, ReadWait);
/// <summary>
/// Catches the sequence's projects up under its lease (see the class remarks) before a read; the index alone answers while
/// the archive is offline, the sequence busy for longer than the lease wait, or a project of it cannot be read now. A
@@ -419,6 +453,8 @@ public sealed class ProjectService
/// </summary>
private async Task ReadAsync(Guid sequenceId, CancellationToken cancellationToken)
{
// A sequence with no folder yet keeps no projects: nothing to catch up, and nothing may be written (its folder would be the archive's root).
if (Unplaced(await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) ?? throw SequenceMissing(sequenceId))) return;
try
{
try
@@ -452,6 +488,8 @@ public sealed class ProjectService
{
var (paths, row) = await LocateAsync(sequenceId, cancellationToken).ConfigureAwait(false);
var folder = paths.Sequence(row.Folder);
// What the sidecars bring into the index, and a Main made in it, are told as any other call's changes.
var before = await WatchedAsync(sequenceId, cancellationToken).ConfigureAwait(false);
try
{
if (!SequenceFolders.Holds(folder, sequenceId))
@@ -467,6 +505,11 @@ public sealed class ProjectService
{
Log.Info("projects", $"The projects of sequence {sequenceId} are read from the index: {ex.Message}");
}
finally
{
if (before is not null && await ChangesAsync(sequenceId, before, settingsChanged: false).ConfigureAwait(false) is { } changed)
await TellAsync(changed).ConfigureAwait(false);
}
}
/// <summary>
@@ -480,17 +523,109 @@ public sealed class ProjectService
private async Task<T> UnderLeaseAsync<T>(Guid sequenceId, Func<LeaseContext, CancellationToken, Task<T>> work, CancellationToken cancellationToken,
TimeSpan? wait = null)
{
var (paths, _) = await LocateAsync(sequenceId, cancellationToken).ConfigureAwait(false);
var (paths, located) = await LocateAsync(sequenceId, cancellationToken).ConfigureAwait(false);
// Before the lease: the archive's root is no sequence's folder, so nothing of this sequence's projects is read from it or written into it.
if (Unplaced(located))
throw new ProjectException(ProjectError.SequenceEmpty, $"Sequence {sequenceId} has no folder yet: it keeps no projects before its first photo.");
var availability = Availability(paths);
if (availability != ArchiveAvailability.Online) throw new ArchiveOfflineException(paths.Root, availability);
await using (await _writer.LockAsync(paths, sequenceId, wait, cancellationToken).ConfigureAwait(false))
ProjectChangeSet? changed = null;
try
{
var row = await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) ?? throw SequenceMissing(sequenceId);
var folder = paths.Sequence(row.Folder);
if (!SequenceFolders.Holds(folder, sequenceId)) throw new SequenceFolderMovedException();
var context = new LeaseContext(folder, row, await _indexer.ReconcileAsync(folder, sequenceId, cancellationToken).ConfigureAwait(false));
await CatchUpAsync(context, cancellationToken).ConfigureAwait(false);
return await work(context, cancellationToken).ConfigureAwait(false);
await using (await _writer.LockAsync(paths, sequenceId, wait, cancellationToken).ConfigureAwait(false))
{
var row = await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) ?? throw SequenceMissing(sequenceId);
var folder = paths.Sequence(row.Folder);
if (Unplaced(row) || !SequenceFolders.Holds(folder, sequenceId)) throw new SequenceFolderMovedException();
// Taken before the reconcile: the versions another program wrote into the sidecars are told too.
var before = await WatchedAsync(sequenceId, cancellationToken).ConfigureAwait(false);
LeaseContext? context = null;
try
{
context = new LeaseContext(folder, row, await _indexer.ReconcileAsync(folder, sequenceId, cancellationToken).ConfigureAwait(false));
await CatchUpAsync(context, cancellationToken).ConfigureAwait(false);
return await work(context, cancellationToken).ConfigureAwait(false);
}
finally
{
// What the reconcile, the catch-up and the work wrote stays written even when the work then refused or failed.
if (before is not null)
changed = await ChangesAsync(sequenceId, before, context is not null && row.SettingsVersion != context.Row.SettingsVersion).ConfigureAwait(false);
}
}
}
finally
{
if (changed is not null) await TellAsync(changed).ConfigureAwait(false);
}
}
/// <summary>The sequence's projects as the index has them now (deleted ones too), when someone is to be told what changes; else null.</summary>
private Task<Dictionary<Guid, SequenceProject>?> WatchedAsync(Guid sequenceId, CancellationToken cancellationToken) =>
WatchedAsync(_db, _writer.Options, sequenceId, cancellationToken);
private Task<ProjectChangeSet?> ChangesAsync(Guid sequenceId, Dictionary<Guid, SequenceProject> before, bool settingsChanged) =>
ChangesAsync(_db, sequenceId, before, settingsChanged);
private Task TellAsync(ProjectChangeSet changed) => TellAsync(_writer.Options, changed);
/// <summary>
/// The sequence's projects as the index has them now (deleted ones too), when someone is to be told what changes
/// (<see cref="ArchiveServiceOptions.ProjectsChanged"/>); else null. Shared with the scans that take the sidecars back
/// outside a project call (<see cref="ArchiveIndexer"/>).
/// </summary>
internal static async Task<Dictionary<Guid, SequenceProject>?> WatchedAsync(ChronosDatabase db, ArchiveServiceOptions options, Guid sequenceId,
CancellationToken cancellationToken) =>
options.ProjectsChanged is null
? null
: (await db.Projects.ListBySequenceAsync(sequenceId, includeDeleted: true, cancellationToken).ConfigureAwait(false)).ToDictionary(p => p.Id);
/// <summary>
/// What changed in the sequence's projects since <paramref name="before"/> (a project new or back, deleted, renamed or
/// made Main or no longer Main, or with a new head); null when nothing did. Never throws: it runs after the work,
/// whatever became of it.
/// </summary>
internal static async Task<ProjectChangeSet?> ChangesAsync(ChronosDatabase db, Guid sequenceId, Dictionary<Guid, SequenceProject> before, bool settingsChanged)
{
IReadOnlyList<SequenceProject> after;
try
{
after = await db.Projects.ListBySequenceAsync(sequenceId, includeDeleted: true, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex) when (ex is DatabaseException or IOException or InvalidOperationException)
{
Log.Warning("projects", $"The project changes of sequence {sequenceId} cannot be read", ex);
return null;
}
var changes = new List<ProjectChange>();
foreach (var project in after)
{
before.TryGetValue(project.Id, out var was);
var (live, wasLive) = (project.DeletedAt is null, was is { DeletedAt: null });
if (live && !wasLive) changes.Add(Change(project, Protocol.ProjectChanges.Created));
else if (!live && wasLive) changes.Add(Change(project, Protocol.ProjectChanges.Deleted));
else if (live)
{
// Main passed to another project (the sidecars name another one Main): told as a rename, which lists read again for.
if (project.Name != was!.Name || project.IsMain != was.IsMain) changes.Add(Change(project, Protocol.ProjectChanges.Renamed));
if (project.HeadVersionId != was.HeadVersionId) changes.Add(Change(project, Protocol.ProjectChanges.Pushed));
}
}
return changes.Count == 0 && !settingsChanged ? null : new ProjectChangeSet(sequenceId, changes, settingsChanged);
static ProjectChange Change(SequenceProject project, string change) => new(project.Id, change, project.HeadNumber, project.HeadVersionId);
}
/// <summary>Tells the host what a call changed; a failure is logged, never passed on.</summary>
internal static async Task TellAsync(ArchiveServiceOptions options, ProjectChangeSet changed)
{
try
{
await options.ProjectsChanged!(changed, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
Log.Warning("projects", $"The project changes of sequence {changed.SequenceId} were not told", ex);
}
}
@@ -664,9 +799,15 @@ public sealed class ProjectService
await _db.Projects.SetMirroredAsync(main.Id, head.Id, context.Row.SettingsVersion, cancellationToken).ConfigureAwait(false);
return;
}
if (LeadingCopy(context, shared, CurrentPortable(context, photos), photos) is { } copy && !ProjectContent.SameChoices(head.SettingsJson, copy, photos)
&& !await MirroredBeforeAsync(main, head, null, copy, photos, cancellationToken).ConfigureAwait(false))
{
await KeepCopyAsync(context, main, head, shared, copy, photos, cancellationToken).ConfigureAwait(false);
return;
}
if (ProjectContent.SameChoices(head.SettingsJson, shared, photos))
{
if (CurrentPortable(context, photos) is { } copy && ProjectContent.SameChoices(head.SettingsJson, copy, photos))
if (CurrentPortable(context, photos) is { } current && ProjectContent.SameChoices(head.SettingsJson, current, photos))
await MarkMirroredAsync(context, main, head, photos, cancellationToken).ConfigureAwait(false);
else
await MirrorAsync(context, main, head, cancellationToken).ConfigureAwait(false);
@@ -691,6 +832,58 @@ public sealed class ProjectService
await MirrorAsync(context, main, external, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Main met with no mirror known on a host whose index may hold newer settings than <c>project.json</c>
/// (<see cref="ArchiveServiceOptions.IndexSettingsMayLead"/>), with this index's copy (<paramref name="copy"/>) none of
/// Main's versions: which of the two is newer cannot be told (an earlier server's <c>PATCH</c> wrote the index alone, an
/// index taken back from a backup is old), so both are kept. The copy becomes an External version on the head, and on
/// it the settings the meeting puts in force as it does elsewhere, from <c>project.json</c>: the head (a mirror cut
/// short, brought back as a Restore), a merge with the versions no mirror wrote, or <c>project.json</c>'s as External.
/// That is mirrored.
/// </summary>
private async Task KeepCopyAsync(LeaseContext context, SequenceProject main, ProjectVersion head, string shared, string copy, FramePhotos photos,
CancellationToken cancellationToken)
{
var recorded = await RecordedMirrorAsync(context, main, head, cancellationToken).ConfigureAwait(false);
var headMirrored = context.Reconcile.Live.TryGetValue(main.Id, out var record) && record.Mirrored?.Id == head.Id;
var (inForce, kind) = ProjectContent.SameChoices(head.SettingsJson, shared, photos)
|| (!headMirrored && await MirroredBeforeAsync(main, head, recorded, shared, photos, cancellationToken).ConfigureAwait(false))
? (head.SettingsJson, ProjectVersionKind.Restore)
: recorded is not null && Merged(recorded, head, shared, photos) is { } merged
? (merged, ProjectVersionKind.Merge)
: (shared, ProjectVersionKind.External);
Log.Warning("projects", $"The settings of sequence {context.Row.Id} in the index differ from its project.json and from Main's versions: "
+ $"they are kept as version {head.Number + 1} of Main, and the settings project.json gives on top of it");
var kept = await AppendDerivedAsync(context, main, head, copy, ProjectVersionKind.External, cancellationToken).ConfigureAwait(false);
main = (await _db.Projects.GetAsync(main.Id, cancellationToken).ConfigureAwait(false))!;
var top = kept;
if (!ProjectContent.SameChoices(copy, inForce, photos))
{
var restoredFrom = kind == ProjectVersionKind.Restore ? head.Id : (Guid?)null;
top = NewVersion(main.Id, kept.Id, main.HeadNumber + 1, kind, inForce, context.Row.FramesVersion, DateTimeOffset.UtcNow) with { RestoredFrom = restoredFrom };
main = await AppendAsync(context.Folder, main, top, cancellationToken).ConfigureAwait(false);
}
// project.json's settings are taken in (kept or in force): the mirror writes over them.
await MirrorAsync(context, main, top, cancellationToken, shared).ConfigureAwait(false);
}
/// <summary>
/// <paramref name="theirs"/> merged with <paramref name="head"/> over <paramref name="basis"/> as <see cref="MergeIntoMainAsync"/>
/// merges them (<paramref name="theirs"/> wins where both changed); null when either is of a newer Chronos.
/// </summary>
private static string? Merged(ProjectVersion basis, ProjectVersion head, string theirs, FramePhotos photos)
{
try
{
return ProjectContent.Canonical(ProjectMerge.MergeWithConflicts(ProjectMerge.Read(ProjectContent.Rebind(basis.SettingsJson, photos)),
ProjectMerge.Read(ProjectContent.Rebind(theirs, photos)), ProjectMerge.Read(ProjectContent.Rebind(head.SettingsJson, photos))).Merged.ToJson());
}
catch (NewerSettingsException)
{
return null;
}
}
/// <summary>
/// The version Main's record names as mirrored last, when it is one the head descends from (not the head itself) and of
/// a format this Chronos reads; null otherwise (an older record names none).
@@ -863,9 +1056,11 @@ public sealed class ProjectService
/// <summary>
/// The Main project of a sequence that has none: version 1 from the sequence's settings as its <c>project.json</c> holds
/// them (this index's copy when there is none, else defaults), this index's copy brought up to them. With the archive
/// read-only it is made in the index only, and nothing is written to the archive: its sidecars are written once the
/// archive takes writes (<see cref="WriteBackAsync"/>).
/// them (this index's copy when there is none, else defaults), this index's copy brought up to them. On a host whose index
/// may hold newer settings than the file (<see cref="ArchiveServiceOptions.IndexSettingsMayLead"/>: the server) and when
/// the two differ, the index's copy is version 2 (External) on top, in force and mirrored: neither is lost. With the
/// archive read-only it is made in the index only, and nothing is written to the archive: its sidecars are written once
/// the archive takes writes (<see cref="WriteBackAsync"/>).
/// </summary>
private async Task MakeMainAsync(LeaseContext context, bool writable, CancellationToken cancellationToken)
{
@@ -884,20 +1079,39 @@ public sealed class ProjectService
UpdatedAt = now,
};
var first = NewVersion(project.Id, null, 1, ProjectVersionKind.Imported, portable, context.Row.FramesVersion, now);
var versions = new List<ProjectVersion> { first };
if (LeadingCopy(context, shared, copy, frames.Photos) is { } leading)
{
Log.Warning("projects", $"The settings of sequence {context.Row.Id} in the index differ from its project.json: Main is made with project.json's as "
+ "version 1 and the index's as version 2, in force");
versions.Add(NewVersion(project.Id, first.Id, 2, ProjectVersionKind.External, leading, context.Row.FramesVersion, now));
}
// Settings this Chronos cannot read (of a newer one) are never written over: the index's copy then stays as it is too.
var inStep = shared is null || copy is null || ProjectContent.SameChoices(portable, copy, frames.Photos);
var inStep = versions.Count == 1 && (shared is null || copy is null || ProjectContent.SameChoices(portable, copy, frames.Photos));
if (inStep) project = project with { MirroredSettingsVersion = context.Row.SettingsVersion, MirroredVersionId = first.Id };
if (!writable)
{
await AddProjectAsync(null, project, first, null, cancellationToken).ConfigureAwait(false);
await AddProjectAsync(null, project, versions, null, cancellationToken).ConfigureAwait(false);
return;
}
var onDisk = shared is not null && File.Exists(context.Folder.ProjectPath);
var made = await AddProjectAsync(context.Folder, project, first, onDisk ? new ProjectHead(first.Id, first.Number) : null, cancellationToken)
var made = await AddProjectAsync(context.Folder, project, versions, onDisk ? new ProjectHead(first.Id, first.Number) : null, cancellationToken)
.ConfigureAwait(false);
if (!inStep) await MirrorAsync(context, made, first, cancellationToken).ConfigureAwait(false);
// project.json holds version 1: what the mirror of version 2 writes over is taken in already.
if (!inStep) await MirrorAsync(context, made, versions[^1], cancellationToken, versions.Count > 1 ? shared : null).ConfigureAwait(false);
}
/// <summary>
/// This index's copy of the sequence's settings when it differs from its <c>project.json</c> on a host whose index may hold
/// the newer ones (<see cref="ArchiveServiceOptions.IndexSettingsMayLead"/>); null otherwise (the desktop, the two the same,
/// either unreadable, or no file: then <paramref name="shared"/> is the copy).
/// </summary>
private string? LeadingCopy(LeaseContext context, string? shared, string? copy, FramePhotos photos) =>
_writer.Options.IndexSettingsMayLead && shared is not null && copy is not null && File.Exists(context.Folder.ProjectPath)
&& !ProjectContent.SameChoices(shared, copy, photos)
? copy
: null;
/// <summary>"Main", or "Main (2)"… when a project of that name exists already (one made before the sequence had its Main).</summary>
private async Task<string> FreeMainNameAsync(Guid sequenceId, CancellationToken cancellationToken)
{
@@ -967,18 +1181,24 @@ public sealed class ProjectService
/// A new project with its first version: sidecars (version, then the record, naming <paramref name="mirrored"/>), then
/// both rows in one transaction; the rows only when <paramref name="folder"/> is null (a read-only archive).
/// </summary>
private async Task<SequenceProject> AddProjectAsync(SequencePaths? folder, SequenceProject project, ProjectVersion first, ProjectHead? mirrored,
private Task<SequenceProject> AddProjectAsync(SequencePaths? folder, SequenceProject project, ProjectVersion first, ProjectHead? mirrored,
CancellationToken cancellationToken) =>
AddProjectAsync(folder, project, [first], mirrored, cancellationToken);
/// <summary>A new project with its first versions, in order (each the next one's parent): the last is its head.</summary>
private async Task<SequenceProject> AddProjectAsync(SequencePaths? folder, SequenceProject project, IReadOnlyList<ProjectVersion> versions, ProjectHead? mirrored,
CancellationToken cancellationToken)
{
var withHead = project with { HeadVersionId = first.Id, HeadNumber = first.Number };
var head = versions[^1];
var withHead = project with { HeadVersionId = head.Id, HeadNumber = head.Number };
if (folder is not null)
{
ProjectSidecars.WriteVersion(folder.VersionPath(project.Id, first.Number, first.Id), first);
foreach (var version in versions) ProjectSidecars.WriteVersion(folder.VersionPath(project.Id, version.Number, version.Id), version);
ProjectSidecars.WriteRecord(folder.ProjectRecordPath(project.Id), ProjectRecord.Of(withHead, mirrored));
}
await using var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false);
await tx.Projects.InsertAsync(withHead with { HeadVersionId = null, HeadNumber = 0 }, cancellationToken).ConfigureAwait(false);
await tx.Projects.InsertVersionAsync(first, cancellationToken).ConfigureAwait(false);
foreach (var version in versions) await tx.Projects.InsertVersionAsync(version, cancellationToken).ConfigureAwait(false);
await tx.Projects.UpdateAsync(withHead, cancellationToken).ConfigureAwait(false);
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
return withHead;
@@ -1222,6 +1442,12 @@ public sealed class ProjectService
? project
: throw new ProjectException(ProjectError.NotFound, $"Project {projectId} was deleted.");
/// <summary>
/// Whether the sequence has no folder in its archive yet (a server's sequence made before its first photo): its folder
/// would read as the archive's root, which every such sequence shares and which is no sequence's.
/// </summary>
private static bool Unplaced(Sequence row) => string.IsNullOrEmpty(row.Folder);
private static ProjectException SequenceMissing(Guid sequenceId) => new(ProjectError.SequenceNotFound, $"Sequence {sequenceId} is not in the index.");
/// <summary>The sequence as read under its lease (the mirror moves its settings version), its folder, and what its projects' reconcile met.</summary>
+123
View File
@@ -0,0 +1,123 @@
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Processing;
using Chronos.Protocol;
namespace Chronos.Data.Projects;
/// <summary>
/// Projects and their versions on the wire (owner review 2, R8): what a server answers from its index, and how a client
/// reads it back into the model a workspace works with, so a server is a project home like this PC's archive; with the
/// wire names of the push outcomes.
/// </summary>
public static class ProjectWire
{
/// <summary>A project as the API shows it; <paramref name="head"/> (its head version) says who changed it last, and when.</summary>
public static ProjectDto ToDto(SequenceProject project, ProjectVersion? head = null)
{
ArgumentNullException.ThrowIfNull(project);
return new ProjectDto(project.Id, project.SequenceId, project.Name, project.IsMain, project.HeadVersionId, project.HeadNumber, project.CreatedBy,
project.CreatedAt, project.UpdatedAt, head is null ? null : ProjectVersionKinds.Name(head.Kind), head?.Author, head?.ClientName, head?.StoredAt);
}
public static ProjectVersionDto ToDto(ProjectVersion version)
{
ArgumentNullException.ThrowIfNull(version);
return new ProjectVersionDto(version.Id, version.ProjectId, version.ParentId, version.Number, ProjectVersionKinds.Name(version.Kind), version.Author,
version.ClientName, version.Note, version.SettingsJson, version.ContentHash, version.SettingsFormat, version.FramesVersion, version.RestoredFrom,
version.CreatedAt, version.StoredAt);
}
/// <summary>A project of a server sequence as the model knows it (the mirror fields stay the server's own).</summary>
public static SequenceProject ToProject(ProjectDto dto)
{
ArgumentNullException.ThrowIfNull(dto);
return new SequenceProject
{
Id = dto.Id,
SequenceId = dto.SequenceId,
Name = dto.Name,
IsMain = dto.IsMain,
HeadVersionId = dto.HeadVersionId,
HeadNumber = dto.HeadNumber,
CreatedBy = dto.CreatedBy,
CreatedAt = dto.CreatedAt,
UpdatedAt = dto.UpdatedAt,
};
}
/// <summary>A version as the model knows it; a kind this build does not know reads as a commit (<see cref="ProjectVersionKinds.Parse"/>).</summary>
public static ProjectVersion ToVersion(ProjectVersionDto dto)
{
ArgumentNullException.ThrowIfNull(dto);
return new ProjectVersion
{
Id = dto.Id,
ProjectId = dto.ProjectId,
ParentId = dto.ParentId,
Number = dto.Number,
Kind = ProjectVersionKinds.Parse(dto.Kind),
Author = dto.Author,
ClientName = dto.ClientName,
Note = dto.Note,
SettingsJson = dto.SettingsJson,
ContentHash = dto.ContentHash,
SettingsFormat = dto.SettingsFormat,
FramesVersion = dto.FramesVersion,
RestoredFrom = dto.RestoredFrom,
CreatedAt = dto.CreatedAt,
StoredAt = dto.StoredAt,
};
}
/// <summary>The wire name of <paramref name="outcome"/> (<see cref="ProjectPushOutcomes"/>).</summary>
public static string Outcome(PushOutcome outcome) => outcome switch
{
PushOutcome.Stored => ProjectPushOutcomes.Stored,
PushOutcome.AlreadyStored => ProjectPushOutcomes.AlreadyStored,
PushOutcome.Diverged => ProjectPushOutcomes.Diverged,
PushOutcome.HashMismatch => ProjectPushOutcomes.HashMismatch,
PushOutcome.NewerFormat => ProjectPushOutcomes.NewerFormat,
PushOutcome.TooLarge => ProjectPushOutcomes.TooLarge,
_ => ProjectPushOutcomes.Invalid,
};
/// <summary>The outcome a wire name stands for; one this build does not know is a refusal (<see cref="PushOutcome.Invalid"/>).</summary>
public static PushOutcome ParseOutcome(string? name) => name switch
{
ProjectPushOutcomes.Stored => PushOutcome.Stored,
ProjectPushOutcomes.AlreadyStored => PushOutcome.AlreadyStored,
ProjectPushOutcomes.Diverged => PushOutcome.Diverged,
ProjectPushOutcomes.HashMismatch => PushOutcome.HashMismatch,
ProjectPushOutcomes.NewerFormat => PushOutcome.NewerFormat,
ProjectPushOutcomes.TooLarge => PushOutcome.TooLarge,
_ => PushOutcome.Invalid,
};
/// <summary>A push's answer as <see cref="ProjectService.PushAsync"/> gives it on this PC's archive.</summary>
public static PushResult ToResult(ProjectPushResultDto dto)
{
ArgumentNullException.ThrowIfNull(dto);
return new PushResult(ParseOutcome(dto.Outcome), dto.Version is null ? null : ToVersion(dto.Version), dto.Head is null ? null : ToVersion(dto.Head));
}
/// <summary>
/// The links a server sends with a sequence's frames (<see cref="ProjectFramesDto.Aliases"/>): its tombstones of reason
/// <c>replaced</c> with their replacement.
/// </summary>
public static IReadOnlyList<RemovedPhotoDto> Aliases(IEnumerable<FrameRemoval> removals) =>
Sync.SyncTombstones.ToDto(removals.Where(r => r.Reason == RemovalReason.Replaced && !string.IsNullOrEmpty(r.ReplacementSha256)));
/// <summary>
/// The frames a server sequence's project positions are placed on, as <see cref="ProjectService.FramesAsync"/> gives a
/// sequence of this PC's archive: rows in index order and their photos, with the encodings its conversions joined.
/// </summary>
public static HomeFrames ToHomeFrames(ProjectFramesDto dto)
{
ArgumentNullException.ThrowIfNull(dto);
var frames = dto.Frames.Select(RenderNodeClient.ToFrame).OrderBy(f => f.Index).ToList();
var aliases = (dto.Aliases ?? []).Where(a => !string.IsNullOrEmpty(a.Sha256) && !string.IsNullOrEmpty(a.Replacement))
.Select(a => new PhotoAlias(a.Sha256, a.Replacement!)).ToList();
return new HomeFrames(dto.FramesVersion, frames, HomePhotos.Of(frames, aliases));
}
}
@@ -0,0 +1,231 @@
using System.Net;
using System.Text.Json;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Protocol.Client;
namespace Chronos.Data.Projects;
/// <summary>
/// A sequence of a Chronos Server as its projects' home (owner review 2, R8, phase 5b): the server's
/// <c>/api/v1/sequences/{sid}/projects</c> through <see cref="ChronosClient"/>, read into the model a workspace works with
/// (<see cref="ProjectWire"/>), so a workspace pushes to and pulls from a server as it does with this PC's archive. A
/// server out of reach (no answer, a timeout, a certificate it no longer presents, an answer that is not the API's), a
/// sign-in that expired, a sequence the server holds busy or an archive offline there (503), a project file it cannot write
/// for now and a server that keeps no projects are <see cref="HomeUnavailableException"/>s: the workspace shows Offline and
/// its work waits. A sequence, project or version the server does not have, and a name it refuses, are
/// <see cref="ProjectException"/>s as on this PC's archive; anything else (an account without the right, a request the
/// server takes for wrong) keeps its <see cref="ChronosApiException"/>. A push answers its outcome without throwing (a
/// divergence carries the head). The client is the caller's: the home never disposes it, and a client disposed meanwhile
/// (the session ended) is a home out of reach.
/// </summary>
public sealed class ServerProjectHome : IProjectHome
{
/// <summary>The largest page of versions the server answers.</summary>
private const int MaxPage = 200;
/// <param name="serverName">The server's name as its <c>server/info</c> gives it, for the project file; the address's host when null.</param>
public ServerProjectHome(ChronosClient client, Guid sequenceId, string? serverName = null)
{
ArgumentNullException.ThrowIfNull(client);
Client = client;
SequenceId = sequenceId;
Server = SyncService.ServerKey(client.BaseAddress);
ServerName = string.IsNullOrWhiteSpace(serverName) ? client.BaseAddress.Host : serverName.Trim();
}
public ChronosClient Client { get; }
/// <summary>The server's sequence.</summary>
public Guid SequenceId { get; }
/// <summary>The server as workspace projects and sync links name it (<see cref="SyncService.ServerKey"/>).</summary>
public string Server { get; }
public string ServerName { get; }
/// <summary>The home of a workspace project of this server's sequence.</summary>
public BundleHome Home => new(BundleHome.ServerKind, SequenceId, null, Server);
/// <remarks>
/// A project file names an archive by id: a server's sequences carry one made from the server's key
/// (<see cref="ArchiveIdOf"/>), with the server's name and no path.
/// </remarks>
public Task<HomeSequence> SequenceAsync(CancellationToken cancellationToken) =>
Reach(async () =>
{
var sequence = await Client.GetSequenceAsync(SequenceId, cancellationToken).ConfigureAwait(false);
return new HomeSequence(new BundleArchive(ArchiveIdOf(Server), ServerName, null), new BundleSequence(sequence.Id, sequence.Folder, sequence.DisplayTitle,
sequence.FrameCount), Home);
}, cancellationToken);
/// <summary>
/// The archive id a server's sequences carry in a workspace's project file, which names one: the same for every
/// sequence of <paramref name="server"/> (<see cref="SyncService.ServerKey"/>), made from its key (a version 8 UUID),
/// never one of this PC's archives.
/// </summary>
public static Guid ArchiveIdOf(string server)
{
ArgumentNullException.ThrowIfNull(server);
var hash = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes("chronos-server-archive:" + server));
hash[6] = (byte)((hash[6] & 0x0F) | 0x80);
hash[8] = (byte)((hash[8] & 0x3F) | 0x80);
return new Guid(hash.AsSpan(0, 16), bigEndian: true);
}
public Task<IReadOnlyList<SequenceProject>> ListAsync(CancellationToken cancellationToken) =>
Reach<IReadOnlyList<SequenceProject>>(async () =>
[.. (await Client.ListProjectsAsync(SequenceId, cancellationToken).ConfigureAwait(false)).Select(ProjectWire.ToProject)], cancellationToken);
/// <remarks>The server records the account that makes the project as its maker, whatever <paramref name="author"/> says.</remarks>
public Task<SequenceProject> CreateAsync(string name, Guid? fromVersionId, string? author, CancellationToken cancellationToken) =>
Reach(async () => ProjectWire.ToProject(await Client.CreateProjectAsync(SequenceId, new CreateProjectRequest(name, fromVersionId), cancellationToken)
.ConfigureAwait(false)), cancellationToken);
public Task<ProjectVersion> HeadAsync(Guid projectId, CancellationToken cancellationToken) =>
Reach(async () => ProjectWire.ToVersion(await Client.GetProjectHeadAsync(SequenceId, projectId, cancellationToken).ConfigureAwait(false)), cancellationToken);
public Task<ProjectVersion?> GetVersionAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken) =>
Reach(async () => await Client.GetProjectVersionAsync(SequenceId, projectId, versionId, cancellationToken).ConfigureAwait(false) is { } version
? ProjectWire.ToVersion(version)
: null, cancellationToken);
/// <remarks>
/// The server ends a page early when its versions' settings are large (<see cref="ProjectVersionPageDto.More"/>): the
/// pages are read on until <paramref name="limit"/> versions came or no more follow, so a short answer always means the end.
/// </remarks>
public Task<IReadOnlyList<ProjectVersion>> VersionsAfterAsync(Guid projectId, int afterNumber, int limit, CancellationToken cancellationToken) =>
Reach(() => PagesAsync(Page(limit), last => Client.ListProjectVersionsAsync(SequenceId, projectId, after: Math.Max(0, last?.Number ?? afterNumber),
limit: Page(limit), ct: cancellationToken)), cancellationToken);
/// <remarks>Read on past a page the server ended early, as <see cref="VersionsAfterAsync"/> is.</remarks>
public Task<IReadOnlyList<ProjectVersion>> HistoryAsync(Guid projectId, int? beforeNumber, int limit, CancellationToken cancellationToken) =>
Reach(() => PagesAsync(Page(limit), last => Client.ListProjectVersionsAsync(SequenceId, projectId,
before: last is not null ? last.Number : beforeNumber is { } before ? Math.Max(0, before) : null, limit: Page(limit), ct: cancellationToken)),
cancellationToken);
/// <summary>Up to <paramref name="limit"/> versions, page after page (each read after the last version of the one before) while more follow.</summary>
private static async Task<IReadOnlyList<ProjectVersion>> PagesAsync(int limit, Func<ProjectVersion?, Task<ProjectVersionPageDto>> read)
{
var versions = new List<ProjectVersion>();
while (true)
{
var page = await read(versions.Count > 0 ? versions[^1] : null).ConfigureAwait(false);
versions.AddRange(page.Items.Take(limit - versions.Count).Select(ProjectWire.ToVersion));
if (!page.More || page.Items.Count == 0 || versions.Count >= limit) return versions;
}
}
/// <summary>
/// Read back from the version's file on the server (<c>?stored=true</c>: <see cref="ProjectService.StoredAsync"/> there),
/// never from its index's row: false when the file is missing or damaged, or the project was deleted.
/// </summary>
public Task<bool> HoldsAsync(Guid projectId, ProjectVersion version, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(version);
return Reach(async () =>
{
if (!ProjectContent.Verifies(version.SettingsJson, version.ContentHash)) return false;
try
{
return await Client.GetStoredProjectVersionAsync(SequenceId, projectId, version.Id, cancellationToken).ConfigureAwait(false) is { } held
&& held.ProjectId == projectId && string.Equals(held.ContentHash, version.ContentHash, StringComparison.OrdinalIgnoreCase);
}
catch (ChronosApiException ex) when (ex is { Status: HttpStatusCode.NotFound, Error.Details: "project" })
{
return false;
}
}, cancellationToken);
}
/// <summary>The server's stamp of the frames (<c>GET …/projects/frames/stamp</c>): the frames are downloaded again only when it moved.</summary>
public Task<string?> FramesStampAsync(CancellationToken cancellationToken) =>
Reach<string?>(async () => (await Client.GetProjectFramesStampAsync(SequenceId, cancellationToken).ConfigureAwait(false)).Stamp, cancellationToken);
/// <remarks>The server numbers the version (head + 1) and records the account that pushed it as its author.</remarks>
public Task<PushResult> PushAsync(Guid projectId, ProjectVersion version, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(version);
return Reach(async () => ProjectWire.ToResult(await Client.PushProjectVersionAsync(SequenceId, projectId, ProjectWire.ToDto(version), cancellationToken)
.ConfigureAwait(false)), cancellationToken);
}
public Task<HomeFrames> FramesAsync(CancellationToken cancellationToken) =>
Reach(async () => ProjectWire.ToHomeFrames(await Client.GetProjectFramesAsync(SequenceId, cancellationToken).ConfigureAwait(false)), cancellationToken);
public Task<SequenceProject> RenameAsync(Guid projectId, string name, CancellationToken cancellationToken) =>
Reach(async () => ProjectWire.ToProject(await Client.RenameProjectAsync(SequenceId, projectId, name, cancellationToken).ConfigureAwait(false)),
cancellationToken);
public Task DeleteAsync(Guid projectId, CancellationToken cancellationToken) =>
Reach(async () =>
{
await Client.DeleteProjectAsync(SequenceId, projectId, cancellationToken).ConfigureAwait(false);
return true;
}, cancellationToken);
/// <summary>
/// Whether <paramref name="exception"/> says a server is out of reach for now (see the class remarks), not that it
/// refused: what a workspace waits out.
/// </summary>
public static bool IsUnavailable(Exception exception, CancellationToken cancellationToken = default) => exception switch
{
HomeUnavailableException => true,
// A refusal for good, which is an IOException too.
Workspaces.WorkspaceSyncException => false,
ChronosApiException api => Unavailable(api),
UntrustedCertificateException or HttpRequestException or JsonException or ObjectDisposedException => true,
// A timeout of the client's (not the caller's cancellation).
OperationCanceledException => !cancellationToken.IsCancellationRequested,
IOException => true,
_ => false,
};
private static int Page(int limit) => Math.Clamp(limit, 1, MaxPage);
/// <summary>A refusal of the server as this PC's archive gives it, or a server out of reach.</summary>
private static async Task<T> Reach<T>(Func<Task<T>> call, CancellationToken cancellationToken)
{
try
{
return await call().ConfigureAwait(false);
}
catch (ChronosApiException ex) when (Refusal(ex) is { } refusal)
{
throw refusal;
}
catch (Exception ex) when (ex is not ProjectException && IsUnavailable(ex, cancellationToken))
{
throw new HomeUnavailableException(ex is ChronosApiException { Status: HttpStatusCode.Unauthorized }
? $"The sign-in on the server expired: {ex.Message}"
: $"The server cannot be reached: {ex.Message}", ex);
}
}
/// <summary>The project error a refusal stands for (a sequence, project or version the server does not have, a name it refuses); null for any other.</summary>
private static ProjectException? Refusal(ChronosApiException ex) => (ex.Status, ex.Error.Code, ex.Error.Details) switch
{
(HttpStatusCode.NotFound, _, "sequence") => new ProjectException(ProjectError.SequenceNotFound, ex.Message),
(HttpStatusCode.NotFound, _, "project" or "version") => new ProjectException(ProjectError.NotFound, ex.Message),
(HttpStatusCode.BadRequest, ProjectErrors.InvalidName, _) => new ProjectException(ProjectError.InvalidName, ex.Message),
(HttpStatusCode.Conflict, ProjectErrors.NameTaken, _) => new ProjectException(ProjectError.NameTaken, ex.Message),
(HttpStatusCode.Conflict, ProjectErrors.MainCannotBeDeleted, _) => new ProjectException(ProjectError.MainCannotBeDeleted, ex.Message),
(HttpStatusCode.Conflict, ProjectErrors.SequenceEmpty, _) => new ProjectException(ProjectError.SequenceEmpty, ex.Message),
_ => null,
};
/// <summary>
/// An answer that says the server cannot serve the call for now: busy, its archive offline or its sequence's folder
/// moved (503), a gateway or a timeout, the sign-in expired (401), a project file it cannot write now (409
/// <c>folder_in_use</c>), a server without the projects (404 with nothing named: the API's fallback), or a success
/// that is no answer of the API (a portal's or a proxy's page).
/// </summary>
private static bool Unavailable(ChronosApiException ex) =>
ex.IsTransient
|| ex.Status == HttpStatusCode.Unauthorized
|| (int)ex.Status is >= 200 and < 300
|| ex is { Status: HttpStatusCode.Conflict, Error.Code: "folder_in_use" }
|| ex is { Status: HttpStatusCode.NotFound, Error.Details: null or "" };
}
+53 -1
View File
@@ -59,6 +59,17 @@ public sealed class SyncAgent : IAsyncDisposable
private readonly SemaphoreSlim _refreshing = new(1, 1);
private Task _running = Task.CompletedTask;
/// <summary>
/// Whether project changes may have been missed: <see cref="Missed"/> from the moment the event stream was lost,
/// <see cref="Reopened"/> once it is open again (no change is missed from then on), back to <see cref="InStep"/> when a
/// comparison that started after that reached the server and <see cref="ProjectChanged"/> said so.
/// </summary>
private int _projectsMissed;
private const int InStep = 0;
private const int Missed = 1;
private const int Reopened = 2;
private SyncSnapshot? _snapshot;
private Exception? _lastError;
@@ -84,6 +95,13 @@ public sealed class SyncAgent : IAsyncDisposable
/// <summary><see cref="Snapshot"/> or <see cref="LastError"/> changed (any thread).</summary>
public event Action? Changed;
/// <summary>
/// A project of one of the server's sequences changed there (owner review 2, R8: <c>projectChanged</c>, any thread), or,
/// with null, a comparison reached the server again after its event stream was lost, so changes may have been missed:
/// workspace projects whose home is this server read where they stand again.
/// </summary>
public event Action<ProjectChangedEvent?>? ProjectChanged;
/// <summary>Starts the comparison and event loops.</summary>
public void Start()
{
@@ -104,12 +122,16 @@ public sealed class SyncAgent : IAsyncDisposable
await _refreshing.WaitAsync(linked.Token).ConfigureAwait(false);
try
{
// Only a comparison that started once the stream was open again covers every change missed meanwhile: one that
// started before may end while the stream is still down, and a change said then would be missed for good.
var reopened = Volatile.Read(ref _projectsMissed) == Reopened;
var policy = _policy();
var snapshot = await _sync.RefreshAsync(_remote, policy, linked.Token).ConfigureAwait(false);
Volatile.Write(ref _snapshot, snapshot);
Volatile.Write(ref _lastError, null);
if (policy.KeepProxiesOffline && _engine is not null) await QueueProxiesAsync(snapshot, linked.Token).ConfigureAwait(false);
Changed?.Invoke();
if (reopened && Interlocked.CompareExchange(ref _projectsMissed, InStep, Reopened) == Reopened) TellProjects(null);
return snapshot;
}
finally
@@ -169,9 +191,14 @@ public sealed class SyncAgent : IAsyncDisposable
{
try
{
await foreach (var e in _remote.EventsAsync(cancellationToken).ConfigureAwait(false))
await foreach (var e in _remote.EventsAsync(Reconnected, cancellationToken).ConfigureAwait(false))
{
failures = 0;
if (e is ProjectChangedEvent project)
{
TellProjects(project);
continue;
}
if (e is not SequenceChangedEvent changed) continue;
_changed[changed.SequenceId] = 0;
_eventWake.Writer.TryWrite(true);
@@ -185,6 +212,9 @@ public sealed class SyncAgent : IAsyncDisposable
{
Log.Info(LogCategory, $"Event stream of {Server} lost: {ex.Message}");
}
// Project changes said meanwhile are missed: the first comparison that reaches the server once the stream is open
// again says so (Reconnected).
Volatile.Write(ref _projectsMissed, Missed);
try
{
await Task.Delay(Backoff(failures++), cancellationToken).ConfigureAwait(false);
@@ -197,6 +227,28 @@ public sealed class SyncAgent : IAsyncDisposable
}
}
/// <summary>
/// The event stream is open (again): after a loss, a comparison is asked for now, and the one that starts from here says
/// that project changes may have been missed (<see cref="ProjectChanged"/> with null).
/// </summary>
private void Reconnected()
{
if (Interlocked.CompareExchange(ref _projectsMissed, Reopened, Missed) == Missed) RequestRefresh();
}
/// <summary>Tells <see cref="ProjectChanged"/>; what a listener throws is logged, never ends the event loop.</summary>
private void TellProjects(ProjectChangedEvent? change)
{
try
{
ProjectChanged?.Invoke(change);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning(LogCategory, $"A project change of {Server} was not handled", ex);
}
}
/// <summary>Compares the sequences named by events, a short while after the first one arrived.</summary>
private async Task ChangedLoopAsync(CancellationToken cancellationToken)
{
+28
View File
@@ -63,6 +63,28 @@ public interface ISyncRemote : IDisposable
/// <summary>Server events until cancelled or the socket closes.</summary>
IAsyncEnumerable<ServerEvent> EventsAsync(CancellationToken cancellationToken);
/// <summary>
/// <see cref="EventsAsync(CancellationToken)"/>, calling <paramref name="connected"/> once the stream is open, before its
/// first event: from then on no event the server sends is missed. A remote that cannot say calls it when the stream is
/// asked for.
/// </summary>
IAsyncEnumerable<ServerEvent> EventsAsync(Action connected, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(connected);
connected();
return EventsAsync(cancellationToken);
}
/// <summary>
/// Every frame of a sequence as of one frames version, with the photo aliases of its conversions (owner review 2, R8:
/// what a workspace copy of a server project holds; servers with the <c>projects</c> capability). A remote without the
/// call (the screenshots' sample server) throws <see cref="NotSupportedException"/>.
/// </summary>
Task<ProjectFramesDto> GetProjectFramesAsync(Guid sequenceId, CancellationToken cancellationToken) => throw new NotSupportedException();
/// <summary>The sequence's deep-analysis report (<c>analysis.json</c>); null when it was never deep-analysed, or the remote has no such call.</summary>
Task<string?> GetAnalysisReportAsync(Guid sequenceId, CancellationToken cancellationToken) => Task.FromResult<string?>(null);
}
/// <summary>Where sync jobs find their server connection.</summary>
@@ -138,6 +160,12 @@ public sealed class ChronosSyncRemote(ChronosClient client, bool ownsClient) : I
public IAsyncEnumerable<ServerEvent> EventsAsync(CancellationToken cancellationToken) => client.EventsAsync(cancellationToken);
public IAsyncEnumerable<ServerEvent> EventsAsync(Action connected, CancellationToken cancellationToken) => client.EventsAsync(connected, cancellationToken);
public Task<ProjectFramesDto> GetProjectFramesAsync(Guid sequenceId, CancellationToken cancellationToken) => client.GetProjectFramesAsync(sequenceId, cancellationToken);
public Task<string?> GetAnalysisReportAsync(Guid sequenceId, CancellationToken cancellationToken) => client.GetAnalysisReportAsync(sequenceId, cancellationToken);
public void Dispose()
{
if (ownsClient) client.Dispose();
+96 -9
View File
@@ -774,32 +774,54 @@ internal sealed class SyncTransfers(SyncService sync)
var cached = new FileInfo(path) is { Exists: true, Length: > 0 };
if (cached && (cachedKind == ProxyCache.Proxy || !offered.Contains(ProxyCache.Proxy))) return (name, cachedKind ?? ProxyCache.Thumb);
var part = path + ".part";
foreach (var kind in offered)
// The cached file is as good as the server's thumbnail.
var kind = await DownloadFirstAsync(remote, frameId, offered.TakeWhile(k => !(cached && k == ProxyCache.Thumb)), part, null, cancellationToken)
.ConfigureAwait(false);
if (kind is not null)
{
File.Move(part, path, overwrite: true);
return (name, kind);
}
return cached ? (name, ProxyCache.Thumb) : null;
}
/// <summary>
/// Downloads the first of <paramref name="kinds"/> a frame has on the server (a 404 tries the next) into a fresh
/// <paramref name="part"/> file, written through <paramref name="through"/> when given (a hash of what arrives, which
/// leaves the file open) and flushed to the disk when <paramref name="durable"/>; the kind it got, or null when the server
/// has none of them, no part file left then. The proxy cache and the workspace copy of a server project (owner review 2,
/// R8) download alike.
/// </summary>
internal static async Task<string?> DownloadFirstAsync(ISyncRemote remote, Guid frameId, IEnumerable<string> kinds, string part, Func<Stream, Stream>? through,
CancellationToken cancellationToken, bool durable = false)
{
foreach (var kind in kinds)
{
// The cached file is as good as the server's thumbnail.
if (cached && kind == ProxyCache.Thumb) break;
try
{
await using (var file = new FileStream(part, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
await remote.DownloadFrameAsync(frameId, kind, file, cancellationToken).ConfigureAwait(false);
File.Move(part, path, overwrite: true);
return (name, kind);
{
await remote.DownloadFrameAsync(frameId, kind, through?.Invoke(file) ?? file, cancellationToken).ConfigureAwait(false);
if (durable) file.Flush(flushToDisk: true);
}
return kind;
}
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
File.Delete(part);
}
}
return cached ? (name, ProxyCache.Thumb) : null;
return null;
}
/// <summary>
/// A frame missing or damaged on the server: its manifest never asks for its proxy and a pass makes none of a missing
/// one, so the thumbnail (or the lack of a file) that stands in for it does not keep the cache stale.
/// </summary>
private static bool NeverProxied(FrameDto frame) => ((FrameFlags)frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0;
internal static bool NeverProxied(FrameDto frame) => ((FrameFlags)frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0;
private static string[] Kinds(ManifestFrame frame) => (frame.HasProxy, frame.HasThumb) switch
/// <summary>The kinds of a frame's assets the server offers, the proxy before the thumbnail that stands in while it has none.</summary>
internal static string[] Kinds(ManifestFrame frame) => (frame.HasProxy, frame.HasThumb) switch
{
(true, true) => [ProxyCache.Proxy, ProxyCache.Thumb],
(true, false) => [ProxyCache.Proxy],
@@ -867,3 +889,68 @@ internal sealed class SyncTransfers(SyncService sync)
public ValueTask ReportAsync() => context.ReportAsync(done, total);
}
}
/// <summary>
/// A write-only stream that hashes (SHA-256) what passes through it into <paramref name="inner"/>, which it leaves open: the
/// hash of a download as it arrived, to check the file it was written to against (owner review 2, R8). It cannot seek,
/// so a download through it always starts from the beginning.
/// </summary>
internal sealed class HashingStream(Stream inner) : Stream
{
private readonly System.Security.Cryptography.IncrementalHash _hash = System.Security.Cryptography.IncrementalHash.CreateHash(
System.Security.Cryptography.HashAlgorithmName.SHA256);
private long _written;
/// <summary>The bytes written through.</summary>
public long Written => _written;
/// <summary>The lower-case hex SHA-256 of what was written through (once; it resets the hash).</summary>
public string Sha256() => Convert.ToHexStringLower(_hash.GetHashAndReset());
public override bool CanRead => false;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => throw new NotSupportedException();
public override long Position
{
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
public override void Flush() => inner.Flush();
public override Task FlushAsync(CancellationToken cancellationToken) => inner.FlushAsync(cancellationToken);
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count));
public override void Write(ReadOnlySpan<byte> buffer)
{
_hash.AppendData(buffer);
_written += buffer.Length;
inner.Write(buffer);
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
_hash.AppendData(buffer.Span);
_written += buffer.Length;
return inner.WriteAsync(buffer, cancellationToken);
}
protected override void Dispose(bool disposing)
{
if (disposing) _hash.Dispose();
base.Dispose(disposing);
}
}
@@ -1,4 +1,5 @@
using System.Globalization;
using System.Net;
using System.Security.Cryptography;
using System.Text.Json;
using Chronos.Core.Archiving;
@@ -12,6 +13,9 @@ using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Protocol.Client;
using SequenceManifest = Chronos.Protocol.SequenceManifest;
namespace Chronos.Data.Workspaces;
@@ -31,10 +35,28 @@ public static class WorkspaceJobs
}
/// <summary>
/// The handlers of the workspace's jobs for a desktop's engine (never a server's: the job writes into a folder its
/// parameters name).
/// <see cref="JobKind.WorkspaceCopy"/> of a project whose home is a server (phase 5b): the media of workspace project
/// <paramref name="projectId"/> (checked out first) downloaded from sequence <paramref name="sequenceId"/> of
/// <paramref name="server"/> (<see cref="SyncService.ServerKey"/>), into the workspace alone. The job's target is the
/// server's sequence, as for a sync download.
/// </summary>
public static IReadOnlyList<IJobHandler> CreateHandlers(ChronosDatabase db, ArchiveService archives) => [new WorkspaceCopyJobHandler(db, archives)];
public static ArchiveJobRequest CopyFromServer(Guid sequenceId, string title, string server, string workspaceRoot, Guid projectId, string media = BundleMedia.Proxies)
{
ArgumentException.ThrowIfNullOrWhiteSpace(server);
ArgumentException.ThrowIfNullOrWhiteSpace(workspaceRoot);
return new ArchiveJobRequest(JobKind.WorkspaceCopy, [sequenceId], title,
JsonSerializer.Serialize(new WorkspaceCopyParameters(workspaceRoot, projectId, media, server), WorkspaceJson.Default.WorkspaceCopyParameters), JobPriority.User);
}
/// <summary>
/// The handlers of the workspace's jobs for a desktop's engine (never a server's: the job writes into a folder its
/// parameters name); copies from a server fail without a connection to it.
/// </summary>
public static IReadOnlyList<IJobHandler> CreateHandlers(ChronosDatabase db, ArchiveService archives) => CreateHandlers(db, archives, null);
/// <param name="servers">The connection a copy from a server's sequence downloads through (the desktop's signed-in session).</param>
public static IReadOnlyList<IJobHandler> CreateHandlers(ChronosDatabase db, ArchiveService archives, ISyncConnector? servers) =>
[new WorkspaceCopyJobHandler(db, archives, servers)];
/// <summary>
/// What a first copy of a sequence's proxies writes into a workspace, as the copy reckons it before it starts (the
@@ -70,14 +92,32 @@ public static class WorkspaceJobs
/// project goes on with them (<see cref="RemovePartialMediaAsync"/>); one cancelled while paused or failed, which no handler
/// runs, has them removed the same way (<see cref="CancelledAsync"/>).
/// Originals come in phase 5c: asked for, the job fails saying so.
/// A project whose home is a server (phase 5b, <see cref="WorkspaceJobs.CopyFromServer"/>) has its media downloaded from
/// the server through the desktop's session (<see cref="ISyncConnector"/>), never through this PC's archive: the frames as
/// of one frames version with the aliases of the server's conversions (<c>GET …/projects/frames</c>), each frame's proxy as
/// the proxy cache fetches it (<see cref="SyncTransfers.DownloadFirstAsync"/>: the proxy, else the thumbnail standing in
/// while the server has none, recorded as such and replaced by a later copy once the server has the proxy), hashed as it
/// arrives and checked against the file written, four at a time; then the server's deep report. A file the editor's media
/// or this run hold of the same photo is hashed again and kept; the editor's file is never written over, as above. The
/// space, the passes, the checkpoint and a cancelled first copy go as for a copy from this PC's archive (the server's
/// folder of the sequence in the checkpoint). Like the sync's downloads it is not held on a metered connection.
/// </summary>
internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService archives) : ICancelledJobHandler
internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService archives, ISyncConnector? servers = null) : ICancelledJobHandler
{
private const int PageSize = 1000;
private const int Passes = 3;
/// <summary>Frames downloaded at once from a server (as the sync's downloads).</summary>
private const int Downloads = 4;
/// <summary>Frames downloaded between two looks at the checkpoint clock.</summary>
private const int DownloadBatch = 32;
private static readonly TimeSpan LockWait = TimeSpan.FromMinutes(2);
private static readonly TimeSpan CheckpointEvery = TimeSpan.FromSeconds(5);
/// <summary>Beside a server's thumbnail downloaded for a frame until the copy commits: what it is, should the run stop first.</summary>
internal const string StandInSuffix = ".thumb";
/// <summary>Bytes left free on the workspace's drive besides the copy, as a download keeps (<see cref="SyncTransfers"/>).</summary>
internal const long SpaceReserve = 512L << 20;
@@ -97,6 +137,11 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
var parameters = Parameters(context.Job);
if (parameters.Media == BundleMedia.Originals) throw new NotSupportedException(Loc.L("Errors.Workspace.OriginalsLater"));
if (parameters.Media != BundleMedia.Proxies) throw new InvalidDataException(Loc.L("Errors.Workspace.Parameters"));
if (parameters.Server is { Length: > 0 } server)
{
await RunFromServerAsync(context, parameters, server).ConfigureAwait(false);
return;
}
if (context.Job.TargetIds is not [var sequenceId] || await db.Sequences.GetAsync(sequenceId, ct).ConfigureAwait(false) is not { } sequence
|| await db.Archives.GetAsync(sequence.ArchiveId, ct).ConfigureAwait(false) is not { } archive)
throw new InvalidOperationException(Loc.L("Archive.Log.SequenceMissing", context.Job.TargetIds.FirstOrDefault()));
@@ -336,7 +381,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
// The working state is the editor's meanwhile: it is held only while the media index and the positions move.
using (await project.LockAsync(LockWait, ct).ConfigureAwait(false))
{
Commit(project, project.ReadBundle(), media, row);
Commit(project, project.ReadBundle(), media, row.Folder, row.DisplayTitle);
RemoveStale(project, media);
}
context.Log(Loc.L("Archive.Log.WorkspaceCopied", row.DisplayTitle, tally.Copied, tally.Made, tally.Kept, tally.Missing));
@@ -345,6 +390,293 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
}
}
/// <summary>
/// The copy of a project whose home is a server (see the class remarks): its frames and their files downloaded into the
/// workspace, then the media index and the working state moved onto them as for a copy from this PC's archive.
/// </summary>
private async Task RunFromServerAsync(JobContext context, WorkspaceCopyParameters parameters, string server)
{
var ct = context.Cancellation;
if (context.Job.TargetIds is not [var sequenceId]) throw new InvalidDataException(Loc.L("Errors.Workspace.Parameters"));
// Asked before the store is opened, which makes its folder (as for a copy from this PC's archive).
if (await InsideALibraryAsync(parameters.WorkspaceRoot, ct).ConfigureAwait(false)) throw new InvalidOperationException(Loc.L("Errors.Workspace.InsideLibrary"));
var store = new WorkspaceStore(parameters.WorkspaceRoot);
var project = store.Find(parameters.ProjectId) ?? throw new InvalidOperationException(Loc.L("Errors.Workspace.NotCheckedOut"));
if (project.ReadBundle().Workspace is not { Home: { Kind: BundleHome.ServerKind } home } || home.SequenceId != sequenceId
|| !string.Equals(home.Server, server, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException(Loc.L("Errors.Workspace.OtherHome"));
try
{
using (WritingMedia(project))
{
using var remote = (servers is null ? null : await servers.ConnectAsync(server, ct).ConfigureAwait(false))
?? throw new InvalidOperationException(Loc.L("Errors.Sync.NotConnected"));
await DownloadAsync(context, project, remote, sequenceId, parameters, ct).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// Stopped writing: what a first copy the user cancelled wrote goes (a pause or a shutdown resumes it).
await RemovePartialMediaAsync(context.Job, project).ConfigureAwait(false);
throw;
}
}
private async Task DownloadAsync(JobContext context, WorkspaceProject project, ISyncRemote remote, Guid sequenceId, WorkspaceCopyParameters parameters,
CancellationToken ct)
{
var (copied, checkpointVersion, checkpointFolder) = Parse(context.Checkpoint);
// What this run downloaded, pass after pass: kept where a frame still shows the same photo.
var fetched = new Dictionary<Guid, WorkspaceFrame>();
for (var pass = 1; ; pass++)
{
var (sequence, frames, assets, aliases, framesVersion, spec) = await ServerFramesAsync(remote, sequenceId, ct).ConfigureAwait(false);
var folder = sequence.Folder ?? string.Empty;
if ((checkpointVersion is { } version && version != framesVersion) || (checkpointFolder is { } read && read != folder)) copied = 0;
var total = (long)frames.Count;
var tally = new Tally();
var entries = new WorkspaceFrame[frames.Count];
// The media the editor reads until this copy commits: their files stay until then (RemoveStale).
var current = TryReadMedia(project)?.Frames.Where(f => f.File is not null).ToDictionary(f => f.Id) ?? [];
Directory.CreateDirectory(project.ProxiesDirectory);
// The workspace is on this PC's own drive: the copy never fills it (the server's files estimated at its proxy size).
var remaining = RemainingDownloads(project, frames, assets, spec);
EnsureSpace(parameters.WorkspaceRoot, remaining[0]);
var clock = System.Diagnostics.Stopwatch.StartNew();
var options = new ParallelOptions { MaxDegreeOfParallelism = Downloads, CancellationToken = ct };
for (var start = 0; start < frames.Count; start += DownloadBatch)
{
var end = Math.Min(frames.Count, start + DownloadBatch);
var done = copied;
await Parallel.ForEachAsync(Enumerable.Range(start, end - start), options, async (i, token) =>
entries[i] = await DownloadAsync(remote, project, frames[i], assets.GetValueOrDefault(frames[i].Id), i < done, current.GetValueOrDefault(frames[i].Id),
fetched.GetValueOrDefault(frames[i].Id), tally, token).ConfigureAwait(false)).ConfigureAwait(false);
if (clock.Elapsed >= CheckpointEvery || end == frames.Count)
{
await context.CheckpointAsync(Checkpoint(Stage.Copy, end, framesVersion, folder), end, total).ConfigureAwait(false);
// Another program may take the space meanwhile.
EnsureSpace(parameters.WorkspaceRoot, remaining[end]);
clock.Restart();
}
else
{
await context.ReportAsync(end, total).ConfigureAwait(false);
}
}
foreach (var entry in entries.Where(e => e.File is not null)) fetched[entry.Id] = entry;
var analysis = await CopyServerAnalysisAsync(remote, sequenceId, project, frames.Count, ct).ConfigureAwait(false);
var after = await remote.GetSequenceAsync(sequenceId, ct).ConfigureAwait(false);
if (after.FramesVersion != framesVersion && pass < Passes)
{
// The files read may be of other frames now: the next pass reads the frames again, keeping what still shows them,
// and so does a run resumed after a crash in it (the checkpoint stored says so).
context.Log(Loc.L("Archive.Log.WorkspaceFramesChanged", sequence.DisplayTitle));
await context.CheckpointAsync(Checkpoint(Stage.Copy, 0, after.FramesVersion, after.Folder ?? string.Empty), 0, total).ConfigureAwait(false);
(copied, checkpointVersion, checkpointFolder) = (0, null, null);
continue;
}
// Frames still arriving are copied as they were read (Update media takes the rest).
var media = new WorkspaceMedia(WorkspaceMedia.FormatName, WorkspaceMedia.CurrentFormatVersion, BundleMedia.Proxies, sequenceId, framesVersion, entries,
DateTimeOffset.UtcNow, analysis, aliases.Count > 0 ? aliases : null);
// The working state is the editor's meanwhile: it is held only while the media index and the positions move.
using (await project.LockAsync(LockWait, ct).ConfigureAwait(false))
{
Commit(project, project.ReadBundle(), media, folder, sequence.DisplayTitle);
RemoveStale(project, media);
}
context.Log(Loc.L("Archive.Log.WorkspaceDownloaded", sequence.DisplayTitle, tally.Copied, tally.Made, tally.Kept, tally.Missing));
await context.CheckpointAsync(Checkpoint(Stage.Done, frames.Count, framesVersion, folder), total, total).ConfigureAwait(false);
return;
}
}
/// <summary>
/// A server sequence's frames in index order as of one frames version, the assets the server holds of each, the links
/// of its conversions, that frames version and the server's proxy size: the frames read twice around the manifest until
/// both are of the same one.
/// </summary>
private static async Task<(SequenceDto Sequence, List<Frame> Frames, Dictionary<Guid, ManifestFrame> Assets, IReadOnlyList<PhotoAlias> Aliases, int FramesVersion,
ProxySpec? Spec)> ServerFramesAsync(ISyncRemote remote, Guid sequenceId, CancellationToken cancellationToken)
{
for (var attempt = 1; ; attempt++)
{
ProjectFramesDto frames;
SequenceManifest manifest;
SequenceDto sequence;
try
{
sequence = await remote.GetSequenceAsync(sequenceId, cancellationToken).ConfigureAwait(false);
frames = await remote.GetProjectFramesAsync(sequenceId, cancellationToken).ConfigureAwait(false);
manifest = await remote.GetManifestAsync(sequenceId, cancellationToken).ConfigureAwait(false);
}
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
// The sequence is gone, or the server keeps no projects (its API knows no such call).
throw new InvalidOperationException(ex.Error.Details == "sequence" ? Loc.L("Archive.Log.SequenceMissing", sequenceId) : Loc.L("Errors.Workspace.NoProjects"), ex);
}
if (manifest.FramesVersion == frames.FramesVersion || attempt == Passes)
{
var home = ProjectWire.ToHomeFrames(frames);
var aliases = (frames.Aliases ?? []).Where(a => !string.IsNullOrEmpty(a.Sha256) && !string.IsNullOrEmpty(a.Replacement))
.Select(a => new PhotoAlias(a.Sha256, a.Replacement!)).ToList();
return (sequence, [.. home.Frames], manifest.Frames.ToDictionary(f => f.Id), aliases, frames.FramesVersion, manifest.Proxies);
}
}
}
/// <summary>
/// A frame's file from the server: kept when this run downloaded it before it stopped or in an earlier pass, or the
/// editor's media hold one of the same photo that is no thumbnail standing in for a proxy the server has now (hashed
/// again: a file that no longer matches is fetched anew); else its proxy, or the thumbnail while the server has none,
/// hashed as it arrives and checked against the file written (downloaded once more when they differ, then refused);
/// none for a frame without either, or missing or damaged on the server. The editor's file (<paramref name="current"/>)
/// is never written over: other bytes for it go under a name of their own, as for a copy from this PC's archive.
/// </summary>
private static async Task<WorkspaceFrame> DownloadAsync(ISyncRemote remote, WorkspaceProject project, Frame frame, ManifestFrame? asset, bool done,
WorkspaceFrame? current, WorkspaceFrame? fetched, Tally tally, CancellationToken cancellationToken)
{
var name = WorkspaceProject.ProxyName(frame.Id);
var target = project.MediaFile(name);
var listed = current is not null && string.Equals(current.File, name, StringComparison.OrdinalIgnoreCase);
IReadOnlyList<string> offered = asset is null || (frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0 ? [] : SyncTransfers.Kinds(asset);
if (done && File.Exists(target))
{
var keptSha = await ContentHash.Sha256Async(target, cancellationToken: cancellationToken).ConfigureAwait(false);
// The editor's file of another photo of the frame (a conversion since) was left by an earlier copy, not this run.
// A run stopped before it recorded the file's kind left a marker beside a thumbnail it took for a missing proxy.
var keptKind = KindOf(fetched, keptSha) ?? KindOf(current, keptSha)
?? (File.Exists(StandInMarker(target)) ? ProxyCache.Thumb : offered.FirstOrDefault() ?? ProxyCache.Proxy);
if ((!listed || keptSha != current!.FileSha256 || SamePhoto(current, frame)) && !(keptKind == ProxyCache.Thumb && offered.Contains(ProxyCache.Proxy)))
{
tally.Keep();
return WorkspaceFrame.Of(frame, name, keptSha, new FileInfo(target).Length, keptKind);
}
}
// What this run downloaded in an earlier pass, then the editor's file of the same photo, unless a thumbnail stands in
// there for a proxy the server has now.
foreach (var held in new[] { fetched, current })
{
if (held is not { File: { } file, FileSha256: { } heldSha } || !SamePhoto(held, frame) || (held.IsStandIn && offered.Contains(ProxyCache.Proxy))) continue;
var path = project.MediaFile(file);
if (!File.Exists(path)
|| !string.Equals(await ContentHash.Sha256Async(path, cancellationToken: cancellationToken).ConfigureAwait(false), heldSha, StringComparison.OrdinalIgnoreCase))
continue;
tally.Keep();
return WorkspaceFrame.Of(frame, file, heldSha.ToLowerInvariant(), new FileInfo(path).Length, held.FileKind ?? ProxyCache.Proxy);
}
if (offered.Count == 0)
{
// A file an earlier copy left for the frame is never kept as its photo: a regenerable copy, it goes, unless the
// editor's media name it (it goes once this copy commits).
if (!listed && File.Exists(target)) TryDelete(target);
tally.Miss();
return WorkspaceFrame.Of(frame, null, null, 0);
}
var part = target + ".part";
for (var attempt = 1; ; attempt++)
{
HashingStream? hashing = null;
string? kind;
string received;
long bytes;
try
{
kind = await SyncTransfers.DownloadFirstAsync(remote, frame.Id, offered, part, file =>
{
hashing?.Dispose();
return hashing = new HashingStream(file);
}, cancellationToken, durable: true).ConfigureAwait(false);
(received, bytes) = hashing is null ? (string.Empty, 0L) : (hashing.Sha256(), hashing.Written);
}
finally
{
hashing?.Dispose();
}
if (kind is null || bytes == 0)
{
if (File.Exists(part)) File.Delete(part);
if (!listed && File.Exists(target)) TryDelete(target);
tally.Miss();
return WorkspaceFrame.Of(frame, null, null, 0);
}
// Other bytes for the file the editor's media name: under a name of their own, never over the editor's file.
var (file, path) = (name, target);
if (listed && current!.FileSha256 is { } editors && !string.Equals(editors, received, StringComparison.OrdinalIgnoreCase)
&& Holds(target, editors.ToLowerInvariant()))
{
file = WorkspaceProject.ProxyName(frame.Id, received);
path = project.MediaFile(file);
}
// The kind is known on disk before the file is: a run stopped after the move resumes with it.
if (kind == ProxyCache.Thumb) File.WriteAllBytes(StandInMarker(path), []);
else if (File.Exists(StandInMarker(path))) File.Delete(StandInMarker(path));
File.Move(part, path, overwrite: true);
if (await ContentHash.Sha256Async(path, cancellationToken: cancellationToken).ConfigureAwait(false) == received)
{
if (kind == ProxyCache.Proxy) tally.Copy();
else tally.Make();
return WorkspaceFrame.Of(frame, file, received, bytes, kind);
}
if (attempt == 2) throw new IOException(Loc.L("Errors.Workspace.CopyMismatch", path));
}
static string StandInMarker(string file) => file + StandInSuffix;
static string? KindOf(WorkspaceFrame? entry, string sha) =>
entry is { FileSha256: { } held } && string.Equals(held, sha, StringComparison.OrdinalIgnoreCase) ? entry.FileKind ?? ProxyCache.Proxy : null;
}
/// <summary>
/// The bytes a copy from a server still writes from each frame on (index <c>i</c>: frames <c>i</c> to the last; one more
/// entry, 0): nothing for a frame the workspace holds a file of already or the server has neither proxy nor thumbnail of,
/// else an estimate at the server's proxy size (its manifest gives no file's size).
/// </summary>
private static long[] RemainingDownloads(WorkspaceProject project, List<Frame> frames, Dictionary<Guid, ManifestFrame> assets, ProxySpec? spec)
{
var held = Directory.Exists(project.ProxiesDirectory) ? HeldFrames(Directory.EnumerateFiles(project.ProxiesDirectory, "*.jpg")) : [];
var policy = spec is null ? new ProxyPolicy() : new ProxyPolicy { LongEdge = spec.LongEdge, Quality = spec.Quality };
var remaining = new long[frames.Count + 1];
for (var i = frames.Count - 1; i >= 0; i--)
{
var frame = frames[i];
var bytes = held.Contains(frame.Id) || assets.GetValueOrDefault(frame.Id) is not { } asset || SyncTransfers.Kinds(asset).Length == 0 ? 0 : Estimate(frame, policy);
remaining[i] = remaining[i + 1] + bytes;
}
return remaining;
}
/// <summary>The server's deep report into the media folder when it describes these frames; its SHA-256, or null without one.</summary>
private static async Task<string?> CopyServerAnalysisAsync(ISyncRemote remote, Guid sequenceId, WorkspaceProject project, int frameCount,
CancellationToken cancellationToken)
{
string? json;
try
{
json = await remote.GetAnalysisReportAsync(sequenceId, cancellationToken).ConfigureAwait(false);
}
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
json = null;
}
try
{
if (json is null || Core.Analysis.Deep.DeepAnalysisReport.FromJson(json).FrameCount != frameCount)
{
if (File.Exists(project.AnalysisPath)) File.Delete(project.AnalysisPath);
return null;
}
}
catch (Exception ex) when (ex is InvalidDataException or JsonException)
{
Log.Warning("workspace", $"The deep report of server sequence {sequenceId} cannot be read; the workspace takes none", ex);
return null;
}
var bytes = System.Text.Encoding.UTF8.GetBytes(json);
var sha = Sha(bytes);
WriteVerified(project.AnalysisPath, bytes, sha);
return sha;
}
/// <summary>Whether <paramref name="folder"/> is an archive's root of this index or lies inside one.</summary>
private async Task<bool> InsideALibraryAsync(string folder, CancellationToken cancellationToken)
{
@@ -397,7 +729,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
// The editor's file of another photo of the frame (a conversion since) was left by an earlier copy, not this run.
if (!listed || keptSha != current!.FileSha256 || SamePhoto(current, frame))
{
tally.Kept++;
tally.Keep();
return WorkspaceFrame.Of(frame, name, keptSha, kept.Length);
}
}
@@ -424,7 +756,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
// A file an earlier copy left for the frame (of other frames, or another folder's) is never kept as its photo by a
// resumed run: a regenerable copy, it goes, unless the editor's media name it (it goes once this copy commits).
if (!listed && File.Exists(target)) TryDelete(target);
tally.Missing++;
tally.Miss();
return WorkspaceFrame.Of(frame, null, null, 0);
}
var sha = Sha(bytes);
@@ -432,12 +764,12 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
if (current?.File is { } held && !string.Equals(held, name, StringComparison.OrdinalIgnoreCase)
&& string.Equals(current.FileSha256, sha, StringComparison.OrdinalIgnoreCase) && Holds(project.MediaFile(held), sha))
{
tally.Kept++;
tally.Keep();
return WorkspaceFrame.Of(frame, held, sha, bytes.Length);
}
if (Holds(target, sha))
{
tally.Kept++;
tally.Keep();
return WorkspaceFrame.Of(frame, name, sha, bytes.Length);
}
// Other bytes for the file the editor's media name (a conversion since): written under a name of their own, never over
@@ -450,13 +782,13 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
target = project.MediaFile(name);
if (Holds(target, sha))
{
tally.Kept++;
tally.Keep();
return WorkspaceFrame.Of(frame, name, sha, bytes.Length);
}
}
WriteVerified(target, bytes, sha);
if (made) tally.Made++;
else tally.Copied++;
if (made) tally.Make();
else tally.Copy();
return WorkspaceFrame.Of(frame, name, sha, bytes.Length);
}
@@ -504,11 +836,11 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
/// as the photo they hold for it, so one whose file a conversion replaced (the same frame, another SHA-256) keeps its
/// positions, as the archive's own settings do (<see cref="ProjectPositions"/>).
/// </summary>
private static void Commit(WorkspaceProject project, ProjectBundle bundle, WorkspaceMedia media, Sequence row)
private static void Commit(WorkspaceProject project, ProjectBundle bundle, WorkspaceMedia media, string folder, string title)
{
var old = TryReadMedia(project);
var workspace = bundle.Workspace! with { Media = new BundleMedia(BundleMedia.Proxies, media.FramesVersion) };
var sequence = bundle.Sequence with { Folder = row.Folder, Title = row.DisplayTitle, Frames = media.Frames.Count };
var sequence = bundle.Sequence with { Folder = folder, Title = title, Frames = media.Frames.Count };
var working = bundle.Project;
// Without the media index the positions were made against, they are taken as naming these frames.
if (!working.IsNewerFormat && old is not null)
@@ -534,14 +866,19 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
held.Size == frame.Size && held.CapturedAt == frame.CapturedAt
&& (string.IsNullOrEmpty(held.Sha256) || string.IsNullOrEmpty(frame.Sha256) || string.Equals(held.Sha256, frame.Sha256, StringComparison.OrdinalIgnoreCase));
/// <summary>Proxies of frames the sequence no longer has: regenerable copies, removed so the media folder holds the frames listed.</summary>
/// <summary>
/// Proxies of frames the sequence no longer has, and downloads a stopped copy from a server left half done: regenerable
/// copies, removed so the media folder holds the frames listed.
/// </summary>
private static void RemoveStale(WorkspaceProject project, WorkspaceMedia media)
{
var listed = media.Frames.Where(f => f.File is not null).Select(f => Path.GetFileName(f.File!)).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var file in Directory.EnumerateFiles(project.ProxiesDirectory, "*.jpg"))
foreach (var file in Directory.EnumerateFiles(project.ProxiesDirectory, "*.jpg").Concat(Directory.EnumerateFiles(project.ProxiesDirectory, "*.part")))
{
if (!listed.Contains(Path.GetFileName(file))) TryDelete(file);
}
// The media committed record each file's kind: the markers of a run are done with.
foreach (var marker in Directory.EnumerateFiles(project.ProxiesDirectory, "*" + StandInSuffix)) TryDelete(marker);
}
private static void TryDelete(string file)
@@ -718,11 +1055,30 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
return (next, version, parts.Length == 4 ? parts[3] : null);
}
/// <summary>What a copy did with each frame, counted from the workers that download them at once.</summary>
private sealed class Tally
{
public int Copied { get; set; }
public int Made { get; set; }
public int Kept { get; set; }
public int Missing { get; set; }
private int _copied;
private int _made;
private int _kept;
private int _missing;
/// <summary>Proxies copied (from the archive) or downloaded (from a server).</summary>
public int Copied => Volatile.Read(ref _copied);
/// <summary>Proxies made from the originals (from the archive), or thumbnails standing in for them (from a server).</summary>
public int Made => Volatile.Read(ref _made);
public int Kept => Volatile.Read(ref _kept);
public int Missing => Volatile.Read(ref _missing);
public void Copy() => Interlocked.Increment(ref _copied);
public void Make() => Interlocked.Increment(ref _made);
public void Keep() => Interlocked.Increment(ref _kept);
public void Miss() => Interlocked.Increment(ref _missing);
}
}
+13 -4
View File
@@ -13,6 +13,10 @@ namespace Chronos.Data.Workspaces;
/// editor read) and the file the workspace holds for it, with its SHA-256 and size as copied.
/// </summary>
/// <param name="File">The file relative to the media folder ("proxies/&lt;frame id&gt;.jpg"); null when the workspace holds none.</param>
/// <param name="FileKind">
/// What the file is when a server sent it (phase 5b): <c>proxy</c>, or <c>thumb</c>, a thumbnail standing in while the server
/// had no proxy of the frame, which a later copy replaces once it has one; null for a proxy (copies from this PC's archive).
/// </param>
public sealed record WorkspaceFrame(
Guid Id,
int Index,
@@ -41,18 +45,23 @@ public sealed record WorkspaceFrame(
FrameFlags Flags,
string? File,
string? FileSha256,
long FileBytes)
long FileBytes,
string? FileKind = null)
{
/// <summary>The record of a home's frame, with the file the workspace holds for it.</summary>
public static WorkspaceFrame Of(Frame frame, string? file, string? fileSha256, long fileBytes)
/// <summary>The record of a home's frame, with the file the workspace holds for it (<paramref name="fileKind"/>: what a server sent).</summary>
public static WorkspaceFrame Of(Frame frame, string? file, string? fileSha256, long fileBytes, string? fileKind = null)
{
ArgumentNullException.ThrowIfNull(frame);
return new WorkspaceFrame(frame.Id, frame.Index, frame.FileName, frame.OriginalFileName, frame.Size, frame.Sha256, frame.CapturedAt, frame.UtcOffsetMinutes,
frame.TimestampSource, frame.ExposureTime, frame.FNumber, frame.Iso, frame.FocalLength, frame.ExposureBias, frame.WhiteBalance, frame.Orientation,
frame.Width, frame.Height, frame.Format, frame.PreviewWidth, frame.PreviewHeight, frame.MeanLogLuminance, frame.ClipLow, frame.ClipHigh, frame.Flags,
file, fileSha256, fileBytes);
file, fileSha256, fileBytes, fileKind);
}
/// <summary>A thumbnail stands in for the frame's proxy (a server had none when it was copied).</summary>
[JsonIgnore]
public bool IsStandIn => FileKind == Sync.ProxyCache.Thumb;
/// <summary>The frame as the processing engine reads it; flagged missing while the workspace holds no file for it.</summary>
public Frame ToFrame(Guid sequenceId) => new()
{
@@ -93,7 +93,8 @@ public sealed record WorkspaceConflict(Guid TheirsVersionId, int TheirsNumber, G
/// Parameters of a <see cref="JobKind.WorkspaceCopy"/> job: target = the home's sequence; the workspace folder, the
/// project whose media to copy and what to copy (<see cref="BundleMedia.Proxies"/>; originals in phase 5c).
/// </summary>
public sealed record WorkspaceCopyParameters(string WorkspaceRoot, Guid ProjectId, string Media);
/// <param name="Server">The server the home's sequence is on (<see cref="SyncService.ServerKey"/>, phase 5b); null for a sequence of this PC's archive.</param>
public sealed record WorkspaceCopyParameters(string WorkspaceRoot, Guid ProjectId, string Media, string? Server = null);
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
UseStringEnumConverter = true, WriteIndented = true)]
+42 -1
View File
@@ -50,10 +50,11 @@ public enum WorkspaceState
/// <summary>
/// A workspace project's state (owner review 2, R8): the leading <see cref="State"/> and every fact behind it. Without a
/// home to ask, <see cref="Behind"/> is 0 and <see cref="Offline"/> false.
/// home to ask, <see cref="Behind"/> is 0 and <see cref="Offline"/> and <see cref="Gone"/> false.
/// </summary>
/// <param name="Base">The home's version the project was last in step with.</param>
/// <param name="HomeHead">The home's newest version, when it was asked.</param>
/// <param name="Gone">The home was asked and no longer has the project (<see cref="WorkspaceState.Gone"/>).</param>
public sealed record WorkspaceStatus(WorkspaceState State, bool Modified, int Ahead, int Behind, bool Offline, bool MediaRemoved, bool ReadOnly,
WorkspaceConflict? Conflict, BundleBase? Base, ProjectVersion? HomeHead)
{
@@ -369,10 +370,50 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), [], pulled);
}
if (project.ReadSync().Conflict is null) PruneReplaced(project);
await FollowNameLockedAsync(project, home, cancellationToken).ConfigureAwait(false);
return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), [], pulled);
}
}
/// <summary>
/// The project's name (and whether it is Main) as its home has them now, written to the copy here: a rename made at the
/// home reaches the workspace. True when the copy's name changed; false when it already matched, or the home could not
/// say (unreachable, or no longer listing the project): the next pull or status tells those.
/// </summary>
public async Task<bool> FollowNameAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(home);
var project = Existing(projectId);
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
return await FollowNameLockedAsync(project, home, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// <see cref="FollowNameAsync"/> under the project's lock. It runs after a pull that succeeded, so it never fails: whatever
/// the home or the copy answers (unreachable, a refusal such as a 403, a file in use) is logged and the name is followed
/// next time; only a cancellation is passed on.
/// </summary>
private static async Task<bool> FollowNameLockedAsync(WorkspaceProject project, IProjectHome home, CancellationToken cancellationToken)
{
try
{
var listed = (await home.ListAsync(cancellationToken).ConfigureAwait(false)).FirstOrDefault(p => p.Id == project.ProjectId);
var bundle = project.ReadBundle();
if (listed is null || bundle.Workspace is not { } workspace || (workspace.Name == listed.Name && workspace.IsMain == listed.IsMain)) return false;
project.WriteBundle(bundle with { Workspace = workspace with { Name = listed.Name, IsMain = listed.IsMain } });
return true;
}
catch (Exception ex) when (ex is HomeUnavailableException or ProjectException)
{
return false;
}
catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
{
Log.Warning("workspace", $"The name of project {project.ProjectId} could not be followed from its home; tried again at the next pull", ex);
return false;
}
}
/// <summary>
/// Settles the conflict a pull or push stopped at, as the user was shown it (<paramref name="shown"/>, else the one
/// recorded). <see cref="ConflictChoice.KeepMine"/> keeps this workspace's values (but for the members in
+122 -1
View File
@@ -472,16 +472,133 @@ public sealed class ChronosClient : IDisposable
public Task ReportNodeFailureAsync(Guid nodeId, Guid jobId, string error, CancellationToken ct = default) =>
SendAsync(HttpMethod.Post, $"api/v1/nodes/{nodeId}/jobs/{jobId}/failed", new NodeJobFailure(error), ProtocolJson.Default.NodeJobFailure, ct);
// ---------------- Projects (owner review 2, R8; servers with the "projects" capability) ----------------
/// <summary>The live projects of a server sequence, Main first (made from the sequence's settings the first time they are read).</summary>
public Task<List<ProjectDto>> ListProjectsAsync(Guid sequenceId, CancellationToken ct = default) =>
GetAsync($"api/v1/sequences/{sequenceId}/projects", ProtocolJson.Default.ListProjectDto, ct);
public Task<ProjectDto> GetProjectAsync(Guid sequenceId, Guid projectId, CancellationToken ct = default) =>
GetAsync($"api/v1/sequences/{sequenceId}/projects/{projectId}", ProtocolJson.Default.ProjectDto, ct);
/// <summary>
/// A new project of the sequence, its first version copied from <see cref="CreateProjectRequest.FromVersionId"/> or from
/// Main's head; a name refused is a 400 <c>invalid_name</c> or 409 <c>name_taken</c> <see cref="ChronosApiException"/>.
/// </summary>
public Task<ProjectDto> CreateProjectAsync(Guid sequenceId, CreateProjectRequest request, CancellationToken ct = default) =>
SendAsync(HttpMethod.Post, $"api/v1/sequences/{sequenceId}/projects", request, ProtocolJson.Default.CreateProjectRequest, ProtocolJson.Default.ProjectDto, ct);
/// <summary>Gives a project another name; a name refused is a 400 <c>invalid_name</c> or 409 <c>name_taken</c> <see cref="ChronosApiException"/>.</summary>
public Task<ProjectDto> RenameProjectAsync(Guid sequenceId, Guid projectId, string name, CancellationToken ct = default) =>
SendAsync(HttpMethod.Patch, $"api/v1/sequences/{sequenceId}/projects/{projectId}", new RenameProjectRequest(name), ProtocolJson.Default.RenameProjectRequest,
ProtocolJson.Default.ProjectDto, ct);
/// <summary>
/// Deletes a project and its versions into the sequence's projects' trash (never erased); Main is refused (409
/// <c>main_cannot_be_deleted</c>).
/// </summary>
public Task DeleteProjectAsync(Guid sequenceId, Guid projectId, CancellationToken ct = default) =>
SendNoContentAsync(HttpMethod.Delete, $"api/v1/sequences/{sequenceId}/projects/{projectId}", ct);
/// <summary>The project's newest version.</summary>
public Task<ProjectVersionDto> GetProjectHeadAsync(Guid sequenceId, Guid projectId, CancellationToken ct = default) =>
GetAsync($"api/v1/sequences/{sequenceId}/projects/{projectId}/head", ProtocolJson.Default.ProjectVersionDto, ct);
/// <summary>
/// One page of a project's versions: newest first, numbered below <paramref name="before"/> (from the head when null),
/// or, with <paramref name="after"/>, oldest first numbered above it (what a workspace pulls). <paramref name="limit"/>:
/// 1–200 (the server's default, 50 newest first and 100 oldest first, when null). A page may hold fewer versions than
/// asked for while more follow (<see cref="ProjectVersionPageDto.More"/>): the server also ends one before its settings
/// pass a few MiB (<c>?summary=true</c> leaves the settings out, for a list of the versions).
/// </summary>
public Task<ProjectVersionPageDto> ListProjectVersionsAsync(Guid sequenceId, Guid projectId, int? before = null, int? after = null, int? limit = null,
CancellationToken ct = default) =>
GetAsync($"api/v1/sequences/{sequenceId}/projects/{projectId}/versions?{N("before", before)}{N("after", after)}{N("limit", limit)}".TrimEnd('&', '?'),
ProtocolJson.Default.ProjectVersionPageDto, ct);
/// <summary>A version of the project by id; null when the server has no such version of it.</summary>
public Task<ProjectVersionDto?> GetProjectVersionAsync(Guid sequenceId, Guid projectId, Guid versionId, CancellationToken ct = default) =>
VersionOrNullAsync($"api/v1/sequences/{sequenceId}/projects/{projectId}/versions/{versionId}", ct);
/// <summary>
/// A version of the project the server holds durably, read back from its file now with its content hash: what a workspace
/// asks before it drops its own copy. Null when the file is missing or damaged, or the server has no such version; a
/// deleted project is a 404 <c>project</c> <see cref="ChronosApiException"/>.
/// </summary>
public Task<ProjectVersionDto?> GetStoredProjectVersionAsync(Guid sequenceId, Guid projectId, Guid versionId, CancellationToken ct = default) =>
VersionOrNullAsync($"api/v1/sequences/{sequenceId}/projects/{projectId}/versions/{versionId}?stored=true", ct);
private async Task<ProjectVersionDto?> VersionOrNullAsync(string path, CancellationToken ct)
{
try
{
return await GetAsync(path, ProtocolJson.Default.ProjectVersionDto, ct).ConfigureAwait(false);
}
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound && ex.Error.Details == "version")
{
return null;
}
}
/// <summary>
/// Pushes <paramref name="version"/>, made in a workspace from the project's head (<see cref="ProjectVersionDto.ParentId"/>):
/// the server stores it as the new head, numbered head + 1 (201, <c>stored</c>), or answers it again for a repeated push
/// (200, <c>already_stored</c>), or refuses it, storing nothing: 409 <c>diverged</c> with the head, 422
/// <c>hash_mismatch</c>, <c>newer_format</c>, <c>too_large</c> or <c>invalid</c>; a body larger than the server (or a proxy before
/// it) takes, 413, is <c>too_large</c> too. These come back as <see cref="ProjectPushResultDto"/> without throwing; any other failure (the sequence or project gone, no permission, the archive offline or the sequence
/// busy: 503) throws <see cref="ChronosApiException"/>. Safe to repeat: the version's id makes a second push a no-op.
/// </summary>
public async Task<ProjectPushResultDto> PushProjectVersionAsync(Guid sequenceId, Guid projectId, ProjectVersionDto version, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(version);
using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v1/sequences/{sequenceId}/projects/{projectId}/versions")
{
Content = JsonContent.Create(version, ProtocolJson.Default.ProjectVersionDto),
};
using var response = await SendRawAsync(request, ct).ConfigureAwait(false);
if (response.StatusCode is HttpStatusCode.OK or HttpStatusCode.Created or HttpStatusCode.Conflict or HttpStatusCode.UnprocessableEntity)
{
var body = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
try
{
if (JsonSerializer.Deserialize(body, ProtocolJson.Default.ProjectPushResultDto) is { Outcome.Length: > 0 } result) return result;
}
catch (JsonException)
{
// Not a push answer (a proxy's page): the status says what failed.
}
}
if (response.StatusCode == HttpStatusCode.RequestEntityTooLarge)
return new ProjectPushResultDto(ProjectPushOutcomes.TooLarge, null, null, ProjectErrors.TooLarge, response.ReasonPhrase);
await EnsureSuccessAsync(response, ct).ConfigureAwait(false);
throw new ChronosApiException(response.StatusCode, new ApiError("http_" + (int)response.StatusCode, response.ReasonPhrase ?? "error"));
}
/// <summary>The sequence's frames and photo aliases as of one frames version: what its projects' positions are placed on.</summary>
public Task<ProjectFramesDto> GetProjectFramesAsync(Guid sequenceId, CancellationToken ct = default) =>
GetAsync($"api/v1/sequences/{sequenceId}/projects/frames", ProtocolJson.Default.ProjectFramesDto, ct);
/// <summary>A cheap stamp of what <see cref="GetProjectFramesAsync"/> answers: the frames are read again only when it moved.</summary>
public Task<ProjectFramesStampDto> GetProjectFramesStampAsync(Guid sequenceId, CancellationToken ct = default) =>
GetAsync($"api/v1/sequences/{sequenceId}/projects/frames/stamp", ProtocolJson.Default.ProjectFramesStampDto, ct);
// ---------------- Events ----------------
/// <summary>Server events over WebSocket until cancelled; reconnect is the caller's policy.</summary>
public async IAsyncEnumerable<ServerEvent> EventsAsync([EnumeratorCancellation] CancellationToken ct = default)
public IAsyncEnumerable<ServerEvent> EventsAsync(CancellationToken ct = default) => EventsAsync(null, ct);
/// <summary>
/// Server events over WebSocket until cancelled, calling <paramref name="connected"/> once the socket is open (before its
/// first event): from then on no event the server sends is missed.
/// </summary>
public async IAsyncEnumerable<ServerEvent> EventsAsync(Action? connected, [EnumeratorCancellation] CancellationToken ct = default)
{
using var socket = new ClientWebSocket();
socket.Options.RemoteCertificateValidationCallback = _pinning.Validate;
if (_token is not null) socket.Options.SetRequestHeader("Authorization", "Bearer " + _token);
var ws = new UriBuilder(new Uri(BaseAddress, "api/v1/events")) { Scheme = BaseAddress.Scheme == "https" ? "wss" : "ws" }.Uri;
await socket.ConnectAsync(ws, ct).ConfigureAwait(false);
connected?.Invoke();
var buffer = new byte[64 * 1024];
using var message = new MemoryStream();
while (socket.State == WebSocketState.Open && !ct.IsCancellationRequested)
@@ -606,4 +723,8 @@ public sealed class ChronosClient : IDisposable
};
private static string Q(string name, string? value) => string.IsNullOrEmpty(value) ? string.Empty : "&" + name + "=" + Uri.EscapeDataString(value);
/// <summary>A number of the query (<c>name=value&amp;</c>); empty when null.</summary>
private static string N(string name, int? value) =>
value is { } n ? name + "=" + n.ToString(System.Globalization.CultureInfo.InvariantCulture) + "&" : string.Empty;
}
+10
View File
@@ -23,5 +23,15 @@ public sealed record ServerInfo(
ServerLimits Limits,
IReadOnlyList<string>? Extensions = null);
/// <summary>Names of <see cref="ServerInfo.Capabilities"/> that clients act on.</summary>
public static class ServerCapabilities
{
/// <summary>
/// The server keeps its sequences' projects (owner review 2, R8): <c>/api/v1/sequences/{sid}/projects</c>, the
/// <c>projectChanged</c> event, renders of a project version. A server without it knows only the sequence's settings.
/// </summary>
public const string Projects = "projects";
}
/// <summary><c>GET /health</c>.</summary>
public sealed record HealthStatus(string Status, string Version, IReadOnlyDictionary<string, string> Checks);
+12 -1
View File
@@ -4,7 +4,8 @@ namespace Chronos.Protocol;
/// <summary>
/// Messages pushed on <c>WS /api/v1/events</c>. Each frame is one JSON object with a <c>type</c> discriminator:
/// jobProgress, jobState, sequenceChanged, cardEvent, nodeState, scheduleChanged.
/// jobProgress, jobState, sequenceChanged, cardEvent, nodeState, scheduleChanged, projectChanged. A client ignores the types it
/// does not know (an older client those of a newer server).
/// </summary>
[JsonPolymorphic(TypeDiscriminatorPropertyName = "type")]
[JsonDerivedType(typeof(JobProgressEvent), "jobProgress")]
@@ -13,6 +14,7 @@ namespace Chronos.Protocol;
[JsonDerivedType(typeof(CardEvent), "cardEvent")]
[JsonDerivedType(typeof(NodeStateEvent), "nodeState")]
[JsonDerivedType(typeof(ScheduleChangedEvent), "scheduleChanged")]
[JsonDerivedType(typeof(ProjectChangedEvent), "projectChanged")]
public abstract record ServerEvent;
public sealed record JobProgressEvent(Guid JobId, long Done, long Total, double? ItemsPerSecond, double? EtaSeconds) : ServerEvent;
@@ -48,3 +50,12 @@ public sealed record NodeStateEvent(Guid NodeId, string ClientName, string State
/// included, or its next run moved (owner review 2, R10): the admin panel's Scheduled tab reads the list again.
/// </summary>
public sealed record ScheduleChangedEvent(Guid ScheduleId, bool Deleted) : ServerEvent;
/// <summary>
/// A project of a sequence changed (owner review 2, R8): <see cref="Change"/> is one of <see cref="ProjectChanges"/>
/// (<c>created</c>, <c>renamed</c>, <c>deleted</c>, <c>pushed</c>), <see cref="HeadNumber"/> and <see cref="HeadVersionId"/>
/// its head after the change. Sent for the API's own changes and when Main takes settings another path wrote (a
/// <c>PATCH</c> of the sequence's settings, an analysis, the sync of a desktop's copy, a conversion); a workspace with that
/// project checked out knows its home moved, and the admin panel reads the projects again.
/// </summary>
public sealed record ProjectChangedEvent(Guid SequenceId, Guid ProjectId, string Change, int HeadNumber, Guid? HeadVersionId) : ServerEvent;
+170
View File
@@ -0,0 +1,170 @@
namespace Chronos.Protocol;
/// <summary>
/// A project of a server sequence (owner review 2, R8; <c>/api/v1/sequences/{sid}/projects</c>): a named set of render
/// settings ("4K landscape", "Vertical social") with a linear history of versions. Every sequence has one Main project
/// (<see cref="IsMain"/>, listed first), whose head is the sequence's own settings: an old client's <c>PATCH
/// /sequences/{id}</c> of the settings becomes a version of it. <see cref="HeadKind"/>, <see cref="HeadAuthor"/>,
/// <see cref="HeadClientName"/> and <see cref="HeadStoredAt"/> describe the head version: who changed the project last,
/// and when. <see cref="CreatedBy"/> is the account that made the project (null for Main, made from the settings).
/// </summary>
public sealed record ProjectDto(
Guid Id,
Guid SequenceId,
string Name,
bool IsMain,
Guid? HeadVersionId,
int HeadNumber,
string? CreatedBy,
DateTimeOffset CreatedAt,
DateTimeOffset UpdatedAt,
string? HeadKind = null,
string? HeadAuthor = null,
string? HeadClientName = null,
DateTimeOffset? HeadStoredAt = null);
/// <summary>
/// One version of a project, immutable once stored (owner review 2, R8). <see cref="SettingsJson"/> is the portable form of
/// the settings (every frame position parked by photo, canonical text) and <see cref="ContentHash"/> the lower-case hex
/// SHA-256 of its UTF-8 bytes, which every side checks. <see cref="Kind"/> is <c>commit</c>, <c>merge</c>, <c>restore</c>,
/// <c>imported</c> or <c>external</c> (Main only: settings written outside the projects). <see cref="SettingsFormat"/> is the
/// settings' format (a newer one opens read-only), <see cref="FramesVersion"/> the frames version they were made against,
/// <see cref="RestoredFrom"/> the version a restore brought back. <see cref="StoredAt"/> is null for a version a workspace
/// has not pushed. A push (<c>POST …/versions</c>) sends the version as the workspace made it, its parent the head it knew:
/// the server numbers it (head + 1), records the account that pushed it as its <see cref="Author"/> and stores it.
/// </summary>
public sealed record ProjectVersionDto(
Guid Id,
Guid ProjectId,
Guid? ParentId,
int Number,
string Kind,
string? Author,
string? ClientName,
string? Note,
string SettingsJson,
string ContentHash,
int SettingsFormat,
int FramesVersion,
Guid? RestoredFrom,
DateTimeOffset CreatedAt,
DateTimeOffset? StoredAt);
/// <summary>
/// <c>POST /api/v1/sequences/{sid}/projects</c>: a new project named <see cref="Name"/> (1–60 characters, unique among the
/// sequence's projects whatever the case), whose first version (kind <c>imported</c>) holds the settings of
/// <see cref="FromVersionId"/> (a version of any project of the sequence), or of Main's head.
/// </summary>
public sealed record CreateProjectRequest(string Name, Guid? FromVersionId = null);
/// <summary><c>PATCH /api/v1/sequences/{sid}/projects/{pid}</c>: the project's new name (1–60 characters, unique among the sequence's projects).</summary>
public sealed record RenameProjectRequest(string Name);
/// <summary>
/// <c>GET /api/v1/sequences/{sid}/projects/{pid}/versions</c>: one page of a project's versions, newest first (below
/// <c>before</c>, from the head when absent) or oldest first with <c>after</c> (what a workspace pulls). <see cref="More"/>:
/// versions follow this page in its order. <see cref="HeadNumber"/> is the project's head as the page was read.
/// </summary>
public sealed record ProjectVersionPageDto(IReadOnlyList<ProjectVersionDto> Items, int HeadNumber, bool More);
/// <summary>
/// The answer to a push (<c>POST /api/v1/sequences/{sid}/projects/{pid}/versions</c>): <see cref="Outcome"/> (one of
/// <see cref="ProjectPushOutcomes"/>), the version as stored (<c>stored</c>: 201, <c>already_stored</c>: 200, a push repeated
/// after its answer was lost) and the project's head. A refusal stores nothing and carries the error's <see cref="Code"/>
/// and its sentence in the request's language (<see cref="Message"/>), so the body also reads as an <see cref="ApiError"/>:
/// 409 <c>project_diverged</c> (<c>diverged</c>: the head moved past the version's parent; pull the head, replay the version
/// on it and push again), 422 <c>hash_mismatch</c> (the settings do not match the content hash), <c>newer_format</c>
/// (settings of a newer format than the server reads), <c>invalid_version</c> (<c>invalid</c>: positions not parked by
/// photo, or the id is another project's version).
/// </summary>
public sealed record ProjectPushResultDto(string Outcome, ProjectVersionDto? Version, ProjectVersionDto? Head, string? Code = null, string? Message = null);
/// <summary>
/// <c>GET /api/v1/sequences/{sid}/projects/frames</c>: what a workspace places a server sequence's project positions on, as
/// of one frames version: every frame in index order (as <c>GET /sequences/{id}/frames</c> gives them) and the links between
/// encodings of one photo, the sequence's tombstones of reason <c>replaced</c> (a conversion's original and its replacement;
/// a position parked on either finds the frame that holds the other). <see cref="Aliases"/> is null when there are none.
/// </summary>
public sealed record ProjectFramesDto(Guid SequenceId, int FramesVersion, IReadOnlyList<FrameDto> Frames, IReadOnlyList<RemovedPhotoDto>? Aliases = null);
/// <summary>
/// <c>GET /api/v1/sequences/{sid}/projects/frames/stamp</c>: a cheap stamp of what <c>…/projects/frames</c> answers, another
/// value whenever the frames, how their photos are named (a hash learnt) or the encodings conversions joined may have
/// changed, so a workspace reads the frames again only then.
/// </summary>
public sealed record ProjectFramesStampDto(Guid SequenceId, string Stamp);
/// <summary>What became of a pushed version (<see cref="ProjectPushResultDto.Outcome"/>).</summary>
public static class ProjectPushOutcomes
{
/// <summary>Stored as the new head: its parent was the head (a fast-forward). 201.</summary>
public const string Stored = "stored";
/// <summary>A version with that id and content is stored already (a repeated push): nothing changed. 200.</summary>
public const string AlreadyStored = "already_stored";
/// <summary>The head moved past the version's parent. 409 <c>project_diverged</c>.</summary>
public const string Diverged = "diverged";
/// <summary>The settings do not match the content hash. 422 <c>hash_mismatch</c>.</summary>
public const string HashMismatch = "hash_mismatch";
/// <summary>Settings of a newer format than the server reads. 422 <c>newer_format</c>.</summary>
public const string NewerFormat = "newer_format";
/// <summary>Not a version of this project (positions not parked by photo, or another project's id). 422 <c>invalid_version</c>.</summary>
public const string Invalid = "invalid";
/// <summary>The version's file would be larger than a version may be (64 MiB). 422 <c>too_large</c>.</summary>
public const string TooLarge = "too_large";
}
/// <summary>Changes of a project a <see cref="ProjectChangedEvent"/> tells.</summary>
public static class ProjectChanges
{
/// <summary>A project was made (Main too, the first time the sequence's projects are read).</summary>
public const string Created = "created";
public const string Renamed = "renamed";
/// <summary>A project left the sequence (into its projects' trash).</summary>
public const string Deleted = "deleted";
/// <summary>
/// The project has a new head: a version pushed, settings written outside the projects taken as Main's external version
/// (an older client, an analysis, the sync of a desktop's copy), a merge, or versions another program sharing the archive
/// wrote.
/// </summary>
public const string Pushed = "pushed";
}
/// <summary>Error codes of the project calls that clients act on (owner review 2, R8).</summary>
public static class ProjectErrors
{
/// <summary>409 from a push: the head moved past the version's parent (the answer carries the head).</summary>
public const string Diverged = "project_diverged";
/// <summary>422 from a push: the settings do not match their content hash.</summary>
public const string HashMismatch = "hash_mismatch";
/// <summary>422 from a push: settings of a newer format than the server reads.</summary>
public const string NewerFormat = "newer_format";
/// <summary>422 from a push: not a version of this project.</summary>
public const string InvalidVersion = "invalid_version";
/// <summary>400: a project name is blank, longer than 60 characters or holds a control character.</summary>
public const string InvalidName = "invalid_name";
/// <summary>409: another project of the sequence has that name (case does not count).</summary>
public const string NameTaken = "name_taken";
/// <summary>409: the Main project holds the sequence's own settings and is never deleted.</summary>
public const string MainCannotBeDeleted = "main_cannot_be_deleted";
/// <summary>409: the sequence has no photo yet (no folder in the archive), so it keeps no projects; its list is empty.</summary>
public const string SequenceEmpty = "sequence_empty";
/// <summary>413 from a push: the body is larger than the server takes; read as the outcome <see cref="ProjectPushOutcomes.TooLarge"/>.</summary>
public const string TooLarge = "too_large";
}
+9
View File
@@ -91,4 +91,13 @@ namespace Chronos.Protocol;
[JsonSerializable(typeof(ReorganizePlanDto))]
[JsonSerializable(typeof(ConvertRequest))]
[JsonSerializable(typeof(ConvertPlanDto))]
[JsonSerializable(typeof(ProjectDto))]
[JsonSerializable(typeof(List<ProjectDto>))]
[JsonSerializable(typeof(ProjectVersionDto))]
[JsonSerializable(typeof(CreateProjectRequest))]
[JsonSerializable(typeof(RenameProjectRequest))]
[JsonSerializable(typeof(ProjectVersionPageDto))]
[JsonSerializable(typeof(ProjectPushResultDto))]
[JsonSerializable(typeof(ProjectFramesDto))]
[JsonSerializable(typeof(ProjectFramesStampDto))]
public sealed partial class ProtocolJson : JsonSerializerContext;
+9
View File
@@ -387,6 +387,15 @@ textarea.input.notes { height: auto; min-height: 64px; padding: 6px 10px; resize
.frame-badge.hero { color: var(--sun); }
.frame-badge.warn { top: auto; bottom: 4px; inset-inline: 4px auto; color: var(--warning); }
.table.renders { grid-template-columns: minmax(100px, 1.4fr) max-content max-content max-content max-content max-content; }
/* A sequence's projects (owner review 2, R8) and, under one opened, its versions. Their table sits in a wrapper, a grid item
of the panel: it may be narrower than the table, so the table's columns fit (fitColumns) instead of the panel scrolling. */
.panel > .table-host { min-width: 0; }
.table.projects { grid-template-columns: minmax(120px, 1.4fr) max-content minmax(120px, 1.2fr) max-content; }
.table.projects.fit-1 { grid-template-columns: minmax(120px, 1fr) max-content max-content; }
.table.projects.fit-1 .col-changed { display: none; }
.versions { display: grid; grid-template-columns: max-content max-content minmax(0, max-content) minmax(0, 1fr) max-content; gap: 6px 18px; align-items: center; padding: 10px 18px; background: var(--bg); border-top: 1px solid var(--stroke); }
.versions .version { display: contents; }
.versions .more { grid-column: 1 / -1; justify-self: start; }
.table.trash { grid-template-columns: max-content minmax(140px, 2fr) max-content max-content minmax(60px, 1fr) max-content max-content; }
.table.trash.fit-1 { grid-template-columns: max-content minmax(120px, 2fr) max-content max-content max-content max-content; }
.table.trash.fit-1 .col-by { display: none; }
@@ -0,0 +1,254 @@
// The projects of a sequence on the panel (owner review 2, R8): each project's name, Main marked, its newest version and who
// changed it last, its versions on demand, and Rename and Delete for the projects other than Main. Nothing here edits a
// project's settings: the desktop does, in its workspace, and pushes its versions here. The list follows projectChanged.
import { t, plural, applyStrings } from "../../i18n.js";
import { escapeHtml, attr, formatNumber, formatDateTime, toast, errorText, confirmDialog, formDialog, emptyState, markInvalid, redraw, fitColumns } from "../../ui.js";
/** Versions read at a time when a project is opened, and with each Load more. */
const VERSION_PAGE = 20;
/** The most versions one read of them gives (ProjectEndpoints.MaxPage): a refresh reads again as many as are shown, up to this. */
const MAX_PAGE = 200;
/** A project name, as the server takes it (ProjectService.MaxNameLength). */
const MAX_NAME = 60;
/** The name every sequence's Main project is made with; shown in the panel's language. */
const MAIN_NAME = "Main";
/** How long after a projectChanged the projects are read again; one read covers every change meanwhile. */
const AFTER_CHANGE_MS = 500;
/** Version kinds the panel names (ProjectVersionKinds). */
const KINDS = { commit: "Commit", merge: "Merge", restore: "Restore", imported: "Imported", external: "External" };
/**
* Draws the Projects section of sequence sequenceId into host (its count into meta) and keeps it current. Returns
* onEvent(e), which the sequence page passes every server event to.
*/
export function projectsSection(host, meta, { api, sequenceId }) {
const base = `/api/v1/sequences/${encodeURIComponent(sequenceId)}/projects`;
let projects = [];
/** The versions read of each project opened: { items, more }. */
const versions = new Map();
const expanded = new Set();
let timer = null;
let failed = null;
/** The projects a projectChanged named since the last read; null after a reconnection, when any may have changed. */
let changed = new Set();
host.innerHTML = `
<div class="table projects" data-levels="1" role="table" aria-labelledby="projects-title">
<div class="thead" role="row"><span role="columnheader" data-i18n="Admin.Projects.Name"></span>
<span role="columnheader" class="end" data-i18n="Admin.Projects.Head"></span>
<span role="columnheader" class="col-changed" data-i18n="Admin.Projects.Changed"></span>
<span role="columnheader"><span class="sr-only" data-i18n="Admin.Common.Actions"></span></span></div>
<div role="rowgroup" id="project-rows"></div>
</div>`;
applyStrings(host);
const table = host.querySelector(".table");
const rows = host.querySelector("#project-rows");
/**
* Reads the projects again, and the versions of those opened that may have changed (every one when stale is null): as
* many as are shown, so the pages Load more read stay.
*/
async function load(stale = null) {
try {
projects = await api.get(base);
failed = null;
// A project deleted meanwhile (here or elsewhere) closes; the versions of the others that changed are read again.
for (const id of expanded) {
if (!projects.some((p) => p.id === id)) forget(id);
}
const again = [...expanded].filter((id) => stale === null || stale.has(id));
await Promise.all(again.map((id) => reloadVersions(id).catch(() => forget(id))));
} catch (err) {
projects = [];
failed = errorText(err);
}
if (!host.isConnected) return;
meta.textContent = failed ? "" : plural("Admin.Projects.Count", projects.length);
draw();
}
/**
* The newest versions of a project, or with more the next page after those shown. Read without their settings
* (summary): the panel shows none, and a large sequence's versions are megabytes each.
*/
async function loadVersions(id, more = false, limit = VERSION_PAGE) {
const known = versions.get(id);
const before = more && known?.items.length ? `&before=${known.items[known.items.length - 1].number}` : "";
const page = await api.get(`${base}/${encodeURIComponent(id)}/versions?limit=${limit}${before}&summary=true`);
versions.set(id, { items: more && known ? known.items.concat(page.items) : page.items, more: page.more });
}
/** The newest versions of a project read again, as many as are shown (at least a page, at most MAX_PAGE). */
function reloadVersions(id) {
const shown = versions.get(id)?.items.length ?? 0;
return loadVersions(id, false, Math.min(MAX_PAGE, Math.max(VERSION_PAGE, shown)));
}
function forget(id) {
expanded.delete(id);
versions.delete(id);
}
function draw() {
redraw(rows, () => {
rows.innerHTML = failed
? `<div class="row" role="row"><div class="wide empty" role="cell">${escapeHtml(failed)}</div></div>`
: projects.map(rowHtml).join("") || `<div class="row" role="row"><div class="wide" role="cell">${emptyState("Admin.Projects.Empty")}</div></div>`;
applyStrings(rows);
});
rows.querySelectorAll("[data-toggle]").forEach((b) => b.addEventListener("click", () => toggle(b.dataset.toggle)));
rows.querySelectorAll("[data-act]").forEach((b) => b.addEventListener("click", () => act(b.dataset.act, find(b.closest("[data-key]").dataset.key))));
rows.querySelectorAll("[data-more-versions]").forEach((b) => b.addEventListener("click", () => moreVersions(b.dataset.moreVersions)));
fitColumns(table);
}
function find(id) {
return projects.find((p) => p.id === id);
}
/** Main keeps the name it was made with in the panel's language; a Main renamed shows its name and the Main mark. */
function projectName(p) {
return p.isMain && p.name === MAIN_NAME ? t("Admin.Projects.Main") : p.name;
}
function rowHtml(p) {
const name = projectName(p);
const mark = p.isMain && p.name !== MAIN_NAME
? `<span class="pill" data-i18n="Admin.Projects.Main" data-i18n-title="Admin.Projects.Main.Tip"></span>` : "";
const who = p.headAuthor ?? p.headClientName ?? "";
const when = p.headStoredAt ?? p.updatedAt;
const actions = p.isMain ? "" : `
<button class="btn small" data-act="rename" data-i18n="Admin.Projects.Rename" data-i18n-title="Admin.Projects.Rename.Tip"></button>
<button class="btn small destructive" data-act="delete" data-i18n="Admin.Projects.Delete" data-i18n-title="Admin.Projects.Delete.Tip"></button>`;
return `
<div class="row" role="row" data-key="${attr(p.id)}">
<span class="name-cell" role="cell"><button class="link ellipsis" data-toggle="${attr(p.id)}" aria-expanded="${expanded.has(p.id)}"
aria-controls="versions-${attr(p.id)}" dir="auto" title="${attr(p.isMain ? `${t("Admin.Projects.Main.Tip")}\n${t("Admin.Projects.Versions.Tip")}` : t("Admin.Projects.Versions.Tip"))}">${escapeHtml(name)}</button>${mark}</span>
<span class="num end nowrap" role="cell" title="${attr(t("Admin.Projects.Head.Tip"))}">${escapeHtml(formatNumber(p.headNumber))}</span>
<span class="col-changed ellipsis" role="cell" title="${attr([kindTip(p.headKind), p.headClientName].filter(Boolean).join("\n"))}"><span dir="auto">${escapeHtml(who)}</span>${who ? " · " : ""}<span class="muted nowrap">${escapeHtml(formatDateTime(when))}</span></span>
<span class="row-actions" role="cell">${actions}</span>
</div>
${expanded.has(p.id) ? `<div class="row log-row" role="row"><div class="wide" role="cell" id="versions-${attr(p.id)}">${versionsHtml(p)}</div></div>` : ""}`;
}
function versionsHtml(p) {
const page = versions.get(p.id);
if (!page) return "";
if (page.items.length === 0) return emptyState("Admin.Projects.NoVersions");
return `<div class="versions" role="list" aria-label="${attr(t("Admin.Projects.VersionsOf", projectName(p)))}">${page.items.map((v) => `
<div class="version" role="listitem">
<span class="num nowrap">${escapeHtml(t("Admin.Projects.Number", formatNumber(v.number)))}${v.id === p.headVersionId
? ` <span class="pill" data-i18n="Admin.Projects.Current" data-i18n-title="Admin.Projects.Current.Tip"></span>` : ""}</span>
<span class="nowrap" title="${attr(kindTip(v.kind))}">${escapeHtml(kindLabel(v.kind))}</span>
<span class="ellipsis" dir="auto" title="${attr([v.author, v.clientName].filter(Boolean).join(" · "))}">${escapeHtml(v.author ?? v.clientName ?? "")}</span>
<span class="ellipsis muted" dir="auto" title="${attr(v.note ?? "")}">${escapeHtml(v.note ?? "")}</span>
<span class="muted nowrap num">${escapeHtml(formatDateTime(v.storedAt ?? v.createdAt))}</span>
</div>`).join("")}
${page.more ? `<button class="btn small more" data-more-versions="${attr(p.id)}" data-i18n="Admin.Common.More" data-i18n-title="Admin.Common.More.Tip"></button>` : ""}</div>`;
}
function kindLabel(kind) {
return KINDS[kind] ? t(`Admin.Projects.Kind.${KINDS[kind]}`) : String(kind ?? "");
}
function kindTip(kind) {
return KINDS[kind] ? t(`Admin.Projects.Kind.${KINDS[kind]}.Tip`) : "";
}
async function toggle(id) {
if (expanded.delete(id)) {
versions.delete(id);
draw();
return;
}
expanded.add(id);
try {
await loadVersions(id);
} catch (err) {
forget(id);
toast(errorText(err), true);
}
draw();
}
async function moreVersions(id) {
try {
await loadVersions(id, true);
} catch (err) {
toast(errorText(err), true);
return;
}
draw();
}
async function act(action, project) {
if (!project || project.isMain) return;
if (action === "rename") return rename(project);
if (action === "delete") return remove(project);
}
async function rename(project) {
const data = await formDialog({
title: t("Admin.Projects.RenameTitle", project.name),
fields: `<label><span data-i18n="Admin.Projects.NewName"></span><input class="input" name="name" dir="auto" maxlength="${MAX_NAME}" autocomplete="off"
value="${attr(project.name)}" data-i18n-title="Admin.Projects.NewName.Tip"></label>`,
confirm: t("Admin.Projects.RenameConfirm"),
confirmTip: t("Admin.Projects.RenameConfirm.Tip"),
cancel: t("Admin.Common.Cancel"),
cancelTip: t("Admin.Common.Cancel.Tip"),
check: (form) => {
const name = form.elements.name.value.trim();
if (name.length > 0 && name.length <= MAX_NAME) return true;
markInvalid(form.elements.name, t("Admin.Projects.NameInvalid"));
form.elements.name.focus();
return false;
},
});
const name = String(data?.get("name") ?? "").trim();
if (!data || name === project.name) return;
try {
await api.patch(`${base}/${encodeURIComponent(project.id)}`, { name });
toast(t("Admin.Projects.Renamed", name));
} catch (err) {
toast(errorText(err), true);
}
await load();
}
/** Delete, after a confirmation that names the project: it and its versions move to the sequence's project trash. */
async function remove(project) {
const confirmed = await confirmDialog({
title: t("Admin.Projects.DeleteTitle", project.name),
body: t("Admin.Projects.DeleteBody", formatNumber(project.headNumber)),
confirm: t("Admin.Projects.DeleteConfirm"),
confirmTip: t("Admin.Projects.DeleteConfirm.Tip"),
cancel: t("Admin.Common.Keep"),
cancelTip: t("Admin.Common.Keep.Tip"),
});
if (!confirmed) return;
try {
await api.del(`${base}/${encodeURIComponent(project.id)}`);
toast(t("Admin.Projects.Deleted", project.name));
forget(project.id);
} catch (err) {
toast(errorText(err), true);
}
await load();
}
load();
return {
onEvent(e) {
if ((e.type === "projectChanged" && e.sequenceId === sequenceId) || e.type === "reconnected") {
if (e.type === "reconnected") changed = null;
else changed?.add(e.projectId);
clearTimeout(timer);
timer = setTimeout(() => {
const stale = changed;
changed = new Set();
if (host.isConnected) load(stale);
}, AFTER_CHANGE_MS);
}
},
};
}
@@ -1,10 +1,12 @@
// A sequence on the panel (owner review 2, R6): its title, tags, rating and notes, its facts, its photos in pages of 500
// with lazy thumbnails, a photo viewer, deleting photos into the archive's trash, the cover, the originals and the renders
// to download. Nothing here edits the video: its settings and its renders are the desktop editor's.
// with lazy thumbnails, a photo viewer, deleting photos into the archive's trash, the cover, its projects (R8: listed,
// renamed and deleted, projects.js), the originals and the renders to download. Nothing here edits the video: its settings,
// its projects' versions and its renders are the desktop editor's.
import { t, plural, applyStrings } from "../../i18n.js";
import { escapeHtml, attr, formatBytes, formatNumber, formatDateTime, toast, errorText, confirmDialog, emptyState, escapeReverts, redraw } from "../../ui.js";
import { icons } from "../../icons.js";
import { captureText, cameraLabel, spanText, statusChips, lazyImage, watchImages, retryImages, Selection, selectableGrid, tagList, coverUrl, listed, JOB_ENDED } from "./shared.js";
import { projectsSection } from "./projects.js";
const FRAME_PAGE = 500;
/** Deleting more photos than this asks for their number to be typed. */
@@ -80,11 +82,16 @@ export async function renderSequence(root, { api, setMeta, actions, onEvent }, i
<div class="table-foot" id="frames-foot" hidden><span class="muted" id="frames-shown"></span><span class="spacer"></span>
<button class="btn small" id="frames-more" data-i18n="Admin.Common.More" data-i18n-title="Admin.Sequence.MorePhotos.Tip"></button></div>
</section>
<section class="panel flush" aria-labelledby="projects-title">
<div class="panel-head padded"><h2 id="projects-title" data-i18n="Admin.Projects.Title"></h2><span class="muted ellipsis" id="projects-meta"></span></div>
<div id="projects" class="table-host"></div>
</section>
<section class="panel flush" aria-labelledby="renders-title">
<div class="panel-head padded"><h2 id="renders-title" data-i18n="Admin.Sequence.Renders"></h2></div>
<div id="renders"></div>
</section>`;
applyStrings(root);
const projects = projectsSection(root.querySelector("#projects"), root.querySelector("#projects-meta"), { api, sequenceId: id });
const form = root.querySelector("form");
const framesHost = root.querySelector("#frames");
escapeReverts(form);
@@ -573,6 +580,7 @@ export async function renderSequence(root, { api, setMeta, actions, onEvent }, i
}
onEvent((e) => {
projects.onEvent(e);
if (e.type === "jobState") {
// The event names neither the job's kind nor its targets: any job that ended may have worked on this one. The timer
// is not pushed back by the next one, so a busy queue still refreshes the page every AFTER_JOB_MS; a refresh that
+1 -1
View File
@@ -98,7 +98,7 @@ public static class ArchiveEndpoints
return InvalidTemplate(context, problem);
if (!ProxyPolicy.IsValidLongEdge(request.ProxyLongEdge)) return ApiErrors.BadRequest(context, "bad_request", "proxyLongEdge");
var engine = archives ?? new ArchiveService(db, new ArchiveServiceOptions { Owner = ArchiveModule.Owner });
var engine = archives ?? new ArchiveService(db, new ArchiveServiceOptions { Owner = ArchiveModule.Owner, IndexSettingsMayLead = true });
Archive updated;
try
{
+1 -1
View File
@@ -80,7 +80,7 @@ public static class FileEndpoints
using var body = new MemoryStream();
await context.Request.Body.CopyToAsync(body, ct);
var images = (archives ?? new ArchiveService(db, new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = ArchiveModule.Owner })).Images;
var images = (archives ?? new ArchiveService(db, new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = ArchiveModule.Owner, IndexSettingsMayLead = true })).Images;
ProxyStoreResult result;
try
{
+58 -5
View File
@@ -1,8 +1,11 @@
using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Projects;
using Chronos.Protocol;
using Chronos.Server.Jobs;
using Chronos.Server.Security;
@@ -11,8 +14,9 @@ using Chronos.Server.Storage;
namespace Chronos.Server.Api;
/// <summary>
/// <c>/api/v1/jobs</c> (BRIEF §14.6): queue and history, creation (a render batch becomes one job per preset), cancel,
/// pause, resume, retry and priority. Changes reach WebSocket clients as <c>jobState</c> and <c>jobProgress</c> events.
/// <c>/api/v1/jobs</c> (BRIEF §14.6): queue and history, creation (a render batch becomes one job per preset; a render of a
/// project version is checked against the sequence's projects, owner review 2, R8), cancel, pause, resume, retry and
/// priority. Changes reach WebSocket clients as <c>jobState</c> and <c>jobProgress</c> events.
/// </summary>
public static class JobEndpoints
{
@@ -62,7 +66,7 @@ public static class JobEndpoints
}
private static async Task<IResult> CreateAsync(HttpContext context, Caller caller, CreateJobRequest request, ChronosDatabase db, JobEngineHost host,
ServerArchive archive, AuditLog audit)
ServerArchive archive, AuditLog audit, [FromServices] ArchiveService? archives)
{
var ct = context.RequestAborted;
if (!JobWire.TryParseKind(request.Kind, out var kind) || !(kind == JobKind.Render || SequenceKinds.Contains(kind) || ArchiveKinds.Contains(kind)))
@@ -94,7 +98,11 @@ public static class JobEndpoints
List<(string Label, string? Parameters)> queue = [(label, request.ParametersJson)];
if (kind == JobKind.Render)
{
if (ParseRender(request.ParametersJson) is not { } render) return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson");
if (ParseRender(request.ParametersJson) is not { } parsed) return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson");
// A render of a project version (owner review 2, R8): of the sequence's projects, a project alone pinned to its head.
var (render, missing) = await ProjectRenderAsync(db, archives, targets[0], parsed, ct);
if (missing is not null) return ApiErrors.NotFound(context, missing);
var parametersJson = render == parsed ? request.ParametersJson : JsonSerializer.Serialize(render, ProtocolJson.Default.RenderJobParameters);
// A batch becomes one job per preset: a render node uploads one file per job (BRIEF §14.7).
IReadOnlyList<RenderJobParameters> each;
try
@@ -107,7 +115,7 @@ public static class JobEndpoints
return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson");
}
queue = each.Count == 1
? [(ProcessingJobs.RenderLabel(label, render.PresetName), request.ParametersJson)]
? [(ProcessingJobs.RenderLabel(label, render.PresetName), parametersJson)]
: [.. each.Select(p => (ProcessingJobs.RenderLabel(label, p.PresetName), (string?)JsonSerializer.Serialize(p, ProtocolJson.Default.RenderJobParameters)))];
}
else if (request.ParametersJson is not null && !IsJsonObject(request.ParametersJson))
@@ -133,6 +141,51 @@ public static class JobEndpoints
return Results.Json(Dto.Job(first!), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted);
}
/// <summary>
/// The render of a project version (owner review 2, R8), checked against the sequence: <see cref="RenderJobParameters.ProjectVersionId"/>
/// must be a version of one of its projects (that project, when <see cref="RenderJobParameters.ProjectId"/> names one too) and
/// fills in the project; a live project alone, without settings of its own, renders its head as it is now, which the job then
/// names, so the render records the version it rendered; embedded settings with a project render as they are, recording
/// the project. A deleted project's versions still render (they are kept). Without either, the parameters as they are.
/// Returns what is missing (<c>project</c>, <c>version</c>) instead of the parameters when they do not hold.
/// </summary>
internal static async Task<(RenderJobParameters Parameters, string? Missing)> ProjectRenderAsync(ChronosDatabase db, ArchiveService? archives, Guid sequenceId,
RenderJobParameters render, CancellationToken ct)
{
if (render.ProjectId is null && render.ProjectVersionId is null) return (render, null);
var projects = LibraryEndpoints.Engine(archives, db).Projects;
ProjectVersion? version = null;
if (render.ProjectVersionId is { } versionId && (version = await KnownVersionAsync(versionId)) is null) return (render, "version");
var projectId = render.ProjectId ?? version!.ProjectId;
if (await db.Projects.GetAsync(projectId, ct) is not { } project)
{
// A project the index does not know yet may be in the sequence's sidecars: listing reads them first.
await projects.ListAsync(sequenceId, ct);
project = await db.Projects.GetAsync(projectId, ct);
}
if (project is null || project.SequenceId != sequenceId) return (render, "project");
if (version is not null) return version.ProjectId == project.Id ? (render with { ProjectId = project.Id }, null) : (render, "version");
if (render.SettingsJson is not null) return (render with { ProjectId = project.Id }, null);
try
{
// Caught up first: Main's head is the sequence's settings as they are now.
var head = await projects.HeadAsync(project.Id, ct);
return (render with { ProjectId = project.Id, ProjectVersionId = head.Id }, null);
}
catch (ProjectException)
{
// A deleted project has no head to render; its versions, named by id, still render (they are kept).
return (render, project.DeletedAt is null ? "version" : "project");
}
async Task<ProjectVersion?> KnownVersionAsync(Guid id)
{
if (await db.Projects.GetVersionAsync(id, ct) is { } known) return known;
await projects.ListAsync(sequenceId, ct);
return await db.Projects.GetVersionAsync(id, ct);
}
}
/// <summary>The oriented size of the sequence's first frame (what a preset without a fixed size renders at), else the job's size.</summary>
private static async Task<(int Width, int Height)> SourceSizeAsync(ChronosDatabase db, Guid sequenceId, RenderJobParameters render, CancellationToken ct) =>
(await db.Frames.ListBySequenceAsync(sequenceId, limit: 1, cancellationToken: ct)).FirstOrDefault() is { Width: > 0, Height: > 0 } frame
+7 -1
View File
@@ -56,7 +56,13 @@ public static class LibraryEndpoints
/// <summary>The archive engine behind these operations: the host's, or one of its own (a test host that replaces the archive module).</summary>
internal static ArchiveService Engine(ArchiveService? archives, ChronosDatabase db) =>
archives ?? new ArchiveService(db, new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = ArchiveModule.Owner, ImagesAfterScan = true });
archives ?? new ArchiveService(db, new ArchiveServiceOptions
{
Decoder = DecoderFactory.CreateServer(),
Owner = ArchiveModule.Owner,
ImagesAfterScan = true,
IndexSettingsMayLead = true
});
/// <summary>
/// What the Library's filters offer (the panel's Year, Camera and Tag menus): the years of first capture, the camera
+416
View File
@@ -0,0 +1,416 @@
using Microsoft.AspNetCore.Http.Metadata;
using Microsoft.AspNetCore.Mvc;
using Chronos.Core.Archiving;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Projects;
using Chronos.Protocol;
using Chronos.Server.Security;
namespace Chronos.Server.Api;
/// <summary>
/// <c>/api/v1/sequences/{sid}/projects</c> (owner review 2, R8): the server as the home of its sequences' projects, through
/// the archive engine's <see cref="ProjectService"/> as a desktop's archive is (its sidecars first, then the index, under the
/// sequence's lease). The live projects with Main first (made from the sequence's settings when first read), a new project
/// from a version or from Main's head, rename, delete into the sequence's projects' trash (never Main), the head, the versions
/// a page at a time and one by id, the push of a version made in a workspace (a fast-forward, a repeated push answered again,
/// a divergence, a hash, format or portability refusal), and the frames a workspace places the positions on. Reading needs
/// Read; making, renaming and pushing Edit; deleting Delete, and the sequence's owner, the project's maker or an admin.
/// Every change is told to connected clients as <c>projectChanged</c> (the archive module, from what each call changed) and
/// creations, renames and deletions are audited. Nothing here edits a video on the admin panel: it lists and manages.
/// </summary>
public static class ProjectEndpoints
{
/// <summary>
/// The body a push may take: a version's portable settings name each exclusion and camera keyframe by photo (about 150
/// bytes each), so the project of a large sequence outgrows the 1 MiB of other JSON bodies. Any version this PC's archive
/// or a workspace stores (a file up to <see cref="ProjectSidecars.MaxVersionBytes"/>; the body, with its settings as one
/// JSON string, is no larger) fits, with room for the rest of the version: a server and a PC's archive take the same.
/// </summary>
public const long PushBodyLimit = ProjectSidecars.MaxVersionBytes + (1L << 20);
/// <summary>Versions one page may hold.</summary>
public const int MaxPage = 200;
/// <summary>
/// The settings one page of versions carries at most (in characters): a page stops before the version that would pass it
/// (one version always goes) and says more follow, so an answer stays a few MiB however large a sequence's versions are.
/// </summary>
internal const long PageSettingsChars = 4L << 20;
private const int MaxNote = 2000;
private const int MaxClientName = 200;
public static void Map(RouteGroupBuilder api)
{
var projects = api.MapGroup("/sequences/{sid:guid}/projects").Requires(Permissions.Read);
projects.MapGet("", ListAsync);
projects.MapPost("", CreateAsync).Requires(Permissions.Edit);
projects.MapGet("/frames", FramesAsync);
projects.MapGet("/frames/stamp", FramesStampAsync);
projects.MapGet("/{pid:guid}", GetAsync);
projects.MapPatch("/{pid:guid}", RenameAsync).Requires(Permissions.Edit);
projects.MapDelete("/{pid:guid}", DeleteAsync).Requires(Permissions.Delete);
projects.MapGet("/{pid:guid}/head", HeadAsync);
projects.MapGet("/{pid:guid}/versions", VersionsAsync);
projects.MapGet("/{pid:guid}/versions/{vid:guid}", VersionAsync);
projects.MapPost("/{pid:guid}/versions", PushAsync).Requires(Permissions.Edit).WithMetadata(new PushBodyLimitMetadata());
}
/// <summary>
/// The sequence's live projects, Main first, each with its head's kind, author, client and time. A sequence without a Main
/// project gets it now, from its settings; while that cannot be done (the archive offline, the sequence busy, its folder
/// elsewhere) the answer is 503 with the reason's code. A sequence with no photo yet (no folder in the archive) has none:
/// the list is empty, and nothing is written.
/// </summary>
private static async Task<IResult> ListAsync(HttpContext context, Guid sid, ChronosDatabase db, [FromServices] ArchiveService? archives) =>
await RunAsync(context, "project", async ct =>
{
if (await db.Sequences.GetAsync(sid, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
var projects = LibraryEndpoints.Engine(archives, db).Projects;
var list = await projects.ListAsync(sid, ct);
if (!list.Any(p => p.IsMain) && !string.IsNullOrEmpty(sequence.Folder))
{
await projects.MainAsync(sid, ct);
list = await projects.ListAsync(sid, ct);
}
var items = new List<ProjectDto>(list.Count);
foreach (var project in list) items.Add(ProjectWire.ToDto(project, await HeadOfAsync(projects, project, ct)));
return Results.Json(items, ProtocolJson.Default.ListProjectDto);
});
/// <summary>
/// A new project (201): its first version, kind <c>imported</c>, copies <c>fromVersionId</c> (a version of any project of the
/// sequence; 404 <c>not_found</c> <c>version</c> otherwise) or Main's head. 400 <c>invalid_name</c>, 409 <c>name_taken</c>,
/// <c>sequence_empty</c> (no photo yet). Audited <c>project_created</c>.
/// </summary>
private static async Task<IResult> CreateAsync(HttpContext context, Caller caller, Guid sid, CreateProjectRequest request, ChronosDatabase db,
[FromServices] ArchiveService? archives, AuditLog audit, IHostApplicationLifetime lifetime) =>
await RunAsync(context, "version", async ct =>
{
if (await db.Sequences.GetAsync(sid, ct) is null) return ApiErrors.NotFound(context, "sequence");
var projects = LibraryEndpoints.Engine(archives, db).Projects;
// Once asked for, the project is made even if the client goes away meanwhile.
var created = await projects.CreateAsync(sid, request.Name ?? string.Empty, request.FromVersionId, caller.User.Username, lifetime.ApplicationStopping);
await audit.WriteAsync(caller, context, "project_created", "project", created.Id.ToString(), $"{sid} · {created.Name}");
return Results.Json(ProjectWire.ToDto(created, await HeadOfAsync(projects, created, ct)), ProtocolJson.Default.ProjectDto,
statusCode: StatusCodes.Status201Created);
});
/// <summary>A live project of the sequence; 404 <c>not_found</c> <c>project</c> for one deleted or of another sequence.</summary>
private static async Task<IResult> GetAsync(HttpContext context, Guid sid, Guid pid, ChronosDatabase db, [FromServices] ArchiveService? archives) =>
await RunAsync(context, "project", async ct =>
{
var projects = LibraryEndpoints.Engine(archives, db).Projects;
var known = await KnownAsync(context, db, projects, sid, pid, ct);
if (known.Refused is { } refused) return refused;
var project = known.Project!;
if (project.DeletedAt is not null) return ApiErrors.NotFound(context, "project");
return Results.Json(ProjectWire.ToDto(project, await HeadOfAsync(projects, project, ct)), ProtocolJson.Default.ProjectDto);
});
/// <summary>
/// Gives a project another name (Main too: the desktop shows Main in its own language either way). 400 <c>invalid_name</c>,
/// 409 <c>name_taken</c>. Audited <c>project_renamed</c> when the name changed.
/// </summary>
private static async Task<IResult> RenameAsync(HttpContext context, Caller caller, Guid sid, Guid pid, RenameProjectRequest request, ChronosDatabase db,
[FromServices] ArchiveService? archives, AuditLog audit, IHostApplicationLifetime lifetime) =>
await RunAsync(context, "project", async ct =>
{
var projects = LibraryEndpoints.Engine(archives, db).Projects;
var known = await KnownAsync(context, db, projects, sid, pid, ct);
if (known.Refused is { } refused) return refused;
var before = known.Project!;
if (before.DeletedAt is not null) return ApiErrors.NotFound(context, "project");
var renamed = await projects.RenameAsync(pid, request.Name ?? string.Empty, lifetime.ApplicationStopping);
if (renamed.Name != before.Name)
await audit.WriteAsync(caller, context, "project_renamed", "project", pid.ToString(), $"{sid} · {before.Name} → {renamed.Name}");
return Results.Json(ProjectWire.ToDto(renamed, await HeadOfAsync(projects, renamed, ct)), ProtocolJson.Default.ProjectDto);
});
/// <summary>
/// Deletes a project (204): its record says so and its folder, with every version, moves to the sequence's
/// <c>.chronos/projects/.trash</c>, kept and never erased by Chronos. The Main project is refused (409
/// <c>main_cannot_be_deleted</c>); so is another account's project of another account's sequence, for anyone but an admin
/// (403). Audited <c>project_deleted</c>.
/// </summary>
private static async Task<IResult> DeleteAsync(HttpContext context, Caller caller, Guid sid, Guid pid, ChronosDatabase db,
[FromServices] ArchiveService? archives, AuditLog audit, IHostApplicationLifetime lifetime) =>
await RunAsync(context, "project", async ct =>
{
var projects = LibraryEndpoints.Engine(archives, db).Projects;
var known = await KnownAsync(context, db, projects, sid, pid, ct);
if (known.Refused is { } refused) return refused;
var project = known.Project!;
if (project.DeletedAt is not null) return ApiErrors.NotFound(context, "project");
if (project.IsMain) return ApiErrors.Conflict(context, ProjectErrors.MainCannotBeDeleted);
if (!caller.IsAdmin && known.Sequence!.OwnerUserId != caller.Id && !MadeBy(project, caller.User)) return ApiErrors.Forbidden(context);
await projects.DeleteAsync(pid, lifetime.ApplicationStopping);
await audit.WriteAsync(caller, context, "project_deleted", "project", pid.ToString(), $"{sid} · {project.Name}");
return Results.NoContent();
});
/// <summary>
/// The newest version of a live project; 404 <c>not_found</c> <c>project</c> once it is deleted (its versions are still
/// listed: a workspace's copy of it reads as gone, never as in step), <c>version</c> when it has none.
/// </summary>
private static async Task<IResult> HeadAsync(HttpContext context, Guid sid, Guid pid, ChronosDatabase db, [FromServices] ArchiveService? archives) =>
await RunAsync(context, "version", async ct =>
{
var projects = LibraryEndpoints.Engine(archives, db).Projects;
var known = await KnownAsync(context, db, projects, sid, pid, ct);
if (known.Refused is { } refused) return refused;
if (known.Project!.DeletedAt is not null) return ApiErrors.NotFound(context, "project");
return Results.Json(ProjectWire.ToDto(await projects.HeadAsync(pid, ct)), ProtocolJson.Default.ProjectVersionDto);
});
/// <summary>
/// One page of the project's versions: newest first, numbered below <paramref name="before"/> (from the head when absent),
/// or with <paramref name="after"/> oldest first, numbered above it. <paramref name="limit"/> 1–<see cref="MaxPage"/> (50 newest
/// first, 100 oldest first); a page also ends before its settings pass <see cref="PageSettingsChars"/>, with <c>more</c>.
/// <paramref name="summary"/>: the versions without their settings (<c>settingsJson</c> empty), what a list of them shows.
/// 400 <c>bad_request</c> (<c>after</c> with <c>before</c>, a number below 0).
/// </summary>
private static async Task<IResult> VersionsAsync(HttpContext context, Guid sid, Guid pid, int? before, int? after, int? limit, bool? summary, ChronosDatabase db,
[FromServices] ArchiveService? archives)
{
if (before is not null && after is not null) return ApiErrors.BadRequest(context, "bad_request", "after");
if (before is < 0) return ApiErrors.BadRequest(context, "bad_request", "before");
if (after is < 0) return ApiErrors.BadRequest(context, "bad_request", "after");
var take = Math.Clamp(limit ?? (after is null ? 50 : 100), 1, MaxPage);
return await RunAsync(context, "project", async ct =>
{
var projects = LibraryEndpoints.Engine(archives, db).Projects;
var known = await KnownAsync(context, db, projects, sid, pid, ct);
if (known.Refused is { } refused) return refused;
var page = after is { } from
? await projects.VersionsAfterAsync(pid, from, take + 1, ct)
: await projects.HistoryAsync(pid, before, take + 1, ct);
// The head as the page was read: the call above caught the project up first.
var head = (await projects.GetAsync(pid, ct))?.HeadNumber ?? known.Project!.HeadNumber;
var items = new List<ProjectVersionDto>(Math.Min(take, page.Count));
var chars = 0L;
foreach (var version in page.Take(take))
{
if (summary != true && items.Count > 0 && chars + version.SettingsJson.Length > PageSettingsChars) break;
chars += version.SettingsJson.Length;
var dto = ProjectWire.ToDto(version);
items.Add(summary == true ? dto with { SettingsJson = string.Empty } : dto);
}
return Results.Json(new ProjectVersionPageDto(items, head, page.Count > items.Count), ProtocolJson.Default.ProjectVersionPageDto);
});
}
/// <summary>
/// A version of the project by id; one the index does not know yet is looked for in the sequence's sidecars first. With
/// <paramref name="stored"/>, only a version the archive holds durably (<see cref="ProjectService.StoredAsync"/>: its
/// file read back now, with that content hash) of a live project: what a workspace asks before it drops its own copy;
/// 404 <c>project</c> for a deleted project, <c>version</c> for a file missing or damaged.
/// </summary>
private static async Task<IResult> VersionAsync(HttpContext context, Guid sid, Guid pid, Guid vid, bool? stored, ChronosDatabase db,
[FromServices] ArchiveService? archives) =>
await RunAsync(context, "version", async ct =>
{
var projects = LibraryEndpoints.Engine(archives, db).Projects;
var known = await KnownAsync(context, db, projects, sid, pid, ct);
if (known.Refused is { } refused) return refused;
if (stored == true && known.Project!.DeletedAt is not null) return ApiErrors.NotFound(context, "project");
if (await projects.GetVersionAsync(vid, ct) is not { } version)
{
await projects.ListAsync(sid, ct);
version = await projects.GetVersionAsync(vid, ct);
}
if (version is null || version.ProjectId != pid || (stored == true && !await projects.StoredAsync(pid, version, ct)))
return ApiErrors.NotFound(context, "version");
return Results.Json(ProjectWire.ToDto(version), ProtocolJson.Default.ProjectVersionDto);
});
/// <summary>
/// Stores a version made in a workspace from the project's head (<see cref="ProjectService.PushAsync"/>), recording the
/// account that pushed it as its author: 201 <c>stored</c> (a fast-forward: numbered head + 1, Main's mirrored into the
/// sequence's settings), 200 <c>already_stored</c> (the same id and content stored before: a push repeated after its
/// answer was lost), 409 <c>project_diverged</c> (the head moved past its parent; the answer carries the head), 422
/// <c>hash_mismatch</c>, <c>newer_format</c>, <c>invalid_version</c> or <c>too_large</c> (a version file over 64 MiB), each answered as a
/// <see cref="ProjectPushResultDto"/> and logged. 400 <c>bad_request</c> (<c>id</c>, <c>settingsJson</c>, <c>contentHash</c>,
/// <c>note</c>, <c>clientName</c>); 413 <c>too_large</c> above <see cref="PushBodyLimit"/>.
/// </summary>
private static async Task<IResult> PushAsync(HttpContext context, Caller caller, Guid sid, Guid pid, ProjectVersionDto request, ChronosDatabase db,
[FromServices] ArchiveService? archives, ILoggerFactory loggers, IHostApplicationLifetime lifetime)
{
if (request is null) return ApiErrors.BadRequest(context, "bad_request");
if (request.Id == Guid.Empty) return ApiErrors.BadRequest(context, "bad_request", "id");
if (string.IsNullOrEmpty(request.SettingsJson)) return ApiErrors.BadRequest(context, "bad_request", "settingsJson");
if (string.IsNullOrEmpty(request.ContentHash)) return ApiErrors.BadRequest(context, "bad_request", "contentHash");
if (request.Note is { Length: > MaxNote }) return ApiErrors.BadRequest(context, "bad_request", "note");
if (request.ClientName is { Length: > MaxClientName }) return ApiErrors.BadRequest(context, "bad_request", "clientName");
return await RunAsync(context, "project", async ct =>
{
var projects = LibraryEndpoints.Engine(archives, db).Projects;
var known = await KnownAsync(context, db, projects, sid, pid, ct);
if (known.Refused is { } refused) return refused;
if (known.Project!.DeletedAt is not null) return ApiErrors.NotFound(context, "project");
var client = string.IsNullOrWhiteSpace(request.ClientName) ? caller.ClientName : request.ClientName.Trim();
var version = ProjectWire.ToVersion(request) with
{
ProjectId = pid,
Author = caller.User.Username,
ClientName = client,
Note = string.IsNullOrWhiteSpace(request.Note) ? null : request.Note.Trim(),
CreatedAt = request.CreatedAt == default ? DateTimeOffset.UtcNow : request.CreatedAt,
StoredAt = null,
};
// Once sent, the version is stored even if the client goes away meanwhile; a client that asks again is answered already_stored.
var result = await projects.PushAsync(pid, version, lifetime.ApplicationStopping);
var outcome = ProjectWire.Outcome(result.Outcome);
loggers.CreateLogger("Chronos.Server.Projects").LogInformation(
"Version {Version} of project {Project} ({Name}) of sequence {Sequence} pushed by {User} from {Client}: {Outcome}{Number}", request.Id, pid,
known.Project.Name, sid, caller.User.Username, client ?? "-", outcome, result.Version is { } stored ? $" as number {stored.Number}" : string.Empty);
var (status, code, message) = result.Outcome switch
{
PushOutcome.Stored => (StatusCodes.Status201Created, (string?)null, (string?)null),
PushOutcome.AlreadyStored => (StatusCodes.Status200OK, null, null),
PushOutcome.Diverged => (StatusCodes.Status409Conflict, ProjectErrors.Diverged, ApiErrors.Message(context, ProjectErrors.Diverged)),
PushOutcome.HashMismatch => (StatusCodes.Status422UnprocessableEntity, ProjectErrors.HashMismatch, ApiErrors.Message(context, "version_hash_mismatch")),
PushOutcome.NewerFormat => (StatusCodes.Status422UnprocessableEntity, ProjectErrors.NewerFormat, ApiErrors.Message(context, ProjectErrors.NewerFormat)),
PushOutcome.TooLarge => (StatusCodes.Status422UnprocessableEntity, "too_large", ApiErrors.Message(context, "too_large")),
_ => (StatusCodes.Status422UnprocessableEntity, ProjectErrors.InvalidVersion, ApiErrors.Message(context, ProjectErrors.InvalidVersion)),
};
return Results.Json(new ProjectPushResultDto(outcome, result.Version is { } v ? ProjectWire.ToDto(v) : null,
result.Head is { } h ? ProjectWire.ToDto(h) : null, code, message), ProtocolJson.Default.ProjectPushResultDto, statusCode: status);
});
}
/// <summary>
/// The sequence's frames in index order and the photo aliases of its conversions, as of one frames version
/// (<see cref="SequenceEndpoints.SnapshotOfAsync"/>): what a workspace places a version's positions on.
/// </summary>
private static async Task<IResult> FramesAsync(HttpContext context, Guid sid, ChronosDatabase db)
{
var ct = context.RequestAborted;
if (await SequenceEndpoints.SnapshotOfAsync(db, sid, async (on, sequence, c) =>
(Frames: await AllFramesAsync(on, sequence.Id, c), Removals: await on.FrameRemovals.ListBySequenceAsync(sequence.Id, c)), ct) is not { } snapshot)
return ApiErrors.NotFound(context, "sequence");
var (row, (frames, removals)) = snapshot;
var aliases = ProjectWire.Aliases(removals);
return Results.Json(new ProjectFramesDto(sid, row.FramesVersion, [.. frames.Select(Dto.Frame)], aliases.Count == 0 ? null : aliases),
ProtocolJson.Default.ProjectFramesDto);
}
/// <summary>
/// A cheap stamp of what <see cref="FramesAsync"/> answers (<see cref="ArchiveProjectHome.StampOfAsync"/>: the frames
/// version, the photos hashed and their checksum, the removals): a workspace reads the frames again only when it moved.
/// </summary>
private static async Task<IResult> FramesStampAsync(HttpContext context, Guid sid, ChronosDatabase db)
{
try
{
return Results.Json(new ProjectFramesStampDto(sid, await ArchiveProjectHome.StampOfAsync(db, sid, context.RequestAborted)),
ProtocolJson.Default.ProjectFramesStampDto);
}
catch (ProjectException)
{
return ApiErrors.NotFound(context, "sequence");
}
}
/// <summary>
/// Whether <paramref name="user"/> made <paramref name="project"/>: the name it records, by an account that existed when
/// the project was made. An account made since under the name of a deleted one is not its maker.
/// </summary>
internal static bool MadeBy(SequenceProject project, User user) =>
project.CreatedBy is { } maker && string.Equals(maker, user.Username, StringComparison.Ordinal) && user.Created <= project.CreatedAt;
/// <summary>Every frame of a sequence in index order, read a page at a time.</summary>
internal static async Task<List<Frame>> AllFramesAsync(ChronosRepositories db, Guid sequenceId, CancellationToken cancellationToken)
{
const int pageSize = 1000;
var frames = new List<Frame>();
for (var after = -1; ;)
{
var page = await db.Frames.ListBySequenceAsync(sequenceId, after, pageSize, cancellationToken);
frames.AddRange(page);
if (page.Count < pageSize) return frames;
after = page[^1].Index;
}
}
/// <summary>
/// The sequence and a project of it (deleted ones too, whose versions are kept); one the index does not know yet (an index
/// taken back from a backup, a project another program sharing the archive made) is looked for in the sequence's sidecars
/// first. Otherwise the refusal: 404 <c>not_found</c> <c>sequence</c> or <c>project</c>.
/// </summary>
private static async Task<(Sequence? Sequence, SequenceProject? Project, IResult? Refused)> KnownAsync(HttpContext context, ChronosDatabase db,
ProjectService projects, Guid sid, Guid pid, CancellationToken ct)
{
if (await db.Sequences.GetAsync(sid, ct) is not { } sequence) return (null, null, ApiErrors.NotFound(context, "sequence"));
if (await projects.GetAsync(pid, ct) is not { } project)
{
await projects.ListAsync(sid, ct);
project = await projects.GetAsync(pid, ct);
}
return project is not null && project.SequenceId == sid ? (sequence, project, null) : (sequence, null, ApiErrors.NotFound(context, "project"));
}
private static async Task<ProjectVersion?> HeadOfAsync(ProjectService projects, SequenceProject project, CancellationToken ct) =>
project.HeadVersionId is { } id ? await projects.GetVersionAsync(id, ct) : null;
/// <summary>
/// Runs a project call with its refusals answered by their codes: 404 <c>not_found</c> (<c>sequence</c>, or
/// <paramref name="notFound"/> for a project or version the engine does not know), 400 <c>invalid_name</c>, 409
/// <c>name_taken</c>, <c>main_cannot_be_deleted</c>, <c>sequence_empty</c>; 503 <c>archive_offline</c> (offline or read-only), <c>sequence_busy</c>
/// (another writer held it past the lease wait), <c>folder_moved</c> (its folder is not where the index has it),
/// <c>projects_unreadable</c> (a project record or version this Chronos cannot read now: nothing was written); 413
/// <c>too_large</c> for a version file over 64 MiB; 409 <c>folder_in_use</c> when a project's file cannot be written.
/// </summary>
private static async Task<IResult> RunAsync(HttpContext context, string notFound, Func<CancellationToken, Task<IResult>> call)
{
try
{
return await call(context.RequestAborted);
}
catch (ProjectException ex)
{
return ex.Reason switch
{
ProjectError.SequenceNotFound => ApiErrors.NotFound(context, "sequence"),
ProjectError.InvalidName => ApiErrors.BadRequest(context, ProjectErrors.InvalidName),
ProjectError.NameTaken => ApiErrors.Conflict(context, ProjectErrors.NameTaken),
ProjectError.MainCannotBeDeleted => ApiErrors.Conflict(context, ProjectErrors.MainCannotBeDeleted),
ProjectError.SequenceEmpty => ApiErrors.Conflict(context, ProjectErrors.SequenceEmpty),
_ => ApiErrors.NotFound(context, notFound),
};
}
catch (ArchiveOfflineException)
{
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline");
}
catch (LeaseUnavailableException)
{
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "sequence_busy");
}
catch (SequenceFolderMovedException)
{
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "folder_moved");
}
catch (ProjectsUnreadableException)
{
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "projects_unreadable");
}
catch (ProjectVersionTooLargeException)
{
return ApiErrors.Result(context, StatusCodes.Status413PayloadTooLarge, "too_large");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return ApiErrors.Conflict(context, "folder_in_use");
}
}
/// <summary>The push route's body limit (<see cref="PushBodyLimit"/>), applied by routing as it selects the endpoint.</summary>
private sealed class PushBodyLimitMetadata : IRequestSizeLimitMetadata
{
public long? MaxRequestBodySize => PushBodyLimit;
}
}
+61 -7
View File
@@ -25,6 +25,9 @@ public static class SequenceEndpoints
{
private const int MaxTitle = 200;
private const int MaxNotes = 2000;
/// <summary>How long a settings edit waits for the sequence's lease (another writer filing photos or analysing it) before it answers 503 <c>sequence_busy</c>.</summary>
private static readonly TimeSpan SettingsLeaseWait = TimeSpan.FromSeconds(20);
/// <summary>Tags a sequence may carry.</summary>
internal const int MaxTags = 50;
@@ -128,8 +131,15 @@ public static class SequenceEndpoints
return Results.Json(Dto.Sequence(sequence), ProtocolJson.Default.SequenceDto);
}
/// <summary>
/// Edits a sequence's title, tags, rating, notes and settings in the index (the settings version as an optional check). New
/// settings also go to the sequence's <c>project.json</c>, under its lease (<see cref="ArchiveService.EditSettingsAsync"/>),
/// as the archive's other writers of the settings do, so the projects never take an older file for the sequence's
/// settings (owner review 2, R8): 503 <c>archive_offline</c>, <c>sequence_busy</c> or <c>folder_moved</c>, and 409
/// <c>folder_in_use</c>, when that cannot be done now, with nothing changed.
/// </summary>
private static async Task<IResult> UpdateAsync(HttpContext context, Caller caller, Guid id, UpdateSequenceRequest request, ChronosDatabase db,
AuditLog audit, EventHub events)
AuditLog audit, EventHub events, ProjectCatchUp projects, [FromServices] ArchiveService? archives)
{
if (request.Title is { Length: > MaxTitle }) return ApiErrors.BadRequest(context, "bad_request", "title");
if (request.Notes is { Length: > MaxNotes }) return ApiErrors.BadRequest(context, "bad_request", "notes");
@@ -150,7 +160,39 @@ public static class SequenceEndpoints
HeroFrameId = request.HeroFrameId
?? (request.SettingsJson is { } settings ? await SettingsHeroAsync(db, id, settings, context.RequestAborted) : null),
};
var result = await db.Sequences.EditAsync(id, edit, expected, request.ExpectedFramesVersion, context.RequestAborted);
SequenceEditResult result;
if (request.SettingsJson is { } written && archives is not null)
{
try
{
result = await archives.EditSettingsAsync(id, written, ct => db.Sequences.EditAsync(id, edit, expected, request.ExpectedFramesVersion, ct),
SettingsLeaseWait, context.RequestAborted);
}
catch (ArgumentException)
{
return ApiErrors.NotFound(context, "sequence");
}
catch (Chronos.Core.Archiving.ArchiveOfflineException)
{
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline");
}
catch (Chronos.Core.Archiving.LeaseUnavailableException)
{
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "sequence_busy");
}
catch (SequenceFolderMovedException)
{
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "folder_moved");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return ApiErrors.Conflict(context, "folder_in_use");
}
}
else
{
result = await db.Sequences.EditAsync(id, edit, expected, request.ExpectedFramesVersion, context.RequestAborted);
}
switch (result.Outcome)
{
case SequenceEditOutcome.NotFound:
@@ -166,6 +208,9 @@ public static class SequenceEndpoints
var sequence = result.Sequence!;
await audit.WriteAsync(caller, context, "sequence_updated", "sequence", id.ToString(), Changes(request));
events.Publish(new SequenceChangedEvent(id, "settings", sequence.FramesVersion, sequence.SettingsVersion));
// Settings written outside the projects (an older client, the sync of a desktop's copy) become Main's next version now,
// so a workspace with Main checked out hears that its home moved (owner review 2, R8).
if (request.SettingsJson is not null) projects.Touch(id);
context.Response.Headers.ETag = ETag(sequence);
return Results.Json(Dto.Sequence(sequence), ProtocolJson.Default.SequenceDto);
}
@@ -183,7 +228,7 @@ public static class SequenceEndpoints
var ct = context.RequestAborted;
if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
if (!caller.IsAdmin && sequence.OwnerUserId != caller.Id) return ApiErrors.Forbidden(context);
var trash = archives?.Trash ?? new SequenceTrash(db, new ArchiveServiceOptions { Owner = ArchiveModule.Owner });
var trash = archives?.Trash ?? new SequenceTrash(db, new ArchiveServiceOptions { Owner = ArchiveModule.Owner, IndexSettingsMayLead = true });
DeletePlan plan;
try
{
@@ -266,19 +311,28 @@ public static class SequenceEndpoints
/// the sequence is gone.
/// </summary>
internal static async Task<(Sequence Sequence, List<ManifestFrame> Frames)?> SnapshotAsync(ChronosDatabase db, Guid id,
Func<ChronosRepositories, Sequence, CancellationToken, Task<List<ManifestFrame>>> listFrames, CancellationToken cancellationToken)
Func<ChronosRepositories, Sequence, CancellationToken, Task<List<ManifestFrame>>> listFrames, CancellationToken cancellationToken) =>
await SnapshotOfAsync(db, id, listFrames, cancellationToken) is { } snapshot ? (snapshot.Sequence, snapshot.Value) : null;
/// <summary>
/// <see cref="SnapshotAsync"/> for anything read from the sequence's frames (the frames a render node renders and the photos
/// a project version is placed on, the frames and photo aliases of a project home): <paramref name="read"/> runs again while
/// the frames version moved during it, then inside the transaction holding the sequence's row. Null when the sequence is gone.
/// </summary>
internal static async Task<(Sequence Sequence, T Value)?> SnapshotOfAsync<T>(ChronosDatabase db, Guid id,
Func<ChronosRepositories, Sequence, CancellationToken, Task<T>> read, CancellationToken cancellationToken)
{
for (var attempt = 0; attempt < SnapshotAttempts; attempt++)
{
if (await db.Sequences.GetAsync(id, cancellationToken) is not { } sequence) return null;
var frames = await listFrames(db, sequence, cancellationToken);
var value = await read(db, sequence, cancellationToken);
if (await db.Sequences.GetAsync(id, cancellationToken) is not { } after) return null;
if (after.FramesVersion == sequence.FramesVersion) return (sequence, frames);
if (after.FramesVersion == sequence.FramesVersion) return (sequence, value);
}
// Commits keep landing (an upload of earlier photos): the frames are listed while none can.
await using var tx = await db.BeginAsync(cancellationToken);
if (await tx.Sequences.GetForUpdateAsync(id, cancellationToken) is not { } locked) return null;
return (locked, await listFrames(tx, locked, cancellationToken));
return (locked, await read(tx, locked, cancellationToken));
}
private static async Task<IResult> FramesAsync(HttpContext context, Guid id, string? cursor, int? limit, ChronosDatabase db)
+2 -1
View File
@@ -104,7 +104,8 @@ public sealed class ServerState
/// <summary>Engine and version of the database ("PostgreSQL 17.2", "SQLite 3.45.1").</summary>
public string Database { get; init; } = string.Empty;
public List<string> Capabilities { get; } = ["uploads", "sync", "jobs", "render-nodes", "events"];
/// <summary>What this server offers clients (<see cref="ServerInfo.Capabilities"/>; <see cref="ServerCapabilities"/> names those clients act on).</summary>
public List<string> Capabilities { get; } = ["uploads", "sync", "jobs", "render-nodes", "events", ServerCapabilities.Projects];
public DateTimeOffset StartedAt { get; } = DateTimeOffset.UtcNow;
}
+4
View File
@@ -163,6 +163,9 @@ public static class ServerHost
services.AddSingleton<UploadMaintenance>();
services.AddHostedService(sp => sp.GetRequiredService<UploadMaintenance>());
services.AddSingleton<ICleanupStep, UploadCleanupStep>();
// Main takes settings written outside the projects soon after they are (owner review 2, R8).
services.AddSingleton<ProjectCatchUp>();
services.AddHostedService(sp => sp.GetRequiredService<ProjectCatchUp>());
services.AddSingleton<DiscoveryBeaconService>();
services.AddHostedService(sp => sp.GetRequiredService<DiscoveryBeaconService>());
}
@@ -181,6 +184,7 @@ public static class ServerHost
AuthEndpoints.Map(api);
UserEndpoints.Map(api);
SequenceEndpoints.Map(api);
ProjectEndpoints.Map(api);
LibraryEndpoints.Map(api);
FileEndpoints.Map(api);
UploadEndpoints.Map(api);
+62 -4
View File
@@ -1,9 +1,12 @@
using System.Globalization;
using System.Text.Json;
using Chronos.Core.Archiving;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Repositories;
using Chronos.Protocol;
using Chronos.Server.Api;
@@ -20,7 +23,9 @@ namespace Chronos.Server.Jobs;
/// render jobs they can encode, report progress, and upload the output in resumable chunks that become a render of
/// the sequence. A claimed job lists every frame with its flags (a node renders none missing, corrupt or excluded) and
/// the proxies the server asks for (<see cref="ServerProxies"/>), which the node sends from the originals it fetched.
/// A node that stops heart-beating loses its jobs to the queue (<see cref="RenderNodeMonitor"/>).
/// A node that stops heart-beating loses its jobs to the queue (<see cref="RenderNodeMonitor"/>). A job of a project version
/// (owner review 2, R8) gets that version's settings placed on the frames it lists, and its render records the project and
/// the version.
/// </summary>
public sealed class RenderNodeService(
ChronosDatabase db,
@@ -90,14 +95,62 @@ public sealed class RenderNodeService(
continue;
}
await TouchAsync(node, cancellationToken);
if (await SettingsAsync(parameters, sequence, cancellationToken) is not { } settings)
{
await FinishAsync(node, job, JobState.Failed, Loc.L("Errors.Render.ProjectVersion"), cancellationToken);
continue;
}
var spec = ServerProxies.Spec(archive.Current);
return new ClaimedJob(Dto.Job(job), sequence.Id, parameters.SettingsJson ?? sequence.SettingsJson ?? "{}", parameters.PresetJson,
parameters.UseProxies, await ServerProxies.FramesAsync(db, archive.Current, sequence, spec, cancellationToken), spec);
// The frames the node renders and the photos a project version's positions are placed on, of one frames version.
var snapshot = await SequenceEndpoints.SnapshotOfAsync(db, sequence.Id, async (on, row, ct) => (
Frames: await ServerProxies.FramesAsync(on, archive.Current, row, spec, ct),
Photos: settings.Portable ? HomePhotos.Of(await ProjectEndpoints.AllFramesAsync(on, row.Id, ct), await HomePhotos.AliasesAsync(on, row.Id, ct)) : null),
cancellationToken);
if (snapshot is not { } taken)
{
await FinishAsync(node, job, JobState.Failed, "The sequence no longer exists.", cancellationToken);
continue;
}
var (frames, photos) = taken.Value;
return new ClaimedJob(Dto.Job(job), sequence.Id, photos is null ? settings.Json : Placed(settings.Json, photos), parameters.PresetJson,
parameters.UseProxies, frames, spec);
}
await TouchAsync(node, cancellationToken);
return (ClaimedJob?)null;
}
/// <summary>
/// The settings a node renders: the job's own (a project version's portable form among them, whose positions are placed on
/// the frames the node gets), else those of the project version the job names (owner review 2, R8), else the sequence's.
/// Null when the job names a version that is not one of the sequence's projects'.
/// </summary>
private async Task<(string Json, bool Portable)?> SettingsAsync(RenderJobParameters parameters, Sequence sequence, CancellationToken cancellationToken)
{
if (parameters.SettingsJson is { } embedded) return (embedded, Waits(embedded));
if (parameters.ProjectVersionId is not { } versionId) return (sequence.SettingsJson ?? "{}", false);
return await db.Projects.GetVersionAsync(versionId, cancellationToken) is { } version
&& await db.Projects.GetAsync(version.ProjectId, cancellationToken) is { } project && project.SequenceId == sequence.Id
? (version.SettingsJson, Waits(version.SettingsJson))
: null;
}
/// <summary>Settings with positions that wait for their photos (a project version's portable form, settings synced from another copy).</summary>
private static bool Waits(string settingsJson) => settingsJson.Contains("pendingFrames", StringComparison.OrdinalIgnoreCase);
/// <summary>The settings with their waiting positions placed on <paramref name="photos"/>, as the server's own render does; others as they are.</summary>
private static string Placed(string settingsJson, FramePhotos photos)
{
try
{
return ProjectContent.Place(settingsJson, photos);
}
catch (JsonException)
{
// Not a project: the node says so as it reads it.
return settingsJson;
}
}
public async Task<Outcome<bool>> ProgressAsync(Caller caller, Guid nodeId, Guid jobId, NodeProgress progress, CancellationToken cancellationToken)
{
if (await OwnedNodeAsync(caller, nodeId, cancellationToken) is not { } node) return Outcome<bool>.Fail(404, "not_found", "node");
@@ -176,10 +229,15 @@ public sealed class RenderNodeService(
if (await uploads.StageVerifiedAsync(upload, cancellationToken) is not { } staged) return Outcome<RenderDto>.Fail(422, "hash_mismatch");
var output = JsonSerializer.Deserialize(upload.RenderJson, ProtocolJson.Default.RenderResultRequest)!;
var sequence = await db.Sequences.GetAsync(job.TargetIds[0], cancellationToken);
// The render records the project and the version its job rendered (owner review 2, R8).
var rendered = JobEndpoints.ParseRender(job.ParametersJson);
Render? render;
try
{
render = sequence is null ? null : await renders.CommitAsync(sequence, staged, output, node.ClientName, cancellationToken);
render = sequence is null
? null
: await renders.CommitAsync(sequence, staged, output, node.ClientName, Guid.CreateVersion7(), rendered?.ProjectId, rendered?.ProjectVersionId,
cancellationToken);
}
catch (Exception ex) when (ex is LeaseUnavailableException or ArchiveOfflineException or FolderMovedException)
{
+19 -1
View File
@@ -14,13 +14,17 @@ namespace Chronos.Server.Storage;
/// thumbnails, and its job handlers (scan, rebuild, verify, import, thumbnails, proxies, maintenance, the duplicates and
/// orphans reports, index backups and clean-ups with the server's own steps, the <see cref="ICleanupStep"/>s in DI, Reorganize's
/// <c>move</c> jobs and the <c>convert</c> jobs, which tell connected clients of the sequences they change or make, and check
/// their space against the space volume's free bytes, <see cref="VolumeSpace.Report"/>); a scan
/// their space against the space volume's free bytes, <see cref="VolumeSpace.Report"/>); the projects of its sequences, every
/// change of them told to connected clients as <c>projectChanged</c> (owner review 2, R8); a scan
/// queues thumbnails and proxies of what it indexes, as an upload does. Decoding is managed only (BRIEF §4.2). Recurring
/// work (the periodic scan, the nightly backup of an SQLite index, clean-ups) is queued by the server's system schedules
/// (<see cref="Jobs.ServerScheduleHost"/>, owner review 2, R10).
/// </summary>
public static class ArchiveModule
{
/// <summary>The change a conversion's Replace tells about a sequence (<c>sequenceChanged</c>).</summary>
private const string ConvertedChange = "converted";
/// <summary>Name the server writes into the archive's lease files.</summary>
public static string Owner { get; } = "server@" + Environment.MachineName;
@@ -40,6 +44,18 @@ public static class ArchiveModule
{
if (await db.Sequences.GetAsync(id, ct) is { } sequence)
events.Publish(new SequenceChangedEvent(id, change, sequence.FramesVersion, sequence.SettingsVersion));
// A conversion may leave settings Main has not taken yet (owner review 2, R8).
if (change == ConvertedChange) sp.GetService<ProjectCatchUp>()?.Touch(id);
},
// Every change of a sequence's projects reaches connected clients (owner review 2, R8): a workspace with that
// project checked out knows its home moved, the admin panel lists the projects again. Main's head written into the
// sequence's settings is a settings change for the clients that read those (an older client, a desktop's sync).
ProjectsChanged = async (changed, ct) =>
{
foreach (var change in changed.Changes)
events.Publish(new ProjectChangedEvent(changed.SequenceId, change.ProjectId, change.Change, change.HeadNumber, change.HeadVersionId));
if (changed.SettingsChanged && await db.Sequences.GetAsync(changed.SequenceId, ct) is { } sequence)
events.Publish(new SequenceChangedEvent(sequence.Id, "settings", sequence.FramesVersion, sequence.SettingsVersion));
},
Decoder = DecoderFactory.CreateServer(),
// Where a conversion writes (owner review 2, R7): the tighter of what the panel shows as the archive's free space
@@ -48,6 +64,8 @@ public static class ArchiveModule
FreeSpace = volumes is null ? null : volumes.WritableFree,
Owner = Owner,
ImagesAfterScan = true,
// An earlier release's PATCH wrote settings into the index alone: they are never reverted to project.json's.
IndexSettingsMayLead = true,
Parallelism = () => options.Parallelism,
CleanupSteps = [.. sp.GetServices<ICleanupStep>()],
// Next to the index in the data folder, where the daily backups always went.
@@ -18,7 +18,8 @@ namespace Chronos.Server.Storage;
/// handler takes the jobs whose every output a managed encoder produces (AVI MJPEG, image sequences, GIF, APNG); MP4
/// jobs wait for render nodes until none can take them (<see cref="RenderNodeAvailability"/>), and then render here as
/// MJPEG in AVI with a line in the job log (BRIEF §14.7). Renders recorded and Auto values changed here reach connected
/// clients as <c>sequenceChanged</c> events (§14.3).
/// clients as <c>sequenceChanged</c> events (§14.3); Auto values changed become Main's next version (owner review 2, R8). A
/// render of a project version places that version's settings on the sequence's frames and records the project and the version.
/// </summary>
public static class ProcessingModule
{
@@ -32,7 +33,7 @@ public static class ProcessingModule
var options = sp.GetRequiredService<ServerOptions>();
return new ProcessingService(db, new ProcessingOptions
{
Archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = ArchiveModule.Owner, Parallelism = () => options.Parallelism },
Archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = ArchiveModule.Owner, IndexSettingsMayLead = true, Parallelism = () => options.Parallelism },
// Analyses and renders take the parallelism as it is when they start, and the one job that runs has the host's
// memory budget for its frame window, as on the desktop (owner review 1).
Tune = basis =>
@@ -48,6 +49,8 @@ public static class ProcessingModule
{
if (await db.Sequences.GetAsync(id, ct) is { } sequence)
events.Publish(new SequenceChangedEvent(id, change, sequence.FramesVersion, sequence.SettingsVersion));
// Auto values an analysis wrote into the settings become Main's next version now (owner review 2, R8).
if (change == ProcessingOptions.SettingsChange) sp.GetService<ProjectCatchUp>()?.Touch(id);
},
});
});
@@ -0,0 +1,89 @@
using System.Collections.Concurrent;
using System.Threading.Channels;
using Chronos.Core.Archiving;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Projects;
namespace Chronos.Server.Storage;
/// <summary>
/// Brings a sequence's projects in step soon after its settings were written outside the projects (owner review 2, R8): an
/// older client's or a desktop sync's <c>PATCH /sequences/{id}</c>, an analysis's Auto values, a conversion. Main takes them
/// as an external version at once (<see cref="ProjectService.CatchUpAsync"/>), and connected clients hear
/// <c>projectChanged</c> without waiting for the next project call, which would catch up all the same. Only a sequence that
/// has its Main project already: Main is made when the projects are first read, never for every sequence an analysis or a
/// sync touches. One sequence at a time in the background; a sequence asked for again while it waits is caught up once; one
/// another writer holds is tried again a few times, then left to that next call. Nothing happens without the archive engine
/// (a test host without it).
/// </summary>
public sealed class ProjectCatchUp(IServiceProvider services, ILogger<ProjectCatchUp> logger) : BackgroundService
{
/// <summary>The waits before each new try of a sequence another writer holds.</summary>
private static readonly TimeSpan[] Retries = [TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(2)];
private readonly Channel<(Guid Id, int Attempt)> _queue = Channel.CreateUnbounded<(Guid Id, int Attempt)>(new UnboundedChannelOptions { SingleReader = true });
private readonly ConcurrentDictionary<Guid, byte> _waiting = new();
private CancellationToken _stopping;
/// <summary>Catches the projects of <paramref name="sequenceId"/> up soon (at once when nothing waits).</summary>
public void Touch(Guid sequenceId) => Enqueue(sequenceId, 0);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_stopping = stoppingToken;
try
{
await foreach (var (id, attempt) in _queue.Reader.ReadAllAsync(stoppingToken))
{
_waiting.TryRemove(id, out _);
await CatchUpAsync(id, attempt, stoppingToken);
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
// The server stops: what waits is caught up by the next project call.
}
}
private void Enqueue(Guid id, int attempt)
{
if (_waiting.TryAdd(id, 0)) _queue.Writer.TryWrite((id, attempt));
}
private async Task CatchUpAsync(Guid id, int attempt, CancellationToken cancellationToken)
{
if (services.GetService<ArchiveService>() is not { } archives) return;
try
{
if (await services.GetRequiredService<ChronosDatabase>().Projects.GetMainAsync(id, cancellationToken) is null) return;
await archives.Projects.CatchUpAsync(id, cancellationToken);
}
catch (LeaseUnavailableException) when (attempt < Retries.Length)
{
_ = RetryLaterAsync(id, attempt);
}
catch (Exception ex) when (ex is ProjectException or ArchiveOfflineException or SequenceFolderMovedException or LeaseUnavailableException)
{
// The sequence is gone, its archive offline or its folder elsewhere, or it stayed busy: the next project call catches up.
logger.LogDebug("The projects of sequence {Sequence} are caught up later: {Reason}", id, ex.Message);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogWarning(ex, "The projects of sequence {Sequence} could not be caught up", id);
}
}
private async Task RetryLaterAsync(Guid id, int attempt)
{
try
{
await Task.Delay(Retries[attempt], _stopping);
Enqueue(id, attempt + 1);
}
catch (OperationCanceledException)
{
// Stopping.
}
}
}
+12 -1
View File
@@ -12,7 +12,7 @@ namespace Chronos.Server.Storage;
/// <param name="archives">The archive engine whose sequence lease the filing takes; one of its own when none is registered.</param>
public sealed class RenderStore(ChronosDatabase db, ServerArchive archive, TimeProvider time, ArchiveService? archives = null)
{
private readonly ArchiveService _archives = archives ?? new ArchiveService(db, new ArchiveServiceOptions { Owner = ArchiveModule.Owner });
private readonly ArchiveService _archives = archives ?? new ArchiveService(db, new ArchiveServiceOptions { Owner = ArchiveModule.Owner, IndexSettingsMayLead = true });
/// <summary>
/// Moves <paramref name="stagedFile"/> (on the archive volume) to <c>&lt;sequence folder&gt;/exports/</c>, never
@@ -31,6 +31,15 @@ public sealed class RenderStore(ChronosDatabase db, ServerArchive archive, TimeP
/// <exception cref="FolderMovedException">The sequence is not in the folder the index has.</exception>
public Task<Render?> CommitAsync(Sequence sequence, string stagedFile, RenderResultRequest output, string producedBy, Guid id,
CancellationToken cancellationToken) =>
CommitAsync(sequence, stagedFile, output, producedBy, id, null, null, cancellationToken);
/// <summary>
/// As above, recording the project and the version rendered (owner review 2, R8: a render node's output of a job that names
/// them); null for a render of the sequence's own settings.
/// </summary>
/// <exception cref="FolderMovedException">The sequence is not in the folder the index has.</exception>
public Task<Render?> CommitAsync(Sequence sequence, string stagedFile, RenderResultRequest output, string producedBy, Guid id, Guid? projectId,
Guid? projectVersionId, CancellationToken cancellationToken) =>
_archives.UnderLeaseAsync(sequence, async row =>
{
if (row is null || string.IsNullOrEmpty(row.Folder) || ArchivePathGuard.Resolve(archive.Root, row.Folder.TrimEnd('/') + "/exports") is not { } exports)
@@ -55,6 +64,8 @@ public sealed class RenderStore(ChronosDatabase db, ServerArchive archive, TimeP
Bytes = output.Size,
Created = time.GetUtcNow(),
ProducedBy = producedBy,
ProjectId = projectId,
ProjectVersionId = projectVersionId,
};
await db.Renders.InsertAsync(render, cancellationToken);
return (Render?)render;