CI / Build and test (push) Successful in 9m26s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 8s
Release / Build, test and publish (push) Successful in 14m31s
CI / PostgreSQL 16 integration (push) Successful in 9m53s
CI / PostgreSQL 17 integration (push) Successful in 9m22s
CI / Docker image (push) Successful in 44s
Release / Server image (push) Successful in 1m36s
Originals in the workspace, local render and send home with provenance, the workspace clean-up, size limit and trash, moving the workspace folder, and the complete Settings › Workspace page (owner review 2, R8, phase 5c). One adversarial review round (35 findings, 32 fixed), a copy-cancel race fixed, 184 strings in all 38 languages. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
289 lines
15 KiB
C#
289 lines
15 KiB
C#
using System.IO;
|
||
using Chronos.Core.Diagnostics;
|
||
using Chronos.Core.Localization;
|
||
using Chronos.Core.Model;
|
||
using Chronos.Data.Archiving;
|
||
using Chronos.Data.Jobs;
|
||
using Chronos.Data.Workspaces;
|
||
|
||
namespace Chronos.App.Workspace;
|
||
|
||
/// <summary>A project of the workspace as the plan of a move lists it: its size, and work not at its home yet (a warning, never a refusal).</summary>
|
||
/// <param name="Unsent">Versions or renders wait to be sent to its home.</param>
|
||
/// <param name="Modified">Changes not saved as a version.</param>
|
||
public sealed record WorkspaceMoveProject(Guid ProjectId, string Name, int Files, long Bytes, bool Unsent, bool Modified);
|
||
|
||
/// <summary>
|
||
/// The plan of Settings › Workspace › Move… (phase 5c): the workspace folder <see cref="From"/> moved with its projects to
|
||
/// <see cref="To"/>: the projects and their bytes, the free bytes at the target, whether both lie on one volume (folders
|
||
/// renamed) or not (files copied and hash-verified), why it is refused (null when it can go), and a fingerprint of what
|
||
/// the plan read, which the move job checks again.
|
||
/// </summary>
|
||
/// <param name="Free">The free bytes of the target's drive; null when they cannot be measured.</param>
|
||
/// <param name="Refusal">
|
||
/// Why the move cannot go, one localized sentence: the target is the folder itself or inside it
|
||
/// (<c>Errors.Workspace.MoveSameFolder</c>), already holds a workspace or a project of the same id
|
||
/// (<c>Errors.Workspace.MoveTargetNotEmpty</c>), lies inside a library (<c>Errors.Workspace.InsideLibraryFolder</c>), lacks
|
||
/// the room (<c>Errors.Workspace.MoveNoRoom</c>), or a workspace job is pending or running (<c>Errors.Workspace.JobsRunning</c>);
|
||
/// null when it can go.
|
||
/// </param>
|
||
public sealed record WorkspaceMovePlan(string From, string To, IReadOnlyList<WorkspaceMoveProject> Projects, int Files, long Bytes, long? Free, bool SameVolume,
|
||
string? Refusal, string Fingerprint)
|
||
{
|
||
/// <summary>Nothing refuses the move.</summary>
|
||
public bool CanMove => Refusal is null;
|
||
|
||
/// <summary>Projects with work not at their home: the move keeps it, the plan says so.</summary>
|
||
public int Warnings => Projects.Count(p => p.Unsent || p.Modified);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Moving the workspace folder with its projects (phase 5c, P6): the plan, the <see cref="JobKind.WorkspaceMove"/> that
|
||
/// carries it out, and the workspace that follows the folder once every file is verified there. While a move is queued,
|
||
/// running or paused, and while the folder in use holds a move's journal (a move under way, or one stopped before it
|
||
/// ended), the workspace is refused for checkouts, copies, saves, syncs, opens and another folder
|
||
/// (<see cref="EnsureNotMoving"/>).
|
||
/// </summary>
|
||
public sealed partial class WorkspaceHost
|
||
{
|
||
/// <summary>The kinds of job that write into the workspace folder: none may wait or run when a move starts.</summary>
|
||
private static readonly JobKind[] WorkspaceJobKinds = [JobKind.WorkspaceCopy, JobKind.WorkspaceRender, JobKind.WorkspaceSend, JobKind.WorkspaceMove];
|
||
|
||
/// <summary>The thread the host was made on (the UI's): the settings are written there when a move ends.</summary>
|
||
private readonly SynchronizationContext? _moveContext = SynchronizationContext.Current;
|
||
|
||
/// <summary>The move job queued from here (or found waiting at start), until it ends; empty when there is none.</summary>
|
||
private Guid _moveJob;
|
||
|
||
/// <summary>The engine whose job changes the host follows, to see a move end.</summary>
|
||
private JobEngine? _followed;
|
||
|
||
/// <summary>
|
||
/// A move of the workspace folder is queued, running or paused, or the folder in use holds the journal of one that has
|
||
/// not ended: syncs, saves and opens wait for it.
|
||
/// </summary>
|
||
public bool IsMoving
|
||
{
|
||
get
|
||
{
|
||
lock (_gate)
|
||
{
|
||
if (_moveJob != Guid.Empty) return true;
|
||
}
|
||
return WorkspaceMover.HasJournal(Root);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// A move of the workspace folder followed here ended, however it ended (any thread): the folder in use may have changed,
|
||
/// and the workspace is no longer held for it (Settings › Workspace shows the folder and what it takes again).
|
||
/// </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; 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 () =>
|
||
{
|
||
if (_db() is not { } db) return null;
|
||
foreach (var state in new[] { JobState.Running, JobState.Queued, JobState.Paused })
|
||
{
|
||
if ((await db.Jobs.ListAsync(state, JobKind.WorkspaceMove, 1, cancellationToken: cancellationToken).ConfigureAwait(false)).Items is [var pending, ..])
|
||
{
|
||
Follow(pending.Id);
|
||
return 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>
|
||
/// The plan of moving the workspace folder to <paramref name="to"/> (<see cref="WorkspaceMovePlan"/>); nothing is
|
||
/// written. Each project is read here, never at its home: a move keeps whatever is not sent yet, the plan only says so.
|
||
/// </summary>
|
||
/// <exception cref="IOException">The workspace folder cannot be read.</exception>
|
||
public Task<WorkspaceMovePlan> PlanMoveAsync(string to, CancellationToken cancellationToken = default)
|
||
{
|
||
ArgumentException.ThrowIfNullOrWhiteSpace(to);
|
||
var root = Root;
|
||
var free = _archives()?.FreeSpace;
|
||
return Task.Run(async () =>
|
||
{
|
||
var target = Path.GetFullPath(to);
|
||
var survey = new WorkspaceMover(root, target) { FreeSpace = free }.Survey();
|
||
var projects = new List<WorkspaceMoveProject>();
|
||
foreach (var folder in survey.Projects.Where(p => p.IsProject))
|
||
{
|
||
cancellationToken.ThrowIfCancellationRequested();
|
||
projects.Add(await MoveProjectAsync(folder, cancellationToken).ConfigureAwait(false));
|
||
}
|
||
var refusal = survey.RefusalText;
|
||
if (refusal is null && await InsideALibraryAsync(survey.To, cancellationToken).ConfigureAwait(false))
|
||
refusal = Loc.L("Errors.Workspace.InsideLibraryFolder", survey.To);
|
||
if (refusal is null && (IsMoving || WorkspaceMover.HasJournal(survey.From))) refusal = Loc.L("Errors.Workspace.Moving");
|
||
if (refusal is null && _db() is { } db && await db.Jobs.HasPendingAsync(WorkspaceJobKinds, cancellationToken: cancellationToken).ConfigureAwait(false))
|
||
refusal = Loc.L("Errors.Workspace.JobsRunning");
|
||
return new WorkspaceMovePlan(survey.From, survey.To, projects, survey.Files, survey.Bytes, survey.Free, survey.SameVolume, refusal, survey.Fingerprint);
|
||
}, cancellationToken);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Queues the <see cref="JobKind.WorkspaceMove"/> of a plan the user confirmed: from now until it ends the workspace is
|
||
/// refused for writes and opens (<see cref="IsMoving"/>).
|
||
/// </summary>
|
||
/// <exception cref="WorkspaceException">The plan refuses the move, or a move is under way already.</exception>
|
||
public async Task<Job> QueueMoveAsync(WorkspaceMovePlan plan, CancellationToken cancellationToken = default)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(plan);
|
||
if (plan.Refusal is { } refusal) throw new WorkspaceException(refusal);
|
||
EnsureNotMoving();
|
||
var engine = _engine() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
|
||
var job = await engine.EnqueueAsync(WorkspaceJobs.Move(plan.From, plan.To, plan.Fingerprint), cancellationToken: cancellationToken).ConfigureAwait(false);
|
||
Follow(job.Id);
|
||
Log.Info("workspace", $"Move {job.Id} of the workspace {plan.From} to {plan.To} queued ({plan.Projects.Count} project(s), {plan.Bytes} bytes)");
|
||
return job;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Queues again the move a journal records (<see cref="UnfinishedMoveAsync"/>): it goes on from the journal, nothing
|
||
/// verified is copied twice.
|
||
/// </summary>
|
||
/// <exception cref="WorkspaceException">The index or the engine is not open.</exception>
|
||
public async Task<Job> ResumeMoveAsync(WorkspaceMoveJournal journal, CancellationToken cancellationToken = default)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(journal);
|
||
var engine = _engine() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
|
||
var job = await engine.EnqueueAsync(WorkspaceJobs.Move(journal.From, journal.To, journal.Fingerprint), cancellationToken: cancellationToken).ConfigureAwait(false);
|
||
Follow(job.Id);
|
||
Log.Info("workspace", $"Move {job.Id} of the workspace {journal.From} to {journal.To} queued again from its journal");
|
||
return job;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Told by the move job once every file of the workspace is verified at <paramref name="to"/>
|
||
/// (<c>WorkspaceJobOptions.Moved</c>, any thread): on the thread the host was made on, Settings › Workspace names the new
|
||
/// folder (none when it is the default) and the workspace opens there. A workspace that is no longer in
|
||
/// <paramref name="from"/> (another folder chosen meanwhile) keeps its folder.
|
||
/// </summary>
|
||
public Task MovedAsync(string from, string to)
|
||
{
|
||
ArgumentException.ThrowIfNullOrWhiteSpace(from);
|
||
ArgumentException.ThrowIfNullOrWhiteSpace(to);
|
||
if (_moveContext is not { } context) return Task.Run(() => FollowFolder(from, to));
|
||
if (SynchronizationContext.Current == context)
|
||
{
|
||
FollowFolder(from, to);
|
||
return Task.CompletedTask;
|
||
}
|
||
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
context.Post(_ =>
|
||
{
|
||
try
|
||
{
|
||
FollowFolder(from, to);
|
||
done.TrySetResult();
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
done.TrySetException(ex);
|
||
}
|
||
}, null);
|
||
return done.Task;
|
||
}
|
||
|
||
/// <summary>The settings name the folder a move verified everything in.</summary>
|
||
private void FollowFolder(string from, string to)
|
||
{
|
||
var target = Full(to);
|
||
if (!string.Equals(Full(Root), Full(from), StringComparison.OrdinalIgnoreCase) && !string.Equals(Full(Root), target, StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
Log.Warning("workspace", $"The workspace moved from {from} to {to}, but {Root} is in use now: it stays so");
|
||
return;
|
||
}
|
||
_settings.WorkspaceFolder = string.Equals(target, Full(DefaultRoot(_environment)), StringComparison.OrdinalIgnoreCase) ? null : target;
|
||
_savePreferences();
|
||
lock (_gate) _open = null;
|
||
Log.Info("workspace", $"The workspace folder is now {target}, moved from {from}");
|
||
|
||
static string Full(string folder) => Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder));
|
||
}
|
||
|
||
/// <summary>Refuses an operation that writes into the workspace while its folder is being moved.</summary>
|
||
/// <exception cref="WorkspaceException">A move is queued or running (<c>Errors.Workspace.Moving</c>).</exception>
|
||
private void EnsureNotMoving()
|
||
{
|
||
if (IsMoving) throw new WorkspaceException(Loc.L("Errors.Workspace.Moving"));
|
||
}
|
||
|
||
/// <summary>Holds the workspace while move job <paramref name="jobId"/> waits, runs or is paused; lets go once it ends, however it ends.</summary>
|
||
private void Follow(Guid jobId)
|
||
{
|
||
var engine = _engine();
|
||
lock (_gate)
|
||
{
|
||
_moveJob = jobId;
|
||
if (engine is null || ReferenceEquals(engine, _followed)) return;
|
||
if (_followed is { } before) before.JobChanged -= OnMoveJobChanged;
|
||
_followed = engine;
|
||
engine.JobChanged += OnMoveJobChanged;
|
||
}
|
||
}
|
||
|
||
private void OnMoveJobChanged(Job job)
|
||
{
|
||
if (job.Kind != JobKind.WorkspaceMove || job.State is not (JobState.Done or JobState.Failed or JobState.Cancelled)) return;
|
||
lock (_gate)
|
||
{
|
||
if (_moveJob != job.Id) return;
|
||
_moveJob = Guid.Empty;
|
||
}
|
||
MoveEnded?.Invoke();
|
||
}
|
||
|
||
/// <summary>A project as the move's plan lists it, read from the workspace alone (its versions not sent, its ledger, its changes).</summary>
|
||
private async Task<WorkspaceMoveProject> MoveProjectAsync(WorkspaceMoveFolder folder, CancellationToken cancellationToken)
|
||
{
|
||
var project = Store.Project(folder.ProjectId);
|
||
var entry = await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false);
|
||
// What a copy this Chronos cannot read holds is not known: it moves as it is, counted as work not at its home.
|
||
if (!entry.IsReadable) return new WorkspaceMoveProject(folder.ProjectId, entry.KnownName ?? entry.Name, folder.Files, folder.Bytes, true, false);
|
||
try
|
||
{
|
||
var status = await Sync.StatusAsync(folder.ProjectId, null, cancellationToken).ConfigureAwait(false);
|
||
var renders = WorkspaceCleaner.UnsentRenders(project);
|
||
return new WorkspaceMoveProject(folder.ProjectId, entry.Name, folder.Files, folder.Bytes, status.Ahead + status.Damaged + renders > 0 || status.Conflict is not null,
|
||
status.Modified && !status.ReadOnly);
|
||
}
|
||
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
|
||
{
|
||
Log.Info("workspace", $"Where project {folder.ProjectId} stands could not be read for the move's plan: {ex.Message}");
|
||
return new WorkspaceMoveProject(folder.ProjectId, entry.Name, folder.Files, folder.Bytes, true, false);
|
||
}
|
||
}
|
||
}
|