Merge branch 'review2-p5a-fix2-workspace' into review2-p5a-int2
# Conflicts: # src/Chronos.Data/Workspaces/WorkspaceSync.cs
This commit is contained in:
commit
775deda0f4
18 files changed
+641
-86
No files matched your search
@@ -38,6 +38,13 @@ public enum WorkspaceState
|
||||
/// sent, and the local copy can only be removed, its work kept aside. Told by the desktop, which asks the home.
|
||||
/// </summary>
|
||||
Gone,
|
||||
|
||||
/// <summary>
|
||||
/// A version saved here cannot be read, or no longer follows from the base (<see cref="WorkspaceStatus.Damaged"/>):
|
||||
/// nothing is saved, sent or taken while it is so, which would leave it and the versions after it out of the chain.
|
||||
/// One the home holds takes the home's copy at the next sync.
|
||||
/// </summary>
|
||||
Damaged,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -56,6 +63,9 @@ public sealed record WorkspaceStatus(WorkspaceState State, bool Modified, int Ah
|
||||
/// teaches the media the home's names; false without a home asked.
|
||||
/// </summary>
|
||||
public bool MediaOutdated { get; init; }
|
||||
|
||||
/// <summary>Version files after the base that cannot be read or do not follow from it (<see cref="WorkspaceState.Damaged"/>).</summary>
|
||||
public int Damaged { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>What a push, pull or resolve did: the versions it stored at the home and those it took from there, and where it left the project.</summary>
|
||||
@@ -93,7 +103,10 @@ public sealed record WorkspaceSession(WorkspaceProject Project, ProjectBundle Bu
|
||||
public bool IsReadOnly => Bundle.IsReadOnly;
|
||||
}
|
||||
|
||||
/// <summary>A push the home refused for good (not a divergence: settings damaged on the way, of a newer format, or not this project's).</summary>
|
||||
/// <summary>
|
||||
/// A push the home refused for good (not a divergence: settings damaged on the way, of a newer format, larger than a
|
||||
/// version may be (<see cref="PushOutcome.TooLarge"/>), or not this project's).
|
||||
/// </summary>
|
||||
public sealed class WorkspaceSyncException(PushOutcome outcome, string message) : IOException(message)
|
||||
{
|
||||
public PushOutcome Outcome { get; } = outcome;
|
||||
@@ -118,7 +131,9 @@ public sealed class WorkspaceSyncException(PushOutcome outcome, string message)
|
||||
/// 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"/>).
|
||||
/// (<see cref="SettleAsync"/>). A local version after the base that cannot be read, or does not follow from it, is never
|
||||
/// taken for one that is not there: nothing is saved, sent or taken past it (<see cref="WorkspaceState.Damaged"/>) until it
|
||||
/// reads again or takes the home's copy.
|
||||
/// </summary>
|
||||
public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
{
|
||||
@@ -260,7 +275,9 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
var bundle = project.ReadBundle();
|
||||
if (project.ReadSync().Conflict is not null) break;
|
||||
var diverged = false;
|
||||
foreach (var local in Unpushed(project, bundle))
|
||||
var locals = Unpushed(project, bundle);
|
||||
EnsureChained(project, bundle, locals);
|
||||
foreach (var local in locals)
|
||||
{
|
||||
var result = await home.PushAsync(projectId, local, cancellationToken).ConfigureAwait(false);
|
||||
switch (result.Outcome)
|
||||
@@ -280,7 +297,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
diverged = true;
|
||||
break;
|
||||
default:
|
||||
throw new WorkspaceSyncException(result.Outcome, $"The home refused version {local.Number} of project {projectId}: {result.Outcome}.");
|
||||
throw Refused(result.Outcome, local, $"project {projectId}");
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -309,6 +326,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
await SettleAsync(project, home, cancellationToken).ConfigureAwait(false);
|
||||
IReadOnlyList<ProjectVersion> pulled = [];
|
||||
var bundle = project.ReadBundle();
|
||||
EnsureChained(project, bundle, Unpushed(project, bundle));
|
||||
if (project.ReadSync().Conflict is not null)
|
||||
{
|
||||
(_, var conflict, pulled) = await ReplayAsync(project, bundle, home, null, cancellationToken).ConfigureAwait(false);
|
||||
@@ -329,8 +347,11 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
/// <paramref name="takeServer"/>), <see cref="ConflictChoice.TakeServer"/> takes the server's on the settings listed;
|
||||
/// either way the local versions are replayed on the home's head and wait to be pushed. A choice applies only to the
|
||||
/// conflicts listed: when what differs now is not that (the home moved on, or this side was edited meanwhile), nothing
|
||||
/// is settled, and the conflict found now is recorded and returned to be asked again. Taking the server's first saves
|
||||
/// uncommitted changes as a version, so the values it replaces are kept (its file in <c>versions/.replaced</c>).
|
||||
/// is settled, and the conflict found now is recorded and returned to be asked again; so is one the home holds no
|
||||
/// versions for now (nothing to take them from). Taking the server's first saves uncommitted changes as a version, so
|
||||
/// the values it replaces are kept (its file in <c>versions/.replaced</c>); replayed, that version holds the server's
|
||||
/// values only and is not sent. After a Save both cut short, either choice first sends the rest of this workspace's
|
||||
/// versions to the copy it made (one somebody else pushed to since is left as it is).
|
||||
/// <see cref="ConflictChoice.SaveBoth"/> saves the working state as a version, sends this workspace's versions to a new
|
||||
/// project at the home (<paramref name="saveBothName"/>, else this project's name with a number) made from the base,
|
||||
/// and moves this project onto the home's head.
|
||||
@@ -347,13 +368,15 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
var bundle = project.ReadBundle();
|
||||
var sync = project.ReadSync();
|
||||
if (sync.Conflict is not { } recorded) return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), [], []);
|
||||
EnsureChained(project, bundle, Unpushed(project, bundle));
|
||||
if (choice == ConflictChoice.SaveBoth)
|
||||
return await SaveBothAsync(project, bundle, home, saveBothName, cancellationToken).ConfigureAwait(false);
|
||||
// A conflict of format refuses the choice (nothing is merged with a newer Chronos's settings): nothing is saved first.
|
||||
if (choice == ConflictChoice.TakeServer && !bundle.IsReadOnly && !recorded.NewerFormat) CommitLocked(project, bundle, null, null);
|
||||
var saved = choice == ConflictChoice.TakeServer && !bundle.IsReadOnly && !recorded.NewerFormat ? CommitLocked(project, bundle, null, null) : null;
|
||||
IReadOnlySet<string> takeTheirs = choice == ConflictChoice.TakeServer ? AllPaths : takeServer ?? new HashSet<string>();
|
||||
ProjectSettings? kept = null;
|
||||
var (_, conflict, pulled) = await ReplayAsync(project, bundle, home, takeTheirs, cancellationToken, shown ?? recorded, k => kept = k).ConfigureAwait(false);
|
||||
var (_, conflict, pulled) = await ReplayAsync(project, project.ReadBundle(), home, takeTheirs, cancellationToken, shown ?? recorded, k => kept = k, saved?.Id)
|
||||
.ConfigureAwait(false);
|
||||
if (conflict is null) project.WriteSync(project.ReadSync() with { Conflict = null });
|
||||
return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), [], pulled)
|
||||
{
|
||||
@@ -422,19 +445,23 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
/// files; the base only moves onto local commits the home already holds); with a choice the conflicts are settled by it,
|
||||
/// only when they are those <paramref name="shown"/> lists (others are recorded and asked about first, as without a
|
||||
/// choice). Taking the server's everywhere tells <paramref name="kept"/> the working state as keeping this side's values
|
||||
/// would have left it (placed). 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.
|
||||
/// would have left it (placed); <paramref name="saved"/> names the version taking them saved first, which is not replayed
|
||||
/// when it then holds nothing its parent does not (its file is set aside with the others, for the undo). A conflict
|
||||
/// recorded before stays when the home holds no version after the base (it lost them: nothing to settle it against).
|
||||
/// 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.
|
||||
/// Before the commit point the rest of a Save both cut short goes to its copy (<see cref="FinishCopyAsync"/>).
|
||||
/// </summary>
|
||||
private async Task<(ProjectBundle Bundle, WorkspaceConflict? Conflict, IReadOnlyList<ProjectVersion> Pulled)> ReplayAsync(WorkspaceProject project,
|
||||
ProjectBundle bundle, IProjectHome home, IReadOnlySet<string>? takeTheirs, CancellationToken cancellationToken, WorkspaceConflict? shown = null,
|
||||
Action<ProjectSettings>? kept = null)
|
||||
Action<ProjectSettings>? kept = null, Guid? saved = null)
|
||||
{
|
||||
var basis = await BaseVersionAsync(project, bundle, home, cancellationToken).ConfigureAwait(false);
|
||||
// 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 chain = locals;
|
||||
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; ;)
|
||||
@@ -449,7 +476,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
if (page.Count < PullPage) break;
|
||||
after = page[^1].Number;
|
||||
}
|
||||
if (theirs.Count == 0) return (bundle, null, theirs);
|
||||
if (theirs.Count == 0) return (bundle, StillRecorded(project, bundle), theirs);
|
||||
var held = theirs.Where(v => unsent.Contains(v.Id)).ToList();
|
||||
var head = theirs[^1];
|
||||
var atHome = theirs.Select(v => v.Id).ToHashSet();
|
||||
@@ -461,13 +488,8 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
var media = await MediaNamedAsAtHomeAsync(project, home, cancellationToken).ConfigureAwait(false);
|
||||
var photos = media?.Photos ?? NoFrames;
|
||||
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;
|
||||
}
|
||||
return await NewerAtHomeAsync(project, bundle, home, media, tipVersion, chain, locals, basis, ours.Count > 0, held, head, theirs, takeTheirs,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
// 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));
|
||||
@@ -489,42 +511,36 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
if (differences.Count > 0 && (takeTheirs is null || (shown is not null && !SameDifferences(shown.Differences, differences))))
|
||||
{
|
||||
var conflict = new WorkspaceConflict(head.Id, head.Number, basis?.Id ?? Guid.Empty, [.. locals.Select(v => v.Id)], differences, DateTimeOffset.UtcNow);
|
||||
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);
|
||||
}
|
||||
if (ours.Count > 0) bundle = await MoveOntoHeldAsync(project, bundle, basis!, held, home, cancellationToken).ConfigureAwait(false);
|
||||
project.WriteSync(project.ReadSync() with { Conflict = conflict, Replay = null });
|
||||
return (bundle, conflict, theirs);
|
||||
}
|
||||
var rebased = new List<ProjectVersion>(locals.Count);
|
||||
ProjectVersion parent = head;
|
||||
var previous = headSettings;
|
||||
for (var i = 0; i < locals.Count; i++)
|
||||
{
|
||||
var local = locals[i];
|
||||
// The version taking the server's saved first, replayed onto their values, holds nothing more: not sent (kept aside for the undo).
|
||||
if (local.Id == saved && ProjectMerge.SameValues(replay.Commits[i], previous)) continue;
|
||||
var portable = ProjectContent.Canonical(replay.Commits[i].ToJson());
|
||||
parent = local with
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
ParentId = parent.Id,
|
||||
Number = parent.Number + 1,
|
||||
Kind = i == locals.Count - 1 && differences.Count > 0 ? ProjectVersionKind.Merge : local.Kind,
|
||||
SettingsJson = portable,
|
||||
ContentHash = ProjectContent.Hash(portable),
|
||||
SettingsFormat = ProjectContent.FormatOf(portable),
|
||||
StoredAt = null,
|
||||
};
|
||||
rebased.Add(parent);
|
||||
previous = replay.Commits[i];
|
||||
}
|
||||
if (differences.Count > 0 && rebased.Count > 0) rebased[^1] = rebased[^1] 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);
|
||||
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");
|
||||
@@ -537,12 +553,47 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
project.WriteBundle(moved);
|
||||
Step("replay.base");
|
||||
await FinishReplayAsync(project, journal, held, home, cancellationToken).ConfigureAwait(false);
|
||||
project.WriteSync(project.ReadSync() with { Replay = null });
|
||||
// A save-both cut short whose copy got the rest above is over with the conflict it was for.
|
||||
project.WriteSync(project.ReadSync() with { Replay = null, SaveBoth = null });
|
||||
if (takeTheirs is EveryPath && kept is not null)
|
||||
kept(ProjectSettings.FromJson(ProjectContent.Place(ProjectContent.Canonical(keptMine.ToJson()), photos), allowNewer: true));
|
||||
return (moved, null, theirs);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A conflict met past local commits the home holds (their answer lost): the base moves onto the last of them,
|
||||
/// <paramref name="onto"/> (their files adopted once it has), so the commits after them stay in the chain from the base
|
||||
/// and the conflict is settled against it. Journaled like a replay.
|
||||
/// </summary>
|
||||
private async Task<ProjectBundle> MoveOntoHeldAsync(WorkspaceProject project, ProjectBundle bundle, ProjectVersion onto, IReadOnlyList<ProjectVersion> held,
|
||||
IProjectHome home, CancellationToken cancellationToken)
|
||||
{
|
||||
var journal = new WorkspaceReplay(onto.Id, [], [], [.. held.Select(v => v.Id)]);
|
||||
var sync = project.ReadSync();
|
||||
// A save-both cut short goes on from the new base: the move is not its commit point (SettleAsync).
|
||||
project.WriteSync(sync with { Replay = journal, SaveBoth = sync.SaveBoth is { } both ? both with { FromBase = onto.Id } : null });
|
||||
Step("replay.journal");
|
||||
bundle = WithBase(bundle, onto);
|
||||
project.WriteBundle(bundle);
|
||||
Step("replay.base");
|
||||
await FinishReplayAsync(project, journal, held, home, cancellationToken).ConfigureAwait(false);
|
||||
return bundle;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The conflict recorded, while the home holds no version after the base: it lost them (an index taken back from an
|
||||
/// older backup, a home answering late), so there is nothing to settle it against and it stays. One the base has reached
|
||||
/// since (a replay that settled it, cut before it said so) is over: null.
|
||||
/// </summary>
|
||||
private static WorkspaceConflict? StillRecorded(WorkspaceProject project, ProjectBundle bundle)
|
||||
{
|
||||
if (project.ReadSync().Conflict is not { } recorded) return null;
|
||||
var basis = bundle.Workspace!.Base;
|
||||
if (basis is not null && (basis.VersionId == recorded.TheirsVersionId || basis.Number >= recorded.TheirsNumber)) return null;
|
||||
Log.Info("workspace", $"The home holds no version of project {project.ProjectId} after the base: its conflict stays");
|
||||
return recorded;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The workspace's media with their photos named as the home names them now (<see cref="WorkspaceMedia.NamedAsAt"/>),
|
||||
/// written back when the home taught them anything, so the versions, the working state and every comparison after this
|
||||
@@ -564,28 +615,37 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
/// last version's), the project moves onto the head as it is, read-only when that is the newer one. Otherwise the local
|
||||
/// versions and the working state stay as they are and a conflict of format waits (<see cref="WorkspaceConflict.NewerFormat"/>):
|
||||
/// Save both sends them to a new project made from the base, in this Chronos's format. A choice to merge them
|
||||
/// (<paramref name="takeTheirs"/> set: keep mine, take the server's) is refused, the conflict left recorded.
|
||||
/// (<paramref name="takeTheirs"/> set: keep mine, take the server's) is refused, the conflict left recorded. As for any
|
||||
/// conflict, one met past local commits the home holds (<paramref name="pastHeld"/>: <paramref name="basis"/> is the last
|
||||
/// of them) first moves the base onto them, so the conflict, the chain and the base name one version.
|
||||
/// </summary>
|
||||
/// <exception cref="WorkspaceSyncException">A choice to merge was made.</exception>
|
||||
private static (ProjectBundle Bundle, WorkspaceConflict? Conflict, IReadOnlyList<ProjectVersion> Pulled) NewerAtHome(WorkspaceProject project,
|
||||
ProjectBundle bundle, WorkspaceMedia? media, ProjectVersion? tipVersion, IReadOnlyList<ProjectVersion> locals, ProjectVersion? basis, ProjectVersion head,
|
||||
IReadOnlyList<ProjectVersion> theirs, IReadOnlySet<string>? takeTheirs)
|
||||
private async Task<(ProjectBundle Bundle, WorkspaceConflict? Conflict, IReadOnlyList<ProjectVersion> Pulled)> NewerAtHomeAsync(WorkspaceProject project,
|
||||
ProjectBundle bundle, IProjectHome home, WorkspaceMedia? media, ProjectVersion? tipVersion, IReadOnlyList<ProjectVersion> chain,
|
||||
IReadOnlyList<ProjectVersion> locals, ProjectVersion? basis, bool pastHeld, IReadOnlyList<ProjectVersion> held, ProjectVersion head,
|
||||
IReadOnlyList<ProjectVersion> theirs, IReadOnlySet<string>? takeTheirs, CancellationToken cancellationToken)
|
||||
{
|
||||
var photos = media?.Photos ?? NoFrames;
|
||||
var tip = tipVersion?.SettingsJson ?? ProjectContent.ToPortable(new ProjectSettings(), photos);
|
||||
if (locals.Count == 0 && (bundle.IsReadOnly
|
||||
|| ProjectContent.SameChoices(tip, Portable(bundle.Project, media) ?? throw MediaMissing(project.ProjectId), photos)))
|
||||
{
|
||||
await FinishCopyAsync(project, home, chain, cancellationToken).ConfigureAwait(false);
|
||||
var placed = ProjectSettings.FromJson(ProjectContent.Place(head.SettingsJson, photos), allowNewer: true);
|
||||
var moved = WithBase(bundle, head) with { Project = placed, Saved = DateTimeOffset.UtcNow };
|
||||
project.WriteBundle(moved);
|
||||
// Moved onto the head: the local files of versions the home held take its copies, as after a replay.
|
||||
if (held.Count > 0)
|
||||
await FinishReplayAsync(project, new WorkspaceReplay(head.Id, [], [], [.. held.Select(v => v.Id)]), held, home, cancellationToken).ConfigureAwait(false);
|
||||
if (project.ReadSync().SaveBoth is not null) project.WriteSync(project.ReadSync() with { SaveBoth = null });
|
||||
return (moved, null, theirs);
|
||||
}
|
||||
if (pastHeld) bundle = await MoveOntoHeldAsync(project, bundle, basis!, held, home, cancellationToken).ConfigureAwait(false);
|
||||
var newer = Math.Max(ProjectContent.FormatOf(head.SettingsJson), basis is null ? 0 : ProjectContent.FormatOf(basis.SettingsJson));
|
||||
var format = new SettingsDifference(ProjectMerge.FormatPath, ProjectContent.FormatOf(tip).ToString(CultureInfo.InvariantCulture),
|
||||
newer.ToString(CultureInfo.InvariantCulture));
|
||||
var conflict = new WorkspaceConflict(head.Id, head.Number, basis?.Id ?? Guid.Empty, [.. locals.Select(v => v.Id)], [format], DateTimeOffset.UtcNow);
|
||||
project.WriteSync(project.ReadSync() with { Conflict = conflict });
|
||||
project.WriteSync(project.ReadSync() with { Conflict = conflict, Replay = null });
|
||||
if (takeTheirs is not null)
|
||||
throw new WorkspaceSyncException(PushOutcome.NewerFormat,
|
||||
$"Version {head.Number} of project {project.ProjectId} holds settings of a newer Chronos: nothing of this workspace's is merged into it (save both, or update Chronos).");
|
||||
@@ -613,10 +673,25 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
/// 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.
|
||||
/// local file of the version the base names (a push cut after it moved the base) takes the home's copy. A version file
|
||||
/// that cannot be read takes the home's copy when the home holds that version (the damaged file is kept aside, in
|
||||
/// <c>versions/.replaced</c>); one the home never had stays, a gap every sync then stops at (<see cref="EnsureChained"/>).
|
||||
/// </summary>
|
||||
private static async Task SettleAsync(WorkspaceProject project, IProjectHome home, CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var unreadable in project.UnreadableVersions())
|
||||
{
|
||||
if (await home.GetVersionAsync(project.ProjectId, unreadable.Id, cancellationToken).ConfigureAwait(false) is not { StoredAt: not null } copy
|
||||
|| copy.Id != unreadable.Id)
|
||||
continue;
|
||||
Verify(copy);
|
||||
project.SetAside(unreadable.Path);
|
||||
// A local version the home stored (its answer lost) with versions saved after it stays in their chain, unsent,
|
||||
// until the next push hears "already stored"; any other is the home's version it is.
|
||||
var parentOfUnsent = project.Versions().Any(v => v.StoredAt is null && v.ParentId == copy.Id);
|
||||
project.WriteVersion(parentOfUnsent ? copy with { StoredAt = null } : copy, replace: true);
|
||||
Log.Warning("workspace", $"Version file {unreadable.Path} could not be read ({unreadable.Reason}); it took the home's copy and was kept aside");
|
||||
}
|
||||
var sync = project.ReadSync();
|
||||
var basis = project.ReadBundle().Workspace!.Base;
|
||||
if (sync.Replay is { } replay)
|
||||
@@ -671,7 +746,9 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
/// 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.
|
||||
/// it is asked for, and the base moving onto the home's head is the commit point. A copy deleted at the home since, or
|
||||
/// one somebody else sent versions to (it is theirs now, left as it is), gives way to a new copy that takes them all.
|
||||
/// Every local version after the base is sent: one the chain does not reach stops it first (<see cref="EnsureChained"/>).
|
||||
/// </summary>
|
||||
private async Task<WorkspaceSyncResult> SaveBothAsync(WorkspaceProject project, ProjectBundle bundle, IProjectHome home, string? name, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -679,18 +756,14 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
if (!bundle.IsReadOnly) CommitLocked(project, bundle, null, null);
|
||||
bundle = project.ReadBundle();
|
||||
var locals = Unpushed(project, bundle);
|
||||
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;
|
||||
}
|
||||
EnsureChained(project, bundle, locals);
|
||||
var pending = project.ReadSync().SaveBoth;
|
||||
var copy = locals.Count > 0 && pending is not null ? await OurCopyAsync(project, home, pending, cancellationToken).ConfigureAwait(false) : null;
|
||||
if (copy is null) pending = null;
|
||||
var pushed = new List<ProjectVersion>();
|
||||
if (locals.Count > 0)
|
||||
for (var attempt = 1; locals.Count > 0; attempt++)
|
||||
{
|
||||
var journaled = pending is not null;
|
||||
if (pending is null)
|
||||
{
|
||||
var basis = await BaseVersionAsync(project, bundle, home, cancellationToken).ConfigureAwait(false);
|
||||
@@ -699,23 +772,24 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
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))
|
||||
if (!journaled || locals.Any(l => !known.Contains(l.Id)))
|
||||
{
|
||||
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 });
|
||||
project.WriteSync(project.ReadSync() 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)
|
||||
try
|
||||
{
|
||||
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);
|
||||
(parentId, parentNumber) = (stored.Id, stored.Number);
|
||||
Step("saveboth.pushed");
|
||||
pushed = await SendToCopyAsync(project, home, copy!, pending, locals, cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
catch (CopyMovedException)
|
||||
{
|
||||
if (attempt >= 2)
|
||||
throw new WorkspaceSyncException(PushOutcome.Diverged, $"Project '{copy!.Name}' at the home kept moving while project {project.ProjectId} was saved into it.");
|
||||
// Somebody sent a version to the copy between our check and our push: it is theirs; a new one takes ours.
|
||||
Log.Info("workspace", $"Save both of project {project.ProjectId}: project '{copy!.Name}' at the home moved meanwhile; a new copy is made");
|
||||
pending = null;
|
||||
}
|
||||
}
|
||||
// This project takes the home's head: the local versions now live in the copy (and their files in versions/.replaced).
|
||||
@@ -732,6 +806,83 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), pushed, [head], copy);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The copy a save-both cut short made (<paramref name="pending"/>) while it is still this workspace's to send to: at the
|
||||
/// home, its head the version it was made with or one this workspace sent it. Null when it was deleted since, or somebody
|
||||
/// else sent it a version (it is theirs: never sent to, never deleted by this workspace).
|
||||
/// </summary>
|
||||
private static async Task<SequenceProject?> OurCopyAsync(WorkspaceProject project, IProjectHome home, WorkspaceSaveBoth pending, CancellationToken cancellationToken)
|
||||
{
|
||||
if ((await home.ListAsync(cancellationToken).ConfigureAwait(false)).FirstOrDefault(p => p.Id == pending.CopyId) is not { } copy)
|
||||
{
|
||||
Log.Info("workspace", $"The copy a save-both of project {project.ProjectId} made is no longer at the home");
|
||||
return null;
|
||||
}
|
||||
var head = await home.HeadAsync(copy.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (head.Id == pending.CopyBaseId || pending.Moves.Any(m => m.CopyVersionId == head.Id)) return copy;
|
||||
Log.Info("workspace", $"Project '{copy.Name}', the copy a save-both of project {project.ProjectId} made, took another's version since: it is left as it is");
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends <paramref name="locals"/> to the save-both's copy under the ids its journal gives them, in order on the version
|
||||
/// it was made with (the home answers "already stored" for those a cut sent before).
|
||||
/// </summary>
|
||||
/// <exception cref="CopyMovedException">The copy's head is not the parent sent: somebody else sent it a version.</exception>
|
||||
/// <exception cref="WorkspaceSyncException">The home refused a version for good.</exception>
|
||||
private async Task<List<ProjectVersion>> SendToCopyAsync(WorkspaceProject project, IProjectHome home, SequenceProject copy, WorkspaceSaveBoth pending,
|
||||
IReadOnlyList<ProjectVersion> locals, CancellationToken cancellationToken)
|
||||
{
|
||||
var ids = pending.Moves.ToDictionary(m => m.LocalId, m => m.CopyVersionId);
|
||||
var (parentId, parentNumber) = (pending.CopyBaseId, pending.CopyBaseNumber);
|
||||
var pushed = new List<ProjectVersion>(locals.Count);
|
||||
foreach (var local in locals)
|
||||
{
|
||||
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.Outcome == PushOutcome.Diverged) throw new CopyMovedException();
|
||||
if (result is not { Outcome: PushOutcome.Stored or PushOutcome.AlreadyStored, Version: { } stored }) throw Refused(result.Outcome, local, $"project '{copy.Name}'");
|
||||
Verify(stored);
|
||||
pushed.Add(stored);
|
||||
(parentId, parentNumber) = (stored.Id, stored.Number);
|
||||
Step("saveboth.pushed");
|
||||
}
|
||||
Log.Info("workspace", $"{pushed.Count} version(s) of project {project.ProjectId} are in its copy '{copy.Name}' at the home");
|
||||
return pushed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Keep mine or take the server's after a Save both cut short (its journal still there): the rest of this workspace's
|
||||
/// versions the journal lists go to the copy it made, so the home never keeps half of one; a copy deleted or taken over
|
||||
/// since is left as it is. The journal itself goes once the project moved (the caller's commit point).
|
||||
/// </summary>
|
||||
private async Task FinishCopyAsync(WorkspaceProject project, IProjectHome home, IReadOnlyList<ProjectVersion> chain, CancellationToken cancellationToken)
|
||||
{
|
||||
if (project.ReadSync().SaveBoth is not { } pending) return;
|
||||
var listed = pending.Moves.Select(m => m.LocalId).ToHashSet();
|
||||
var sent = chain.TakeWhile(v => listed.Contains(v.Id)).ToList();
|
||||
if (sent.Count == 0 || await OurCopyAsync(project, home, pending, cancellationToken).ConfigureAwait(false) is not { } copy) return;
|
||||
try
|
||||
{
|
||||
await SendToCopyAsync(project, home, copy, pending, sent, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (CopyMovedException)
|
||||
{
|
||||
Log.Info("workspace", $"Project '{copy.Name}' took another's version while a save-both of project {project.ProjectId} was finished: it is left as it is");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The home answered a save-both's copy moved under it (<see cref="PushOutcome.Diverged"/>).</summary>
|
||||
private sealed class CopyMovedException() : Exception("The copy moved at the home.");
|
||||
|
||||
/// <summary>A push the home refused for good: too large for a version, or refused otherwise (<see cref="WorkspaceSyncException.Outcome"/> says why).</summary>
|
||||
private static WorkspaceSyncException Refused(PushOutcome outcome, ProjectVersion local, string target) => outcome switch
|
||||
{
|
||||
PushOutcome.TooLarge => new WorkspaceSyncException(outcome,
|
||||
$"Version {local.Number} of {target} is larger than the {ProjectSidecars.MaxVersionBytes >> 20} MB a version may be: the home did not store it."),
|
||||
_ => new WorkspaceSyncException(outcome, $"The home refused version {local.Number} of {target}: {outcome}."),
|
||||
};
|
||||
|
||||
/// <summary>A new project at the home named <paramref name="name"/>, else "<paramref name="source"/> (2)", "(3)"… whichever is free.</summary>
|
||||
private static async Task<SequenceProject> CreateNamedAsync(IProjectHome home, string? name, string source, Guid? from, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -758,6 +909,8 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
var portable = Portable(bundle.Project, media) ?? throw MediaMissing(project.ProjectId);
|
||||
var hash = ProjectContent.Hash(portable);
|
||||
var locals = Unpushed(project, bundle);
|
||||
// Saved after a gap, the new version would hang from the versions before it and the ones after it would be left out.
|
||||
EnsureChained(project, bundle, locals);
|
||||
var (tipId, tipNumber, tipHash) = locals.Count > 0
|
||||
? (locals[^1].Id, locals[^1].Number, locals[^1].ContentHash)
|
||||
: (workspace.Base?.VersionId, workspace.Base?.Number ?? 0, workspace.Base?.ContentHash);
|
||||
@@ -809,8 +962,10 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
{
|
||||
media = null;
|
||||
}
|
||||
var conflict = project.ReadSync().Conflict;
|
||||
var sync = project.ReadSync();
|
||||
var conflict = sync.Conflict;
|
||||
var locals = Unpushed(project, bundle);
|
||||
var damaged = Gaps(project, bundle, locals, sync).Count;
|
||||
ProjectVersion? head = null;
|
||||
HomeFrames? frames = null;
|
||||
var offline = false;
|
||||
@@ -841,6 +996,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
// A local commit the home stored although its answer was lost reads as behind by the commits it holds: they are ours.
|
||||
if (head is not null && locals.Any(v => v.Id == head.Id)) behind = 0;
|
||||
var state = media is null ? WorkspaceState.MediaRemoved
|
||||
: damaged > 0 ? WorkspaceState.Damaged
|
||||
: conflict is not null ? WorkspaceState.Conflict
|
||||
: offline ? WorkspaceState.Offline
|
||||
: behind > 0 ? WorkspaceState.Behind
|
||||
@@ -850,6 +1006,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
return new WorkspaceStatus(state, modified, locals.Count, behind, offline, media is null, bundle.IsReadOnly, conflict, workspace.Base, head)
|
||||
{
|
||||
MediaOutdated = outdated,
|
||||
Damaged = damaged,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -879,6 +1036,37 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The version files after the base the chain of versions to send (<paramref name="chain"/>) does not reach: files that
|
||||
/// cannot be read, and unsent versions that do not follow from the base. Those a replay or a save-both cut short left
|
||||
/// (their journals, which the next sync settles) are not counted.
|
||||
/// </summary>
|
||||
private static List<string> Gaps(WorkspaceProject project, ProjectBundle bundle, IReadOnlyList<ProjectVersion> chain, WorkspaceSyncState sync)
|
||||
{
|
||||
var basis = bundle.Workspace!.Base;
|
||||
var after = basis?.Number ?? 0;
|
||||
var reached = chain.Select(v => v.Id).ToHashSet();
|
||||
if (sync.Replay is { } replay) reached.UnionWith([.. replay.Replayed, .. replay.Replaced]);
|
||||
if (sync.SaveBoth is { } both) reached.UnionWith(both.Moves.Select(m => m.LocalId));
|
||||
var gaps = project.UnreadableVersions().Where(u => u.Number > after && !reached.Contains(u.Id)).Select(u => u.Path).ToList();
|
||||
gaps.AddRange(project.Versions().Where(v => v.StoredAt is null && v.Number > after && v.Id != basis?.VersionId && !reached.Contains(v.Id))
|
||||
.Select(project.VersionPath));
|
||||
return gaps;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Refuses to save, send or take anything while a version saved here after the base cannot be read or does not follow
|
||||
/// from it (<see cref="WorkspaceState.Damaged"/>): the chain would go on without it and the versions after it.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidDataException">There is such a version; the log names its file.</exception>
|
||||
private static void EnsureChained(WorkspaceProject project, ProjectBundle bundle, IReadOnlyList<ProjectVersion> chain)
|
||||
{
|
||||
var gaps = Gaps(project, bundle, chain, project.ReadSync());
|
||||
if (gaps.Count == 0) return;
|
||||
Log.Warning("workspace", $"Project {project.ProjectId} has versions saved here the chain from its base does not reach: {string.Join(", ", gaps)}");
|
||||
throw new InvalidDataException($"Project {project.ProjectId} has {gaps.Count} version file(s) after its base that cannot be read or do not follow from it: {gaps[0]}.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the working state's portable form holds what the last version does (the last local one, else the base),
|
||||
/// once each names its photos as the media hold them now: a version saved before the media were copied again after a
|
||||
|
||||
Reference in new issue
Block a user