merge: review2-p5a-fix-workspace into phase 5a fix round 1 integration

# Conflicts:
#	src/Chronos.Data/Workspaces/WorkspaceSync.cs
This commit is contained in:
Alby96 committed 2026-11-03 10:39:19 +01:00
commit 9772c2f934
18 files changed
+958 -93

No files matched your search

+196 -29
View File
@@ -1,5 +1,6 @@
using System.Globalization;
using System.Text.Json;
using Chronos.Core.Diagnostics;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Projects;
@@ -88,6 +89,11 @@ public sealed class WorkspaceSyncException(PushOutcome outcome, string message)
/// moves onto them read-only, any other waits on a conflict of format that only Save both settles
/// (<see cref="WorkspaceConflict.NewerFormat"/>). Every operation holds the project's lease; nothing is ever deleted: a
/// restore or save-both first saves uncommitted changes as a version.
/// Every write sequence survives a cut at any step: the working state's base is the commit point. A push moves the base
/// before its local file reads as sent; a replay journals itself in <c>sync.json</c> (<see cref="WorkspaceReplay"/>), writes
/// the replayed versions, then the base, and only then sets the old ones aside; a save-both journals its copy and the ids
/// it sends under (<see cref="WorkspaceSaveBoth"/>). The next push, pull or resolve finishes or undoes what a cut left
/// (<see cref="SettleAsync"/>).
/// </summary>
public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
{
@@ -104,6 +110,11 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
/// <summary>How long an operation waits for the project's lease (another program working on it).</summary>
public TimeSpan LockWait { get; init; } = TimeSpan.FromSeconds(30);
/// <summary>For tests: called with a step's name between the writes of a sync, where it may throw as a crash would.</summary>
internal Action<string>? Cut { get; init; }
private void Step(string name) => Cut?.Invoke(name);
/// <summary>
/// The project <paramref name="projectId"/> of <paramref name="home"/> brought into the workspace: its folder, the home's
/// head as the base and the working state (positions waiting for the media, which a
@@ -130,30 +141,41 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
?? throw new ProjectException(ProjectError.NotFound, $"The home has no project {projectId}.");
var head = await home.HeadAsync(projectId, cancellationToken).ConfigureAwait(false);
Verify(head);
project.WriteVersion(head, replace: true);
Directory.CreateDirectory(project.ExportsDirectory);
var bundle = new ProjectBundle(sequence.Archive, sequence.Sequence, ProjectSettings.FromJson(head.SettingsJson, allowNewer: true), DateTimeOffset.UtcNow)
{
Workspace = new BundleWorkspace(projectId, listed.Name, listed.IsMain, sequence.Home, Base(head), new BundleMedia(media, 0)),
};
// The working state first: one larger than a project file holds is refused before anything is written
// (ProjectTooLargeException), never left as a file no later open could read. Its base is fetched again if a cut
// comes before the version's own file.
project.WriteBundle(bundle);
project.WriteVersion(head, replace: true);
Directory.CreateDirectory(project.ExportsDirectory);
return project;
}
}
/// <summary>The working state for the editor: its settings placed on the media's frames, and the media's sequence.</summary>
/// <summary>
/// The working state for the editor: its settings placed on the media's frames, and the media's sequence. Both files are
/// read under the project's lease, as one state: a copy committing new media rewrites them in turn.
/// </summary>
/// <exception cref="InvalidOperationException">The project is not in the workspace.</exception>
public Task<WorkspaceSession> OpenAsync(Guid projectId, CancellationToken cancellationToken = default) =>
Task.Run(() =>
/// <exception cref="Core.Archiving.LeaseUnavailableException">Another writer kept the project for longer than <see cref="LockWait"/>.</exception>
public async Task<WorkspaceSession> OpenAsync(Guid projectId, CancellationToken cancellationToken = default)
{
var project = Existing(projectId);
ProjectBundle bundle;
WorkspaceMedia? media;
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
(bundle, media) = await Task.Run(() => (project.ReadBundle(), project.ReadMedia()), cancellationToken).ConfigureAwait(false);
return await Task.Run(() =>
{
var project = Existing(projectId);
var bundle = project.ReadBundle();
var media = project.ReadMedia();
var working = bundle.Project;
if (media is not null && !working.IsNewerFormat)
working = ProjectSettings.FromJson(ProjectContent.Place(working.ToJson(), media.Photos), allowNewer: true);
return new WorkspaceSession(project, bundle, working, media, media is null ? null : SequenceOf(project, bundle, media));
}, cancellationToken);
}, cancellationToken).ConfigureAwait(false);
}
/// <summary>Stores the working state (the editor's settings, positions on the media's frames); no version is made.</summary>
/// <exception cref="InvalidOperationException">The project is read-only (a newer Chronos's settings) or not in the workspace.</exception>
@@ -196,6 +218,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
var project = Existing(projectId);
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
await SettleAsync(project, home, cancellationToken).ConfigureAwait(false);
var pushed = new List<ProjectVersion>();
var pulled = new List<ProjectVersion>();
for (var attempt = 0; attempt < PushAttempts; attempt++)
@@ -210,10 +233,13 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
{
case PushOutcome.Stored or PushOutcome.AlreadyStored when result.Version is { } stored:
Verify(stored);
if (stored.Number != local.Number) project.SetAside(local);
project.WriteVersion(stored, replace: true);
// The base moves first: cut after it, the local file still reads as unsent and the next sync
// adopts it; cut before it, the home answers "already stored" next time. Marked sent first, it
// would leave the chain from the old base and take the versions after it along.
bundle = WithBase(bundle, stored);
project.WriteBundle(bundle);
Step("push.base");
Adopt(project, local, stored);
pushed.Add(stored);
continue;
case PushOutcome.Diverged:
@@ -244,6 +270,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
var project = Existing(projectId);
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
await SettleAsync(project, home, cancellationToken).ConfigureAwait(false);
IReadOnlyList<ProjectVersion> pulled = [];
if (project.ReadSync().Conflict is null)
{
@@ -271,6 +298,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
var project = Existing(projectId);
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
await SettleAsync(project, home, cancellationToken).ConfigureAwait(false);
var bundle = project.ReadBundle();
var sync = project.ReadSync();
if (sync.Conflict is null) return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), [], []);
@@ -332,15 +360,19 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
/// <summary>
/// Pulls the home's versions after the base and replays the local ones and the working state on its head. With
/// <paramref name="takeTheirs"/> null a conflict is recorded and nothing else moves (the versions pulled are kept as
/// files); with a choice the conflicts are settled by it.
/// files; the base only moves onto local commits the home already holds); with a choice the conflicts are settled by it.
/// Written in steps a cut can stop at any point (<see cref="WorkspaceReplay"/>): the journal, the replayed versions, the
/// base with the merged working state (the commit point), then the old versions set aside and the held ones adopted.
/// </summary>
private async Task<(ProjectBundle Bundle, WorkspaceConflict? Conflict, IReadOnlyList<ProjectVersion> Pulled)> ReplayAsync(WorkspaceProject project,
ProjectBundle bundle, IProjectHome home, IReadOnlySet<string>? takeTheirs, CancellationToken cancellationToken)
{
var basis = await BaseVersionAsync(project, bundle, home, cancellationToken).ConfigureAwait(false);
// Read before the home's versions are written over them: a local commit the home stored although its answer was lost
// comes back among them, and the commits after it were made on it.
// A local commit the home stored although its answer was lost comes back among the home's versions, and the commits
// after it were made on it. Its file keeps reading as unsent until the base has moved onto it or past it: written
// over now, it would leave the chain from the base, and the commits after it with it.
var locals = Unpushed(project, bundle);
var unsent = project.Versions().Where(v => v.StoredAt is null).Select(v => v.Id).ToHashSet();
var theirs = new List<ProjectVersion>();
for (var after = basis?.Number ?? 0; ;)
{
@@ -348,13 +380,14 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
foreach (var version in page)
{
Verify(version);
project.WriteVersion(version, replace: true);
if (!unsent.Contains(version.Id)) project.WriteVersion(version, replace: true);
}
theirs.AddRange(page);
if (page.Count < PullPage) break;
after = page[^1].Number;
}
if (theirs.Count == 0) return (bundle, null, theirs);
var held = theirs.Where(v => unsent.Contains(v.Id)).ToList();
var head = theirs[^1];
var atHome = theirs.Select(v => v.Id).ToHashSet();
var ours = locals.TakeWhile(v => atHome.Contains(v.Id)).ToList();
@@ -364,7 +397,14 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
// The media first learn how the home names its photos now (hashed or converted there since the copy).
var media = await MediaNamedAsAtHomeAsync(project, home, cancellationToken).ConfigureAwait(false);
var photos = media?.Photos ?? NoFrames;
if (IsNewer(head) || IsNewer(basis)) return NewerAtHome(project, bundle, media, tipVersion, locals, basis, head, theirs, takeTheirs);
if (IsNewer(head) || IsNewer(basis))
{
var newer = NewerAtHome(project, bundle, media, tipVersion, locals, basis, head, theirs, takeTheirs);
// Moved onto the head: the local files of versions the home held take its copies, as after a replay.
if (newer.Conflict is null && held.Count > 0)
await FinishReplayAsync(project, new WorkspaceReplay(head.Id, [], [], [.. held.Select(v => v.Id)]), held, home, cancellationToken).ConfigureAwait(false);
return newer;
}
// Each side names a photo as the frames held it when it was saved: named as the media hold it now (a conversion or a
// hash since), the same photo merges as one.
var basisSettings = basis is null ? new ProjectSettings() : ProjectMerge.Read(ProjectContent.Rebind(basis.SettingsJson, photos));
@@ -383,15 +423,28 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
if (differences.Count > 0 && takeTheirs is null)
{
var conflict = new WorkspaceConflict(head.Id, head.Number, basis?.Id ?? Guid.Empty, [.. locals.Select(v => v.Id)], differences, DateTimeOffset.UtcNow);
project.WriteSync(project.ReadSync() with { Conflict = conflict });
if (ours.Count > 0)
{
// The conflict is met past local commits the home holds: the base moves onto the last of them (their files
// adopted once it has), so the commits after them stay in the chain and the conflict is settled against it.
var onto = new WorkspaceReplay(basis!.Id, [], [], [.. held.Select(v => v.Id)]);
project.WriteSync(project.ReadSync() with { Replay = onto });
Step("replay.journal");
bundle = WithBase(bundle, basis);
project.WriteBundle(bundle);
Step("replay.base");
await FinishReplayAsync(project, onto, held, home, cancellationToken).ConfigureAwait(false);
}
project.WriteSync(project.ReadSync() with { Conflict = conflict, Replay = null });
return (bundle, conflict, theirs);
}
var parent = head;
var rebased = new List<ProjectVersion>(locals.Count);
ProjectVersion parent = head;
for (var i = 0; i < locals.Count; i++)
{
var local = locals[i];
var portable = ProjectContent.Canonical(replay.Commits[i].ToJson());
var rebased = local with
parent = local with
{
Id = Guid.CreateVersion7(),
ParentId = parent.Id,
@@ -402,13 +455,23 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
SettingsFormat = ProjectContent.FormatOf(portable),
StoredAt = null,
};
project.SetAside(local);
project.WriteVersion(rebased);
parent = rebased;
rebased.Add(parent);
}
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 };
var journal = new WorkspaceReplay(head.Id, [.. locals.Select(v => v.Id)], [.. rebased.Select(v => v.Id)], [.. held.Select(v => v.Id)]);
project.WriteSync(project.ReadSync() with { Replay = journal });
Step("replay.journal");
foreach (var version in rebased)
{
project.WriteVersion(version);
Step("replay.version");
}
// The commit point: before it the old chain hangs from the old base, after it the replayed one from the head.
project.WriteBundle(moved);
Step("replay.base");
await FinishReplayAsync(project, journal, held, home, cancellationToken).ConfigureAwait(false);
project.WriteSync(project.ReadSync() with { Replay = null });
return (moved, null, theirs);
}
@@ -461,38 +524,142 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
return (bundle, conflict, theirs);
}
/// <summary>Both sides kept: this workspace's versions to a new project at the home, this project onto the home's head.</summary>
/// <summary>
/// Finishes a replay whose base moved (<see cref="WorkspaceReplay.OntoBase"/>): each local version the home holds takes
/// its copy (from <paramref name="known"/>, a file of the workspace, else the home), the replaced ones are set aside.
/// </summary>
private static async Task FinishReplayAsync(WorkspaceProject project, WorkspaceReplay replay, IReadOnlyList<ProjectVersion> known, IProjectHome home,
CancellationToken cancellationToken)
{
foreach (var id in replay.Adopted)
{
var locals = project.Versions().Where(v => v.Id == id && v.StoredAt is null).ToList();
if (locals.Count == 0) continue;
if ((known.FirstOrDefault(v => v.Id == id) ?? await StoredCopyAsync(project, id, home, cancellationToken).ConfigureAwait(false)) is not { } stored) continue;
foreach (var local in locals) Adopt(project, local, stored);
}
foreach (var id in replay.Replaced) SetAsideUnsent(project, id);
}
/// <summary>
/// Finishes or undoes what a cut left (see the class remarks), before anything reads the chain: a replay's journal is
/// finished once the base is its target, else its replayed versions are set aside (the old chain still hangs from the
/// base); a save-both whose project moved onto the home's head sets its sent versions aside and clears its conflict; a
/// local file of the version the base names (a push cut after it moved the base) takes the home's copy.
/// </summary>
private static async Task SettleAsync(WorkspaceProject project, IProjectHome home, CancellationToken cancellationToken)
{
var sync = project.ReadSync();
var basis = project.ReadBundle().Workspace!.Base;
if (sync.Replay is { } replay)
{
if (basis?.VersionId == replay.OntoBase) await FinishReplayAsync(project, replay, [], home, cancellationToken).ConfigureAwait(false);
else foreach (var id in replay.Replayed) SetAsideUnsent(project, id);
sync = sync with { Replay = null };
project.WriteSync(sync);
Log.Info("workspace", $"A sync of project {project.ProjectId} cut short was {(basis?.VersionId == replay.OntoBase ? "finished" : "undone")}");
}
if (sync.SaveBoth is { } both && basis?.VersionId != both.FromBase)
{
foreach (var move in both.Moves) SetAsideUnsent(project, move.LocalId);
var settled = sync.Conflict is { } conflict && conflict.BaseVersionId == (both.FromBase ?? Guid.Empty);
sync = sync with { SaveBoth = null, Conflict = settled ? null : sync.Conflict };
project.WriteSync(sync);
Log.Info("workspace", $"A save-both of project {project.ProjectId} cut short was finished");
}
if (basis is not null && project.Versions().Where(v => v.Id == basis.VersionId && v.StoredAt is null).ToList() is { Count: > 0 } lingering
&& await StoredCopyAsync(project, basis.VersionId, home, cancellationToken).ConfigureAwait(false) is { } stored)
{
foreach (var local in lingering) Adopt(project, local, stored);
}
}
/// <summary>The home's copy of version <paramref name="id"/>: a file of the workspace marked sent, else asked from the home (kept as a file); null when the home has none.</summary>
private static async Task<ProjectVersion?> StoredCopyAsync(WorkspaceProject project, Guid id, IProjectHome home, CancellationToken cancellationToken)
{
if (project.Versions().FirstOrDefault(v => v.Id == id && v.StoredAt is not null) is { } file) return file;
if (await home.GetVersionAsync(project.ProjectId, id, cancellationToken).ConfigureAwait(false) is not { StoredAt: not null } fetched) return null;
Verify(fetched);
return fetched;
}
/// <summary>
/// The local file of a version the home holds takes the home's copy (sent, maybe under another number). Called only once
/// the base names the version or one after it: before, the copy would take it out of the chain of unsent versions.
/// </summary>
private static void Adopt(WorkspaceProject project, ProjectVersion local, ProjectVersion stored)
{
project.WriteVersion(stored, replace: true);
if (stored.Number != local.Number) project.SetAside(local);
}
/// <summary>Sets aside the unsent local files of version <paramref name="id"/>.</summary>
private static void SetAsideUnsent(WorkspaceProject project, Guid id)
{
foreach (var version in project.Versions().Where(v => v.Id == id && v.StoredAt is null)) project.SetAside(version);
}
/// <summary>
/// Both sides kept: this workspace's versions to a new project at the home, this project onto the home's head. The copy
/// and the ids its versions are sent under are journaled before the first is sent (<see cref="WorkspaceSaveBoth"/>): a
/// retry after a cut sends to the same copy what it lacks (the home answers "already stored" for the rest), whatever name
/// it is asked for, and the base moving onto the home's head is the commit point.
/// </summary>
private async Task<WorkspaceSyncResult> SaveBothAsync(WorkspaceProject project, ProjectBundle bundle, IProjectHome home, string? name, CancellationToken cancellationToken)
{
var workspace = bundle.Workspace!;
if (!bundle.IsReadOnly) CommitLocked(project, bundle, null, null);
bundle = project.ReadBundle();
var locals = Unpushed(project, bundle);
var basis = await BaseVersionAsync(project, bundle, home, cancellationToken).ConfigureAwait(false);
var sync = project.ReadSync();
var pending = sync.SaveBoth;
SequenceProject? copy = null;
if (pending is not null)
{
copy = (await home.ListAsync(cancellationToken).ConfigureAwait(false)).FirstOrDefault(p => p.Id == pending.CopyId);
// A copy deleted at the home meanwhile: a new one is made.
if (copy is null) pending = null;
}
var pushed = new List<ProjectVersion>();
if (locals.Count > 0)
{
copy = await CreateNamedAsync(home, name, workspace.Name, basis?.Id, cancellationToken).ConfigureAwait(false);
var parent = await home.HeadAsync(copy.Id, cancellationToken).ConfigureAwait(false);
if (pending is null)
{
var basis = await BaseVersionAsync(project, bundle, home, cancellationToken).ConfigureAwait(false);
copy = await CreateNamedAsync(home, name, workspace.Name, basis?.Id, cancellationToken).ConfigureAwait(false);
var first = await home.HeadAsync(copy.Id, cancellationToken).ConfigureAwait(false);
pending = new WorkspaceSaveBoth(copy.Id, first.Id, first.Number, workspace.Base?.VersionId, []);
}
var known = pending.Moves.Select(m => m.LocalId).ToHashSet();
if (locals.Any(l => !known.Contains(l.Id)) || !ReferenceEquals(pending, sync.SaveBoth))
{
pending = pending with { Moves = [.. pending.Moves, .. locals.Where(l => !known.Contains(l.Id)).Select(l => new WorkspaceMove(l.Id, Guid.CreateVersion7()))] };
project.WriteSync(sync with { SaveBoth = pending });
}
Step("saveboth.journal");
var ids = pending.Moves.ToDictionary(m => m.LocalId, m => m.CopyVersionId);
var (parentId, parentNumber) = (pending.CopyBaseId, pending.CopyBaseNumber);
foreach (var local in locals)
{
var moved = local with { Id = Guid.CreateVersion7(), ProjectId = copy.Id, ParentId = parent.Id, Number = parent.Number + 1, StoredAt = null };
var moved = local with { Id = ids[local.Id], ProjectId = copy!.Id, ParentId = parentId, Number = parentNumber + 1, StoredAt = null };
var result = await home.PushAsync(copy.Id, moved, cancellationToken).ConfigureAwait(false);
if (result is not { Outcome: PushOutcome.Stored or PushOutcome.AlreadyStored, Version: { } stored })
throw new WorkspaceSyncException(result.Outcome, $"The home refused version {local.Number} saved as project '{copy.Name}': {result.Outcome}.");
pushed.Add(stored);
parent = stored;
(parentId, parentNumber) = (stored.Id, stored.Number);
Step("saveboth.pushed");
}
}
// This project takes the home's head: the local versions now live in the copy (and their files in versions/.replaced).
var head = await home.HeadAsync(project.ProjectId, cancellationToken).ConfigureAwait(false);
Verify(head);
project.WriteVersion(head, replace: true);
foreach (var local in locals) project.SetAside(local);
var media = project.ReadMedia();
var working = ProjectSettings.FromJson(ProjectContent.Place(head.SettingsJson, media?.Photos ?? NoFrames), allowNewer: true);
project.WriteBundle(WithBase(bundle, head) with { Project = working, Saved = DateTimeOffset.UtcNow });
Step("saveboth.base");
foreach (var local in locals) project.SetAside(local);
foreach (var move in pending?.Moves ?? []) SetAsideUnsent(project, move.LocalId);
project.WriteSync(WorkspaceSyncState.None);
return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), pushed, [head], copy);
}