feat(workspace): render a project on this PC from its originals

A workspace project that holds its originals now renders locally
(JobKind.WorkspaceRender), so the full-resolution render no longer
waits on the home. This holds also when the home is a server.

- The handler reads its inputs under the project's lease. It refuses
  proxies-only media, and it refuses frames without an original,
  saying how many lack one. It renders into exports/ with unique
  names and a resumable checkpoint.
- Each output gets a ledger entry: SHA-256, the render id from
  RenderJobHandler.RenderId, and the version, recorded only when
  versions/ holds it and its hash verifies.
- After rendering, the handler queues a WorkspaceSend follow-up for
  the outputs it recorded. A cancel leaves no partial file.
- The editor routes Originals media to the local engine even for a
  server home, and lists those jobs beside the server's. It treats
  WorkspaceRender like Render for the toast and the reload, says
  "Sent home" when a send ends, and shows unsent ledger renders as
  "Not sent".
- Version on render saves a changed project as a version noted
  "Render" before it renders, and sends it with Sync automatically.
  With the setting off, the render behaves as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-04 16:03:05 +01:00
1 parent 0c51d11080
commit 59e7aca006
12 files changed
+779 -32

No files matched your search

+3
View File
@@ -327,6 +327,9 @@
ToolTip="{l:Loc Tooltips.Editor.Export.History}" Margin="6,0,0,0" Visibility="{Binding CanOpenHistory, Converter={StaticResource BoolToVisibility}}" />
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Link}" Content="{l:Loc Editor.Export.Reveal}" Command="{Binding RevealLastCommand}"
ToolTip="{l:Loc Tooltips.Editor.Render.Reveal}" Margin="6,0,0,0" Visibility="{Binding CanReveal, Converter={StaticResource BoolToVisibility}}" />
<TextBlock DockPanel.Dock="Right" Text="{l:Loc Editor.Render.NotSent}" Style="{StaticResource Text.Faint}" FontSize="{StaticResource Size.Chip}"
VerticalAlignment="Center" Margin="6,0,0,0" ToolTip="{Binding UnsentToolTip}"
Visibility="{Binding HasUnsent, Converter={StaticResource BoolToVisibility}}" />
<TextBlock Text="{Binding HistoryText}" Style="{StaticResource Text.Faint}" FontSize="{StaticResource Size.Chip}" TextTrimming="CharacterEllipsis" VerticalAlignment="Center"
ToolTip="{Binding HistoryText}" />
</DockPanel>
+13 -5
View File
@@ -634,7 +634,9 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
var export = batch ? RenderExport : RenderExport with { Batch = [] };
var requests = Session.RenderRequests(export);
foreach (var request in requests) await Session.SubmitAsync(request with { Priority = priority });
if (IsRemote) Shell.Notify(Loc.L("Editor.Render.QueuedServer", ServerName), requests[0].Label);
if (Session.Source is IProjectRenders { RendersLocally: true })
Shell.Notify(Loc.L("Editor.Render.QueuedLocal"), requests[0].Label, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
else if (IsRemote) Shell.Notify(Loc.L("Editor.Render.QueuedServer", ServerName), requests[0].Label);
else Shell.Notify(Loc.L("Editor.Render.Queued"), requests[0].Label, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
}
@@ -957,7 +959,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
private void RefreshSteps()
{
if (_disposed) return;
var facts = new PathFacts(Session.Content, Session.Advice, Session.Project, _jobs.Active(JobKind.DeepAnalyse), _jobs.Active(JobKind.Render),
var facts = new PathFacts(Session.Content, Session.Advice, Session.Project, _jobs.Active(JobKind.DeepAnalyse), _jobs.Active(JobKind.Render) ?? _jobs.Active(JobKind.WorkspaceRender),
_planned ? RenderBlockedReason : null, _rendered.Matches(Session.Project));
foreach (var tab in Tabs) tab.SetStep(EditPath.Of(tab.Key, facts));
Analysis.OnStepChanged();
@@ -1174,7 +1176,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
if (_disposed)
{
// Closed after the Jobs screen left this render's end to it (FollowsRender): said without a read.
if (job is { Kind: JobKind.Render, State: JobState.Done } && _jobs.IsActive(job.Id) && Shell.Jobs.ClaimRenderToast(job.Id))
if (job is { State: JobState.Done } && IsRender(job.Kind) && _jobs.IsActive(job.Id) && Shell.Jobs.ClaimRenderToast(job.Id))
AnnounceRender(job, read: false);
return;
}
@@ -1186,13 +1188,19 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
if (!wasActive) return;
if (job is { Kind: JobKind.DeepAnalyse, State: JobState.Done }) ClearVisited();
// A render this editor followed to its end is said here, with its output, unless the Jobs screen said it first.
if (job.State == JobState.Done) _ = ReloadAsync(job.Kind == JobKind.Render && Shell.Jobs.ClaimRenderToast(job.Id) ? job : null);
if (job.State == JobState.Done) _ = ReloadAsync(IsRender(job.Kind) && Shell.Jobs.ClaimRenderToast(job.Id) ? job : null);
// A local render's send home (phase 5c): said once, here or on the Jobs screen.
if (job is { Kind: JobKind.WorkspaceSend, State: JobState.Done } && Shell.Jobs.ClaimRenderToast(job.Id)) Shell.Notify(Loc.L("Editor.Render.SentHome"), Title);
// An analysis may have written its Auto values into the library's settings (Main): the project takes them or says so.
if (job.State == JobState.Done && _project is { } project) _ = project.JobEndedAsync(job);
else if (IsRemote && job.State is JobState.Failed or JobState.Cancelled) ReportServerJobEnded(job);
else if (IsRemote && job.Kind is not (JobKind.WorkspaceRender or JobKind.WorkspaceSend) && job.State is JobState.Failed or JobState.Cancelled)
ReportServerJobEnded(job);
});
}
/// <summary>A render of the sequence: at its home, or on this PC from a workspace project's originals (phase 5c).</summary>
private static bool IsRender(JobKind kind) => kind is JobKind.Render or JobKind.WorkspaceRender;
/// <summary>
/// The frames of the server sequence changed while it is open, or a workspace project's sync took a newer Chronos's
/// settings (any thread): everything that changes the project is disabled and says why, and a toast says so (for a
+8
View File
@@ -403,6 +403,14 @@ public sealed class ExportTab : EditorTab
? Loc.Plural("Editor.Export.History", renders.Count, Formatting.Date(renders[0].Created))
: Loc.L("Editor.Export.NoHistory");
/// <summary>A workspace project's renders made on this PC that are not at its home yet (phase 5c): "Not sent".</summary>
public bool HasUnsent => Editor.Session.Source is WorkspaceSequenceSource { UnsentRenders: > 0 };
/// <summary>Why the renders are not in the library (or on the server) yet, and that their files stay in the workspace.</summary>
public string? UnsentToolTip => Editor.Session.Source is WorkspaceSequenceSource { UnsentRenders: > 0 } source
? Loc.L(source.IsServerHome ? "Tooltips.Editor.Render.NotSent.Server" : "Tooltips.Editor.Render.NotSent")
: null;
public IReadOnlyList<string> Batch => Export.Batch;
/// <summary>Completes when the card estimates in flight are done.</summary>
+8 -4
View File
@@ -11,8 +11,8 @@ public sealed class SequenceJobs(Guid sequenceId)
{
private readonly Dictionary<Guid, Job> _active = [];
/// <summary>An analysis or render runs: settings wait.</summary>
public bool IsBusy => _active.Values.Any(j => j.State == JobState.Running);
/// <summary>An analysis or render runs: settings wait (a local render's send home does not hold them).</summary>
public bool IsBusy => _active.Values.Any(j => j.State == JobState.Running && j.Kind != JobKind.WorkspaceSend);
/// <summary>A deep analysis waits, runs or is paused.</summary>
public bool IsAnalysing => _active.Values.Any(j => j.Kind == JobKind.DeepAnalyse);
@@ -23,13 +23,17 @@ public sealed class SequenceJobs(Guid sequenceId)
/// <summary>The job of <paramref name="kind"/> to show, chosen as <see cref="Shown"/> is (the Edit path's steps).</summary>
public Job? Active(JobKind kind) => First(_active.Values.Where(j => j.Kind == kind));
/// <summary>An analysis or render of this sequence.</summary>
/// <summary>An analysis or render of this sequence, a workspace project's render on this PC or its send home (phase 5c).</summary>
public bool Concerns(Job job)
{
ArgumentNullException.ThrowIfNull(job);
return job.TargetIds.Contains(sequenceId) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render;
return job.TargetIds.Contains(sequenceId) && IsSequenceKind(job.Kind);
}
/// <summary>The kinds the editor follows.</summary>
public static bool IsSequenceKind(JobKind kind) =>
kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render or JobKind.WorkspaceRender or JobKind.WorkspaceSend;
/// <summary>The job is one of those that wait, run or are paused.</summary>
public bool IsActive(Guid jobId) => _active.ContainsKey(jobId);
+1 -1
View File
@@ -208,7 +208,7 @@ internal sealed class ServerJobs : IAsyncDisposable
_changed(job);
}
private bool Concerns(Job job) => job.TargetIds.Contains(_sequenceId) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render;
private bool Concerns(Job job) => job.TargetIds.Contains(_sequenceId) && SequenceJobs.IsSequenceKind(job.Kind);
/// <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)
+114 -11
View File
@@ -29,6 +29,9 @@ public interface IProjectRenders
{
/// <summary>The jobs that render <paramref name="export"/> of <paramref name="project"/> (the editor's settings, positions on the source's frames).</summary>
IReadOnlyList<ArchiveJobRequest> RenderRequests(Sequence sequence, ProjectSettings project, ExportSettings export, int sourceWidth, int sourceHeight);
/// <summary>The renders run on this PC (a workspace project holding its originals, phase 5c), whatever the home.</summary>
bool RendersLocally { get; }
}
/// <summary>
@@ -95,6 +98,8 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
private FramePhotos _photos = new([]);
private BundleWorkspace? _workspace;
private bool _readOnly;
private bool _holdsOriginals;
private int _unsent;
private int _disposed;
/// <param name="server">The server the project's home is (phase 5b); null for a project of this PC's archive.</param>
@@ -136,6 +141,15 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
/// <summary>Settings of a newer Chronos: shown, never saved.</summary>
public bool IsReadOnly => Volatile.Read(ref _readOnly);
/// <summary>
/// The media read last hold the originals (phase 5c): the project renders on this PC's engine from them, into its
/// <c>exports/</c>, and the renders are sent home after (<see cref="JobKind.WorkspaceRender"/>), also for a server home.
/// </summary>
public bool RendersLocally => Volatile.Read(ref _holdsOriginals);
/// <summary>The local renders of the project's ledger not at the home yet, as read last.</summary>
public int UnsentRenders => Volatile.Read(ref _unsent);
public bool IsOutdated => false;
/// <summary>The library's values and the editor's are asked about where both changed a setting, as a sync asks.</summary>
@@ -179,6 +193,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
IReadOnlyList<Render> renders = row is null ? [] : await _db.Renders.ListBySequenceAsync(home.SequenceId, cancellationToken);
return await Task.Run(() =>
{
renders = [.. renders, .. UnsentOf(session.Project, home.SequenceId)];
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();
@@ -278,6 +293,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
Created = r.Created,
ProducedBy = r.ProducedBy,
}).ToList() ?? [];
renders = [.. renders.Concat(UnsentOf(session.Project, home.SequenceId)).OrderByDescending(r => r.Created)];
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, [])
@@ -495,7 +511,9 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
/// <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);
ArgumentNullException.ThrowIfNull(request);
// A render from the workspace's originals and its send run on this PC's engine, whatever the home (phase 5c).
if (_server is not null && !RunsHere(request.Kind)) 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;
@@ -504,26 +522,40 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
/// <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 [];
var local = (await _db.Jobs.ListAsync(null, JobsListed, null, cancellationToken)).Items;
if (_server is null) return local;
// This PC's renders from the originals and their sends beside the server's jobs (phase 5c).
IReadOnlyList<Job> here = [.. local.Where(j => RunsHere(j.Kind))];
if (Api() is null || Volatile.Read(ref _serverJobs) is not { } jobs) return here;
try
{
return await jobs.ListAsync(cancellationToken);
return [.. (await jobs.ListAsync(cancellationToken)).Concat(here)];
}
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 [];
return here;
}
}
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 async Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken)
{
if (_server is not null && !await IsLocalJobAsync(jobId, cancellationToken)) await ServerJobsOrThrow().CancelAsync(jobId, cancellationToken);
else await (_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).CancelAsync(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);
public async Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken)
{
if (_server is not null && !await IsLocalJobAsync(jobId, cancellationToken)) await ServerJobsOrThrow().RetryAsync(jobId, cancellationToken);
else await (_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).ResumeAsync(jobId, cancellationToken);
}
/// <summary>The kinds a workspace project runs on this PC's engine whatever its home: a render from its originals and its send home.</summary>
private static bool RunsHere(JobKind kind) => kind is JobKind.WorkspaceRender or JobKind.WorkspaceSend;
/// <summary>A job of this PC's engine that runs here whatever the home (<see cref="RunsHere"/>).</summary>
private async Task<bool> IsLocalJobAsync(Guid jobId, CancellationToken cancellationToken) =>
await _db.Jobs.GetAsync(jobId, cancellationToken) is { } job && RunsHere(job.Kind);
/// <summary>
/// The render at the home (owner review 2, R8: edit with proxies, render where the originals are): one job per preset
@@ -542,6 +574,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
ArgumentNullException.ThrowIfNull(export);
var portable = ProjectContent.ToPortable(project with { Export = export }, Photos);
var hash = ProjectContent.Hash(portable);
if (RendersLocally && Workspace is { } workspace) return LocalRenderRequests(sequence, workspace.Home, portable, hash, export, sourceWidth, sourceHeight);
if (_server is not null)
{
if (InStepWithHome(project) is { } basis)
@@ -566,6 +599,75 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
return [.. requests.Select(r => r with { ParametersJson = WithoutVersion(r.ParametersJson) })];
}
/// <summary>
/// The render on this PC from the originals the workspace holds (phase 5c): one <see cref="JobKind.WorkspaceRender"/> per
/// preset with the project's portable settings, naming the head version of <c>versions/</c> when the settings are the
/// ones it holds (the render records it; an unsaved working state renders without a version), sent home after.
/// </summary>
private IReadOnlyList<ArchiveJobRequest> LocalRenderRequests(Sequence sequence, BundleHome home, string portable, string hash, ExportSettings export,
int sourceWidth, int sourceHeight)
{
var head = HeadVersion(hash);
var version = new ProjectVersion { Id = head ?? Guid.Empty, ProjectId = ProjectId, Number = 0, SettingsJson = portable, ContentHash = hash };
var root = _sync.Store.Root;
var server = home.IsArchive ? null : home.Server;
return
[
.. ProcessingJobs.RenderVersion(sequence, version, export, sourceWidth, sourceHeight).Select(r => WorkspaceJobs.Render(home.SequenceId,
r.Label ?? sequence.DisplayTitle, root, ProjectId, head, (head is null ? WithoutVersion(r.ParametersJson) : r.ParametersJson)!, server)),
];
}
/// <summary>The id of the newest version the workspace holds when it holds <paramref name="hash"/>; null otherwise.</summary>
private Guid? HeadVersion(string hash)
{
try
{
return Project.Versions() is [.., var last] && string.Equals(last.ContentHash, hash, StringComparison.OrdinalIgnoreCase) ? last.Id : null;
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Warning("editor", $"The versions of workspace project {ProjectId} cannot be read; the render names none", ex);
return null;
}
}
/// <summary>The local renders of the project's ledger not at the home yet, as renders of <paramref name="sequenceId"/> (newest first).</summary>
private IReadOnlyList<Render> UnsentOf(WorkspaceProject project, Guid sequenceId)
{
try
{
var unsent = project.ReadRenders().Unsent;
Volatile.Write(ref _unsent, unsent.Count);
return
[
.. unsent.OrderByDescending(e => e.Rendered).Select(e => new Render
{
Id = e.RenderId,
SequenceId = sequenceId,
PresetName = e.PresetName,
OutputPath = project.ExportFile(e.File),
Codec = e.Codec,
Width = e.Width,
Height = e.Height,
Fps = e.Fps,
DurationSeconds = e.DurationSeconds,
Bytes = e.Size,
Created = e.Rendered,
ProducedBy = Environment.MachineName,
ProjectId = e.ProjectId,
ProjectVersionId = e.ProjectVersionId,
}),
];
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Warning("editor", $"The render ledger of workspace project {ProjectId} cannot be read", ex);
Volatile.Write(ref _unsent, 0);
return [];
}
}
/// <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.
@@ -643,6 +745,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
_photos = index.Photos;
_standIns = [.. index.Frames.Where(f => f.IsStandIn).Select(f => f.Id)];
_workspace = workspace;
_holdsOriginals = index.HoldsOriginals;
changed = _readOnly != readOnly;
_readOnly = readOnly;
}
+1 -1
View File
@@ -303,7 +303,7 @@ public sealed class JobsViewModel : SectionViewModel
else if (before != JobState.Failed && !IsSelected) _unseenFailures.Add(job.Id);
var notice = JobNotices.For(before, job);
// A flush can take the end before the editor that follows the render has seen it: the editor says it, with its output.
if (notice == JobNotice.Done && job.Kind == JobKind.Render
if (notice == JobNotice.Done && job.Kind is JobKind.Render or JobKind.WorkspaceRender or JobKind.WorkspaceSend
&& (Shell.Sequence.Editor?.FollowsRender(job.Id) == true || !ClaimRenderToast(job.Id))) return;
_endings.Add(notice, job);
}
@@ -252,12 +252,15 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
/// <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.
/// the server could not take them or no longer has the project, or a conflict waits. A project of this PC's archive,
/// or one rendered on this PC from its originals (phase 5c), renders as it is: true. With Settings › Workspace › Version
/// on render, a changed project is saved as a version first (<see cref="SaveForRenderAsync"/>).
/// </summary>
public async Task<bool> ReadyToRenderAsync()
{
if (!IsServerHome) return true;
if (_host.Settings.WorkspaceVersionOnRender && !await SaveForRenderAsync()) return false;
// Rendered on this PC from the originals the workspace holds (phase 5c): the project renders as it is.
if (!IsServerHome || _source.RendersLocally) return true;
await StoreEditAsync();
var status = await _host.StatusAsync(ProjectId);
if (_disposed) return false;
@@ -296,6 +299,45 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
return !_disposed && _source.InStepWithHome(_session.Project) is not null;
}
/// <summary>
/// Settings › Workspace › Version on render (phase 5c): a project changed since its last version is saved as a version
/// noted "Render" before its render, and sent at once with Sync automatically when the home can be reached (out of reach,
/// it waits here). False when it could not be saved, or the sync met a conflict to settle first.
/// </summary>
private async Task<bool> SaveForRenderAsync()
{
await StoreEditAsync();
var status = await _host.StatusAsync(ProjectId);
if (_disposed) return false;
Apply(status);
if (!status.Modified || !CanSaveVersion) return true;
WorkspaceSaveResult result;
try
{
result = await _host.SaveVersionAsync(ProjectId, Loc.L("Editor.Workspace.RenderNote"));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Project {ProjectId} could not be saved before its render", ex);
_ui.Notify(Loc.L("Editor.Workspace.RenderHeld"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
return false;
}
if (_disposed) return false;
Apply(result.Status);
if (result.Synced is { } taken) await TakeAsync(taken);
if (result.Version is { } version)
{
// The home numbers what it stores: the last one sent is this version.
var number = result.Synced is { Pushed.Count: > 0 } synced ? synced.Pushed[^1].Number : version.Number;
_ui.Notify(Loc.L("Editor.Workspace.SavedForRender", Formatting.Count(number)), Name);
}
if (result.SyncError is { } error)
_ui.Notify(Loc.L("Editor.Workspace.NotSent"), WorkspaceText.Failure(error, IsServerHome), isError: error is not HomeUnavailableException);
if (result.Status.Conflict is not { } conflict) return true;
AskConflict(conflict);
return false;
}
/// <summary>
/// Saves the working state as a version with <paramref name="note"/>, sent at once with Sync automatically; what the
/// sync took from the home comes into the editor, a conflict it met is asked about.
@@ -1,24 +1,286 @@
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Chronos.Core.Analysis.Deep;
using Chronos.Core.Archiving;
using Chronos.Core.Export;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Processing.Jobs;
using SequenceFrames = Chronos.Data.Processing.SequenceFrames;
namespace Chronos.Data.Workspaces;
/// <summary>
/// <see cref="JobKind.WorkspaceRender"/> (phase 5c, <see cref="WorkspaceJobs.Render"/>): a workspace project rendered on this
/// PC from the originals its media hold, as <see cref="Processing.Jobs.RenderJobHandler"/> renders an archive's sequence,
/// into the project's <c>exports/</c> (each output written as <c>.part</c>, then renamed), each output hashed and recorded in
/// the project's ledger (<see cref="WorkspaceRenders"/>, its id <c>RenderJobHandler.RenderId(jobId, index)</c>), then a
/// <see cref="JobKind.WorkspaceSend"/> queued with the new ids. Media without an original for every placed frame are refused.
/// into the project's <c>exports/</c> (each output written by the encoder under a hidden temporary name, then renamed), each
/// output hashed and recorded in the project's ledger (<see cref="WorkspaceRenders"/>, its id
/// <c>RenderJobHandler.RenderId(jobId, index)</c>), then a <see cref="JobKind.WorkspaceSend"/> queued with the new ids.
/// Media without an original for every placed frame are refused. The project's lease is held while the inputs are read
/// and while each ledger entry is written, not for the whole render: the editor keeps saving its working state meanwhile.
/// The settings rendered are the ones the job embeds (the editor's portable settings), else the version it names from
/// <c>versions/</c>; the version is recorded only when <c>versions/</c> holds it with the content hash of what rendered.
/// Checkpoint: the entries recorded and the output being written; a resumed job removes that output's leftovers (never one
/// the ledger names) and renders only what is not recorded yet.
/// </summary>
internal sealed class WorkspaceRenderJobHandler(ChronosDatabase db, ArchiveService archives, WorkspaceJobOptions options) : IJobHandler
{
private static readonly TimeSpan LockWait = TimeSpan.FromMinutes(2);
public JobKind Kind => JobKind.WorkspaceRender;
public Task RunAsync(JobContext context)
public async Task RunAsync(JobContext context)
{
ArgumentNullException.ThrowIfNull(context);
_ = (db, archives, options);
throw new NotImplementedException("Local renders of a workspace project come with phase 5c (P2).");
// The index and the archive engine are not read: everything a local render needs is in the workspace project.
_ = (db, archives);
var cancellation = context.Cancellation;
var parameters = WorkspaceJobs.RenderParameters(context.Job) ?? throw new InvalidDataException(Loc.L("Errors.Workspace.JobParameters"));
var (render, export) = ProcessingJobs.ReadRender(parameters.RenderJson);
var store = new WorkspaceStore(parameters.WorkspaceRoot);
var project = store.Find(parameters.ProjectId) ?? throw new InvalidOperationException(Loc.L("Errors.Workspace.RenderProject"));
var inputs = await ReadInputsAsync(project, parameters, render, cancellation).ConfigureAwait(false);
var (sequence, frames, settings, versionId) = (inputs.Sequence, inputs.Frames, inputs.Settings, inputs.VersionId);
// A local render's outputs stay in the project's exports, from where they are sent home.
var projectSettings = ProjectStore.Parse(settings) with { Export = export with { Folder = null } };
var settingsJson = projectSettings.ToJson();
var settingsHash = ProjectContent.Hash(inputs.Portable);
var exports = project.ExportsDirectory;
Directory.CreateDirectory(exports);
using var names = new OutputNames();
var all = RenderJobHandler.Targets(projectSettings.Export, render.PresetName);
var resume = RenderCheckpoint.Parse(context.Checkpoint);
var done = resume.Done.ToList();
var ledger = project.ReadRenders();
for (var i = 0; i < all.Count; i++)
{
if (!done.Contains(i) && ledger.Find(RenderJobHandler.RenderId(context.Job.Id, i)) is not null) done.Add(i);
}
if (resume is { Pending: { } pending, PendingOutput: { } chosen } && !done.Contains(pending) && Inside(exports, chosen) && names.TryReserve(chosen))
{
Discard(chosen, keepOutput: ledger.Entries.Any(e => SamePath(project.ExportFile(e.File), chosen)));
names.Release(chosen);
}
var targets = all.Select((t, i) => (i, t)).Where(t => !done.Contains(t.i)).ToList();
var recorded = new List<Guid>();
if (targets.Count > 0)
{
string? writing = null;
IReadOnlyList<TargetOutcome> outcomes;
try
{
await using var renderer = new SequenceRender(frames, projectSettings, inputs.Analysis, options.Processing, originals: true, companions: null);
outcomes = await renderer.RenderAllAsync(
targets,
(target, setup) => names.Reserve(taken => ExportNaming.OutputPath(projectSettings.Export, exports, SequenceRender.NameContext(sequence, target, setup),
name => taken(name) || ledger.Entries.Any(e => SamePath(project.ExportFile(e.File), name)))),
(index, path) =>
{
writing = path;
return context.CheckpointAsync(new RenderCheckpoint(done, index, path).ToJson(), context.Done, context.Total);
},
async (index, target, result) =>
{
// The output is complete: recorded even if the job is being cancelled, so it is never orphaned.
var id = RenderJobHandler.RenderId(context.Job.Id, index);
var entry = await EntryAsync(project, context.Job.Id, id, target, result, versionId, settingsHash).ConfigureAwait(false);
using (await project.LockAsync(LockWait, CancellationToken.None).ConfigureAwait(false))
{
ledger = project.ReadRenders().With(entry);
project.WriteRenders(ledger);
}
done.Add(index);
recorded.Add(id);
writing = null;
await context.CheckpointAsync(new RenderCheckpoint(done, null, null).ToJson(), context.Done, context.Total).ConfigureAwait(false);
context.Log(Loc.L("Export.Log.Rendered", target.PresetName, Path.GetFileName(result.OutputPath)));
foreach (var remark in SequenceRender.Remarks(result)) context.Log(remark);
},
context.ReportAsync,
cancellation).ConfigureAwait(false);
if (renderer.StandIns.Count > 0)
context.Log(Loc.L("Export.Log.StandIns", string.Join(", ", renderer.StandIns.Select(i => (i + 1).ToString(Loc.Culture)))));
}
catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
{
// What the encoder was writing goes; every output recorded stays, and a resumed job renders the rest.
if (writing is { } partial) Discard(partial, keepOutput: true);
await QueueSendAsync(context, parameters, sequence, recorded).ConfigureAwait(false);
throw;
}
var failed = outcomes.Where(o => o.Error is not null).ToList();
foreach (var outcome in failed) context.Log(Loc.L("Export.Log.Failed", outcome.Target.PresetName, outcome.Error));
await QueueSendAsync(context, parameters, sequence, recorded).ConfigureAwait(false);
if (failed.Count > 0)
throw new InvalidOperationException(failed.Count == 1 ? failed[0].Error : Loc.L("Errors.Render.Failed", failed.Count, outcomes.Count));
}
}
/// <summary>What the render reads, taken under the project's lease so the media, the versions and the project file agree.</summary>
private sealed record Inputs(Sequence Sequence, SequenceFrames Frames, string Settings, string Portable, Guid? VersionId, DeepAnalysisReport? Analysis);
/// <summary>
/// The sequence over the workspace's originals, the settings to render (placed on its frames) and the version they are,
/// read under the project's lease.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The project is gone (<c>Errors.Workspace.RenderProject</c>), holds no originals (<c>Errors.Workspace.OriginalsMissing</c>),
/// lacks the original of a frame the render places (<c>Errors.Workspace.RenderNoOriginals</c>, with their number), or the
/// version the job names is not in <c>versions/</c> (<c>Errors.Workspace.RenderVersion</c>).
/// </exception>
private static async Task<Inputs> ReadInputsAsync(WorkspaceProject project, WorkspaceRenderParameters parameters, Protocol.RenderJobParameters render,
CancellationToken cancellationToken)
{
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
if (!File.Exists(project.BundlePath)) throw new InvalidOperationException(Loc.L("Errors.Workspace.RenderProject"));
var bundle = project.ReadBundle();
var workspace = bundle.Workspace!;
var media = project.ReadMedia();
if (media is not { HoldsOriginals: true })
throw new InvalidOperationException(Loc.L(workspace.Home.IsArchive ? "Errors.Workspace.OriginalsMissing" : "Errors.Workspace.OriginalsMissing.Server"));
var versions = project.Versions();
var named = parameters.ProjectVersionId ?? render.ProjectVersionId;
var version = named is { } id ? versions.FirstOrDefault(v => v.Id == id) : null;
string portable;
if (render.SettingsJson is { Length: > 0 } embedded) portable = embedded;
else if (named is not null) portable = version?.SettingsJson ?? throw new InvalidOperationException(Loc.L("Errors.Workspace.RenderVersion"));
else portable = versions.Count > 0 ? versions[^1].SettingsJson : ProjectContent.ToPortable(bundle.Project, media.Photos);
// Recorded only for the settings it holds (a version is never named for settings it did not render).
Guid? versionId = version is not null && ProjectContent.Verifies(portable, version.ContentHash) ? version.Id : null;
var settings = portable.Contains("pendingFrames", StringComparison.OrdinalIgnoreCase) ? Place(portable, media.Photos) : portable;
var placed = ProjectStore.Parse(settings);
var excluded = placed.ExcludedFrames.ToHashSet();
var lacking = media.Frames.Count(f => f.Original is null && !excluded.Contains(f.Index) && (f.Flags & SequenceFrames.NotRendered) == 0);
if (lacking > 0) throw new InvalidOperationException(Loc.L("Errors.Workspace.RenderNoOriginals", lacking));
var frames = media.ToOriginalFrames();
var files = media.Frames.Select(f => f.Original is { } original ? project.MediaFile(original) : null).ToList();
var sequence = SequenceOf(bundle, media, frames);
return new Inputs(sequence, new SequenceFrames(sequence, frames, files), settings, portable, versionId, Analysis(project, frames.Count));
}
}
/// <summary>The home's sequence as the project file and the media name it (the workspace keeps no index row of it).</summary>
private static Sequence SequenceOf(ProjectBundle bundle, WorkspaceMedia media, IReadOnlyList<Frame> frames)
{
var times = frames.Where(f => f.CapturedAt is not null).Select(f => f.CapturedAt!.Value).Order().ToList();
var home = bundle.Workspace!.Home;
return new Sequence
{
Id = home.SequenceId,
ArchiveId = bundle.Archive.Id,
Title = bundle.Sequence.Title,
Folder = bundle.Sequence.Folder,
FrameCount = frames.Count,
FirstCapture = times.Count > 0 ? times[0] : null,
LastCapture = times.Count > 0 ? times[^1] : null,
FramesVersion = media.FramesVersion,
Origin = home.IsArchive ? SequenceOrigin.Local : SequenceOrigin.Server,
};
}
/// <summary>The deep report the copy brought from the home, when it describes these frames; null otherwise.</summary>
private static DeepAnalysisReport? Analysis(WorkspaceProject project, int frameCount)
{
if (!File.Exists(project.AnalysisPath)) return null;
try
{
var report = DeepAnalysisReport.Load(project.AnalysisPath);
return report.FrameCount == frameCount ? report : null;
}
catch (Exception ex) when (ex is IOException or InvalidDataException or JsonException or UnauthorizedAccessException)
{
Core.Diagnostics.Log.Warning("workspace", $"{project.AnalysisPath} cannot be read", ex);
return null;
}
}
/// <summary>Portable settings placed on the media's frames; others as they are.</summary>
private static string Place(string portable, FramePhotos photos)
{
try
{
return ProjectContent.Place(portable, photos);
}
catch (JsonException)
{
// Not a project: reading it says so.
return portable;
}
}
/// <summary>The ledger entry of a finished output: hashed as it is on the disk now.</summary>
private static async Task<WorkspaceRenderEntry> EntryAsync(WorkspaceProject project, Guid jobId, Guid renderId, ExportTarget target, RenderResult result,
Guid? versionId, string settingsHash)
{
var sha = await HashAsync(result.OutputPath).ConfigureAwait(false);
var file = Path.GetRelativePath(project.ExportsDirectory, result.OutputPath).Replace('\\', '/');
return new WorkspaceRenderEntry(renderId, jobId, file, sha, result.Bytes, target.PresetName, result.Codec.ToString(), result.Width, result.Height,
result.FrameRate.Value, result.DurationSeconds, project.ProjectId, versionId, settingsHash, DateTimeOffset.UtcNow);
}
/// <summary>
/// The SHA-256 of an output: of the file, or, for an image sequence's folder, of its files' relative paths and SHA-256 in
/// order (a send checks the folder the same way).
/// </summary>
internal static async Task<string> HashAsync(string output)
{
if (File.Exists(output)) return await ContentHash.Sha256Async(output, cancellationToken: CancellationToken.None).ConfigureAwait(false);
var listing = new StringBuilder();
foreach (var file in Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories).Order(StringComparer.Ordinal))
{
var sha = await ContentHash.Sha256Async(file, cancellationToken: CancellationToken.None).ConfigureAwait(false);
listing.Append(Path.GetRelativePath(output, file).Replace('\\', '/')).Append(' ').Append(sha).Append('\n');
}
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(listing.ToString())));
}
/// <summary>Queues the send home of the renders this run recorded, whatever stops the job now (they are done).</summary>
private static async Task QueueSendAsync(JobContext context, WorkspaceRenderParameters parameters, Sequence sequence, List<Guid> recorded)
{
if (recorded.Count == 0) return;
var send = WorkspaceJobs.Send(sequence.Id, sequence.DisplayTitle, parameters.WorkspaceRoot, parameters.ProjectId, [.. recorded],
parameters.Server, context.Job.Priority);
await context.EnqueueFollowUpAsync(send.Kind, send.Targets, send.Label, send.ParametersJson, send.Priority, CancellationToken.None).ConfigureAwait(false);
}
private static bool Inside(string folder, string path)
{
var relative = Path.GetRelativePath(folder, path);
return !relative.StartsWith("..", StringComparison.Ordinal) && !Path.IsPathRooted(relative);
}
private static bool SamePath(string a, string b) =>
string.Equals(Path.GetFullPath(a), Path.GetFullPath(b), OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
/// <summary>
/// Removes what an interrupted attempt left of <paramref name="output"/>: the encoder's hidden temporary file or folder,
/// and an output completed but never recorded (it renders again under the same name) unless <paramref name="keepOutput"/>.
/// </summary>
private static void Discard(string output, bool keepOutput)
{
var parent = Path.GetDirectoryName(output);
if (parent is null || !Directory.Exists(parent)) return;
var leftovers = Directory.EnumerateFileSystemEntries(parent, "." + Path.GetFileName(output) + ".*.tmp").ToList();
if (!keepOutput) leftovers.Add(output);
foreach (var leftover in leftovers)
{
try
{
if (Directory.Exists(leftover)) Directory.Delete(leftover, recursive: true);
else if (File.Exists(leftover)) File.Delete(leftover);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Core.Diagnostics.Log.Warning("workspace", $"{leftover} could not be removed", ex);
}
}
}
}
@@ -137,7 +137,7 @@ public sealed class ServerHomeTests(TestContext context)
public async Task TheEditorFollowsTheServerAndRendersOnlyWhatItHolds()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false, WorkspaceVersionOnRender = false });
var server = new FakeServer(bed);
Connect(host, server);
var projectId = await CheckoutAsync(bed, host);
@@ -0,0 +1,128 @@
using System.Globalization;
using System.IO;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.App.Workspace;
using Chronos.Core.Export;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Processing;
using Chronos.Data.Workspaces;
using Chronos.Protocol.Client;
using Chronos.Testing;
namespace Chronos.App.Tests.Workspace;
/// <summary>
/// Phase 5c in Edit: a workspace project that holds its originals renders on this PC (<see cref="JobKind.WorkspaceRender"/>),
/// also when its home is a server, and Settings › Workspace › Version on render saves a changed project as a version first.
/// </summary>
[Category("workspace")]
public sealed class WorkspaceLocalRenderTests(TestContext context)
{
private const string Server = "https://nas.test:8443";
private static readonly ExportSettings Mjpeg = new()
{
Preset = new Auto<string>().WithManual("mjpeg-avi"),
Overrides = new ExportOverrides { Width = 96, Height = 64 },
NameTemplate = "clip-{codec}",
};
static WorkspaceLocalRenderTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
[Test]
public async Task TheOriginalsRenderOnThisPcEvenForAServerHome()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false, WorkspaceVersionOnRender = false });
var checkout = await host.CheckoutAsync(bed.SequenceId, null, null, BundleMedia.Originals, cancellationToken: bed.Ct);
await bed.WaitForJobAsync(checkout.Copy.Id);
var projectId = checkout.Project.Id;
// Named the server's, as a copy downloaded from the server leaves it.
var folder = host.Store.Find(projectId)!;
var bundle = folder.ReadBundle();
var home = new BundleHome(BundleHome.ServerKind, bed.SequenceId, null, Server);
folder.WriteBundle(bundle with { Workspace = bundle.Workspace! with { Home = home } });
// Not signed in to the server: a render from the originals runs here all the same.
var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
new WorkspaceServerHome((IRemoteSequenceApi?)null));
var content = await source.LoadAsync(bed.Ct);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
await using (session)
{
Assert.True(source is { IsServerHome: true, RendersLocally: true, UnsentRenders: 0 });
var requests = session.RenderRequests(Mjpeg);
var request = requests.Single();
Assert.Equal(JobKind.WorkspaceRender, request.Kind);
Assert.SequenceEqual([bed.SequenceId], request.Targets);
var parameters = Assert.NotNull(WorkspaceJobs.RenderParameters(new Job { Id = Guid.CreateVersion7(), Kind = request.Kind, ParametersJson = request.ParametersJson }));
Assert.Equal((projectId, host.Store.Root, Server), (parameters.ProjectId, parameters.WorkspaceRoot, parameters.Server));
var (render, _) = ProcessingJobs.ReadRender(parameters.RenderJson);
Assert.NotNull(render.SettingsJson, "the portable settings travel with the job");
// Queued on this PC's engine and listed beside the server's jobs (the render itself is the Data tests': this bed decodes nothing).
var jobId = await source.SubmitAsync(request, bed.Ct);
var queued = Assert.NotNull(await bed.Db.Jobs.GetAsync(jobId, bed.Ct));
Assert.Equal(JobKind.WorkspaceRender, queued.Kind);
Assert.Contains(await source.ListJobsAsync(bed.Ct), j => j.Id == jobId);
await WorkspaceTestBed.UntilAsync(() => bed.Db.Jobs.GetAsync(jobId).GetAwaiter().GetResult()?.State is JobState.Done or JobState.Failed, "the render ends");
// A render the ledger holds and the home has not taken: listed with the others, not sent.
var output = Path.Combine(folder.ExportsDirectory, "clip-MJPEG.avi");
Directory.CreateDirectory(folder.ExportsDirectory);
await File.WriteAllBytesAsync(output, [1, 2, 3], bed.Ct);
var entry = new WorkspaceRenderEntry(Guid.CreateVersion7(), jobId, "clip-MJPEG.avi", new string('0', 64), 3, "Custom", "Mjpeg", 96, 64, 25, 0.16,
projectId, null, null, DateTimeOffset.UtcNow);
using (await folder.LockAsync(TimeSpan.FromSeconds(TestTiming.Budget(10)), bed.Ct)) folder.WriteRenders(WorkspaceRenders.Empty.With(entry));
var reread = await source.LoadAsync(bed.Ct);
Assert.Equal(1, source.UnsentRenders);
Assert.Equal((entry.RenderId, output), (reread.Renders[0].Id, reread.Renders[0].OutputPath));
}
}
[Test]
public async Task VersionOnRenderSavesAChangedProjectFirst()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var settings = new AppSettings();
Assert.True(settings is { WorkspaceVersionOnRender: true, WorkspaceAutoSync: true }, "on by default");
var host = bed.Host(settings);
var projectId = await bed.CheckoutAsync(host);
var (source, session) = await bed.OpenAsync(host, projectId);
var ui = new RecordingUi();
await using (session)
using (var menu = new ProjectMenuViewModel(host, source, session, ui))
{
await menu.RefreshAsync();
var folder = host.Store.Find(projectId)!;
var before = folder.Versions().Count;
// Nothing changed: nothing saved.
Assert.True(await menu.ReadyToRenderAsync());
Assert.Equal(before, folder.Versions().Count);
// Changed: saved as a version noted Render and sent (Sync automatically); the render names it.
Assert.True(session.SetHero(2));
Assert.True(await session.FlushAsync());
Assert.True(await menu.ReadyToRenderAsync());
var saved = folder.Versions()[^1];
Assert.Equal((before + 1, Loc.L("Editor.Workspace.RenderNote")), (folder.Versions().Count, saved.Note));
Assert.Equal(WorkspaceState.InSync, menu.Status!.State);
Assert.Equal(Loc.L("Editor.Workspace.SavedForRender", Formatting.Count(folder.ReadBundle().Workspace!.Base!.Number)), ui.Toasts[^1].Title);
var (render, _) = ProcessingJobs.ReadRender(session.RenderRequests(session.Project.Export)[0].ParametersJson);
Assert.Equal(folder.ReadBundle().Workspace!.Base!.VersionId, render.ProjectVersionId);
// Off: the project renders as it is, no version saved.
settings.WorkspaceVersionOnRender = false;
Assert.True(session.SetHero(3));
Assert.True(await session.FlushAsync());
Assert.True(await menu.ReadyToRenderAsync());
Assert.Equal(before + 1, folder.Versions().Count);
Assert.Empty(ui.Confirmations);
}
}
}
@@ -0,0 +1,189 @@
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Export;
using Chronos.Core.Imaging;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Processing.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Tests.Processing;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.Data.Tests.Workspaces;
/// <summary>
/// A workspace project rendered on this PC from the originals its media hold (phase 5c, <see cref="JobKind.WorkspaceRender"/>):
/// into its exports, recorded in its ledger and sent home after; refused without the originals; a cancel leaves nothing half written.
/// </summary>
[Category("workspace")]
public sealed class WorkspaceRenderTests(TestContext context)
{
private const int Frames = 24;
private static readonly ExportSettings Mjpeg = new()
{
Preset = new Auto<string>().WithManual("mjpeg-avi"),
Overrides = new ExportOverrides { Width = 96, Height = 64 },
NameTemplate = "clip-{codec}",
};
private static SyntheticSequence Scene() => SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = Frames, StartEv = 0.5, EndEv = -0.5 });
private sealed record Bed(ProcessingFixture Fx, Sequence Sequence, WorkspaceStore Store, WorkspaceProject Project, JobEngine Engine) : IAsyncDisposable
{
public async ValueTask DisposeAsync()
{
await Engine.DisposeAsync();
await Fx.DisposeAsync();
}
}
/// <summary>A sequence of the archive, Main checked out into a workspace with <paramref name="media"/> copied, and an engine running every handler.</summary>
private async Task<Bed> BedAsync(string media = BundleMedia.Originals, Action<ProcessingFixture, Sequence>? beforeCopy = null)
{
var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Scene());
var engine = new JobEngine(fx.Db,
[
.. fx.Archive.Service.CreateJobHandlers(), .. fx.Processing.CreateJobHandlers(),
.. WorkspaceJobs.CreateHandlers(fx.Db, fx.Archive.Service, null, new WorkspaceJobOptions(fx.Processing.Options, () => false)),
],
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
await engine.StartAsync(fx.Ct);
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory("render-ws"), "workspace"));
var sync = new WorkspaceSync(store, "test") { LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)) };
var home = new ArchiveProjectHome(fx.Db, fx.Archive.Service.Projects, sequence.Id);
var main = await fx.Archive.Service.Projects.MainAsync(sequence.Id, fx.Ct);
var project = await sync.CheckoutAsync(home, main.Id, media, fx.Ct);
beforeCopy?.Invoke(fx, sequence);
var copy = await engine.EnqueueAsync(WorkspaceJobs.Copy(sequence, store.Root, main.Id, media), cancellationToken: fx.Ct);
await fx.WaitForAsync(copy.Id, JobState.Done);
return new Bed(fx, sequence, store, project, engine);
}
private static ArchiveJobRequest RenderRequest(Bed bed, Guid? versionId = null)
{
var json = ProcessingJobs.Render(bed.Sequence, Mjpeg, 96, 64, new ProjectSettings()).ParametersJson!;
return WorkspaceJobs.Render(bed.Sequence.Id, bed.Sequence.DisplayTitle, bed.Store.Root, bed.Project.ProjectId, versionId, json);
}
[Test]
public async Task ARenderFromTheOriginalsIsWrittenToExportsRecordedAndSentAfter()
{
await using var bed = await BedAsync();
var fx = bed.Fx;
var job = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: fx.Ct);
await fx.WaitForAsync(job.Id, JobState.Done);
var output = Path.Combine(bed.Project.ExportsDirectory, "clip-MJPEG.avi");
Assert.FileExists(output);
Assert.Empty(Directory.EnumerateFileSystemEntries(bed.Project.ExportsDirectory, ".*"));
var entry = bed.Project.ReadRenders().Entries.Single();
Assert.Equal(RenderJobHandler.RenderId(job.Id, 0), entry.RenderId);
Assert.Equal((job.Id, "clip-MJPEG.avi", new FileInfo(output).Length, WorkspaceRenderEntry.Pending, bed.Project.ProjectId),
(entry.JobId, entry.File, entry.Size, entry.State, entry.ProjectId));
Assert.Equal(await Chronos.Core.Archiving.ContentHash.Sha256Async(output), entry.Sha256);
Assert.Equal(("Mjpeg", 96, 64), (entry.Codec, entry.Width, entry.Height));
Assert.Null(entry.ProjectVersionId, "the working state the job embeds is no version this workspace holds");
Assert.Empty(await fx.Db.Renders.ListBySequenceAsync(bed.Sequence.Id, fx.Ct));
// The send home follows with the new render.
var send = (await fx.Db.Jobs.ListAsync(null, 50, null, fx.Ct)).Items.Single(j => j.Kind == JobKind.WorkspaceSend);
var sent = Assert.NotNull(WorkspaceJobs.SendParameters(send));
Assert.SequenceEqual([entry.RenderId], sent.RenderIds);
Assert.Equal((bed.Project.ProjectId, bed.Store.Root), (sent.ProjectId, sent.WorkspaceRoot));
// The same render of the archive's own sequence: the same pictures, at the same size and length.
var archive = await bed.Engine.EnqueueAsync(ProcessingJobs.Render(bed.Sequence, Mjpeg, 96, 64), cancellationToken: fx.Ct);
await fx.WaitForAsync(archive.Id, JobState.Done);
var row = (await fx.Db.Renders.ListBySequenceAsync(bed.Sequence.Id, fx.Ct)).Single();
Assert.Equal((row.Width, row.Height, row.Fps, row.DurationSeconds), (entry.Width, entry.Height, entry.Fps, entry.DurationSeconds));
// Again: another name, the first output and its entry kept.
var again = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: fx.Ct);
await fx.WaitForAsync(again.Id, JobState.Done);
var entries = bed.Project.ReadRenders().Entries;
Assert.Equal(2, entries.Count);
Assert.True(entries[1].File != entries[0].File, entries[1].File);
Assert.Equal(entry, entries[0]);
}
[Test]
public async Task AVersionHeldInTheWorkspaceIsRecordedWithTheRender()
{
await using var bed = await BedAsync();
var fx = bed.Fx;
var (_, sync) = (bed.Store, new WorkspaceSync(bed.Store, "test"));
var session = await sync.OpenAsync(bed.Project.ProjectId, fx.Ct);
await sync.SaveAsync(bed.Project.ProjectId, session.Working with { ExcludedFrames = [2] }, fx.Ct);
var version = Assert.NotNull(await sync.CommitAsync(bed.Project.ProjectId, "Render", cancellationToken: fx.Ct));
var json = ProcessingJobs.Render(bed.Sequence, Mjpeg, 96, 64).ParametersJson!;
// The job names the version alone: the settings come from versions/.
var stripped = System.Text.Json.Nodes.JsonNode.Parse(json)!.AsObject();
stripped.Remove("settingsJson");
var job = await bed.Engine.EnqueueAsync(
WorkspaceJobs.Render(bed.Sequence.Id, bed.Sequence.DisplayTitle, bed.Store.Root, bed.Project.ProjectId, version.Id, stripped.ToJsonString()), cancellationToken: fx.Ct);
await fx.WaitForAsync(job.Id, JobState.Done);
var entry = bed.Project.ReadRenders().Entries.Single();
Assert.Equal(version.Id, entry.ProjectVersionId);
Assert.Equal(version.ContentHash, entry.SettingsHash);
// A version the workspace does not hold: refused, saying so.
var unknown = await bed.Engine.EnqueueAsync(
WorkspaceJobs.Render(bed.Sequence.Id, bed.Sequence.DisplayTitle, bed.Store.Root, bed.Project.ProjectId, Guid.CreateVersion7(), stripped.ToJsonString()),
cancellationToken: fx.Ct);
Assert.Equal(Loc.L("Errors.Workspace.RenderVersion"), (await fx.WaitForAsync(unknown.Id, JobState.Failed)).Error);
}
[Test]
public async Task WithoutTheOriginalsTheRenderIsRefusedSayingHowManyLack()
{
await using var bed = await BedAsync(beforeCopy: (fx, sequence) =>
{
File.Delete(Path.Combine(fx.Archive.Paths.Root, "Synthetic", ProcessingFixture.FileName(3)));
File.Delete(Path.Combine(fx.Archive.Paths.Root, "Synthetic", ProcessingFixture.FileName(7)));
});
var fx = bed.Fx;
Assert.Equal(Frames - 2, bed.Project.ReadMedia()!.Frames.Count(f => f.HasOriginal));
var job = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: fx.Ct);
Assert.Equal(Loc.L("Errors.Workspace.RenderNoOriginals", 2), (await fx.WaitForAsync(job.Id, JobState.Failed)).Error);
Assert.Empty(bed.Project.ReadRenders().Entries);
Assert.False(Directory.Exists(bed.Project.ExportsDirectory) && Directory.EnumerateFileSystemEntries(bed.Project.ExportsDirectory).Any());
}
[Test]
public async Task ProxiesAloneAreRefused()
{
await using var bed = await BedAsync(BundleMedia.Proxies);
var job = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: bed.Fx.Ct);
Assert.Equal(Loc.L("Errors.Workspace.OriginalsMissing"), (await bed.Fx.WaitForAsync(job.Id, JobState.Failed)).Error);
}
[Test]
public async Task ACancelledRenderLeavesNoPartialOutput()
{
await using var bed = await BedAsync();
var fx = bed.Fx;
fx.Decoder.HoldPurpose = DecodePurpose.Render;
fx.Decoder.Hold = Path.GetFileName(bed.Project.ReadMedia()!.Frames[12].Original);
var job = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: fx.Ct);
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
await bed.Engine.CancelAsync(job.Id, fx.Ct);
await fx.WaitForAsync(job.Id, JobState.Cancelled);
var until = DateTime.UtcNow.AddSeconds(30);
while (bed.Engine.RunningJobIds.Contains(job.Id))
{
Assert.True(DateTime.UtcNow < until, "the render did not stop");
await Task.Delay(20, fx.Ct);
}
var left = Directory.Exists(bed.Project.ExportsDirectory) ? Directory.GetFileSystemEntries(bed.Project.ExportsDirectory) : [];
Assert.Empty(left);
Assert.Empty(bed.Project.ReadRenders().Entries);
Assert.False((await fx.Db.Jobs.ListAsync(null, 50, null, fx.Ct)).Items.Any(j => j.Kind == JobKind.WorkspaceSend), "nothing to send");
}
}