merge: review2-p5a-fix-merge into phase 5a fix round 1 integration
This commit is contained in:
commit
6542562428
12 files changed
+905
-38
No files matched your search
@@ -1,3 +1,6 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Chronos.Core.Project;
|
||||
|
||||
/// <summary>
|
||||
@@ -24,6 +27,13 @@ public sealed record Auto<T>
|
||||
|
||||
public IReadOnlyList<string>? ReasonArgs { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Members this Chronos does not know (written by a newer one, such as the advisor's confidence): kept as they are, so
|
||||
/// they survive a round trip and every edit of the parameter (owner review 2, R8).
|
||||
/// </summary>
|
||||
[JsonExtensionData]
|
||||
public Dictionary<string, JsonElement>? Extra { get; set; }
|
||||
|
||||
/// <summary>The value in force: manual when set by the user, otherwise the advisor's, otherwise <paramref name="fallback"/>.</summary>
|
||||
public T Resolve(T fallback) => !IsAuto && Manual is not null ? Manual : HasAdvice && AutoValue is not null ? AutoValue : fallback;
|
||||
|
||||
|
||||
@@ -55,7 +55,8 @@ public sealed class FramePhotos
|
||||
public FramePhotos(IEnumerable<(int Index, FramePhoto Photo)> frames, IEnumerable<PhotoAlias>? aliases)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(frames);
|
||||
_canonical = PhotoAlias.Classes(aliases);
|
||||
Aliases = aliases is null ? [] : [.. aliases.Where(a => a is not null)];
|
||||
_canonical = PhotoAlias.Classes(Aliases);
|
||||
var list = frames.Where(f => f.Index >= 0).ToList();
|
||||
_byIndex = new FramePhoto?[list.Count == 0 ? 0 : list.Max(f => f.Index) + 1];
|
||||
foreach (var (index, photo) in list) _byIndex[index] = photo;
|
||||
@@ -82,6 +83,9 @@ public sealed class FramePhotos
|
||||
|
||||
public int Count => _byIndex.Length;
|
||||
|
||||
/// <summary>The links between encodings of one photo these frames were given (empty without any): another copy's frames can take them.</summary>
|
||||
public IReadOnlyList<PhotoAlias> Aliases { get; }
|
||||
|
||||
/// <summary>The photo at <paramref name="index"/>; null when no frame has that index.</summary>
|
||||
public FramePhoto? this[int index] => (uint)index < (uint)_byIndex.Length ? _byIndex[index] : null;
|
||||
|
||||
|
||||
@@ -57,9 +57,12 @@ public static class ProjectContent
|
||||
/// <summary>
|
||||
/// The portable text with each pending frame whose photo <paramref name="frames"/> hold named as they hold it now: an
|
||||
/// encoding a conversion replaced by the one the frame holds (<see cref="PhotoAlias"/>, also its undo), a photo parked
|
||||
/// before it was hashed by its SHA-256, size and capture time. The same choices on the same photos then read as the same
|
||||
/// text (<see cref="SameChoices"/>), whichever encoding or hashing state they were saved against; a placement finds the
|
||||
/// same frames either way. Canonical when anything is renamed; the text as it is otherwise, and for a newer format.
|
||||
/// before it was hashed by its SHA-256, size and capture time, and which copy of that photo it is among the frames
|
||||
/// holding it under that name (a photo of a burst told apart by its order while unhashed is unique once hashed). Entries
|
||||
/// that name one photo once renamed become one (<see cref="Fold"/>). The same choices on the same photos then read as
|
||||
/// the same text (<see cref="SameChoices"/>), whichever encoding or hashing state they were saved against; a placement
|
||||
/// finds the same frames either way. Canonical when anything is renamed or folded; the text as it is otherwise, and for
|
||||
/// a newer format.
|
||||
/// </summary>
|
||||
/// <exception cref="JsonException">The text is not a project object.</exception>
|
||||
public static string Rebind(string portableJson, FramePhotos frames)
|
||||
@@ -80,19 +83,90 @@ public static class ProjectContent
|
||||
var occurrence = entry["occurrence"] is JsonValue o && o.TryGetValue<int>(out var n) && n > 0 ? n : 0;
|
||||
// Only a frame that is hashed names a photo better than the entry does.
|
||||
if (frames.IndexOf(new FramePhoto(sha, size, captured), occurrence) is not { } at || frames[at] is not { IsHashed: true } held) continue;
|
||||
// The copy a placement looks for under the new name: among the frames holding that SHA-256, not those of that size and time.
|
||||
var copy = frames.Occurrence(at);
|
||||
var sameTime = held.CapturedAt is { } heldAt
|
||||
? captured is { } entryAt && FramePhoto.Millisecond(heldAt) == FramePhoto.Millisecond(entryAt)
|
||||
: captured is null;
|
||||
if (string.Equals(held.Sha256, sha, StringComparison.OrdinalIgnoreCase) && held.Size == size && sameTime) continue;
|
||||
if (string.Equals(held.Sha256, sha, StringComparison.OrdinalIgnoreCase) && held.Size == size && sameTime && copy == occurrence) continue;
|
||||
entry["sha256"] = held.Sha256!.ToLowerInvariant();
|
||||
entry["size"] = held.Size;
|
||||
if (held.CapturedAt is { } heldTime) entry["capturedAt"] = heldTime;
|
||||
else entry.Remove("capturedAt");
|
||||
if (copy > 0) entry["occurrence"] = copy;
|
||||
else entry.Remove("occurrence");
|
||||
renamed = true;
|
||||
}
|
||||
renamed |= FoldAlike(pending);
|
||||
return renamed ? Canonical(project.ToJsonString()) : portableJson;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The photo a pending entry names and which copy of it: "sha:<sha-256>#<occurrence>", or
|
||||
/// "photo:<size>@<capture ticks>#<occurrence>" for a photo not hashed; null for an entry naming no photo.
|
||||
/// Entries of one key are one photo's positions (<see cref="Fold"/>).
|
||||
/// </summary>
|
||||
public static string? PhotoKey(JsonNode? entry)
|
||||
{
|
||||
if (entry is not JsonObject e) return null;
|
||||
var occurrence = e["occurrence"] is JsonValue o && o.TryGetValue<int>(out var n) ? n : 0;
|
||||
if (e["sha256"] is JsonValue s && s.TryGetValue<string>(out var sha) && sha.Length > 0)
|
||||
return string.Create(CultureInfo.InvariantCulture, $"sha:{sha.ToLowerInvariant()}#{occurrence}");
|
||||
var size = e["size"] is JsonValue z && z.TryGetValue<long>(out var bytes) ? bytes : 0;
|
||||
return e["capturedAt"] is JsonValue c && c.TryGetValue<DateTime>(out var at)
|
||||
? string.Create(CultureInfo.InvariantCulture, $"photo:{size}@{at.Ticks}#{occurrence}")
|
||||
: null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Folds <paramref name="entry"/> into <paramref name="into"/>, two pending entries of one photo (saved under two names,
|
||||
/// alike since): excluded or hero when either is, the keyframes of both (each once), and the members this Chronos does not
|
||||
/// know of both (those of <paramref name="into"/> where both have one). Nothing either held is dropped.
|
||||
/// </summary>
|
||||
public static void Fold(JsonObject into, JsonObject entry)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(into);
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
if (Flag(entry, "excluded")) into["excluded"] = true;
|
||||
if (Flag(entry, "hero")) into["hero"] = true;
|
||||
if (entry["keyframes"] is JsonArray { Count: > 0 } keys)
|
||||
{
|
||||
if (into["keyframes"] is not JsonArray mine) into["keyframes"] = mine = new JsonArray();
|
||||
foreach (var key in keys.ToList())
|
||||
{
|
||||
if (!mine.Any(k => JsonNode.DeepEquals(k, key))) mine.Add(key?.DeepClone());
|
||||
}
|
||||
}
|
||||
foreach (var (name, value) in entry.ToList())
|
||||
{
|
||||
if (!ProjectSettings.PendingMembers.Contains(name) && !into.ContainsKey(name)) into[name] = value?.DeepClone();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Folds the pending entries naming one photo into the first of them (<see cref="Fold"/>); whether any were.</summary>
|
||||
private static bool FoldAlike(JsonArray pending)
|
||||
{
|
||||
var first = new Dictionary<string, JsonObject>(StringComparer.Ordinal);
|
||||
var folded = new List<JsonNode>();
|
||||
foreach (var entry in pending.OfType<JsonObject>())
|
||||
{
|
||||
if (PhotoKey(entry) is not { } key) continue;
|
||||
if (first.TryGetValue(key, out var into))
|
||||
{
|
||||
Fold(into, entry);
|
||||
folded.Add(entry);
|
||||
}
|
||||
else
|
||||
{
|
||||
first[key] = entry;
|
||||
}
|
||||
}
|
||||
foreach (var entry in folded) pending.Remove(entry);
|
||||
return folded.Count > 0;
|
||||
}
|
||||
|
||||
private static bool Flag(JsonObject entry, string name) => entry[name] is JsonValue value && value.TryGetValue<bool>(out var set) && set;
|
||||
|
||||
/// <summary>
|
||||
/// Whether two portable texts hold the same choices on the frames of <paramref name="frames"/>: the same text, or the
|
||||
/// same once their pending frames are named as the frames hold their photos now (<see cref="Rebind"/>).
|
||||
|
||||
@@ -44,10 +44,20 @@ public enum StackSetting
|
||||
}
|
||||
|
||||
/// <summary>A control point of the time-remap curve: output fraction → source fraction (both 0..1).</summary>
|
||||
public sealed record CurvePoint(double X, double Y);
|
||||
public sealed record CurvePoint(double X, double Y)
|
||||
{
|
||||
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
|
||||
[JsonExtensionData]
|
||||
public Dictionary<string, JsonElement>? Extra { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Virtual-camera keyframe in normalised coordinates.</summary>
|
||||
public sealed record CameraKey(int Frame, double CenterX, double CenterY, double Zoom, double Rotation, string Easing = "EaseInOut");
|
||||
public sealed record CameraKey(int Frame, double CenterX, double CenterY, double Zoom, double Rotation, string Easing = "EaseInOut")
|
||||
{
|
||||
/// <summary>Members this Chronos does not know (written by a newer one): kept as they are, so they survive a round trip.</summary>
|
||||
[JsonExtensionData]
|
||||
public Dictionary<string, JsonElement>? Extra { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The frame positions of a project that name a photo this copy of the sequence does not hold: settings taken from a
|
||||
@@ -564,14 +574,21 @@ public sealed record ProjectSettings
|
||||
return changed;
|
||||
}
|
||||
|
||||
/// <summary>Gives the pending frames whose photo <paramref name="to"/> holds their positions back.</summary>
|
||||
/// <summary>
|
||||
/// Gives the pending frames whose photo <paramref name="to"/> holds their positions back. An entry with members this
|
||||
/// Chronos does not know (a newer one's values of the photo) stays, without its positions: those members are not this
|
||||
/// Chronos's to drop, and the next portable form parks the positions in it again.
|
||||
/// </summary>
|
||||
private static bool PlacePending(JsonObject project, FramePhotos to, List<Parked> pending)
|
||||
{
|
||||
var changed = false;
|
||||
foreach (var parked in pending)
|
||||
{
|
||||
if (to.IndexOf(parked.Photo, parked.Occurrence) is not { } at) continue;
|
||||
parked.Placed = changed = true;
|
||||
var kept = HasUnknownMembers(parked.Entry);
|
||||
if (kept && !HoldsPosition(parked.Entry)) continue;
|
||||
parked.Placed = !kept;
|
||||
changed = true;
|
||||
if (Flag(parked.Entry, "excluded"))
|
||||
{
|
||||
if (project["excludedFrames"] is not JsonArray positions) project["excludedFrames"] = positions = new JsonArray();
|
||||
@@ -592,6 +609,12 @@ public sealed record ProjectSettings
|
||||
keyframes.Add(copy);
|
||||
}
|
||||
}
|
||||
if (kept)
|
||||
{
|
||||
parked.Entry["excluded"] = false;
|
||||
parked.Entry["hero"] = false;
|
||||
parked.Entry["keyframes"] = new JsonArray();
|
||||
}
|
||||
}
|
||||
if (project["heroFrame"] is null) return changed;
|
||||
// A hero is chosen: none waits any more, and an entry left with nothing to place goes.
|
||||
@@ -651,8 +674,20 @@ public sealed record ProjectSettings
|
||||
|
||||
private static bool Flag(JsonObject entry, string name) => entry[name] is JsonValue value && value.TryGetValue<bool>(out var set) && set;
|
||||
|
||||
/// <summary>A pending entry still has a position to give its photo.</summary>
|
||||
private static bool Waits(JsonObject entry) => Flag(entry, "excluded") || Flag(entry, "hero") || entry["keyframes"] is JsonArray { Count: > 0 };
|
||||
/// <summary>The members of a pending entry this Chronos knows: its photo, which copy of it, and the positions on it.</summary>
|
||||
internal static readonly HashSet<string> PendingMembers = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"sha256", "size", "capturedAt", "occurrence", "excluded", "hero", "keyframes",
|
||||
};
|
||||
|
||||
/// <summary>A pending entry has a position to give its photo.</summary>
|
||||
private static bool HoldsPosition(JsonObject entry) => Flag(entry, "excluded") || Flag(entry, "hero") || entry["keyframes"] is JsonArray { Count: > 0 };
|
||||
|
||||
/// <summary>A pending entry holds members this Chronos does not know (written by a newer one).</summary>
|
||||
private static bool HasUnknownMembers(JsonObject entry) => entry.Any(p => !PendingMembers.Contains(p.Key));
|
||||
|
||||
/// <summary>A pending entry still holds something: a position to give its photo, or members that are not this Chronos's to drop.</summary>
|
||||
private static bool Waits(JsonObject entry) => HoldsPosition(entry) || HasUnknownMembers(entry);
|
||||
|
||||
private static bool IsPosition(JsonNode? node, out int position)
|
||||
{
|
||||
|
||||
@@ -22,6 +22,12 @@ public sealed record ProjectReplay(IReadOnlyList<ProjectSettings> Commits, IRead
|
||||
public bool HasConflicts => Conflicts.Count > 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A merge both sides of which changed met settings of a newer Chronos (<see cref="ProjectSettings.IsNewerFormat"/>): this
|
||||
/// Chronos never merges them, as their known members may mean something else there (owner review 2, R8). Nothing was merged.
|
||||
/// </summary>
|
||||
public sealed class NewerSettingsException(string message) : InvalidOperationException(message);
|
||||
|
||||
/// <summary>
|
||||
/// Three-way merge of projects: the editor's edit (<c>ours</c>) and a change stored meanwhile by someone else
|
||||
/// (<c>theirs</c>: an analysis filling Auto values, another client through the server, another workspace through a
|
||||
@@ -31,15 +37,24 @@ public sealed record ProjectReplay(IReadOnlyList<ProjectSettings> Commits, IRead
|
||||
/// user instead (a server sequence, BRIEF §14.5; a workspace project, owner review 2, R8). Pending frames (frame
|
||||
/// positions parked by photo, the portable form of <see cref="ProjectContent"/>) merge photo by photo and flag by flag, so
|
||||
/// two people excluding different photos never conflict; two heroes chosen on both sides do (path <see cref="HeroPath"/>).
|
||||
/// Members this Chronos does not know merge like the others and are kept.
|
||||
/// Entries of one photo in one project (saved under two names, alike since) merge as one, keeping the positions of both.
|
||||
/// Members this Chronos does not know merge like the others and are kept. Settings of a newer Chronos are never merged:
|
||||
/// a side that did not change takes the other's as they are, anything else is refused (<see cref="NewerSettingsException"/>).
|
||||
/// </summary>
|
||||
public static class ProjectMerge
|
||||
{
|
||||
/// <summary>The path of the conflict of two heroes chosen among pending frames on both sides.</summary>
|
||||
public const string HeroPath = "hero";
|
||||
|
||||
/// <summary>
|
||||
/// The path of the settings format (<see cref="ProjectSettings.Version"/>): a difference there is settings of a newer
|
||||
/// Chronos that this one cannot merge with its own (a workspace's conflict of format).
|
||||
/// </summary>
|
||||
public const string FormatPath = "version";
|
||||
|
||||
private const string PendingPath = "pendingFrames";
|
||||
|
||||
/// <exception cref="NewerSettingsException">Both sides changed, and one of the three is of a newer format.</exception>
|
||||
public static ProjectSettings Merge(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs) =>
|
||||
MergeWithConflicts(basis, ours, theirs).Merged;
|
||||
|
||||
@@ -48,6 +63,7 @@ public static class ProjectMerge
|
||||
/// conflicts. A conflict whose path is in <paramref name="takeTheirs"/> takes theirs (the user chose "take server"
|
||||
/// there), every other one ours.
|
||||
/// </summary>
|
||||
/// <exception cref="NewerSettingsException">Both sides changed, and one of the three is of a newer format.</exception>
|
||||
public static ProjectMergeResult MergeWithConflicts(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs, IReadOnlySet<string>? takeTheirs = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(basis);
|
||||
@@ -56,6 +72,14 @@ public static class ProjectMerge
|
||||
var conflicts = new List<SettingsDifference>();
|
||||
var choice = takeTheirs ?? EmptySet;
|
||||
var (b, o, t) = (Keyed(basis), Keyed(ours), Keyed(theirs));
|
||||
if (basis.IsNewerFormat || ours.IsNewerFormat || theirs.IsNewerFormat)
|
||||
{
|
||||
// Their known members may mean something else there: only a side that did not change gives way.
|
||||
if (JsonNode.DeepEquals(o, b) || JsonNode.DeepEquals(t, o)) return new ProjectMergeResult(Read(theirs.ToJson()), []);
|
||||
if (JsonNode.DeepEquals(t, b)) return new ProjectMergeResult(Read(ours.ToJson()), []);
|
||||
throw new NewerSettingsException(string.Create(CultureInfo.InvariantCulture,
|
||||
$"Settings of format {Math.Max(basis.Version, Math.Max(ours.Version, theirs.Version))} are not merged by this Chronos (format {ProjectSettings.CurrentVersion})."));
|
||||
}
|
||||
var merged = MergeNode(b, o, t, string.Empty, conflicts, choice) as JsonObject ?? new JsonObject();
|
||||
OneHero(merged, o, t, conflicts, choice);
|
||||
return new ProjectMergeResult(FromKeyed(merged), conflicts);
|
||||
@@ -75,6 +99,7 @@ public static class ProjectMerge
|
||||
/// history stays linear and the last one holds the net change. Conflicts are those of the last commit; their paths in
|
||||
/// <paramref name="takeTheirs"/> take theirs in every commit.
|
||||
/// </summary>
|
||||
/// <exception cref="NewerSettingsException">A commit and theirs both changed, and one of them (or the basis) is of a newer format.</exception>
|
||||
public static ProjectReplay Replay(ProjectSettings basis, IReadOnlyList<ProjectSettings> mine, ProjectSettings theirs, IReadOnlySet<string>? takeTheirs = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(mine);
|
||||
@@ -157,14 +182,22 @@ public static class ProjectMerge
|
||||
private static string? HeroOf(JsonObject project) =>
|
||||
project[PendingPath] is JsonObject pending ? pending.FirstOrDefault(p => p.Value is JsonObject entry && Flag(entry, "hero")).Key : null;
|
||||
|
||||
/// <summary>The project as JSON with its pending frames as an object keyed by photo (<see cref="KeyOf"/>).</summary>
|
||||
/// <summary>
|
||||
/// The project as JSON with its pending frames as an object keyed by photo (<see cref="KeyOf"/>); entries of one photo
|
||||
/// (saved under two names, alike since) are one, with the positions of both (<see cref="ProjectContent.Fold"/>).
|
||||
/// </summary>
|
||||
private static JsonObject Keyed(ProjectSettings settings)
|
||||
{
|
||||
var project = JsonNode.Parse(settings.ToJson())!.AsObject();
|
||||
if (project[PendingPath] is JsonArray pending)
|
||||
{
|
||||
var keyed = new JsonObject();
|
||||
foreach (var entry in pending) keyed[KeyOf(entry)] = entry?.DeepClone();
|
||||
foreach (var entry in pending)
|
||||
{
|
||||
var key = KeyOf(entry);
|
||||
if (keyed[key] is JsonObject known && entry is JsonObject other) ProjectContent.Fold(known, other);
|
||||
else keyed[key] = entry?.DeepClone();
|
||||
}
|
||||
project[PendingPath] = keyed;
|
||||
}
|
||||
return project;
|
||||
@@ -188,22 +221,10 @@ public static class ProjectMerge
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The key of a pending entry: its photo and which copy of it ("sha:…#0", or "photo:size@ticks#0" for a photo not hashed),
|
||||
/// or its JSON for an entry naming no photo.
|
||||
/// The key of a pending entry: its photo and which copy of it (<see cref="ProjectContent.PhotoKey"/>: "sha:…#0", or
|
||||
/// "photo:size@ticks#0" for a photo not hashed), or its JSON for an entry naming no photo.
|
||||
/// </summary>
|
||||
private static string KeyOf(JsonNode? entry)
|
||||
{
|
||||
if (entry is JsonObject e)
|
||||
{
|
||||
var occurrence = e["occurrence"] is JsonValue o && o.TryGetValue<int>(out var n) ? n : 0;
|
||||
if (e["sha256"] is JsonValue s && s.TryGetValue<string>(out var sha) && sha.Length > 0)
|
||||
return string.Create(CultureInfo.InvariantCulture, $"sha:{sha.ToLowerInvariant()}#{occurrence}");
|
||||
var size = e["size"] is JsonValue z && z.TryGetValue<long>(out var bytes) ? bytes : 0;
|
||||
if (e["capturedAt"] is JsonValue c && c.TryGetValue<DateTime>(out var at))
|
||||
return string.Create(CultureInfo.InvariantCulture, $"photo:{size}@{at.Ticks}#{occurrence}");
|
||||
}
|
||||
return "raw:" + (entry?.ToJsonString() ?? "null");
|
||||
}
|
||||
private static string KeyOf(JsonNode? entry) => ProjectContent.PhotoKey(entry) ?? "raw:" + (entry?.ToJsonString() ?? "null");
|
||||
|
||||
/// <summary>The entry of the photo of <paramref name="template"/> holding no position; null for an entry naming no photo.</summary>
|
||||
private static JsonNode? Unplaced(JsonNode? template)
|
||||
|
||||
@@ -549,10 +549,30 @@ public sealed class ProjectService
|
||||
return;
|
||||
}
|
||||
// Both moved: the settings written meanwhile merge with the head (the version made in a workspace wins where both changed),
|
||||
// each photo named as the frames hold it now so the same photo merges as one.
|
||||
var merged = ProjectMerge.Merge(ProjectMerge.Read(ProjectContent.Rebind(mirrored.SettingsJson, frames.Photos)),
|
||||
ProjectMerge.Read(ProjectContent.Rebind(head.SettingsJson, frames.Photos)), ProjectMerge.Read(ProjectContent.Rebind(current, frames.Photos)));
|
||||
var version = await AppendDerivedAsync(context, main, head, ProjectContent.Canonical(merged.ToJson()), ProjectVersionKind.Merge, cancellationToken)
|
||||
// each photo named as the frames hold it now so the same photo merges as one. Where both changed, the settings written
|
||||
// meanwhile become an external version first, so the values the merge leaves out stay in the history to restore.
|
||||
ProjectMergeResult merged;
|
||||
try
|
||||
{
|
||||
merged = ProjectMerge.MergeWithConflicts(ProjectMerge.Read(ProjectContent.Rebind(mirrored.SettingsJson, frames.Photos)),
|
||||
ProjectMerge.Read(ProjectContent.Rebind(head.SettingsJson, frames.Photos)), ProjectMerge.Read(ProjectContent.Rebind(current, frames.Photos)));
|
||||
}
|
||||
catch (NewerSettingsException ex)
|
||||
{
|
||||
// A newer Chronos's version is never merged with this one's settings: both are left as they are, recorded as seen.
|
||||
Log.Warning("projects", $"Version {head.Number} of Main of sequence {context.Row.Id} and its settings written meanwhile are left as they are", ex);
|
||||
await _db.Projects.SetMirroredAsync(main.Id, head.Id, context.Row.SettingsVersion, cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
var parent = head;
|
||||
if (merged.HasConflicts)
|
||||
{
|
||||
parent = await AppendDerivedAsync(context, main, head, current, ProjectVersionKind.External, cancellationToken).ConfigureAwait(false);
|
||||
main = (await _db.Projects.GetAsync(main.Id, cancellationToken).ConfigureAwait(false))!;
|
||||
Log.Info("projects", $"Version {head.Number} of Main of sequence {context.Row.Id} and its settings written meanwhile both changed "
|
||||
+ $"{string.Join(", ", merged.Conflicts.Select(c => c.Path))}: version {head.Number}'s values are kept, the others are version {parent.Number}");
|
||||
}
|
||||
var version = await AppendDerivedAsync(context, main, parent, ProjectContent.Canonical(merged.Merged.ToJson()), ProjectVersionKind.Merge, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
main = (await _db.Projects.GetAsync(main.Id, cancellationToken).ConfigureAwait(false))!;
|
||||
await MirrorAsync(context, main, version, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
@@ -4,6 +4,7 @@ using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Render;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Projects;
|
||||
|
||||
namespace Chronos.Data.Workspaces;
|
||||
|
||||
@@ -104,6 +105,45 @@ public sealed record WorkspaceMedia(string Format, int FormatVersion, string Kin
|
||||
|
||||
/// <summary>The frames held, as the processing engine reads them.</summary>
|
||||
public IReadOnlyList<Frame> ToFrames() => [.. Frames.Select(f => f.ToFrame(SequenceId))];
|
||||
|
||||
/// <summary>
|
||||
/// These media with their photos named as <paramref name="home"/> names them now (owner review 2, R8): a frame copied
|
||||
/// before the home hashed its photo (a folder adopted, verified since) takes the SHA-256 the home's frame of that id has
|
||||
/// for the same photo (the same size and capture time; a conversion that gave the frame another file is not the same
|
||||
/// photo), and the encodings the home's conversions joined since the copy are added to <see cref="Aliases"/>. Versions
|
||||
/// the home made since name those photos so; named alike here, one photo merges as one. The frames, their files and the
|
||||
/// frames version stay as they are. This instance when there is nothing to learn.
|
||||
/// </summary>
|
||||
public WorkspaceMedia NamedAsAt(HomeFrames home)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(home);
|
||||
var there = new Dictionary<Guid, Frame>(home.Frames.Count);
|
||||
foreach (var frame in home.Frames) there[frame.Id] = frame;
|
||||
var learned = false;
|
||||
var frames = new List<WorkspaceFrame>(Frames.Count);
|
||||
foreach (var frame in Frames)
|
||||
{
|
||||
if (string.IsNullOrEmpty(frame.Sha256) && there.TryGetValue(frame.Id, out var held) && !string.IsNullOrEmpty(held.Sha256)
|
||||
&& held.Size == frame.Size && Millisecond(held.CapturedAt) == Millisecond(frame.CapturedAt))
|
||||
{
|
||||
frames.Add(frame with { Sha256 = held.Sha256.ToLowerInvariant() });
|
||||
learned = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
frames.Add(frame);
|
||||
}
|
||||
}
|
||||
var known = Aliases ?? [];
|
||||
var links = known.Select(Link).ToHashSet();
|
||||
var added = home.Photos.Aliases.Where(a => links.Add(Link(a))).ToList();
|
||||
if (!learned && added.Count == 0) return this;
|
||||
return this with { Frames = learned ? frames : Frames, Aliases = added.Count > 0 ? [.. known, .. added] : Aliases };
|
||||
|
||||
static long? Millisecond(DateTime? time) => time is { } at ? at.Ticks / TimeSpan.TicksPerMillisecond : null;
|
||||
// A media index read back may hold a damaged link: compared as it is, and left out of the classes like any other.
|
||||
static (string?, string?) Link(PhotoAlias alias) => (alias.Sha256?.ToLowerInvariant(), alias.Replacement?.ToLowerInvariant());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -27,7 +27,16 @@ public sealed record WorkspaceSyncState(Guid? RestoredFrom, WorkspaceConflict? C
|
||||
/// taking the server's (each member or all), or saving both (<see cref="WorkspaceSync.ResolveAsync"/>).
|
||||
/// </summary>
|
||||
public sealed record WorkspaceConflict(Guid TheirsVersionId, int TheirsNumber, Guid BaseVersionId, IReadOnlyList<Guid> Mine,
|
||||
IReadOnlyList<SettingsDifference> Differences, DateTimeOffset Found);
|
||||
IReadOnlyList<SettingsDifference> Differences, DateTimeOffset Found)
|
||||
{
|
||||
/// <summary>
|
||||
/// The home's head holds settings of a newer Chronos (a difference at <see cref="ProjectMerge.FormatPath"/>): nothing of
|
||||
/// this workspace's is merged into them. Only Save both settles it (this workspace's versions go to a new project in this
|
||||
/// Chronos's format), or a Chronos that reads them; keeping mine or taking the server's is refused.
|
||||
/// </summary>
|
||||
[JsonIgnore]
|
||||
public bool NewerFormat => Differences.Any(d => d.Path == ProjectMerge.FormatPath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parameters of a <see cref="JobKind.WorkspaceCopy"/> job: target = the home's sequence; the workspace folder, the
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
@@ -81,9 +82,12 @@ public sealed class WorkspaceSyncException(PushOutcome outcome, string message)
|
||||
/// (<see cref="ProjectMerge.Replay"/>, new ids, the old files kept in <c>versions/.replaced</c>), and the working state is
|
||||
/// merged too (<see cref="ProjectMerge.MergeWithConflicts"/>); settings both sides changed to different values stop
|
||||
/// there as a conflict (<see cref="WorkspaceConflict"/>) for the user to settle (<see cref="ResolveAsync"/>). Versions
|
||||
/// travel in the portable form (<see cref="ProjectContent"/>), so frames inserted at the home never move a position. Every
|
||||
/// operation holds the project's lease; nothing is ever deleted: a restore or save-both first saves uncommitted changes
|
||||
/// as a version.
|
||||
/// travel in the portable form (<see cref="ProjectContent"/>), so frames inserted at the home never move a position; before
|
||||
/// a merge the media learn how the home names its photos now (hashed or converted there since the copy), so every side
|
||||
/// names one photo alike. Settings of a newer Chronos are never merged with this one's: a project with nothing of its own
|
||||
/// moves onto them read-only, any other waits on a conflict of format that only Save both settles
|
||||
/// (<see cref="WorkspaceConflict.NewerFormat"/>). Every operation holds the project's lease; nothing is ever deleted: a
|
||||
/// restore or save-both first saves uncommitted changes as a version.
|
||||
/// </summary>
|
||||
public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
{
|
||||
@@ -357,8 +361,10 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
var tipVersion = locals.Count > 0 ? locals[^1] : basis;
|
||||
if (ours.Count > 0) basis = theirs.First(v => v.Id == ours[^1].Id);
|
||||
locals = [.. locals.Skip(ours.Count)];
|
||||
var media = project.ReadMedia();
|
||||
// The media first learn how the home names its photos now (hashed or converted there since the copy).
|
||||
var media = await MediaNamedAsAtHomeAsync(project, home, cancellationToken).ConfigureAwait(false);
|
||||
var photos = media?.Photos ?? NoFrames;
|
||||
if (IsNewer(head) || IsNewer(basis)) return NewerAtHome(project, bundle, media, tipVersion, locals, basis, head, theirs, takeTheirs);
|
||||
// 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));
|
||||
@@ -406,6 +412,55 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
return (moved, null, theirs);
|
||||
}
|
||||
|
||||
/// <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
|
||||
/// one name each photo alike. Null while the workspace holds no media.
|
||||
/// </summary>
|
||||
private static async Task<WorkspaceMedia?> MediaNamedAsAtHomeAsync(WorkspaceProject project, IProjectHome home, CancellationToken cancellationToken)
|
||||
{
|
||||
if (project.ReadMedia() is not { } media) return null;
|
||||
var named = media.NamedAsAt(await home.FramesAsync(cancellationToken).ConfigureAwait(false));
|
||||
if (!ReferenceEquals(named, media)) project.WriteMedia(named);
|
||||
return named;
|
||||
}
|
||||
|
||||
private static bool IsNewer(ProjectVersion? version) => version is not null && ProjectContent.FormatOf(version.SettingsJson) > ProjectSettings.CurrentVersion;
|
||||
|
||||
/// <summary>
|
||||
/// The home's head, or the base, holds settings of a newer Chronos: nothing is merged into or out of them, as their known
|
||||
/// members may mean something else there. With nothing of this workspace's own (no version to send, the working state the
|
||||
/// 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.
|
||||
/// </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)
|
||||
{
|
||||
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)))
|
||||
{
|
||||
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);
|
||||
return (moved, null, theirs);
|
||||
}
|
||||
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 });
|
||||
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).");
|
||||
return (bundle, conflict, theirs);
|
||||
}
|
||||
|
||||
/// <summary>Both sides kept: this workspace's versions to a new project at the home, this project onto the home's head.</summary>
|
||||
private async Task<WorkspaceSyncResult> SaveBothAsync(WorkspaceProject project, ProjectBundle bundle, IProjectHome home, string? name, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user