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>
225 lines
12 KiB
C#
225 lines
12 KiB
C#
using System.Globalization;
|
||
using System.IO;
|
||
using Chronos.App.Infrastructure;
|
||
using Chronos.App.Workspace;
|
||
using Chronos.Core.Localization;
|
||
using Chronos.Core.Model;
|
||
using Chronos.Data;
|
||
using Chronos.Data.Archiving;
|
||
using Chronos.Data.Jobs;
|
||
using Chronos.Data.Workspaces;
|
||
using Chronos.Testing;
|
||
|
||
namespace Chronos.App.Tests.Workspace;
|
||
|
||
/// <summary>
|
||
/// Settings › Workspace › Move… (phase 5c, P6) as the desktop runs it: the plan and its confirmation, the open project
|
||
/// closed first, the workspace held while the move waits or runs, the setting switched only once the move verified
|
||
/// everything, a failed move that leaves both as they were, and a move stopped before it ended taken up again.
|
||
/// </summary>
|
||
[Category("workspace")]
|
||
public sealed class WorkspaceMoveTests(TestContext context)
|
||
{
|
||
static WorkspaceMoveTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||
|
||
[Test]
|
||
public async Task TheWorkspaceWaitsForTheMoveAndFollowsTheFolderOnlyOnceItEnded()
|
||
{
|
||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
|
||
var settings = new AppSettings();
|
||
var mainId = await bed.CheckoutAsync(bed.Host(settings));
|
||
await using var moves = await MovesAsync(bed, settings);
|
||
var host = moves.Host;
|
||
var from = host.Root;
|
||
var target = Path.Combine(bed.Directory, "moved workspace");
|
||
|
||
var plan = await host.PlanMoveAsync(target);
|
||
Assert.True(plan.CanMove, plan.Refusal);
|
||
Assert.Equal((from, Path.GetFullPath(target), true), (plan.From, plan.To, plan.SameVolume));
|
||
var project = Assert.NotNull(plan.Projects.SingleOrDefault());
|
||
Assert.Equal(mainId, project.ProjectId);
|
||
Assert.True(plan.Files >= project.Files && project.Files > 0 && plan.Bytes > 0);
|
||
|
||
var failures = new List<string>();
|
||
var closes = 0;
|
||
var close = true;
|
||
Task<bool> CloseProject()
|
||
{
|
||
closes++;
|
||
return Task.FromResult(close);
|
||
}
|
||
|
||
// Declined, or the open project kept open: nothing is queued.
|
||
var dialogs = new MoveDialogs { Folder = target, Answer = false };
|
||
Assert.False(await WorkspaceFolderChange.MoveAsync(host, dialogs, CloseProject, failures.Add));
|
||
var asked = Assert.NotNull(dialogs.Asked.SingleOrDefault());
|
||
Assert.Equal(Loc.L("Settings.Workspace.MovePlan.Message", plan.From, plan.To), asked.Message);
|
||
Assert.Contains(Loc.L("Settings.Workspace.MovePlan.Projects", Formatting.Count(1)), asked.Detail);
|
||
Assert.Contains(Loc.L("Settings.Workspace.MovePlan.SameVolume"), asked.Detail);
|
||
Assert.True(asked is { IsDestructive: false, ActionText.Length: > 0, ActionToolTip.Length: > 0, SafeToolTip.Length: > 0 });
|
||
Assert.Equal(0, closes, "nothing closed before the plan is confirmed");
|
||
dialogs.Answer = true;
|
||
close = false;
|
||
Assert.False(await WorkspaceFolderChange.MoveAsync(host, dialogs, CloseProject, failures.Add));
|
||
Assert.False(host.IsMoving);
|
||
|
||
// Queued: until it ends the workspace opens, copies, syncs and changes folder no more, and is not moved twice.
|
||
close = true;
|
||
Assert.True(await WorkspaceFolderChange.MoveAsync(host, dialogs, CloseProject, failures.Add));
|
||
Assert.Empty(failures);
|
||
Assert.True(host.IsMoving);
|
||
var moving = Loc.L("Errors.Workspace.Moving");
|
||
Assert.Equal(moving, (await Assert.ThrowsAsync<WorkspaceException>(() => host.FindAsync(mainId))).Message);
|
||
Assert.Equal(moving, (await Assert.ThrowsAsync<WorkspaceException>(() => host.ProjectsOfAsync(bed.SequenceId))).Message);
|
||
Assert.Equal(moving, (await Assert.ThrowsAsync<WorkspaceException>(() => host.SyncAsync(mainId))).Message);
|
||
Assert.Equal(moving, (await Assert.ThrowsAsync<WorkspaceException>(() => host.QueueCopyAsync(mainId))).Message);
|
||
Assert.Equal(moving, (await Assert.ThrowsAsync<WorkspaceException>(() => host.CheckoutAsync(bed.SequenceId, mainId, null))).Message);
|
||
Assert.Equal(moving, (await Assert.ThrowsAsync<WorkspaceException>(() => host.UseFolderAsync(Path.Combine(bed.Directory, "elsewhere")))).Message);
|
||
Assert.False(await WorkspaceFolderChange.MoveAsync(host, dialogs, CloseProject, failures.Add));
|
||
Assert.SequenceEqual([moving], failures);
|
||
Assert.Equal(((string?)null, 0), (settings.WorkspaceFolder, moves.Saves), "the setting waits for the move");
|
||
|
||
await moves.Engine.StartAsync(context.Cancellation);
|
||
var job = Assert.NotNull((await moves.Db.Jobs.ListAsync(null, JobKind.WorkspaceMove, 5, cancellationToken: context.Cancellation)).Items.SingleOrDefault());
|
||
await moves.WaitAsync(job.Id, JobState.Done);
|
||
await WorkspaceTestBed.UntilAsync(() => !host.IsMoving, "the workspace is let go");
|
||
|
||
Assert.Equal((Path.GetFullPath(target), 1), (settings.WorkspaceFolder, moves.Saves));
|
||
Assert.Equal(Path.GetFullPath(target), host.Root);
|
||
Assert.Equal(mainId, Assert.NotNull(await host.FindAsync(mainId)).ProjectId);
|
||
Assert.Equal(mainId, (await host.ListAsync()).Single().ProjectId);
|
||
Assert.False(Directory.Exists(Path.Combine(from, mainId.ToString("N"))), "the project left the folder");
|
||
}
|
||
|
||
[Test]
|
||
public async Task AMoveThatFailsLeavesTheSettingAndTheWorkspaceWhereTheyWere()
|
||
{
|
||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
|
||
var settings = new AppSettings();
|
||
var mainId = await bed.CheckoutAsync(bed.Host(settings));
|
||
await using var moves = await MovesAsync(bed, settings);
|
||
var host = moves.Host;
|
||
var from = host.Root;
|
||
var target = Path.Combine(bed.Directory, "target");
|
||
|
||
// A workspace job waiting refuses the plan.
|
||
var copy = await moves.Engine.EnqueueAsync(JobKind.WorkspaceCopy, [bed.SequenceId], "copy", null, cancellationToken: context.Cancellation);
|
||
Assert.Equal(Loc.L("Errors.Workspace.JobsRunning"), (await host.PlanMoveAsync(target)).Refusal);
|
||
await moves.Engine.CancelAsync(copy.Id, context.Cancellation);
|
||
|
||
var plan = await host.PlanMoveAsync(target);
|
||
await host.QueueMoveAsync(plan);
|
||
// Meanwhile the target became a workspace of its own: the job refuses it.
|
||
_ = new WorkspaceStore(target);
|
||
await moves.Engine.StartAsync(context.Cancellation);
|
||
var job = Assert.NotNull((await moves.Db.Jobs.ListAsync(null, JobKind.WorkspaceMove, 5, cancellationToken: context.Cancellation)).Items.SingleOrDefault());
|
||
var failed = await moves.WaitAsync(job.Id, JobState.Failed);
|
||
Assert.Equal(Loc.L("Errors.Workspace.MoveTargetNotEmpty", Path.GetFullPath(target)), failed.Error);
|
||
await WorkspaceTestBed.UntilAsync(() => !host.IsMoving, "the workspace is let go");
|
||
|
||
Assert.Equal(((string?)null, 0, from), (settings.WorkspaceFolder, moves.Saves, host.Root));
|
||
Assert.Equal(mainId, Assert.NotNull(await host.FindAsync(mainId)).ProjectId);
|
||
Assert.Empty(new WorkspaceStore(target).List());
|
||
}
|
||
|
||
[Test]
|
||
public async Task AMoveStoppedBeforeItEndedIsOfferedAgainAndGoesOn()
|
||
{
|
||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
|
||
var settings = new AppSettings();
|
||
var mainId = await bed.CheckoutAsync(bed.Host(settings));
|
||
await using var moves = await MovesAsync(bed, settings);
|
||
var host = moves.Host;
|
||
var from = host.Root;
|
||
var target = Path.Combine(bed.Directory, "target");
|
||
|
||
// The program closed as the move began: its journal is in the folder, and no job waits for it.
|
||
var plan = await host.PlanMoveAsync(target);
|
||
using (var closed = new CancellationTokenSource())
|
||
{
|
||
await closed.CancelAsync();
|
||
await Assert.ThrowsAsync<OperationCanceledException>(() => new WorkspaceMover(from, target).MoveAsync(plan.Fingerprint, cancellationToken: closed.Token));
|
||
}
|
||
Assert.True(host.IsMoving, "a journal holds the workspace");
|
||
Assert.Equal(Loc.L("Errors.Workspace.Moving"), (await Assert.ThrowsAsync<WorkspaceException>(() => host.FindAsync(mainId))).Message);
|
||
var journal = Assert.NotNull(await host.UnfinishedMoveAsync());
|
||
Assert.Equal((Path.GetFullPath(target), WorkspaceMoveStage.Moving), (journal.To, journal.Stage));
|
||
|
||
var job = await host.ResumeMoveAsync(journal);
|
||
Assert.Null(await host.UnfinishedMoveAsync());
|
||
await moves.Engine.StartAsync(context.Cancellation);
|
||
var done = await moves.WaitAsync(job.Id, JobState.Done);
|
||
Assert.Contains(Loc.L("Archive.Log.WorkspaceMoveResumed", Path.Combine(from, WorkspaceMover.JournalFile)), done.LogTail);
|
||
await WorkspaceTestBed.UntilAsync(() => !host.IsMoving, "the workspace is let go");
|
||
Assert.Equal(Path.GetFullPath(target), settings.WorkspaceFolder);
|
||
Assert.Equal(mainId, Assert.NotNull(await host.FindAsync(mainId)).ProjectId);
|
||
Assert.Null(await host.UnfinishedMoveAsync());
|
||
}
|
||
|
||
/// <summary>
|
||
/// A workspace over the bed's folder whose move jobs run on an engine of their own (over an index of their own, so the
|
||
/// bed's engine never takes them), which tells the workspace once a move ended; the engine is started by the test.
|
||
/// </summary>
|
||
private async Task<Moves> MovesAsync(WorkspaceTestBed bed, AppSettings settings)
|
||
{
|
||
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("moves"), "index.db")), context.Cancellation);
|
||
var moves = new Moves(db);
|
||
var options = new WorkspaceJobOptions(WorkspaceJobOptions.For(bed.Archives).Processing, () => false, (f, t) => moves.Host.MovedAsync(f, t));
|
||
moves.Engine = new JobEngine(db, WorkspaceJobs.CreateHandlers(db, bed.Archives, null, options),
|
||
new JobEngineOptions { Workers = 1, WorkerId = "moves", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
|
||
moves.Host = new WorkspaceHost(bed.Environment, settings, () => moves.Saves++, () => db, () => bed.Archives, () => moves.Engine)
|
||
{
|
||
LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)),
|
||
};
|
||
return moves;
|
||
}
|
||
|
||
private sealed class Moves(ChronosDatabase db) : IAsyncDisposable
|
||
{
|
||
public ChronosDatabase Db { get; } = db;
|
||
public JobEngine Engine { get; set; } = null!;
|
||
public WorkspaceHost Host { get; set; } = null!;
|
||
public int Saves { get; set; }
|
||
|
||
public async Task<Job> WaitAsync(Guid jobId, JobState expected)
|
||
{
|
||
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(60));
|
||
while (true)
|
||
{
|
||
var job = await Db.Jobs.GetAsync(jobId);
|
||
if (job is { State: JobState.Done or JobState.Failed or JobState.Cancelled })
|
||
{
|
||
Assert.Equal(expected, job.State, job.Error ?? job.LogTail);
|
||
return job;
|
||
}
|
||
if (DateTime.UtcNow > deadline) Assert.Fail($"Job {jobId} still {job?.State} after its time budget");
|
||
await Task.Delay(50);
|
||
}
|
||
}
|
||
|
||
public async ValueTask DisposeAsync()
|
||
{
|
||
await Engine.DisposeAsync();
|
||
await Db.DisposeAsync();
|
||
}
|
||
}
|
||
|
||
/// <summary>Dialogs that pick <see cref="Folder"/> and answer every confirmation with <see cref="Answer"/>, recording what they were asked.</summary>
|
||
private sealed class MoveDialogs : IAppDialogs
|
||
{
|
||
public string? Folder { get; set; }
|
||
public bool Answer { get; set; }
|
||
public List<ConfirmRequest> Asked { get; } = [];
|
||
public string? PickFolder(string title, string? initialFolder = null) => Folder;
|
||
public string? PickJsonFile(string title) => null;
|
||
|
||
public bool Confirm(ConfirmRequest request)
|
||
{
|
||
Asked.Add(request);
|
||
return Answer;
|
||
}
|
||
|
||
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
|
||
}
|
||
}
|