Files
Chronos/src/Titano.Data/Sync/SyncRules.cs
T
Claude f4103d42a1 fix(sync): download and match originals the server has not hashed
A folder the server adopted and never verified lists no SHA-256. A
download of such a sequence failed ("did not arrive intact") because
every unhashed frame collapsed into one wanted entry and the empty hash
was refused, and desktops never sent the proxies the server asked for
those frames (V-9).

- Each unhashed server original is fetched by frame id into staging,
  accepted on its size (two attempts, resumed with Range) and hashed
  here; the archive ingest files it by that hash like any other.
- Server frames without a hash are matched to this PC's originals by
  size and capture time: they are not downloaded twice, not uploaded
  again, counted right in the comparison (each frame on its own), and
  their wanted proxies are counted and sent from the matching original.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-12 16:21:35 +00:00

285 lines
15 KiB
C#

using System.Globalization;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using Titano.Core.Imaging;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Data.Archiving;
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) =>
SyncRules.Blank(Title) == SyncRules.Blank(other.Title)
&& SyncRules.Blank(Notes) == SyncRules.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, with the
/// server frames version their frame positions name when they were translated to the server's frames.
/// </summary>
public UpdateSequenceRequest ToRequest(int? expectedSettingsVersion, int? expectedFramesVersion = null) =>
new(Title ?? string.Empty, Tags, Rating, Notes ?? string.Empty, SyncRules.NormalizeSettings(SettingsJson), expectedSettingsVersion,
ExpectedFramesVersion: expectedFramesVersion);
}
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
[JsonSerializable(typeof(SyncPayload))]
internal sealed partial class SyncPayloadJson : JsonSerializerContext;
/// <summary>
/// One field that differs: its dotted path ("exposure.deflickerWindow.manual", or "sequence.tags" for the metadata)
/// and the value on each side (JSON for settings, plain text for metadata; 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>Path prefix of the title, tags, rating and notes in <see cref="Differences(SyncPayload, SyncPayload, int)"/>.</summary>
public const string MetadataPath = "sequence.";
/// <summary>
/// Where a linked pair stands. Settings changed on both sides since they last agreed are a conflict (the engine
/// settles equal content 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>
/// Up to <paramref name="max"/> differences between two payloads: title, tags, rating and notes first (paths
/// <c>sequence.title</c>, <c>sequence.tags</c>, …, tags as one comma-separated value), then the settings.
/// </summary>
public static IReadOnlyList<SettingsDifference> Differences(SyncPayload mine, SyncPayload theirs, int max = 3)
{
var differences = new List<SettingsDifference>();
if (Blank(mine.Title) != Blank(theirs.Title)) differences.Add(new(MetadataPath + "title", Blank(mine.Title), Blank(theirs.Title)));
if (!mine.Tags.ToHashSet(StringComparer.OrdinalIgnoreCase).SetEquals(theirs.Tags))
differences.Add(new(MetadataPath + "tags", string.Join(", ", mine.Tags), string.Join(", ", theirs.Tags)));
if (mine.Rating != theirs.Rating)
differences.Add(new(MetadataPath + "rating", mine.Rating.ToString(CultureInfo.InvariantCulture), theirs.Rating.ToString(CultureInfo.InvariantCulture)));
if (Blank(mine.Notes) != Blank(theirs.Notes)) differences.Add(new(MetadataPath + "notes", Blank(mine.Notes), Blank(theirs.Notes)));
if (differences.Count < max) differences.AddRange(Differences(mine.SettingsJson, theirs.SettingsJson, max - differences.Count));
return differences.Count > max ? differences.GetRange(0, max) : differences;
}
/// <summary>
/// Originals missing on each side by content (BRIEF §14.5: originals never conflict), from their SHA-256 alone (an
/// empty or null one: not hashed yet). See <see cref="CompareOriginals(IReadOnlyCollection{FramePhoto}, IReadOnlyCollection{FramePhoto})"/>.
/// </summary>
public static (int MissingRemote, int MissingLocal) CompareOriginals(IReadOnlyCollection<string?> localHashes, IReadOnlyCollection<string> remoteHashes) =>
CompareOriginals([.. localHashes.Select(h => new FramePhoto(h, 0, null))], [.. remoteHashes.Select(h => new FramePhoto(h, 0, null))]);
/// <summary>
/// Originals missing on each side by content (BRIEF §14.5: originals never conflict): the same SHA-256 where both
/// sides hashed them, else the same size and capture time (<see cref="FramePhoto.Matches"/>; a folder adopted on
/// either side and not verified yet). Local frames not hashed yet that nothing matched are assumed to match server
/// frames that nothing matched.
/// </summary>
public static (int MissingRemote, int MissingLocal) CompareOriginals(IReadOnlyCollection<FramePhoto> local, IReadOnlyCollection<FramePhoto> remote)
{
ArgumentNullException.ThrowIfNull(local);
ArgumentNullException.ThrowIfNull(remote);
var remoteHashes = remote.Where(p => p.IsHashed).Select(p => p.Sha256!.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
var localHashes = local.Where(p => p.IsHashed).Select(p => p.Sha256!.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
// What no hash matched: each content once, each frame not hashed on its own.
var localLeft = Unmatched(local, remoteHashes);
var remoteLeft = Unmatched(remote, localHashes);
var byTime = new Dictionary<(long Size, long Time), List<int>>();
for (var i = 0; i < remoteLeft.Count; i++)
{
if (remoteLeft[i].CapturedAt is not { } time) continue;
var key = (remoteLeft[i].Size, time.Ticks / TimeSpan.TicksPerMillisecond);
if (!byTime.TryGetValue(key, out var list)) byTime[key] = list = [];
list.Add(i);
}
var paired = new bool[remoteLeft.Count];
int localHashedLeft = 0, localUnhashedLeft = 0, remoteMatched = 0;
foreach (var photo in localLeft)
{
var match = -1;
if (photo.CapturedAt is { } time && byTime.TryGetValue((photo.Size, time.Ticks / TimeSpan.TicksPerMillisecond), out var candidates))
{
var at = candidates.FindIndex(i => !paired[i] && remoteLeft[i].Matches(photo));
if (at >= 0) match = candidates[at];
}
if (match >= 0)
{
paired[match] = true;
remoteMatched++;
}
else if (photo.IsHashed)
{
localHashedLeft++;
}
else
{
localUnhashedLeft++;
}
}
var remoteUnmatched = remoteLeft.Count - remoteMatched;
return (localHashedLeft + Math.Max(0, localUnhashedLeft - remoteUnmatched), Math.Max(0, remoteUnmatched - localUnhashedLeft));
static List<FramePhoto> Unmatched(IEnumerable<FramePhoto> side, HashSet<string> other) =>
[
.. side.Where(p => p.IsHashed && !other.Contains(p.Sha256!.ToLowerInvariant())).DistinctBy(p => p.Sha256!.ToLowerInvariant()),
.. side.Where(p => !p.IsHashed),
];
}
/// <summary>
/// Frames whose proxy the server asks for (it cannot decode their originals, BRIEF §2.3) that this PC holds and its
/// <paramref name="decoder"/> reads: an upload makes and sends them. A local original not hashed yet (a folder adopted
/// and not verified) stands for a wanted frame of its size that no hash matched (by size, not name: the server names
/// its copy by its own template); the upload hashes it before making the proxy. A wanted frame the server has not
/// hashed is the local original of its size and capture time (<paramref name="captured"/>, by server frame id), as
/// <see cref="ProxyOriginal"/> finds it for the upload.
/// </summary>
public static int ProxiesToSend(SequenceManifest manifest, IReadOnlyCollection<Frame> local, ImageDecoder decoder,
IReadOnlyDictionary<Guid, DateTime?>? captured = null)
{
ArgumentNullException.ThrowIfNull(manifest);
IReadOnlyList<Frame> frames = [.. local];
var photos = Photos(frames);
var count = 0;
// The originals of frames the server has not hashed first: they are no longer free to stand for others by size.
var taken = new HashSet<Guid>();
foreach (var frame in manifest.Frames.Where(f => f.WantsProxy && f.Sha256.Length == 0))
{
if (ProxyOriginal(frame, captured?.GetValueOrDefault(frame.Id), frames, photos) is { } original && taken.Add(original.Id) && Readable(original)) count++;
}
var hashed = frames.Where(f => !string.IsNullOrEmpty(f.Sha256)).ToLookup(f => f.Sha256!.ToLowerInvariant(), StringComparer.Ordinal);
var unhashed = frames.Where(f => string.IsNullOrEmpty(f.Sha256) && Readable(f) && !taken.Contains(f.Id)).GroupBy(f => f.Size)
.ToDictionary(g => g.Key, g => g.Count());
foreach (var frame in manifest.Frames.Where(f => f.WantsProxy && f.Sha256.Length > 0))
{
var sha = frame.Sha256.ToLowerInvariant();
if (hashed.Contains(sha))
{
if (hashed[sha].Any(Readable)) count++;
}
else if (unhashed.TryGetValue(frame.Size, out var left) && left > 0)
{
unhashed[frame.Size] = left - 1;
count++;
}
}
return count;
bool Readable(Frame frame) => !ArchiveImages.NeedsProxy(decoder, frame.Format);
}
/// <summary>
/// The local original of a wanted frame the server has not hashed yet (adopted there, not verified): the one of its
/// size and capture time (<paramref name="capturedAt"/>, from the server's frame row); null when none is, or the time
/// is unknown. <paramref name="photos"/> are <see cref="Photos"/> of <paramref name="local"/>.
/// </summary>
public static Frame? ProxyOriginal(ManifestFrame wanted, DateTime? capturedAt, IReadOnlyList<Frame> local, FramePhotos photos)
{
ArgumentNullException.ThrowIfNull(wanted);
ArgumentNullException.ThrowIfNull(local);
ArgumentNullException.ThrowIfNull(photos);
return capturedAt is not null && photos.IndexOf(new FramePhoto(null, wanted.Size, capturedAt)) is { } at ? local[at] : null;
}
/// <summary>The photos of <paramref name="local"/>'s frames, by their place in the list.</summary>
public static FramePhotos Photos(IReadOnlyList<Frame> local) => new(local.Select((f, i) => (i, new FramePhoto(f.Sha256, f.Size, f.CapturedAt))));
/// <summary>
/// Whether <paramref name="local"/> holds originals a server cannot decode (it asks for their proxies, BRIEF §2.3,
/// §4.2: managed decoders only) that this PC's <paramref name="decoder"/> reads, so it can make those proxies.
/// </summary>
public static bool MakesProxiesFor(IEnumerable<Frame> local, ImageDecoder decoder) =>
local.Select(f => f.Format).Distinct().Any(format => ArchiveImages.ServerNeedsProxy(format) && !ArchiveImages.NeedsProxy(decoder, format));
internal static string Blank(string? text) => text?.Trim() ?? string.Empty;
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()));
}
}