feat(workspace): move the workspace folder with its projects
Settings › Workspace › Change only pointed Edit at another folder and left every project behind. Moving a workspace to a bigger or faster disk now carries its projects along, without ever putting work at risk: - a plan first: projects, files, bytes, free space at the target, whether folders are renamed (one volume) or copied (another), projects with work not at their home as a warning; refused for the folder itself or one inside it, a target holding a workspace or a same-id folder, a target inside a library, too little room, or a workspace job still pending - the WorkspaceMove job checks the plan's fingerprint again, journals the move in <from>/.move.json, renames each entry on one volume, and across volumes copies each file to a .part, hashes both sides and only then renames it into place; the source goes only after every entry is verified and the desktop switched to the target - a failure before the switch is undone (renamed entries go back, copies are removed) so the source stays the workspace; a pause or a closed program goes on from the journal; a user cancel undoes it - while a move waits, runs or its journal is in the folder in use, opens, checkouts, copies, saves, syncs and another folder are refused, and a journal left at start is offered again with Resume - the setting names the new folder only once the move verified everything Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2e1c67f531
commit
c93a4b0779
8 files changed
+1670
-37
No files matched your search
@@ -1,5 +1,10 @@
|
||||
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;
|
||||
|
||||
@@ -18,8 +23,9 @@ public sealed record WorkspaceMoveProject(Guid ProjectId, string Name, int Files
|
||||
/// <param name="Refusal">
|
||||
/// Why the move cannot go, one localized sentence: the target is the folder itself or inside it
|
||||
/// (<c>Errors.Workspace.MoveSameFolder</c>), already holds a workspace or a project of the same id
|
||||
/// (<c>Errors.Workspace.MoveTargetNotEmpty</c>), lacks the room (<c>Errors.Workspace.DiskFull</c>), or a workspace job is
|
||||
/// pending or running (<c>Errors.Workspace.JobsRunning</c>); null when it can go.
|
||||
/// (<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)
|
||||
@@ -33,38 +39,169 @@ public sealed record WorkspaceMovePlan(string From, string To, IReadOnlyList<Wor
|
||||
|
||||
/// <summary>
|
||||
/// Moving the workspace folder with its projects (phase 5c, P6): the plan, the <see cref="JobKind.WorkspaceMove"/> that
|
||||
/// carries it out, and the workspace that follows the folder once every file is verified there. While a move is queued or
|
||||
/// running the workspace is refused for syncs, saves and opens (<see cref="EnsureNotMoving"/>). Stubs until the move lands.
|
||||
/// 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>A move of the workspace folder is queued or running: syncs, saves and opens wait for it.</summary>
|
||||
public bool IsMoving => false;
|
||||
/// <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 plan of moving the workspace folder to <paramref name="to"/> (<see cref="WorkspaceMovePlan"/>); nothing is written.</summary>
|
||||
/// <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 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"/>).
|
||||
/// </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;
|
||||
}
|
||||
}
|
||||
return WorkspaceMover.HasJournal(Root) ? WorkspaceMover.ReadJournal(Root) : 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);
|
||||
throw new NotImplementedException("Moving the workspace folder comes with phase 5c (P6).");
|
||||
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.</summary>
|
||||
/// <exception cref="WorkspaceException">The plan refuses the move.</exception>
|
||||
public Task<Job> QueueMoveAsync(WorkspaceMovePlan plan, CancellationToken cancellationToken = default)
|
||||
/// <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);
|
||||
throw new NotImplementedException("Moving the workspace folder comes with phase 5c (P6).");
|
||||
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>): Settings › Workspace names the new folder and the workspace opens there.
|
||||
/// (<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);
|
||||
throw new NotImplementedException("Moving the workspace folder comes with phase 5c (P6).");
|
||||
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>
|
||||
@@ -73,4 +210,61 @@ public sealed partial class WorkspaceHost
|
||||
{
|
||||
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) _moveJob = Guid.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 = 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);
|
||||
}
|
||||
|
||||
static int UnsentRenders(WorkspaceProject project)
|
||||
{
|
||||
try
|
||||
{
|
||||
return project.ReadRenders().Unsent.Count;
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
// A ledger this Chronos cannot read: what it lists is not known to be at the home.
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user