Merge branch 'review2-p5a-fix4-sync' into review2-p5a-int4

This commit is contained in:
Alby96 committed 2026-11-03 14:23:47 +01:00
commit 93afe71639
14 files changed
+729 -57

No files matched your search

@@ -327,6 +327,32 @@ public sealed class WorkspaceHostTests(TestContext context)
Assert.Null(host.Store.Find(vertical));
}
[Test]
public async Task ARemovalThatCannotMoveAFilePutsTheCopyBackWholeAndSaysSo()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var vertical = await bed.CheckoutAsync(host, newName: "Vertical");
var project = host.Store.Find(vertical)!;
var bundle = File.ReadAllBytes(project.BundlePath);
var held = Path.Combine(project.Folder, "notes.txt");
File.WriteAllText(held, "mine");
// Another program holds a file of the copy: what was moved aside goes back, the working state with it.
using (new FileStream(held, FileMode.Open, FileAccess.Read, FileShare.None))
await Assert.ThrowsAsync<IOException>(() => host.RemoveLocalCopyAsync(vertical, discard: true));
Assert.SequenceEqual(bundle, File.ReadAllBytes(project.BundlePath), "the working state is back");
Assert.Contains(await host.ListAsync(), e => e.ProjectId == vertical && e.IsReadable);
Assert.True(Directory.Exists(project.MediaDirectory) && Directory.Exists(project.VersionsDirectory), "the copy is whole");
var trash = Path.Combine(host.Root, WorkspaceHost.TrashFolder);
Assert.False(Directory.Exists(trash) && Directory.EnumerateDirectories(trash).Any(d => Path.GetFileName(d).StartsWith(vertical.ToString("N"), StringComparison.Ordinal)),
"nothing is left aside");
// The file let go: removed.
await host.RemoveLocalCopyAsync(vertical, discard: true);
Assert.Null(host.Store.Find(vertical));
}
[Test]
public async Task OlderVersionsArePrunedPastKeptVersionsOnlyOnceTheLibraryHoldsThem()
{
@@ -176,6 +176,45 @@ public sealed class WorkspaceMenuTests(TestContext context)
}
}
[Test]
public async Task SaveBothOfAProjectDeletedInTheLibrarySaysItIsGoneOnceAndOffersTheCopy()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context);
var here = bed.Host();
var there = bed.Host(name: "other-pc");
var sideId = await bed.CheckoutAsync(here, newName: "Side");
await bed.CheckoutAsync(there, sideId);
var (sourceA, sessionA) = await bed.OpenAsync(there, sideId);
var (sourceB, sessionB) = await bed.OpenAsync(here, sideId);
var (uiA, uiB) = (new RecordingUi(), new RecordingUi());
await using (sessionA)
await using (sessionB)
using (var a = new ProjectMenuViewModel(there, sourceA, sessionA, uiA))
using (var b = new ProjectMenuViewModel(here, sourceB, sessionB, uiB))
{
sessionA.Edit(p => Exposure(p, 0.1));
await a.SaveVersionAsync(null);
sessionB.Edit(p => Exposure(p, 0.7));
await b.SyncAsync();
uiB.CloseDialog(Assert.NotNull(uiB.Open as ConflictDialogViewModel));
// Another PC deletes the project in the library while the choice is made here.
await bed.Archives.Projects.DeleteAsync(sideId, bed.Ct);
var before = uiB.Toasts.Count;
await b.ResolveAsync(ConflictChoice.SaveBoth);
Assert.Equal(WorkspaceState.Gone, b.Status!.State);
Assert.Null(b.Status.Conflict, "nothing is left to answer");
Assert.Null(uiB.Open, "the conflict is not asked again");
var said = uiB.Toasts.Skip(before).ToList();
Assert.Count(1, said.Where(t => t.Message == Loc.L("Errors.Workspace.DeletedAtHome")).ToList());
var copy = Assert.Contains(said, t => t.Action is not null);
Assert.Equal(b.Name, copy.Message, "the copy Save both made is offered");
Assert.False(b.SaveVersionCommand.CanExecute(null), "nothing can be sent to it");
Assert.Equal(0.7, sessionB.Project.Exposure.ExposureOffsetEv, "the work stays in the editor");
Assert.Equal(0.7, here.Store.Find(sideId)!.ReadBundle().Project.Exposure.ExposureOffsetEv);
}
}
[Test]
public async Task OpenProjectOffersTheLibrarysOtherProjects()
{
@@ -256,6 +295,10 @@ public sealed class WorkspaceMenuTests(TestContext context)
var gone = new WorkspaceStatus(WorkspaceState.Gone, false, 0, 0, true, false, false, null, basis, null);
var edited = new WorkspaceStatus(WorkspaceState.Modified, true, 0, 0, false, false, false, null, basis, null);
Assert.Equal(WorkspaceState.Gone, ProjectMenuViewModel.WithLocal(gone, edited).State);
// A conflict recorded here asks nothing of a project the library no longer has.
var recorded = new WorkspaceConflict(Guid.NewGuid(), 3, basis.VersionId, [], [], DateTimeOffset.UtcNow);
var stillGone = ProjectMenuViewModel.WithLocal(gone, edited with { State = WorkspaceState.Conflict, Conflict = recorded });
Assert.Equal((WorkspaceState.Gone, (WorkspaceConflict?)null), (stillGone.State, stillGone.Conflict));
var behind = gone with { State = WorkspaceState.Behind, Behind = 2, Offline = false };
Assert.Equal((WorkspaceState.Behind, 2), (ProjectMenuViewModel.WithLocal(behind, edited).State, ProjectMenuViewModel.WithLocal(behind, edited).Behind));
Assert.Equal(WorkspaceState.Modified, ProjectMenuViewModel.WithLocal(behind, edited with { Base = basis with { VersionId = Guid.NewGuid() } }).State,
@@ -192,6 +192,9 @@ public sealed class WorkspaceSectionTests(TestContext context)
var aside = Assert.Contains(Directory.EnumerateDirectories(Path.Combine(outside, WorkspaceHost.TrashFolder)),
d => Path.GetFileName(d).StartsWith(damagedId.ToString("N"), StringComparison.Ordinal));
Assert.Equal("kept", await File.ReadAllTextAsync(Path.Combine(aside, "notes.txt")));
// Nothing knows its name: the toast names no folder id.
await WorkspaceTestBed.UntilAsync(() => toasts.Any(t => t.Title == Loc.L("Editor.Workspace.Removed")), "the removal is said");
Assert.Null(toasts.Single(t => t.Title == Loc.L("Editor.Workspace.Removed")).Message);
}
finally
{
@@ -201,6 +204,91 @@ public sealed class WorkspaceSectionTests(TestContext context)
}
});
[Test]
public Task AMainThisChronosCannotReadSaysWhyAtOnceAndADamagedOneOffersItsRemoval() => ScreenHost.RunAsync(async () =>
{
var directory = context.CreateTempDirectory("workspace-unreadable-main");
var environment = AppEnvironment.From(AppPaths.Resolve(Directory.CreateDirectory(Path.Combine(directory, "app")).FullName,
Directory.CreateDirectory(Path.Combine(directory, "local")).FullName, []));
UiLanguage.Apply("en");
var settings = new AppSettings { Language = "en", FirstRunCompleted = true, CheckForUpdates = false };
var dialogs = new ScriptedDialogs();
var services = new AppServices(environment, settings, () => { }, dialogs);
await services.AttachAsync(await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(environment.DatabasePath)), startEngine: true);
var shell = new ShellViewModel(services);
var toasts = new List<Toast>();
shell.PendingToasts.CollectionChanged += (_, e) => toasts.AddRange(e.NewItems?.OfType<Toast>() ?? []);
try
{
var sequenceId = await SequenceAsync(services, Path.Combine(directory, "archive"));
var section = shell.Sequence;
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenInWorkspaceDialogViewModel, "Open in workspace asks the first time");
((OpenInWorkspaceDialogViewModel)section.Dialog!).OpenCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => section.Editor is not null, "Main opens");
var mainId = section.OpenProjectId!.Value;
Assert.True(await section.ConfirmCloseAsync());
await section.CloseAsync();
shell.KeepSequence(null);
var folder = Path.Combine(services.Workspace.Root, mainId.ToString("N"));
var bundle = Path.Combine(folder, WorkspaceProject.BundleFile);
// Saved by a newer Chronos: said at once, nothing offered over it, nothing asked.
await WriteWhenFreeAsync(bundle,
$$"""{ "format": "chronos-project", "formatVersion": 9, "sequence": { "title": "Synthetic" }, "workspace": { "projectId": "{{mainId}}", "name": "Main", "isMain": true } }""");
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => toasts.Any(t => t.Message == Loc.L("Errors.Workspace.NewerCopy")), "a newer Main is refused");
var newer = toasts.Single(t => t.Message == Loc.L("Errors.Workspace.NewerCopy"));
Assert.True(newer is { Title: var title, IsError: true, ActionCommand: null } && title == Loc.L("Editor.Workspace.OpenFailed"));
Assert.True(section.Dialog is null && section.Editor is null, "nothing asked, nothing opened");
Assert.FileExists(bundle);
shell.KeepSequence(null);
// Damaged: said at once, with Remove local copy; its Discard keeps the files aside, named as the copy is known.
await WriteWhenFreeAsync(bundle, "{ not a project");
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => toasts.Any(t => t.Message == Loc.L("Errors.Workspace.Damaged")), "a damaged Main is refused");
var damaged = toasts.Single(t => t.Message == Loc.L("Errors.Workspace.Damaged"));
Assert.Equal((Loc.L("Editor.Workspace.OpenFailed"), true, Loc.L("Editor.Project.RemoveCopy"), Loc.L("Tooltips.Editor.Workspace.State.DamagedCopy")),
(damaged.Title, damaged.IsError, damaged.ActionText, damaged.ActionToolTip));
Assert.True(section.Dialog is null && section.Editor is null, "nothing asked, nothing opened");
damaged.ActionCommand!.Execute(null);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is RemoveCopyDialogViewModel, "its removal is offered");
var remove = (RemoveCopyDialogViewModel)section.Dialog!;
Assert.True(remove.Plan.Damaged, "removed as a damaged copy");
Assert.Equal(Loc.L("Editor.RemoveCopy.Title", Loc.L("Editor.Project.Main")), remove.Heading);
remove.DiscardCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => toasts.Any(t => t.Title == Loc.L("Editor.Workspace.Removed")), "the copy goes");
Assert.False(Directory.Exists(folder));
var removed = toasts.Single(t => t.Title == Loc.L("Editor.Workspace.Removed"));
Assert.Equal(Loc.L("Editor.Project.Main"), removed.Message, "named as the index knows it, never by its folder");
}
finally
{
await shell.Sequence.CloseAsync();
shell.Dispose();
await services.DisposeAsync();
}
});
/// <summary>Writes <paramref name="path"/> once the project's last background read (its state, after the close) lets go of it.</summary>
private static async Task WriteWhenFreeAsync(string path, string text)
{
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(20));
while (true)
{
try
{
await File.WriteAllTextAsync(path, text);
return;
}
catch (IOException) when (DateTime.UtcNow < until)
{
await Task.Delay(50);
}
}
}
/// <summary>An archive with one sequence of six synthetic photos, indexed.</summary>
private async Task<Guid> SequenceAsync(AppServices services, string root)
{
@@ -2,6 +2,7 @@ using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Repositories;
using Chronos.Data.Tests.Archiving;
using Chronos.Data.Tests.Infrastructure;
using Chronos.Data.Tests.Projects;
@@ -268,10 +269,17 @@ public abstract class WorkspaceSafetyTests(TestContext context) : DatabaseTest(c
var both = await three.ResolveAsync(id, fx.Home, ConflictChoice.SaveBoth, cancellationToken: fx.Ct);
Assert.Equal(WorkspaceState.Gone, both.Status.State);
// Gone holds no conflict to answer: the editor says the project is gone, never asks the conflict again.
Assert.Null(both.Status.Conflict, "a project the home no longer has asks nothing");
var copy = Assert.NotNull(both.SavedAs, "the copy holds this side's work at the home");
Assert.NotNull(project.ReadSync().Conflict, "the conflict stays recorded");
Assert.Null((await three.StatusAsync(id, fx.Home, fx.Ct)).Conflict);
var listed = (await fx.Home.ListAsync(fx.Ct)).Count;
var again = await three.ResolveAsync(id, fx.Home, ConflictChoice.SaveBoth, cancellationToken: fx.Ct);
Assert.Equal(WorkspaceState.Gone, again.Status.State);
Assert.Null(again.Status.Conflict);
Assert.Equal(listed, (await fx.Home.ListAsync(fx.Ct)).Count);
Assert.Contains(await fx.Home.ListAsync(fx.Ct), p => p.Id == copy.Id);
Assert.Equal(WorkspaceState.Gone, (await three.PushAsync(id, fx.Home, fx.Ct)).Status.State);
// Nothing of this side's is lost: its versions wait here, the working state as it was.
@@ -280,6 +288,116 @@ public abstract class WorkspaceSafetyTests(TestContext context) : DatabaseTest(c
Assert.Contains(project.Versions(), v => v.Note == "bright");
}
[Test]
public async Task KeepMineOrTakeTheLibrarysOnAProjectDeletedAtTheHomeIsGoneAndChangesNothing()
{
var fx = await FixtureAsync();
var side = await ProjectAsync(fx, "Side");
var (_, three, project, id) = await SavedConflictAsync(fx, side);
await EditAsync(three, id, s => s with { Stack = new StackSettings { Mode = StackSetting.Mean } }, fx.Ct);
var shown = Assert.NotNull(project.ReadSync().Conflict);
var versions = project.Versions().Select(v => (v.Id, v.ContentHash)).ToList();
await fx.Archive.Service.Projects.DeleteAsync(id, fx.Ct);
// Neither choice is merged onto the last version the home had: Gone, the working state and the unsent version as they were.
foreach (var choice in new[] { ConflictChoice.KeepMine, ConflictChoice.TakeServer })
{
var result = await three.ResolveAsync(id, fx.Home, choice, shown: shown, cancellationToken: fx.Ct);
Assert.Equal(WorkspaceState.Gone, result.Status.State, $"{choice}");
Assert.Null(result.Status.Conflict);
Assert.Null(result.Kept, "nothing was taken over");
Assert.Empty(result.Pulled);
var working = (await three.OpenAsync(id, fx.Ct)).Working;
Assert.Equal((2.0, StackSetting.Mean), (working.Exposure.ExposureOffsetEv, working.Stack.Mode));
Assert.Equal("bright", three.Unpushed(id).Single().Note);
Assert.SequenceEqual(versions, project.Versions().Select(v => (v.Id, v.ContentHash)));
Assert.Empty(Replaced(project));
Assert.Equal(shown.TheirsVersionId, Assert.NotNull(project.ReadSync().Conflict).TheirsVersionId, "the conflict stays recorded");
}
Assert.Equal(WorkspaceState.Gone, (await three.PullAsync(id, fx.Home, fx.Ct)).Status.State);
Assert.Equal("bright", three.Unpushed(id).Single().Note);
}
[Test]
public async Task APushStoppedAtAConflictLeavesTheReplacedVersionsAndOneThatEndsWellPrunesThem()
{
var fx = await FixtureAsync();
var (_, one) = fx.Workspace("one");
var (_, three) = fx.Workspace("three");
var id = (await fx.CheckoutAsync(one)).ProjectId;
var project = await fx.CheckoutAsync(three, id);
await EditAsync(one, id, s => Offset(s, 0.5), fx.Ct);
await one.CommitAsync(id, cancellationToken: fx.Ct);
await one.PushAsync(id, fx.Home, fx.Ct);
await EditAsync(three, id, s => Offset(s, 2), fx.Ct);
await three.CommitAsync(id, "bright", cancellationToken: fx.Ct);
var old = OldReplaced(project, 40);
var stopped = await three.PushAsync(id, fx.Home, fx.Ct);
Assert.Equal(WorkspaceState.Conflict, stopped.Status.State);
Assert.FileExists(old);
await three.ResolveAsync(id, fx.Home, ConflictChoice.KeepMine, shown: stopped.Status.Conflict, cancellationToken: fx.Ct);
Assert.Count(1, (await three.PushAsync(id, fx.Home, fx.Ct)).Pushed);
Assert.False(File.Exists(old), "a push that ended well prunes");
}
/// <summary>A file in <c>versions/.replaced</c> set aside <paramref name="days"/> days ago, by this Chronos (the folder known since then).</summary>
private static string OldReplaced(WorkspaceProject project, int days)
{
var aside = Path.Combine(project.VersionsDirectory, WorkspaceProject.ReplacedFolder);
Directory.CreateDirectory(aside);
var then = DateTime.UtcNow - TimeSpan.FromDays(days);
File.WriteAllText(Path.Combine(project.VersionsDirectory, WorkspaceProject.ReplacedSinceFile), then.ToString("O", System.Globalization.CultureInfo.InvariantCulture));
var old = Path.Combine(aside, $"1-{Guid.CreateVersion7():N}.json");
File.WriteAllText(old, "{}");
File.SetLastWriteTimeUtc(old, then);
return old;
}
[Test]
public async Task AMergeIsMarkedOnTheVersionThatCarriesItNeverOnOneTheWorkingStateAloneConflicted()
{
var fx = await FixtureAsync();
var (_, one) = fx.Workspace("one");
var (_, two) = fx.Workspace("two");
var id = (await fx.CheckoutAsync(one)).ProjectId;
await fx.CheckoutAsync(two, id);
await EditAsync(one, id, s => Offset(s, 0.5), fx.Ct);
await one.CommitAsync(id, cancellationToken: fx.Ct);
await one.PushAsync(id, fx.Home, fx.Ct);
// Saved here: a stack the library never touched; then, not saved, the offset the library changed too.
await EditAsync(two, id, s => s with { Stack = new StackSettings { Mode = StackSetting.Mean } }, fx.Ct);
await two.CommitAsync(id, "stacked", cancellationToken: fx.Ct);
await EditAsync(two, id, s => Offset(s, 1.0), fx.Ct);
var shown = Assert.NotNull((await two.PullAsync(id, fx.Home, fx.Ct)).Status.Conflict);
Assert.Equal("exposure.exposureOffsetEv", shown.Differences.Single().Path);
// Keep mine: the choice lives in the working state; "stacked" replayed merges nothing and stays a commit.
var kept = await two.ResolveAsync(id, fx.Home, ConflictChoice.KeepMine, shown: shown, cancellationToken: fx.Ct);
Assert.Null(kept.Status.Conflict);
var stacked = two.Unpushed(id).Single();
Assert.Equal(("stacked", ProjectVersionKind.Commit), (stacked.Note, stacked.Kind));
Assert.Equal(1.0, await WorkingOffsetAsync(two, id, fx.Ct));
// A version whose own change met the library's: marked as the merge.
var (_, three) = fx.Workspace("three");
await fx.CheckoutAsync(three, id);
await two.PushAsync(id, fx.Home, fx.Ct);
await EditAsync(three, id, s => Offset(s, 2.0), fx.Ct);
await three.CommitAsync(id, "bright", cancellationToken: fx.Ct);
await EditAsync(three, id, s => s with { Stack = new StackSettings { Mode = StackSetting.Median } }, fx.Ct);
await three.CommitAsync(id, "median", cancellationToken: fx.Ct);
await two.CommitAsync(id, "sent", cancellationToken: fx.Ct);
await two.PushAsync(id, fx.Home, fx.Ct);
var asked = Assert.NotNull((await three.PushAsync(id, fx.Home, fx.Ct)).Status.Conflict);
await three.ResolveAsync(id, fx.Home, ConflictChoice.KeepMine, shown: asked, cancellationToken: fx.Ct);
var replayed = three.Unpushed(id);
Assert.SequenceEqual(["bright", "median"], replayed.Select(v => v.Note));
Assert.Equal(ProjectVersionKind.Merge, replayed[^1].Kind, "the last version carrying the choice");
Assert.Equal(ProjectVersionKind.Commit, replayed[0].Kind);
}
[Test]
public async Task ACopyWritesAConvertedPhotoUnderANameOfItsOwnAndSwitchesAtItsCommit()
{
@@ -375,6 +493,70 @@ public abstract class WorkspaceSafetyTests(TestContext context) : DatabaseTest(c
Assert.Equal(fx.Frames.Count, Directory.GetFiles(project.ProxiesDirectory, "*.jpg").Length);
}
[Test]
public async Task AFirstCopyCancelledWhilePausedRemovesTheMediaItWroteUnderTheLease()
{
var fx = await FixtureAsync();
var (store, sync) = fx.Workspace();
var id = (await fx.Archive.Service.Projects.MainAsync(fx.Sequence.Id, fx.Ct)).Id;
var project = await sync.CheckoutAsync(fx.Home, id, cancellationToken: fx.Ct);
Job job;
using (await project.LockAsync(Wait, fx.Ct))
{
job = await fx.StartCopyAsync(store, id);
await UntilAsync(() => Directory.Exists(project.ProxiesDirectory) && Directory.GetFiles(project.ProxiesDirectory, "*.jpg").Length == fx.Frames.Count,
"the copy's files", fx.Ct);
await fx.PauseAsync(job.Id);
await fx.Archive.WaitForAsync(job.Id, JobState.Paused, (int)TestTiming.Budget(30));
}
// Cancelled while paused (no handler runs it) and while another holds the project: removed once that one let go.
var lease = await project.LockAsync(Wait, fx.Ct);
try
{
await fx.CancelAsync(job.Id);
await fx.Archive.WaitForAsync(job.Id, JobState.Cancelled, (int)TestTiming.Budget(30));
await Task.Delay(200, fx.Ct);
Assert.True(Directory.Exists(project.MediaDirectory), "nothing is removed while another holds the project");
}
finally
{
lease.Dispose();
}
await UntilAsync(() => !Directory.Exists(project.MediaDirectory), "the cancelled copy's media removed", fx.Ct);
Assert.Equal(id, project.ReadBundle().Workspace!.ProjectId);
// Copied again, then a copy paused and cancelled: media a copy finished stay.
await fx.CopyAsync(store, id);
var media = project.ReadMedia()!;
using (await project.LockAsync(Wait, fx.Ct))
{
job = await fx.StartCopyAsync(store, id);
await fx.Archive.WaitForAsync(job.Id, JobState.Running, (int)TestTiming.Budget(30));
await fx.PauseAsync(job.Id);
await fx.Archive.WaitForAsync(job.Id, JobState.Paused, (int)TestTiming.Budget(30));
await fx.CancelAsync(job.Id);
}
await Task.Delay(200, fx.Ct);
using (await project.LockAsync(Wait, fx.Ct))
Assert.Equal(media.Frames.Count, project.ReadMedia()!.Frames.Count);
foreach (var frame in media.Frames) Assert.FileExists(project.MediaFile(frame.File!));
}
[Test]
public void TheSpaceACopyNeedsCountsAPhotoHeldUnderEitherName()
{
var a = Guid.CreateVersion7();
var b = Guid.CreateVersion7();
var held = WorkspaceCopyJobHandler.HeldFrames([
Path.Combine("p", $"{a:N}.jpg"),
Path.Combine("p", $"{b:N}-0123456789abcdef.jpg"),
Path.Combine("p", $"{Guid.CreateVersion7():N}x.jpg"),
Path.Combine("p", "notes.jpg"),
]);
Assert.SequenceEqual(new[] { a, b }.Order(), held.Order());
}
[Test]
public async Task AVersionReadAsDamagedWhileAnotherHoldsTheProjectIsReportedOnlyOnceConfirmed()
{
@@ -404,6 +586,9 @@ public abstract class WorkspaceSafetyTests(TestContext context) : DatabaseTest(c
var aside = Path.Combine(project.VersionsDirectory, WorkspaceProject.ReplacedFolder);
Directory.CreateDirectory(aside);
var now = DateTime.UtcNow;
// This Chronos has known the folder for longer than any of its files.
File.WriteAllText(Path.Combine(project.VersionsDirectory, WorkspaceProject.ReplacedSinceFile),
(now - TimeSpan.FromDays(400)).ToString("O", System.Globalization.CultureInfo.InvariantCulture));
var files = new List<(string Path, Guid Id)>();
for (var i = 0; i < 25; i++)
{
@@ -426,6 +611,37 @@ public abstract class WorkspaceSafetyTests(TestContext context) : DatabaseTest(c
Assert.DoesNotContain(files[23].Path, left);
}
[Test]
public void AFileAnEarlierBuildSetAsideIsKeptAMonthFromWhenThisOneFirstKnewTheFolder()
{
var store = new WorkspaceStore(Path.Combine(Context.CreateTempDirectory("prune-old"), "workspace"));
var project = store.Project(Guid.CreateVersion7());
var aside = Path.Combine(project.VersionsDirectory, WorkspaceProject.ReplacedFolder);
Directory.CreateDirectory(aside);
var now = DateTime.UtcNow;
// Set aside by an earlier build, which kept the time its version was written: a year ago.
var old = Path.Combine(aside, $"1-{Guid.CreateVersion7():N}.json");
File.WriteAllText(old, "{}");
File.SetLastWriteTimeUtc(old, now - TimeSpan.FromDays(365));
Assert.Equal(0, project.PruneReplaced(new HashSet<Guid>(), now));
Assert.FileExists(old);
var since = Path.Combine(project.VersionsDirectory, WorkspaceProject.ReplacedSinceFile);
Assert.FileExists(since);
Assert.Equal(0, project.PruneReplaced(new HashSet<Guid>(), now + TimeSpan.FromDays(29)));
Assert.FileExists(old);
Assert.Equal(1, project.PruneReplaced(new HashSet<Guid>(), now + TimeSpan.FromDays(31)));
Assert.False(File.Exists(old), "a month after this Chronos first knew it");
// A marker that cannot be read is written again as now: nothing goes by an age it cannot tell.
var older = Path.Combine(aside, $"2-{Guid.CreateVersion7():N}.json");
File.WriteAllText(older, "{}");
File.SetLastWriteTimeUtc(older, now - TimeSpan.FromDays(365));
File.WriteAllText(since, "not a time");
Assert.Equal(0, project.PruneReplaced(new HashSet<Guid>(), now));
Assert.FileExists(older);
}
[Test]
public async Task ASyncThatEndsWellPrunesTheReplacedVersions()
{
@@ -438,9 +654,7 @@ public abstract class WorkspaceSafetyTests(TestContext context) : DatabaseTest(c
Assert.Count(1, files);
var taken = files[0];
Assert.True(DateTime.UtcNow - File.GetLastWriteTimeUtc(taken) < TimeSpan.FromHours(1), "a file set aside is dated then");
var old = Path.Combine(aside, $"1-{Guid.CreateVersion7():N}.json");
File.WriteAllText(old, "{}");
File.SetLastWriteTimeUtc(old, DateTime.UtcNow - TimeSpan.FromDays(40));
var old = OldReplaced(project, 40);
await two.PushAsync(id, fx.Home, fx.Ct);
Assert.False(File.Exists(old));
@@ -465,6 +679,28 @@ public abstract class WorkspaceSafetyTests(TestContext context) : DatabaseTest(c
Assert.Equal(read + 1, home.FramesReads);
Assert.True((await sync.StatusAsync(id, home, fx.Ct)).MediaOutdated);
Assert.Equal(read + 1, home.FramesReads);
// A hash replaced in place (a Verify that found other bytes) moves the stamp, with no other frames version.
var frame = (await fx.Db.Frames.ListBySequenceAsync(fx.Sequence.Id, cancellationToken: fx.Ct))[2];
var before = await fx.Home.FramesStampAsync(fx.Ct);
var sha = frame.Sha256 ?? new string('0', 64);
var other = (sha[0] == 'f' ? "e" : "f") + sha[1..];
Assert.Equal(1, await fx.Db.Frames.UpdateIntegrityAsync([new FrameIntegrity(frame.Id, frame.Flags, other)], fx.Ct));
Assert.NotEqual(before, await fx.Home.FramesStampAsync(fx.Ct));
await sync.StatusAsync(id, home, fx.Ct);
Assert.Equal(read + 2, home.FramesReads, "the frames read again");
}
[Test]
public async Task TheFramesStampMovesWhenTwoPhotosSwapTheirHashes()
{
var fx = await FixtureAsync(4);
var frames = await fx.Db.Frames.ListBySequenceAsync(fx.Sequence.Id, cancellationToken: fx.Ct);
var (a, b) = (new string('a', 64), new string('b', 64));
await fx.Db.Frames.UpdateIntegrityAsync([new FrameIntegrity(frames[0].Id, frames[0].Flags, a), new FrameIntegrity(frames[1].Id, frames[1].Flags, b)], fx.Ct);
var before = await fx.Home.FramesStampAsync(fx.Ct);
await fx.Db.Frames.UpdateIntegrityAsync([new FrameIntegrity(frames[0].Id, frames[0].Flags, b), new FrameIntegrity(frames[1].Id, frames[1].Flags, a)], fx.Ct);
Assert.NotEqual(before, await fx.Home.FramesStampAsync(fx.Ct));
}
}