using System.Globalization; using System.Text.Json; using System.Text.Json.Nodes; using Chronos.Core.Project; using Chronos.Data.Sync; namespace Chronos.Data.Projects; /// The result of a three-way merge of projects: the merged settings and the members both sides changed to different values. /// Each settled for the side asked (takeTheirs), else for ours; empty when the merge needed nobody. public sealed record ProjectMergeResult(ProjectSettings Merged, IReadOnlyList Conflicts) { public bool HasConflicts => Conflicts.Count > 0; } /// /// Commits not stored at their home yet, replayed on top of the version stored there meanwhile (owner review 2, R8): one /// project per commit, in order, and the conflicts of the last one (the net change of all of them against theirs). /// public sealed record ProjectReplay(IReadOnlyList Commits, IReadOnlyList Conflicts) { public bool HasConflicts => Conflicts.Count > 0; } /// /// A merge both sides of which changed met settings of a newer Chronos (): this /// Chronos never merges them, as their known members may mean something else there (owner review 2, R8). Nothing was merged. /// public sealed class NewerSettingsException(string message) : InvalidOperationException(message); /// /// Three-way merge of projects: the editor's edit (ours) and a change stored meanwhile by someone else /// (theirs: an analysis filling Auto values, another client through the server, another workspace through a /// project's home), both made from basis. Values are compared member by member down the JSON tree; a member only /// one side changed takes that side's value, a member both changed takes the editor's (the user is looking at it) unless /// its path is among those asked to take theirs. lists those members for a source that asks the /// 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 ) merge photo by photo and flag by flag, so /// two people excluding different photos never conflict; two heroes chosen on both sides do (path ). /// 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 (). /// public static class ProjectMerge { /// The path of the conflict of two heroes chosen among pending frames on both sides. public const string HeroPath = "hero"; /// /// The path of the settings format (): a difference there is settings of a newer /// Chronos that this one cannot merge with its own (a workspace's conflict of format). /// public const string FormatPath = "version"; private const string PendingPath = "pendingFrames"; /// Both sides changed, and one of the three is of a newer format. public static ProjectSettings Merge(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs) => MergeWithConflicts(basis, ours, theirs).Merged; /// /// The merge of and made from , and its /// conflicts. A conflict whose path is in takes theirs (the user chose "take server" /// there), every other one ours. /// /// Both sides changed, and one of the three is of a newer format. public static ProjectMergeResult MergeWithConflicts(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs, IReadOnlySet? takeTheirs = null) { ArgumentNullException.ThrowIfNull(basis); ArgumentNullException.ThrowIfNull(ours); ArgumentNullException.ThrowIfNull(theirs); var conflicts = new List(); 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); } /// /// The members both sides changed to different values, in document order: the path below the project /// ("exposure.deflickerWindow.manual"; "pendingFrames.<photo>.excluded" for a pending frame), the editor's value and /// theirs as JSON (null when absent). /// public static IReadOnlyList Conflicts(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs) => MergeWithConflicts(basis, ours, theirs).Conflicts; /// /// Replays commits made from (, oldest first, each including the ones /// before it) on top of : each becomes theirs with that commit's changes since the basis, so the /// history stays linear and the last one holds the net change. Conflicts are those of the last commit; their paths in /// take theirs in every commit. /// /// A commit and theirs both changed, and one of them (or the basis) is of a newer format. public static ProjectReplay Replay(ProjectSettings basis, IReadOnlyList mine, ProjectSettings theirs, IReadOnlySet? takeTheirs = null) { ArgumentNullException.ThrowIfNull(mine); var commits = new List(mine.Count); IReadOnlyList conflicts = []; foreach (var commit in mine) { var result = MergeWithConflicts(basis, commit, theirs, takeTheirs); commits.Add(result.Merged); conflicts = result.Conflicts; } return new ProjectReplay(commits, conflicts); } /// True when both projects store the same values. public static bool SameValues(ProjectSettings a, ProjectSettings b) => a.ToJson() == b.ToJson(); private static readonly IReadOnlySet EmptySet = new HashSet(); private static JsonNode? MergeNode(JsonNode? basis, JsonNode? ours, JsonNode? theirs, string path, List conflicts, IReadOnlySet takeTheirs) { if (JsonNode.DeepEquals(ours, basis)) return theirs?.DeepClone(); if (JsonNode.DeepEquals(theirs, basis) || JsonNode.DeepEquals(theirs, ours)) return ours?.DeepClone(); if (path == PendingPath && ours is JsonObject or null && theirs is JsonObject or null) return MergePending(basis as JsonObject, ours as JsonObject, theirs as JsonObject, conflicts, takeTheirs); if (ours is JsonObject mine && theirs is JsonObject other) { var common = basis as JsonObject; var merged = new JsonObject(); foreach (var name in mine.Select(p => p.Key).Union(other.Select(p => p.Key))) { var child = path.Length == 0 ? name : path + "." + name; var value = MergeNode(common?[name], mine[name], other[name], child, conflicts, takeTheirs); if (value is not null || (takeTheirs.Contains(child) ? other.ContainsKey(name) : mine.ContainsKey(name))) merged[name] = value; } return merged; } var at = path.Length == 0 ? "settings" : path; conflicts.Add(new SettingsDifference(at, ours?.ToJsonString(), theirs?.ToJsonString())); return takeTheirs.Contains(at) ? theirs?.DeepClone() : ours?.DeepClone(); } /// /// Pending frames keyed by photo, merged entry by entry: an entry one side lacks counts as the photo with no position on /// it, so excluding one photo here and another there both stay, and a flag both changed alike is no conflict. /// private static JsonObject MergePending(JsonObject? basis, JsonObject? ours, JsonObject? theirs, List conflicts, IReadOnlySet takeTheirs) { var merged = new JsonObject(); var keys = (ours?.Select(p => p.Key) ?? []).Union(theirs?.Select(p => p.Key) ?? []).Union(basis?.Select(p => p.Key) ?? []).ToList(); foreach (var key in keys) { var template = ours?[key] ?? theirs?[key] ?? basis?[key]; var value = MergeNode(basis?[key] ?? Unplaced(template), ours?[key] ?? Unplaced(template), theirs?[key] ?? Unplaced(template), PendingPath + "." + key, conflicts, takeTheirs); if (value is not null) merged[key] = value; } return merged; } /// /// Two heroes after a merge (each side chose one among photos that wait): one conflict, settled for ours or, when asked, /// theirs; the other entry no longer holds the hero. /// private static void OneHero(JsonObject merged, JsonObject ours, JsonObject theirs, List conflicts, IReadOnlySet takeTheirs) { if (merged[PendingPath] is not JsonObject pending) return; var heroes = pending.Where(p => p.Value is JsonObject entry && Flag(entry, "hero")).Select(p => p.Key).ToList(); if (heroes.Count < 2) return; var mine = HeroOf(ours); var other = HeroOf(theirs); var keep = takeTheirs.Contains(HeroPath) ? other ?? heroes[0] : mine ?? heroes[0]; foreach (var key in heroes.Where(k => k != keep)) pending[key]!["hero"] = false; conflicts.Add(new SettingsDifference(HeroPath, mine is null ? null : (ours[PendingPath] as JsonObject)?[mine]?.ToJsonString(), other is null ? null : (theirs[PendingPath] as JsonObject)?[other]?.ToJsonString())); } private static string? HeroOf(JsonObject project) => project[PendingPath] is JsonObject pending ? pending.FirstOrDefault(p => p.Value is JsonObject entry && Flag(entry, "hero")).Key : null; /// /// The project as JSON with its pending frames as an object keyed by photo (); entries of one photo /// (saved under two names, alike since) are one, with the positions of both (). /// 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) { 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; } /// A keyed project back as settings: pending frames as a list again, without those that no longer hold a position. private static ProjectSettings FromKeyed(JsonObject project) { if (project[PendingPath] is JsonObject keyed) { var list = new JsonArray(); foreach (var (_, entry) in keyed) { if (entry is JsonObject e && !Waits(e)) continue; list.Add(entry?.DeepClone()); } if (list.Count == 0) project.Remove(PendingPath); else project[PendingPath] = list; } return ProjectSettings.FromJson(project.ToJsonString(), allowNewer: true); } /// /// 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. /// private static string KeyOf(JsonNode? entry) => ProjectContent.PhotoKey(entry) ?? "raw:" + (entry?.ToJsonString() ?? "null"); /// The entry of the photo of holding no position; null for an entry naming no photo. private static JsonNode? Unplaced(JsonNode? template) { if (template is not JsonObject entry || KeyOf(entry).StartsWith("raw:", StringComparison.Ordinal)) return null; var empty = new JsonObject(); foreach (var name in new[] { "sha256", "size", "capturedAt", "occurrence" }) { if (entry[name] is { } value) empty[name] = value.DeepClone(); } empty["excluded"] = false; empty["hero"] = false; empty["keyframes"] = new JsonArray(); return empty; } private static bool Flag(JsonObject entry, string name) => entry[name] is JsonValue value && value.TryGetValue(out var set) && set; /// A pending entry still holds a position (its unknown members count too: they are not this Chronos's to drop). private static bool Waits(JsonObject entry) => Flag(entry, "excluded") || Flag(entry, "hero") || entry["keyframes"] is JsonArray { Count: > 0 } || entry.Any(p => p.Key is not ("sha256" or "size" or "capturedAt" or "occurrence" or "excluded" or "hero" or "keyframes")); /// One outside change ( → ) applied to any number of projects made from the basis. public sealed class Rebase(ProjectSettings basis, ProjectSettings theirs) { public ProjectSettings Apply(ProjectSettings ours) { ArgumentNullException.ThrowIfNull(ours); return Merge(basis, ours, theirs); } } /// A project's JSON text as settings, a newer Chronos's too (read-only there). /// The text is not a project. internal static ProjectSettings Read(string json) { try { return ProjectSettings.FromJson(json, allowNewer: true); } catch (JsonException ex) { throw new InvalidDataException(ex.Message, ex); } } }