fix(workspace): finish or keep every choice, copy and sync a cut or a deleted project leaves
- A take of the library's values cut past its commit point settles its conflict (replay journal marks Settles); a later stale choice finds nothing to settle, and one cut before it keeps the conflict so the next choice is applied. - A local version that changes nothing once replayed on the head is not sent nor written as a Merge; its file stays in versions/.replaced. - Save both journals its intent (name, base, time) before the home is asked, so a cut after the copy was made reuses that copy on retry. - A project deleted at the home reads as Gone from pull, push, resolve and save both, logged once, without retry loops; versions and working state stay. - Save both keeps the restore recorded in sync.json. - The copy job writes a photo's new bytes under a name of its own while the editor's media still name the old file, switching at the commit; a cancelled first copy removes its own half media under the lease (VM hook removed). - Status reads the version files once, re-reads the home's frames only when its stamp moved, reports damage only when confirmed under the lease, and waits once for a busy lease before calling the media outdated. - versions/.replaced is pruned after a sync that ended well (30 days, newest 20 kept, never a file a journal names). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
488b588ad9
commit
5eeb64b680
14 files changed
+1183
-216
No files matched your search
@@ -35,7 +35,8 @@ public enum WorkspaceState
|
||||
|
||||
/// <summary>
|
||||
/// The home answered that it no longer has the project or its sequence (the sequence left its index): nothing more can be
|
||||
/// sent, and the local copy can only be removed, its work kept aside. Told by the desktop, which asks the home.
|
||||
/// sent, and the local copy can only be removed, its work kept aside. Told by a status asked of the home, and by a sync
|
||||
/// or a choice that met it (nothing here is changed by it).
|
||||
/// </summary>
|
||||
Gone,
|
||||
|
||||
@@ -258,7 +259,9 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
|
||||
/// <summary>
|
||||
/// Pushes the local versions in order. When the home moved meanwhile, its versions are pulled and the local ones
|
||||
/// replayed on top of them first; a real conflict stops the push (<see cref="WorkspaceState.Conflict"/>).
|
||||
/// replayed on top of them first; a real conflict stops the push (<see cref="WorkspaceState.Conflict"/>). A project the
|
||||
/// home no longer has reads as <see cref="WorkspaceState.Gone"/>, its versions kept here. A push that ended well prunes
|
||||
/// <c>versions/.replaced</c> (<see cref="WorkspaceProject.PruneReplaced"/>).
|
||||
/// </summary>
|
||||
/// <exception cref="HomeUnavailableException">The home cannot be reached; nothing was lost, push again later.</exception>
|
||||
/// <exception cref="WorkspaceSyncException">The home refused a version for good.</exception>
|
||||
@@ -268,45 +271,55 @@ 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++)
|
||||
try
|
||||
{
|
||||
var bundle = project.ReadBundle();
|
||||
if (project.ReadSync().Conflict is not null) break;
|
||||
var diverged = false;
|
||||
var locals = Unpushed(project, bundle);
|
||||
EnsureChained(project, bundle, locals);
|
||||
foreach (var local in locals)
|
||||
await SettleAsync(project, home, cancellationToken).ConfigureAwait(false);
|
||||
for (var attempt = 0; attempt < PushAttempts; attempt++)
|
||||
{
|
||||
var result = await home.PushAsync(projectId, local, cancellationToken).ConfigureAwait(false);
|
||||
switch (result.Outcome)
|
||||
var bundle = project.ReadBundle();
|
||||
if (project.ReadSync().Conflict is not null) break;
|
||||
var diverged = false;
|
||||
var locals = Unpushed(project, bundle);
|
||||
EnsureChained(project, bundle, locals);
|
||||
foreach (var local in locals)
|
||||
{
|
||||
case PushOutcome.Stored or PushOutcome.AlreadyStored when result.Version is { } stored:
|
||||
Verify(stored);
|
||||
// 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:
|
||||
diverged = true;
|
||||
break;
|
||||
default:
|
||||
throw Refused(result.Outcome, local, $"project {projectId}");
|
||||
var result = await home.PushAsync(projectId, local, cancellationToken).ConfigureAwait(false);
|
||||
switch (result.Outcome)
|
||||
{
|
||||
case PushOutcome.Stored or PushOutcome.AlreadyStored when result.Version is { } stored:
|
||||
Verify(stored);
|
||||
// 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:
|
||||
diverged = true;
|
||||
break;
|
||||
default:
|
||||
throw Refused(result.Outcome, local, $"project {projectId}");
|
||||
}
|
||||
break;
|
||||
}
|
||||
break;
|
||||
if (!diverged) break;
|
||||
var (_, conflict, taken) = await ReplayAsync(project, bundle, home, null, cancellationToken).ConfigureAwait(false);
|
||||
pulled.AddRange(taken);
|
||||
if (conflict is not null) break;
|
||||
}
|
||||
if (!diverged) break;
|
||||
var (_, conflict, taken) = await ReplayAsync(project, bundle, home, null, cancellationToken).ConfigureAwait(false);
|
||||
pulled.AddRange(taken);
|
||||
if (conflict is not null) break;
|
||||
}
|
||||
catch (ProjectException ex) when (NotFoundAtHome(ex))
|
||||
{
|
||||
// Deleted at the home: no failure to retry but the state the project is in (Gone); nothing here moves.
|
||||
if (!await GoneAsync(project, home, ex, cancellationToken).ConfigureAwait(false)) throw;
|
||||
return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), pushed, pulled);
|
||||
}
|
||||
PruneReplaced(project);
|
||||
return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), pushed, pulled);
|
||||
}
|
||||
}
|
||||
@@ -315,7 +328,8 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
/// Takes the home's versions newer than the base: the working state (and any local versions, replayed) moves onto the
|
||||
/// home's head; a real conflict stops it (<see cref="WorkspaceState.Conflict"/>). A conflict recorded before is worked
|
||||
/// out again (the home may have moved on, this side may have been edited since), so what is asked is what differs now;
|
||||
/// one that no longer conflicts is settled by the merge.
|
||||
/// one that no longer conflicts is settled by the merge. A project the home no longer has reads as
|
||||
/// <see cref="WorkspaceState.Gone"/>, its copy here left as it is.
|
||||
/// </summary>
|
||||
/// <exception cref="HomeUnavailableException">The home cannot be reached.</exception>
|
||||
public async Task<WorkspaceSyncResult> PullAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken = default)
|
||||
@@ -324,20 +338,29 @@ 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 = [];
|
||||
var bundle = project.ReadBundle();
|
||||
EnsureChained(project, bundle, Unpushed(project, bundle));
|
||||
if (project.ReadSync().Conflict is not null)
|
||||
try
|
||||
{
|
||||
(_, var conflict, pulled) = await ReplayAsync(project, bundle, home, null, cancellationToken).ConfigureAwait(false);
|
||||
if (conflict is null) project.WriteSync(project.ReadSync() with { Conflict = null });
|
||||
await SettleAsync(project, home, cancellationToken).ConfigureAwait(false);
|
||||
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);
|
||||
if (conflict is null) project.WriteSync(project.ReadSync() with { Conflict = null });
|
||||
}
|
||||
else
|
||||
{
|
||||
var head = await home.HeadAsync(projectId, cancellationToken).ConfigureAwait(false);
|
||||
if (head.Id != bundle.Workspace!.Base?.VersionId) (_, _, pulled) = await ReplayAsync(project, bundle, home, null, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (ProjectException ex) when (NotFoundAtHome(ex))
|
||||
{
|
||||
var head = await home.HeadAsync(projectId, cancellationToken).ConfigureAwait(false);
|
||||
if (head.Id != bundle.Workspace!.Base?.VersionId) (_, _, pulled) = await ReplayAsync(project, bundle, home, null, cancellationToken).ConfigureAwait(false);
|
||||
if (!await GoneAsync(project, home, ex, cancellationToken).ConfigureAwait(false)) throw;
|
||||
return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), [], pulled);
|
||||
}
|
||||
if (project.ReadSync().Conflict is null) PruneReplaced(project);
|
||||
return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), [], pulled);
|
||||
}
|
||||
}
|
||||
@@ -346,16 +369,19 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
/// Settles the conflict a pull or push stopped at, as the user was shown it (<paramref name="shown"/>, else the one
|
||||
/// recorded). <see cref="ConflictChoice.KeepMine"/> keeps this workspace's values (but for the members in
|
||||
/// <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; so is one the home holds no
|
||||
/// versions for now (nothing to take them from). Taking the server's keeps the working state it replaces as a version
|
||||
/// file in <c>versions/.replaced</c>, outside the chain: nothing is committed, replayed or sent for it, so a take that
|
||||
/// leaves only the server's values sends nothing. 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).
|
||||
/// either way the local versions are replayed on the home's head and wait to be pushed (one the choice leaves changing
|
||||
/// nothing is not: its file is kept in <c>versions/.replaced</c>). 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; so is one the home holds no versions for now (nothing
|
||||
/// to take them from). A choice cut short past its commit point was applied: the conflict is over, and a later choice
|
||||
/// finds nothing to settle. Taking the server's keeps the working state it replaces as a version file in
|
||||
/// <c>versions/.replaced</c>, outside the chain: nothing is committed, replayed or sent for it, so a take that leaves
|
||||
/// only the server's values sends nothing. 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.
|
||||
/// 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 (<see cref="WorkspaceState.Gone"/>).
|
||||
/// </summary>
|
||||
/// <exception cref="HomeUnavailableException">The home cannot be reached; the conflict stays.</exception>
|
||||
public async Task<WorkspaceSyncResult> ResolveAsync(Guid projectId, IProjectHome home, ConflictChoice choice, IReadOnlySet<string>? takeServer = null,
|
||||
@@ -365,23 +391,31 @@ 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 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);
|
||||
// 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<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);
|
||||
if (conflict is null) project.WriteSync(project.ReadSync() with { Conflict = null });
|
||||
return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), [], pulled)
|
||||
try
|
||||
{
|
||||
Kept = conflict is null ? kept : null,
|
||||
};
|
||||
await SettleAsync(project, home, cancellationToken).ConfigureAwait(false);
|
||||
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);
|
||||
// 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<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);
|
||||
if (conflict is null) project.WriteSync(project.ReadSync() with { Conflict = null });
|
||||
return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), [], pulled)
|
||||
{
|
||||
Kept = conflict is null ? kept : null,
|
||||
};
|
||||
}
|
||||
catch (ProjectException ex) when (NotFoundAtHome(ex))
|
||||
{
|
||||
if (!await GoneAsync(project, home, ex, cancellationToken).ConfigureAwait(false)) throw;
|
||||
return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), [], []);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -522,6 +556,13 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
{
|
||||
var local = locals[i];
|
||||
var portable = ProjectContent.Canonical(replay.Commits[i].ToJson());
|
||||
// A commit the replay leaves changing nothing (the server's values taken over its own, or the same change made
|
||||
// there) is not replayed into an empty version to send: its file goes to versions/.replaced with the others.
|
||||
if (ProjectContent.SameChoices(parent.SettingsJson, portable, photos))
|
||||
{
|
||||
Log.Info("workspace", $"Version {local.Number} of project {project.ProjectId} changes nothing once replayed on version {head.Number}: it is not sent");
|
||||
continue;
|
||||
}
|
||||
parent = local with
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
@@ -542,7 +583,8 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
if (takeTheirs is EveryPath && differences.Count > 0 && Portable(bundle.Project, media) is { } unsaved
|
||||
&& (tipVersion is null || !ProjectContent.SameChoices(tipVersion.SettingsJson, unsaved, photos)))
|
||||
project.WriteAside(VersionOf(project, unsaved, tipVersion, ProjectVersionKind.Commit, null, null, null, media?.FramesVersion ?? bundle.Workspace!.Media.FramesVersion));
|
||||
var journal = new WorkspaceReplay(head.Id, [.. locals.Select(v => v.Id)], [.. rebased.Select(v => v.Id)], [.. held.Select(v => v.Id)]);
|
||||
// Past its commit point the replay has settled the conflict recorded beside it, the choice made applied (SettleAsync).
|
||||
var journal = new WorkspaceReplay(head.Id, [.. locals.Select(v => v.Id)], [.. rebased.Select(v => v.Id)], [.. held.Select(v => v.Id)], Settles: true);
|
||||
project.WriteSync(project.ReadSync() with { Replay = journal });
|
||||
Step("replay.journal");
|
||||
foreach (var version in rebased)
|
||||
@@ -697,11 +739,14 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
var basis = project.ReadBundle().Workspace!.Base;
|
||||
if (sync.Replay is { } replay)
|
||||
{
|
||||
if (basis?.VersionId == replay.OntoBase) await FinishReplayAsync(project, replay, [], home, cancellationToken).ConfigureAwait(false);
|
||||
var finished = basis?.VersionId == replay.OntoBase;
|
||||
if (finished) await FinishReplayAsync(project, replay, [], home, cancellationToken).ConfigureAwait(false);
|
||||
else foreach (var id in replay.Replayed) SetAsideUnsent(project, id);
|
||||
sync = sync with { Replay = null };
|
||||
// Past its commit point a replay that settles a conflict has applied the choice made: the conflict is over. Cut
|
||||
// before it, nothing moved and the conflict stays to be asked again.
|
||||
sync = sync with { Replay = null, Conflict = finished && replay.Settles ? null : sync.Conflict };
|
||||
project.WriteSync(sync);
|
||||
Log.Info("workspace", $"A sync of project {project.ProjectId} cut short was {(basis?.VersionId == replay.OntoBase ? "finished" : "undone")}");
|
||||
Log.Info("workspace", $"A sync of project {project.ProjectId} cut short was {(finished ? "finished" : "undone")}");
|
||||
}
|
||||
if (sync.SaveBoth is { } both && basis?.VersionId != both.FromBase)
|
||||
{
|
||||
@@ -744,12 +789,15 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
}
|
||||
|
||||
/// <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. 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"/>).
|
||||
/// Both sides kept: this workspace's versions to a new project at the home, this project onto the home's head. The
|
||||
/// copy's name and the version it is made from are journaled before the home is asked for it, then the copy and the ids
|
||||
/// its versions are sent under, before the first is sent (<see cref="WorkspaceSaveBoth"/>): a retry after a cut finds the
|
||||
/// copy the home made by its name (<see cref="WorkspaceCopyIntent"/>) and sends it 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. 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"/>). A project the home deleted meanwhile keeps its versions and its
|
||||
/// working state here as they are, the copy holding them too (<see cref="WorkspaceState.Gone"/>); a retry sends nothing new.
|
||||
/// </summary>
|
||||
private async Task<WorkspaceSyncResult> SaveBothAsync(WorkspaceProject project, ProjectBundle bundle, IProjectHome home, string? name, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -759,8 +807,11 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
var locals = Unpushed(project, bundle);
|
||||
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;
|
||||
SequenceProject? copy = null;
|
||||
if (locals.Count > 0 && pending is not null && await OurCopyAsync(project, home, pending, cancellationToken).ConfigureAwait(false) is { } ours)
|
||||
(copy, pending) = ours;
|
||||
else
|
||||
pending = null;
|
||||
var pushed = new List<ProjectVersion>();
|
||||
for (var attempt = 1; locals.Count > 0; attempt++)
|
||||
{
|
||||
@@ -768,9 +819,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
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, []);
|
||||
(copy, pending) = await CreateCopyAsync(project, home, name, workspace, basis, locals, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
var known = pending.Moves.Select(m => m.LocalId).ToHashSet();
|
||||
if (!journaled || locals.Any(l => !known.Contains(l.Id)))
|
||||
@@ -794,7 +843,18 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
}
|
||||
}
|
||||
// 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);
|
||||
ProjectVersion head;
|
||||
try
|
||||
{
|
||||
head = await home.HeadAsync(project.ProjectId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (ProjectException ex) when (NotFoundAtHome(ex))
|
||||
{
|
||||
// Deleted at the home meanwhile: nothing to move onto. The versions are in the copy, and stay here too, unsent,
|
||||
// with the journal, so a retry finds that copy and sends nothing again.
|
||||
ReportGone(project, ex);
|
||||
return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), pushed, [], copy);
|
||||
}
|
||||
Verify(head);
|
||||
project.WriteVersion(head, replace: true);
|
||||
var media = project.ReadMedia();
|
||||
@@ -803,28 +863,107 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
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);
|
||||
// Settled and finished; a restore recorded stays, the next version saved tells whether it still restores.
|
||||
project.WriteSync(project.ReadSync() with { Conflict = null, Replay = null, SaveBoth = null });
|
||||
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).
|
||||
/// home, its head the version it was made with or one this workspace sent it; with the journal as it now names it. One
|
||||
/// only asked for (<see cref="WorkspaceSaveBoth.Intended"/>: a cut came before its answer) is found by the name it was
|
||||
/// asked under: a project of that name made since, whose only version is the one it was made from (its ids journaled
|
||||
/// then). Null when it was deleted since, never made, 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)
|
||||
private static async Task<(SequenceProject Copy, WorkspaceSaveBoth Pending)?> 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)
|
||||
var listed = await home.ListAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (pending.Intended)
|
||||
{
|
||||
if (pending.Intent is not { } intent
|
||||
|| listed.FirstOrDefault(p => string.Equals(p.Name, intent.Name.Trim(), StringComparison.OrdinalIgnoreCase)) is not { } named
|
||||
|| named.CreatedAt < intent.Asked - IntentSkew)
|
||||
{
|
||||
Log.Info("workspace", $"The copy a save-both of project {project.ProjectId} asked for was not made at the home");
|
||||
return null;
|
||||
}
|
||||
var first = await home.HeadAsync(named.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (first.Number != 1 || (intent.FromHash is { } hash && !string.Equals(first.ContentHash, hash, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
Log.Info("workspace", $"Project '{named.Name}' at the home is not the copy a save-both of project {project.ProjectId} asked for: it is left as it is");
|
||||
return null;
|
||||
}
|
||||
var found = pending with { CopyId = named.Id, CopyBaseId = first.Id, CopyBaseNumber = first.Number };
|
||||
project.WriteSync(project.ReadSync() with { SaveBoth = found });
|
||||
Log.Info("workspace", $"Project '{named.Name}' at the home is the copy a save-both of project {project.ProjectId} cut short asked for: it is used");
|
||||
return (named, found);
|
||||
}
|
||||
if (listed.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;
|
||||
if (head.Id == pending.CopyBaseId || pending.Moves.Any(m => m.CopyVersionId == head.Id)) return (copy, pending);
|
||||
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>How much earlier than asked a home's clock may date the copy a save-both asked for (<see cref="WorkspaceCopyIntent.Asked"/>).</summary>
|
||||
private static readonly TimeSpan IntentSkew = TimeSpan.FromMinutes(5);
|
||||
|
||||
/// <summary>
|
||||
/// A new project at the home for a save-both, named <paramref name="name"/>, else "<paramref name="workspace"/>'s name
|
||||
/// (2)", "(3)"… whichever is free, made from <paramref name="basis"/>. Each name is journaled before the home is asked
|
||||
/// (<see cref="WorkspaceCopyIntent"/>), then the copy with the ids <paramref name="locals"/> are sent under. A name the
|
||||
/// home finds taken leaves no journal when it was asked for (the caller asks again without one).
|
||||
/// </summary>
|
||||
/// <exception cref="ProjectException">The name asked for is taken or invalid.</exception>
|
||||
private async Task<(SequenceProject Copy, WorkspaceSaveBoth Pending)> CreateCopyAsync(WorkspaceProject project, IProjectHome home, string? name,
|
||||
BundleWorkspace workspace, ProjectVersion? basis, IReadOnlyList<ProjectVersion> locals, CancellationToken cancellationToken)
|
||||
{
|
||||
var moves = locals.Select(l => new WorkspaceMove(l.Id, Guid.CreateVersion7())).ToList();
|
||||
var named = !string.IsNullOrWhiteSpace(name);
|
||||
HashSet<string> taken = named ? [] : (await home.ListAsync(cancellationToken).ConfigureAwait(false)).Select(p => p.Name).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
for (var n = 2; ; n++)
|
||||
{
|
||||
var candidate = named ? name!.Trim() : Numbered(workspace.Name, n);
|
||||
if (!named && n < 100 && taken.Contains(candidate)) continue;
|
||||
var intended = new WorkspaceSaveBoth(Guid.Empty, Guid.Empty, 0, workspace.Base?.VersionId, moves,
|
||||
new WorkspaceCopyIntent(candidate, basis?.Id, basis?.ContentHash, DateTimeOffset.UtcNow));
|
||||
project.WriteSync(project.ReadSync() with { SaveBoth = intended });
|
||||
Step("saveboth.intent");
|
||||
SequenceProject copy;
|
||||
try
|
||||
{
|
||||
copy = await home.CreateAsync(candidate, basis?.Id, null, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (ProjectException ex) when (ex.Reason == ProjectError.NameTaken && !named && n < 100)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
catch (ProjectException ex) when (ex.Reason is ProjectError.NameTaken or ProjectError.InvalidName)
|
||||
{
|
||||
// Not made: no copy of that name is this workspace's.
|
||||
project.WriteSync(project.ReadSync() with { SaveBoth = null });
|
||||
throw;
|
||||
}
|
||||
Step("saveboth.created");
|
||||
var first = await home.HeadAsync(copy.Id, cancellationToken).ConfigureAwait(false);
|
||||
var pending = intended with { CopyId = copy.Id, CopyBaseId = first.Id, CopyBaseNumber = first.Number };
|
||||
project.WriteSync(project.ReadSync() with { SaveBoth = pending });
|
||||
return (copy, pending);
|
||||
}
|
||||
|
||||
static string Numbered(string source, int n)
|
||||
{
|
||||
var candidate = $"{source} ({n})";
|
||||
return candidate.Length > ProjectService.MaxNameLength ? $"{source[..(ProjectService.MaxNameLength - 6)]} ({n})" : candidate;
|
||||
}
|
||||
}
|
||||
|
||||
/// <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).
|
||||
@@ -854,18 +993,20 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
|
||||
/// <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).
|
||||
/// versions the journal lists go to the copy it made (or asked for, found by its name), so the home never keeps half of
|
||||
/// one; a copy deleted, never made 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;
|
||||
if (sent.Count == 0 || await OurCopyAsync(project, home, pending, cancellationToken).ConfigureAwait(false) is not { } ours) return;
|
||||
var (copy, known) = ours;
|
||||
try
|
||||
{
|
||||
await SendToCopyAsync(project, home, copy, pending, sent, cancellationToken).ConfigureAwait(false);
|
||||
await SendToCopyAsync(project, home, copy, known, sent, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (CopyMovedException)
|
||||
{
|
||||
@@ -884,24 +1025,6 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
_ => 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)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(name)) return await home.CreateAsync(name, from, null, cancellationToken).ConfigureAwait(false);
|
||||
for (var n = 2; ; n++)
|
||||
{
|
||||
var candidate = $"{source} ({n})";
|
||||
if (candidate.Length > ProjectService.MaxNameLength) candidate = $"{source[..(ProjectService.MaxNameLength - 6)]} ({n})";
|
||||
try
|
||||
{
|
||||
return await home.CreateAsync(candidate, from, null, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (ProjectException ex) when (ex.Reason == ProjectError.NameTaken && n < 100)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ProjectVersion? CommitLocked(WorkspaceProject project, ProjectBundle bundle, string? note, string? author)
|
||||
{
|
||||
if (bundle.IsReadOnly) throw ReadOnly(project.ProjectId);
|
||||
@@ -909,13 +1032,14 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
var media = project.ReadMedia();
|
||||
var portable = Portable(bundle.Project, media) ?? throw MediaMissing(project.ProjectId);
|
||||
var hash = ProjectContent.Hash(portable);
|
||||
var locals = Unpushed(project, bundle);
|
||||
var versions = project.Versions();
|
||||
var locals = Unpushed(versions, 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);
|
||||
if (hash == tipHash || SameAsTip(project, bundle, locals, portable, media)) return null;
|
||||
if (hash == tipHash || SameAsTip(versions, bundle, locals, portable, media)) return null;
|
||||
var sync = project.ReadSync();
|
||||
// A restore taken back since (Undo, Ctrl+Z) no longer shows in the working state: that version is no restore.
|
||||
var restoredFrom = sync.RestoredFrom is { } restored && StillRestores(project, restored, Tip(project, bundle, locals), portable, media?.Photos ?? NoFrames)
|
||||
@@ -956,40 +1080,41 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
/// Where the project stands. With a <paramref name="home"/>, the media first learn how it names its photos now (a photo
|
||||
/// hashed or converted there since the copy, <see cref="WorkspaceMedia.NamedAsAt"/>), so a version the home made since
|
||||
/// and the working state name each photo alike: written at once while the project's lease is held
|
||||
/// (<paramref name="leased"/>), else when it can be taken without waiting (<see cref="WorkspaceStatus.MediaOutdated"/>
|
||||
/// when it cannot).
|
||||
/// (<paramref name="leased"/>), else when it can be taken now or after a moment (<see cref="WorkspaceStatus.MediaOutdated"/>
|
||||
/// when it cannot). The home's frames are read again only when its stamp of them moved (<see cref="IProjectHome.FramesStampAsync"/>).
|
||||
/// 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 <see cref="WorkspaceState.Gone"/>.
|
||||
/// </summary>
|
||||
private async Task<WorkspaceStatus> StatusLockedAsync(WorkspaceProject project, IProjectHome? home, CancellationToken cancellationToken, bool leased = true)
|
||||
{
|
||||
var bundle = project.ReadBundle();
|
||||
var local = ReadLocal(project);
|
||||
if (local.Damaged > 0 && !leased) local = await ConfirmDamagedAsync(project, local, cancellationToken).ConfigureAwait(false);
|
||||
var (bundle, media, sync, versions, locals, damaged) = local;
|
||||
var workspace = bundle.Workspace!;
|
||||
WorkspaceMedia? media;
|
||||
try
|
||||
{
|
||||
media = project.ReadMedia();
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
media = null;
|
||||
}
|
||||
var sync = project.ReadSync();
|
||||
var conflict = sync.Conflict;
|
||||
var locals = Unpushed(project, bundle);
|
||||
var damaged = Gaps(project, bundle, locals, sync).Count;
|
||||
// A take of the server's values (or any replay that settles) cut past its commit point applied the choice: the
|
||||
// conflict is over, as the next sync writes.
|
||||
var conflict = sync.Replay is { Settles: true } replay && workspace.Base?.VersionId == replay.OntoBase ? null : sync.Conflict;
|
||||
ProjectVersion? head = null;
|
||||
HomeFrames? frames = null;
|
||||
var offline = false;
|
||||
var gone = false;
|
||||
if (home is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
head = await home.HeadAsync(project.ProjectId, cancellationToken).ConfigureAwait(false);
|
||||
if (media is not null) frames = await home.FramesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (media is not null) frames = await FramesOfAsync(home, workspace.Home, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (HomeUnavailableException)
|
||||
{
|
||||
offline = true;
|
||||
}
|
||||
catch (ProjectException ex) when (ex.Reason is ProjectError.NotFound or ProjectError.SequenceNotFound)
|
||||
{
|
||||
ReportGone(project, ex);
|
||||
(gone, offline) = (true, true);
|
||||
}
|
||||
}
|
||||
var outdated = false;
|
||||
if (media is not null && frames is not null)
|
||||
@@ -1001,11 +1126,12 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
}
|
||||
var tipHash = locals.Count > 0 ? locals[^1].ContentHash : workspace.Base?.ContentHash;
|
||||
var modified = !bundle.IsReadOnly && (Portable(bundle.Project, media) is not { } portable
|
||||
|| (ProjectContent.Hash(portable) != tipHash && !SameAsTip(project, bundle, locals, portable, media)));
|
||||
|| (ProjectContent.Hash(portable) != tipHash && !SameAsTip(versions, bundle, locals, portable, media)));
|
||||
var behind = head is not null && head.Id != workspace.Base?.VersionId ? Math.Max(1, head.Number - (workspace.Base?.Number ?? 0)) : 0;
|
||||
// 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
|
||||
var state = gone ? WorkspaceState.Gone
|
||||
: media is null ? WorkspaceState.MediaRemoved
|
||||
: damaged > 0 ? WorkspaceState.Damaged
|
||||
: conflict is not null ? WorkspaceState.Conflict
|
||||
: offline ? WorkspaceState.Offline
|
||||
@@ -1020,17 +1146,137 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>What the workspace holds of a project, read once: its working state, media, sync state and versions.</summary>
|
||||
private sealed record LocalState(ProjectBundle Bundle, WorkspaceMedia? Media, WorkspaceSyncState Sync, IReadOnlyList<ProjectVersion> Versions,
|
||||
List<ProjectVersion> Locals, int Damaged);
|
||||
|
||||
private static LocalState ReadLocal(WorkspaceProject project)
|
||||
{
|
||||
var bundle = project.ReadBundle();
|
||||
WorkspaceMedia? media;
|
||||
try
|
||||
{
|
||||
media = project.ReadMedia();
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
media = null;
|
||||
}
|
||||
var sync = project.ReadSync();
|
||||
var (versions, unreadable) = project.ReadVersionFiles();
|
||||
var locals = Unpushed(versions, bundle);
|
||||
return new LocalState(bundle, media, sync, versions, locals, Gaps(project, bundle, locals, sync, versions, unreadable).Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A state read without the lease that found damaged versions, read again under it (taken without waiting): what that
|
||||
/// read finds. While another operation holds the project its writes may be half done, so nothing is reported damaged.
|
||||
/// </summary>
|
||||
private static async Task<LocalState> ConfirmDamagedAsync(WorkspaceProject project, LocalState local, CancellationToken cancellationToken)
|
||||
{
|
||||
IDisposable lease;
|
||||
try
|
||||
{
|
||||
lease = await project.LockAsync(TimeSpan.Zero, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (LeaseUnavailableException)
|
||||
{
|
||||
Log.Debug("workspace", $"Project {project.ProjectId} reads as damaged while another operation holds it: not reported yet");
|
||||
return local with { Damaged = 0 };
|
||||
}
|
||||
using (lease) return ReadLocal(project);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The home's frames: read again only when the home's stamp of them moved since they were last read for that home
|
||||
/// (<see cref="IProjectHome.FramesStampAsync"/>), else those read then; always read from a home that keeps no stamp.
|
||||
/// </summary>
|
||||
private async Task<HomeFrames> FramesOfAsync(IProjectHome home, BundleHome key, CancellationToken cancellationToken)
|
||||
{
|
||||
var stamp = await home.FramesStampAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (stamp is not null && _frames.TryGetValue(key, out var known) && known.Stamp == stamp) return known.Frames;
|
||||
var frames = await home.FramesAsync(cancellationToken).ConfigureAwait(false);
|
||||
// Read after the stamp: these frames are at least as new as it, so a stamp moved meanwhile reads them again next time.
|
||||
if (stamp is not null) _frames[key] = (stamp, frames);
|
||||
return frames;
|
||||
}
|
||||
|
||||
/// <summary>The homes' frames last read by a status, by home, with the stamp they were read at.</summary>
|
||||
private readonly System.Collections.Concurrent.ConcurrentDictionary<BundleHome, (string Stamp, HomeFrames Frames)> _frames = new();
|
||||
|
||||
/// <summary>The projects whose home answered it no longer has them, each logged once.</summary>
|
||||
private readonly System.Collections.Concurrent.ConcurrentDictionary<Guid, byte> _gone = new();
|
||||
|
||||
private void ReportGone(WorkspaceProject project, ProjectException ex)
|
||||
{
|
||||
if (_gone.TryAdd(project.ProjectId, 0))
|
||||
Log.Info("workspace", $"The home no longer has project {project.ProjectId}: its copy here is kept as it is, with its versions ({ex.Message})");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// After <paramref name="ex"/> (a project or version the home does not know) stopped a sync: whether the home no longer
|
||||
/// has the project itself (deleted there, or its sequence gone), which is no failure to retry but the state the project is
|
||||
/// in. False when the home still has it (the version alone was not found) or cannot be asked now.
|
||||
/// </summary>
|
||||
private async Task<bool> GoneAsync(WorkspaceProject project, IProjectHome home, ProjectException ex, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await home.HeadAsync(project.ProjectId, cancellationToken).ConfigureAwait(false);
|
||||
return false;
|
||||
}
|
||||
catch (ProjectException gone) when (gone.Reason is ProjectError.NotFound or ProjectError.SequenceNotFound)
|
||||
{
|
||||
ReportGone(project, ex);
|
||||
return true;
|
||||
}
|
||||
catch (HomeUnavailableException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <c>versions/.replaced</c> pruned after a sync that ended well (<see cref="WorkspaceProject.PruneReplaced"/>): never a
|
||||
/// version the sync state still names (a journal, a conflict, a restore). A file that cannot go waits for the next one.
|
||||
/// </summary>
|
||||
private static void PruneReplaced(WorkspaceProject project)
|
||||
{
|
||||
var sync = project.ReadSync();
|
||||
var referenced = new HashSet<Guid>();
|
||||
if (sync.Replay is { } replay) referenced.UnionWith([.. replay.Replaced, .. replay.Replayed, .. replay.Adopted, replay.OntoBase]);
|
||||
if (sync.SaveBoth is { } both) referenced.UnionWith([.. both.Moves.Select(m => m.LocalId), .. both.Moves.Select(m => m.CopyVersionId)]);
|
||||
if (sync.Conflict is { } conflict) referenced.UnionWith([.. conflict.Mine, conflict.TheirsVersionId, conflict.BaseVersionId]);
|
||||
if (sync.RestoredFrom is { } restored) referenced.Add(restored);
|
||||
var removed = project.PruneReplaced(referenced, DateTime.UtcNow);
|
||||
if (removed > 0) Log.Info("workspace", $"{removed} old file(s) of project {project.ProjectId} left versions/.replaced");
|
||||
}
|
||||
|
||||
/// <summary>Whether a sync stopped because the home does not know a project or a version (<see cref="GoneAsync"/> tells which).</summary>
|
||||
private static bool NotFoundAtHome(ProjectException ex) => ex.Reason is ProjectError.NotFound or ProjectError.SequenceNotFound;
|
||||
|
||||
/// <summary>
|
||||
/// Writes the media with the photos named as <paramref name="frames"/> name them (read again under the lease: a copy
|
||||
/// may have written new media meanwhile); without <paramref name="leased"/>, only when the lease is free now. Whether
|
||||
/// the media know the home's names.
|
||||
/// may have written new media meanwhile); without <paramref name="leased"/>, only when the lease can be taken now or,
|
||||
/// tried once more, after a moment (<see cref="LearnWait"/>). Whether the media know the home's names.
|
||||
/// </summary>
|
||||
private async Task<bool> LearnNamesAsync(WorkspaceProject project, HomeFrames frames, bool leased, CancellationToken cancellationToken)
|
||||
{
|
||||
IDisposable? lease = null;
|
||||
try
|
||||
{
|
||||
if (!leased) lease = await project.LockAsync(TimeSpan.Zero, cancellationToken).ConfigureAwait(false);
|
||||
if (!leased)
|
||||
{
|
||||
try
|
||||
{
|
||||
lease = await project.LockAsync(TimeSpan.Zero, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (LeaseUnavailableException)
|
||||
{
|
||||
// Two reads of the state at once (the picker and the menu), or a copy's commit: held only for a moment.
|
||||
lease = await project.LockAsync(LearnWait, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
if (project.ReadMedia() is not { } media) return false;
|
||||
var named = media.NamedAsAt(frames);
|
||||
if (!ReferenceEquals(named, media)) project.WriteMedia(named);
|
||||
@@ -1046,20 +1292,30 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>How long a status read waits, the second time, for the lease to teach the media the home's names.</summary>
|
||||
private static readonly TimeSpan LearnWait = TimeSpan.FromMilliseconds(500);
|
||||
|
||||
/// <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.
|
||||
/// (their journals, which the next sync settles) are not counted. The files are read once.
|
||||
/// </summary>
|
||||
private static List<string> Gaps(WorkspaceProject project, ProjectBundle bundle, IReadOnlyList<ProjectVersion> chain, WorkspaceSyncState sync)
|
||||
{
|
||||
var (versions, unreadable) = project.ReadVersionFiles();
|
||||
return Gaps(project, bundle, chain, sync, versions, unreadable);
|
||||
}
|
||||
|
||||
private static List<string> Gaps(WorkspaceProject project, ProjectBundle bundle, IReadOnlyList<ProjectVersion> chain, WorkspaceSyncState sync,
|
||||
IReadOnlyList<ProjectVersion> versions, IReadOnlyList<UnreadableVersion> unreadable)
|
||||
{
|
||||
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))
|
||||
var gaps = unreadable.Where(u => u.Number > after && !reached.Contains(u.Id)).Select(u => u.Path).ToList();
|
||||
gaps.AddRange(versions.Where(v => v.StoredAt is null && v.Number > after && v.Id != basis?.VersionId && !reached.Contains(v.Id))
|
||||
.Select(project.VersionPath));
|
||||
return gaps;
|
||||
}
|
||||
@@ -1082,15 +1338,19 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
/// once each names its photos as the media hold them now: a version saved before the media were copied again after a
|
||||
/// conversion or a hash at the home parks the same photos under their former names.
|
||||
/// </summary>
|
||||
private static bool SameAsTip(WorkspaceProject project, ProjectBundle bundle, List<ProjectVersion> locals, string portable, WorkspaceMedia? media)
|
||||
private static bool SameAsTip(IReadOnlyList<ProjectVersion> versions, ProjectBundle bundle, List<ProjectVersion> locals, string portable, WorkspaceMedia? media)
|
||||
{
|
||||
if (media is null) return false;
|
||||
return Tip(project, bundle, locals) is { } tip && ProjectContent.SameChoices(tip.SettingsJson, portable, media.Photos);
|
||||
return Tip(versions, bundle, locals) is { } tip && ProjectContent.SameChoices(tip.SettingsJson, portable, media.Photos);
|
||||
}
|
||||
|
||||
/// <summary>The last version: the newest local one, else the base (null when this workspace keeps neither).</summary>
|
||||
private static ProjectVersion? Tip(WorkspaceProject project, ProjectBundle bundle, List<ProjectVersion> locals) =>
|
||||
locals.Count > 0 ? locals[^1] : bundle.Workspace!.Base is { } basis ? project.Versions().FirstOrDefault(v => v.Id == basis.VersionId) : null;
|
||||
locals.Count > 0 ? locals[^1] : Tip(project.Versions(), bundle, locals);
|
||||
|
||||
/// <summary>The last version among <paramref name="versions"/> (the workspace's, read once).</summary>
|
||||
private static ProjectVersion? Tip(IReadOnlyList<ProjectVersion> versions, ProjectBundle bundle, List<ProjectVersion> locals) =>
|
||||
locals.Count > 0 ? locals[^1] : bundle.Workspace!.Base is { } basis ? versions.FirstOrDefault(v => v.Id == basis.VersionId) : null;
|
||||
|
||||
/// <summary>
|
||||
/// Whether the working state <paramref name="portable"/>, saved as a version on <paramref name="parent"/>, still restores
|
||||
@@ -1125,10 +1385,13 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
shown.Count == found.Count && shown.ToHashSet().SetEquals(found);
|
||||
|
||||
/// <summary>The local versions after the base, oldest first, each the child of the one before (the base's for the first).</summary>
|
||||
private static List<ProjectVersion> Unpushed(WorkspaceProject project, ProjectBundle bundle)
|
||||
private static List<ProjectVersion> Unpushed(WorkspaceProject project, ProjectBundle bundle) => Unpushed(project.Versions(), bundle);
|
||||
|
||||
/// <summary>The local versions after the base among <paramref name="versions"/> (the workspace's, read once).</summary>
|
||||
private static List<ProjectVersion> Unpushed(IReadOnlyList<ProjectVersion> versions, ProjectBundle bundle)
|
||||
{
|
||||
var basis = bundle.Workspace!.Base;
|
||||
var candidates = project.Versions().Where(v => v.StoredAt is null && v.Number > (basis?.Number ?? 0)).ToList();
|
||||
var candidates = versions.Where(v => v.StoredAt is null && v.Number > (basis?.Number ?? 0)).ToList();
|
||||
var chain = new List<ProjectVersion>();
|
||||
var parent = basis?.VersionId;
|
||||
while (candidates.FirstOrDefault(v => v.ParentId == parent) is { } next)
|
||||
|
||||
Reference in new issue
Block a user