feat(workspace): lay the phase 5c foundation

Phase 5c (owner review 2, R8) is built by six packages in parallel. This
commit settles everything they share, so each one touches its own files:

- job kinds WorkspaceRender (21), WorkspaceSend (22) and WorkspaceMove (23)
  with their wire names, default priorities, notices and parameter records;
  their handlers are registered as skeletons that throw until their
  package lands
- WorkspaceJobOptions and a new CreateHandlers overload; the earlier ones
  stay and default the options
- originals in the media index (an index of phase 5b reads as proxies
  only), their file names, and the exports/renders.json ledger of local
  renders, written atomically
- the optional project and version of an uploaded render
- the workspace settings (size limit, default media, version on render,
  clean-up age, project to open) and when each project was opened, which
  Reset and Import keep and Export leaves out
- WorkspaceHost split into partial files, with stubs for usage, trash and
  the folder move, removal hooks for unsent renders and last originals,
  and a guard that holds work while the workspace moves
- every new string of the phase in English and Italian, with tooltips

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-04 15:05:09 +01:00
1 parent 102f28b5df
commit 2e1c67f531
43 files changed
+1725 -128

No files matched your search

+15 -3
View File
@@ -178,15 +178,27 @@ 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, from
/// this PC's archive or, through the signed-in session, from a server.</summary>
/// queued (it is never claimed here). The workspace's jobs are the desktop's alone: they write into this PC's workspace
/// (a copy from this PC's archive or, through the signed-in session, from a server; a local render with this PC's
/// encoders; the sending of its renders home; the move of its folder, which Settings › Workspace then names).</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.Sync) : [],
.. services.Database is { } db && services.Archives is { } archives
? WorkspaceJobs.CreateHandlers(db, archives, services.Sync, WorkspaceOptions(services, archives))
: [],
];
/// <summary>
/// The workspace jobs' share of the desktop (phase 5c): its processing options for local renders, the metered hold of
/// Settings › Server over transfers with a server, and the workspace that follows a moved folder.
/// </summary>
private static WorkspaceJobOptions WorkspaceOptions(AppServices services, ArchiveService archives) =>
new(services.Processing?.Options ?? WorkspaceJobOptions.For(archives).Processing,
() => services.Settings.PauseUploadsOnMetered && MeteredNetwork.IsMetered(),
services.Workspace.MovedAsync);
/// <summary>
/// Queues a scan of <paramref name="archive"/> unless one is already waiting or running; the sequences it indexes get
/// a background deep analysis when Settings › Analysis asks for it.
@@ -7,6 +7,7 @@ using Chronos.Core.Diagnostics;
using Chronos.Core.Import;
using Chronos.Core.IO;
using Chronos.Core.Naming;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Repositories;
using Chronos.Ui.Theming;
@@ -39,6 +40,21 @@ public enum HardwarePreference
HardwareForPreviews,
}
/// <summary>
/// Which project Edit opens for a sequence that has several in the workspace (Settings › Workspace › Open project, phase 5c).
/// </summary>
public enum WorkspaceOpenPolicy
{
/// <summary>The project opened last for the sequence (<see cref="AppSettings.WorkspaceRecent"/>), else the one saved last.</summary>
LastUsed,
/// <summary>The sequence's Main project.</summary>
Main,
/// <summary>Ask each time, listing the sequence's projects.</summary>
Ask,
}
/// <summary>A server certificate the user trusted on first use (BRIEF §12.7).</summary>
public sealed class TrustedCertificate
{
@@ -58,6 +74,8 @@ public sealed class AppSettings
public const int DefaultCacheLimitGb = 20;
public const int DefaultScanIntervalMinutes = 10;
public const int DefaultWorkspaceKeptVersions = 20;
public const int DefaultWorkspaceSizeLimitGb = 100;
public const int DefaultWorkspaceCleanAfterDays = 30;
/// <summary>2⁻⁴ of white: the deep analysis' night threshold (a mean log2 luminance of −4).</summary>
public const double DefaultNightBrightnessPercent = 6.25;
@@ -169,6 +187,36 @@ public sealed class AppSettings
/// <summary>The workspace project opened last for each sequence (sequence id → project id); Edit opens it again.</summary>
public Dictionary<Guid, Guid> WorkspaceRecent { get; set; } = [];
/// <summary>
/// Phase 5c: past this size (GB of 2³⁰ bytes) the workspace's clean-up removes the media of the projects used longest ago
/// that are in step with their home (never one open, with jobs, or with renders not sent); 0 = no limit.
/// </summary>
public int WorkspaceSizeLimitGb { get; set; } = DefaultWorkspaceSizeLimitGb;
/// <summary>
/// What "Open in workspace" copies unless chosen otherwise: <see cref="BundleMedia.Proxies"/> or
/// <see cref="BundleMedia.Originals"/> (the proxies plus the originals, to render on this PC).
/// </summary>
public string WorkspaceDefaultMedia { get; set; } = BundleMedia.Proxies;
/// <summary>A render of a project with changes not saved as a version saves one first (and sends it when Sync automatically is on).</summary>
public bool WorkspaceVersionOnRender { get; set; } = true;
/// <summary>
/// The workspace's clean-up removes the media of a project not opened for this many days, once it is in step with its
/// home; 0 = never.
/// </summary>
public int WorkspaceCleanAfterDays { get; set; } = DefaultWorkspaceCleanAfterDays;
/// <summary>Which project Edit opens for a sequence with several in the workspace.</summary>
public WorkspaceOpenPolicy WorkspaceOpenProject { get; set; } = WorkspaceOpenPolicy.LastUsed;
/// <summary>
/// When each workspace project was last opened in Edit (project id → time), which the clean-up goes by (else the time
/// its working state was saved). This PC's, like <see cref="WorkspaceRecent"/>.
/// </summary>
public Dictionary<Guid, DateTimeOffset> WorkspaceOpened { get; set; } = [];
// ---- Server ----
public string? ServerUrl { get; set; }
public string? ServerUsername { get; set; }
@@ -285,6 +333,64 @@ public sealed class AppSettings
/// <summary>A deep copy (JSON round trip), used for import and reset.</summary>
public AppSettings Clone() => Parse(ToJson()) ?? new AppSettings();
/// <summary>
/// Settings › Advanced › Reset: every default, but the values that are this PC's or this user's state rather than
/// preferences: the archive and the session, the window and its rail, the sequence edited last, the first-run flag, the
/// jobs cleared, and the workspace (its folder, moved only by its own operation, the projects opened last and when).
/// </summary>
public AppSettings ResetKeepingState() => new()
{
LastArchivePath = LastArchivePath,
ServerUrl = ServerUrl,
ServerUsername = ServerUsername,
ProtectedToken = ProtectedToken,
TrustedCertificates = TrustedCertificates,
RecentServers = RecentServers,
Window = Window,
RailCollapsed = RailCollapsed,
LastEditedSequence = LastEditedSequence,
FirstRunCompleted = FirstRunCompleted,
JobsClearedAt = JobsClearedAt,
WorkspaceFolder = WorkspaceFolder,
WorkspaceRecent = WorkspaceRecent,
WorkspaceOpened = WorkspaceOpened,
};
/// <summary>
/// Settings › Export: a copy without secrets and machine-bound values (the session, the window, the workspace's folder and
/// what it remembers of its projects: another PC's ids mean nothing there).
/// </summary>
public AppSettings ForExport()
{
var copy = Clone();
copy.ProtectedToken = null;
copy.Window = null;
copy.WorkspaceFolder = null;
copy.WorkspaceRecent = [];
copy.WorkspaceOpened = [];
return copy;
}
/// <summary>
/// Settings › Import: <paramref name="imported"/> with this PC's own values taken from these settings: the session, the
/// window and its rail, the sequence edited last, the first-run flag, and the workspace (its folder, the projects opened
/// last and when). Changes and returns <paramref name="imported"/>.
/// </summary>
public AppSettings KeepLocalIn(AppSettings imported)
{
ArgumentNullException.ThrowIfNull(imported);
imported.ProtectedToken = ProtectedToken;
imported.ServerUrl = ServerUrl;
imported.Window = Window;
imported.RailCollapsed = RailCollapsed;
imported.LastEditedSequence = LastEditedSequence;
imported.FirstRunCompleted = FirstRunCompleted;
imported.WorkspaceFolder = WorkspaceFolder;
imported.WorkspaceRecent = WorkspaceRecent;
imported.WorkspaceOpened = WorkspaceOpened;
return imported;
}
}
[JsonSourceGenerationOptions(WriteIndented = true, UseStringEnumConverter = true)]
+2 -1
View File
@@ -40,7 +40,8 @@ public static class JobNotices
private static bool Announces(JobKind kind) =>
kind is JobKind.Render or JobKind.DeepAnalyse or JobKind.Verify or JobKind.Rebuild or JobKind.Maintenance or JobKind.UploadCommit
or JobKind.Move or JobKind.Adopt or JobKind.EmptyTrash or JobKind.Convert;
or JobKind.Move or JobKind.Adopt or JobKind.EmptyTrash or JobKind.Convert or JobKind.WorkspaceRender or JobKind.WorkspaceSend
or JobKind.WorkspaceMove;
/// <summary>
/// Work that keeps the index and its previews current: the next run repeats it, the Archive screen shows what is missing.
+1 -1
View File
@@ -12,7 +12,7 @@ public static class JobText
/// <summary>True for jobs whose items are frames, so their speed reads in fps.</summary>
public static bool CountsFrames(JobKind kind) =>
kind is JobKind.Render or JobKind.Proxies or JobKind.Thumbs or JobKind.DeepAnalyse;
kind is JobKind.Render or JobKind.Proxies or JobKind.Thumbs or JobKind.DeepAnalyse or JobKind.WorkspaceRender;
/// <summary>True for jobs whose progress counts bytes (hash verification, card import).</summary>
public static bool CountsBytes(JobKind kind) => kind is JobKind.Verify or JobKind.Import;
+8 -35
View File
@@ -1207,7 +1207,8 @@ public sealed class SettingsViewModel : SectionViewModel
[
JobKind.Render, JobKind.Import, JobKind.Download, JobKind.UploadCommit, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse,
JobKind.DeepAnalyse, JobKind.Thumbs, JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move,
JobKind.Backup, JobKind.Cleanup, JobKind.EmptyTrash, JobKind.Convert, JobKind.WorkspaceCopy,
JobKind.Backup, JobKind.Cleanup, JobKind.EmptyTrash, JobKind.Convert, JobKind.WorkspaceCopy, JobKind.WorkspaceRender, JobKind.WorkspaceSend,
JobKind.WorkspaceMove,
];
/// <summary>Stores <paramref name="level"/> for <paramref name="kind"/>, keeping only the levels that differ from the defaults.</summary>
@@ -1632,23 +1633,8 @@ public sealed class SettingsViewModel : SectionViewModel
IsDestructive = true,
});
if (!confirmed) return;
var defaults = new AppSettings
{
LastArchivePath = _s.LastArchivePath,
ServerUrl = _s.ServerUrl,
ServerUsername = _s.ServerUsername,
ProtectedToken = _s.ProtectedToken,
TrustedCertificates = _s.TrustedCertificates,
RecentServers = _s.RecentServers,
Window = _s.Window,
RailCollapsed = _s.RailCollapsed,
LastEditedSequence = _s.LastEditedSequence,
FirstRunCompleted = _s.FirstRunCompleted,
JobsClearedAt = _s.JobsClearedAt,
// The workspace holds this PC's work: its folder stays where it is (moving it is its own operation).
WorkspaceFolder = _s.WorkspaceFolder,
WorkspaceRecent = _s.WorkspaceRecent,
};
// The workspace holds this PC's work: its folder stays where it is (moving it is its own operation).
var defaults = _s.ResetKeepingState();
// Start with Windows lives in the registry, not in the settings file: its default is off.
Startup.SetEnabled(false);
ApplyAll(defaults);
@@ -1690,12 +1676,8 @@ public sealed class SettingsViewModel : SectionViewModel
{
var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Settings.Export.Title"));
if (folder is null) return;
var copy = _s.Clone();
// Secrets and machine-bound values stay on this PC.
copy.ProtectedToken = null;
copy.Window = null;
copy.WorkspaceFolder = null;
copy.WorkspaceRecent = [];
var copy = _s.ForExport();
var path = Path.Combine(folder, $"Chronos settings {DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}.json");
await Task.Run(() => AtomicFile.WriteAllText(path, copy.ToJson()));
Shell.Notify(Loc.L("Settings.Export.Done"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
@@ -1720,18 +1702,9 @@ public sealed class SettingsViewModel : SectionViewModel
Shell.Notify(Loc.L("Errors.Settings.Import"), isError: true);
return;
}
// Everything but the session, the window and its rail, the sequence edited last (another PC's ids mean nothing here)
// and the first-run flag.
imported.ProtectedToken = _s.ProtectedToken;
imported.ServerUrl = _s.ServerUrl;
imported.Window = _s.Window;
imported.RailCollapsed = _s.RailCollapsed;
imported.LastEditedSequence = _s.LastEditedSequence;
imported.FirstRunCompleted = _s.FirstRunCompleted;
// The workspace is this PC's: its folder and the projects opened last stay.
imported.WorkspaceFolder = _s.WorkspaceFolder;
imported.WorkspaceRecent = _s.WorkspaceRecent;
ApplyAll(imported);
// Everything but the session, the window and its rail, the sequence edited last (another PC's ids mean nothing here),
// the first-run flag and the workspace, which is this PC's (its folder, the projects opened last and when).
ApplyAll(_s.KeepLocalIn(imported));
// Settings of a PC never rewrite the shared archive.json: the imported templates and sizes are the defaults of new
// archives, and the rows show the own settings of the archive at the (possibly imported) archive folder.
_retarget = RetargetArchiveAsync();
@@ -66,6 +66,31 @@ public static class WorkspaceFolderChange
}
}
/// <summary>
/// Settings › Workspace › Move… (phase 5c): the shell's flow over <see cref="MoveAsync(WorkspaceHost, IAppDialogs, Func{Task{bool}}, Action{string})"/>,
/// with its folder picker, confirmation, editor and toasts. True when the move was queued.
/// </summary>
public static Task<bool> MoveAsync(ShellViewModel shell)
{
ArgumentNullException.ThrowIfNull(shell);
throw new NotImplementedException("Moving the workspace folder comes with phase 5c (P6).");
}
/// <summary>
/// Picks the folder the workspace moves to through <paramref name="dialogs"/>, shows its plan
/// (<see cref="WorkspaceHost.PlanMoveAsync"/>) and asks for the user's word, lets <paramref name="closeProject"/> close a
/// workspace project open in the editor (false keeps everything as it is), then queues the move
/// (<see cref="WorkspaceHost.QueueMoveAsync"/>). <paramref name="failed"/> hears why it was refused. True when it was queued.
/// </summary>
public static Task<bool> MoveAsync(WorkspaceHost host, IAppDialogs dialogs, Func<Task<bool>> closeProject, Action<string> failed)
{
ArgumentNullException.ThrowIfNull(host);
ArgumentNullException.ThrowIfNull(dialogs);
ArgumentNullException.ThrowIfNull(closeProject);
ArgumentNullException.ThrowIfNull(failed);
throw new NotImplementedException("Moving the workspace folder comes with phase 5c (P6).");
}
/// <summary>The plan as a confirmation: where Edit's projects come from now, and what stays where it is.</summary>
public static ConfirmRequest Request(WorkspaceFolderPlan plan)
{
@@ -0,0 +1,102 @@
using System.IO;
using Chronos.Core.Project;
using Chronos.Data.Workspaces;
namespace Chronos.App.Workspace;
/// <summary>
/// What the workspace takes of its drive (Settings › Workspace, phase 5c): the projects' media (proxies and originals, which
/// the clean-up and the size limit may remove), the whole folder, and its trash (<see cref="WorkspaceHost.TrashFolder"/>).
/// </summary>
/// <param name="MediaBytes">The bytes of every project's <c>media/</c> folder.</param>
/// <param name="TotalBytes">The bytes of the whole workspace folder, its trash included.</param>
/// <param name="TrashBytes">The bytes of the workspace's trash.</param>
/// <param name="TrashItems">The entries of the workspace's trash (one per copy removed or originals set aside).</param>
public sealed record WorkspaceUsage(long MediaBytes, long TotalBytes, long TrashBytes, int TrashItems)
{
/// <summary>A workspace that holds nothing.</summary>
public static WorkspaceUsage None { get; } = new(0, 0, 0, 0);
}
/// <summary>One entry of the workspace's trash as Empty… lists it: its folder name, size, files and when it was put there.</summary>
public sealed record WorkspaceTrashItem(string Name, long Bytes, int Files, DateTimeOffset Trashed);
/// <summary>
/// The plan of Settings › Workspace › Trash › Empty… (phase 5c): every entry of the workspace's trash and their bytes, and a
/// fingerprint over their names, sizes and times. Emptying erases exactly these entries, and only while the fingerprint
/// still matches (the user types the number of entries to confirm); schedules and the size limit never empty the trash.
/// </summary>
public sealed record WorkspaceTrashPlan(string Folder, IReadOnlyList<WorkspaceTrashItem> Items, long Bytes, string Fingerprint)
{
/// <summary>Nothing to erase: Empty… is disabled.</summary>
public bool IsEmpty => Items.Count == 0;
}
/// <summary>What emptying the workspace's trash erased.</summary>
public sealed record WorkspaceTrashResult(int Items, long Bytes);
/// <summary>
/// The workspace's clean-up side (phase 5c, P4): its usage, the plan and emptying of its trash, and what a local copy's removal
/// keeps of renders not sent and originals the home lost. Stubs until the clean-up lands: usage and the trash read as empty,
/// and a removal finds nothing more to keep.
/// </summary>
public sealed partial class WorkspaceHost
{
/// <summary>What the workspace takes of its drive (<see cref="WorkspaceUsage"/>), measured off the UI thread.</summary>
public Task<WorkspaceUsage> UsageAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.FromResult(WorkspaceUsage.None);
}
/// <summary>The plan of emptying the workspace's trash (<see cref="WorkspaceTrashPlan"/>); nothing is erased.</summary>
public Task<WorkspaceTrashPlan> PlanTrashAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.FromResult(new WorkspaceTrashPlan(Path.Combine(Root, TrashFolder), [], 0, string.Empty));
}
/// <summary>
/// Erases the entries of <paramref name="plan"/> from the workspace's trash for good, after the user typed their number;
/// refused when the trash changed since the plan (<c>Errors.Workspace.TrashChanged</c>).
/// </summary>
/// <exception cref="WorkspaceException">The trash changed since the plan; nothing was erased.</exception>
public Task<WorkspaceTrashResult> EmptyTrashAsync(WorkspaceTrashPlan plan, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(plan);
throw new NotImplementedException("Emptying the workspace's trash comes with phase 5c (P4).");
}
/// <summary>
/// What a local copy's removal plan counts besides its versions (<see cref="WorkspaceRemovalPlan.UnsentRenders"/>,
/// <see cref="WorkspaceRemovalPlan.LastOriginals"/>): renders of its ledger not sent, and originals the home no longer holds.
/// </summary>
private Task<(int UnsentRenders, int LastOriginals)> RemovalMediaAsync(WorkspaceProject project, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(project);
cancellationToken.ThrowIfCancellationRequested();
return Task.FromResult((0, 0));
}
/// <summary>A removal without Discard is refused while the project's ledger holds renders not sent (Send first sends them).</summary>
/// <exception cref="WorkspaceException">Renders wait to be sent.</exception>
private Task EnsureRendersSentAsync(WorkspaceProject project, BundleWorkspace workspace, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(project);
ArgumentNullException.ThrowIfNull(workspace);
cancellationToken.ThrowIfCancellationRequested();
return Task.CompletedTask;
}
/// <summary>
/// Before a removed copy's media are deleted, under the project's lease: the originals the home no longer holds with the
/// same SHA-256 moved into <paramref name="aside"/> (the copy's trash entry), never deleted.
/// </summary>
private Task KeepLastOriginalsAsync(WorkspaceProject project, string aside, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(project);
ArgumentException.ThrowIfNullOrEmpty(aside);
cancellationToken.ThrowIfCancellationRequested();
return Task.CompletedTask;
}
}
@@ -0,0 +1,25 @@
using Chronos.Core.Localization;
using Chronos.Data.Workspaces;
namespace Chronos.App.Workspace;
/// <summary>
/// The workspace's media (phase 5c, P1): what a copy writes (proxies, and the originals besides), copying the originals of a
/// project, and going back to proxies only.
/// </summary>
public sealed partial class WorkspaceHost
{
/// <summary>The bytes the first copy of a sequence's media writes into the workspace, and the free bytes of the workspace's drive.</summary>
/// <exception cref="WorkspaceException">The index or the archive engine is not open.</exception>
public Task<WorkspaceCopyFacts> CopyFactsAsync(Guid sequenceId, CancellationToken cancellationToken = default)
{
var db = _db() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
var archives = _archives() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
var root = Root;
return Task.Run(async () =>
{
var (bytes, free) = await WorkspaceJobs.CopyFactsAsync(db, archives, sequenceId, root, cancellationToken).ConfigureAwait(false);
return new WorkspaceCopyFacts(bytes, free);
}, cancellationToken);
}
}
@@ -0,0 +1,76 @@
using Chronos.Core.Localization;
using Chronos.Core.Model;
namespace Chronos.App.Workspace;
/// <summary>A project of the workspace as the plan of a move lists it: its size, and work not at its home yet (a warning, never a refusal).</summary>
/// <param name="Unsent">Versions or renders wait to be sent to its home.</param>
/// <param name="Modified">Changes not saved as a version.</param>
public sealed record WorkspaceMoveProject(Guid ProjectId, string Name, int Files, long Bytes, bool Unsent, bool Modified);
/// <summary>
/// The plan of Settings › Workspace › Move… (phase 5c): the workspace folder <see cref="From"/> moved with its projects to
/// <see cref="To"/>: the projects and their bytes, the free bytes at the target, whether both lie on one volume (folders
/// renamed) or not (files copied and hash-verified), why it is refused (null when it can go), and a fingerprint of what
/// the plan read, which the move job checks again.
/// </summary>
/// <param name="Free">The free bytes of the target's drive; null when they cannot be measured.</param>
/// <param name="Refusal">
/// Why the move cannot go, one localized sentence: the target is the folder itself or inside it
/// (<c>Errors.Workspace.MoveSameFolder</c>), already holds a workspace or a project of the same id
/// (<c>Errors.Workspace.MoveTargetNotEmpty</c>), lacks the room (<c>Errors.Workspace.DiskFull</c>), or a workspace job is
/// pending or running (<c>Errors.Workspace.JobsRunning</c>); null when it can go.
/// </param>
public sealed record WorkspaceMovePlan(string From, string To, IReadOnlyList<WorkspaceMoveProject> Projects, int Files, long Bytes, long? Free, bool SameVolume,
string? Refusal, string Fingerprint)
{
/// <summary>Nothing refuses the move.</summary>
public bool CanMove => Refusal is null;
/// <summary>Projects with work not at their home: the move keeps it, the plan says so.</summary>
public int Warnings => Projects.Count(p => p.Unsent || p.Modified);
}
/// <summary>
/// Moving the workspace folder with its projects (phase 5c, P6): the plan, the <see cref="JobKind.WorkspaceMove"/> that
/// carries it out, and the workspace that follows the folder once every file is verified there. While a move is queued or
/// running the workspace is refused for syncs, saves and opens (<see cref="EnsureNotMoving"/>). Stubs until the move lands.
/// </summary>
public sealed partial class WorkspaceHost
{
/// <summary>A move of the workspace folder is queued or running: syncs, saves and opens wait for it.</summary>
public bool IsMoving => false;
/// <summary>The plan of moving the workspace folder to <paramref name="to"/> (<see cref="WorkspaceMovePlan"/>); nothing is written.</summary>
public Task<WorkspaceMovePlan> PlanMoveAsync(string to, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(to);
throw new NotImplementedException("Moving the workspace folder comes with phase 5c (P6).");
}
/// <summary>Queues the <see cref="JobKind.WorkspaceMove"/> of a plan the user confirmed.</summary>
/// <exception cref="WorkspaceException">The plan refuses the move.</exception>
public Task<Job> QueueMoveAsync(WorkspaceMovePlan plan, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(plan);
throw new NotImplementedException("Moving the workspace folder comes with phase 5c (P6).");
}
/// <summary>
/// Told by the move job once every file of the workspace is verified at <paramref name="to"/>
/// (<c>WorkspaceJobOptions.Moved</c>): Settings › Workspace names the new folder and the workspace opens there.
/// </summary>
public Task MovedAsync(string from, string to)
{
ArgumentException.ThrowIfNullOrWhiteSpace(from);
ArgumentException.ThrowIfNullOrWhiteSpace(to);
throw new NotImplementedException("Moving the workspace folder comes with phase 5c (P6).");
}
/// <summary>Refuses an operation that writes into the workspace while its folder is being moved.</summary>
/// <exception cref="WorkspaceException">A move is queued or running (<c>Errors.Workspace.Moving</c>).</exception>
private void EnsureNotMoving()
{
if (IsMoving) throw new WorkspaceException(Loc.L("Errors.Workspace.Moving"));
}
}
@@ -0,0 +1,9 @@
namespace Chronos.App.Workspace;
/// <summary>
/// The workspace's local renders (phase 5c, P2): rendering a project from the originals it holds on this PC, and sending its
/// renders home.
/// </summary>
public sealed partial class WorkspaceHost
{
}
+53 -21
View File
@@ -70,8 +70,17 @@ public sealed record WorkspaceFolderPlan(string Current, string Folder, int Proj
}
/// <summary>What "Open in workspace" shows of the copy it queues: its bytes (as the copy reckons them) and the free bytes of the workspace's drive.</summary>
public sealed record WorkspaceCopyFacts(long Bytes, long? Free)
/// <param name="Bytes">What the copy of the proxies writes.</param>
/// <param name="OriginalsBytes">What the copy of the originals writes besides (phase 5c); null when not known.</param>
public sealed record WorkspaceCopyFacts(long Bytes, long? Free, long? OriginalsBytes = null)
{
/// <summary>
/// The drive lacks room for the copy of <paramref name="media"/> (<see cref="BundleMedia.Originals"/>: the proxies and the
/// originals) and the reserve the copy keeps free.
/// </summary>
public bool TooLittleSpaceFor(string media) =>
Free is { } free && free < Bytes + (media == BundleMedia.Originals ? OriginalsBytes ?? 0 : 0) + WorkspaceJobs.CopySpaceReserve;
/// <summary>The drive lacks the copy and the reserve the copy keeps: it would stop saying so.</summary>
public bool TooLittleSpace => Free is { } free && free < Bytes + WorkspaceJobs.CopySpaceReserve;
}
@@ -113,8 +122,20 @@ public sealed record WorkspaceRemovalPlan(Guid ProjectId, string Name, int Files
/// </summary>
public string? KnownName { get; init; }
/// <summary>
/// Local renders not at the home yet (phase 5c, the project's ledger): Send first sends them, Discard keeps them in the
/// workspace's trash with the rest of the work not sent.
/// </summary>
public int UnsentRenders { get; init; }
/// <summary>
/// Originals the workspace holds that the home no longer holds with the same SHA-256 (phase 5c): they go to the
/// workspace's trash, never deleted, when the copy is removed.
/// </summary>
public int LastOriginals { get; init; }
/// <summary>Everything the copy holds is at the home: it can go without discarding anything.</summary>
public bool IsSafe => Unsent == 0 && !Modified && !Conflict && !Damaged;
public bool IsSafe => Unsent == 0 && UnsentRenders == 0 && !Modified && !Conflict && !Damaged;
}
/// <summary>
@@ -129,7 +150,7 @@ public sealed record WorkspaceRemovalPlan(Guid ProjectId, string Name, int Files
/// 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
public sealed partial class WorkspaceHost
{
/// <summary>Where discarded work of removed local copies is kept (the store lists only folders named by a project id).</summary>
public const string TrashFolder = ".trash";
@@ -358,20 +379,6 @@ public sealed class WorkspaceHost
Log.Info("workspace", $"The workspace folder is now {plan.Folder} ({plan.ProjectsLeft} project(s) stay in {plan.Current})");
}
/// <summary>The bytes the first copy of a sequence's media writes into the workspace, and the free bytes of the workspace's drive.</summary>
/// <exception cref="WorkspaceException">The index or the archive engine is not open.</exception>
public Task<WorkspaceCopyFacts> CopyFactsAsync(Guid sequenceId, CancellationToken cancellationToken = default)
{
var db = _db() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
var archives = _archives() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
var root = Root;
return Task.Run(async () =>
{
var (bytes, free) = await WorkspaceJobs.CopyFactsAsync(db, archives, sequenceId, root, cancellationToken).ConfigureAwait(false);
return new WorkspaceCopyFacts(bytes, free);
}, cancellationToken);
}
/// <summary>The project of <paramref name="sequenceId"/> opened last here, else the one saved last; null when the workspace has none.</summary>
public async Task<WorkspaceEntry?> LastUsedAsync(Guid sequenceId, CancellationToken cancellationToken = default)
{
@@ -388,6 +395,16 @@ public sealed class WorkspaceHost
_savePreferences();
}
/// <summary>
/// Records that Edit opened <paramref name="projectId"/> at <paramref name="at"/> (now when null): the clean-up's Clean
/// after goes by it (phase 5c, <see cref="AppSettings.WorkspaceOpened"/>). Call it on the UI thread, which writes the settings.
/// </summary>
public void RecordOpened(Guid projectId, DateTimeOffset? at = null)
{
_settings.WorkspaceOpened[projectId] = at ?? DateTimeOffset.UtcNow;
_savePreferences();
}
/// <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) =>
HomeProjectsAsync(ArchiveHome(sequenceId), cancellationToken);
@@ -426,6 +443,7 @@ public sealed class WorkspaceHost
var sequenceId = home.SequenceId;
var checkout = await Task.Run(async () =>
{
EnsureNotMoving();
// Refused before anything is written: the copy job would refuse such a folder after the checkout filled it.
if (await InsideALibraryAsync(cancellationToken).ConfigureAwait(false))
throw new WorkspaceException(Loc.L("Errors.Workspace.InsideLibraryEdit", Root)) { FolderRefused = true };
@@ -461,6 +479,7 @@ public sealed class WorkspaceHost
/// </summary>
public Task<Job> QueueCopyAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
var bundle = Existing(projectId).ReadBundle();
return await QueueCopyCoreAsync(bundle.Workspace!.Home, projectId, bundle.Workspace.Media.Kind, bundle.Sequence.Title ?? string.Empty, cancellationToken)
.ConfigureAwait(false);
@@ -516,6 +535,7 @@ public sealed class WorkspaceHost
{
var version = await Task.Run(async () =>
{
EnsureNotMoving();
EnsureWritable(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
return await Sync.CommitAsync(projectId, note, null, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
@@ -538,6 +558,7 @@ public sealed class WorkspaceHost
/// <summary>The working state as a new local version without a note and without sending it; null when nothing changed.</summary>
public Task<ProjectVersion?> CommitAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
EnsureWritable(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
return await Sync.CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
@@ -551,6 +572,7 @@ public sealed class WorkspaceHost
/// <exception cref="WorkspaceSyncException">The home refused a version for good.</exception>
public Task<WorkspaceSyncResult> SyncAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
var home = HomeOfProject(projectId);
var pulled = await Sync.PullAsync(projectId, home, cancellationToken).ConfigureAwait(false);
// Deleted at the library: nothing to send, nothing to prune; the copy stays as it is.
@@ -570,6 +592,7 @@ public sealed class WorkspaceHost
public Task<WorkspaceSyncResult> ResolveAsync(Guid projectId, ConflictChoice choice, IReadOnlySet<string>? takeServer = null,
WorkspaceConflict? shown = null, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
var home = HomeOfProject(projectId);
WorkspaceSyncResult resolved;
if (choice == ConflictChoice.SaveBoth)
@@ -619,6 +642,7 @@ public sealed class WorkspaceHost
/// </summary>
public Task<ProjectSettings> RestoreAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
var status = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
if (status.ReadOnly) throw new WorkspaceException(Loc.L("Errors.Workspace.ReadOnly"));
if (status.MediaRemoved) throw new WorkspaceException(Loc.L("Errors.Workspace.MediaMissing"));
@@ -766,8 +790,9 @@ public sealed class WorkspaceHost
// A conflict recorded counts as work not at the home, also once the library no longer has the project (Gone asks none);
// one a settling replay took past its commit point is over, as the status reads it.
var conflict = status.Conflict is not null || project.OpenConflict() is not null;
var (unsentRenders, lastOriginals) = await RemovalMediaAsync(project, cancellationToken).ConfigureAwait(false);
return new WorkspaceRemovalPlan(projectId, name, files, bytes, status.Ahead + status.Damaged, status.Modified, conflict, status.Offline,
status.State == WorkspaceState.Gone);
status.State == WorkspaceState.Gone) { UnsentRenders = unsentRenders, LastOriginals = lastOriginals };
}, cancellationToken);
/// <summary>
@@ -802,6 +827,7 @@ public sealed class WorkspaceHost
// 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(Unsent(workspace.Home));
await EnsureRendersSentAsync(project, workspace, cancellationToken).ConfigureAwait(false);
await VerifyHomeAsync(projectId, workspace, cancellationToken).ConfigureAwait(false);
}
await RemoveFolderAsync(project, cancellationToken).ConfigureAwait(false);
@@ -950,6 +976,8 @@ public sealed class WorkspaceHost
}
throw;
}
// Originals the home no longer holds go aside with the rest; only what the home can make again is deleted.
await KeepLastOriginalsAsync(project, aside, cancellationToken).ConfigureAwait(false);
if (Directory.Exists(project.MediaDirectory)) Directory.Delete(project.MediaDirectory, recursive: true);
void Move(string from, string to)
@@ -1007,9 +1035,13 @@ public sealed class WorkspaceHost
private void Forget(Guid sequenceId, Guid projectId)
{
if (!_settings.WorkspaceRecent.TryGetValue(sequenceId, out var known) || known != projectId) return;
_settings.WorkspaceRecent.Remove(sequenceId);
_savePreferences();
var changed = _settings.WorkspaceOpened.Remove(projectId);
if (_settings.WorkspaceRecent.TryGetValue(sequenceId, out var known) && known == projectId)
{
_settings.WorkspaceRecent.Remove(sequenceId);
changed = true;
}
if (changed) _savePreferences();
}
/// <summary>
+18
View File
@@ -105,6 +105,24 @@ public enum JobKind
/// and resumable (owner review 2, R8); stored as 20.
/// </summary>
WorkspaceCopy = 20,
/// <summary>
/// Renders a workspace project from the originals the workspace holds, on this PC, into the project's <c>exports/</c>
/// with a ledger entry per output (owner review 2, R8, phase 5c); stored as 21.
/// </summary>
WorkspaceRender = 21,
/// <summary>
/// Sends a workspace project's local renders home (this PC's archive or its server) with their project and version,
/// each hash-checked and idempotent by render id (owner review 2, R8, phase 5c); stored as 22.
/// </summary>
WorkspaceSend = 22,
/// <summary>
/// Moves the workspace folder with its projects to another folder, journaled and hash-verified across volumes, the
/// source kept until every file is verified (owner review 2, R8, phase 5c); stored as 23.
/// </summary>
WorkspaceMove = 23,
}
/// <summary>Why a photo left a sequence (its tombstone, owner review 2, R6); stored as a number.</summary>
+6 -2
View File
@@ -23,8 +23,9 @@ public sealed record JobPriorityQueue
{
/// <summary>
/// The levels a kind has unless the user changed it: renders, imports and downloads first, and the copy of a project's
/// media into the workspace, which Edit waits for (owner review 2, R8); the long passes that resume anywhere, and the
/// housekeeping of the schedules (backups, clean-ups), last.
/// media into the workspace, which Edit waits for (owner review 2, R8), a workspace's local render and the move of the
/// workspace folder, which Edit is held for (phase 5c); a local render's sending home at the normal level; the long
/// passes that resume anywhere, and the housekeeping of the schedules (backups, clean-ups), last.
/// </summary>
public static IReadOnlyDictionary<JobKind, JobKindPriority> DefaultLevels { get; } = new Dictionary<JobKind, JobKindPriority>
{
@@ -32,6 +33,9 @@ public sealed record JobPriorityQueue
[JobKind.Import] = JobKindPriority.High,
[JobKind.Download] = JobKindPriority.High,
[JobKind.WorkspaceCopy] = JobKindPriority.High,
[JobKind.WorkspaceRender] = JobKindPriority.High,
[JobKind.WorkspaceSend] = JobKindPriority.Normal,
[JobKind.WorkspaceMove] = JobKindPriority.High,
[JobKind.Verify] = JobKindPriority.Low,
[JobKind.Proxies] = JobKindPriority.Low,
[JobKind.Backup] = JobKindPriority.Low,
+3 -3
View File
@@ -558,14 +558,14 @@ internal sealed class SyncTransfers(SyncService sync)
}
}
private static string? SafeFileName(string? name)
internal static string? SafeFileName(string? name)
{
var file = Path.GetFileName(name?.Trim());
return string.IsNullOrEmpty(file) || file.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || file is "." or ".." ? null : file;
}
/// <summary>"name.mp4", else "name (2).mp4", … — an existing export is never replaced.</summary>
private static string Unique(string folder, string fileName)
internal static string Unique(string folder, string fileName)
{
var candidate = Path.Combine(folder, fileName);
var stem = Path.GetFileNameWithoutExtension(fileName);
@@ -693,7 +693,7 @@ internal sealed class SyncTransfers(SyncService sync)
/// manifest's SHA-256 (two attempts). A part as long as the file (a job stopped while hashing it) is only hashed again;
/// a part the server can no longer resume (416) starts over.
/// </summary>
private static async Task<(string Path, string Sha256)> FetchOriginalAsync(ISyncRemote remote, ManifestFrame frame, string staging,
internal static async Task<(string Path, string Sha256)> FetchOriginalAsync(ISyncRemote remote, ManifestFrame frame, string staging,
CancellationToken cancellationToken)
{
if (frame.Sha256.Length == 0) return await FetchUnhashedAsync(remote, frame, staging, cancellationToken).ConfigureAwait(false);
@@ -19,60 +19,6 @@ using SequenceManifest = Chronos.Protocol.SequenceManifest;
namespace Chronos.Data.Workspaces;
/// <summary>Builds the jobs of the workspace (owner review 2, R8), and their handlers for the desktop's engine.</summary>
public static class WorkspaceJobs
{
/// <summary>
/// <see cref="JobKind.WorkspaceCopy"/>: the media of workspace project <paramref name="projectId"/> (checked out first,
/// <see cref="WorkspaceSync.CheckoutAsync"/>) copied from its home, the sequence of this PC's archive.
/// </summary>
public static ArchiveJobRequest Copy(Sequence sequence, string workspaceRoot, Guid projectId, string media = BundleMedia.Proxies)
{
ArgumentNullException.ThrowIfNull(sequence);
ArgumentException.ThrowIfNullOrWhiteSpace(workspaceRoot);
return new ArchiveJobRequest(JobKind.WorkspaceCopy, [sequence.Id], sequence.DisplayTitle,
JsonSerializer.Serialize(new WorkspaceCopyParameters(workspaceRoot, projectId, media), WorkspaceJson.Default.WorkspaceCopyParameters), JobPriority.User);
}
/// <summary>
/// <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 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
/// archive's proxies' sizes, an estimate for those it makes), and the free bytes on <paramref name="workspaceRoot"/>'s
/// drive (null when it cannot be measured): "Open in workspace" shows both. The copy keeps <see cref="CopySpaceReserve"/>
/// free besides.
/// </summary>
/// <exception cref="InvalidOperationException">The index has no such sequence or archive.</exception>
public static Task<(long Bytes, long? Free)> CopyFactsAsync(ChronosDatabase db, ArchiveService archives, Guid sequenceId, string workspaceRoot,
CancellationToken cancellationToken = default) =>
new WorkspaceCopyJobHandler(db, archives).FactsAsync(sequenceId, workspaceRoot, cancellationToken);
/// <summary>Bytes the copy leaves free on the workspace's drive besides what it copies.</summary>
public static long CopySpaceReserve => WorkspaceCopyJobHandler.SpaceReserve;
}
/// <summary>
/// <see cref="JobKind.WorkspaceCopy"/> for a sequence of this PC's archive (owner review 2, R8): its proxies into the
/// workspace project's <c>media/proxies/&lt;frame id&gt;.jpg</c>, the archive's own when current, else made here from the
@@ -0,0 +1,183 @@
using System.Text.Json;
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.Sync;
namespace Chronos.Data.Workspaces;
/// <summary>
/// What the workspace's job handlers take from the desktop besides the index and the archive engine (phase 5c).
/// </summary>
/// <param name="Processing">
/// Decoders, encoders and tuning of a local render (<see cref="JobKind.WorkspaceRender"/>): the desktop's
/// <see cref="ProcessingService.Options"/>.
/// </param>
/// <param name="HoldTransfers">
/// True while transfers with a server are held (Settings › Server › Pause metered transfers on a metered connection): a
/// <see cref="JobKind.WorkspaceCopy"/> or <see cref="JobKind.WorkspaceSend"/> naming a server is not started then. Never
/// holds a copy from or a send to this PC's archive.
/// </param>
/// <param name="Moved">
/// Told once a <see cref="JobKind.WorkspaceMove"/> verified every file at its target (from, to): the desktop names the new
/// folder in Settings › Workspace and refreshes the workspace; null where nothing follows the folder.
/// </param>
public sealed record WorkspaceJobOptions(ProcessingOptions Processing, Func<bool> HoldTransfers, Func<string, string, Task>? Moved = null)
{
/// <summary>The options of an engine without a processing service of its own: the archive engine's decoders, nothing held, no move followed.</summary>
public static WorkspaceJobOptions For(ArchiveService archives)
{
ArgumentNullException.ThrowIfNull(archives);
return new WorkspaceJobOptions(new ProcessingOptions { Archive = new ArchiveServiceOptions { Decoder = archives.Decoder } }, () => false);
}
}
/// <summary>Builds the jobs of the workspace (owner review 2, R8), and their handlers for the desktop's engine.</summary>
public static class WorkspaceJobs
{
/// <summary>
/// <see cref="JobKind.WorkspaceCopy"/>: the media of workspace project <paramref name="projectId"/> (checked out first,
/// <see cref="WorkspaceSync.CheckoutAsync"/>) copied from its home, the sequence of this PC's archive.
/// </summary>
public static ArchiveJobRequest Copy(Sequence sequence, string workspaceRoot, Guid projectId, string media = BundleMedia.Proxies)
{
ArgumentNullException.ThrowIfNull(sequence);
ArgumentException.ThrowIfNullOrWhiteSpace(workspaceRoot);
return new ArchiveJobRequest(JobKind.WorkspaceCopy, [sequence.Id], sequence.DisplayTitle,
JsonSerializer.Serialize(new WorkspaceCopyParameters(workspaceRoot, projectId, media), WorkspaceJson.Default.WorkspaceCopyParameters), JobPriority.User);
}
/// <summary>
/// <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 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>
/// <see cref="JobKind.WorkspaceRender"/> (phase 5c): workspace project <paramref name="projectId"/> rendered on this PC from
/// the originals its media hold, into its <c>exports/</c>, as <paramref name="renderJson"/> says (Protocol
/// <c>RenderJobParameters</c> with the portable settings: what <see cref="ProcessingJobs"/> writes for a render), each
/// output recorded with <paramref name="projectVersionId"/> in the project's ledger and sent home after. The target is the
/// home's sequence (this PC's archive, or <paramref name="server"/>'s, <see cref="SyncService.ServerKey"/>), so the
/// editor follows it as it follows a render of that sequence.
/// </summary>
public static ArchiveJobRequest Render(Guid sequenceId, string title, string workspaceRoot, Guid projectId, Guid? projectVersionId, string renderJson,
string? server = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(workspaceRoot);
ArgumentException.ThrowIfNullOrWhiteSpace(renderJson);
return new ArchiveJobRequest(JobKind.WorkspaceRender, [sequenceId], title,
JsonSerializer.Serialize(new WorkspaceRenderParameters(workspaceRoot, projectId, projectVersionId, renderJson, server),
WorkspaceJson.Default.WorkspaceRenderParameters), JobPriority.User);
}
/// <summary>
/// <see cref="JobKind.WorkspaceSend"/> (phase 5c): the local renders <paramref name="renderIds"/> of workspace project
/// <paramref name="projectId"/> (every unsent one of its ledger when empty) sent to its home, the sequence of this PC's
/// archive or of <paramref name="server"/> (<see cref="SyncService.ServerKey"/>), with their project and version.
/// </summary>
public static ArchiveJobRequest Send(Guid sequenceId, string title, string workspaceRoot, Guid projectId, IReadOnlyList<Guid> renderIds, string? server = null,
JobPriority priority = JobPriority.User)
{
ArgumentException.ThrowIfNullOrWhiteSpace(workspaceRoot);
ArgumentNullException.ThrowIfNull(renderIds);
return new ArchiveJobRequest(JobKind.WorkspaceSend, [sequenceId], title,
JsonSerializer.Serialize(new WorkspaceSendParameters(workspaceRoot, projectId, [.. renderIds], server), WorkspaceJson.Default.WorkspaceSendParameters),
priority);
}
/// <summary>
/// <see cref="JobKind.WorkspaceMove"/> (phase 5c): the workspace folder <paramref name="from"/> moved with its projects to
/// <paramref name="to"/>, as the plan of fingerprint <paramref name="planFingerprint"/> the user confirmed showed it. The
/// job has no target; its label is the folder it moves to.
/// </summary>
public static ArchiveJobRequest Move(string from, string to, string planFingerprint)
{
ArgumentException.ThrowIfNullOrWhiteSpace(from);
ArgumentException.ThrowIfNullOrWhiteSpace(to);
ArgumentException.ThrowIfNullOrWhiteSpace(planFingerprint);
return new ArchiveJobRequest(JobKind.WorkspaceMove, [], to,
JsonSerializer.Serialize(new WorkspaceMoveParameters(from, to, planFingerprint), WorkspaceJson.Default.WorkspaceMoveParameters), JobPriority.User);
}
/// <summary>The parameters of a <see cref="JobKind.WorkspaceRender"/> job; null when it has none that read.</summary>
public static WorkspaceRenderParameters? RenderParameters(Job job) => Read(job, JobKind.WorkspaceRender, WorkspaceJson.Default.WorkspaceRenderParameters);
/// <summary>The parameters of a <see cref="JobKind.WorkspaceSend"/> job; null when it has none that read.</summary>
public static WorkspaceSendParameters? SendParameters(Job job) => Read(job, JobKind.WorkspaceSend, WorkspaceJson.Default.WorkspaceSendParameters);
/// <summary>The parameters of a <see cref="JobKind.WorkspaceMove"/> job; null when it has none that read.</summary>
public static WorkspaceMoveParameters? MoveParameters(Job job) => Read(job, JobKind.WorkspaceMove, WorkspaceJson.Default.WorkspaceMoveParameters);
/// <summary>The parameters of a <see cref="JobKind.WorkspaceCopy"/> job; null when it has none that read.</summary>
public static WorkspaceCopyParameters? CopyParameters(Job job) => Read(job, JobKind.WorkspaceCopy, WorkspaceJson.Default.WorkspaceCopyParameters);
/// <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) =>
CreateHandlers(db, archives, servers, WorkspaceJobOptions.For(archives));
/// <summary>
/// The handlers of every workspace job (phase 5c): the copy of a project's media, its local render, the sending of its
/// renders home and the move of the workspace folder.
/// </summary>
/// <param name="servers">The connection a copy from, or a send to, a server's sequence goes through (the desktop's signed-in session).</param>
/// <param name="options">The desktop's processing options, its hold on transfers and what follows a moved folder.</param>
public static IReadOnlyList<IJobHandler> CreateHandlers(ChronosDatabase db, ArchiveService archives, ISyncConnector? servers, WorkspaceJobOptions options)
{
ArgumentNullException.ThrowIfNull(db);
ArgumentNullException.ThrowIfNull(archives);
ArgumentNullException.ThrowIfNull(options);
return
[
new WorkspaceCopyJobHandler(db, archives, servers),
new WorkspaceRenderJobHandler(db, archives, options),
new WorkspaceSendJobHandler(db, archives, servers, options),
new WorkspaceMoveJobHandler(db, options),
];
}
/// <summary>
/// What a first copy of a sequence's proxies writes into a workspace, as the copy reckons it before it starts (the
/// archive's proxies' sizes, an estimate for those it makes), and the free bytes on <paramref name="workspaceRoot"/>'s
/// drive (null when it cannot be measured): "Open in workspace" shows both. The copy keeps <see cref="CopySpaceReserve"/>
/// free besides.
/// </summary>
/// <exception cref="InvalidOperationException">The index has no such sequence or archive.</exception>
public static Task<(long Bytes, long? Free)> CopyFactsAsync(ChronosDatabase db, ArchiveService archives, Guid sequenceId, string workspaceRoot,
CancellationToken cancellationToken = default) =>
new WorkspaceCopyJobHandler(db, archives).FactsAsync(sequenceId, workspaceRoot, cancellationToken);
/// <summary>Bytes the copy leaves free on the workspace's drive besides what it copies.</summary>
public static long CopySpaceReserve => WorkspaceCopyJobHandler.SpaceReserve;
private static T? Read<T>(Job job, JobKind kind, System.Text.Json.Serialization.Metadata.JsonTypeInfo<T> info) where T : class
{
ArgumentNullException.ThrowIfNull(job);
if (job.Kind != kind || job.ParametersJson is not { Length: > 0 } json) return null;
try
{
return JsonSerializer.Deserialize(json, info);
}
catch (JsonException)
{
return null;
}
}
}
+40 -3
View File
@@ -17,6 +17,13 @@ namespace Chronos.Data.Workspaces;
/// 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>
/// <param name="Original">
/// The frame's original the workspace holds, relative to the media folder (<see cref="WorkspaceProject.OriginalName"/>:
/// "originals/&lt;frame id&gt;-&lt;sha8&gt;&lt;ext&gt;", phase 5c), in media of kind <see cref="BundleMedia.Originals"/>; null
/// when it holds none (proxies only, or the home had no original of the frame: the proxy stands in for editing).
/// </param>
/// <param name="OriginalSha256">The original's SHA-256 as copied and checked (lower case); null with <paramref name="Original"/>.</param>
/// <param name="OriginalBytes">The original's size as copied; 0 with no original.</param>
public sealed record WorkspaceFrame(
Guid Id,
int Index,
@@ -46,7 +53,10 @@ public sealed record WorkspaceFrame(
string? File,
string? FileSha256,
long FileBytes,
string? FileKind = null)
string? FileKind = null,
string? Original = null,
string? OriginalSha256 = null,
long OriginalBytes = 0)
{
/// <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)
@@ -62,6 +72,24 @@ public sealed record WorkspaceFrame(
[JsonIgnore]
public bool IsStandIn => FileKind == Sync.ProxyCache.Thumb;
/// <summary>The workspace holds the frame's original (media of kind <see cref="BundleMedia.Originals"/>).</summary>
[JsonIgnore]
public bool HasOriginal => Original is not null;
/// <summary>
/// The frame as a render from the workspace's originals reads it (phase 5c): its file is <see cref="Original"/>, and
/// it is flagged missing while the workspace holds no original for it (a render refuses such media first).
/// </summary>
public Frame ToOriginalFrame(Guid sequenceId)
{
var frame = ToFrame(sequenceId);
return frame with
{
RelativePath = Original ?? FileName,
Flags = Original is null ? Flags | FrameFlags.Missing : Flags,
};
}
/// <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()
{
@@ -97,8 +125,10 @@ public sealed record WorkspaceFrame(
/// <summary>
/// What a workspace project holds of its sequence's photos (<c>media/media.json</c>, owner review 2, R8): the kind
/// (<see cref="BundleMedia.Proxies"/>; originals in phase 5c), the sequence and its frames version at the home when they
/// were copied, and every frame in index order. Written last by a copy, so a copy cut short leaves the previous index.
/// (<see cref="BundleMedia.Proxies"/>, or from phase 5c <see cref="BundleMedia.Originals"/>: the proxies plus each frame's
/// original, <see cref="WorkspaceFrame.Original"/>), the sequence and its frames version at the home when they were
/// copied, and every frame in index order. Written last by a copy, so a copy cut short leaves the previous index. An index
/// of phase 5b has no original fields: it reads as proxies only.
/// </summary>
/// <param name="Aliases">The encodings of the sequence's photos a conversion joined at the home (R7, its tombstones of reason
/// "replaced") when the media were copied: a version parked on a photo before its file was converted still finds its frame.</param>
@@ -115,6 +145,13 @@ public sealed record WorkspaceMedia(string Format, int FormatVersion, string Kin
/// <summary>The frames held, as the processing engine reads them.</summary>
public IReadOnlyList<Frame> ToFrames() => [.. Frames.Select(f => f.ToFrame(SequenceId))];
/// <summary>The frames over the originals the workspace holds (<see cref="WorkspaceFrame.ToOriginalFrame"/>), as a local render reads them.</summary>
public IReadOnlyList<Frame> ToOriginalFrames() => [.. Frames.Select(f => f.ToOriginalFrame(SequenceId))];
/// <summary>Media of kind <see cref="BundleMedia.Originals"/>: the proxies plus the originals the frames name.</summary>
[JsonIgnore]
public bool HoldsOriginals => Kind == BundleMedia.Originals;
/// <summary>
/// These media with their photos named as <paramref name="home"/> names them now (owner review 2, R8): a frame copied
/// before the home hashed its photo (a folder adopted, verified since) takes the SHA-256 the home's frame of that id has
@@ -0,0 +1,23 @@
using Chronos.Core.Model;
using Chronos.Data.Jobs;
namespace Chronos.Data.Workspaces;
/// <summary>
/// <see cref="JobKind.WorkspaceMove"/> (phase 5c, <see cref="WorkspaceJobs.Move"/>): the workspace folder moved with its
/// projects, after the plan the user confirmed (its fingerprint checked again): journaled in <c>&lt;from&gt;/.move.json</c>,
/// moved per project on one volume, copied and hash-verified on both sides across volumes, a project's source deleted only
/// once every file of it is verified, resumable from the journal; at the end <see cref="WorkspaceJobOptions.Moved"/> is told.
/// On failure the source stays the workspace and unverified partial copies are removed.
/// </summary>
internal sealed class WorkspaceMoveJobHandler(ChronosDatabase db, WorkspaceJobOptions options) : IJobHandler
{
public JobKind Kind => JobKind.WorkspaceMove;
public Task RunAsync(JobContext context)
{
ArgumentNullException.ThrowIfNull(context);
_ = (db, options);
throw new NotImplementedException("Moving the workspace folder comes with phase 5c (P6).");
}
}
@@ -0,0 +1,24 @@
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
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.
/// </summary>
internal sealed class WorkspaceRenderJobHandler(ChronosDatabase db, ArchiveService archives, WorkspaceJobOptions options) : IJobHandler
{
public JobKind Kind => JobKind.WorkspaceRender;
public Task RunAsync(JobContext context)
{
ArgumentNullException.ThrowIfNull(context);
_ = (db, archives, options);
throw new NotImplementedException("Local renders of a workspace project come with phase 5c (P2).");
}
}
@@ -0,0 +1,136 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using Chronos.Core.IO;
using Chronos.Core.Model;
namespace Chronos.Data.Workspaces;
/// <summary>
/// One local render of a workspace project (phase 5c), as its ledger (<see cref="WorkspaceRenders"/>) records it: the output
/// a <see cref="JobKind.WorkspaceRender"/> wrote into the project's <c>exports/</c>, its SHA-256 and size as written, what it
/// is (preset, codec, size, rate, length), the project and version it was rendered from, and whether it went home
/// (<see cref="JobKind.WorkspaceSend"/>). The file stays in <c>exports/</c> after it is sent, until a clean-up removes it.
/// </summary>
/// <param name="RenderId">
/// The render's id, the same at the home once sent (<c>RenderJobHandler.RenderId(jobId, index)</c>): a send repeated after a
/// cut finds the home holding it already, and nothing is filed twice.
/// </param>
/// <param name="JobId">The <see cref="JobKind.WorkspaceRender"/> job that wrote it.</param>
/// <param name="File">The output, relative to the project's <c>exports/</c> folder (forward slashes; <see cref="WorkspaceProject.ExportFile"/>).</param>
/// <param name="Sha256">The output's SHA-256 (lower case) as it was written: a send hashes the file again and refuses another.</param>
/// <param name="Size">The output's size in bytes.</param>
/// <param name="ProjectVersionId">The project version rendered; null for a working state no version names.</param>
/// <param name="SettingsHash">The content hash of the portable settings rendered (<c>ProjectContent</c>); null when not known.</param>
/// <param name="Rendered">When the output was finished.</param>
/// <param name="State"><see cref="Pending"/>, <see cref="SentState"/> or <see cref="Failed"/> (a later Chronos may write others: read as pending).</param>
/// <param name="Sent">When the home took it; null until then.</param>
/// <param name="Error">Why the last send failed (one localized sentence); null otherwise.</param>
public sealed record WorkspaceRenderEntry(
Guid RenderId,
Guid JobId,
string File,
string Sha256,
long Size,
string PresetName,
string? Codec,
int Width,
int Height,
double Fps,
double DurationSeconds,
Guid ProjectId,
Guid? ProjectVersionId,
string? SettingsHash,
DateTimeOffset Rendered,
string State = WorkspaceRenderEntry.Pending,
DateTimeOffset? Sent = null,
string? Error = null)
{
/// <summary>Written, not at the home yet.</summary>
public const string Pending = "pending";
/// <summary>The home holds it (a render row of the home's sequence with this id).</summary>
public const string SentState = "sent";
/// <summary>The last send failed (<see cref="Error"/> says why); sent again by the next send.</summary>
public const string Failed = "failed";
/// <summary>The home holds this render.</summary>
[JsonIgnore]
public bool IsSent => State == SentState;
/// <summary>Not at the home yet: pending, failed, or a state this Chronos does not know. A clean-up never removes its file.</summary>
[JsonIgnore]
public bool IsUnsent => !IsSent;
/// <summary>This entry as taken by the home at <paramref name="at"/>.</summary>
public WorkspaceRenderEntry AsSent(DateTimeOffset at) => this with { State = SentState, Sent = at, Error = null };
/// <summary>This entry after a send that failed for <paramref name="error"/>; it stays to be sent again.</summary>
public WorkspaceRenderEntry AsFailed(string error) => this with { State = Failed, Error = error };
}
/// <summary>
/// The ledger of a workspace project's local renders (<c>exports/renders.json</c>, phase 5c): every output a
/// <see cref="JobKind.WorkspaceRender"/> finished, oldest first, one entry per render id. Read whole and written whole and
/// atomically (temporary file, flush, rename), always under the project's lease; a missing ledger is an empty one.
/// </summary>
public sealed record WorkspaceRenders(string Format, int FormatVersion, IReadOnlyList<WorkspaceRenderEntry> Entries)
{
public const string FormatName = "chronos-workspace-renders";
public const int CurrentFormatVersion = 1;
/// <summary>A ledger without entries.</summary>
public static WorkspaceRenders Empty { get; } = new(FormatName, CurrentFormatVersion, []);
/// <summary>The entries not at the home yet (<see cref="WorkspaceRenderEntry.IsUnsent"/>), oldest first.</summary>
[JsonIgnore]
public IReadOnlyList<WorkspaceRenderEntry> Unsent => [.. Entries.Where(e => e.IsUnsent)];
/// <summary>The entry of <paramref name="renderId"/>; null when the ledger has none.</summary>
public WorkspaceRenderEntry? Find(Guid renderId) => Entries.FirstOrDefault(e => e.RenderId == renderId);
/// <summary>This ledger with <paramref name="entry"/> in place of the entry of its render id, or appended when it has none.</summary>
public WorkspaceRenders With(WorkspaceRenderEntry entry)
{
ArgumentNullException.ThrowIfNull(entry);
var entries = Entries.ToList();
var at = entries.FindIndex(e => e.RenderId == entry.RenderId);
if (at >= 0) entries[at] = entry;
else entries.Add(entry);
return this with { Entries = entries };
}
/// <summary>This ledger without the entry of <paramref name="renderId"/> (a sent file a clean-up removed, a discarded render).</summary>
public WorkspaceRenders Without(Guid renderId) => Entries.Any(e => e.RenderId == renderId) ? this with { Entries = [.. Entries.Where(e => e.RenderId != renderId)] } : this;
/// <summary>The ledger at <paramref name="path"/>; <see cref="Empty"/> when there is none.</summary>
/// <exception cref="InvalidDataException">The file is no ledger, is damaged, or a newer Chronos wrote it.</exception>
/// <exception cref="IOException">The file cannot be read.</exception>
public static WorkspaceRenders Read(string path)
{
ArgumentException.ThrowIfNullOrEmpty(path);
if (!System.IO.File.Exists(path)) return Empty;
WorkspaceRenders? renders;
try
{
renders = JsonSerializer.Deserialize(AtomicFile.ReadAllText(path), WorkspaceJson.Default.WorkspaceRenders);
}
catch (JsonException ex)
{
throw new InvalidDataException($"{path} cannot be read.", ex);
}
if (renders is null || renders.Format != FormatName || renders.Entries is null) throw new InvalidDataException($"{path} is not a renders ledger.");
if (renders.FormatVersion > CurrentFormatVersion) throw new InvalidDataException($"{path} is newer than this Chronos.");
return renders;
}
/// <summary>Writes <paramref name="renders"/> to <paramref name="path"/> whole and atomically, making its folder when needed.</summary>
/// <exception cref="IOException">The file cannot be written; the ledger there stays as it was.</exception>
public static void Write(string path, WorkspaceRenders renders)
{
ArgumentException.ThrowIfNullOrEmpty(path);
ArgumentNullException.ThrowIfNull(renders);
if (Path.GetDirectoryName(Path.GetFullPath(path)) is { Length: > 0 } folder) Directory.CreateDirectory(folder);
AtomicFile.WriteAllText(path, JsonSerializer.Serialize(renders with { Format = FormatName, FormatVersion = CurrentFormatVersion }, WorkspaceJson.Default.WorkspaceRenders));
}
}
@@ -0,0 +1,25 @@
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Sync;
namespace Chronos.Data.Workspaces;
/// <summary>
/// <see cref="JobKind.WorkspaceSend"/> (phase 5c, <see cref="WorkspaceJobs.Send"/>): the local renders of a workspace project
/// sent home with their project and version, per unsent ledger entry: the file hashed again (another is refused and stays),
/// the version it names pushed first when the home lacks it, then filed in this PC's archive (as the sync files a server's
/// exports) or uploaded to its server (<c>RenderUploadRequest</c> with <c>ProjectId</c> and <c>ProjectVersionId</c>), and the
/// entry marked sent. Idempotent by render id: a send repeated after a cut finds the home holding it already.
/// </summary>
internal sealed class WorkspaceSendJobHandler(ChronosDatabase db, ArchiveService archives, ISyncConnector? servers, WorkspaceJobOptions options) : IJobHandler
{
public JobKind Kind => JobKind.WorkspaceSend;
public Task RunAsync(JobContext context)
{
ArgumentNullException.ThrowIfNull(context);
_ = (db, archives, servers, options);
throw new NotImplementedException("Sending a workspace project's renders home comes with phase 5c (P3).");
}
}
+72 -4
View File
@@ -91,17 +91,48 @@ public sealed record WorkspaceConflict(Guid TheirsVersionId, int TheirsNumber, G
/// <summary>
/// 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).
/// project whose media to copy and what to copy (<see cref="BundleMedia.Proxies"/>, or <see cref="BundleMedia.Originals"/>:
/// the proxies plus the originals, phase 5c).
/// </summary>
/// <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);
/// <summary>
/// Parameters of a <see cref="JobKind.WorkspaceRender"/> job (phase 5c): target = the home's sequence; the workspace folder,
/// the project rendered from the originals its media hold, the version rendered (null: the head version the workspace
/// holds), and the render's export settings as Protocol <c>RenderJobParameters</c> JSON (portable settings, preset,
/// overrides, batch), as <see cref="Processing.ProcessingJobs"/> writes them for a render.
/// </summary>
/// <param name="ProjectVersionId">The version rendered and recorded with each output; null renders the head version the workspace holds.</param>
/// <param name="RenderJson">Protocol <c>RenderJobParameters</c> as JSON.</param>
/// <param name="Server">The server the home's sequence is on (<see cref="SyncService.ServerKey"/>); null for a sequence of this PC's archive.</param>
public sealed record WorkspaceRenderParameters(string WorkspaceRoot, Guid ProjectId, Guid? ProjectVersionId, string RenderJson, string? Server = null);
/// <summary>
/// Parameters of a <see cref="JobKind.WorkspaceSend"/> job (phase 5c): target = the home's sequence; the workspace folder,
/// the project, and the ledger entries (<see cref="WorkspaceRenderEntry.RenderId"/>) whose files go home.
/// </summary>
/// <param name="RenderIds">The renders sent; empty sends every pending entry of the project's ledger.</param>
/// <param name="Server">The server the home's sequence is on (<see cref="SyncService.ServerKey"/>); null for a sequence of this PC's archive.</param>
public sealed record WorkspaceSendParameters(string WorkspaceRoot, Guid ProjectId, IReadOnlyList<Guid> RenderIds, string? Server = null);
/// <summary>
/// Parameters of a <see cref="JobKind.WorkspaceMove"/> job (phase 5c): no target; the workspace folder moved
/// (<paramref name="From"/>), the folder it goes to, and the fingerprint of the plan the user confirmed (the job refuses a
/// workspace that changed since).
/// </summary>
public sealed record WorkspaceMoveParameters(string From, string To, string PlanFingerprint);
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
UseStringEnumConverter = true, WriteIndented = true)]
[JsonSerializable(typeof(WorkspaceManifest))]
[JsonSerializable(typeof(WorkspaceMedia))]
[JsonSerializable(typeof(WorkspaceSyncState))]
[JsonSerializable(typeof(WorkspaceCopyParameters))]
[JsonSerializable(typeof(WorkspaceRenderParameters))]
[JsonSerializable(typeof(WorkspaceSendParameters))]
[JsonSerializable(typeof(WorkspaceMoveParameters))]
[JsonSerializable(typeof(WorkspaceRenders))]
internal sealed partial class WorkspaceJson : JsonSerializerContext;
/// <summary>
@@ -309,9 +340,11 @@ public sealed class WorkspaceStore
/// <summary>
/// One project in the workspace (owner review 2, R8): <c>&lt;root&gt;/&lt;project id&gt;/</c> with
/// <c>project.chronos</c> (the working state: a project file of format 2, its settings placed on the media's frames),
/// <c>media/media.json</c> with <c>media/proxies/&lt;frame id&gt;.jpg</c> (originals later) and <c>media/analysis.json</c>
/// (the home's deep report), <c>versions/&lt;number&gt;-&lt;id&gt;.json</c> (commits not pushed yet, and the versions pulled),
/// <c>sync.json</c>, <c>exports/</c> and the lease <c>.lock.lease</c> that one writer at a time holds.
/// <c>media/media.json</c> with <c>media/proxies/&lt;frame id&gt;.jpg</c>, <c>media/originals/&lt;frame id&gt;-&lt;sha8&gt;&lt;ext&gt;</c>
/// (media of kind originals, phase 5c) and <c>media/analysis.json</c> (the home's deep report),
/// <c>versions/&lt;number&gt;-&lt;id&gt;.json</c> (commits not pushed yet, and the versions pulled), <c>sync.json</c>,
/// <c>exports/</c> with the local renders and their ledger <c>exports/renders.json</c> (phase 5c), and the lease
/// <c>.lock.lease</c> that one writer at a time holds.
/// </summary>
public sealed class WorkspaceProject
{
@@ -324,6 +357,12 @@ public sealed class WorkspaceProject
public const string ExportsFolder = "exports";
public const string SyncFile = "sync.json";
/// <summary>The name of the ledger of the project's local renders (<see cref="WorkspaceRenders"/>) in <see cref="ExportsFolder"/>.</summary>
public const string RendersFileName = "renders.json";
/// <summary>The ledger of the project's local renders (phase 5c), relative to <see cref="Folder"/>.</summary>
public const string RendersFile = ExportsFolder + "/" + RendersFileName;
/// <summary>
/// Old local commits replaced by their replay on top of the home's head, files the home's copy replaced, and the working
/// states a take of the server's values replaced: kept up to a month, the newest 20 at most (<see cref="PruneReplaced"/>).
@@ -365,6 +404,9 @@ public sealed class WorkspaceProject
public string ExportsDirectory => Path.Combine(Folder, ExportsFolder);
public string SyncPath => Path.Combine(Folder, SyncFile);
/// <summary>The ledger of the project's local renders (<see cref="RendersFile"/>, phase 5c).</summary>
public string RendersPath => Path.Combine(ExportsDirectory, RendersFileName);
public bool Exists => File.Exists(BundlePath);
/// <summary>The file a frame's proxy is copied to, relative to <see cref="MediaDirectory"/>.</summary>
@@ -380,9 +422,35 @@ public sealed class WorkspaceProject
return ProxiesFolder + "/" + frameId.ToString("N") + "-" + sha256[..Math.Min(16, sha256.Length)].ToLowerInvariant() + ".jpg";
}
/// <summary>
/// The file a frame's original is copied to, relative to <see cref="MediaDirectory"/> (phase 5c):
/// <c>originals/&lt;frame id&gt;-&lt;sha8&gt;&lt;ext&gt;</c>. The first 8 hex digits of its SHA-256 tell two encodings of one
/// frame apart (a conversion since: the editor keeps the one it reads until the copy commits), and the original's own
/// extension is kept, lower case, since decoders go by it.
/// </summary>
/// <param name="extension">The original's extension, with or without its dot (".CR3", "dng", or the file name's <see cref="Path.GetExtension(string)"/>); empty or null for none.</param>
public static string OriginalName(Guid frameId, string sha256, string? extension)
{
ArgumentException.ThrowIfNullOrEmpty(sha256);
var ext = (extension ?? string.Empty).Trim().TrimStart('.').ToLowerInvariant();
if (ext.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || ext.Contains('/') || ext.Contains('\\')) ext = string.Empty;
return OriginalsFolder + "/" + frameId.ToString("N") + "-" + sha256[..Math.Min(8, sha256.Length)].ToLowerInvariant() + (ext.Length > 0 ? "." + ext : string.Empty);
}
/// <summary>The ledger of the project's local renders; empty while it has none (<see cref="WorkspaceRenders.Read"/>).</summary>
/// <exception cref="InvalidDataException">The ledger is damaged or newer.</exception>
/// <exception cref="IOException">The ledger cannot be read.</exception>
public WorkspaceRenders ReadRenders() => WorkspaceRenders.Read(RendersPath);
/// <summary>Writes the ledger of the project's local renders whole and atomically (<see cref="WorkspaceRenders.Write"/>); the caller holds the project's lease.</summary>
public void WriteRenders(WorkspaceRenders renders) => WorkspaceRenders.Write(RendersPath, renders);
/// <summary>The absolute path of a file named relative to <see cref="MediaDirectory"/>.</summary>
public string MediaFile(string relative) => LongPath.FromPortableRelative(MediaDirectory, relative);
/// <summary>The absolute path of a local render named relative to <see cref="ExportsDirectory"/> (<see cref="WorkspaceRenderEntry.File"/>).</summary>
public string ExportFile(string relative) => LongPath.FromPortableRelative(ExportsDirectory, relative);
/// <summary>Holds the project for one writer (this program's sync, a copy job) until disposed.</summary>
/// <exception cref="LeaseUnavailableException">Another writer kept it for longer than <paramref name="wait"/>.</exception>
public async Task<IDisposable> LockAsync(TimeSpan wait, CancellationToken cancellationToken = default)
+7 -1
View File
@@ -46,6 +46,10 @@ public sealed record CardImportReport(Guid ImportId, string Card, string State,
/// and files the render under the sequence's exports. A completion that cannot file it for now answers 503
/// <c>sequence_busy</c>, <c>archive_offline</c> or <c>folder_moved</c> (another index moved the sequence's folder; the
/// server's next scan finds it) and keeps the upload, to be completed again.
/// A render a workspace made on a client (phase 5c) names the project and version it was rendered from
/// (<see cref="ProjectId"/>, <see cref="ProjectVersionId"/>): the server records them with the render once it checked that
/// the project is the sequence's and the version the project's (422 <c>project_mismatch</c> otherwise). Both are optional
/// and appended: a request of an earlier client has neither, and an earlier server ignores them.
/// </summary>
public sealed record RenderUploadRequest(
Guid RenderId,
@@ -58,4 +62,6 @@ public sealed record RenderUploadRequest(
int Height,
double Fps,
double DurationSeconds,
string? ProducedBy);
string? ProducedBy,
Guid? ProjectId = null,
Guid? ProjectVersionId = null);