fix(workspace): close the phase 5c review findings
Originals are now judged by their bytes, never by the media index: a removal or clean-up hashes every file under media/originals and deletes it only when the home holds that SHA-256; every other file, named or not, goes to the workspace trash. Trash entries are filled under a staging name that Empty never lists. A ledger can only name files inside exports/. Jobs follow the workspace: a copy, render or send resolves the folder that holds its project now (a moved workspace, a retry after a move) and waits while a move has not switched yet. A clean-up failure after the switch is a warning that keeps the journal for a later resume; entries that changed since they were copied are kept, and a same-volume rename refused across volumes falls back to copy and verify. Sends map a replayed version by content hash, or go with the project only, and note an old server that drops provenance. The media index (format 2) and project file (format 3) refuse older readers while they hold originals. Metered connections also hold sync downloads and server copies. The editor gains Send again, the Settings page can resume a stopped move, the disabled tooltips say why, and unused strings are pruned. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
09fcff4eb2
commit
2654683a12
125 files changed
+1618
-401
No files matched your search
@@ -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}}" />
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Link}" Content="{l:Loc Editor.Render.SendAgain}" Command="{Binding SendAgainCommand}"
|
||||
ToolTip="{Binding SendAgainToolTip}" ToolTipService.ShowOnDisabled="True" Margin="6,0,0,0"
|
||||
Visibility="{Binding HasUnsent, 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}}" />
|
||||
|
||||
@@ -241,8 +241,8 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
/// <summary>The Export "Sync" option: available, or why not.</summary>
|
||||
public ExportSyncGate SyncGate { get => _syncGate; private set => Set(ref _syncGate, value); }
|
||||
|
||||
/// <summary>The server job the header shows (<see cref="SequenceJobs.Shown"/>).</summary>
|
||||
private Job? ServerJob => IsRemote ? _jobs.Shown : null;
|
||||
/// <summary>The server job the header shows (<see cref="SequenceJobs.ShownAtHome"/>): never a workspace project's render on this PC or its send.</summary>
|
||||
private Job? ServerJob => IsRemote ? _jobs.ShownAtHome : null;
|
||||
|
||||
/// <summary>
|
||||
/// "3,600 frames · Canon EOS R5 · 2 s interval · 2 h 00 m · 3 warnings"; on the Export tab what the video will be:
|
||||
|
||||
@@ -3,12 +3,16 @@ using System.IO;
|
||||
using System.Windows.Input;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Settings;
|
||||
using Chronos.App.Shell;
|
||||
using Chronos.App.Workspace;
|
||||
using Chronos.Core.Advice;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Video;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Ui.Controls;
|
||||
using Chronos.Ui.Mvvm;
|
||||
@@ -406,6 +410,34 @@ public sealed class ExportTab : EditorTab
|
||||
/// <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>Send again: queues the sending home of every render made here not sent yet; disabled while one is queued from here.</summary>
|
||||
public ICommand SendAgainCommand => _sendAgain ??= new AsyncRelayCommand(SendAgainAsync, () => HasUnsent && !_sendQueued);
|
||||
|
||||
private AsyncRelayCommand? _sendAgain;
|
||||
|
||||
/// <summary>A send was queued from here and the ledger was not read again since.</summary>
|
||||
private bool _sendQueued;
|
||||
|
||||
/// <summary>What Send again does, worded for the project's home.</summary>
|
||||
public string SendAgainToolTip => WorkspaceText.ForHome("Tooltips.Editor.Render.SendAgain", Editor.Session.Source is WorkspaceSequenceSource { IsServerHome: true });
|
||||
|
||||
private async Task SendAgainAsync()
|
||||
{
|
||||
if (Editor.Session.Source is not WorkspaceSequenceSource source) return;
|
||||
try
|
||||
{
|
||||
_sendQueued = await Editor.Shell.Services.Workspace.SendRendersAsync(source.ProjectId);
|
||||
_sendAgain?.RaiseCanExecuteChanged();
|
||||
if (_sendQueued)
|
||||
Editor.Shell.Notify(Loc.L("Editor.Render.Sending"), Editor.Title, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Editor.Shell.Navigate(SectionKey.Jobs));
|
||||
}
|
||||
catch (Exception ex) when (ex is WorkspaceException or IOException or InvalidDataException or UnauthorizedAccessException or DatabaseException)
|
||||
{
|
||||
Log.Warning("editor", $"The renders of workspace project {source.ProjectId} could not be queued to be sent", ex);
|
||||
Editor.Shell.Notify(Loc.L("Editor.Render.SendFailed"), ex is WorkspaceException ? ex.Message : ErrorText.For(ex), isError: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <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")
|
||||
@@ -484,6 +516,9 @@ public sealed class ExportTab : EditorTab
|
||||
|
||||
public override void OnContentChanged()
|
||||
{
|
||||
// The ledger was read again: Send again goes by what it holds now.
|
||||
_sendQueued = false;
|
||||
_sendAgain?.RaiseCanExecuteChanged();
|
||||
LoadCards();
|
||||
if (SelectedCopy is null || !SavedCopies.Contains(SelectedCopy)) SelectedCopy = SavedCopies.FirstOrDefault();
|
||||
base.OnContentChanged();
|
||||
|
||||
@@ -20,6 +20,16 @@ public sealed class SequenceJobs(Guid sequenceId)
|
||||
/// <summary>The job to show: one running, else one paused, else the oldest waiting; null when there is none.</summary>
|
||||
public Job? Shown => First(_active.Values);
|
||||
|
||||
/// <summary>
|
||||
/// The job a server sequence's header shows, chosen as <see cref="Shown"/> is among the jobs that run at its home: a
|
||||
/// workspace project's render on this PC and its send home are this PC's jobs (the Jobs screen and the Export tab say
|
||||
/// them), never the server's.
|
||||
/// </summary>
|
||||
public Job? ShownAtHome => First(_active.Values.Where(j => !IsLocalKind(j.Kind)));
|
||||
|
||||
/// <summary>A workspace project's render on this PC or its send home (phase 5c): this PC's job whatever the home.</summary>
|
||||
public static bool IsLocalKind(JobKind kind) => kind is JobKind.WorkspaceRender or JobKind.WorkspaceSend;
|
||||
|
||||
/// <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));
|
||||
|
||||
|
||||
@@ -192,12 +192,14 @@ public sealed class AppServices : IAsyncDisposable
|
||||
|
||||
/// <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.
|
||||
/// Settings › Server over transfers with a server, the workspace that follows a moved folder, and the folder in use
|
||||
/// (a job queued before a move finds its project there).
|
||||
/// </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);
|
||||
services.Workspace.MovedAsync,
|
||||
() => services.Workspace.Root);
|
||||
|
||||
/// <summary>
|
||||
/// Queues a scan of <paramref name="archive"/> unless one is already waiting or running; the sequences it indexes get
|
||||
|
||||
@@ -211,6 +211,18 @@ public sealed class AppSettings
|
||||
/// <summary>Which project Edit opens for a sequence with several in the workspace.</summary>
|
||||
public WorkspaceOpenPolicy WorkspaceOpenProject { get; set; } = WorkspaceOpenPolicy.LastUsed;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="WorkspaceDefaultMedia"/> as everything applies it: the originals for any case of "originals", else the
|
||||
/// proxies (a value set elsewhere reads as the proxies). Settings › Workspace shows the same.
|
||||
/// </summary>
|
||||
[System.Text.Json.Serialization.JsonIgnore]
|
||||
public string EffectiveDefaultMedia =>
|
||||
string.Equals(WorkspaceDefaultMedia, BundleMedia.Originals, StringComparison.OrdinalIgnoreCase) ? BundleMedia.Originals : BundleMedia.Proxies;
|
||||
|
||||
/// <summary><see cref="WorkspaceOpenProject"/> as everything applies it: a value this Chronos does not know reads as the last used. Settings › Workspace shows the same.</summary>
|
||||
[System.Text.Json.Serialization.JsonIgnore]
|
||||
public WorkspaceOpenPolicy EffectiveOpenPolicy => Enum.IsDefined(WorkspaceOpenProject) ? WorkspaceOpenProject : 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"/>.
|
||||
@@ -236,7 +248,7 @@ public sealed class AppSettings
|
||||
/// <summary>Send and take project settings changed on one side without asking (Server.html).</summary>
|
||||
public bool SyncSettingsAutomatically { get; set; } = true;
|
||||
|
||||
/// <summary>Pause transfers with a server (uploads, workspace copies and renders sent) while Windows reports the connection as metered (Server.html).</summary>
|
||||
/// <summary>Pause transfers with a server (uploads, sync downloads, workspace copies and renders sent) while Windows reports the connection as metered (Server.html).</summary>
|
||||
public bool PauseUploadsOnMetered { get; set; }
|
||||
|
||||
// ---- Jobs ----
|
||||
|
||||
@@ -871,8 +871,7 @@ public sealed class SequenceViewModel : SectionViewModel
|
||||
}
|
||||
|
||||
/// <summary>The media a checkout copies unless "Open in workspace" chose: Settings › Workspace › Media.</summary>
|
||||
private static string DefaultMedia(AppServices services) =>
|
||||
services.Settings.WorkspaceDefaultMedia == BundleMedia.Originals ? BundleMedia.Originals : BundleMedia.Proxies;
|
||||
private static string DefaultMedia(AppServices services) => services.Settings.EffectiveDefaultMedia;
|
||||
|
||||
/// <summary>
|
||||
/// The project of the sequence Edit opens when none was asked for (phase 5c, Settings › Workspace › Open project): the
|
||||
@@ -883,7 +882,7 @@ public sealed class SequenceViewModel : SectionViewModel
|
||||
Func<WorkspaceEntry, bool> fits)
|
||||
{
|
||||
var last = await workspace.LastUsedAsync(sequenceId) is { } used && fits(used) ? used : null;
|
||||
var policy = services.Settings.WorkspaceOpenProject;
|
||||
var policy = services.Settings.EffectiveOpenPolicy;
|
||||
if (policy == WorkspaceOpenPolicy.LastUsed) return (false, last);
|
||||
var here = (await workspace.ProjectsOfAsync(sequenceId)).Where(p => fits(p) && p.IsReadable).ToList();
|
||||
if (policy == WorkspaceOpenPolicy.Main) return (false, here.FirstOrDefault(p => p.IsMain) ?? last);
|
||||
@@ -1121,6 +1120,8 @@ public sealed class SequenceViewModel : SectionViewModel
|
||||
if (section.Shell.Services.Database is not { } db || await db.Sequences.GetAsync(sequenceId) is not { } row) return;
|
||||
if (section.Shell.Library.Items.FirstOrDefault(i => i.Id == row.Id) is { } item) item.Update(row);
|
||||
}
|
||||
|
||||
public void ShowJobs() => section.Shell.Navigate(SectionKey.Jobs);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -532,17 +532,21 @@
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBox Style="{StaticResource TextBox.Path}" IsReadOnly="True" Text="{Binding WorkspaceRows.Folder, Mode=OneWay}" ToolTip="{l:Loc Tooltips.Settings.Workspace.Folder}"
|
||||
AutomationProperties.Name="{l:Loc Settings.Workspace.Folder}" />
|
||||
<Button Grid.Column="1" Content="{l:Loc Common.Open}" Command="{Binding WorkspaceRows.OpenCommand}" ToolTip="{l:Loc Tooltips.Settings.OpenWorkspace}"
|
||||
Margin="10,0,0,0" />
|
||||
<Button Grid.Column="2" Content="{l:Loc Settings.Workspace.Change}" Command="{Binding WorkspaceRows.ChangeCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Settings.ChangeWorkspace}" Margin="8,0,0,0"
|
||||
ToolTip="{Binding WorkspaceRows.ChangeToolTip}" ToolTipService.ShowOnDisabled="True" Margin="8,0,0,0"
|
||||
Visibility="{Binding WorkspaceRows.CanChange, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button Grid.Column="3" Content="{l:Loc Settings.Workspace.Move}" Command="{Binding WorkspaceRows.MoveCommand}"
|
||||
ToolTip="{Binding WorkspaceRows.MoveToolTip}" ToolTipService.ShowOnDisabled="True" Margin="8,0,0,0"
|
||||
Visibility="{Binding WorkspaceRows.CanMove, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button Grid.Column="4" Content="{l:Loc Settings.Workspace.ResumeMove}" Command="{Binding WorkspaceRows.ResumeMoveCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Settings.Workspace.ResumeMove}" Margin="8,0,0,0"
|
||||
Visibility="{Binding WorkspaceRows.CanResumeMove, Converter={StaticResource BoolToVisibility}}" />
|
||||
</Grid>
|
||||
<TextBlock Style="{StaticResource Text.Hint}" Text="{Binding WorkspaceRows.UsageText}" ToolTip="{l:Loc Tooltips.Settings.Workspace.Used}" Margin="0,6,0,0"
|
||||
Visibility="{Binding WorkspaceRows.HasUsageText, Converter={StaticResource BoolToVisibility}}" />
|
||||
|
||||
@@ -173,7 +173,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
// ---- Workspace ----
|
||||
WorkspaceRows = new WorkspaceSettingsRows(_s, Save, () => AppEnvironment.Shown(Shell.Services.Workspace.Root), OpenWorkspaceFolder, ChangeWorkspaceFolderAsync,
|
||||
WorkspaceSettingsServices.For(Shell.Services.Workspace, Shell.Services.Dialogs, (title, message, isError) => Shell.Notify(title, message, isError: isError),
|
||||
MoveWorkspaceFolderAsync));
|
||||
MoveWorkspaceFolderAsync, () => WorkspaceFolderChange.ResumeUnfinishedAsync(Shell)));
|
||||
|
||||
// ---- Storage ----
|
||||
// A capture shows its folders under a sample data folder; what is typed is taken back to the folder it stands for.
|
||||
@@ -991,6 +991,8 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
UpdateArchiveFree();
|
||||
ArchiveReload = LoadArchiveAsync();
|
||||
if (_page == SettingsPage.Advanced) LoadBackups();
|
||||
// What the workspace takes and holds in its trash may have changed elsewhere (a local copy removed in Edit).
|
||||
if (_page == SettingsPage.Workspace) _ = WorkspaceRows.MeasureAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -11,8 +11,8 @@ namespace Chronos.App.Server;
|
||||
/// <summary>
|
||||
/// "Pause metered transfers" (Server.html): while <see cref="AppSettings.PauseUploadsOnMetered"/> is on and Windows reports
|
||||
/// the connection as metered, the transfers with a server are paused (a running one stops after its current chunk or file
|
||||
/// and keeps its checkpoint): upload jobs, and since phase 5c the workspace's copies from a server and its renders sent to
|
||||
/// one (<see cref="Holds"/>); a copy from or a send to this PC's archive is never held. They are resumed when the connection
|
||||
/// and keeps its checkpoint): upload jobs, the sync's downloads, and since phase 5c the workspace's copies from a server and
|
||||
/// its renders sent to one (<see cref="Holds"/>); a copy from or a send to this PC's archive is never held. They are resumed when the connection
|
||||
/// is no longer metered or the option goes off. Only the jobs it paused are resumed. Checked when the network or one of
|
||||
/// those jobs changes, and every minute.
|
||||
/// </summary>
|
||||
@@ -65,18 +65,19 @@ public sealed class UploadHold : IDisposable
|
||||
}
|
||||
|
||||
/// <summary>The kinds of job a metered connection may hold (<see cref="Holds"/> says which of them).</summary>
|
||||
internal static IReadOnlyList<JobKind> Kinds { get; } = [JobKind.UploadCommit, JobKind.WorkspaceCopy, JobKind.WorkspaceSend];
|
||||
internal static IReadOnlyList<JobKind> Kinds { get; } = [JobKind.UploadCommit, JobKind.Download, JobKind.WorkspaceCopy, JobKind.WorkspaceSend];
|
||||
|
||||
/// <summary>
|
||||
/// Whether a metered connection holds <paramref name="job"/>: an upload, or a workspace copy or send whose home is a server
|
||||
/// (its parameters name one). One whose parameters cannot be read is not held: it fails with its reason.
|
||||
/// Whether a metered connection holds <paramref name="job"/>: an upload, a sync download (every one is from a server), or a
|
||||
/// workspace copy or send whose home is a server (its parameters name one). One whose parameters cannot be read is not
|
||||
/// held: it fails with its reason.
|
||||
/// </summary>
|
||||
internal static bool Holds(Job job)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(job);
|
||||
return job.Kind switch
|
||||
{
|
||||
JobKind.UploadCommit => true,
|
||||
JobKind.UploadCommit or JobKind.Download => true,
|
||||
JobKind.WorkspaceCopy => WorkspaceJobs.CopyParameters(job)?.Server is { Length: > 0 },
|
||||
JobKind.WorkspaceSend => WorkspaceJobs.SendParameters(job)?.Server is { Length: > 0 },
|
||||
_ => false,
|
||||
|
||||
@@ -36,11 +36,17 @@ public sealed class WorkspaceSettingsServices
|
||||
/// <summary>Picks a folder, shows the move's plan and queues it (<see cref="WorkspaceFolderChange.MoveAsync(Shell.ShellViewModel)"/>); null where the folder cannot move.</summary>
|
||||
public Func<Task>? Move { get; init; }
|
||||
|
||||
/// <summary>A move of the workspace folder is queued or running (<see cref="WorkspaceHost.IsMoving"/>).</summary>
|
||||
/// <summary>A move of the workspace folder is queued or running, or stopped with its journal (<see cref="WorkspaceHost.IsMoving"/>; reads the disk).</summary>
|
||||
public Func<bool> IsMoving { get; init; } = () => false;
|
||||
|
||||
/// <summary>A move stopped before it ended, no job taking it up (<see cref="WorkspaceHost.UnfinishedMoveAsync"/>); null where none is looked for.</summary>
|
||||
public Func<CancellationToken, Task<bool>>? HasUnfinishedMove { get; init; }
|
||||
|
||||
/// <summary>Queues again the move that stopped (<see cref="WorkspaceFolderChange.ResumeUnfinishedAsync"/>); null where it cannot.</summary>
|
||||
public Func<Task>? ResumeMove { get; init; }
|
||||
|
||||
/// <summary>The workspace's own operations, with the shell's <paramref name="dialogs"/> and toasts (<paramref name="notify"/>).</summary>
|
||||
public static WorkspaceSettingsServices For(WorkspaceHost host, IAppDialogs dialogs, Action<string, string?, bool> notify, Func<Task>? move)
|
||||
public static WorkspaceSettingsServices For(WorkspaceHost host, IAppDialogs dialogs, Action<string, string?, bool> notify, Func<Task>? move, Func<Task>? resume = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(host);
|
||||
ArgumentNullException.ThrowIfNull(dialogs);
|
||||
@@ -54,6 +60,8 @@ public sealed class WorkspaceSettingsServices
|
||||
Notify = notify,
|
||||
Move = move,
|
||||
IsMoving = () => host.IsMoving,
|
||||
HasUnfinishedMove = async token => await host.UnfinishedMoveAsync(token) is not null,
|
||||
ResumeMove = resume,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -83,6 +91,12 @@ public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Fun
|
||||
private bool _isMeasuring;
|
||||
private CancellationTokenSource? _measure;
|
||||
|
||||
/// <summary>Whether the workspace is held for a move, as read last (the disk is read once per refresh, never at each requery).</summary>
|
||||
private bool? _moving;
|
||||
|
||||
/// <summary>A move stopped before it ended, as the last measure found (Resume shows).</summary>
|
||||
private bool _unfinished;
|
||||
|
||||
// ---------------- Folder ----------------
|
||||
|
||||
/// <summary>The workspace folder in use.</summary>
|
||||
@@ -92,17 +106,35 @@ public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Fun
|
||||
public RelayCommand OpenCommand { get; } = new(open);
|
||||
|
||||
/// <summary>Uses another folder, after its plan (WorkspaceFolderChange); none where the folder cannot change, nor while it moves.</summary>
|
||||
public AsyncRelayCommand ChangeCommand { get; } = new(change ?? (() => Task.CompletedTask), () => change is not null && !(services?.IsMoving() ?? false));
|
||||
public AsyncRelayCommand ChangeCommand => _change ??= new AsyncRelayCommand(() => ThenReadMoveAsync(change), () => change is not null && !IsMoving);
|
||||
|
||||
private AsyncRelayCommand? _change;
|
||||
|
||||
public bool CanChange => change is not null;
|
||||
|
||||
/// <summary>Change…'s tooltip: what it does, or why it waits (a move under way, or one stopped that Resume takes up).</summary>
|
||||
public string ChangeToolTip => MoveState ?? Loc.L("Tooltips.Settings.ChangeWorkspace");
|
||||
|
||||
/// <summary>Moves the folder with its projects, after its plan (WorkspaceFolderChange.MoveAsync); none where it cannot move, nor while it moves.</summary>
|
||||
public AsyncRelayCommand MoveCommand { get; } = new(services?.Move ?? (() => Task.CompletedTask), () => services?.Move is not null && !services.IsMoving());
|
||||
public AsyncRelayCommand MoveCommand => _move ??= new AsyncRelayCommand(() => ThenReadMoveAsync(services?.Move), () => services?.Move is not null && !IsMoving);
|
||||
|
||||
private AsyncRelayCommand? _move;
|
||||
|
||||
public bool CanMove => services?.Move is not null;
|
||||
|
||||
/// <summary>The move button's tooltip: what it does, or that a move is under way.</summary>
|
||||
public string MoveToolTip => IsMoving ? Loc.L("Errors.Workspace.Moving") : Loc.L("Tooltips.Settings.Workspace.Move");
|
||||
/// <summary>The move button's tooltip: what it does, or why it waits (a move under way, or one stopped that Resume takes up).</summary>
|
||||
public string MoveToolTip => MoveState ?? Loc.L("Tooltips.Settings.Workspace.Move");
|
||||
|
||||
/// <summary>A move of the folder stopped before it ended and no job takes it up: Resume shows.</summary>
|
||||
public bool CanResumeMove => _unfinished && services?.ResumeMove is not null;
|
||||
|
||||
/// <summary>Queues again the move that stopped, from its journal; the page is measured again after.</summary>
|
||||
public AsyncRelayCommand ResumeMoveCommand => _resume ??= new AsyncRelayCommand(ResumeMoveAsync, () => CanResumeMove);
|
||||
|
||||
private AsyncRelayCommand? _resume;
|
||||
|
||||
/// <summary>Why Change… and Move… wait; null when they do not.</summary>
|
||||
private string? MoveState => _unfinished ? Loc.L("Tooltips.Settings.Workspace.MoveUnfinished") : IsMoving ? Loc.L("Errors.Workspace.Moving") : null;
|
||||
|
||||
/// <summary>"12.4 GB used" (the whole folder, its trash included); "Measuring…" meanwhile; null before the first measure or when it failed.</summary>
|
||||
public string? UsageText =>
|
||||
@@ -223,7 +255,7 @@ public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Fun
|
||||
|
||||
public bool IsOpenLastUsed
|
||||
{
|
||||
get => settings.WorkspaceOpenProject == WorkspaceOpenPolicy.LastUsed || !Enum.IsDefined(settings.WorkspaceOpenProject);
|
||||
get => settings.EffectiveOpenPolicy == WorkspaceOpenPolicy.LastUsed;
|
||||
set
|
||||
{
|
||||
if (value) SetOpenProject(WorkspaceOpenPolicy.LastUsed);
|
||||
@@ -232,7 +264,7 @@ public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Fun
|
||||
|
||||
public bool IsOpenMain
|
||||
{
|
||||
get => settings.WorkspaceOpenProject == WorkspaceOpenPolicy.Main;
|
||||
get => settings.EffectiveOpenPolicy == WorkspaceOpenPolicy.Main;
|
||||
set
|
||||
{
|
||||
if (value) SetOpenProject(WorkspaceOpenPolicy.Main);
|
||||
@@ -241,7 +273,7 @@ public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Fun
|
||||
|
||||
public bool IsOpenAsk
|
||||
{
|
||||
get => settings.WorkspaceOpenProject == WorkspaceOpenPolicy.Ask;
|
||||
get => settings.EffectiveOpenPolicy == WorkspaceOpenPolicy.Ask;
|
||||
set
|
||||
{
|
||||
if (value) SetOpenProject(WorkspaceOpenPolicy.Ask);
|
||||
@@ -265,8 +297,8 @@ public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Fun
|
||||
|
||||
private AsyncRelayCommand? _emptyTrash;
|
||||
|
||||
/// <summary>Empty…'s tooltip: what it does, or that there is nothing to erase.</summary>
|
||||
public string EmptyTrashToolTip => Loc.L(HasTrash ? "Tooltips.Settings.Workspace.EmptyTrash" : "Tooltips.Settings.Workspace.EmptyTrash.Disabled");
|
||||
/// <summary>Empty…'s tooltip: what it does, or that there is nothing to erase (only once a measure said so).</summary>
|
||||
public string EmptyTrashToolTip => Loc.L(HasTrash || _usage is null ? "Tooltips.Settings.Workspace.EmptyTrash" : "Tooltips.Settings.Workspace.EmptyTrash.Disabled");
|
||||
|
||||
/// <summary>
|
||||
/// Measures what the workspace takes of its drive and what its trash holds (the page shown, after Empty…, Change and Move);
|
||||
@@ -281,14 +313,18 @@ public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Fun
|
||||
SetMeasuring(true);
|
||||
try
|
||||
{
|
||||
var usage = await services.Usage(measure.Token);
|
||||
var measuring = services.Usage(measure.Token);
|
||||
// Meanwhile, whether a move holds the workspace, or stopped and waits to be taken up, read off the UI thread.
|
||||
var (moving, unfinished) = await ReadMoveStateAsync(measure.Token);
|
||||
if (_measure == measure) SetMoveState(moving, unfinished);
|
||||
var usage = await measuring;
|
||||
if (_measure == measure) _usage = usage;
|
||||
}
|
||||
catch (OperationCanceledException) when (measure.IsCancellationRequested)
|
||||
{
|
||||
// A newer measure took over.
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or Data.DatabaseException)
|
||||
{
|
||||
Log.Warning("workspace", "The workspace folder could not be measured", ex);
|
||||
if (_measure == measure) _usage = null;
|
||||
@@ -383,10 +419,71 @@ public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Fun
|
||||
Refresh();
|
||||
}
|
||||
|
||||
/// <summary>Labels in the current language, values as the settings have them now.</summary>
|
||||
internal void Refresh() => OnAllPropertiesChanged();
|
||||
/// <summary>Labels in the current language, values as the settings have them now (whether a move holds the workspace read again once).</summary>
|
||||
internal void Refresh()
|
||||
{
|
||||
_moving = null;
|
||||
OnAllPropertiesChanged();
|
||||
RaiseMoveCommands();
|
||||
}
|
||||
|
||||
private bool IsMoving => services?.IsMoving() ?? false;
|
||||
/// <summary>A move holds the workspace, as read last (read once when not known since the last refresh).</summary>
|
||||
private bool IsMoving => _moving ??= services?.IsMoving() ?? false;
|
||||
|
||||
private async Task ResumeMoveAsync()
|
||||
{
|
||||
if (services?.ResumeMove is not { } resume) return;
|
||||
await resume();
|
||||
Refresh();
|
||||
await MeasureAsync();
|
||||
}
|
||||
|
||||
private void SetMoveState(bool moving, bool unfinished)
|
||||
{
|
||||
(_moving, _unfinished) = (moving, unfinished);
|
||||
Raise(nameof(MoveToolTip), nameof(ChangeToolTip), nameof(CanResumeMove));
|
||||
RaiseMoveCommands();
|
||||
}
|
||||
|
||||
/// <summary>Whether a move holds the workspace, and whether one stopped waits to be taken up; neither when the index cannot say (logged).</summary>
|
||||
private async Task<(bool Moving, bool Unfinished)> ReadMoveStateAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (services is null) return (false, false);
|
||||
try
|
||||
{
|
||||
var moving = await Task.Run(services.IsMoving, cancellationToken);
|
||||
var unfinished = services.HasUnfinishedMove is { } look && await look(cancellationToken);
|
||||
return (moving, unfinished);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or Data.DatabaseException)
|
||||
{
|
||||
Log.Warning("workspace", "Whether the workspace folder is being moved could not be read", ex);
|
||||
return (false, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Runs Change… or Move…, then reads again whether a move holds the folder (the one just queued, say).</summary>
|
||||
private async Task ThenReadMoveAsync(Func<Task>? action)
|
||||
{
|
||||
if (action is null) return;
|
||||
try
|
||||
{
|
||||
await action();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_moving = null;
|
||||
Raise(nameof(MoveToolTip), nameof(ChangeToolTip));
|
||||
RaiseMoveCommands();
|
||||
}
|
||||
}
|
||||
|
||||
private void RaiseMoveCommands()
|
||||
{
|
||||
_change?.RaiseCanExecuteChanged();
|
||||
_move?.RaiseCanExecuteChanged();
|
||||
_resume?.RaiseCanExecuteChanged();
|
||||
}
|
||||
|
||||
/// <summary>The value the workspace applies: at least one version.</summary>
|
||||
private int Kept => Math.Max(1, settings.WorkspaceKeptVersions);
|
||||
@@ -398,7 +495,7 @@ public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Fun
|
||||
private int CleanAfter => Math.Max(0, settings.WorkspaceCleanAfterDays);
|
||||
|
||||
/// <summary>Open in workspace copies the originals; any other value stored reads as the proxies, as the open dialog takes it.</summary>
|
||||
private bool IsOriginalsDefault => string.Equals(settings.WorkspaceDefaultMedia, BundleMedia.Originals, StringComparison.OrdinalIgnoreCase);
|
||||
private bool IsOriginalsDefault => settings.EffectiveDefaultMedia == BundleMedia.Originals;
|
||||
|
||||
private void SetDefaultMedia(string media)
|
||||
{
|
||||
|
||||
@@ -45,6 +45,11 @@ public interface IWorkspaceUi
|
||||
|
||||
/// <summary>The home's sequence changed (a version of Main sent: its settings and hero frame): what shows it reads it again.</summary>
|
||||
Task SequenceChangedAsync(Guid sequenceId);
|
||||
|
||||
/// <summary>Shows the Jobs screen (a toast's Jobs action); nothing where there is none.</summary>
|
||||
void ShowJobs()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -212,10 +217,14 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
|
||||
/// <summary>Proxies only… (phase 5c): the originals copied here deleted once the home is checked to hold each one.</summary>
|
||||
public ICommand ProxiesOnlyCommand { get; }
|
||||
|
||||
/// <summary>What Copy originals… does, or why it is disabled (the media busy, or the originals here already).</summary>
|
||||
public string CopyOriginalsToolTip => IsMediaBusy ? Loc.L("Tooltips.Editor.Project.MediaBusy")
|
||||
: HoldsOriginals ? Loc.L("Tooltips.Editor.Project.HasOriginals")
|
||||
: WorkspaceText.ForHome("Tooltips.Editor.Project.CopyOriginals", IsServerHome);
|
||||
|
||||
/// <summary>What Proxies only… does, or why it is disabled (the media busy, or proxies only here already).</summary>
|
||||
public string ProxiesOnlyToolTip => IsMediaBusy ? Loc.L("Tooltips.Editor.Project.MediaBusy")
|
||||
: !HoldsOriginals ? Loc.L("Tooltips.Editor.Project.ProxiesAlready")
|
||||
: WorkspaceText.ForHome("Tooltips.Editor.Project.ProxiesOnly", IsServerHome);
|
||||
|
||||
/// <summary>Reads where the project stands (against its home) and whether the home's frames moved.</summary>
|
||||
@@ -729,7 +738,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
|
||||
_copyJob = job.Id;
|
||||
_copyingOriginals = true;
|
||||
RaiseState();
|
||||
_ui.Notify(Loc.L("Editor.Workspace.CopyingOriginals"), _session.Content.Sequence.DisplayTitle, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"));
|
||||
_ui.Notify(Loc.L("Editor.Workspace.CopyingOriginals"), _session.Content.Sequence.DisplayTitle, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), _ui.ShowJobs);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
|
||||
@@ -84,7 +84,7 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
|
||||
? [new DialogFact(Loc.L("Editor.OpenWorkspace.Originals"), Formatting.Bytes(originals), Reason: Loc.L("Tooltips.Editor.OpenWorkspace.OriginalsSize"))]
|
||||
: Array.Empty<DialogFact>(),
|
||||
];
|
||||
_isOriginals = defaultMedia == BundleMedia.Originals && CanCopyOriginals;
|
||||
_isOriginals = string.Equals(defaultMedia, BundleMedia.Originals, StringComparison.OrdinalIgnoreCase) && CanCopyOriginals;
|
||||
Projects = [.. projects.OrderByDescending(p => p.IsMain).Select(p => new ProjectOption(p, unreadable?.GetValueOrDefault(p.Id)))];
|
||||
_selected = Projects.FirstOrDefault(p => p.IsAvailable);
|
||||
_isNew = !HasProjects;
|
||||
|
||||
@@ -148,6 +148,24 @@ public static class WorkspaceFolderChange
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Settings › Workspace › Resume: the move that stopped before it ended (<see cref="WorkspaceHost.UnfinishedMoveAsync"/>)
|
||||
/// queued again from its journal; nothing when there is none any more.
|
||||
/// </summary>
|
||||
public static async Task ResumeUnfinishedAsync(ShellViewModel shell)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(shell);
|
||||
try
|
||||
{
|
||||
if (await shell.Services.Workspace.UnfinishedMoveAsync() is { } journal) await ResumeAsync(shell, journal);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
|
||||
{
|
||||
Log.Warning("workspace", "An unfinished move of the workspace could not be looked for", ex);
|
||||
shell.Notify(Loc.L("Settings.Workspace.NotMoved"), ErrorText.For(ex), isError: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The move's plan as a confirmation: where the projects go, how many and how big, the free bytes at the target, whether
|
||||
/// folders are renamed or files copied and checked, and how many projects hold work not at their home (they move with it).
|
||||
|
||||
@@ -190,7 +190,7 @@ public sealed partial class WorkspaceHost
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
var unsent = WorkspaceCleaner.UnsentRenders(project);
|
||||
var last = (await LastOriginalsOfAsync(project, cancellationToken).ConfigureAwait(false)).Count;
|
||||
var last = await LastOriginalsOfAsync(project, cancellationToken).ConfigureAwait(false);
|
||||
return (unsent, last);
|
||||
}
|
||||
|
||||
@@ -216,13 +216,17 @@ public sealed partial class WorkspaceHost
|
||||
}
|
||||
|
||||
/// <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.
|
||||
/// Before a removed copy's media are deleted, under the project's lease: every file of its folder of originals, named by
|
||||
/// the media index or not (an index that cannot be read names none), hashed now and deleted only when the home's frames,
|
||||
/// read now, hold a photo of that SHA-256; every other one moved into <paramref name="aside"/> (the copy's trash entry),
|
||||
/// never deleted, and every one when the home cannot be asked (<see cref="WorkspaceOriginals.ClearOriginals"/>).
|
||||
/// </summary>
|
||||
private async Task KeepLastOriginalsAsync(WorkspaceProject project, string aside, CancellationToken cancellationToken)
|
||||
/// <returns>The originals that could be neither deleted nor moved: they stay in the folder of originals.</returns>
|
||||
private async Task<int> ClearOriginalsAsync(WorkspaceProject project, string aside, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
ArgumentException.ThrowIfNullOrEmpty(aside);
|
||||
if (!WorkspaceCleaner.HoldsOriginalFiles(project)) return 0;
|
||||
// The working state went into the entry first: the home is read from there.
|
||||
BundleHome? home = null;
|
||||
try
|
||||
@@ -233,19 +237,39 @@ public sealed partial class WorkspaceHost
|
||||
{
|
||||
Log.Info("workspace", $"The home of removed project {project.ProjectId} is not known: every original it holds is kept ({ex.Message})");
|
||||
}
|
||||
var last = await LastOriginalsOfAsync(project, cancellationToken, home, known: true).ConfigureAwait(false);
|
||||
if (last.Count == 0) return;
|
||||
var moved = WorkspaceCleaner.SetOriginalsAside(project, last, aside);
|
||||
Log.Info("workspace", $"{moved} original(s) of project {project.ProjectId} its home no longer holds kept in {aside}");
|
||||
var held = home is null ? null : await HomeFramesAsync(project, home, cancellationToken).ConfigureAwait(false);
|
||||
var (deleted, trashed, _, left) = WorkspaceOriginals.ClearOriginals(project, held?.Frames, aside);
|
||||
Log.Info("workspace", $"Originals of removed project {project.ProjectId}: {deleted} deleted (the home holds them), {trashed} kept in {aside}"
|
||||
+ (left > 0 ? $", {left} left where they are (held open)" : string.Empty));
|
||||
return left;
|
||||
}
|
||||
|
||||
/// <summary>The frames of <paramref name="home"/> as it holds them now; null (logged) when it cannot be asked.</summary>
|
||||
private async Task<HomeFrames?> HomeFramesAsync(WorkspaceProject project, BundleHome home, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
return HomeOf(home) is { } reached ? await reached.FramesAsync(cancellationToken).ConfigureAwait(false) : null;
|
||||
}
|
||||
catch (Exception ex) when (ex is HomeUnavailableException or ProjectException or DatabaseException or IOException or InvalidDataException)
|
||||
{
|
||||
// Not known: every original counts as the last one, and goes to the trash.
|
||||
Log.Info("workspace", $"The home of project {project.ProjectId} could not be asked for its frames: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The frames whose original the workspace holds and the home no longer holds as it is (every one while the home cannot
|
||||
/// be asked); the home is the working state's, else (<paramref name="known"/>) <paramref name="named"/>.
|
||||
/// What a removal plan counts of the originals that go to the trash rather than away: the files of the folder of
|
||||
/// originals the media index does not name (every one when the index cannot be read), plus the frames whose recorded
|
||||
/// original the home no longer holds as it is (every one while the home cannot be asked). The removal hashes each file
|
||||
/// itself; this count is what the plan says, never what decides.
|
||||
/// </summary>
|
||||
private async Task<IReadOnlyList<WorkspaceFrame>> LastOriginalsOfAsync(WorkspaceProject project, CancellationToken cancellationToken, BundleHome? named = null,
|
||||
bool known = false)
|
||||
private async Task<int> LastOriginalsOfAsync(WorkspaceProject project, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!WorkspaceCleaner.HoldsOriginalFiles(project)) return 0;
|
||||
var files = Directory.EnumerateFiles(project.OriginalsDirectory)
|
||||
.Where(f => !f.EndsWith(".part", StringComparison.OrdinalIgnoreCase)).Select(Path.GetFileName).OfType<string>().ToList();
|
||||
WorkspaceMedia? media;
|
||||
try
|
||||
{
|
||||
@@ -253,22 +277,49 @@ public sealed partial class WorkspaceHost
|
||||
}
|
||||
catch (InvalidDataException ex)
|
||||
{
|
||||
Log.Info("workspace", $"The media index of project {project.ProjectId} cannot be read: no original is counted from it ({ex.Message})");
|
||||
return [];
|
||||
Log.Info("workspace", $"The media index of project {project.ProjectId} cannot be read: every original counts as one to keep ({ex.Message})");
|
||||
return files.Count;
|
||||
}
|
||||
if (media is null || !media.Frames.Any(f => f.HasOriginal)) return [];
|
||||
var named = media?.Frames.Where(f => f.Original is not null).Select(f => Path.GetFileName(f.Original!)).ToHashSet(StringComparer.OrdinalIgnoreCase) ?? [];
|
||||
var unnamed = files.Count(f => !named.Contains(f));
|
||||
if (media is null || named.Count == 0) return unnamed;
|
||||
HomeFrames? held = null;
|
||||
try
|
||||
{
|
||||
var homeOf = known ? named : project.ReadBundle().Workspace!.Home;
|
||||
if (homeOf is not null && HomeOf(homeOf) is { } home) held = await home.FramesAsync(cancellationToken).ConfigureAwait(false);
|
||||
held = await HomeFramesAsync(project, project.ReadBundle().Workspace!.Home, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is HomeUnavailableException or ProjectException or DatabaseException or IOException or InvalidDataException)
|
||||
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
|
||||
{
|
||||
// Not known: every original counts as the last one, and goes to the trash.
|
||||
Log.Info("workspace", $"The home of project {project.ProjectId} could not be asked for its frames: {ex.Message}");
|
||||
Log.Info("workspace", $"The home of project {project.ProjectId} is not known: {ex.Message}");
|
||||
}
|
||||
return WorkspaceCleaner.LastOriginals(media, held);
|
||||
return unnamed + WorkspaceCleaner.LastOriginals(media, held).Count(f => files.Contains(Path.GetFileName(f.Original!), StringComparer.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Edit › Export › Send again: queues the sending home of every render of the project not sent yet
|
||||
/// (<see cref="JobKind.WorkspaceSend"/>), unless one is queued, running or paused already.
|
||||
/// </summary>
|
||||
/// <returns>True when a send is queued or waits already; false when nothing waits to be sent.</returns>
|
||||
/// <exception cref="WorkspaceException">The workspace is being moved, or the index or the engine is not open.</exception>
|
||||
public Task<bool> SendRendersAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||||
{
|
||||
EnsureNotMoving();
|
||||
if (_engine() is null || _db() is null) throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
|
||||
var project = Existing(projectId);
|
||||
if (WorkspaceCleaner.UnsentRenders(project) == 0) return false;
|
||||
await QueueRenderSendAsync(project, project.ReadBundle().Workspace!, cancellationToken).ConfigureAwait(false);
|
||||
return true;
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>A send of the project's renders is queued, running or paused (Send again waits for it).</summary>
|
||||
public async Task<bool> RenderSendPendingAsync(Guid projectId, Guid sequenceId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_db() is not { } db) return false;
|
||||
foreach (var pending in await db.Jobs.ListPendingAsync(JobKind.WorkspaceSend, sequenceId, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (WorkspaceJobs.SendParameters(pending)?.ProjectId == projectId) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Queues the sending of the project's renders not sent yet (<see cref="JobKind.WorkspaceSend"/>), unless one is queued or running.</summary>
|
||||
|
||||
@@ -80,10 +80,20 @@ public sealed partial class WorkspaceHost
|
||||
/// </summary>
|
||||
public event Action? MoveEnded;
|
||||
|
||||
/// <summary>A move job followed here waits, runs or is paused (no disk is read).</summary>
|
||||
public bool IsMoveQueued
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate) return _moveJob != Guid.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A move stopped before it ended: the folder in use holds its journal and no move job waits, runs or is paused. Null
|
||||
/// when there is none (a move under way is no move to take up). A move job waiting at start is followed from now on,
|
||||
/// so the workspace waits for it (<see cref="IsMoving"/>).
|
||||
/// A move stopped before it ended: the folder in use holds its journal and no move job waits, runs or is paused; or a
|
||||
/// move switched to the folder in use and left part of the folder it came from (its journal there names what is left
|
||||
/// to clear). Null when there is none (a move under way is no move to take up). A move job waiting at start is followed
|
||||
/// from now on, so the workspace waits for it (<see cref="IsMoving"/>).
|
||||
/// </summary>
|
||||
public Task<WorkspaceMoveJournal?> UnfinishedMoveAsync(CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||||
{
|
||||
@@ -96,7 +106,20 @@ public sealed partial class WorkspaceHost
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return WorkspaceMover.HasJournal(Root) ? WorkspaceMover.ReadJournal(Root) : null;
|
||||
if (WorkspaceMover.HasJournal(Root)) return WorkspaceMover.ReadJournal(Root);
|
||||
// The folder in use is a move's target: the folder it left may hold what could not be cleared after the switch.
|
||||
var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(Root));
|
||||
foreach (var state in new[] { JobState.Done, JobState.Failed, JobState.Cancelled })
|
||||
{
|
||||
foreach (var job in (await db.Jobs.ListAsync(state, JobKind.WorkspaceMove, 5, cancellationToken: cancellationToken).ConfigureAwait(false)).Items)
|
||||
{
|
||||
if (WorkspaceJobs.MoveParameters(job) is not { From.Length: > 0 } moved || !WorkspaceMover.HasJournal(moved.From)) continue;
|
||||
if (WorkspaceMover.ReadJournal(moved.From) is { Stage: WorkspaceMoveStage.Switched } left
|
||||
&& string.Equals(Path.TrimEndingDirectorySeparator(Path.GetFullPath(left.To)), root, StringComparison.OrdinalIgnoreCase))
|
||||
return left;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -296,7 +296,9 @@ public sealed partial class WorkspaceHost
|
||||
{
|
||||
try
|
||||
{
|
||||
if (HomeOf(home) is { } reached) await Sync.FollowNameAsync(change.ProjectId, reached).ConfigureAwait(false);
|
||||
// Nothing is written into a folder being moved: the next status read takes the name.
|
||||
if (IsMoving) Log.Info("workspace", $"The new name of project {change.ProjectId} on {server} waits for the workspace's move");
|
||||
else if (HomeOf(home) is { } reached) await Sync.FollowNameAsync(change.ProjectId, reached).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
@@ -944,10 +946,11 @@ public sealed partial class WorkspaceHost
|
||||
if (copy != Guid.Empty && _engine() is { } engine && _db() is { } db && await db.Jobs.GetAsync(copy, cancellationToken).ConfigureAwait(false) is
|
||||
{ State: JobState.Queued or JobState.Running or JobState.Paused })
|
||||
await engine.CancelAsync(copy, cancellationToken).ConfigureAwait(false);
|
||||
var aside = Path.Combine(Store.Root, TrashFolder, project.ProjectId.ToString("N") + "-" + DateTime.UtcNow.Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||
// Filled under a staging name Empty… never lists, and named once whole.
|
||||
using var trash = WorkspaceTrash.Begin(Store.Root, project.ProjectId, DateTime.UtcNow);
|
||||
var aside = trash.Path;
|
||||
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
Directory.CreateDirectory(aside);
|
||||
var moved = new List<(string From, string To)>();
|
||||
try
|
||||
{
|
||||
@@ -987,9 +990,21 @@ public sealed partial 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);
|
||||
// Every original is hashed and goes aside unless the home holds the same bytes; only what the home can make again
|
||||
// is deleted. One that can be neither deleted nor moved stays where it is, and the media folder with it.
|
||||
if (await ClearOriginalsAsync(project, aside, cancellationToken).ConfigureAwait(false) == 0)
|
||||
{
|
||||
if (Directory.Exists(project.MediaDirectory)) Directory.Delete(project.MediaDirectory, recursive: true);
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (var entry in Directory.EnumerateFileSystemEntries(project.MediaDirectory).ToList())
|
||||
{
|
||||
if (string.Equals(Path.GetFileName(entry), WorkspaceProject.OriginalsFolder, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
if (Directory.Exists(entry)) Directory.Delete(entry, recursive: true);
|
||||
else File.Delete(entry);
|
||||
}
|
||||
}
|
||||
|
||||
void Move(string from, string to)
|
||||
{
|
||||
|
||||
@@ -67,8 +67,14 @@ public sealed record ProjectBundle(BundleArchive Archive, BundleSequence Sequenc
|
||||
public const string Extension = ".chronos";
|
||||
public const string FormatName = "chronos-project";
|
||||
|
||||
/// <summary>The newest format this Chronos reads and writes (2: with a workspace section).</summary>
|
||||
public const int CurrentFormatVersion = 2;
|
||||
/// <summary>
|
||||
/// The newest format this Chronos reads and writes (3: a workspace section whose media hold originals, phase 5c). A
|
||||
/// Chronos before phase 5c refuses such a working copy as newer, so it never removes originals it cannot weigh.
|
||||
/// </summary>
|
||||
public const int CurrentFormatVersion = 3;
|
||||
|
||||
/// <summary>The format of a file with a workspace section whose media are proxies only (2), which phase 5b reads too.</summary>
|
||||
public const int WorkspaceFormatVersion = 2;
|
||||
|
||||
/// <summary>The format of a file without a workspace section.</summary>
|
||||
public const int PlainFormatVersion = 1;
|
||||
@@ -95,7 +101,9 @@ public sealed record ProjectBundle(BundleArchive Archive, BundleSequence Sequenc
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteString("format", FormatName);
|
||||
w.WriteNumber("formatVersion", Workspace is null ? PlainFormatVersion : CurrentFormatVersion);
|
||||
w.WriteNumber("formatVersion", Workspace is null ? PlainFormatVersion
|
||||
: Workspace.Media.Kind == BundleMedia.Originals ? CurrentFormatVersion
|
||||
: WorkspaceFormatVersion);
|
||||
w.WriteString("saved", Saved);
|
||||
w.WriteStartObject("archive");
|
||||
w.WriteString("id", Archive.Id);
|
||||
|
||||
@@ -178,30 +178,6 @@ public sealed class WorkspaceCleaner
|
||||
&& string.Equals(there.Sha256, sha, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves the originals of <paramref name="frames"/> the project holds into <paramref name="aside"/>'s <c>originals</c>
|
||||
/// folder (a workspace trash entry, made when needed); the caller holds the project's lease. Returns how many moved.
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">An original could not be moved; those moved before it stay in the trash.</exception>
|
||||
public static int SetOriginalsAside(WorkspaceProject project, IEnumerable<WorkspaceFrame> frames, string aside)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
ArgumentNullException.ThrowIfNull(frames);
|
||||
ArgumentException.ThrowIfNullOrEmpty(aside);
|
||||
var moved = 0;
|
||||
foreach (var frame in frames)
|
||||
{
|
||||
if (frame.Original is not { } relative) continue;
|
||||
var source = project.MediaFile(relative);
|
||||
if (!File.Exists(source)) continue;
|
||||
var folder = Path.Combine(aside, WorkspaceProject.OriginalsFolder);
|
||||
Directory.CreateDirectory(folder);
|
||||
File.Move(source, Path.Combine(folder, Path.GetFileName(source)));
|
||||
moved++;
|
||||
}
|
||||
return moved;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The local renders of the project its home does not have yet (its ledger's unsent entries); a ledger that cannot be
|
||||
/// read counts the files of <c>exports/</c> besides it, at least one: whether they went home is not known.
|
||||
@@ -284,9 +260,10 @@ public sealed class WorkspaceCleaner
|
||||
}
|
||||
if (status.Offline && status.State != WorkspaceState.Gone) return (WorkspaceKeep.Offline, 0, 0);
|
||||
if (status.State != WorkspaceState.InSync) return (WorkspaceKeep.NotInSync, 0, 0);
|
||||
// The home's frames, asked now: an original goes only when the home holds the same one.
|
||||
// The home's frames, asked now: an original goes only when the home holds the same bytes. Every file of the folder of
|
||||
// originals counts, named by the media index or not (one a removal could not move aside stays unnamed there).
|
||||
HomeFrames? held = null;
|
||||
if (candidate.Media!.Frames.Any(f => f.HasOriginal))
|
||||
if (HoldsOriginalFiles(project))
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -331,23 +308,15 @@ public sealed class WorkspaceCleaner
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the project's media and its sent renders, under its lease: the originals the home lost into the trash first,
|
||||
/// then the media index rewritten with no file (so nothing ever names a file that is gone), then the sent renders, then
|
||||
/// the folders of proxies and originals. A file that cannot be deleted (held open) stays, and is logged.
|
||||
/// Removes the project's media and its sent renders, under its lease: the media index rewritten with no file first (so
|
||||
/// nothing ever names a file that is gone), then the sent renders (only files inside <c>exports/</c>), then the
|
||||
/// originals, each hashed now and deleted only when the home holds the same bytes, else moved to the trash
|
||||
/// (<see cref="WorkspaceOriginals.ClearOriginals"/>), and last the proxies. A file that cannot be deleted or moved (held
|
||||
/// open) stays, and is logged.
|
||||
/// </summary>
|
||||
private static (long Freed, int Trashed) Clear(WorkspaceProject project, WorkspaceMedia media, WorkspaceRenders renders, HomeFrames? held, DateTimeOffset now)
|
||||
{
|
||||
var before = Cleanable(project, renders);
|
||||
var lost = LastOriginals(media, held);
|
||||
var trashed = 0;
|
||||
var trashedBytes = 0L;
|
||||
if (lost.Count > 0)
|
||||
{
|
||||
trashedBytes = lost.Where(f => File.Exists(project.MediaFile(f.Original!))).Sum(f => new FileInfo(project.MediaFile(f.Original!)).Length);
|
||||
var aside = WorkspaceTrash.NewEntry(project.Store.Root, project.ProjectId, now.UtcDateTime);
|
||||
trashed = SetOriginalsAside(project, lost, aside);
|
||||
Log.Info("workspace", $"{trashed} original(s) of project {project.ProjectId} its home no longer holds kept in {aside}");
|
||||
}
|
||||
project.WriteMedia(media with
|
||||
{
|
||||
Frames = [.. media.Frames.Select(f => f with { File = null, FileSha256 = null, FileBytes = 0, FileKind = null, Original = null, OriginalSha256 = null, OriginalBytes = 0 })],
|
||||
@@ -356,7 +325,11 @@ public sealed class WorkspaceCleaner
|
||||
var ledger = renders;
|
||||
foreach (var entry in renders.Entries.Where(e => e.IsSent))
|
||||
{
|
||||
var path = project.ExportFile(entry.File);
|
||||
if (project.ContainedExportFile(entry.File) is not { } path)
|
||||
{
|
||||
Log.Warning("workspace", $"The ledger of project {project.ProjectId} names '{entry.File}' for render {entry.RenderId}, not a file of its exports: nothing is removed for it");
|
||||
continue;
|
||||
}
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(path)) Directory.Delete(path, recursive: true);
|
||||
@@ -369,28 +342,50 @@ public sealed class WorkspaceCleaner
|
||||
}
|
||||
}
|
||||
if (!ReferenceEquals(ledger, renders)) project.WriteRenders(ledger);
|
||||
foreach (var folder in new[] { project.ProxiesDirectory, project.OriginalsDirectory })
|
||||
var (trashed, trashedBytes) = (0, 0L);
|
||||
if (Directory.Exists(project.OriginalsDirectory))
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(folder)) Directory.Delete(folder, recursive: true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("workspace", $"{folder} could not be removed whole; what is left stays", ex);
|
||||
}
|
||||
using var trash = WorkspaceTrash.Begin(project.Store.Root, project.ProjectId, now.UtcDateTime);
|
||||
var cleared = WorkspaceOriginals.ClearOriginals(project, held?.Frames, trash.Path);
|
||||
(trashed, trashedBytes) = (cleared.Trashed, cleared.TrashedBytes);
|
||||
if (trash.Finish() is { } aside) Log.Info("workspace", $"{trashed} original(s) of project {project.ProjectId} its home does not hold as they are kept in {aside}");
|
||||
if (cleared.Left > 0) Log.Warning("workspace", $"{cleared.Left} original(s) of project {project.ProjectId} could be neither deleted nor set aside; they stay");
|
||||
}
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(project.ProxiesDirectory)) Directory.Delete(project.ProxiesDirectory, recursive: true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("workspace", $"{project.ProxiesDirectory} could not be removed whole; what is left stays", ex);
|
||||
}
|
||||
var after = Cleanable(project, ledger);
|
||||
return (Math.Max(0, before - after - trashedBytes), trashed);
|
||||
}
|
||||
|
||||
/// <summary>The project's folder of originals holds a file (an original, named by the media index or not, or a part of one).</summary>
|
||||
public static bool HoldsOriginalFiles(WorkspaceProject project)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
try
|
||||
{
|
||||
return Directory.Exists(project.OriginalsDirectory) && Directory.EnumerateFiles(project.OriginalsDirectory, "*", SearchOption.AllDirectories).Any();
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// Not known: counted as holding some, so the home is asked.
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What a clean-up may remove of the project: its proxies, its originals and the renders its home took.</summary>
|
||||
private static long Cleanable(WorkspaceProject project, WorkspaceRenders renders) =>
|
||||
Measure(project.ProxiesDirectory).Bytes + Measure(project.OriginalsDirectory).Bytes + SentBytes(project, renders);
|
||||
|
||||
/// <summary>The bytes of the renders of <paramref name="renders"/> the home took that are still in <c>exports/</c> (an image sequence's folder counts its files).</summary>
|
||||
private static long SentBytes(WorkspaceProject project, WorkspaceRenders renders) =>
|
||||
renders.Entries.Where(e => e.IsSent).Select(e => project.ExportFile(e.File)).Sum(path => File.Exists(path) ? new FileInfo(path).Length : Measure(path).Bytes);
|
||||
renders.Entries.Where(e => e.IsSent).Select(e => project.ContainedExportFile(e.File)).OfType<string>()
|
||||
.Sum(path => File.Exists(path) ? new FileInfo(path).Length : Measure(path).Bytes);
|
||||
|
||||
/// <summary>The project's ledger; null (logged) when it cannot be read.</summary>
|
||||
private static WorkspaceRenders? ReadLedger(WorkspaceProject project)
|
||||
|
||||
@@ -53,10 +53,19 @@ namespace Chronos.Data.Workspaces;
|
||||
/// arrives and checked against the file written, four at a time; then the server's deep report. A file the editor's media
|
||||
/// or this run hold of the same photo is hashed again and kept; the editor's file is never written over, as above. The
|
||||
/// space, the passes, the checkpoint and a cancelled first copy go as for a copy from this PC's archive (the server's
|
||||
/// folder of the sequence in the checkpoint). Like the sync's downloads it is not held on a metered connection.
|
||||
/// folder of the sequence in the checkpoint). On a metered connection it waits before it downloads anything while
|
||||
/// <see cref="WorkspaceJobOptions.HoldTransfers"/> says so (the desktop pauses it meanwhile).
|
||||
/// A copy queued before the workspace moved works where the workspace is now, and none runs while the workspace is being
|
||||
/// moved (<see cref="WorkspaceJobRoots"/>). A copy of originals the user cancelled over media a copy finished before
|
||||
/// removes the originals it wrote that the media do not name, each deleted only when the home holds its bytes
|
||||
/// (<see cref="RemoveCancelledOriginalsAsync"/>).
|
||||
/// </summary>
|
||||
internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService archives, ISyncConnector? servers = null) : ICancelledJobHandler
|
||||
internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService archives, ISyncConnector? servers = null, WorkspaceJobOptions? options = null)
|
||||
: ICancelledJobHandler
|
||||
{
|
||||
/// <summary>How often a copy held on a metered connection looks again.</summary>
|
||||
internal static TimeSpan HoldPoll { get; set; } = TimeSpan.FromSeconds(2);
|
||||
|
||||
private const int PageSize = 1000;
|
||||
private const int Passes = 3;
|
||||
|
||||
@@ -101,7 +110,13 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
|
||||
// R8), and a workspace inside one would put its copies among that library's own files.
|
||||
if (await InsideALibraryAsync(parameters.WorkspaceRoot, ct).ConfigureAwait(false))
|
||||
throw new InvalidOperationException(Loc.L("Errors.Workspace.InsideLibrary"));
|
||||
var store = new WorkspaceStore(parameters.WorkspaceRoot);
|
||||
// Where the project is now (a workspace moved since the job was queued), never while it is being moved; nothing is
|
||||
// made where it is not.
|
||||
var root = WorkspaceJobRoots.Resolve(parameters.WorkspaceRoot, parameters.ProjectId, options?.CurrentRoot, "Errors.Workspace.NotCheckedOut");
|
||||
if (!PathsEqual(root, parameters.WorkspaceRoot) && await InsideALibraryAsync(root, ct).ConfigureAwait(false))
|
||||
throw new InvalidOperationException(Loc.L("Errors.Workspace.InsideLibrary"));
|
||||
parameters = parameters with { WorkspaceRoot = root };
|
||||
var store = new WorkspaceStore(root);
|
||||
var project = store.Find(parameters.ProjectId) ?? throw new InvalidOperationException(Loc.L("Errors.Workspace.NotCheckedOut"));
|
||||
if (project.ReadBundle().Workspace is not { Home: { IsArchive: true } home } || home.SequenceId != sequenceId)
|
||||
throw new InvalidOperationException(Loc.L("Errors.Workspace.OtherHome"));
|
||||
@@ -114,6 +129,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
|
||||
{
|
||||
// Stopped writing: what a first copy the user cancelled wrote goes (a pause or a shutdown resumes it).
|
||||
await RemovePartialMediaAsync(context.Job, project).ConfigureAwait(false);
|
||||
await RemoveCancelledOriginalsAsync(context.Job, project, parameters).ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@@ -135,13 +151,27 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
// Opening a store makes its folder: one gone stays gone.
|
||||
if (!Directory.Exists(Path.Combine(parameters.WorkspaceRoot, parameters.ProjectId.ToString("N")))) return Task.CompletedTask;
|
||||
string root;
|
||||
try
|
||||
{
|
||||
// Where the project is now; opening a store makes its folder, so one gone stays gone. A workspace being moved is
|
||||
// left as it is: the next copy checks every file it finds.
|
||||
root = WorkspaceJobRoots.Resolve(parameters.WorkspaceRoot, parameters.ProjectId, options?.CurrentRoot, "Errors.Workspace.NotCheckedOut");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
Log.Info("workspace", $"The media of cancelled copy {job.Id} are left as they are: {ex.Message}");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (new WorkspaceStore(parameters.WorkspaceRoot).Find(parameters.ProjectId) is { } project) await RemovePartialMediaAsync(job, project).ConfigureAwait(false);
|
||||
if (new WorkspaceStore(root).Find(parameters.ProjectId) is { } project)
|
||||
{
|
||||
await RemovePartialMediaAsync(job, project).ConfigureAwait(false);
|
||||
await RemoveCancelledOriginalsAsync(job, project, parameters).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
@@ -193,6 +223,83 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
|
||||
static bool Clearable(WorkspaceProject project) => project.Exists && !File.Exists(project.MediaIndexPath) && Directory.Exists(project.MediaDirectory);
|
||||
}
|
||||
|
||||
/// <summary>Waits while transfers with a server are held (a metered connection), saying so once.</summary>
|
||||
private async Task WhileHeldAsync(JobContext context)
|
||||
{
|
||||
if (options?.HoldTransfers is not { } held || !held()) return;
|
||||
context.Log(Loc.L("Archive.Log.WorkspaceCopyHeld"));
|
||||
while (held()) await Task.Delay(HoldPoll, context.Cancellation).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A copy of originals the user cancelled over media a copy finished before (<c>media.json</c> there, so
|
||||
/// <see cref="RemovePartialMediaAsync"/> keeps them): the originals it wrote that those media do not name go, under the
|
||||
/// project's lease, unless another copy of the project goes on with them; each is hashed and deleted only when the home's
|
||||
/// frames, read now, hold its bytes, else kept in the workspace's trash. What a download left half done goes. A home that
|
||||
/// cannot be asked leaves the whole files where they are (the next copy reuses them, a clean-up hashes them).
|
||||
/// </summary>
|
||||
private async Task RemoveCancelledOriginalsAsync(Job job, WorkspaceProject project, WorkspaceCopyParameters parameters)
|
||||
{
|
||||
if (parameters.Media != BundleMedia.Originals) return;
|
||||
try
|
||||
{
|
||||
if (!project.Exists || !File.Exists(project.MediaIndexPath) || !Directory.Exists(project.OriginalsDirectory)) return;
|
||||
if (!await StillToClearAsync(job, project).ConfigureAwait(false)) return;
|
||||
var home = await HomeFramesOrNullAsync(job, parameters).ConfigureAwait(false);
|
||||
using (await project.LockExistingAsync(LockWait, CancellationToken.None).ConfigureAwait(false))
|
||||
{
|
||||
if (!await StillToClearAsync(job, project).ConfigureAwait(false)) return;
|
||||
lock (WritersGate)
|
||||
{
|
||||
// A copy of this program that started since the jobs were read: its files stay.
|
||||
if (Writers.ContainsKey(project.Folder)) return;
|
||||
}
|
||||
if (TryReadMedia(project) is not { } media || !Directory.Exists(project.OriginalsDirectory)) return;
|
||||
var named = media.Frames.Where(f => f.Original is not null).Select(f => Path.GetFileName(f.Original!)).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var staging = Path.Combine(project.OriginalsDirectory, OriginalsStaging);
|
||||
if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true);
|
||||
var written = Directory.EnumerateFiles(project.OriginalsDirectory).Where(f => !named.Contains(Path.GetFileName(f))).ToList();
|
||||
foreach (var part in written.Where(IsPart)) TryDelete(part);
|
||||
var whole = written.Where(f => !IsPart(f)).ToList();
|
||||
if (home is null)
|
||||
{
|
||||
if (whole.Count > 0) Log.Info("workspace", $"The home of project {project.ProjectId} could not be asked: the {whole.Count} original(s) cancelled copy {job.Id} wrote stay");
|
||||
return;
|
||||
}
|
||||
var trashed = WorkspaceOriginals.DeleteOrTrash(project, whole, home);
|
||||
if (!Directory.EnumerateFileSystemEntries(project.OriginalsDirectory).Any()) Directory.Delete(project.OriginalsDirectory);
|
||||
if (whole.Count > 0) Log.Info("workspace", $"The {whole.Count} original(s) cancelled copy {job.Id} of project {project.ProjectId} wrote were removed ({trashed} kept in the trash)");
|
||||
}
|
||||
}
|
||||
catch (DirectoryNotFoundException)
|
||||
{
|
||||
// The project's folder went meanwhile (its removal): nothing is left to clear.
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or LeaseUnavailableException)
|
||||
{
|
||||
Log.Warning("workspace", $"The originals of a cancelled copy of project {project.ProjectId} could not be removed", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The frames of the copy's home as they are now (this PC's index, or the server's); null when they cannot be read.</summary>
|
||||
private async Task<IReadOnlyList<Frame>?> HomeFramesOrNullAsync(Job job, WorkspaceCopyParameters parameters)
|
||||
{
|
||||
if (job.TargetIds is not [var sequenceId]) return null;
|
||||
try
|
||||
{
|
||||
if (parameters.Server is not { Length: > 0 } server) return (await FramesAsync(sequenceId, CancellationToken.None).ConfigureAwait(false)).Frames;
|
||||
if (servers is null) return null;
|
||||
using var remote = await servers.ConnectAsync(server, CancellationToken.None).ConfigureAwait(false);
|
||||
if (remote is null) return null;
|
||||
return (await ServerFramesAsync(remote, sequenceId, CancellationToken.None).ConfigureAwait(false)).Frames;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Info("workspace", $"The home of cancelled copy {job.Id} could not be asked for its frames: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The cancelled copy still reads so, and no other copy of the project into this workspace waits, runs or is paused.</summary>
|
||||
private async Task<bool> StillToClearAsync(Job job, WorkspaceProject project)
|
||||
{
|
||||
@@ -378,13 +485,19 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
|
||||
if (context.Job.TargetIds is not [var sequenceId]) throw new InvalidDataException(Loc.L("Errors.Workspace.Parameters"));
|
||||
// Asked before the store is opened, which makes its folder (as for a copy from this PC's archive).
|
||||
if (await InsideALibraryAsync(parameters.WorkspaceRoot, ct).ConfigureAwait(false)) throw new InvalidOperationException(Loc.L("Errors.Workspace.InsideLibrary"));
|
||||
var store = new WorkspaceStore(parameters.WorkspaceRoot);
|
||||
var root = WorkspaceJobRoots.Resolve(parameters.WorkspaceRoot, parameters.ProjectId, options?.CurrentRoot, "Errors.Workspace.NotCheckedOut");
|
||||
if (!PathsEqual(root, parameters.WorkspaceRoot) && await InsideALibraryAsync(root, ct).ConfigureAwait(false))
|
||||
throw new InvalidOperationException(Loc.L("Errors.Workspace.InsideLibrary"));
|
||||
parameters = parameters with { WorkspaceRoot = root };
|
||||
var store = new WorkspaceStore(root);
|
||||
var project = store.Find(parameters.ProjectId) ?? throw new InvalidOperationException(Loc.L("Errors.Workspace.NotCheckedOut"));
|
||||
if (project.ReadBundle().Workspace is not { Home: { Kind: BundleHome.ServerKind } home } || home.SequenceId != sequenceId
|
||||
|| !string.Equals(home.Server, server, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException(Loc.L("Errors.Workspace.OtherHome"));
|
||||
try
|
||||
{
|
||||
// Nothing is downloaded while transfers with a server are held (a metered connection).
|
||||
await WhileHeldAsync(context).ConfigureAwait(false);
|
||||
using (WritingMedia(project))
|
||||
{
|
||||
using var remote = (servers is null ? null : await servers.ConnectAsync(server, ct).ConfigureAwait(false))
|
||||
@@ -396,6 +509,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
|
||||
{
|
||||
// Stopped writing: what a first copy the user cancelled wrote goes (a pause or a shutdown resumes it).
|
||||
await RemovePartialMediaAsync(context.Job, project).ConfigureAwait(false);
|
||||
await RemoveCancelledOriginalsAsync(context.Job, project, parameters).ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@@ -844,6 +958,9 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
|
||||
}
|
||||
|
||||
/// <summary>Whether <paramref name="folder"/> is an archive's root of this index or lies inside one.</summary>
|
||||
private static bool PathsEqual(string a, string b) =>
|
||||
string.Equals(Path.TrimEndingDirectorySeparator(Path.GetFullPath(a)), Path.TrimEndingDirectorySeparator(Path.GetFullPath(b)), OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
|
||||
|
||||
private async Task<bool> InsideALibraryAsync(string folder, CancellationToken cancellationToken)
|
||||
{
|
||||
var path = Plain(Path.GetFullPath(folder));
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Archiving;
|
||||
@@ -18,14 +20,19 @@ namespace Chronos.Data.Workspaces;
|
||||
/// </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.
|
||||
/// <see cref="JobKind.WorkspaceCopy"/> or <see cref="JobKind.WorkspaceSend"/> naming a server waits before it downloads or
|
||||
/// uploads anything 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)
|
||||
/// <param name="CurrentRoot">
|
||||
/// The workspace folder in use now (the desktop's Settings › Workspace): a copy, render or send queued before the workspace
|
||||
/// moved finds its project there when the folder its parameters name no longer holds it; null where only that one counts.
|
||||
/// </param>
|
||||
public sealed record WorkspaceJobOptions(ProcessingOptions Processing, Func<bool> HoldTransfers, Func<string, string, Task>? Moved = null,
|
||||
Func<string?>? CurrentRoot = 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)
|
||||
@@ -146,7 +153,7 @@ public static class WorkspaceJobs
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
return
|
||||
[
|
||||
new WorkspaceCopyJobHandler(db, archives, servers),
|
||||
new WorkspaceCopyJobHandler(db, archives, servers, options),
|
||||
new WorkspaceRenderJobHandler(db, archives, options),
|
||||
new WorkspaceSendJobHandler(db, archives, servers, options),
|
||||
new WorkspaceMoveJobHandler(db, options),
|
||||
@@ -181,3 +188,55 @@ public static class WorkspaceJobs
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Where a copy, render or send of a workspace project works (phase 5c): the folder its parameters name, or the one the
|
||||
/// workspace moved to since. Nothing of the workspace is written while it is being moved, and nothing is made where the
|
||||
/// project is not (opening a store makes its folder).
|
||||
/// </summary>
|
||||
internal static class WorkspaceJobRoots
|
||||
{
|
||||
/// <summary>
|
||||
/// The workspace folder that holds <paramref name="projectId"/> for a job queued with <paramref name="named"/>: that folder
|
||||
/// when it holds the project; else the target of a move of it past its switch, or the folder in use now
|
||||
/// (<paramref name="current"/>), when either holds it. Refused while a move of either folder has not switched yet
|
||||
/// (<c>Errors.Workspace.Moving</c>: the job fails and can be retried once the move ends); <paramref name="missing"/> (a
|
||||
/// resource key) when no folder holds the project.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidOperationException">The workspace is being moved, or no folder holds the project.</exception>
|
||||
public static string Resolve(string named, Guid projectId, Func<string?>? current, string missing)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(named);
|
||||
var candidates = new List<string>();
|
||||
string? currentRoot = null;
|
||||
try
|
||||
{
|
||||
currentRoot = current?.Invoke() is { Length: > 0 } root ? WorkspaceStore.FullRoot(root) : null;
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or IOException or NotSupportedException)
|
||||
{
|
||||
Log.Debug("workspace", $"The workspace folder in use cannot be read: {ex.Message}");
|
||||
}
|
||||
foreach (var root in new[] { WorkspaceStore.FullRoot(named), currentRoot })
|
||||
{
|
||||
if (root is null) continue;
|
||||
if (WorkspaceMover.HasJournal(root))
|
||||
{
|
||||
// Past its switch the move's target is the workspace, and what is left here is a source still to clear.
|
||||
if (WorkspaceMover.ReadJournal(root) is not { Stage: WorkspaceMoveStage.Switched } journal) throw new InvalidOperationException(Loc.L("Errors.Workspace.Moving"));
|
||||
candidates.Add(WorkspaceStore.FullRoot(journal.To));
|
||||
continue;
|
||||
}
|
||||
candidates.Add(root);
|
||||
}
|
||||
foreach (var root in candidates.Distinct(StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
if (!File.Exists(Path.Combine(root, projectId.ToString("N"), WorkspaceProject.BundleFile))) continue;
|
||||
if (WorkspaceMover.HasJournal(root)) throw new InvalidOperationException(Loc.L("Errors.Workspace.Moving"));
|
||||
if (!string.Equals(root, WorkspaceStore.FullRoot(named), StringComparison.OrdinalIgnoreCase))
|
||||
Log.Info("workspace", $"Project {projectId} is no longer in {named}: the job works in {root}, where the workspace is now");
|
||||
return root;
|
||||
}
|
||||
throw new InvalidOperationException(Loc.L(missing));
|
||||
}
|
||||
}
|
||||
@@ -128,7 +128,9 @@ public sealed record WorkspaceFrame(
|
||||
/// (<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.
|
||||
/// of phase 5b has no original fields: it reads as proxies only. One that holds originals or was cleaned is written as
|
||||
/// format 2 (<see cref="WrittenFormatVersion"/>), which a Chronos before phase 5c refuses as newer and reads as media
|
||||
/// removed (copied again) rather than as proxies whose files are all missing; proxies alone stay format 1, which it reads.
|
||||
/// </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>
|
||||
@@ -141,7 +143,16 @@ public sealed record WorkspaceMedia(string Format, int FormatVersion, string Kin
|
||||
DateTimeOffset Copied, string? AnalysisSha256 = null, IReadOnlyList<PhotoAlias>? Aliases = null, DateTimeOffset? Cleaned = null)
|
||||
{
|
||||
public const string FormatName = "chronos-workspace-media";
|
||||
public const int CurrentFormatVersion = 1;
|
||||
|
||||
/// <summary>The newest format this Chronos reads (2: media with originals, or cleaned).</summary>
|
||||
public const int CurrentFormatVersion = 2;
|
||||
|
||||
/// <summary>The format of media of proxies only that a copy wrote, which a Chronos before phase 5c reads too.</summary>
|
||||
public const int ProxiesFormatVersion = 1;
|
||||
|
||||
/// <summary>The format these media are written in: 2 when they hold originals (or name one) or were cleaned, else 1.</summary>
|
||||
[JsonIgnore]
|
||||
public int WrittenFormatVersion => HoldsOriginals || IsCleaned || Frames.Any(f => f.HasOriginal) ? CurrentFormatVersion : ProxiesFormatVersion;
|
||||
|
||||
/// <summary>The frames' photos in index order, as project positions name them, with the encodings conversions joined.</summary>
|
||||
[JsonIgnore]
|
||||
|
||||
@@ -88,7 +88,11 @@ internal sealed partial class WorkspaceMoveJson : JsonSerializerContext;
|
||||
/// written in the source before the first step and at every entry: a move stopped (paused, the program closed, the PC
|
||||
/// down) goes on from it, trusting the files at their final names and the entries it records as verified; a move that
|
||||
/// fails before the switch is undone (<see cref="Abandon"/>): renamed entries go back, copies at the target are removed,
|
||||
/// the journal goes.
|
||||
/// the journal goes. After the switch a source entry goes only when each of its files still matches its copy at the target
|
||||
/// (name, size and time, as verified); one that changed since is kept and logged, and one that cannot be removed (a file held
|
||||
/// open) stays with the journal, so the move taken up later clears it: neither fails a move whose target is the workspace.
|
||||
/// A rename refused because the folders lie on two volumes after all (a volume mounted in a folder) turns the move into a
|
||||
/// copy before anything was renamed.
|
||||
/// </summary>
|
||||
public sealed class WorkspaceMover
|
||||
{
|
||||
@@ -127,7 +131,7 @@ public sealed class WorkspaceMover
|
||||
/// <summary>
|
||||
/// Called at named steps with the path concerned (tests: a crash, a file damaged on its way): <c>verify</c> (a copy's
|
||||
/// <c>.part</c>, written and about to be read back), <c>copied</c> (a file at its final name), <c>moved</c> (an entry
|
||||
/// renamed into the target), <c>switched</c> (the desktop told).
|
||||
/// renamed into the target), <c>rename</c> (an entry about to be renamed into the target), <c>switched</c> (the desktop told).
|
||||
/// </summary>
|
||||
internal Action<string, string>? Cut { get; init; }
|
||||
|
||||
@@ -264,9 +268,27 @@ public sealed class WorkspaceMover
|
||||
{
|
||||
try
|
||||
{
|
||||
journal = journal.SameVolume
|
||||
? await RenameAsync(journal, progress, log, cancellationToken).ConfigureAwait(false)
|
||||
: await CopyAsync(journal, survey, progress, log, cancellationToken).ConfigureAwait(false);
|
||||
if (journal.SameVolume)
|
||||
{
|
||||
try
|
||||
{
|
||||
journal = await RenameAsync(journal, progress, log, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (IOException ex) when (IsCrossVolume(ex) && NothingRenamed(journal))
|
||||
{
|
||||
// Two volumes under one drive letter (a volume mounted in a folder): the files are copied and verified.
|
||||
Log.Info("workspace", $"{From} and {To} lie on two volumes after all: the move copies and verifies the files ({ex.Message})");
|
||||
if (FreeBytes(To) is { } room && room < survey.Bytes + Reserve)
|
||||
throw new InvalidOperationException(Loc.L("Errors.Workspace.MoveNoRoom", ((survey.Bytes + Reserve - room) / 1e9).ToString("0.0", Loc.Culture)), ex);
|
||||
journal = journal with { SameVolume = false };
|
||||
WriteJournal(journal);
|
||||
journal = await CopyAsync(journal, survey, progress, log, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
journal = await CopyAsync(journal, survey, progress, log, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
@@ -280,12 +302,19 @@ public sealed class WorkspaceMover
|
||||
// From here on the target is the workspace: told again when a run taken up after the switch did not see its answer.
|
||||
if (switched is not null) await switched(From, To).ConfigureAwait(false);
|
||||
Cut?.Invoke("switched", To);
|
||||
Clean(journal);
|
||||
var left = Clean(journal);
|
||||
log?.Invoke(Loc.L("Archive.Log.WorkspaceMoved", To, journal.Entries.Count(e => Guid.TryParseExact(e, "N", out _)), survey.Files));
|
||||
Log.Info("workspace", $"The workspace moved from {From} to {To}");
|
||||
if (left > 0) log?.Invoke(Loc.L("Archive.Log.WorkspaceMoveLeft", From, left));
|
||||
Log.Info("workspace", $"The workspace moved from {From} to {To}" + (left > 0 ? $"; {left} entr(ies) of the old folder stay there" : string.Empty));
|
||||
return (survey, resumed);
|
||||
}
|
||||
|
||||
/// <summary>A move or rename refused because source and target lie on two volumes (Windows <c>ERROR_NOT_SAME_DEVICE</c>, Unix <c>EXDEV</c>).</summary>
|
||||
private static bool IsCrossVolume(IOException ex) => (ex.HResult & 0xFFFF) == (OperatingSystem.IsWindows() ? 0x11 : 18);
|
||||
|
||||
/// <summary>No entry of the journal was renamed into the target yet.</summary>
|
||||
private bool NothingRenamed(WorkspaceMoveJournal journal) => journal.Entries.All(e => !Exists(Path.Combine(To, e)));
|
||||
|
||||
/// <summary>
|
||||
/// Undoes a move its journal records as not switched yet, so the source stays the workspace: on one volume the entries
|
||||
/// renamed into the target go back; across volumes the copies it made at the target are removed (what cannot be removed
|
||||
@@ -351,6 +380,7 @@ public sealed class WorkspaceMover
|
||||
if (Exists(source))
|
||||
{
|
||||
if (Exists(target)) throw new IOException(Loc.L("Errors.Workspace.MoveTargetNotEmpty", To));
|
||||
Cut?.Invoke("rename", source);
|
||||
Rename(source, target);
|
||||
Cut?.Invoke("moved", target);
|
||||
if (Guid.TryParseExact(entry, "N", out _)) log?.Invoke(Loc.L("Archive.Log.WorkspaceMoveProject", Name(target)));
|
||||
@@ -460,17 +490,29 @@ public sealed class WorkspaceMover
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// After the switch: across volumes every entry of the source goes (each one verified at the target), folders first, the
|
||||
/// manifest last; then the journal, and the source folder when nothing else is left in it.
|
||||
/// After the switch: across volumes every entry of the source goes, folders first, the manifest last, each only while
|
||||
/// every file of it still matches its copy at the target (<see cref="StillAsCopied"/>): one that changed since it was
|
||||
/// verified is kept, and logged, never deleted. Then the journal, and the source folder when nothing else is left in it.
|
||||
/// An entry that cannot be removed (a file held open past a few attempts) stays, and the journal with it naming only
|
||||
/// such entries, so the move taken up clears them.
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">An entry of the source could not be removed; the journal stays, and the move taken up removes it.</exception>
|
||||
private void Clean(WorkspaceMoveJournal journal)
|
||||
/// <returns>The entries of the source left where they are.</returns>
|
||||
private int Clean(WorkspaceMoveJournal journal)
|
||||
{
|
||||
var stuck = new List<string>();
|
||||
var kept = 0;
|
||||
if (!journal.SameVolume)
|
||||
{
|
||||
foreach (var entry in journal.Entries.OrderBy(e => e == WorkspaceStore.ManifestFile ? 1 : 0))
|
||||
{
|
||||
var source = Path.Combine(From, entry);
|
||||
if (!Exists(source)) continue;
|
||||
if (!StillAsCopied(source, Path.Combine(To, entry)))
|
||||
{
|
||||
kept++;
|
||||
Log.Warning("workspace", $"{source} changed after it was copied to {To}: it is kept where it is, never deleted");
|
||||
continue;
|
||||
}
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
try
|
||||
@@ -479,16 +521,53 @@ public sealed class WorkspaceMover
|
||||
else if (File.Exists(source)) File.Delete(source);
|
||||
break;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException && attempt < DeleteAttempts)
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
if (attempt >= DeleteAttempts)
|
||||
{
|
||||
Log.Warning("workspace", $"{source} could not be removed after the move: it stays, and the move taken up removes it", ex);
|
||||
stuck.Add(entry);
|
||||
break;
|
||||
}
|
||||
// An indexer or an antivirus reading a file a moment: tried again shortly.
|
||||
Thread.Sleep(100 * attempt);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (stuck.Count > 0)
|
||||
{
|
||||
WriteJournal(journal with { Entries = stuck, Verified = [.. journal.Verified.Where(stuck.Contains)] });
|
||||
return stuck.Count + kept;
|
||||
}
|
||||
File.Delete(JournalPath);
|
||||
TryDeleteEmpty(From);
|
||||
return kept;
|
||||
}
|
||||
|
||||
/// <summary>Clock steps a target's file system may round a file's time to (FAT keeps two seconds).</summary>
|
||||
private static readonly TimeSpan TimeSlack = TimeSpan.FromSeconds(2);
|
||||
|
||||
/// <summary>
|
||||
/// Every file of the source entry (a file, or a folder's files, leases left out) is at the target with the same relative
|
||||
/// name and size and the time the copy gave it (the source's, within the target's rounding): nothing came or changed in
|
||||
/// the source since it was verified.
|
||||
/// </summary>
|
||||
private static bool StillAsCopied(string source, string target)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(source)) return Matches(new FileInfo(source), new FileInfo(target));
|
||||
return Listed(source).All(relative => Matches(new FileInfo(Path.Combine(source, relative)), new FileInfo(Path.Combine(target, relative))));
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Debug("workspace", $"{source} could not be compared with {target}: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool Matches(FileInfo from, FileInfo to) =>
|
||||
to.Exists && from.Length == to.Length && (from.LastWriteTimeUtc - to.LastWriteTimeUtc).Duration() <= TimeSlack;
|
||||
}
|
||||
|
||||
/// <summary>A folder's files relative to it, in ordinal order, the leases left out (they belong to whoever holds the project there).</summary>
|
||||
|
||||
@@ -101,7 +101,7 @@ public static class WorkspaceOriginals
|
||||
if (bundle.Workspace is { } workspace && workspace.Media.Kind != BundleMedia.Proxies)
|
||||
project.WriteBundle(bundle with { Workspace = workspace with { Media = workspace.Media with { Kind = BundleMedia.Proxies } } });
|
||||
var trashed = DeleteOrTrash(project, files, home.Frames);
|
||||
var staging = Path.Combine(project.OriginalsDirectory, ".staging");
|
||||
var staging = Path.Combine(project.OriginalsDirectory, StagingFolder);
|
||||
if (Directory.Exists(staging)) TryDeleteFolder(staging);
|
||||
if (Directory.Exists(project.OriginalsDirectory) && !Directory.EnumerateFileSystemEntries(project.OriginalsDirectory).Any()) TryDeleteFolder(project.OriginalsDirectory);
|
||||
Log.Info("workspace", $"Originals of project {project.ProjectId} removed: {plan.Originals} deleted, {trashed} kept in {TrashFolder}");
|
||||
@@ -111,37 +111,114 @@ public static class WorkspaceOriginals
|
||||
|
||||
/// <summary>
|
||||
/// Deletes each of <paramref name="files"/> (originals of <paramref name="project"/>) whose SHA-256, read now, is that of a
|
||||
/// photo <paramref name="home"/> holds, not flagged missing or damaged; moves the others to the workspace's trash.
|
||||
/// photo <paramref name="home"/> holds, not flagged missing or damaged; moves the others to the workspace's trash (one
|
||||
/// entry, filled under its staging name and named once whole). A file that can be neither deleted nor moved (held open)
|
||||
/// stays where it is, and is logged.
|
||||
/// </summary>
|
||||
/// <returns>The files moved to the trash.</returns>
|
||||
internal static int DeleteOrTrash(WorkspaceProject project, IReadOnlyList<string> files, IReadOnlyList<Frame> home)
|
||||
{
|
||||
if (files.Count == 0) return 0;
|
||||
using var trash = WorkspaceTrash.Begin(project.Store.Root, project.ProjectId, DateTime.UtcNow);
|
||||
return DeleteOrTrash(project, files, home, Path.Combine(trash.Path, WorkspaceProject.OriginalsFolder)).Trashed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears the project's folder of originals for good: every file in it, whether the media index names it or not, hashed
|
||||
/// now and deleted only when <paramref name="home"/> (the home's frames as just read; null when they are not known) holds
|
||||
/// a photo of that SHA-256 not flagged missing or damaged, else moved into <paramref name="trashEntry"/>'s
|
||||
/// <c>originals</c> folder (made when needed). The parts a copy left (<c>.part</c>, <c>.staging</c>: downloads not
|
||||
/// finished) are deleted, and the folder goes once nothing is left in it. The caller holds the project's lease.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// The files deleted, those moved to the trash with their bytes, and those that stay where they are (neither deleted nor
|
||||
/// moved: held open), which the folder keeps.
|
||||
/// </returns>
|
||||
public static (int Deleted, int Trashed, long TrashedBytes, int Left) ClearOriginals(WorkspaceProject project, IReadOnlyList<Frame>? home, string trashEntry)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
ArgumentException.ThrowIfNullOrEmpty(trashEntry);
|
||||
var folder = project.OriginalsDirectory;
|
||||
if (!Directory.Exists(folder)) return (0, 0, 0, 0);
|
||||
var staging = Path.Combine(folder, StagingFolder);
|
||||
var files = new List<string>();
|
||||
var parts = new List<string>();
|
||||
foreach (var file in Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
if (Inside(staging, file)) continue;
|
||||
(file.EndsWith(".part", StringComparison.OrdinalIgnoreCase) ? parts : files).Add(file);
|
||||
}
|
||||
var (deleted, trashed, trashedBytes, left) = DeleteOrTrash(project, files, home ?? [], Path.Combine(trashEntry, WorkspaceProject.OriginalsFolder));
|
||||
foreach (var part in parts)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(part);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("workspace", $"{part} could not be removed", ex);
|
||||
}
|
||||
}
|
||||
if (Directory.Exists(staging)) TryDeleteFolder(staging);
|
||||
RemoveEmptyFolders(folder);
|
||||
return (deleted, trashed, trashedBytes, left);
|
||||
}
|
||||
|
||||
/// <summary>The folder of originals a copy from a server downloads into until a file is whole.</summary>
|
||||
internal const string StagingFolder = ".staging";
|
||||
|
||||
private static (int Deleted, int Trashed, long TrashedBytes, int Left) DeleteOrTrash(WorkspaceProject project, IReadOnlyList<string> files, IReadOnlyList<Frame> home,
|
||||
string trash)
|
||||
{
|
||||
var held = HeldAtHome(home);
|
||||
string? trash = null;
|
||||
var trashed = 0;
|
||||
int deleted = 0, trashed = 0, left = 0;
|
||||
long trashedBytes = 0;
|
||||
foreach (var file in files)
|
||||
{
|
||||
try
|
||||
{
|
||||
var (sha, _) = Hash(file);
|
||||
var (sha, bytes) = Hash(file);
|
||||
if (sha is not null && held.Contains(sha))
|
||||
{
|
||||
File.Delete(file);
|
||||
deleted++;
|
||||
continue;
|
||||
}
|
||||
trash ??= Path.Combine(project.Store.Root, TrashFolder,
|
||||
project.ProjectId.ToString("N") + "-" + DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture), WorkspaceProject.OriginalsFolder);
|
||||
Directory.CreateDirectory(trash);
|
||||
File.Move(file, Path.Combine(trash, Path.GetFileName(file)), overwrite: true);
|
||||
var target = Path.Combine(trash, Path.GetRelativePath(project.OriginalsDirectory, file));
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
|
||||
// Never over another file of the entry: one that cannot go there stays where it is.
|
||||
File.Move(file, target, overwrite: false);
|
||||
trashed++;
|
||||
trashedBytes += bytes;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("workspace", $"{file} could not be removed", ex);
|
||||
left++;
|
||||
Log.Warning("workspace", $"{file} could not be removed; it stays where it is", ex);
|
||||
}
|
||||
}
|
||||
return trashed;
|
||||
return (deleted, trashed, trashedBytes, left);
|
||||
}
|
||||
|
||||
private static bool Inside(string folder, string path) =>
|
||||
path.StartsWith(Path.TrimEndingDirectorySeparator(folder) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>Removes the empty folders under <paramref name="folder"/>, and <paramref name="folder"/> itself when it is left empty.</summary>
|
||||
private static void RemoveEmptyFolders(string folder)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var sub in Directory.EnumerateDirectories(folder, "*", SearchOption.AllDirectories).OrderByDescending(d => d.Length).ToList())
|
||||
{
|
||||
if (!Directory.EnumerateFileSystemEntries(sub).Any()) Directory.Delete(sub);
|
||||
}
|
||||
if (!Directory.EnumerateFileSystemEntries(folder).Any()) Directory.Delete(folder);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Debug("workspace", $"{folder} stays: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The original files in the project's folder of originals (never a part a copy writes, nor its staging folder).</summary>
|
||||
|
||||
@@ -21,7 +21,10 @@ namespace Chronos.Data.Workspaces;
|
||||
/// 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 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.
|
||||
/// <c>RenderJobHandler.RenderId(jobId, index)</c>), then a <see cref="JobKind.WorkspaceSend"/> queued of every render of the
|
||||
/// project not sent yet (this run's, an earlier run's of this job, and those whose send failed before), whenever this job
|
||||
/// ever recorded one that is not sent: a resumed or retried run queues it too. A render queued before the workspace moved
|
||||
/// works where the workspace is now, and none runs while it is being moved (<see cref="WorkspaceJobRoots"/>).
|
||||
/// 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
|
||||
@@ -43,7 +46,11 @@ internal sealed class WorkspaceRenderJobHandler(ChronosDatabase db, ArchiveServi
|
||||
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);
|
||||
// Where the project is now (a workspace moved since the job was queued), never while it is being moved; nothing is
|
||||
// made where it is not.
|
||||
var root = WorkspaceJobRoots.Resolve(parameters.WorkspaceRoot, parameters.ProjectId, options.CurrentRoot, "Errors.Workspace.RenderProject");
|
||||
parameters = parameters with { WorkspaceRoot = root };
|
||||
var store = new WorkspaceStore(root);
|
||||
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);
|
||||
@@ -69,7 +76,13 @@ internal sealed class WorkspaceRenderJobHandler(ChronosDatabase db, ArchiveServi
|
||||
names.Release(chosen);
|
||||
}
|
||||
var targets = all.Select((t, i) => (i, t)).Where(t => !done.Contains(t.i)).ToList();
|
||||
var recorded = new List<Guid>();
|
||||
// What an earlier run of this job recorded and did not send (it stopped before queueing the send, or that failed).
|
||||
var recorded = ledger.Entries.Where(e => e.JobId == context.Job.Id && e.IsUnsent).Select(e => e.RenderId).ToList();
|
||||
if (targets.Count == 0)
|
||||
{
|
||||
await QueueSendAsync(context, parameters, sequence, recorded).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
if (targets.Count > 0)
|
||||
{
|
||||
string? writing = null;
|
||||
@@ -97,7 +110,7 @@ internal sealed class WorkspaceRenderJobHandler(ChronosDatabase db, ArchiveServi
|
||||
project.WriteRenders(ledger);
|
||||
}
|
||||
done.Add(index);
|
||||
recorded.Add(id);
|
||||
if (!recorded.Contains(id)) 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)));
|
||||
@@ -242,12 +255,15 @@ internal sealed class WorkspaceRenderJobHandler(ChronosDatabase db, ArchiveServi
|
||||
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>
|
||||
/// <summary>
|
||||
/// Queues the send home of every render of the project not sent yet (an empty list of ids: the send reads the ledger when
|
||||
/// it runs), whatever stops the job now, once this job recorded one that is not sent (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);
|
||||
var send = WorkspaceJobs.Send(sequence.Id, sequence.DisplayTitle, parameters.WorkspaceRoot, parameters.ProjectId, [], parameters.Server,
|
||||
context.Job.Priority);
|
||||
await context.EnqueueFollowUpAsync(send.Kind, send.Targets, send.Label, send.ParametersJson, send.Priority, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,9 @@ namespace Chronos.Data.Workspaces;
|
||||
/// sent home with their project and version, per unsent ledger entry (<see cref="WorkspaceRenders"/>; the ids the job names,
|
||||
/// or every unsent one): the file hashed again (one missing or changed since it was rendered is refused, marked failed in the
|
||||
/// ledger and left where it is), the version it names pushed first when the home lacks it (a push that fails fails the job,
|
||||
/// the entry left as it was), then filed in this PC's archive (copied into the archive's staging folder, read back against
|
||||
/// the entry left as it was; a version the push replayed under a new id, after the home moved on, is found again by the
|
||||
/// content hash of what rendered, else the render goes with its project alone, and the entry says so from then on), then
|
||||
/// filed in this PC's archive (copied into the archive's staging folder, read back against
|
||||
/// its SHA-256, and filed under the sequence's lease as the sync files a server's exports,
|
||||
/// <see cref="SyncTransfers.FileRenderAsync"/>, after checking the project and version are the sequence's) or uploaded to its
|
||||
/// server (<see cref="RenderUploadRequest"/> with <c>ProjectId</c> and <c>ProjectVersionId</c>, which the server checks the
|
||||
@@ -27,7 +29,9 @@ namespace Chronos.Data.Workspaces;
|
||||
/// render id the home files under another sequence is refused. The ledger is read and written under the project's lease,
|
||||
/// each entry read again before it is written, so a render finished meanwhile is kept.
|
||||
/// A send to a server is held while <see cref="WorkspaceJobOptions.HoldTransfers"/> says so (a metered connection): it waits
|
||||
/// before each upload, and the desktop pauses it meanwhile. A send to this PC's archive is never held.
|
||||
/// before each upload, and the desktop pauses it meanwhile. A send to this PC's archive is never held. A server from before
|
||||
/// phase 5c files the render without its project and version: the job's log says so. A send queued before the workspace
|
||||
/// moved works where the workspace is now, and none runs while it is being moved (<see cref="WorkspaceJobRoots"/>).
|
||||
/// </summary>
|
||||
internal sealed class WorkspaceSendJobHandler(ChronosDatabase db, ArchiveService archives, ISyncConnector? servers, WorkspaceJobOptions options) : IJobHandler
|
||||
{
|
||||
@@ -46,7 +50,10 @@ internal sealed class WorkspaceSendJobHandler(ChronosDatabase db, ArchiveService
|
||||
if (context.Job.TargetIds is not [var sequenceId] || string.IsNullOrWhiteSpace(parameters.WorkspaceRoot))
|
||||
throw new InvalidDataException(Loc.L("Errors.Workspace.JobParameters"));
|
||||
var server = parameters.Server is { Length: > 0 } named ? named : null;
|
||||
var project = new WorkspaceStore(parameters.WorkspaceRoot).Find(parameters.ProjectId)
|
||||
// Where the project is now (a workspace moved since the job was queued), never while it is being moved; nothing is
|
||||
// made where it is not.
|
||||
var root = WorkspaceJobRoots.Resolve(parameters.WorkspaceRoot, parameters.ProjectId, options.CurrentRoot, "Errors.Workspace.NotCheckedOut");
|
||||
var project = new WorkspaceStore(root).Find(parameters.ProjectId)
|
||||
?? throw new InvalidOperationException(Loc.L("Errors.Workspace.NotCheckedOut"));
|
||||
var workspace = project.ReadBundle().Workspace ?? throw new InvalidOperationException(Loc.L("Errors.Workspace.NotCheckedOut"));
|
||||
var home = workspace.Home;
|
||||
@@ -77,7 +84,7 @@ internal sealed class WorkspaceSendJobHandler(ChronosDatabase db, ArchiveService
|
||||
?? throw new InvalidOperationException(Loc.L("Errors.Sync.NotConnected"));
|
||||
await SendAsync(context, project, workspace, entries,
|
||||
() => servers!.ProjectHome(home) ?? throw new InvalidOperationException(Loc.L("Errors.Sync.NotConnected")), held: true,
|
||||
(entry, file, token) => UploadAsync(remote, sequenceId, entry, file, token)).ConfigureAwait(false);
|
||||
(entry, file, token) => UploadAsync(context, remote, sequenceId, entry, file, token)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -101,25 +108,35 @@ internal sealed class WorkspaceSendJobHandler(ChronosDatabase db, ArchiveService
|
||||
{
|
||||
var ct = context.Cancellation;
|
||||
var (sent, there, refused) = (0, 0, 0);
|
||||
// The versions this run found at the home, or sent there first.
|
||||
var versions = new HashSet<Guid>();
|
||||
// The versions this run found at the home, or sent there first, with the id the home holds each by (a replay gives another).
|
||||
var versions = new Dictionary<Guid, Guid?>();
|
||||
for (var i = 0; i < entries.Count; i++)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (held) await WhileHeldAsync(context).ConfigureAwait(false);
|
||||
var entry = entries[i];
|
||||
var file = project.ExportFile(entry.File);
|
||||
var refusal = await CheckAsync(project, entry, file, folders: !held, ct).ConfigureAwait(false);
|
||||
var file = project.ContainedExportFile(entry.File);
|
||||
var refusal = file is null ? Loc.L("Errors.Workspace.SendMissing", Path.GetFileName(entry.File ?? string.Empty)) : await CheckAsync(entry, file, folders: !held, ct).ConfigureAwait(false);
|
||||
if (refusal is null)
|
||||
{
|
||||
if (entry.ProjectVersionId is { } versionId && !versions.Contains(versionId))
|
||||
if (entry.ProjectVersionId is { } versionId)
|
||||
{
|
||||
await EnsureVersionAsync(context, project, workspace, home(), entry.ProjectId, versionId, ct).ConfigureAwait(false);
|
||||
versions.Add(versionId);
|
||||
if (!versions.TryGetValue(versionId, out var atHome))
|
||||
{
|
||||
atHome = await EnsureVersionAsync(context, project, workspace, home(), entry, versionId, ct).ConfigureAwait(false);
|
||||
versions[versionId] = atHome;
|
||||
}
|
||||
if (atHome != versionId)
|
||||
{
|
||||
// The ledger says from now on what the home holds: later sends agree with this one.
|
||||
entry = entry with { ProjectVersionId = atHome };
|
||||
var mapped = atHome;
|
||||
await UpdateAsync(project, entry.RenderId, e => e with { ProjectVersionId = mapped }).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
try
|
||||
{
|
||||
if (await deliver(entry, file, ct).ConfigureAwait(false)) sent++;
|
||||
if (await deliver(entry, file!, ct).ConfigureAwait(false)) sent++;
|
||||
else there++;
|
||||
// The home holds it: recorded whatever stops the job now.
|
||||
await UpdateAsync(project, entry.RenderId, e => e.AsSent(DateTimeOffset.UtcNow)).ConfigureAwait(false);
|
||||
@@ -147,12 +164,10 @@ internal sealed class WorkspaceSendJobHandler(ChronosDatabase db, ArchiveService
|
||||
/// when <paramref name="folders"/>: this PC's archive files folders as its own renders do) is checked by its total size
|
||||
/// and the hash of its listing, as the render recorded it (<see cref="WorkspaceRenderJobHandler.HashAsync"/>).
|
||||
/// </summary>
|
||||
private static async Task<string?> CheckAsync(WorkspaceProject project, WorkspaceRenderEntry entry, string file, bool folders, CancellationToken ct)
|
||||
/// <remarks>A ledger names files inside the exports only (<see cref="WorkspaceProject.ContainedExportFile"/>): one pointing elsewhere is never read.</remarks>
|
||||
private static async Task<string?> CheckAsync(WorkspaceRenderEntry entry, string file, bool folders, CancellationToken ct)
|
||||
{
|
||||
var name = Path.GetFileName(entry.File);
|
||||
var exports = Path.TrimEndingDirectorySeparator(Path.GetFullPath(project.ExportsDirectory)) + Path.DirectorySeparatorChar;
|
||||
// A ledger names files inside the exports only; one pointing elsewhere is never read.
|
||||
if (!Path.GetFullPath(file).StartsWith(exports, StringComparison.OrdinalIgnoreCase)) return Loc.L("Errors.Workspace.SendMissing", name);
|
||||
if (Directory.Exists(file))
|
||||
{
|
||||
if (!folders) return Loc.L("Errors.Workspace.SendSequence", name);
|
||||
@@ -168,14 +183,21 @@ internal sealed class WorkspaceSendJobHandler(ChronosDatabase db, ArchiveService
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>How many of the home's newest versions are read for one of the same content, when a replay gave a rendered version another id.</summary>
|
||||
private const int ReplayedLookBack = 100;
|
||||
|
||||
/// <summary>
|
||||
/// Version <paramref name="versionId"/> of the project at the home: pushed there first (every local version, in order, as a
|
||||
/// sync pushes them) when the home lacks it. A push that does not bring it there fails the job.
|
||||
/// Version <paramref name="versionId"/> of the project at the home, as the id the home holds it by: pushed there first
|
||||
/// (every local version, in order, as a sync pushes them) when the home lacks it. A push that replays it on a home that
|
||||
/// moved on gives it another id (and one that changes nothing is not sent at all): the home's version of the content
|
||||
/// hash that rendered (<see cref="WorkspaceRenderEntry.SettingsHash"/>) stands for it, else none (null: the render goes
|
||||
/// with its project alone, as a render of a version the home never had). A push that fails fails the job.
|
||||
/// </summary>
|
||||
private static async Task EnsureVersionAsync(JobContext context, WorkspaceProject project, BundleWorkspace workspace, IProjectHome home, Guid projectId,
|
||||
Guid versionId, CancellationToken ct)
|
||||
private static async Task<Guid?> EnsureVersionAsync(JobContext context, WorkspaceProject project, BundleWorkspace workspace, IProjectHome home,
|
||||
WorkspaceRenderEntry entry, Guid versionId, CancellationToken ct)
|
||||
{
|
||||
if (await home.GetVersionAsync(projectId, versionId, ct).ConfigureAwait(false) is not null) return;
|
||||
var projectId = entry.ProjectId;
|
||||
if (await home.GetVersionAsync(projectId, versionId, ct).ConfigureAwait(false) is not null) return versionId;
|
||||
try
|
||||
{
|
||||
await new WorkspaceSync(project.Store, Environment.MachineName) { LockWait = LockWait }.PushAsync(projectId, home, ct).ConfigureAwait(false);
|
||||
@@ -186,9 +208,26 @@ internal sealed class WorkspaceSendJobHandler(ChronosDatabase db, ArchiveService
|
||||
context.Log(ex.Message);
|
||||
throw new InvalidOperationException(Loc.L("Errors.Workspace.SendVersion"), ex);
|
||||
}
|
||||
var pushed = await home.GetVersionAsync(projectId, versionId, ct).ConfigureAwait(false)
|
||||
?? throw new InvalidOperationException(Loc.L("Errors.Workspace.SendVersion"));
|
||||
context.Log(Loc.L("Archive.Log.WorkspaceVersionPushed", workspace.Name, pushed.Number));
|
||||
if (await home.GetVersionAsync(projectId, versionId, ct).ConfigureAwait(false) is { } pushed)
|
||||
{
|
||||
context.Log(Loc.L("Archive.Log.WorkspaceVersionPushed", workspace.Name, pushed.Number));
|
||||
return versionId;
|
||||
}
|
||||
ProjectVersion? same = null;
|
||||
if (entry.SettingsHash is { Length: > 0 } hash)
|
||||
{
|
||||
var history = await home.HistoryAsync(projectId, null, ReplayedLookBack, ct).ConfigureAwait(false);
|
||||
same = history.FirstOrDefault(v => string.Equals(v.ContentHash, hash, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
if (same is not null)
|
||||
{
|
||||
Log.Info("workspace", $"Version {versionId} of project {projectId} reached the home as version {same.Id} (a replay): render {entry.RenderId} names that one");
|
||||
context.Log(Loc.L("Archive.Log.WorkspaceVersionReplayed", workspace.Name, same.Number));
|
||||
return same.Id;
|
||||
}
|
||||
Log.Info("workspace", $"Version {versionId} of project {projectId} is not at the home after the push, nor one of the same content: render {entry.RenderId} goes with its project alone");
|
||||
context.Log(Loc.L("Archive.Log.WorkspaceVersionNotHome", workspace.Name));
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -283,14 +322,21 @@ internal sealed class WorkspaceSendJobHandler(ChronosDatabase db, ArchiveService
|
||||
/// project for another sequence's, the id for another sequence's render, the file for too large or not the one hashed):
|
||||
/// marked failed; anything else (the server out of reach, busy, the sign-in expired) fails the job, the entry left as it was.
|
||||
/// </summary>
|
||||
private async Task<bool> UploadAsync(ISyncRemote remote, Guid sequenceId, WorkspaceRenderEntry entry, string file, CancellationToken ct)
|
||||
private async Task<bool> UploadAsync(JobContext context, ISyncRemote remote, Guid sequenceId, WorkspaceRenderEntry entry, string file, CancellationToken ct)
|
||||
{
|
||||
var name = SyncTransfers.SafeFileName(Path.GetFileName(entry.File)) ?? entry.RenderId.ToString("N");
|
||||
var request = new RenderUploadRequest(entry.RenderId, name, entry.Size, entry.Sha256.ToLowerInvariant(), entry.PresetName, entry.Codec, entry.Width, entry.Height,
|
||||
entry.Fps, entry.DurationSeconds, options.Processing.ProducedBy, entry.ProjectId, entry.ProjectVersionId);
|
||||
try
|
||||
{
|
||||
return await remote.UploadRenderAsync(sequenceId, file, request, ct).ConfigureAwait(false) is not null;
|
||||
if (await remote.UploadRenderAsync(sequenceId, file, request, ct).ConfigureAwait(false) is not { } filed) return false;
|
||||
// A server from before phase 5c ignores the project and version: the render is there, without them.
|
||||
if (filed.ProjectId != entry.ProjectId || filed.ProjectVersionId != entry.ProjectVersionId)
|
||||
{
|
||||
Log.Warning("workspace", $"The server filed render {entry.RenderId} without its project {entry.ProjectId} and version {entry.ProjectVersionId} (a server before phase 5c)");
|
||||
context.Log(Loc.L("Archive.Log.WorkspaceSendNoProvenance", name));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (ChronosApiException ex) when (ex.Status is HttpStatusCode.BadRequest or HttpStatusCode.Conflict or HttpStatusCode.RequestEntityTooLarge
|
||||
or HttpStatusCode.UnprocessableEntity)
|
||||
|
||||
@@ -451,6 +451,33 @@ public sealed class WorkspaceProject
|
||||
/// <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>
|
||||
/// The absolute path of a local render named relative to <see cref="ExportsDirectory"/>, only when it lies strictly inside
|
||||
/// that folder and is not its ledger; null for a name that is empty, rooted, climbs out (<c>..</c>), names the folder
|
||||
/// itself (<c>.</c>) or the ledger. What reads, sends or deletes a ledger's file goes through this, so a damaged or
|
||||
/// hand-edited ledger never points it at anything else.
|
||||
/// </summary>
|
||||
public string? ContainedExportFile(string? relative)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(relative)) return null;
|
||||
var portable = relative.Replace('\\', '/');
|
||||
if (Path.IsPathRooted(relative) || portable.StartsWith('/') || portable.Contains(':', StringComparison.Ordinal)
|
||||
|| portable.Split('/').Any(part => part is "" or "." or "..")) return null;
|
||||
string full, folder;
|
||||
try
|
||||
{
|
||||
full = Path.GetFullPath(ExportFile(relative));
|
||||
folder = Path.TrimEndingDirectorySeparator(Path.GetFullPath(ExportsDirectory)) + Path.DirectorySeparatorChar;
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
|
||||
if (!full.StartsWith(folder, comparison) || full.Length <= folder.Length) return null;
|
||||
return string.Equals(full, Path.GetFullPath(RendersPath), comparison) ? null : full;
|
||||
}
|
||||
|
||||
/// <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)
|
||||
@@ -509,7 +536,7 @@ public sealed class WorkspaceProject
|
||||
internal void WriteMedia(WorkspaceMedia media)
|
||||
{
|
||||
Directory.CreateDirectory(MediaDirectory);
|
||||
AtomicFile.WriteAllText(MediaIndexPath, JsonSerializer.Serialize(media, WorkspaceJson.Default.WorkspaceMedia));
|
||||
AtomicFile.WriteAllText(MediaIndexPath, JsonSerializer.Serialize(media with { FormatVersion = media.WrittenFormatVersion }, WorkspaceJson.Default.WorkspaceMedia));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
@@ -24,7 +25,9 @@ public sealed class WorkspaceTrashChangedException(string message) : IOException
|
||||
/// <summary>
|
||||
/// The trash of a workspace (<c><workspace>/.trash</c>, phase 5c): what a removed local copy kept of its work
|
||||
/// (<c><project id>-<ticks></c>), and the originals a clean-up found the home no longer holds
|
||||
/// (<c><project id>-<ticks>/originals</c>). Nothing in Chronos writes into an entry once it is made, and only the
|
||||
/// (<c><project id>-<ticks>/originals</c>). An entry is filled under a staging name the listing leaves out
|
||||
/// (<c>.incoming-<project id>-<ticks></c>, <see cref="Begin"/>) and takes its own name in one rename once it is
|
||||
/// whole, so nothing writes into an entry a plan lists; one a crash left half filled lists as an entry of its own. Only the
|
||||
/// user's Empty… erases them: the plan lists them (<see cref="List"/>), and <see cref="Empty"/> erases exactly those, only
|
||||
/// while the fingerprint of the plan still matches. Schedules and the size limit never empty it.
|
||||
/// </summary>
|
||||
@@ -33,6 +36,12 @@ public static class WorkspaceTrash
|
||||
/// <summary>The trash's folder name in the workspace (the store lists only folders named by a project id).</summary>
|
||||
public const string FolderName = ".trash";
|
||||
|
||||
/// <summary>The name an entry has while it is filled (<see cref="Begin"/>).</summary>
|
||||
internal const string IncomingPrefix = ".incoming-";
|
||||
|
||||
/// <summary>The staging folders being filled now in this program (by name: a project id and ticks): the listing leaves them out.</summary>
|
||||
private static readonly ConcurrentDictionary<string, byte> Filling = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>The trash folder of the workspace at <paramref name="workspaceRoot"/>.</summary>
|
||||
public static string FolderOf(string workspaceRoot)
|
||||
{
|
||||
@@ -54,6 +63,59 @@ public static class WorkspaceTrash
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A new entry of the trash for <paramref name="projectId"/>, filled under a staging name the listing leaves out; it takes
|
||||
/// its own name (<see cref="NewEntry"/>) when the builder is disposed, or goes when nothing came into it. The staging
|
||||
/// folder is made when the builder is.
|
||||
/// </summary>
|
||||
public static WorkspaceTrashBuilder Begin(string workspaceRoot, Guid projectId, DateTime nowUtc)
|
||||
{
|
||||
var folder = FolderOf(workspaceRoot);
|
||||
for (var ticks = nowUtc.Ticks; ; ticks++)
|
||||
{
|
||||
var path = Path.Combine(folder, IncomingPrefix + projectId.ToString("N") + "-" + ticks.ToString(CultureInfo.InvariantCulture));
|
||||
// Named as being filled before it is made: a listing never sees it half made.
|
||||
if (Directory.Exists(path) || File.Exists(path) || !Filling.TryAdd(Path.GetFileName(path), 0)) continue;
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(path);
|
||||
}
|
||||
catch
|
||||
{
|
||||
Filling.TryRemove(Path.GetFileName(path), out _);
|
||||
throw;
|
||||
}
|
||||
return new WorkspaceTrashBuilder(workspaceRoot, projectId, path);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The staging folder <paramref name="staging"/> made an entry of its own (its own name), or removed when empty; no longer left out of the listing.</summary>
|
||||
internal static string? Finish(string workspaceRoot, Guid projectId, string staging)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(staging)) return null;
|
||||
if (!Directory.EnumerateFileSystemEntries(staging).Any())
|
||||
{
|
||||
Directory.Delete(staging);
|
||||
return null;
|
||||
}
|
||||
var entry = NewEntry(workspaceRoot, projectId, DateTime.UtcNow);
|
||||
Directory.Move(staging, entry);
|
||||
return entry;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// Listed from now on under its staging name: what it holds stays in the trash, and Empty… can erase it.
|
||||
Log.Warning("workspace", $"The trash entry {staging} could not take its own name; it stays as it is", ex);
|
||||
return Directory.Exists(staging) ? staging : null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Filling.TryRemove(Path.GetFileName(staging), out _);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The entries of the workspace's trash at <paramref name="workspaceRoot"/>, with their fingerprint; empty when there is no trash.</summary>
|
||||
/// <exception cref="IOException">The trash cannot be read.</exception>
|
||||
public static WorkspaceTrashListing List(string workspaceRoot, CancellationToken cancellationToken = default)
|
||||
@@ -66,6 +128,8 @@ public static class WorkspaceTrash
|
||||
foreach (var entry in new DirectoryInfo(folder).EnumerateFileSystemInfos())
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
// An entry being filled now is no entry yet: a plan never lists it, so Empty… never erases it.
|
||||
if (entry is DirectoryInfo && Filling.ContainsKey(entry.Name)) continue;
|
||||
var (files, bytes) = (0, 0L);
|
||||
if (entry is DirectoryInfo directory)
|
||||
{
|
||||
@@ -162,3 +226,34 @@ public static class WorkspaceTrash
|
||||
Directory.Delete(path, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A trash entry being filled (<see cref="WorkspaceTrash.Begin"/>): <see cref="Path"/> is its staging folder, left out of every
|
||||
/// listing; disposing it gives the entry its own name (<see cref="Entry"/>), or removes it when nothing came into it.
|
||||
/// </summary>
|
||||
public sealed class WorkspaceTrashBuilder : IDisposable
|
||||
{
|
||||
private readonly string _root;
|
||||
private readonly Guid _projectId;
|
||||
private int _done;
|
||||
|
||||
internal WorkspaceTrashBuilder(string root, Guid projectId, string path)
|
||||
{
|
||||
(_root, _projectId, Path) = (root, projectId, path);
|
||||
}
|
||||
|
||||
/// <summary>The staging folder to fill.</summary>
|
||||
public string Path { get; }
|
||||
|
||||
/// <summary>The entry once finished; null before, or when nothing came into it.</summary>
|
||||
public string? Entry { get; private set; }
|
||||
|
||||
/// <summary>Gives the entry its own name (or removes it when empty); later calls do nothing.</summary>
|
||||
public string? Finish()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _done, 1) == 0) Entry = WorkspaceTrash.Finish(_root, _projectId, Path);
|
||||
return Entry;
|
||||
}
|
||||
|
||||
public void Dispose() => Finish();
|
||||
}
|
||||
Reference in new issue
Block a user