fix(sync): keep project positions on their photos when settings cross copies
Settings synced between a PC and its server sequence were stored as they
came, in the other copy's frame order. When the inserted photos arrived
later (a download, an upload), the index moved those already-correct
positions a second time, so exclusions, the hero and camera keyframes
landed on other photos (V-21, CD-2).
- Settings are translated by photo (SHA-256, else size and capture time)
to the frames of the copy they go to: the server's before they are
compared or applied here, this PC's to the server's frames as its
manifest lists them before a push (SyncPositions).
- A position on a photo the receiving copy lacks waits in project.json as
a pending frame and takes its place when the photo arrives, on an
insertion or an append in step with the index; the Library's hero
frame follows. A hero chosen meanwhile wins, and advice does not fill
a hero while one waits. Old projects without the member are unchanged.
- Pushes send expectedFramesVersion; PATCH /api/v1/sequences/{id} answers
409 frames_conflict when the frames changed since, and the next
comparison translates again.
- A pulled payload equal to the local copy is settled without the
archive: an offline or read-only archive no longer fails the
comparison (V-10).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
25 files changed
+1091
-51
No files matched your search
@@ -36,7 +36,8 @@ internal static class ParameterBindings
|
||||
{
|
||||
Parameter = AdvisorParameters.Hero, Section = AdvisorSection.Frames,
|
||||
Effective = s => s.HeroFrame,
|
||||
Set = (s, r) => s.HeroFrame is null ? s with { HeroFrame = (int)r.Value! } : s,
|
||||
// A hero waiting for its photo (taken from another copy) is the user's choice too.
|
||||
Set = (s, r) => s.HeroFrame is null && !s.HeroPending ? s with { HeroFrame = (int)r.Value! } : s,
|
||||
},
|
||||
new()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
namespace Titano.Core.Project;
|
||||
|
||||
/// <summary>
|
||||
/// A photo as every copy of a sequence knows it (BRIEF §14.5: originals are content-addressed): its SHA-256 once hashed,
|
||||
/// else its size and capture time (a folder adopted and not verified yet). Frame ids and positions differ between a
|
||||
/// server sequence and a PC's copy of it; the photo does not.
|
||||
/// </summary>
|
||||
/// <param name="Sha256">Hex SHA-256; null or empty while the copy has not hashed the file.</param>
|
||||
public sealed record FramePhoto(string? Sha256, long Size, DateTime? CapturedAt)
|
||||
{
|
||||
public bool IsHashed => !string.IsNullOrEmpty(Sha256);
|
||||
|
||||
/// <summary>
|
||||
/// The same photo: the same SHA-256 when both are hashed, otherwise the same size and capture time (to the
|
||||
/// millisecond, as databases keep it).
|
||||
/// </summary>
|
||||
public bool Matches(FramePhoto other)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(other);
|
||||
if (IsHashed && other.IsHashed) return string.Equals(Sha256, other.Sha256, StringComparison.OrdinalIgnoreCase);
|
||||
return Size == other.Size && CapturedAt is { } mine && other.CapturedAt is { } theirs && Millisecond(mine) == Millisecond(theirs);
|
||||
}
|
||||
|
||||
internal static long Millisecond(DateTime time) => time.Ticks / TimeSpan.TicksPerMillisecond;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The photos of one copy's frames by frame index (positions in capture order, BRIEF §5), and where a photo is among
|
||||
/// them. Immutable once built, so parallel workers may share it.
|
||||
/// </summary>
|
||||
public sealed class FramePhotos
|
||||
{
|
||||
private readonly FramePhoto?[] _byIndex;
|
||||
private readonly Dictionary<string, int> _bySha = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<(long Size, long Time), List<int>> _bySizeAndTime = [];
|
||||
|
||||
/// <param name="frames">Each frame's index and photo, in any order.</param>
|
||||
public FramePhotos(IEnumerable<(int Index, FramePhoto Photo)> frames)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(frames);
|
||||
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;
|
||||
for (var i = 0; i < _byIndex.Length; i++)
|
||||
{
|
||||
if (_byIndex[i] is not { } photo) continue;
|
||||
if (photo.IsHashed) _bySha.TryAdd(photo.Sha256!.ToLowerInvariant(), i);
|
||||
if (photo.CapturedAt is not { } time) continue;
|
||||
var key = (photo.Size, FramePhoto.Millisecond(time));
|
||||
if (!_bySizeAndTime.TryGetValue(key, out var same)) _bySizeAndTime[key] = same = [];
|
||||
same.Add(i);
|
||||
}
|
||||
}
|
||||
|
||||
public int Count => _byIndex.Length;
|
||||
|
||||
/// <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;
|
||||
|
||||
/// <summary>Some frame is not hashed yet: matching it needs capture times.</summary>
|
||||
public bool HasUnhashed => _byIndex.Any(p => p is { IsHashed: false });
|
||||
|
||||
/// <summary>The index of the first frame holding <paramref name="photo"/> (<see cref="FramePhoto.Matches"/>); null when none does.</summary>
|
||||
public int? IndexOf(FramePhoto photo)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(photo);
|
||||
if (photo.IsHashed && _bySha.TryGetValue(photo.Sha256!.ToLowerInvariant(), out var hashed)) return hashed;
|
||||
if (photo.CapturedAt is not { } time || !_bySizeAndTime.TryGetValue((photo.Size, FramePhoto.Millisecond(time)), out var candidates)) return null;
|
||||
foreach (var index in candidates)
|
||||
{
|
||||
if (_byIndex[index]!.Matches(photo)) return index;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Both lists hold the same photos at the same indices: a position names the same photo on both.</summary>
|
||||
public bool SameAs(FramePhotos other)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(other);
|
||||
if (other.Count != Count) return false;
|
||||
for (var i = 0; i < Count; i++)
|
||||
{
|
||||
var (mine, theirs) = (this[i], other[i]);
|
||||
if (mine is null != theirs is null || (mine is not null && !mine.Matches(theirs!))) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -130,6 +130,7 @@ public sealed record ProjectBundle(BundleArchive Archive, BundleSequence Sequenc
|
||||
{
|
||||
ExcludedFrames = current.ExcludedFrames,
|
||||
HeroFrame = current.HeroFrame,
|
||||
PendingFrames = current.PendingFrames,
|
||||
Camera = Project.Camera with { Keyframes = current.Camera.Keyframes },
|
||||
};
|
||||
|
||||
|
||||
@@ -48,6 +48,30 @@ public sealed record CurvePoint(double X, double Y);
|
||||
/// <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");
|
||||
|
||||
/// <summary>
|
||||
/// The frame positions of a project that name a photo this copy of the sequence does not hold: settings taken from a
|
||||
/// copy that holds it (BRIEF §14.5). They become positions again when the photo arrives
|
||||
/// (<see cref="ProjectSettings.TranslateFramePositions"/>).
|
||||
/// </summary>
|
||||
public sealed record PendingFrame
|
||||
{
|
||||
public string? Sha256 { get; init; }
|
||||
public long Size { get; init; }
|
||||
public DateTime? CapturedAt { get; init; }
|
||||
|
||||
/// <summary>The photo is excluded from renders.</summary>
|
||||
public bool Excluded { get; init; }
|
||||
|
||||
/// <summary>The photo is the hero frame, unless another one is chosen before it arrives.</summary>
|
||||
public bool Hero { get; init; }
|
||||
|
||||
/// <summary>Virtual-camera keyframes on the photo; their <see cref="CameraKey.Frame"/> is set when it arrives.</summary>
|
||||
public IReadOnlyList<CameraKey> Keyframes { get; init; } = [];
|
||||
|
||||
[JsonIgnore]
|
||||
public FramePhoto Photo => new(Sha256, Size, CapturedAt);
|
||||
}
|
||||
|
||||
public sealed record TimingSettings
|
||||
{
|
||||
public Auto<TimingMode> Mode { get; init; } = new();
|
||||
@@ -177,6 +201,9 @@ public sealed record ProjectSettings
|
||||
/// <summary>Layout of a project edited as JSON (<see cref="MoveFramePositions"/>): indented like <see cref="ToJson"/>.</summary>
|
||||
private static readonly JsonSerializerOptions IndentedJson = new() { WriteIndented = true };
|
||||
|
||||
/// <summary>Member names as a project edited as JSON reads them (an older or hand-written file may use any casing).</summary>
|
||||
private static readonly JsonNodeOptions CaseInsensitive = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
public int Version { get; init; } = CurrentVersion;
|
||||
public TimingSettings Timing { get; init; } = new();
|
||||
public ExposureSettings Exposure { get; init; } = new();
|
||||
@@ -191,6 +218,16 @@ public sealed record ProjectSettings
|
||||
/// <summary>Index of the hero frame (sequence thumbnail).</summary>
|
||||
public int? HeroFrame { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Exclusions, hero and keyframes naming photos this copy does not hold yet (settings synced from a copy that holds
|
||||
/// them); null when there are none. They take their place when the photos arrive (<see cref="TranslateFramePositions"/>).
|
||||
/// </summary>
|
||||
public IReadOnlyList<PendingFrame>? PendingFrames { get; init; }
|
||||
|
||||
/// <summary>The hero waits for its photo, so advice does not choose one meanwhile.</summary>
|
||||
[JsonIgnore]
|
||||
public bool HeroPending => PendingFrames?.Any(p => p.Hero) == true;
|
||||
|
||||
public string ToJson() => JsonSerializer.Serialize(this, ProjectJson.Default.ProjectSettings);
|
||||
|
||||
/// <summary>
|
||||
@@ -286,6 +323,244 @@ public sealed record ProjectSettings
|
||||
replace(JsonValue.Create(now));
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether a project names frames (exclusions, a hero, camera keyframes or <see cref="PendingFrames"/>); settings
|
||||
/// naming none cross between copies of a sequence as they are. False for text that is not a project object.
|
||||
/// </summary>
|
||||
public static bool NamesFrames(string? json)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json)) return false;
|
||||
try
|
||||
{
|
||||
return JsonNode.Parse(json, CaseInsensitive) is JsonObject project
|
||||
&& (project["excludedFrames"] is JsonArray { Count: > 0 } || project["heroFrame"] is JsonValue || project["pendingFrames"] is JsonArray { Count: > 0 }
|
||||
|| (project["camera"] is JsonObject camera && camera["keyframes"] is JsonArray { Count: > 0 }));
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or ArgumentException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Translates the frame positions of a project written against the frames of another copy of the sequence
|
||||
/// (<paramref name="from"/>; a server sequence and a PC's copy hold the same photos, though not always all of them,
|
||||
/// BRIEF §14.5) to the frames of <paramref name="to"/>, by photo: each exclusion, the hero and each camera keyframe
|
||||
/// moves to the frame of <paramref name="to"/> holding its photo. One whose photo <paramref name="to"/> lacks becomes
|
||||
/// a <see cref="PendingFrame"/>, and pending frames whose photo <paramref name="to"/> holds become positions again; a
|
||||
/// pending hero only while no other hero is chosen, a pending keyframe only where no keyframe is. With
|
||||
/// <paramref name="from"/> null the positions already name <paramref name="to"/>'s frames and only pending frames are
|
||||
/// placed (photos that arrived). A position naming no frame of <paramref name="from"/> names nothing and goes. Edited
|
||||
/// in place like <see cref="MoveFramePositions"/>; null when nothing changes or <paramref name="json"/> is not a
|
||||
/// project object.
|
||||
/// </summary>
|
||||
public static string? TranslateFramePositions(string json, FramePhotos? from, FramePhotos to)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(to);
|
||||
if (string.IsNullOrWhiteSpace(json)) return null;
|
||||
try
|
||||
{
|
||||
if (JsonNode.Parse(json, CaseInsensitive) is not JsonObject project) return null;
|
||||
var pending = new List<Parked>();
|
||||
var unreadable = new List<JsonNode?>();
|
||||
if (project["pendingFrames"] is JsonArray stored)
|
||||
{
|
||||
foreach (var node in stored)
|
||||
{
|
||||
// An entry naming no photo is not this Titano's to place: it stays as it is.
|
||||
if (node is JsonObject entry && PhotoOf(entry) is { } photo) pending.Add(new Parked(photo, entry.DeepClone().AsObject()));
|
||||
else unreadable.Add(node?.DeepClone());
|
||||
}
|
||||
}
|
||||
var changed = from is not null && !from.SameAs(to) && TranslatePositions(project, from, to, pending);
|
||||
changed |= PlacePending(project, to, pending);
|
||||
if (!changed) return null;
|
||||
SortPositions(project);
|
||||
var left = pending.Where(p => !p.Placed).Select(p => (JsonNode?)p.Entry).Concat(unreadable).ToArray();
|
||||
if (left.Length == 0) project.Remove("pendingFrames");
|
||||
else project["pendingFrames"] = new JsonArray(left);
|
||||
return project.ToJsonString(IndentedJson);
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or ArgumentException or InvalidOperationException)
|
||||
{
|
||||
// Not JSON, a member given twice, or a member of an unexpected kind: not a project to edit.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Moves every position of <paramref name="project"/> from <paramref name="from"/>'s frames to <paramref name="to"/>'s.</summary>
|
||||
private static bool TranslatePositions(JsonObject project, FramePhotos from, FramePhotos to, List<Parked> pending)
|
||||
{
|
||||
var changed = false;
|
||||
if (project["excludedFrames"] is JsonArray excluded)
|
||||
{
|
||||
var kept = new List<JsonNode?>(excluded.Count);
|
||||
foreach (var node in excluded)
|
||||
{
|
||||
if (!IsPosition(node, out var at)) kept.Add(node?.DeepClone());
|
||||
else if (from[at] is not { } photo) changed = true;
|
||||
else if (to.IndexOf(photo) is { } now)
|
||||
{
|
||||
kept.Add(JsonValue.Create(now));
|
||||
changed |= now != at;
|
||||
}
|
||||
else
|
||||
{
|
||||
Park(pending, photo).Entry["excluded"] = true;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
Replace(excluded, kept);
|
||||
}
|
||||
if (project["heroFrame"] is JsonValue hero && hero.TryGetValue<int>(out var heroAt))
|
||||
{
|
||||
var photo = from[heroAt];
|
||||
var now = photo is null ? null : to.IndexOf(photo);
|
||||
if (photo is not null && now is null) Park(pending, photo).Entry["hero"] = true;
|
||||
if (now != heroAt)
|
||||
{
|
||||
project["heroFrame"] = now;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (project["camera"] is JsonObject camera && camera["keyframes"] is JsonArray keyframes)
|
||||
{
|
||||
var kept = new List<JsonNode?>(keyframes.Count);
|
||||
foreach (var node in keyframes)
|
||||
{
|
||||
if (node is not JsonObject key || !IsPosition(key["frame"], out var at))
|
||||
{
|
||||
kept.Add(node?.DeepClone());
|
||||
continue;
|
||||
}
|
||||
var copy = key.DeepClone().AsObject();
|
||||
if (from[at] is not { } photo)
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
else if (to.IndexOf(photo) is { } now)
|
||||
{
|
||||
copy["frame"] = now;
|
||||
kept.Add(copy);
|
||||
changed |= now != at;
|
||||
}
|
||||
else
|
||||
{
|
||||
var parked = Park(pending, photo).Entry;
|
||||
if (parked["keyframes"] is not JsonArray keys) parked["keyframes"] = keys = new JsonArray();
|
||||
keys.Add(copy);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
Replace(keyframes, kept);
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
/// <summary>Gives the pending frames whose photo <paramref name="to"/> holds their positions back.</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) is not { } at) continue;
|
||||
parked.Placed = changed = true;
|
||||
if (Flag(parked.Entry, "excluded"))
|
||||
{
|
||||
if (project["excludedFrames"] is not JsonArray positions) project["excludedFrames"] = positions = new JsonArray();
|
||||
if (!positions.Any(n => IsPosition(n, out var p) && p == at)) positions.Add(at);
|
||||
}
|
||||
// A hero chosen since the settings were taken is newer than the one that waited.
|
||||
if (Flag(parked.Entry, "hero") && project["heroFrame"] is null) project["heroFrame"] = at;
|
||||
if (parked.Entry["keyframes"] is JsonArray { Count: > 0 } keys)
|
||||
{
|
||||
if (project["camera"] is not JsonObject camera) project["camera"] = camera = new JsonObject();
|
||||
if (camera["keyframes"] is not JsonArray keyframes) camera["keyframes"] = keyframes = new JsonArray();
|
||||
foreach (var key in keys.OfType<JsonObject>())
|
||||
{
|
||||
// A keyframe set on that frame since is newer.
|
||||
if (keyframes.Any(n => n is JsonObject k && IsPosition(k["frame"], out var f) && f == at)) continue;
|
||||
var copy = key.DeepClone().AsObject();
|
||||
copy["frame"] = at;
|
||||
keyframes.Add(copy);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (project["heroFrame"] is null) return changed;
|
||||
// A hero is chosen: none waits any more, and an entry left with nothing to place goes.
|
||||
foreach (var parked in pending.Where(p => !p.Placed && Flag(p.Entry, "hero")))
|
||||
{
|
||||
parked.Entry["hero"] = false;
|
||||
parked.Placed = !Flag(parked.Entry, "excluded") && parked.Entry["keyframes"] is not JsonArray { Count: > 0 };
|
||||
changed = true;
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
/// <summary>Exclusions in ascending order without repeats and keyframes by frame (values that are no position last, as they were).</summary>
|
||||
private static void SortPositions(JsonObject project)
|
||||
{
|
||||
if (project["excludedFrames"] is JsonArray excluded)
|
||||
{
|
||||
var positions = excluded.Select(n => IsPosition(n, out var p) ? p : (int?)null).OfType<int>().Distinct().Order().Select(p => (JsonNode?)JsonValue.Create(p));
|
||||
Replace(excluded, [.. positions, .. excluded.Where(n => !IsPosition(n, out _)).Select(n => n?.DeepClone())]);
|
||||
}
|
||||
if (project["camera"] is JsonObject camera && camera["keyframes"] is JsonArray keyframes)
|
||||
{
|
||||
var sorted = keyframes.Select(n => n?.DeepClone())
|
||||
.OrderBy(n => n is JsonObject key && IsPosition(key["frame"], out var f) ? f : int.MaxValue).ToList();
|
||||
Replace(keyframes, sorted);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The pending entry of <paramref name="photo"/>, added when there is none.</summary>
|
||||
private static Parked Park(List<Parked> pending, FramePhoto photo)
|
||||
{
|
||||
if (pending.FirstOrDefault(p => p.Photo.Matches(photo)) is { } known) return known;
|
||||
var entry = new JsonObject();
|
||||
if (photo.IsHashed) entry["sha256"] = photo.Sha256!.ToLowerInvariant();
|
||||
entry["size"] = photo.Size;
|
||||
if (photo.CapturedAt is { } captured) entry["capturedAt"] = captured;
|
||||
entry["excluded"] = false;
|
||||
entry["hero"] = false;
|
||||
entry["keyframes"] = new JsonArray();
|
||||
var parked = new Parked(photo, entry);
|
||||
pending.Add(parked);
|
||||
return parked;
|
||||
}
|
||||
|
||||
/// <summary>The photo a pending entry names; null when it names none.</summary>
|
||||
private static FramePhoto? PhotoOf(JsonObject entry)
|
||||
{
|
||||
var sha = entry["sha256"] is JsonValue s && s.TryGetValue<string>(out var text) ? text : null;
|
||||
var size = entry["size"] is JsonValue z && z.TryGetValue<long>(out var bytes) ? bytes : -1;
|
||||
DateTime? captured = entry["capturedAt"] is JsonValue t && t.TryGetValue<DateTime>(out var time) ? time : null;
|
||||
return string.IsNullOrEmpty(sha) && (captured is null || size < 0) ? null : new FramePhoto(sha, size, captured);
|
||||
}
|
||||
|
||||
private static bool Flag(JsonObject entry, string name) => entry[name] is JsonValue value && value.TryGetValue<bool>(out var set) && set;
|
||||
|
||||
private static bool IsPosition(JsonNode? node, out int position)
|
||||
{
|
||||
position = 0;
|
||||
return node is JsonValue value && value.TryGetValue(out position);
|
||||
}
|
||||
|
||||
private static void Replace(JsonArray array, IEnumerable<JsonNode?> nodes)
|
||||
{
|
||||
var copy = nodes.ToList();
|
||||
array.Clear();
|
||||
foreach (var node in copy) array.Add(node);
|
||||
}
|
||||
|
||||
/// <summary>A pending entry being edited: its photo, its JSON, and whether its photo took its place.</summary>
|
||||
private sealed class Parked(FramePhoto photo, JsonObject entry)
|
||||
{
|
||||
public FramePhoto Photo { get; } = photo;
|
||||
public JsonObject Entry { get; } = entry;
|
||||
public bool Placed { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(
|
||||
|
||||
@@ -97,14 +97,14 @@ public sealed class ArchiveIndexer
|
||||
/// </summary>
|
||||
internal async Task SyncAsync(Archive archive, SequencePaths sequence, SequenceManifest manifest, CancellationToken cancellationToken)
|
||||
{
|
||||
(string Before, string Moved)? positions = null;
|
||||
PositionMove? positions = null;
|
||||
await using (var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var existing = await tx.Sequences.GetAsync(manifest.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (existing is not null)
|
||||
{
|
||||
positions = await ProjectPositions.MoveAsync(tx, existing, manifest, cancellationToken).ConfigureAwait(false);
|
||||
if (positions is { } project) existing = existing with { SettingsJson = project.Moved };
|
||||
if (positions is not null) existing = positions.ApplyTo(existing);
|
||||
}
|
||||
await tx.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, sequence, existing), cancellationToken).ConfigureAwait(false);
|
||||
await tx.Frames.SyncSequenceAsync(manifest.Id, SequenceMapping.ToFrames(manifest, sequence), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
@@ -457,7 +457,8 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
|
||||
/// <summary>
|
||||
/// Appends the new rows when the index was in step with the sidecar; otherwise (or when frames were repaired, whose
|
||||
/// flags change) resyncs the whole sequence, which also moves the project's frame positions after an insertion.
|
||||
/// flags change) resyncs the whole sequence, which also moves the project's frame positions after an insertion. A
|
||||
/// project waiting for photos taken from another copy's settings places those that arrived either way.
|
||||
/// </summary>
|
||||
private async Task IndexAsync(Archive archive, SequencePaths sequence, SequenceManifest manifest, int before, List<SidecarFrame> appended,
|
||||
bool repaired, CancellationToken cancellationToken)
|
||||
@@ -469,13 +470,20 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
await _indexer.SyncAsync(archive, sequence, manifest, cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
PositionMove? placed = null;
|
||||
await using (var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var existing = await tx.Sequences.GetAsync(manifest.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (existing is not null && ProjectPositions.Place(existing, manifest) is { } positions)
|
||||
{
|
||||
placed = positions;
|
||||
existing = positions.ApplyTo(existing);
|
||||
}
|
||||
await tx.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, sequence, existing), cancellationToken).ConfigureAwait(false);
|
||||
await tx.Frames.BulkInsertAsync(appended.Select(f => SequenceMapping.ToFrame(f, manifest.Id, sequence)), cancellationToken).ConfigureAwait(false);
|
||||
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
if (placed is not null) ProjectPositions.WriteProject(sequence, placed.Before, placed.Moved);
|
||||
await _indexer.RecordStampsAsync(archive, sequence, manifest.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
|
||||
@@ -14,17 +14,19 @@ namespace Titano.Data.Archiving;
|
||||
/// scan found, a sync download, a journalled batch completed after a crash. Positions name the frames in the indexed
|
||||
/// order (what editors, renders and the API read), so the old order comes from the index rows. Only an insertion is
|
||||
/// followed: when an indexed frame is no longer in the sidecar, positions cannot be mapped and stay as they are. The move
|
||||
/// is part of the frames change, not a settings edit, so the settings version stays and a synced copy receiving the
|
||||
/// same frames makes the same move.
|
||||
/// is part of the frames change, not a settings edit, so the settings version stays. Settings synced from another copy
|
||||
/// arrive translated to this copy's frames (<see cref="ProjectSettings.TranslateFramePositions"/>); their positions on
|
||||
/// photos that were not here yet (<see cref="ProjectSettings.PendingFrames"/>) take their place when the photos arrive,
|
||||
/// wherever they land.
|
||||
/// </summary>
|
||||
internal static class ProjectPositions
|
||||
{
|
||||
/// <summary>
|
||||
/// The index's copy of the project (the one in force) and the same project with its positions moved to the order of
|
||||
/// <paramref name="manifest"/>; null when nothing moves. A <c>project.json</c> the index has no copy of was written by
|
||||
/// another process against its own frames, so it is left to that writer.
|
||||
/// The index's copy of the project (the one in force) with its positions moved to the order of
|
||||
/// <paramref name="manifest"/> and its pending frames placed; null when nothing changes. A <c>project.json</c> the
|
||||
/// index has no copy of was written by another process against its own frames, so it is left to that writer.
|
||||
/// </summary>
|
||||
public static async Task<(string Before, string Moved)?> MoveAsync(TitanoRepositories db, Sequence indexed, SequenceManifest manifest,
|
||||
public static async Task<PositionMove?> MoveAsync(TitanoRepositories db, Sequence indexed, SequenceManifest manifest,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// The sidecar's frames are the ones indexed: nothing was inserted.
|
||||
@@ -33,13 +35,52 @@ internal static class ProjectPositions
|
||||
var rows = await db.Frames.ListPositionsAsync(indexed.Id, cancellationToken).ConfigureAwait(false);
|
||||
var now = new Dictionary<Guid, int>(manifest.Frames.Count);
|
||||
foreach (var frame in manifest.Frames) now[frame.Id] = frame.I;
|
||||
var moves = new Dictionary<int, int>();
|
||||
Dictionary<int, int>? moves = [];
|
||||
foreach (var row in rows)
|
||||
{
|
||||
if (!now.TryGetValue(row.FrameId, out var index)) return null;
|
||||
if (!now.TryGetValue(row.FrameId, out var index))
|
||||
{
|
||||
moves = null;
|
||||
break;
|
||||
}
|
||||
if (index != row.Index) moves[row.Index] = index;
|
||||
}
|
||||
return ProjectSettings.MoveFramePositions(project, moves) is { } moved ? (project, moved) : null;
|
||||
return Placed(project, moves is null ? null : ProjectSettings.MoveFramePositions(project, moves), manifest);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The index's copy of the project with the pending frames whose photos <paramref name="manifest"/> now holds put in
|
||||
/// place: frames appended in step with the index, which moves no position. Null when nothing changes.
|
||||
/// </summary>
|
||||
public static PositionMove? Place(Sequence indexed, SequenceManifest manifest) =>
|
||||
indexed.SettingsJson is { } project ? Placed(project, null, manifest) : null;
|
||||
|
||||
private static PositionMove? Placed(string before, string? moved, SequenceManifest manifest)
|
||||
{
|
||||
var current = moved ?? before;
|
||||
// Most projects wait for no photo: the sidecar's photos are gathered only for those that do.
|
||||
var placed = current.Contains("pendingFrames", StringComparison.OrdinalIgnoreCase)
|
||||
? ProjectSettings.TranslateFramePositions(current, null, new FramePhotos(manifest.Frames.Select(f => (f.I, new FramePhoto(f.Sha256, f.Size, f.CapturedAt)))))
|
||||
: null;
|
||||
if ((placed ?? moved) is not { } after) return null;
|
||||
// A hero that waited for its photo names a frame the Library shows too.
|
||||
var hero = placed is not null && HeroOf(current) is null && HeroOf(placed) is { } index ? manifest.Frames.FirstOrDefault(f => f.I == index)?.Id : null;
|
||||
return new PositionMove(before, after, hero);
|
||||
}
|
||||
|
||||
private static int? HeroOf(string json)
|
||||
{
|
||||
try
|
||||
{
|
||||
return JsonNode.Parse(json, new JsonNodeOptions { PropertyNameCaseInsensitive = true }) is JsonObject project
|
||||
&& project["heroFrame"] is JsonValue value && value.TryGetValue<int>(out var hero)
|
||||
? hero
|
||||
: null;
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or ArgumentException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -73,3 +114,13 @@ internal static class ProjectPositions
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A project whose positions followed its frames: the index's copy before and after, and the frame a hero that waited
|
||||
/// for its photo now names (the index's hero frame follows it); null when the hero frame stays.
|
||||
/// </summary>
|
||||
internal sealed record PositionMove(string Before, string Moved, Guid? HeroFrameId)
|
||||
{
|
||||
/// <summary>The index row with the moved project.</summary>
|
||||
public Sequence ApplyTo(Sequence row) => row with { SettingsJson = Moved, HeroFrameId = HeroFrameId ?? row.HeroFrameId };
|
||||
}
|
||||
@@ -233,12 +233,22 @@ public sealed class SequenceRepository
|
||||
/// changed the sequence first (BRIEF §14.5).
|
||||
/// </summary>
|
||||
public Task<SequenceEditResult> EditAsync(Guid id, SequenceEdit edit, int? expectedSettingsVersion, CancellationToken cancellationToken = default) =>
|
||||
EditAsync(id, edit, expectedSettingsVersion, null, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="EditAsync(Guid, SequenceEdit, int?, CancellationToken)"/>, also refused when the sequence's frames
|
||||
/// version is no longer <paramref name="expectedFramesVersion"/>: settings naming frames by position were written
|
||||
/// against frames that changed since.
|
||||
/// </summary>
|
||||
public Task<SequenceEditResult> EditAsync(Guid id, SequenceEdit edit, int? expectedSettingsVersion, int? expectedFramesVersion,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
_db.InTransactionAsync(async session =>
|
||||
{
|
||||
var current = await session.QuerySingleOrDefaultAsync($"{_select} WHERE s.id = $1{_db.Sql.ForUpdate}", [id], Map, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (current is null) return new SequenceEditResult(SequenceEditOutcome.NotFound, null);
|
||||
if (expectedSettingsVersion is { } expected && expected != current.SettingsVersion)
|
||||
if ((expectedSettingsVersion is { } expected && expected != current.SettingsVersion)
|
||||
|| (expectedFramesVersion is { } frames && frames != current.FramesVersion))
|
||||
return new SequenceEditResult(SequenceEditOutcome.Conflict, current);
|
||||
var hero = current.HeroFrameId;
|
||||
if (edit.HeroFrameId == Guid.Empty) hero = null;
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
using Titano.Core.Project;
|
||||
using Titano.Protocol;
|
||||
using SequenceFrames = Titano.Data.Processing.SequenceFrames;
|
||||
|
||||
namespace Titano.Data.Sync;
|
||||
|
||||
/// <summary>
|
||||
/// The frame positions of settings crossing between a local copy and its server sequence (exclusions, hero, camera
|
||||
/// keyframes; BRIEF §5, §14.5). Each copy numbers its frames in capture order, and the two may hold different photos
|
||||
/// while originals are still to travel, so settings are translated by photo on the way: the server's are moved to this
|
||||
/// copy's frames before they are compared or applied, and this copy's to the server's frames as
|
||||
/// <paramref name="manifest"/> lists them before they are sent. A position on a photo the receiving copy lacks waits
|
||||
/// there as a pending frame and takes its place when the photo arrives (<see cref="ProjectSettings.TranslateFramePositions"/>).
|
||||
/// </summary>
|
||||
internal sealed class SyncPositions(TitanoDatabase db, ISyncRemote remote, Guid localId, SequenceManifest manifest)
|
||||
{
|
||||
private FramePhotos? _server;
|
||||
|
||||
/// <summary>The server's frames version the translation to the server's frames is made against.</summary>
|
||||
public int ServerFrames => manifest.FramesVersion;
|
||||
|
||||
/// <summary>Settings of the server sequence with their positions on this copy's frames, as they are now.</summary>
|
||||
public async Task<string?> ToLocalAsync(string? settingsJson, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!ProjectSettings.NamesFrames(settingsJson)) return settingsJson;
|
||||
var local = await LocalAsync(cancellationToken).ConfigureAwait(false);
|
||||
var server = await ServerAsync(local, cancellationToken).ConfigureAwait(false);
|
||||
return ProjectSettings.TranslateFramePositions(settingsJson!, server, local) ?? settingsJson;
|
||||
}
|
||||
|
||||
/// <summary>Settings of this copy with their positions on the server's frames.</summary>
|
||||
public async Task<string?> ToServerAsync(string? settingsJson, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!ProjectSettings.NamesFrames(settingsJson)) return settingsJson;
|
||||
var local = await LocalAsync(cancellationToken).ConfigureAwait(false);
|
||||
var server = await ServerAsync(local, cancellationToken).ConfigureAwait(false);
|
||||
return ProjectSettings.TranslateFramePositions(settingsJson!, local, server) ?? settingsJson;
|
||||
}
|
||||
|
||||
/// <summary>This copy's frames, read each time (an import may insert some between a comparison and a write).</summary>
|
||||
private async Task<FramePhotos> LocalAsync(CancellationToken cancellationToken) =>
|
||||
new((await SequenceFrames.ListAsync(db, localId, cancellationToken).ConfigureAwait(false))
|
||||
.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, f.CapturedAt))));
|
||||
|
||||
/// <summary>
|
||||
/// The server's frames from the manifest; their capture times are fetched only when a frame of either side is not
|
||||
/// hashed, since such a frame is matched by size and capture time.
|
||||
/// </summary>
|
||||
private async Task<FramePhotos> ServerAsync(FramePhotos local, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_server is not null) return _server;
|
||||
IReadOnlyDictionary<Guid, DateTime?> captured = new Dictionary<Guid, DateTime?>();
|
||||
if (local.HasUnhashed || manifest.Frames.Any(f => f.Sha256.Length == 0))
|
||||
captured = (await remote.ListFramesAsync(manifest.SequenceId, cancellationToken).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt);
|
||||
return _server = new FramePhotos(manifest.Frames.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, captured.GetValueOrDefault(f.Id)))));
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,10 @@ public interface ISyncRemote : IDisposable
|
||||
async Task<FrameDto?> FirstFrameAsync(Guid sequenceId, CancellationToken cancellationToken) =>
|
||||
(await ListFramesAsync(sequenceId, cancellationToken).ConfigureAwait(false)).FirstOrDefault();
|
||||
|
||||
/// <summary>A 409 <see cref="TitanoApiException"/> means the settings version moved on the server.</summary>
|
||||
/// <summary>
|
||||
/// A 409 <see cref="TitanoApiException"/> means the settings version moved on the server, or its frames did since
|
||||
/// <see cref="UpdateSequenceRequest.ExpectedFramesVersion"/>.
|
||||
/// </summary>
|
||||
Task<SequenceDto> UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -26,9 +26,13 @@ public sealed record SyncPayload(string? Title, IReadOnlyList<string> Tags, int
|
||||
|
||||
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);
|
||||
/// <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)]
|
||||
|
||||
@@ -8,6 +8,7 @@ using Titano.Core.Diagnostics;
|
||||
using Titano.Core.IO;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Data.Archiving;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Data.Processing;
|
||||
@@ -40,7 +41,8 @@ public sealed record SyncOptions
|
||||
/// and, when frame counters or render counts moved, the manifest: originals are matched by SHA-256 and never conflict;
|
||||
/// renders by id. Settings, title, tags, rating and notes travel together under the settings version, so a change on
|
||||
/// one side is sent or taken (automatically or on request) and a change on both sides with different content is a
|
||||
/// conflict the user settles with <see cref="ResolveAsync"/>, against the versions the user was shown. Uploads and
|
||||
/// conflict the user settles with <see cref="ResolveAsync"/>, against the versions the user was shown. The settings'
|
||||
/// frame positions are translated by photo to the frames of the copy they go to (<see cref="SyncPositions"/>). Uploads and
|
||||
/// downloads run as jobs (<see cref="CreateJobHandlers"/>): uploads use the chunked, hash-verified, resumable protocol;
|
||||
/// downloaded originals are verified and committed through the archive ingest, so sidecars stay right; proxies go to a
|
||||
/// cache and open as a <see cref="RemoteSequence"/>; renders travel on request. Thumbnails never travel upward, and
|
||||
@@ -185,7 +187,7 @@ public sealed class SyncService
|
||||
try
|
||||
{
|
||||
var (link, local) = await LinkedAsync(remote.Server, remoteId, cancellationToken).ConfigureAwait(false);
|
||||
if (link is not { ConflictRemote: { } theirs, ConflictLocalSettings: { } seenLocal, ConflictRemoteSettings: { } seenRemote }
|
||||
if (link is not { ConflictRemote: not null, ConflictLocalSettings: { } seenLocal, ConflictRemoteSettings: { } seenRemote }
|
||||
|| local.SettingsVersion != seenLocal)
|
||||
{
|
||||
changed = true;
|
||||
@@ -194,7 +196,9 @@ public sealed class SyncService
|
||||
{
|
||||
try
|
||||
{
|
||||
var updated = await remote.UpdateSequenceAsync(remoteId, SyncPayload.Of(local).ToRequest(seenRemote), cancellationToken).ConfigureAwait(false);
|
||||
var manifest = await remote.GetManifestAsync(remoteId, cancellationToken).ConfigureAwait(false);
|
||||
var request = await RequestAsync(remote, local, manifest, seenRemote, cancellationToken).ConfigureAwait(false);
|
||||
var updated = await remote.UpdateSequenceAsync(remoteId, request, cancellationToken).ConfigureAwait(false);
|
||||
link = Agreed(Observe(link, remote.Server, updated), local.SettingsVersion, updated.SettingsVersion);
|
||||
}
|
||||
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict)
|
||||
@@ -204,15 +208,18 @@ public sealed class SyncService
|
||||
}
|
||||
else
|
||||
{
|
||||
// The server's version as it is now: the one shown, with its positions on the server's current frames.
|
||||
var dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false);
|
||||
if (dto.SettingsVersion != seenRemote)
|
||||
var manifest = dto.SettingsVersion == seenRemote ? await remote.GetManifestAsync(remoteId, cancellationToken).ConfigureAwait(false) : null;
|
||||
if (manifest?.SettingsVersion != seenRemote)
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (resolution == SyncResolution.SaveBoth) saved = await SaveCopyAsync(local, cancellationToken).ConfigureAwait(false);
|
||||
if (await ApplyLocallyAsync(local, theirs, cancellationToken).ConfigureAwait(false) is { } applied)
|
||||
var theirs = SyncPayload.Of(dto, manifest!.SettingsJson);
|
||||
if (await ApplyLocallyAsync(local, theirs, Positions(remote, local, manifest), cancellationToken).ConfigureAwait(false) is { } applied)
|
||||
{
|
||||
link = Agreed(Observe(link, remote.Server, dto), applied.SettingsVersion, seenRemote);
|
||||
}
|
||||
@@ -339,11 +346,11 @@ public sealed class SyncService
|
||||
var (link, local) = await LinkedAsync(remote.Server, remoteId, cancellationToken).ConfigureAwait(false);
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
var dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false);
|
||||
var manifest = await remote.GetManifestAsync(remoteId, cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var updated = await remote.UpdateSequenceAsync(remoteId, SyncPayload.Of(local).ToRequest(dto.SettingsVersion), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
var request = await RequestAsync(remote, local, manifest, manifest.SettingsVersion, cancellationToken).ConfigureAwait(false);
|
||||
var updated = await remote.UpdateSequenceAsync(remoteId, request, cancellationToken).ConfigureAwait(false);
|
||||
await _links.UpsertAsync(Agreed(Observe(link, remote.Server, updated), local.SettingsVersion, updated.SettingsVersion), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return;
|
||||
@@ -370,7 +377,8 @@ public sealed class SyncService
|
||||
var dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false);
|
||||
var manifest = await remote.GetManifestAsync(remoteId, cancellationToken).ConfigureAwait(false);
|
||||
// Edited on this PC meanwhile: nothing is agreed yet, so the next comparison settles both sides' content.
|
||||
if (await ApplyLocallyAsync(local, SyncPayload.Of(dto, manifest.SettingsJson), cancellationToken).ConfigureAwait(false) is not { } applied) return;
|
||||
if (await ApplyLocallyAsync(local, SyncPayload.Of(dto, manifest.SettingsJson), Positions(remote, local, manifest), cancellationToken)
|
||||
.ConfigureAwait(false) is not { } applied) return;
|
||||
await _links.UpsertAsync(Agreed(Observe(link, remote.Server, dto), applied.SettingsVersion, manifest.SettingsVersion), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
@@ -543,6 +551,9 @@ public sealed class SyncService
|
||||
var localChanged = link.BaseLocalSettings != local.SettingsVersion;
|
||||
var remoteChanged = link.BaseRemoteSettings != link.RemoteSettingsVersion;
|
||||
if (!localChanged && !remoteChanged) return (link, local);
|
||||
// Frames inserted here since the copy was listed moved its positions without a new settings version.
|
||||
if (await _db.Sequences.GetAsync(local.Id, cancellationToken).ConfigureAwait(false) is { } current && current.SettingsVersion == local.SettingsVersion)
|
||||
local = current;
|
||||
if (localChanged && remoteChanged)
|
||||
{
|
||||
if (link.ConflictLocalSettings == local.SettingsVersion && link.ConflictRemoteSettings == link.RemoteSettingsVersion) return (link, local);
|
||||
@@ -550,7 +561,8 @@ public sealed class SyncService
|
||||
// The listing and the manifest disagree: the server changed during the comparison; settle it next time.
|
||||
if (manifest.SettingsVersion != dto.SettingsVersion) return (link, local);
|
||||
var mine = SyncPayload.Of(local);
|
||||
var theirs = SyncPayload.Of(dto, manifest.SettingsJson);
|
||||
// Compared (and shown) with its positions on this copy's frames: the same photos are the same settings.
|
||||
var theirs = SyncPayload.Of(dto, await Positions(remote, local, manifest).ToLocalAsync(manifest.SettingsJson, cancellationToken).ConfigureAwait(false));
|
||||
if (mine.SameAs(theirs)) return (Agreed(link, local.SettingsVersion, manifest.SettingsVersion), local);
|
||||
// Last writer wins only when one side changed; both changed differently is the user's choice (BRIEF §14.5).
|
||||
return (link with
|
||||
@@ -562,10 +574,15 @@ public sealed class SyncService
|
||||
}
|
||||
if (!policy.AutoSyncSettings) return (link, local);
|
||||
if (localChanged)
|
||||
return (policy.CanEdit ? await PushAsync(remote, link, local, link.BaseRemoteSettings, cancellationToken).ConfigureAwait(false) : link, local);
|
||||
{
|
||||
if (!policy.CanEdit) return (link, local);
|
||||
manifest ??= await remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false);
|
||||
return (await PushAsync(remote, link, local, manifest, link.BaseRemoteSettings, cancellationToken).ConfigureAwait(false), local);
|
||||
}
|
||||
manifest ??= await remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false);
|
||||
if (manifest.SettingsVersion != dto.SettingsVersion) return (link, local);
|
||||
if (await ApplyLocallyAsync(local, SyncPayload.Of(dto, manifest.SettingsJson), cancellationToken).ConfigureAwait(false) is { } pulled)
|
||||
if (await ApplyLocallyAsync(local, SyncPayload.Of(dto, manifest.SettingsJson), Positions(remote, local, manifest), cancellationToken)
|
||||
.ConfigureAwait(false) is { } pulled)
|
||||
return (Agreed(link, pulled.SettingsVersion, manifest.SettingsVersion), pulled);
|
||||
// The local copy was read when the comparison began and an edit was saved on this PC since: both sides changed,
|
||||
// so the server's version must not replace it unseen (BRIEF §14.5).
|
||||
@@ -574,12 +591,17 @@ public sealed class SyncService
|
||||
return await SettleSettingsAsync(remote, link, dto, fresh, manifest, policy, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Sends this PC's payload unless the server moved past <paramref name="expected"/>, which shows up as a conflict next.</summary>
|
||||
private static async Task<SyncLink> PushAsync(ISyncRemote remote, SyncLink link, Sequence local, int? expected, CancellationToken cancellationToken)
|
||||
/// <summary>
|
||||
/// Sends this PC's payload unless the server moved past <paramref name="expected"/>, which shows up as a conflict next,
|
||||
/// or its frames changed since <paramref name="manifest"/> (the positions are translated again next time).
|
||||
/// </summary>
|
||||
private async Task<SyncLink> PushAsync(ISyncRemote remote, SyncLink link, Sequence local, SequenceManifest manifest, int? expected,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var updated = await remote.UpdateSequenceAsync(link.RemoteId, SyncPayload.Of(local).ToRequest(expected), cancellationToken).ConfigureAwait(false);
|
||||
var request = await RequestAsync(remote, local, manifest, expected, cancellationToken).ConfigureAwait(false);
|
||||
var updated = await remote.UpdateSequenceAsync(link.RemoteId, request, cancellationToken).ConfigureAwait(false);
|
||||
return Agreed(Observe(link, link.Server, updated), local.SettingsVersion, updated.SettingsVersion);
|
||||
}
|
||||
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict)
|
||||
@@ -588,6 +610,21 @@ public sealed class SyncService
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The PATCH that makes the server's copy equal to <paramref name="local"/>, its frame positions moved to the server's
|
||||
/// frames as <paramref name="manifest"/> lists them; the server refuses it when its frames changed since.
|
||||
/// </summary>
|
||||
private async Task<UpdateSequenceRequest> RequestAsync(ISyncRemote remote, Sequence local, SequenceManifest manifest, int? expected,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var positions = Positions(remote, local, manifest);
|
||||
var settings = await positions.ToServerAsync(local.SettingsJson, cancellationToken).ConfigureAwait(false);
|
||||
var frames = ProjectSettings.NamesFrames(local.SettingsJson) ? positions.ServerFrames : (int?)null;
|
||||
return (SyncPayload.Of(local) with { SettingsJson = settings }).ToRequest(expected, frames);
|
||||
}
|
||||
|
||||
private SyncPositions Positions(ISyncRemote remote, Sequence local, SequenceManifest manifest) => new(_db, remote, local.Id, manifest);
|
||||
|
||||
/// <summary>
|
||||
/// Links local copies and server sequences that hold the same originals but no link joins (an Uploader upload of
|
||||
/// the same card, a link lost with an old index): candidates start at the same second with the same camera, and
|
||||
@@ -648,12 +685,21 @@ public sealed class SyncService
|
||||
private static bool SameMoment(DateTimeOffset a, DateTimeOffset b) => a.UtcTicks / 10 == b.UtcTicks / 10;
|
||||
|
||||
/// <summary>
|
||||
/// Writes a payload into the local index, project and sidecar in one step (settings version + 1) under the sequence's
|
||||
/// lease, which the editor's saves take too, and only while the local copy is still at the settings version
|
||||
/// <paramref name="local"/> was read at. Null when an edit was saved on this PC since: nothing is written then.
|
||||
/// Writes the server's payload into the local index, project and sidecar in one step (settings version + 1) under the
|
||||
/// sequence's lease, which the editor's saves take too, and only while the local copy is still at the settings version
|
||||
/// <paramref name="local"/> was read at. The settings' frame positions are moved to this copy's frames as they are
|
||||
/// under the lease (<paramref name="positions"/>). Null when an edit was saved on this PC since: nothing is written
|
||||
/// then. A payload the local copy already holds writes nothing, so it needs neither a writable archive nor the lease.
|
||||
/// </summary>
|
||||
private async Task<Sequence?> ApplyLocallyAsync(Sequence local, SyncPayload payload, CancellationToken cancellationToken)
|
||||
private async Task<Sequence?> ApplyLocallyAsync(Sequence local, SyncPayload payload, SyncPositions positions, CancellationToken cancellationToken)
|
||||
{
|
||||
var stored = await _db.Sequences.GetAsync(local.Id, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new InvalidDataException($"Sequence {local.Id} is not indexed.");
|
||||
if (stored.SettingsVersion != local.SettingsVersion) return null;
|
||||
// Settled as it is: an archive that is offline or read-only does not keep the link from being agreed.
|
||||
var mapped = payload with { SettingsJson = await positions.ToLocalAsync(payload.SettingsJson, cancellationToken).ConfigureAwait(false) };
|
||||
if (mapped.SameAs(SyncPayload.Of(stored))) return stored;
|
||||
|
||||
var archive = await _db.Archives.GetAsync(local.ArchiveId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new InvalidDataException($"Archive {local.ArchiveId} is not indexed.");
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
@@ -664,6 +710,8 @@ public sealed class SyncService
|
||||
var row = await _db.Sequences.GetAsync(local.Id, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new InvalidDataException($"Sequence {local.Id} is not indexed.");
|
||||
if (row.SettingsVersion != local.SettingsVersion) return null;
|
||||
// The frames cannot change under the lease: the positions are moved to them as they are now.
|
||||
payload = payload with { SettingsJson = await positions.ToLocalAsync(payload.SettingsJson, cancellationToken).ConfigureAwait(false) };
|
||||
var metadata = !payload.SameMetadata(SyncPayload.Of(row));
|
||||
var settings = !SyncRules.SameSettings(payload.SettingsJson, row.SettingsJson);
|
||||
if (!metadata && !settings) return row;
|
||||
|
||||
@@ -37,6 +37,8 @@ public sealed record CreateSequenceRequest(string? Title, string? CameraHint);
|
||||
/// <summary>
|
||||
/// <c>PATCH /api/v1/sequences/{id}</c>. <see cref="ExpectedSettingsVersion"/> enables conflict detection (409).
|
||||
/// <see cref="HeroFrameId"/> names the frame the sequence shows (one of its own; <see cref="Guid.Empty"/> clears it).
|
||||
/// <see cref="ExpectedFramesVersion"/> is the frames version the settings' frame positions were written against: the
|
||||
/// edit is refused (409 <c>frames_conflict</c>) when frames were added or removed since.
|
||||
/// </summary>
|
||||
public sealed record UpdateSequenceRequest(
|
||||
string? Title,
|
||||
@@ -45,7 +47,8 @@ public sealed record UpdateSequenceRequest(
|
||||
string? Notes,
|
||||
string? SettingsJson,
|
||||
int? ExpectedSettingsVersion,
|
||||
Guid? HeroFrameId = null);
|
||||
Guid? HeroFrameId = null,
|
||||
int? ExpectedFramesVersion = null);
|
||||
|
||||
/// <param name="PreviewWidth">Width of the largest embedded preview before orientation, like <paramref name="Width"/>; 0 when unknown.</param>
|
||||
/// <param name="PreviewHeight">Height of that preview before orientation; 0 when unknown.</param>
|
||||
|
||||
@@ -140,14 +140,18 @@ public static class SequenceEndpoints
|
||||
HeroFrameId = request.HeroFrameId
|
||||
?? (request.SettingsJson is { } settings ? await SettingsHeroAsync(db, id, settings, context.RequestAborted) : null),
|
||||
};
|
||||
var result = await db.Sequences.EditAsync(id, edit, expected, context.RequestAborted);
|
||||
var result = await db.Sequences.EditAsync(id, edit, expected, request.ExpectedFramesVersion, context.RequestAborted);
|
||||
switch (result.Outcome)
|
||||
{
|
||||
case SequenceEditOutcome.NotFound:
|
||||
return ApiErrors.NotFound(context, "sequence");
|
||||
case SequenceEditOutcome.Conflict when expected is { } settingsVersion && settingsVersion != result.Sequence!.SettingsVersion:
|
||||
context.Response.Headers.ETag = ETag(result.Sequence);
|
||||
return ApiErrors.Conflict(context, "settings_conflict", result.Sequence.SettingsVersion.ToString(CultureInfo.InvariantCulture));
|
||||
case SequenceEditOutcome.Conflict:
|
||||
// The settings name frames by position and were written against frames that changed since.
|
||||
context.Response.Headers.ETag = ETag(result.Sequence!);
|
||||
return ApiErrors.Conflict(context, "settings_conflict", result.Sequence!.SettingsVersion.ToString(CultureInfo.InvariantCulture));
|
||||
return ApiErrors.Conflict(context, "frames_conflict", result.Sequence!.FramesVersion.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
var sequence = result.Sequence!;
|
||||
await audit.WriteAsync(caller, context, "sequence_updated", "sequence", id.ToString(), Changes(request));
|
||||
|
||||
Reference in new issue
Block a user