fix(workspace): phase 5a fix round 2, workspace sync and copy

A Save both, a recorded conflict and a damaged version file could each leave
a local version out of the chain or a copy half-made at the home. This round
makes every one of these end with nothing lost and nothing half done.

- Save both retry: a journaled copy somebody else sent a version to (or one
  deleted since) is left as it is, and a new copy takes every local version.
  A divergence met at the copy while sending also makes a new copy, once.
- Keep mine, Take server, or a pull that settles a conflict after a Save both
  was cut short first send the rest of the journaled versions to that copy,
  if it is still this workspace's. The journal is cleared at the commit point.
- A conflict of format met past local versions the home already stored
  (their answer lost) now moves the base onto them, like any other conflict.
  The conflict, the base and the chain then name one version. A save-both
  journal follows the base when it moves.
- A conflict recorded before stays while the home holds no version after
  the base. A base that has reached the conflict's head clears it.
- Take server no longer replays or sends the version it saves first when,
  replayed, that version holds only the server's values. It stays in
  versions/.replaced for the undo. The test checks the exact history again.
- Version files after the base that cannot be read, or that do not follow
  from it, are listed (WorkspaceProject.UnreadableVersions). The new state
  WorkspaceState.Damaged shows them. Commit, push, pull and resolve refuse to
  go past them. A damaged file whose version the home holds takes the home's
  copy at the next sync, and the damaged file is kept aside. Remove local
  copy counts these files as unsent.
- PushOutcome.TooLarge raises its own WorkspaceSyncException message. The
  desktop says Errors.Workspace.VersionTooLarge for it and for
  ProjectVersionTooLargeException when a local commit is too large.
- The editor maps LeaseUnavailableException from opening a busy project to
  Errors.Workspace.Busy.
- The copy job no longer deletes, during the pass, a proxy that the editor's
  current media name. RemoveStale removes it after the commit. A resumed run
  does not keep such a file as a frame whose photo changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-03 11:31:18 +01:00
1 parent 8256b72913
commit e23cba3ee1
18 files changed
+646 -88

No files matched your search

@@ -105,7 +105,10 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
public event Action<Job>? JobChanged;
/// <exception cref="EditorException">The workspace holds no media for the project (copy them again), or the project is gone.</exception>
/// <exception cref="EditorException">
/// The workspace holds no media for the project (copy them again), the project is gone, or a sync or a copy kept it for
/// longer than the sync waits (<see cref="WorkspaceSync.LockWait"/>).
/// </exception>
public async Task<SequenceContent> LoadAsync(CancellationToken cancellationToken)
{
WorkspaceSession session;
@@ -121,6 +124,12 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
{
throw new EditorException(Loc.L("Editor.Error.Project"), ex);
}
catch (LeaseUnavailableException ex)
{
// A long sync or copy holds the project: nothing was read, opening it again later reads it whole.
Log.Info("editor", $"Workspace project {ProjectId} is busy: {ex.Message}");
throw new EditorException(Loc.L("Errors.Workspace.Busy"), ex);
}
if (session is not { Sequence: { } media, Media: { } index }) throw new EditorException(Loc.L("Errors.Workspace.MediaMissing"));
var home = session.Bundle.Workspace!.Home;
var row = await _db.Sequences.GetAsync(home.SequenceId, cancellationToken);
+2 -1
View File
@@ -47,7 +47,8 @@ public static class ErrorText
// A template an archive refused (Settings › Archive, or this PC's templates for a new archive): the rule it breaks.
TemplateRuleException rule => Loc.L("Errors.Template." + rule.Rule),
// The workspace (owner review 2, R8): its own sentences, a home out of reach, a project the home refused.
Workspace.WorkspaceException or HomeUnavailableException or ProjectException or WorkspaceSyncException => Workspace.WorkspaceText.Failure(ex),
Workspace.WorkspaceException or HomeUnavailableException or ProjectException or WorkspaceSyncException or ProjectVersionTooLargeException =>
Workspace.WorkspaceText.Failure(ex),
// The server words its errors in the client's language (Accept-Language).
ChronosApiException api when FromServer(api.Error) => api.Error.Message,
// Any other reply (a reverse proxy's 502 page while the server restarts, its 413 for a large body, a bare 500) holds
@@ -617,6 +617,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
var status = local with { Behind = behind, Offline = last.Offline, HomeHead = last.HomeHead };
var state = gone ? WorkspaceState.Gone
: status.MediaRemoved ? WorkspaceState.MediaRemoved
: status.Damaged > 0 ? WorkspaceState.Damaged
: status.Conflict is not null ? WorkspaceState.Conflict
: status.Offline ? WorkspaceState.Offline
: status.Behind > 0 ? WorkspaceState.Behind
+5 -3
View File
@@ -267,7 +267,7 @@ public sealed class WorkspaceHost
return local with
{
Offline = true,
State = local.State is WorkspaceState.MediaRemoved or WorkspaceState.Conflict && !gone ? local.State
State = local.State is WorkspaceState.MediaRemoved or WorkspaceState.Damaged or WorkspaceState.Conflict && !gone ? local.State
: gone ? WorkspaceState.Gone
: WorkspaceState.Offline,
};
@@ -508,7 +508,7 @@ public sealed class WorkspaceHost
var name = project.ReadBundle().Workspace!.Name;
var status = await StatusAsync(projectId, cancellationToken: cancellationToken).ConfigureAwait(false);
var (files, bytes) = Measure(project.Folder);
return new WorkspaceRemovalPlan(projectId, name, files, bytes, status.Ahead, status.Modified, status.Conflict is not null, status.Offline,
return new WorkspaceRemovalPlan(projectId, name, files, bytes, status.Ahead + status.Damaged, status.Modified, status.Conflict is not null, status.Offline,
status.State == WorkspaceState.Gone);
}, cancellationToken);
@@ -528,7 +528,9 @@ public sealed class WorkspaceHost
if (!discard)
{
var status = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly) || status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
// A version saved here that cannot be read may be one the home never had: only discarding keeps it aside.
if (status.Ahead > 0 || status.Damaged > 0 || (status.Modified && !status.ReadOnly) || status.Conflict is not null)
throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
await VerifyHomeAsync(projectId, workspace, cancellationToken).ConfigureAwait(false);
}
await RemoveFolderAsync(project, cancellationToken).ConfigureAwait(false);
@@ -32,6 +32,7 @@ public static class WorkspaceText
WorkspaceState.Offline => StatusKind.Offline,
WorkspaceState.MediaRemoved => StatusKind.NoProxies,
WorkspaceState.Gone => StatusKind.Warning,
WorkspaceState.Damaged => StatusKind.Error,
_ => StatusKind.Queued,
};
@@ -88,6 +89,9 @@ public static class WorkspaceText
ProjectException { Reason: ProjectError.InvalidName } => Loc.L("Errors.Workspace.InvalidName"),
ProjectException { Reason: ProjectError.MainCannotBeDeleted } => Loc.L("Errors.Workspace.MainKept"),
ProjectException => Loc.L("Errors.Workspace.ProjectGone"),
// A version over the size one may be: saved here (refused before anything was written) or sent (the home stored nothing).
ProjectVersionTooLargeException or WorkspaceSyncException { Outcome: PushOutcome.TooLarge } =>
Loc.L("Errors.Workspace.VersionTooLarge", ProjectSidecars.MaxVersionBytes >> 20),
WorkspaceSyncException => Loc.L("Errors.Workspace.Refused"),
InvalidDataException => Loc.L("Errors.Workspace.Damaged"),
Editor.EditorException => ex.Message,
@@ -114,6 +114,8 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
var total = (long)frames.Count;
var tally = new Tally();
var entries = new WorkspaceFrame[frames.Count];
// The media the editor reads until this copy commits: their files stay until then (RemoveStale).
var current = TryReadMedia(project)?.Frames.Where(f => f.File is not null).ToDictionary(f => f.Id) ?? [];
Directory.CreateDirectory(project.ProxiesDirectory);
// The workspace is on this PC's own drive, with the index, the settings and the logs: the copy never fills it.
var remaining = Remaining(project, folder, frames, policy);
@@ -122,7 +124,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
for (var i = 0; i < frames.Count; i++)
{
ct.ThrowIfCancellationRequested();
entries[i] = Copy(project, folder, paths, frames[i], policy, done: i < copied, tally, ct);
entries[i] = Copy(project, folder, paths, frames[i], policy, done: i < copied, current.GetValueOrDefault(frames[i].Id), tally, ct);
if (clock.Elapsed >= CheckpointEvery)
{
await context.CheckpointAsync(Checkpoint(Stage.Copy, i + 1, row.FramesVersion, row.Folder), i + 1, total).ConfigureAwait(false);
@@ -205,17 +207,26 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
/// <summary>
/// The frame's file in the workspace: kept when an earlier run copied it (before the checkpoint, or the same bytes as the
/// archive's proxy), else the archive's current proxy, else one made from the original; none for a frame without either.
/// The file the media the editor reads now name for the frame (<paramref name="current"/>) is never removed here: the
/// editor keeps it while the copy runs and if it fails, and a copy that commits without it removes it then
/// (<see cref="RemoveStale"/>). Nor is it taken as this run's copy of a frame whose photo changed since.
/// </summary>
private WorkspaceFrame Copy(WorkspaceProject project, SequencePaths folder, ArchivePaths paths, Frame frame, ProxyPolicy policy, bool done, Tally tally,
CancellationToken cancellationToken)
private WorkspaceFrame Copy(WorkspaceProject project, SequencePaths folder, ArchivePaths paths, Frame frame, ProxyPolicy policy, bool done,
WorkspaceFrame? current, Tally tally, CancellationToken cancellationToken)
{
var name = WorkspaceProject.ProxyName(frame.Id);
var target = project.MediaFile(name);
var listed = current is not null && string.Equals(current.File, name, StringComparison.OrdinalIgnoreCase);
if (done && File.Exists(target))
{
tally.Kept++;
var kept = AtomicFile.ReadAllBytes(target);
return WorkspaceFrame.Of(frame, name, Sha(kept), kept.Length);
var keptSha = Sha(kept);
// The editor's file of another photo of the frame (a conversion since) was left by an earlier copy, not this run.
if (!listed || keptSha != current!.FileSha256 || SamePhoto(current, frame))
{
tally.Kept++;
return WorkspaceFrame.Of(frame, name, keptSha, kept.Length);
}
}
var source = folder.Proxy(frame.Index);
byte[]? bytes = null;
@@ -238,8 +249,8 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
if (bytes is null)
{
// A file an earlier copy left for the frame (of other frames, or another folder's) is never kept as its photo by a
// resumed run: a regenerable copy, it goes.
if (File.Exists(target)) TryDelete(target);
// resumed run: a regenerable copy, it goes, unless the editor's media name it (it goes once this copy commits).
if (!listed && File.Exists(target)) TryDelete(target);
tally.Missing++;
return WorkspaceFrame.Of(frame, null, null, 0);
}
@@ -321,6 +332,11 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
private static FramePhoto Photo(WorkspaceFrame frame) => new(frame.Sha256, frame.Size, frame.CapturedAt);
/// <summary>Whether the media's entry of a frame is of the photo the frame holds now (a conversion gives it another file).</summary>
private static bool SamePhoto(WorkspaceFrame held, Frame frame) =>
held.Size == frame.Size && held.CapturedAt == frame.CapturedAt
&& (string.IsNullOrEmpty(held.Sha256) || string.IsNullOrEmpty(frame.Sha256) || string.Equals(held.Sha256, frame.Sha256, StringComparison.OrdinalIgnoreCase));
/// <summary>Proxies of frames the sequence no longer has: regenerable copies, removed so the media folder holds the frames listed.</summary>
private static void RemoveStale(WorkspaceProject project, WorkspaceMedia media)
{
+34 -7
View File
@@ -48,6 +48,9 @@ public sealed record WorkspaceSaveBoth(Guid CopyId, Guid CopyBaseId, int CopyBas
/// <summary>A local version (<paramref name="LocalId"/>) and the id it is sent under to a save-both's copy.</summary>
public sealed record WorkspaceMove(Guid LocalId, Guid CopyVersionId);
/// <summary>A version file of a workspace that cannot be read (<see cref="WorkspaceProject.UnreadableVersions"/>): the number and id its name carries, and why.</summary>
public sealed record UnreadableVersion(int Number, Guid Id, string Path, string Reason);
/// <summary>
/// A pull or push that met real conflicts (owner review 2, R8): the home's head it met, the version the local commits were
/// made from, the local commits (oldest first) and the members both sides changed (mine, theirs). Settled by keeping mine,
@@ -342,11 +345,24 @@ public sealed class WorkspaceProject
AtomicFile.WriteAllText(MediaIndexPath, JsonSerializer.Serialize(media, WorkspaceJson.Default.WorkspaceMedia));
}
/// <summary>The versions this workspace holds, oldest first; one that cannot be read is left out (and logged).</summary>
public IReadOnlyList<ProjectVersion> Versions()
/// <summary>
/// The versions this workspace holds, oldest first. One that cannot be read is left out here, logged, and listed by
/// <see cref="UnreadableVersions"/>: the sync treats one above the base as a gap in the chain of versions to send, never
/// as a version that is not there (<see cref="WorkspaceSync"/>).
/// </summary>
public IReadOnlyList<ProjectVersion> Versions() => ReadVersions(log: true).Versions;
/// <summary>
/// The version files of the workspace that cannot be read now (damaged, held open, over the size a version may be, of
/// a newer Chronos), by the number and id their names carry, oldest first.
/// </summary>
public IReadOnlyList<UnreadableVersion> UnreadableVersions() => ReadVersions(log: false).Unreadable;
private (List<ProjectVersion> Versions, List<UnreadableVersion> Unreadable) ReadVersions(bool log)
{
var versions = new List<ProjectVersion>();
foreach (var (_, _, path) in ProjectSidecars.ListVersions(VersionsDirectory))
var unreadable = new List<UnreadableVersion>();
foreach (var (number, id, path) in ProjectSidecars.ListVersions(VersionsDirectory))
{
try
{
@@ -355,12 +371,21 @@ public sealed class WorkspaceProject
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Warning("workspace", $"Version file {path} cannot be read", ex);
// Said once per file as it is now: every sync step lists the versions again.
if (log && (!Reported.TryGetValue(path, out var said) || said != ex.Message))
{
Reported[path] = ex.Message;
Log.Warning("workspace", $"Version file {path} cannot be read", ex);
}
unreadable.Add(new UnreadableVersion(number, id, path, ex.Message));
}
}
return versions;
return (versions, unreadable);
}
/// <summary>The version files whose read failure was logged, with why (logged again when the reason changes).</summary>
private static readonly System.Collections.Concurrent.ConcurrentDictionary<string, string> Reported = new(StringComparer.Ordinal);
/// <summary>The path of a version in <see cref="VersionsDirectory"/>.</summary>
public string VersionPath(ProjectVersion version) => Path.Combine(VersionsDirectory, ArchiveLayout.ProjectVersionFileName(version.Number, version.Id));
@@ -370,9 +395,11 @@ public sealed class WorkspaceProject
/// Moves a version file aside into <c>versions/.replaced</c> (a local commit replayed under another id), trying again
/// for a moment while another program (an indexer, an antivirus) holds it open.
/// </summary>
internal void SetAside(ProjectVersion version)
internal void SetAside(ProjectVersion version) => SetAside(VersionPath(version));
/// <summary>Moves the version file at <paramref name="path"/> aside into <c>versions/.replaced</c> (see <see cref="SetAside(ProjectVersion)"/>).</summary>
internal void SetAside(string path)
{
var path = VersionPath(version);
if (!File.Exists(path)) return;
var aside = Path.Combine(VersionsDirectory, ReplacedFolder);
Directory.CreateDirectory(aside);
+257 -66
View File
@@ -37,6 +37,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>
@@ -46,7 +53,11 @@ public enum WorkspaceState
/// <param name="Base">The home's version the project was last in step with.</param>
/// <param name="HomeHead">The home's newest version, when it was asked.</param>
public sealed record WorkspaceStatus(WorkspaceState State, bool Modified, int Ahead, int Behind, bool Offline, bool MediaRemoved, bool ReadOnly,
WorkspaceConflict? Conflict, BundleBase? Base, ProjectVersion? HomeHead);
WorkspaceConflict? Conflict, BundleBase? Base, ProjectVersion? HomeHead)
{
/// <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>
/// <param name="SavedAs">After <see cref="ConflictChoice.SaveBoth"/>: the new project at the home holding this workspace's versions.</param>
@@ -83,7 +94,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;
@@ -108,7 +122,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)
{
@@ -241,7 +257,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)
@@ -261,7 +279,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;
}
@@ -290,6 +308,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);
@@ -310,8 +329,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.
@@ -328,13 +350,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)
{
@@ -400,19 +424,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; ;)
@@ -427,7 +455,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();
@@ -439,13 +467,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));
@@ -467,42 +490,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");
@@ -515,12 +532,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
@@ -542,28 +594,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).");
@@ -591,10 +652,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)
@@ -649,7 +725,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)
{
@@ -657,18 +735,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);
@@ -677,23 +751,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).
@@ -710,6 +785,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)
{
@@ -736,6 +888,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);
@@ -780,8 +934,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;
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)));
@@ -802,13 +958,48 @@ 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
: locals.Count > 0 ? WorkspaceState.Ahead
: modified ? WorkspaceState.Modified
: WorkspaceState.InSync;
return new WorkspaceStatus(state, modified, locals.Count, behind, offline, media is null, bundle.IsReadOnly, conflict, workspace.Base, head);
return new WorkspaceStatus(state, modified, locals.Count, behind, offline, media is null, bundle.IsReadOnly, conflict, workspace.Base, head)
{
Damaged = damaged,
};
}
/// <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>