diff --git a/src/Chronos.App/Sections/SequenceViewModel.cs b/src/Chronos.App/Sections/SequenceViewModel.cs index ae62d3c9..aa0cd014 100644 --- a/src/Chronos.App/Sections/SequenceViewModel.cs +++ b/src/Chronos.App/Sections/SequenceViewModel.cs @@ -443,10 +443,12 @@ public sealed class SequenceViewModel : SectionViewModel try { var plan = await workspace.PlanRemovalAsync(projectId); - OpenDialog(new RemoveCopyDialogViewModel(plan, discard => RemoveCopyAsync(projectId, name, discard), async () => + // A damaged copy is named as it is still known, never by its folder's id (none when nothing knows it). + var shown = plan.Damaged ? plan.KnownName : name; + OpenDialog(new RemoveCopyDialogViewModel(plan, discard => RemoveCopyAsync(projectId, shown, discard), async () => { await workspace.SendAllAsync(projectId); - await RemoveCopyAsync(projectId, name, discard: false); + await RemoveCopyAsync(projectId, shown, discard: false); }, () => plan.Damaged ? RemoveCopyDialogViewModel.ConfirmDiscard(_workspaceUi, plan) : RemoveCopyDialogViewModel.ConfirmDiscard(_workspaceUi, name), d => CloseDialog(d))); } @@ -456,7 +458,7 @@ public sealed class SequenceViewModel : SectionViewModel Shell.Notify(Loc.L("Editor.Workspace.RemoveFailed"), WorkspaceText.Failure(ex), isError: true); } - async Task RemoveCopyAsync(Guid id, string project, bool discard) + async Task RemoveCopyAsync(Guid id, string? project, bool discard) { await workspace.RemoveLocalCopyAsync(id, discard); Shell.Notify(Loc.L("Editor.Workspace.Removed"), project); @@ -604,6 +606,15 @@ public sealed class SequenceViewModel : SectionViewModel }; // This Chronos cannot read its working state (damaged, or a newer Chronos's): nothing is checked out over it. if (entry is { IsReadable: false } unreadable) throw WorkspaceHost.Unreadable(unreadable); + // No project of the sequence here opens, and its Main here is such a copy (never among its projects): said at once, + // with Remove local copy for a damaged one, rather than asking which project and then refusing Main. + if (entry is null && request?.ProjectId is null && await UnreadableMainAsync(workspace, row.Id) is { } main) + { + RefuseUnreadable(main); + _afterOpen = null; + Shell.KeepSequence(OpenSequenceId); + return null; + } if (entry is { HasMedia: true }) { workspace.Remember(row.Id, entry.ProjectId); @@ -647,6 +658,30 @@ public sealed class SequenceViewModel : SectionViewModel return null; } + /// The workspace's copy of the sequence's Main when this Chronos cannot read it (damaged, or a newer Chronos's); null otherwise. + private static async Task UnreadableMainAsync(WorkspaceHost workspace, Guid sequenceId) + { + if ((await workspace.HomeProjectsAsync(sequenceId)).FirstOrDefault(p => p.IsMain) is not { } main) return null; + return await workspace.FindAsync(main.Id) is { IsReadable: false } copy ? copy : null; + } + + /// + /// Why a copy this Chronos cannot read does not open: a newer Chronos's is left as it is (nothing is offered over it), a + /// damaged one offers Remove local copy, whose Discard keeps its files aside. + /// + private void RefuseUnreadable(WorkspaceEntry copy) + { + Log.Info("workspace", $"Project {copy.ProjectId} here cannot be read by this Chronos ({(copy.Newer ? "newer" : "damaged")}): it is not opened"); + if (copy.Newer) + { + Shell.Notify(Loc.L("Editor.Workspace.OpenFailed"), Loc.L("Errors.Workspace.NewerCopy"), isError: true); + return; + } + var item = new WorkspaceProjectItem(copy, null); + Shell.Notify(Loc.L("Editor.Workspace.OpenFailed"), Loc.L("Errors.Workspace.Damaged"), Loc.L("Editor.Project.RemoveCopy"), + Loc.L("Tooltips.Editor.Workspace.State.DamagedCopy"), () => _ = RemoveProjectCopyAsync(item), isError: true); + } + /// /// "Open in workspace": the projects of the sequence's home, the media, what their copy writes and the room the /// workspace's drive has; null when closed without a choice. diff --git a/src/Chronos.App/Workspace/ProjectMenuViewModel.cs b/src/Chronos.App/Workspace/ProjectMenuViewModel.cs index d98edfb8..73f8bcbb 100644 --- a/src/Chronos.App/Workspace/ProjectMenuViewModel.cs +++ b/src/Chronos.App/Workspace/ProjectMenuViewModel.cs @@ -138,9 +138,11 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel public string MediaUpdateText => Loc.L(IsUpdatingMedia ? "Editor.Workspace.Updating" : "Editor.Workspace.MediaChanged"); - public bool CanSaveVersion => !_session.IsReadOnly && _status is not { Conflict: not null } and not { MediaRemoved: true }; + /// A version can be saved: the settings are this Chronos's, no conflict waits, the media are here and the library still has the project. + public bool CanSaveVersion => !_session.IsReadOnly && _status is not { Conflict: not null } and not { MediaRemoved: true } and not { State: WorkspaceState.Gone }; public string SaveVersionToolTip => _session.IsReadOnly ? Loc.L("Errors.Workspace.ReadOnly") + : _status?.State == WorkspaceState.Gone ? Loc.L("Errors.Workspace.DeletedAtHome") : _status?.Conflict is not null ? Loc.L("Errors.Workspace.Conflict") : Loc.L("Tooltips.Editor.Project.SaveVersion"); @@ -221,7 +223,9 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel _ui.Notify(Loc.L("Editor.Workspace.Saved", Formatting.Count(result.Version.Number)), Name); } if (result.SyncError is { } error) _ui.Notify(Loc.L("Editor.Workspace.NotSent"), WorkspaceText.Failure(error), isError: error is not HomeUnavailableException); - if (result.Status.Conflict is { } conflict) AskConflict(conflict); + // Deleted in the library: said once, and no conflict is asked (nothing can be merged with it); the version stays here. + if (result.Status.State == WorkspaceState.Gone) NotifyGone(); + else if (result.Status.Conflict is { } conflict) AskConflict(conflict); } /// @@ -239,7 +243,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel if (_disposed) return; Apply(result.Status); await TakeAsync(result); - if (result.Status.State == WorkspaceState.Gone) _ui.Notify(Loc.L("Editor.Workspace.State.Gone"), Loc.L("Errors.Workspace.DeletedAtHome")); + if (result.Status.State == WorkspaceState.Gone) NotifyGone(); else if (result.Status.Conflict is { } conflict) AskConflict(conflict, background: quiet); else if (!quiet) _ui.Notify(Loc.L(result.Status.State == WorkspaceState.InSync ? "Editor.Workspace.InSync" : "Editor.Workspace.Synced"), Name); } @@ -260,6 +264,8 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel /// Settles the conflict listed (else the one recorded) as chosen, then brings the settled /// working state into the editor: the library's values taken as one undo step (the toast's Undo, Ctrl+Z), what Save /// both made offered by its toast. When what differs changed since it was shown, nothing is settled and it is asked again. + /// A project deleted in the library meanwhile is said so once, nothing asked again: its work stays here (the copy Save + /// both made holding it too, offered by its toast). /// public async Task ResolveAsync(ConflictChoice choice, WorkspaceConflict? shown = null) { @@ -267,6 +273,12 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel var result = await _host.ResolveAsync(ProjectId, choice, shown: shown); if (_disposed) return; Apply(result.Status); + if (result.Status.State == WorkspaceState.Gone) + { + NotifyGone(); + NotifySavedAs(result); + return; + } if (result.Status.Conflict is { } again) { await TakeAsync(result); @@ -283,14 +295,21 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel { await TakeAsync(result, force: true); } - if (result.SavedAs is { } copy) - { - var sequenceId = SequenceId; - _ui.Notify(Loc.L("Editor.Workspace.SavedAs", copy.Name), Name, Loc.L("Editor.Workspace.OpenCopy"), Loc.L("Tooltips.Editor.Workspace.OpenCopy", copy.Name), - () => _ = _ui.OpenProjectAsync(sequenceId, copy.Id)); - } + NotifySavedAs(result); } + /// The project Save both made, offered by its toast. + private void NotifySavedAs(WorkspaceSyncResult result) + { + if (result.SavedAs is not { } copy) return; + var sequenceId = SequenceId; + _ui.Notify(Loc.L("Editor.Workspace.SavedAs", copy.Name), Name, Loc.L("Editor.Workspace.OpenCopy"), Loc.L("Tooltips.Editor.Workspace.OpenCopy", copy.Name), + () => _ = _ui.OpenProjectAsync(sequenceId, copy.Id)); + } + + /// The library no longer has the project: nothing more is sent, its work stays here (Remove local copy keeps it aside). + private void NotifyGone() => _ui.Notify(Loc.L("Editor.Workspace.State.Gone"), Loc.L("Errors.Workspace.DeletedAtHome")); + /// /// Restores as the project, as one undo step (uncommitted changes are saved as a version /// first, so nothing is lost); the toast's Undo takes it back while it is the last change. @@ -485,6 +504,8 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel var result = await _host.SyncAsync(ProjectId); Apply(result.Status); await TakeAsync(result); + // Nothing can be sent to a project the library no longer has: only Discard takes the copy, its work kept aside. + if (result.Status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome")); if (result.Status.Conflict is { } conflict) { AskConflict(conflict); @@ -619,7 +640,15 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel var gone = last.State == WorkspaceState.Gone; // A base that moved since (a sync) leaves how far the library is ahead unknown until it is asked again. var behind = last.Base?.VersionId == local.Base?.VersionId ? last.Behind : 0; - var status = local with { Behind = behind, Offline = last.Offline, HomeHead = last.HomeHead, MediaOutdated = last.MediaOutdated }; + // A project the library no longer has holds no conflict to answer (the one recorded stays for the record). + var status = local with + { + Behind = behind, + Offline = last.Offline, + HomeHead = last.HomeHead, + MediaOutdated = last.MediaOutdated, + Conflict = gone ? null : local.Conflict, + }; var state = gone ? WorkspaceState.Gone : status.MediaRemoved ? WorkspaceState.MediaRemoved : status.Damaged > 0 ? WorkspaceState.Damaged diff --git a/src/Chronos.App/Workspace/WorkspaceHost.cs b/src/Chronos.App/Workspace/WorkspaceHost.cs index 7685c6d8..9015edce 100644 --- a/src/Chronos.App/Workspace/WorkspaceHost.cs +++ b/src/Chronos.App/Workspace/WorkspaceHost.cs @@ -211,7 +211,18 @@ public sealed class WorkspaceHost { if (!Directory.Exists(Root) && await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) return []; var entries = new List(); - foreach (var project in Store.List()) entries.Add(await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false)); + foreach (var project in Store.List()) + { + try + { + entries.Add(await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false)); + } + catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException) + { + // One copy that cannot be listed never hides the others. + Log.Warning("workspace", $"The project in {project.Folder} could not be listed", ex); + } + } return (IReadOnlyList)entries; }, cancellationToken); @@ -377,6 +388,8 @@ public sealed class WorkspaceHost State = local.State is WorkspaceState.MediaRemoved or WorkspaceState.Damaged or WorkspaceState.Conflict && !gone ? local.State : gone ? WorkspaceState.Gone : WorkspaceState.Offline, + // Gone holds no conflict to answer; the one recorded stays in the copy. + Conflict = gone ? null : local.Conflict, }; } }, cancellationToken); @@ -468,6 +481,8 @@ public sealed class WorkspaceHost Log.Info("workspace", $"Conflict of project {projectId} not settled ({choice}): what differs changed since it was shown"); return resolved; } + // Deleted in the library: nothing more to send (a Save both's copy holds the versions already). + if (resolved.Status.State == WorkspaceState.Gone) return resolved; Log.Info("workspace", $"Conflict of project {projectId} settled: {choice}{(resolved.SavedAs is { } copy ? $", saved as '{copy.Name}'" : string.Empty)}"); var pushed = await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false); return new WorkspaceSyncResult(pushed.Status, [.. resolved.Pushed, .. pushed.Pushed], [.. resolved.Pulled, .. pushed.Pulled], resolved.SavedAs) @@ -575,6 +590,7 @@ public sealed class WorkspaceHost if (local.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict")); if (!local.ReadOnly) await Sync.CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false); var status = (await SendAsync(projectId, home, cancellationToken).ConfigureAwait(false)).Status; + if (status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome")); if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict")); if (status.Ahead > 0 || (status.Modified && !status.ReadOnly)) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent")); await ArchiveProjects(project).DeleteAsync(projectId, cancellationToken).ConfigureAwait(false); @@ -586,9 +602,10 @@ public sealed class WorkspaceHost } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or LeaseUnavailableException) { - // The home's delete stands (its trash holds every version); the copy, all of it sent, waits for Remove local copy. + // The home's delete stands (its trash holds every version); the copy, all of it sent and put back whole, waits + // for Remove local copy. One whose working state could not go back is no longer listed: nothing waits for it. Log.Warning("workspace", $"Project {projectId} was deleted at its home, but its local copy stays", ex); - return (workspace.Home.SequenceId, false); + return (workspace.Home.SequenceId, !project.Exists); } }, cancellationToken); Forget(sequenceId, projectId); @@ -605,6 +622,7 @@ public sealed class WorkspaceHost var local = await Task.Run(() => Sync.StatusAsync(projectId, null, cancellationToken), cancellationToken).ConfigureAwait(false); if (local is { Conflict: null, ReadOnly: false, MediaRemoved: false }) await CommitAsync(projectId, cancellationToken).ConfigureAwait(false); var status = (await SyncAsync(projectId, cancellationToken).ConfigureAwait(false)).Status; + if (status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome")); if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict")); if (status.Ahead > 0 || (status.Modified && !status.ReadOnly)) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent")); } @@ -626,7 +644,9 @@ public sealed class WorkspaceHost var name = project.ReadBundle().Workspace!.Name; var status = await StatusAsync(projectId, cancellationToken: cancellationToken).ConfigureAwait(false); var (files, bytes) = Measure(project.Folder); - return new WorkspaceRemovalPlan(projectId, name, files, bytes, status.Ahead + status.Damaged, status.Modified, status.Conflict is not null, status.Offline, + // A conflict recorded counts as work not at the home, also once the library no longer has the project (Gone asks none). + var conflict = status.Conflict is not null || project.ReadSync().Conflict is not null; + return new WorkspaceRemovalPlan(projectId, name, files, bytes, status.Ahead + status.Damaged, status.Modified, conflict, status.Offline, status.State == WorkspaceState.Gone); }, cancellationToken); @@ -751,8 +771,10 @@ public sealed class WorkspaceHost /// The project's folder taken out of the workspace under its lease: every file and folder in it but the media and the /// lease (the working state, the versions, the sync state, the exports, and whatever else a Chronos keeps there) moved /// to .trash/<id>-<time> as it is (kept: nothing a user made is erased), the media deleted; the emptied - /// folder goes once the lease is released, only when nothing else came into it meanwhile. + /// folder goes once the lease is released, only when nothing else came into it meanwhile. A file that cannot be moved + /// (held open) puts back what was moved, so the copy stays whole and listed, and the failure is thrown. /// + /// A file of the copy could not be moved; the copy is as it was. private async Task RemoveFolderAsync(WorkspaceProject project, CancellationToken cancellationToken) { // A copy of its media still under way would write them again behind the removal. @@ -765,16 +787,53 @@ public sealed class WorkspaceHost using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false)) { Directory.CreateDirectory(aside); - // The working state first: without it the folder is no project any more, whatever happens after. - File.Move(project.BundlePath, Path.Combine(aside, WorkspaceProject.BundleFile)); - foreach (var entry in Directory.EnumerateFileSystemEntries(project.Folder).ToList()) + var moved = new List<(string From, string To)>(); + try { - var name = Path.GetFileName(entry); - if (IsLease(name) || string.Equals(name, WorkspaceProject.MediaFolder, StringComparison.OrdinalIgnoreCase)) continue; - if (Directory.Exists(entry)) Directory.Move(entry, Path.Combine(aside, name)); - else File.Move(entry, Path.Combine(aside, name)); + // The working state first: without it the folder is no project any more, whatever happens after. + Move(project.BundlePath, Path.Combine(aside, WorkspaceProject.BundleFile)); + foreach (var entry in Directory.EnumerateFileSystemEntries(project.Folder).ToList()) + { + var name = Path.GetFileName(entry); + if (IsLease(name) || string.Equals(name, WorkspaceProject.MediaFolder, StringComparison.OrdinalIgnoreCase)) continue; + Move(entry, Path.Combine(aside, name)); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // A file held open (another program's): everything moved goes back, the working state last, so the copy stays + // whole and listed, and Remove local copy can be asked again. + Log.Warning("workspace", $"The copy in {project.Folder} could not be moved aside: what was moved goes back", ex); + for (var i = moved.Count - 1; i >= 0; i--) + { + try + { + if (Directory.Exists(moved[i].To)) Directory.Move(moved[i].To, moved[i].From); + else File.Move(moved[i].To, moved[i].From); + } + catch (Exception back) when (back is IOException or UnauthorizedAccessException) + { + Log.Error("workspace", $"{moved[i].To} could not go back to {moved[i].From}: it is kept there", back); + } + } + try + { + if (!Directory.EnumerateFileSystemEntries(aside).Any()) Directory.Delete(aside); + } + catch (Exception left) when (left is IOException or UnauthorizedAccessException) + { + Log.Debug("workspace", $"{aside} stays: {left.Message}"); + } + throw; } if (Directory.Exists(project.MediaDirectory)) Directory.Delete(project.MediaDirectory, recursive: true); + + void Move(string from, string to) + { + if (Directory.Exists(from)) Directory.Move(from, to); + else File.Move(from, to); + moved.Add((from, to)); + } } try { @@ -885,8 +944,9 @@ public sealed class WorkspaceHost title ??= (await db.Sequences.GetAsync(known.SequenceId, cancellationToken).ConfigureAwait(false))?.DisplayTitle; } } - catch (DatabaseException dbx) + catch (Exception dbx) when (dbx is not OperationCanceledException and not OutOfMemoryException) { + // The index closing (the program ending), or any other failure: the copy is listed by what is known. Log.Info("workspace", $"The index could not name the project in {project.Folder}: {dbx.Message}"); } } diff --git a/src/Chronos.Data/Jobs/JobEngine.cs b/src/Chronos.Data/Jobs/JobEngine.cs index e84eac82..67a16749 100644 --- a/src/Chronos.Data/Jobs/JobEngine.cs +++ b/src/Chronos.Data/Jobs/JobEngine.cs @@ -128,8 +128,27 @@ public sealed class JobEngine : IAsyncDisposable /// public bool CanRun(JobKind kind) => _handlers.ContainsKey(kind) && (Options.Kinds is null || Options.Kinds.Contains(kind)); - /// Cancels a queued or running job; a running handler observes its token. - public Task CancelAsync(Guid id, CancellationToken cancellationToken = default) => TransitionAsync(id, JobState.Cancelled, cancellationToken); + /// + /// Cancels a queued or running job; a running handler observes its token. A paused or failed one, which no handler runs, + /// leaves what it wrote to its handler to clear (). + /// + public async Task CancelAsync(Guid id, CancellationToken cancellationToken = default) + { + var before = await _db.Jobs.GetAsync(id, cancellationToken).ConfigureAwait(false); + await TransitionAsync(id, JobState.Cancelled, cancellationToken).ConfigureAwait(false); + // Neither claimable nor running here: no handler cleans up after it itself. + if (before is not { State: JobState.Paused or JobState.Failed } || _running.ContainsKey(id) + || !_handlers.TryGetValue(before.Kind, out var handler) || handler is not ICancelledJobHandler cancelled) + return; + try + { + await cancelled.CancelledAsync(before with { State = JobState.Cancelled }, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (!(ex is OperationCanceledException && cancellationToken.IsCancellationRequested)) + { + Log.Warning("jobs", $"{before.Kind} job {id} was cancelled, but what it left could not be cleared", ex); + } + } /// Pauses a job: a running one stops at its next check and keeps its checkpoint, and the next queued job starts. public Task PauseAsync(Guid id, CancellationToken cancellationToken = default) => TransitionAsync(id, JobState.Paused, cancellationToken); diff --git a/src/Chronos.Data/Jobs/JobHandler.cs b/src/Chronos.Data/Jobs/JobHandler.cs index 37bc5302..4341479f 100644 --- a/src/Chronos.Data/Jobs/JobHandler.cs +++ b/src/Chronos.Data/Jobs/JobHandler.cs @@ -23,6 +23,20 @@ public interface ISelectiveJobHandler : IJobHandler ValueTask AcceptsAsync(Job job, CancellationToken cancellationToken); } +/// +/// A handler whose jobs leave something behind that a cancel removes (a first copy's partial files). A running job sees the +/// cancel through its token and cleans up itself; for a job no handler runs when it is cancelled (paused, failed), the +/// engine tells the handler instead (). +/// +public interface ICancelledJobHandler : IJobHandler +{ + /// + /// , of this handler's kind and run by no handler now, was cancelled. Returns once the clean-up is + /// under way (it may wait for what it removes, so it should not keep the caller); a failure is the handler's to log. + /// + Task CancelledAsync(Job job, CancellationToken cancellationToken); +} + /// A component that brings several handlers (the archive engine: scan, rebuild, verify, import, images, maintenance). public interface IJobHandlerProvider { diff --git a/src/Chronos.Data/Projects/IProjectHome.cs b/src/Chronos.Data/Projects/IProjectHome.cs index 14d2732b..d66d0846 100644 --- a/src/Chronos.Data/Projects/IProjectHome.cs +++ b/src/Chronos.Data/Projects/IProjectHome.cs @@ -148,14 +148,15 @@ public sealed class ArchiveProjectHome(ChronosDatabase db, ProjectService projec /// /// The sequence's frames version (frames added, removed, converted or renamed), with how many of its photos the index has - /// hashed (a Verify hashes them without another frames version) and how many removals it keeps (a conversion's links). + /// hashed and a checksum of those hashes (a Verify hashes them, or finds other bytes, without another frames version) + /// and how many removals it keeps (a conversion's links). /// public async Task FramesStampAsync(CancellationToken cancellationToken) { var row = await db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) ?? throw new ProjectException(ProjectError.SequenceNotFound, $"Sequence {sequenceId} is not in the index."); - var (hashed, removals) = await db.Frames.CountNamedAsync(sequenceId, cancellationToken).ConfigureAwait(false); - return string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{row.FramesVersion}:{hashed}:{removals}"); + var (hashed, checksum, removals) = await db.Frames.CountNamedAsync(sequenceId, cancellationToken).ConfigureAwait(false); + return string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{row.FramesVersion}:{hashed}:{checksum}:{removals}"); } /// diff --git a/src/Chronos.Data/Repositories/FrameRepository.cs b/src/Chronos.Data/Repositories/FrameRepository.cs index d069bad6..359aa487 100644 --- a/src/Chronos.Data/Repositories/FrameRepository.cs +++ b/src/Chronos.Data/Repositories/FrameRepository.cs @@ -239,16 +239,23 @@ public sealed class FrameRepository }, cancellationToken); /// - /// How many photos of a sequence the index has hashed, and how many removals (tombstones) it keeps for it: with the - /// frames version, what decides how project positions name its photos (). + /// How many photos of a sequence the index has hashed, a checksum of those hashes (it moves when one is replaced in + /// place, as a Verify that finds other bytes does), and how many removals (tombstones) it keeps for it: with the frames + /// version, what decides how project positions name its photos (). + /// The checksum sums the first five hex digits of each hash weighted by the frame's place, in SQL both dialects read. /// - public Task<(long Hashed, long Removals)> CountNamedAsync(Guid sequenceId, CancellationToken cancellationToken = default) => + public Task<(long Hashed, long Checksum, long Removals)> CountNamedAsync(Guid sequenceId, CancellationToken cancellationToken = default) => _db.RunAsync(async session => { + var find = _db.Sql.IsPostgres ? "strpos" : "instr"; + string Digit(int at) => $"{find}('0123456789abcdef', lower(substr(sha256, {at}, 1)))"; var row = await session.QuerySingleAsync( - "SELECT (SELECT count(sha256) FROM frames WHERE sequence_id = $1), (SELECT count(*) FROM frame_removals WHERE sequence_id = $1)", + "SELECT (SELECT count(sha256) FROM frames WHERE sequence_id = $1), " + + $"(SELECT CAST(COALESCE(SUM(CAST(idx % 1000 + 1 AS bigint) * ({Digit(1)} * 65536 + {Digit(2)} * 4096 + {Digit(3)} * 256 + {Digit(4)} * 16 + {Digit(5)})), 0) AS bigint) " + + "FROM frames WHERE sequence_id = $1), " + + "(SELECT count(*) FROM frame_removals WHERE sequence_id = $1)", [sequenceId], cancellationToken).ConfigureAwait(false); - return (row.GetInt64(0), row.GetInt64(1)); + return (row.GetInt64(0), row.GetInt64(1), row.GetInt64(2)); }, cancellationToken); /// Number of frames of a sequence. diff --git a/src/Chronos.Data/Workspaces/WorkspaceCopyJobHandler.cs b/src/Chronos.Data/Workspaces/WorkspaceCopyJobHandler.cs index f8d55662..7cfc389a 100644 --- a/src/Chronos.Data/Workspaces/WorkspaceCopyJobHandler.cs +++ b/src/Chronos.Data/Workspaces/WorkspaceCopyJobHandler.cs @@ -66,10 +66,11 @@ public static class WorkspaceJobs /// job stops saying how much is missing (the workspace shares this PC's drive with the index and the logs). /// Checkpoint: copy:<frame>:<frames version>:<folder>; a run resumed on other frames or in another folder /// checks every file again, and a pass started again stores that before it reads anything. A first copy the user cancels -/// removes the media it wrote itself, once it has stopped writing and under the project's lease (). +/// removes the media it wrote itself, once it has stopped writing and under the project's lease (); +/// one cancelled while paused or failed, which no handler runs, has them removed the same way (). /// Originals come in phase 5c: asked for, the job fails saying so. /// -internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService archives) : IJobHandler +internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService archives) : ICancelledJobHandler { private const int PageSize = 1000; private const int Passes = 3; @@ -119,6 +120,40 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService } } + /// + /// A copy cancelled while no handler ran it (paused, failed): what a first copy wrote goes as after a cancel while it ran, + /// under the project's lease, in the background (the lease may be held for a while: the cancel does not wait for it). + /// A workspace folder or a project no longer there has nothing to clear, and nothing is made for it. + /// + public Task CancelledAsync(Job job, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(job); + WorkspaceCopyParameters parameters; + try + { + parameters = Parameters(job); + } + catch (InvalidDataException) + { + 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; + _ = Task.Run(async () => + { + try + { + if (new WorkspaceStore(parameters.WorkspaceRoot).Find(parameters.ProjectId) is { } project) await RemovePartialMediaAsync(job, project).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + // Nobody waits for this task: whatever stopped it is logged; the next copy checks every file it finds. + Log.Warning("workspace", $"The media of cancelled copy {job.Id} could not be cleared", ex); + } + }, CancellationToken.None); + return Task.CompletedTask; + } + /// /// A first copy of the project's media the user cancelled (the job reads ), once it has /// stopped writing: the photos it wrote (copies the home can make again) are removed under the project's lease, so the @@ -131,6 +166,8 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService try { if (await db.Jobs.GetAsync(job.Id, CancellationToken.None).ConfigureAwait(false) is not { State: JobState.Cancelled }) return; + // Nothing half written (or the copy removed meanwhile): the lease, which makes the folder, is not taken. + if (File.Exists(project.MediaIndexPath) || !Directory.Exists(project.MediaDirectory)) return; using (await project.LockAsync(LockWait, CancellationToken.None).ConfigureAwait(false)) { if (File.Exists(project.MediaIndexPath) || !Directory.Exists(project.MediaDirectory)) return; @@ -441,15 +478,26 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService /// /// The bytes the copy still writes from each frame on (index i: frames i to the last; one more entry, 0): - /// nothing for a frame the workspace holds a file of already (kept, or replaced by one of about its size), the archive's + /// nothing for a frame the workspace holds a file of already (kept, or replaced by one of about its size; under its own + /// name or the one other bytes of it take, ), the archive's /// proxy's size where it has one, else an estimate at the proxy size the copy makes (). /// private static long[] Remaining(WorkspaceProject project, SequencePaths folder, List frames, ProxyPolicy policy) => - Remaining(Directory.Exists(project.ProxiesDirectory) - ? Directory.EnumerateFiles(project.ProxiesDirectory).Select(Path.GetFileName).ToHashSet(StringComparer.OrdinalIgnoreCase) - : [], folder, frames, policy); + Remaining(Directory.Exists(project.ProxiesDirectory) ? HeldFrames(Directory.EnumerateFiles(project.ProxiesDirectory, "*.jpg")) : [], folder, frames, policy); - private static long[] Remaining(HashSet held, SequencePaths folder, List frames, ProxyPolicy policy) + /// The frames the files at are proxies of: "<frame id>.jpg" and "<frame id>-<sha16>.jpg". + internal static HashSet HeldFrames(IEnumerable paths) + { + var held = new HashSet(); + foreach (var path in paths) + { + var name = Path.GetFileNameWithoutExtension(path); + if (name.Length >= 32 && (name.Length == 32 || name[32] == '-') && Guid.TryParseExact(name[..32], "N", out var id)) held.Add(id); + } + return held; + } + + private static long[] Remaining(HashSet held, SequencePaths folder, List frames, ProxyPolicy policy) { var proxies = Directory.Exists(folder.Proxies) ? new DirectoryInfo(folder.Proxies).EnumerateFiles().ToDictionary(f => f.Name, f => f.Length, StringComparer.OrdinalIgnoreCase) @@ -458,7 +506,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService for (var i = frames.Count - 1; i >= 0; i--) { var frame = frames[i]; - var bytes = held.Contains(ProxyCache.FileName(frame.Id)) ? 0 + var bytes = held.Contains(frame.Id) ? 0 : proxies.TryGetValue(ArchiveLayout.ProxyFileName(frame.Index), out var length) ? length : (frame.Flags & FrameFlags.Missing) != 0 ? 0 : Estimate(frame, policy); diff --git a/src/Chronos.Data/Workspaces/WorkspaceStore.cs b/src/Chronos.Data/Workspaces/WorkspaceStore.cs index 6bb7e7ae..77fcac28 100644 --- a/src/Chronos.Data/Workspaces/WorkspaceStore.cs +++ b/src/Chronos.Data/Workspaces/WorkspaceStore.cs @@ -288,6 +288,13 @@ public sealed class WorkspaceProject /// public const string ReplacedFolder = ".replaced"; + /// + /// Beside in versions/: when this Chronos first set a file aside there or pruned it + /// (an ISO-8601 time). A file dated before it was set aside by an earlier build, which kept the time it was written: it + /// counts as set aside then, at the earliest (). + /// + public const string ReplacedSinceFile = ".replaced.since"; + private const string LeaseName = ".lock"; internal WorkspaceProject(WorkspaceStore store, Guid projectId) @@ -443,6 +450,7 @@ public sealed class WorkspaceProject if (!File.Exists(path)) return; var aside = Path.Combine(VersionsDirectory, ReplacedFolder); Directory.CreateDirectory(aside); + ReplacedSince(DateTime.UtcNow); var target = Path.Combine(aside, Path.GetFileName(path)); if (File.Exists(target)) target += "." + DateTime.UtcNow.Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture); for (var attempt = 1; ; attempt++) @@ -469,6 +477,7 @@ public sealed class WorkspaceProject { ArgumentNullException.ThrowIfNull(version); ProjectSidecars.WriteVersion(Path.Combine(VersionsDirectory, ReplacedFolder, Path.GetFileName(VersionPath(version))), version); + ReplacedSince(DateTime.UtcNow); } /// Files keeps in versions/.replaced whatever their age. @@ -481,19 +490,24 @@ public sealed class WorkspaceProject /// Removes from versions/.replaced the files set aside more than ago and those past /// the newest , never one of a version in (a journal's). Every /// file there is a copy of what the chain or the home holds, or what a take of the server's values replaced (its undo): - /// called only after a sync that ended well. How many went. + /// called only after a sync that ended well. A file is set aside when this Chronos dated it (it touches what it sets + /// aside), and no earlier than this Chronos first knew the folder (): one an earlier build + /// set aside keeps the time its version was written, which says nothing of when it went aside. How many went. /// internal int PruneReplaced(IReadOnlySet referenced, DateTime nowUtc) { ArgumentNullException.ThrowIfNull(referenced); var aside = Path.Combine(VersionsDirectory, ReplacedFolder); if (!Directory.Exists(aside)) return 0; - var files = new DirectoryInfo(aside).EnumerateFiles().OrderByDescending(f => f.LastWriteTimeUtc).ThenByDescending(f => f.Name, StringComparer.Ordinal).ToList(); + var since = ReplacedSince(nowUtc); + var files = new DirectoryInfo(aside).EnumerateFiles() + .Select(f => (File: f, Aside: f.LastWriteTimeUtc > since ? f.LastWriteTimeUtc : since)) + .OrderByDescending(f => f.Aside).ThenByDescending(f => f.File.LastWriteTimeUtc).ThenByDescending(f => f.File.Name, StringComparer.Ordinal).ToList(); var removed = 0; for (var i = 0; i < files.Count; i++) { - var file = files[i]; - if (i < ReplacedKept && nowUtc - file.LastWriteTimeUtc <= ReplacedMaxAge) continue; + var (file, set) = files[i]; + if (i < ReplacedKept && nowUtc - set <= ReplacedMaxAge) continue; if (VersionIdOf(file.Name) is { } id && referenced.Contains(id)) continue; try { @@ -515,6 +529,31 @@ public sealed class WorkspaceProject } } + /// + /// When this Chronos first knew versions/.replaced (): read, else written as + /// (also over a file that cannot be read). One that cannot be written counts as now: nothing + /// set aside by an earlier build goes by its age then. + /// + private DateTime ReplacedSince(DateTime nowUtc) + { + var path = Path.Combine(VersionsDirectory, ReplacedSinceFile); + try + { + if (File.Exists(path) + && DateTime.TryParse(File.ReadAllText(path).Trim(), System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind, + out var known) + && known.Kind == DateTimeKind.Utc && known <= nowUtc) + return known; + Directory.CreateDirectory(VersionsDirectory); + AtomicFile.WriteAllText(path, nowUtc.ToString("O", System.Globalization.CultureInfo.InvariantCulture)); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Debug("workspace", $"{path} could not be kept: {ex.Message}"); + } + return nowUtc; + } + private static void TryTouch(string path) { try diff --git a/src/Chronos.Data/Workspaces/WorkspaceSync.cs b/src/Chronos.Data/Workspaces/WorkspaceSync.cs index a7835b61..c03697df 100644 --- a/src/Chronos.Data/Workspaces/WorkspaceSync.cs +++ b/src/Chronos.Data/Workspaces/WorkspaceSync.cs @@ -273,6 +273,8 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName) { var pushed = new List(); var pulled = new List(); + // Ended well: every local version sent, no conflict met, no attempt left over. + var sent = false; try { await SettleAsync(project, home, cancellationToken).ConfigureAwait(false); @@ -307,7 +309,11 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName) } break; } - if (!diverged) break; + if (!diverged) + { + sent = true; + break; + } var (_, conflict, taken) = await ReplayAsync(project, bundle, home, null, cancellationToken).ConfigureAwait(false); pulled.AddRange(taken); if (conflict is not null) break; @@ -319,7 +325,8 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName) if (!await GoneAsync(project, home, ex, cancellationToken).ConfigureAwait(false)) throw; return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), pushed, pulled); } - PruneReplaced(project); + // A push stopped at a conflict, or by a home that kept moving, leaves versions/.replaced as it is. + if (sent && project.ReadSync().Conflict is null) PruneReplaced(project); return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), pushed, pulled); } } @@ -346,6 +353,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName) EnsureChained(project, bundle, Unpushed(project, bundle)); if (project.ReadSync().Conflict is not null) { + await EnsureAtHomeAsync(project, home, cancellationToken).ConfigureAwait(false); (_, var conflict, pulled) = await ReplayAsync(project, bundle, home, null, cancellationToken).ConfigureAwait(false); if (conflict is null) project.WriteSync(project.ReadSync() with { Conflict = null }); } @@ -381,7 +389,8 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName) /// saves the working state as a version, sends this workspace's versions to a new /// project at the home (, else this project's name with a number) made from the base, /// and moves this project onto the home's head; a project deleted at the home meanwhile keeps its versions here, the - /// copy holding them too (). + /// copy holding them too (). Keep mine and Take the server's on a project deleted at the + /// home change nothing here (it reads as Gone): nothing is merged onto the last version it had there. /// /// The home cannot be reached; the conflict stays. public async Task ResolveAsync(Guid projectId, IProjectHome home, ConflictChoice choice, IReadOnlySet? takeServer = null, @@ -400,6 +409,8 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName) EnsureChained(project, bundle, Unpushed(project, bundle)); if (choice == ConflictChoice.SaveBoth) return await SaveBothAsync(project, bundle, home, saveBothName, cancellationToken).ConfigureAwait(false); + // Never merged onto the last version of a project deleted at the home: it reads as Gone, everything here kept. + await EnsureAtHomeAsync(project, home, cancellationToken).ConfigureAwait(false); // Nothing is committed first: a version of the working state would be replayed into one that only repeats the // head, and sent. What the take replaces of the working state is kept aside by the replay instead. IReadOnlySet takeTheirs = choice == ConflictChoice.TakeServer ? AllPaths : takeServer ?? new HashSet(); @@ -563,6 +574,9 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName) } var rebased = new List(locals.Count); ProjectVersion parent = head; + // The last replayed version that carries the merge: its own commit met a setting the conflict listed. + var merged = -1; + var listed = Paths(differences); for (var i = 0; i < locals.Count; i++) { var local = locals[i]; @@ -574,6 +588,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName) Log.Info("workspace", $"Version {local.Number} of project {project.ProjectId} changes nothing once replayed on version {head.Number}: it is not sent"); continue; } + if (listed.Count > 0 && ProjectMerge.Conflicts(basisSettings, mine[i], headSettings).Any(d => listed.Contains(d.Path))) merged = rebased.Count; parent = local with { Id = Guid.CreateVersion7(), @@ -586,7 +601,8 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName) }; rebased.Add(parent); } - if (differences.Count > 0 && rebased.Count > 0) rebased[^1] = rebased[^1] with { Kind = ProjectVersionKind.Merge }; + // Marked on the version that holds the choice made, never on an earlier one a skipped version leaves last. + if (merged >= 0) rebased[merged] = rebased[merged] with { Kind = ProjectVersionKind.Merge }; var placed = ProjectSettings.FromJson(ProjectContent.Place(ProjectContent.Canonical(merge.Merged.ToJson()), photos), allowNewer: true); var moved = WithBase(bundle, head) with { Project = placed, Saved = DateTimeOffset.UtcNow }; await FinishCopyAsync(project, home, chain, cancellationToken).ConfigureAwait(false); @@ -1095,7 +1111,8 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName) /// when it cannot). The home's frames are read again only when its stamp of them moved (). /// Without the lease, a version file that reads as damaged is read again under it before the state says so: another /// operation between two of its writes is no damage; while that one holds the project, it is not reported (that - /// operation stops at it itself). A home that answers it no longer has the project reads as . + /// operation stops at it itself). A home that answers it no longer has the project reads as , + /// with no conflict to answer ( null; the one recorded stays in sync.json). /// private async Task StatusLockedAsync(WorkspaceProject project, IProjectHome? home, CancellationToken cancellationToken, bool leased = true) { @@ -1150,7 +1167,9 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName) : locals.Count > 0 ? WorkspaceState.Ahead : modified ? WorkspaceState.Modified : WorkspaceState.InSync; - return new WorkspaceStatus(state, modified, locals.Count, behind, offline, media is null, bundle.IsReadOnly, conflict, workspace.Base, head) + // A project the home no longer has holds no conflict to answer (nothing can be merged with it): the one recorded stays + // in sync.json, for the record and for a project the home holds again. + return new WorkspaceStatus(state, modified, locals.Count, behind, offline, media is null, bundle.IsReadOnly, gone ? null : conflict, workspace.Base, head) { MediaOutdated = outdated, Damaged = damaged, @@ -1263,6 +1282,14 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName) if (removed > 0) Log.Info("workspace", $"{removed} old file(s) of project {project.ProjectId} left versions/.replaced"); } + /// + /// The home still has the project: asked before a choice or a recorded conflict is replayed, so nothing is merged onto + /// the last version of a project deleted there (whose history the home may still read back). + /// + /// The home no longer has the project or its sequence (). + private static async Task EnsureAtHomeAsync(WorkspaceProject project, IProjectHome home, CancellationToken cancellationToken) => + await home.HeadAsync(project.ProjectId, cancellationToken).ConfigureAwait(false); + /// Whether a sync stopped because the home does not know a project or a version ( tells which). private static bool NotFoundAtHome(ProjectException ex) => ex.Reason is ProjectError.NotFound or ProjectError.SequenceNotFound; diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs index 6fa55e04..069b0529 100644 --- a/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs +++ b/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs @@ -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(() => 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() { diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceMenuTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceMenuTests.cs index a823fc53..2a017ff3 100644 --- a/tests/Chronos.App.Tests/Workspace/WorkspaceMenuTests.cs +++ b/tests/Chronos.App.Tests/Workspace/WorkspaceMenuTests.cs @@ -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, diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceSectionTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceSectionTests.cs index 720063a4..35a5e652 100644 --- a/tests/Chronos.App.Tests/Workspace/WorkspaceSectionTests.cs +++ b/tests/Chronos.App.Tests/Workspace/WorkspaceSectionTests.cs @@ -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(); + shell.PendingToasts.CollectionChanged += (_, e) => toasts.AddRange(e.NewItems?.OfType() ?? []); + 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(); + } + }); + + /// Writes once the project's last background read (its state, after the close) lets go of it. + 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); + } + } + } + /// An archive with one sequence of six synthetic photos, indexed. private async Task SequenceAsync(AppServices services, string root) { diff --git a/tests/Chronos.Data.Tests/Workspaces/WorkspaceSafetyTests.cs b/tests/Chronos.Data.Tests/Workspaces/WorkspaceSafetyTests.cs index 4a7d3d0a..d7274f25 100644 --- a/tests/Chronos.Data.Tests/Workspaces/WorkspaceSafetyTests.cs +++ b/tests/Chronos.Data.Tests/Workspaces/WorkspaceSafetyTests.cs @@ -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"); + } + + /// A file in versions/.replaced set aside days ago, by this Chronos (the folder known since then). + 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(), now)); + Assert.FileExists(old); + var since = Path.Combine(project.VersionsDirectory, WorkspaceProject.ReplacedSinceFile); + Assert.FileExists(since); + Assert.Equal(0, project.PruneReplaced(new HashSet(), now + TimeSpan.FromDays(29))); + Assert.FileExists(old); + Assert.Equal(1, project.PruneReplaced(new HashSet(), 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(), 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)); } }