feat(sync): client sync engine with links, settings conflicts, transfers and background agent
Per-sequence state between the local index and a server from listings and manifest diffs; version-counter settings sync with explicit conflicts; upload, original and proxy download jobs; WebSocket-driven background agent. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
13 files changed
+1858
-2
No files matched your search
@@ -0,0 +1,145 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Protocol;
|
||||
|
||||
namespace Titano.Data.Sync;
|
||||
|
||||
/// <summary>The fields both sides version together (BRIEF §14.5: settings and tags carry version counters).</summary>
|
||||
public sealed record SyncPayload(string? Title, IReadOnlyList<string> Tags, int Rating, string? Notes, string? SettingsJson)
|
||||
{
|
||||
public static SyncPayload Of(Sequence s) => new(s.Title, s.Tags, s.Rating, s.Notes, s.SettingsJson);
|
||||
|
||||
public static SyncPayload Of(SequenceDto s, string? settingsJson) => new(s.Title, s.Tags, s.Rating, s.Notes, settingsJson);
|
||||
|
||||
/// <summary>Title, tags, rating and notes match (blank equals absent, tags ignore case and order).</summary>
|
||||
public bool SameMetadata(SyncPayload other) =>
|
||||
Blank(Title) == Blank(other.Title)
|
||||
&& Blank(Notes) == Blank(other.Notes)
|
||||
&& Rating == other.Rating
|
||||
&& Tags.ToHashSet(StringComparer.OrdinalIgnoreCase).SetEquals(other.Tags);
|
||||
|
||||
public bool SameAs(SyncPayload other) => SameMetadata(other) && SyncRules.SameSettings(SettingsJson, other.SettingsJson);
|
||||
|
||||
/// <summary>The PATCH that makes the server's copy equal to this one; settings are sent in their normalised form.</summary>
|
||||
public UpdateSequenceRequest ToRequest(int? expectedSettingsVersion) =>
|
||||
new(Title ?? string.Empty, Tags, Rating, Notes ?? string.Empty, SyncRules.NormalizeSettings(SettingsJson), expectedSettingsVersion);
|
||||
|
||||
private static string Blank(string? text) => text?.Trim() ?? string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>One setting that differs: its dotted path ("exposure.deflicker.window") and the JSON value on each side (null when absent).</summary>
|
||||
public sealed record SettingsDifference(string Path, string? Mine, string? Theirs);
|
||||
|
||||
/// <summary>Decisions of the sync engine that need no I/O: the status of a row, settings equality and differences, merges.</summary>
|
||||
public static class SyncRules
|
||||
{
|
||||
/// <summary>
|
||||
/// Where a linked pair stands. Settings changed on both sides since they last agreed are a conflict (the engine
|
||||
/// settles equal content and metadata-only differences before a row is shown); missing originals count before
|
||||
/// settings changed on one side only.
|
||||
/// </summary>
|
||||
public static SyncStatus Status(Sequence? local, SyncLink? link)
|
||||
{
|
||||
if (link is null) return SyncStatus.LocalOnly;
|
||||
if (local is null) return link.ProxiesCached > 0 ? SyncStatus.ProxiesOnly : SyncStatus.RemoteOnly;
|
||||
var localChanged = link.BaseLocalSettings != local.SettingsVersion;
|
||||
var remoteChanged = link.BaseRemoteSettings != link.RemoteSettingsVersion;
|
||||
if (localChanged && remoteChanged) return SyncStatus.Conflict;
|
||||
if (link.MissingRemote > 0 || localChanged) return SyncStatus.LocalAhead;
|
||||
if (link.MissingLocal > 0 || remoteChanged) return SyncStatus.ServerAhead;
|
||||
return SyncStatus.InSync;
|
||||
}
|
||||
|
||||
/// <summary>The state stored on the local sequence for the Library; null for rows without a local copy or in transfer.</summary>
|
||||
public static SyncState? ToSequenceState(SyncStatus status) => status switch
|
||||
{
|
||||
SyncStatus.InSync => SyncState.InSync,
|
||||
SyncStatus.LocalOnly => SyncState.LocalOnly,
|
||||
SyncStatus.LocalAhead => SyncState.LocalAhead,
|
||||
SyncStatus.ServerAhead => SyncState.ServerAhead,
|
||||
SyncStatus.Conflict => SyncState.Conflict,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Settings JSON in the form both sides store: a project read and written again (missing members take their
|
||||
/// defaults, so "no settings" equals the default project). Text that is not a project of this build is kept as is.
|
||||
/// </summary>
|
||||
public static string NormalizeSettings(string? json)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json)) return new ProjectSettings().ToJson();
|
||||
try
|
||||
{
|
||||
return ProjectSettings.FromJson(json).ToJson();
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or InvalidDataException)
|
||||
{
|
||||
return json.Trim();
|
||||
}
|
||||
}
|
||||
|
||||
public static bool SameSettings(string? a, string? b) => Differences(a, b, 1).Count == 0;
|
||||
|
||||
/// <summary>Up to <paramref name="max"/> settings that differ, in document order.</summary>
|
||||
public static IReadOnlyList<SettingsDifference> Differences(string? mine, string? theirs, int max = 3)
|
||||
{
|
||||
var differences = new List<SettingsDifference>();
|
||||
Collect(Parse(NormalizeSettings(mine)), Parse(NormalizeSettings(theirs)), string.Empty, differences, max);
|
||||
return differences;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Metadata-only divergence (settings equal): tags are united, title, rating and notes come from the side edited last.
|
||||
/// </summary>
|
||||
public static SyncPayload Merge(SyncPayload local, SyncPayload remote, bool localIsNewer)
|
||||
{
|
||||
var newer = localIsNewer ? local : remote;
|
||||
var tags = local.Tags.Concat(remote.Tags).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
|
||||
return newer with { Tags = tags, SettingsJson = local.SettingsJson };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Originals missing on each side by content (BRIEF §14.5: originals never conflict). Local frames not hashed yet
|
||||
/// (adopted, not verified) are assumed to match server frames that no hash matched.
|
||||
/// </summary>
|
||||
public static (int MissingRemote, int MissingLocal) CompareOriginals(IReadOnlyCollection<string?> localHashes, IReadOnlyCollection<string> remoteHashes)
|
||||
{
|
||||
var remote = remoteHashes.Select(h => h.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
|
||||
var hashed = localHashes.Where(h => !string.IsNullOrEmpty(h)).Select(h => h!.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
|
||||
var unhashed = localHashes.Count(string.IsNullOrEmpty);
|
||||
var matched = hashed.Count(remote.Contains);
|
||||
var unmatchedRemote = remote.Count - matched;
|
||||
return (hashed.Count - matched + Math.Max(0, unhashed - unmatchedRemote), Math.Max(0, unmatchedRemote - unhashed));
|
||||
}
|
||||
|
||||
private static JsonNode? Parse(string json)
|
||||
{
|
||||
try
|
||||
{
|
||||
return JsonNode.Parse(json);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return JsonValue.Create(json);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Collect(JsonNode? a, JsonNode? b, string path, List<SettingsDifference> differences, int max)
|
||||
{
|
||||
if (differences.Count >= max) return;
|
||||
if (a is JsonObject left && b is JsonObject right)
|
||||
{
|
||||
foreach (var name in left.Select(p => p.Key).Concat(right.Select(p => p.Key)).Distinct(StringComparer.Ordinal))
|
||||
{
|
||||
left.TryGetPropertyValue(name, out var x);
|
||||
right.TryGetPropertyValue(name, out var y);
|
||||
Collect(x, y, path.Length == 0 ? name : path + "." + name, differences, max);
|
||||
if (differences.Count >= max) return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!JsonNode.DeepEquals(a, b)) differences.Add(new SettingsDifference(path.Length == 0 ? "settings" : path, a?.ToJsonString(), b?.ToJsonString()));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user