fix: full verification against the brief — 137 confirmed findings fixed over six passes #4

Merged
Alby96 merged 169 commits from claude/keen-knuth-uhxv8w into main 2026-10-13 12:10:04 +02:00
32 changed files with 1843 additions and 153 deletions
Showing only changes of commit 51acc7f91b - Show all commits

No files matched your search

+1 -1
View File
@@ -58,7 +58,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
| `Jobs` | `JobEngine` (its number of workers can change while it runs), `IJobHandler`, `IJobHandlerProvider`, `JobContext` (progress, checkpoints, follow-up jobs) |
| `Archiving` | `ArchiveService` (create/adopt/open, archive settings written to `archive.json` then the index), `ArchiveIndexer` (scan, rebuild), `ArchiveIngest` (uploads and imports), `ImportService`, `ArchiveVerifier`, `ArchiveImages`, `FrameTiers` (decode tier, `PreviewOnly`/`Undecodable` flags and preview size of frames, written to sidecar and index by the light analysis, deep analysis, renders and image passes), `GprCompanions` (the JPEG of each GoPro GPR, found in the index when an import kept it in another sequence), `ArchiveMaintenance`, `MassRenamer`, `SequenceTrash` (delete into the archive's hidden trash with a dry run, restore; the folder moves back when the index step fails), job handlers |
| `Processing` | `ProcessingService`, `SequenceAnalyser`, `DeepReports` (a saved deep report while it still describes the frames), `SequenceRender`, `ProjectStore`, `ProjectBundles` (a `.titano` file for a sequence, and the sequence a file names), `RenderNodeClient`, job handlers |
| `Sync` | `SyncService` (sync table of one server: compare, link by content, settle conflicts, enqueue transfers), `SyncRules` (status, settings merge and differences, no I/O), `SyncLinkStore` (`sync_links`, `sync_state`), `SyncTransfers` and `SyncJobHandler` (resumable, hash-verified uploads and downloads as jobs; downloads commit through the archive ingest), `SyncAgent` (background comparison, server events, backoff, offline proxies), `ProxyCache` and `RemoteSequence` (server sequences opened with proxies), `ISyncRemote` (the server calls; `TitanoSyncRemote` over `TitanoClient`) |
| `Sync` | `SyncService` (sync table of one server: compare, link by content, settle conflicts, enqueue transfers), `SyncRules` (status, settings merge and differences, no I/O), `SyncPositions` (the settings' frame positions translated by photo to the frames of the copy they go to), `SyncLinkStore` (`sync_links`, `sync_state`), `SyncTransfers` and `SyncJobHandler` (resumable, hash-verified uploads and downloads as jobs; downloads commit through the archive ingest), `SyncAgent` (background comparison, server events, backoff, offline proxies), `ProxyCache` and `RemoteSequence` (server sequences opened with proxies), `ISyncRemote` (the server calls; `TitanoSyncRemote` over `TitanoClient`) |
### 2.3 Titano.App areas
+1
View File
@@ -43,6 +43,7 @@
<data name="Server.Error.FolderInUse" xml:space="preserve"><value>A file of the sequence is open in another program; close it and try again.</value><comment>long</comment></data>
<data name="Server.Error.FolderMissing" xml:space="preserve"><value>Its folder is no longer on disk; nothing is left to move to the trash.</value><comment>long</comment></data>
<data name="Server.Error.Forbidden" xml:space="preserve"><value>Your account cannot do this.</value><comment>long</comment></data>
<data name="Server.Error.FramesConflict" xml:space="preserve"><value>The photos of the sequence changed on the server; reload it and apply your edit again.</value><comment>long</comment></data>
<data name="Server.Error.HashMismatch" xml:space="preserve"><value>The file arrived damaged; upload it again.</value><comment>long</comment></data>
<data name="Server.Error.HttpsRequired" xml:space="preserve"><value>Open the admin panel over HTTPS to sign in.</value><comment>long</comment></data>
<data name="Server.Error.Incomplete" xml:space="preserve"><value>Some chunks are still missing.</value><comment>long</comment></data>
+1
View File
@@ -41,6 +41,7 @@
<data name="Server.Error.FolderInUse" xml:space="preserve"><value>Un file della sequenza è aperto in un altro programma; chiudilo e riprova.</value></data>
<data name="Server.Error.FolderMissing" xml:space="preserve"><value>La sua cartella non è più sul disco; non resta nulla da spostare nel cestino.</value></data>
<data name="Server.Error.Forbidden" xml:space="preserve"><value>Il tuo account non può farlo.</value></data>
<data name="Server.Error.FramesConflict" xml:space="preserve"><value>Le foto della sequenza sono cambiate sul server; ricaricala e riapplica la modifica.</value></data>
<data name="Server.Error.HashMismatch" xml:space="preserve"><value>Il file è arrivato danneggiato; caricalo di nuovo.</value></data>
<data name="Server.Error.HttpsRequired" xml:space="preserve"><value>Apri il pannello di amministrazione in HTTPS per accedere.</value></data>
<data name="Server.Error.Incomplete" xml:space="preserve"><value>Mancano ancora alcuni blocchi.</value></data>
+2 -1
View File
@@ -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()
{
+88
View File
@@ -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;
}
}
+1
View File
@@ -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 },
};
+287
View File
@@ -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,256 @@ 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 hero chosen since one was left pending is newer, so that one no
/// longer waits even when the chosen one must wait in turn), 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 = false;
if (project["heroFrame"] is JsonValue && pending.Any(p => Flag(p.Entry, "hero")))
{
// Checked before the hero itself may be parked below, which leaves no hero chosen.
foreach (var parked in pending) parked.Entry["hero"] = false;
pending.RemoveAll(p => !Waits(p.Entry));
changed = true;
}
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 = !Waits(parked.Entry);
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;
/// <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 };
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(
+4 -3
View File
@@ -103,14 +103,15 @@ 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);
// Locked: a settings edit committed after this read (the server's PATCH takes no lease) would be written back over.
var existing = await tx.Sequences.GetForUpdateAsync(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);
+13 -3
View File
@@ -195,7 +195,8 @@ public sealed class ArchiveIngest : IArchiveIngest
{
if (row.SettingsJson is { } settings) AtomicFile.WriteAllText(sequence.ProjectPath, settings);
await using var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false);
var current = await tx.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false)
// Locked, so an edit of the new sequence committed meanwhile is not written back over.
var current = await tx.Sequences.GetForUpdateAsync(sequenceId, cancellationToken).ConfigureAwait(false)
?? throw new InvalidOperationException($"Sequence {sequenceId} was deleted before its first frame.");
await tx.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, sequence, current), cancellationToken).ConfigureAwait(false);
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
@@ -457,7 +458,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 +471,21 @@ 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);
// Locked: a settings edit committed after this read (the server's PATCH takes no lease) would be written back over.
var existing = await tx.Sequences.GetForUpdateAsync(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);
}
+60 -9
View File
@@ -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 };
}
@@ -167,6 +167,14 @@ public sealed class SequenceRepository
public Task<Sequence?> GetAsync(Guid id, CancellationToken cancellationToken = default) =>
_db.SingleAsync($"{_select} WHERE s.id = $1", [id], Map, cancellationToken);
/// <summary>
/// <see cref="GetAsync"/> inside a transaction, the row locked until it ends (PostgreSQL; SQLite's write lock already
/// serialises writers): a transaction that writes the whole row back from this read cannot undo an edit that another
/// one commits meanwhile, as <see cref="EditAsync(Guid, SequenceEdit, int?, int?, CancellationToken)"/> takes the same lock.
/// </summary>
public Task<Sequence?> GetForUpdateAsync(Guid id, CancellationToken cancellationToken = default) =>
_db.SingleAsync($"{_select} WHERE s.id = $1{_db.Sql.ForUpdate}", [id], Map, cancellationToken);
/// <summary>Deletes the sequence with its frames, renders and tag links.</summary>
public async Task<bool> DeleteAsync(Guid id, CancellationToken cancellationToken = default) =>
await _db.ExecuteAsync("DELETE FROM sequences WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) > 0;
@@ -233,12 +241,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;
+46 -14
View File
@@ -57,7 +57,12 @@ public sealed class RemoteSequence
}
/// <summary>What the proxy cache keeps next to the files of one server sequence.</summary>
internal sealed record ProxyCacheIndex(SequenceDto Sequence, string? SettingsJson, int FramesVersion, IReadOnlyList<FrameDto> Frames, IReadOnlyList<string?> Files);
/// <param name="Kinds">
/// What each file is, in frame order: <see cref="ProxyCache.Proxy"/> or <see cref="ProxyCache.Thumb"/> (a thumbnail standing in
/// while the server has no proxy of the frame); null where no file is cached, and for a cache written before kinds were kept.
/// </param>
internal sealed record ProxyCacheIndex(SequenceDto Sequence, string? SettingsJson, int FramesVersion, IReadOnlyList<FrameDto> Frames, IReadOnlyList<string?> Files,
IReadOnlyList<string?>? Kinds = null);
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
[JsonSerializable(typeof(ProxyCacheIndex))]
@@ -70,6 +75,12 @@ internal sealed partial class ProxyCacheJson : JsonSerializerContext;
/// </summary>
internal sealed class ProxyCache(string root)
{
/// <summary>The asset kind of a cached proxy (the server's name for it).</summary>
public const string Proxy = "proxy";
/// <summary>The asset kind of a thumbnail cached in place of a proxy the server did not have.</summary>
public const string Thumb = "thumb";
private const string IndexFile = "remote.json";
public string Folder(string server, Guid remoteId) =>
@@ -82,23 +93,26 @@ internal sealed class ProxyCache(string root)
public void Save(string server, Guid remoteId, ProxyCacheIndex index) =>
AtomicFile.WriteAllText(Path.Combine(Folder(server, remoteId), IndexFile), JsonSerializer.Serialize(index, ProxyCacheJson.Default.ProxyCacheIndex));
/// <summary>
/// What each cached file of a server sequence is, by frame id (<see cref="ProxyCacheIndex.Kinds"/>): none for a frame
/// without a file, null for a file of a cache written before kinds were kept.
/// </summary>
public IReadOnlyDictionary<Guid, string?> Kinds(string server, Guid remoteId)
{
var kinds = new Dictionary<Guid, string?>();
if (ReadIndex(server, remoteId) is not { } index) return kinds;
for (var i = 0; i < index.Frames.Count; i++)
{
if (index.Files[i] is not null) kinds[index.Frames[i].Id] = index.Kinds is { } known && i < known.Count ? known[i] : null;
}
return kinds;
}
/// <summary>The cached sequence, or null when it was never cached or the cache was cleared.</summary>
public RemoteSequence? Load(string server, Guid remoteId)
{
var folder = Folder(server, remoteId);
var path = Path.Combine(folder, IndexFile);
if (!File.Exists(path)) return null;
ProxyCacheIndex? index;
try
{
index = JsonSerializer.Deserialize(File.ReadAllText(path), ProxyCacheJson.Default.ProxyCacheIndex);
}
catch (Exception ex) when (ex is JsonException or IOException)
{
Log.Warning("sync", $"Proxy cache of {remoteId} is unreadable", ex);
return null;
}
if (index is null || index.Files.Count != index.Frames.Count) return null;
if (ReadIndex(server, remoteId) is not { } index) return null;
var dto = index.Sequence;
var sequence = RenderNodeClient.ToSequence(dto) with
{
@@ -126,6 +140,24 @@ internal sealed class ProxyCache(string root)
return new RemoteSequence(server, sequence, frames, files);
}
/// <summary>The index of a cached sequence; null when there is none or it cannot be read.</summary>
private ProxyCacheIndex? ReadIndex(string server, Guid remoteId)
{
var path = Path.Combine(Folder(server, remoteId), IndexFile);
if (!File.Exists(path)) return null;
ProxyCacheIndex? index;
try
{
index = JsonSerializer.Deserialize(File.ReadAllText(path), ProxyCacheJson.Default.ProxyCacheIndex);
}
catch (Exception ex) when (ex is JsonException or IOException)
{
Log.Warning("sync", $"Proxy cache of {remoteId} is unreadable", ex);
return null;
}
return index is null || index.Files.Count != index.Frames.Count ? null : index;
}
/// <summary>Removes the files of a sequence the server no longer has.</summary>
public void Delete(string server, Guid remoteId)
{
+124
View File
@@ -0,0 +1,124 @@
using Titano.Core.Model;
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"/>).
/// Positions are only ever translated against the frames they name: this copy's row is read with its frames as one
/// state (frames inserted here move the row's positions in the same step), and a manifest whose frames mix two orders
/// is not translated at all.
/// </summary>
internal sealed class SyncPositions(TitanoDatabase db, ISyncRemote remote, Guid localId, SequenceManifest manifest)
{
/// <summary>Times this copy's frames are listed again when an insertion lands while they are read.</summary>
private const int Attempts = 3;
/// <summary>The manifest's frames by hash, and with their capture times once fetched.</summary>
private FramePhotos? _hashed, _timed;
/// <summary>The server's frames version the translation to the server's frames is made against.</summary>
public int ServerFrames => manifest.FramesVersion;
/// <summary>
/// The server's settings with their positions on this copy's frames as they are now, with this copy's row at those
/// frames; null when that row is no longer at <paramref name="settingsVersion"/> (an edit was saved here since), or
/// either copy's frames cannot be read as one state now (the next comparison translates again).
/// </summary>
public async Task<TranslatedSettings?> ToLocalAsync(string? settingsJson, int settingsVersion, CancellationToken cancellationToken)
{
if (!ProjectSettings.NamesFrames(settingsJson))
return await db.Sequences.GetAsync(localId, cancellationToken).ConfigureAwait(false) is { } row && row.SettingsVersion == settingsVersion
? new TranslatedSettings(row, settingsJson)
: null;
if (await LocalAsync(cancellationToken).ConfigureAwait(false) is not { } local || local.Row.SettingsVersion != settingsVersion) return null;
if (await ServerAsync(local.Frames, cancellationToken).ConfigureAwait(false) is not { } server) return null;
return new TranslatedSettings(local.Row, ProjectSettings.TranslateFramePositions(settingsJson!, server, local.Frames) ?? settingsJson);
}
/// <summary>
/// This copy's settings at <paramref name="settingsVersion"/> with their positions on the server's frames, with the
/// row they were taken from: frames inserted here since the copy was read moved its positions without a new settings
/// version, so the row is read again with its frames. Null when the row is at another settings version (an edit was
/// saved since), or either copy's frames cannot be read as one state now.
/// </summary>
public async Task<TranslatedSettings?> ToServerAsync(int settingsVersion, CancellationToken cancellationToken)
{
if (await db.Sequences.GetAsync(localId, cancellationToken).ConfigureAwait(false) is not { } row || row.SettingsVersion != settingsVersion) return null;
// Positions cannot appear in a project that names no frame: an insertion only moves those it has.
if (!ProjectSettings.NamesFrames(row.SettingsJson)) return new TranslatedSettings(row, row.SettingsJson);
if (await LocalAsync(cancellationToken).ConfigureAwait(false) is not { } local || local.Row.SettingsVersion != settingsVersion) return null;
if (await ServerAsync(local.Frames, cancellationToken).ConfigureAwait(false) is not { } server) return null;
var settings = local.Row.SettingsJson;
return new TranslatedSettings(local.Row, settings is null ? null : ProjectSettings.TranslateFramePositions(settings, local.Frames, server) ?? settings);
}
/// <summary>
/// This copy's row and frames as one state: the frames are listed between two reads of the row that find the same
/// frames version (an insertion renumbers the frames and moves the row's positions in one transaction, and bumps the
/// version). Null when the sequence is gone or an insertion lands during every attempt.
/// </summary>
private async Task<LocalState?> LocalAsync(CancellationToken cancellationToken)
{
for (var attempt = 0; attempt < Attempts; attempt++)
{
if (await db.Sequences.GetAsync(localId, cancellationToken).ConfigureAwait(false) is not { } before) return null;
var frames = await SequenceFrames.ListAsync(db, localId, cancellationToken).ConfigureAwait(false);
if (await db.Sequences.GetAsync(localId, cancellationToken).ConfigureAwait(false) is not { } after) return null;
if (after.FramesVersion == before.FramesVersion)
return new LocalState(after, new FramePhotos(frames.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, f.CapturedAt)))));
}
return null;
}
/// <summary>
/// The server's frames from the manifest; null when they do not read as one frame list (an index given twice, or
/// not the indices 0…n-1: pages read across an insertion). Their capture times are fetched unless both copies hold
/// the same hashed photos at the same places: a frame is matched by size and capture time when either side has not
/// hashed it, and a position parked on a server photo always names its capture time, so the same project reads the
/// same whichever side hashed what.
/// </summary>
private async Task<FramePhotos?> ServerAsync(FramePhotos local, CancellationToken cancellationToken)
{
if (_hashed is null)
{
if (!OneList(manifest.Frames)) return null;
_hashed = new FramePhotos(manifest.Frames.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, null))));
}
if (_hashed.SameAs(local)) return _hashed;
if (_timed is null)
{
var captured = (await remote.ListFramesAsync(manifest.SequenceId, cancellationToken).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt);
_timed = new FramePhotos(manifest.Frames.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, captured.GetValueOrDefault(f.Id)))));
}
return _timed;
}
/// <summary>Each frame once, at the indices 0…n-1 a sequence's frames always take.</summary>
private static bool OneList(IReadOnlyList<ManifestFrame> frames)
{
var seen = new bool[frames.Count];
var ids = new HashSet<Guid>();
foreach (var frame in frames)
{
if ((uint)frame.Index >= (uint)seen.Length || seen[frame.Index] || !ids.Add(frame.Id)) return false;
seen[frame.Index] = true;
}
return true;
}
private sealed record LocalState(Sequence Row, FramePhotos Frames);
}
/// <summary>
/// Settings translated by <see cref="SyncPositions"/>, with this copy's row at the frames their positions were
/// translated to or from (its own settings may have been moved since it was first read).
/// </summary>
internal sealed record TranslatedSettings(Sequence Local, string? SettingsJson);
+8 -3
View File
@@ -20,14 +20,17 @@ public interface ISyncRemote : IDisposable
Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken);
/// <summary>Every frame row of a sequence, in index order.</summary>
/// <summary>Every frame row of a sequence, each once, in index order.</summary>
Task<IReadOnlyList<FrameDto>> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken);
/// <summary>The first frame row of a sequence (its thumbnail stands for a sequence without a hero frame); null when it has none yet.</summary>
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>
@@ -98,11 +101,13 @@ public sealed class TitanoSyncRemote(TitanoClient client, bool ownsClient) : ISy
public async Task<IReadOnlyList<FrameDto>> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken)
{
var all = new List<FrameDto>();
// Pages follow the frame index: frames inserted while they are read list a frame again, which is kept once.
var seen = new HashSet<Guid>();
string? cursor = null;
do
{
var page = await client.ListFramesAsync(sequenceId, cursor, FramePage, cancellationToken).ConfigureAwait(false);
all.AddRange(page.Items);
all.AddRange(page.Items.Where(f => seen.Add(f.Id)));
cursor = page.NextCursor;
}
while (cursor is not null);
+76 -16
View File
@@ -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)]
@@ -119,31 +123,71 @@ public static class SyncRules
}
/// <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.
/// 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)
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). A photo is there when any photo of the other side matches it, as downloads and
/// uploads find them (<see cref="FramePhotos.IndexOf"/>): two copies of one photo in a folder the server adopted are
/// both held by the one original this PC keeps. 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)
{
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));
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 localPhotos = new FramePhotos(localLeft.Select((p, i) => (i, p)));
var remotePhotos = new FramePhotos(remoteLeft.Select((p, i) => (i, p)));
var remoteUnmatched = remoteLeft.Count(p => localPhotos.IndexOf(p) is null);
int localHashedLeft = 0, localUnhashedLeft = 0;
foreach (var photo in localLeft.Where(p => remotePhotos.IndexOf(p) is null))
{
if (photo.IsHashed) localHashedLeft++;
else localUnhashedLeft++;
}
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.
/// 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)
public static int ProxiesToSend(SequenceManifest manifest, IReadOnlyCollection<Frame> local, ImageDecoder decoder,
IReadOnlyDictionary<Guid, DateTime?>? captured = null)
{
ArgumentNullException.ThrowIfNull(manifest);
var hashed = local.Where(f => !string.IsNullOrEmpty(f.Sha256)).ToLookup(f => f.Sha256!.ToLowerInvariant(), StringComparer.Ordinal);
var unhashed = local.Where(f => string.IsNullOrEmpty(f.Sha256) && Readable(f)).GroupBy(f => f.Size).ToDictionary(g => g.Key, g => g.Count());
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();
@@ -162,6 +206,22 @@ public static class SyncRules
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.
+101 -28
View File
@@ -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,8 +196,17 @@ public sealed class SyncService
{
try
{
var updated = await remote.UpdateSequenceAsync(remoteId, SyncPayload.Of(local).ToRequest(seenRemote), cancellationToken).ConfigureAwait(false);
link = Agreed(Observe(link, remote.Server, updated), local.SettingsVersion, updated.SettingsVersion);
var manifest = await remote.GetManifestAsync(remoteId, cancellationToken).ConfigureAwait(false);
// Edited here since it was shown, or frames that kept changing while they were read: compared again.
if (await RequestAsync(remote, local, manifest, seenRemote, cancellationToken).ConfigureAwait(false) is not { } request)
{
changed = true;
}
else
{
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 +215,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 +353,17 @@ 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);
if (await RequestAsync(remote, local, manifest, manifest.SettingsVersion, cancellationToken).ConfigureAwait(false) is not { } request)
{
// An edit saved here meanwhile goes instead; frames that keep changing here leave it to the next comparison.
if (attempt >= 3 || await _db.Sequences.GetAsync(local.Id, cancellationToken).ConfigureAwait(false) is not { } fresh) return;
local = fresh;
continue;
}
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 +390,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);
}
@@ -399,14 +420,18 @@ public sealed class SyncService
await RefreshSequencesAsync(remote, [remoteId], CompareOnly, cancellationToken).ConfigureAwait(false);
}
/// <summary>Records what the proxy cache holds for a server sequence.</summary>
internal async Task SetProxiesAsync(string server, SequenceDto dto, int cached, int framesVersion, CancellationToken cancellationToken)
/// <summary>
/// Records what the proxy cache holds for a server sequence. Thumbnails standing in for proxies the server did not
/// have leave the cache stale: it is filled again once the server has its proxies.
/// </summary>
internal async Task SetProxiesAsync(string server, SequenceDto dto, int cached, int thumbnails, int framesVersion, CancellationToken cancellationToken)
{
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
var link = Observe(await _links.GetAsync(server, dto.Id, cancellationToken).ConfigureAwait(false), server, dto);
await _links.UpsertAsync(link with { ProxiesCached = cached, ProxiesFramesVersion = framesVersion }, cancellationToken).ConfigureAwait(false);
int? filledAt = thumbnails > 0 && !link.ServerHasProxies ? null : framesVersion;
await _links.UpsertAsync(link with { ProxiesCached = cached, ProxiesFramesVersion = filledAt }, cancellationToken).ConfigureAwait(false);
}
finally
{
@@ -497,9 +522,14 @@ public sealed class SyncService
var frames = await SequenceFrames.ListAsync(_db, local.Id, cancellationToken).ConfigureAwait(false);
// A frame flagged missing here counts as absent: downloading the originals restores it from the server.
var present = frames.Where(f => (f.Flags & FrameFlags.Missing) == 0).ToList();
var (missingRemote, missingLocal) = SyncRules.CompareOriginals([.. present.Select(f => f.Sha256)], [.. manifest.Frames.Select(f => f.Sha256)]);
// A frame either side has not hashed yet (a folder adopted, not verified) is told apart by size and capture time.
var captured = manifest.Frames.Any(f => f.Sha256.Length == 0) || present.Any(f => f.Sha256 is null)
? (await remote.ListFramesAsync(link.RemoteId, cancellationToken).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt)
: null;
var (missingRemote, missingLocal) = SyncRules.CompareOriginals([.. present.Select(f => new FramePhoto(f.Sha256, f.Size, f.CapturedAt))],
[.. manifest.Frames.Select(f => new FramePhoto(f.Sha256, f.Size, captured?.GetValueOrDefault(f.Id)))]);
// Proxies the server asks for that this PC can make from its originals travel with an upload too (BRIEF §2.3).
var proxies = policy.CanEdit && manifest.Proxies is not null ? SyncRules.ProxiesToSend(manifest, present, Options.Archive.Decoder) : 0;
var proxies = policy.CanEdit && manifest.Proxies is not null ? SyncRules.ProxiesToSend(manifest, present, Options.Archive.Decoder, captured) : 0;
// Those change without the server's frame counters moving: while some may be made here, the server's next
// change of the sequence brings a new comparison.
var watch = policy.CanEdit && (proxies > 0 || SyncRules.MakesProxiesFor(present, Options.Archive.Decoder));
@@ -543,14 +573,22 @@ 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);
manifest ??= await remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false);
// The listing and the manifest disagree: the server changed during the comparison; settle it next time.
if (manifest.SettingsVersion != dto.SettingsVersion) return (link, local);
// Compared (and shown) with its positions on this copy's frames, against this copy as it is at those frames: the
// same photos are the same settings. Edited here meanwhile, or frames that kept changing: compared next time.
if (await Positions(remote, local, manifest).ToLocalAsync(manifest.SettingsJson, local.SettingsVersion, cancellationToken).ConfigureAwait(false)
is not { } translated) return (link, local);
local = translated.Local;
var mine = SyncPayload.Of(local);
var theirs = SyncPayload.Of(dto, manifest.SettingsJson);
var theirs = SyncPayload.Of(dto, translated.SettingsJson);
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 +600,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 +617,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 either copy's frames changed since they were read (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);
if (await RequestAsync(remote, local, manifest, expected, cancellationToken).ConfigureAwait(false) is not { } request) return link;
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 +636,23 @@ public sealed class SyncService
}
}
/// <summary>
/// The PATCH that makes the server's copy equal to this copy at <paramref name="local"/>'s settings version (read again
/// with its frames, which may have moved its positions since), its frame positions moved to the server's frames as
/// <paramref name="manifest"/> lists them; the server refuses it when its frames changed since. Null when this copy
/// was edited since <paramref name="local"/> was read, or either copy's frames cannot be read as one state now.
/// </summary>
private async Task<UpdateSequenceRequest?> RequestAsync(ISyncRemote remote, Sequence local, SequenceManifest manifest, int? expected,
CancellationToken cancellationToken)
{
var positions = Positions(remote, local, manifest);
if (await positions.ToServerAsync(local.SettingsVersion, cancellationToken).ConfigureAwait(false) is not { } translated) return null;
var frames = ProjectSettings.NamesFrames(translated.Local.SettingsJson) ? positions.ServerFrames : (int?)null;
return (SyncPayload.Of(translated.Local) with { SettingsJson = translated.SettingsJson }).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 +713,19 @@ 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 and the archive's frame commits 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, or the frames of either copy could not be read as one state: 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)
{
if (await positions.ToLocalAsync(payload.SettingsJson, local.SettingsVersion, cancellationToken).ConfigureAwait(false) is not { } stored) return null;
// Settled as it is: an archive that is offline or read-only does not keep the link from being agreed.
if ((payload with { SettingsJson = stored.SettingsJson }).SameAs(SyncPayload.Of(stored.Local))) return stored.Local;
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);
@@ -661,9 +733,10 @@ public sealed class SyncService
var folder = paths.Sequence(local.Folder);
await using (await _writer.LockAsync(paths, local.Id, cancellationToken).ConfigureAwait(false))
{
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.
if (await positions.ToLocalAsync(payload.SettingsJson, local.SettingsVersion, cancellationToken).ConfigureAwait(false) is not { } current) return null;
var row = current.Local;
payload = payload with { SettingsJson = current.SettingsJson };
var metadata = !payload.SameMetadata(SyncPayload.Of(row));
var settings = !SyncRules.SameSettings(payload.SettingsJson, row.SettingsJson);
if (!metadata && !settings) return row;
+135 -57
View File
@@ -4,6 +4,7 @@ using System.Net;
using Titano.Core.Archiving;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Data.Archiving;
using Titano.Data.Archiving.Jobs;
using Titano.Data.Jobs;
@@ -11,6 +12,7 @@ using Titano.Data.Processing;
using Titano.Protocol;
using Titano.Protocol.Client;
using SequenceFrames = Titano.Data.Processing.SequenceFrames;
using SequenceManifest = Titano.Protocol.SequenceManifest;
namespace Titano.Data.Sync;
@@ -19,8 +21,9 @@ namespace Titano.Data.Sync;
/// resumable protocol after hashing it again (an original that no longer matches its archived hash is never sent),
/// creating the server sequence first and sending its settings when the upload made it, then the proxies the server asks
/// for (originals it cannot decode, BRIEF §2.3), made here from this PC's originals. Downloads fetch originals the
/// local copy lacks into the archive's staging folder (resuming with Range), require the manifest's SHA-256 and commit
/// them through the archive ingest, which names them and writes the sidecar; the first original creates the local
/// local copy lacks into the archive's staging folder (resuming with Range), require the manifest's SHA-256 (or, for an
/// original the server has not hashed yet, its size, and hash it here) and commit them through the archive ingest,
/// which names them and writes the sidecar; the first original creates the local
/// sequence, which then takes the server's settings. Frames of the local copy not hashed yet are hashed first (so the
/// server's copies of them are recognised), and originals flagged missing here are restored to their recorded place.
/// Proxy downloads fill the proxy cache. Renders travel on request: this PC's to the server (hash-verified chunked
@@ -44,10 +47,15 @@ internal sealed class SyncTransfers(SyncService sync)
var (remoteId, created) = await TargetAsync(context, remote, local).ConfigureAwait(false);
var frames = (await SequenceFrames.ListAsync(db, local.Id, ct).ConfigureAwait(false)).Where(f => (f.Flags & FrameFlags.Missing) == 0).ToList();
var present = remoteId is { } known
? (await remote.GetManifestAsync(known, ct).ConfigureAwait(false)).Frames.Select(f => f.Sha256.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal)
: [];
var pending = new Queue<Frame>(frames.Where(f => f.Sha256 is null || !present.Contains(f.Sha256.ToLowerInvariant())));
var manifest = remoteId is { } known ? await remote.GetManifestAsync(known, ct).ConfigureAwait(false) : null;
var present = manifest?.Frames.Where(f => f.Sha256.Length > 0).Select(f => f.Sha256.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal) ?? [];
// Originals the server holds without a hash (adopted there, not verified) are the ones of their size and capture
// time: the server could not recognise them by content, so they are not sent again.
var adopted = manifest is not null && manifest.Frames.Any(f => f.Sha256.Length == 0)
? await UnhashedAsync(remote, manifest, ct).ConfigureAwait(false)
: new FramePhotos([]);
var pending = new Queue<Frame>(frames.Where(f => (f.Sha256 is null || !present.Contains(f.Sha256.ToLowerInvariant()))
&& adopted.IndexOf(new FramePhoto(f.Sha256, f.Size, f.CapturedAt)) is null));
var progress = new TransferProgress(context, frames.Count, frames.Count - pending.Count);
await progress.ReportAsync().ConfigureAwait(false);
var skipped = 0;
@@ -86,10 +94,18 @@ internal sealed class SyncTransfers(SyncService sync)
if (skipped > 0) throw new InvalidDataException(Loc.Plural("Errors.Sync.Unreadable", skipped));
}
/// <summary>The server's frames it has not hashed yet, by size and capture time, at their indices.</summary>
private static async Task<FramePhotos> UnhashedAsync(ISyncRemote remote, SequenceManifest manifest, CancellationToken cancellationToken)
{
var captured = (await remote.ListFramesAsync(manifest.SequenceId, cancellationToken).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt);
return new FramePhotos(manifest.Frames.Where(f => f.Sha256.Length == 0).Select(f => (f.Index, new FramePhoto(null, f.Size, captured.GetValueOrDefault(f.Id)))));
}
/// <summary>
/// The proxies the server asks for (<see cref="ManifestFrame.WantsProxy"/>) that this PC's decoders can make from its
/// originals (by their archived SHA-256, or the one <paramref name="hashes"/> holds for an original the index has none
/// for), made as the server's proxy policy says with the server's capture data, and sent. One the server refuses is
/// for; by size and capture time for a frame the server has not hashed, <see cref="SyncRules.ProxyOriginal"/>), made as
/// the server's proxy policy says with the server's capture data, and sent. One the server refuses is
/// counted in the job log; a server that makes no proxies, or an account that may not send them, ends the pass; a
/// server busy or out of reach fails the job like an original would.
/// </summary>
@@ -106,6 +122,7 @@ internal sealed class SyncTransfers(SyncService sync)
if ((frame.Sha256 ?? hashes.GetValueOrDefault(frame.Id)) is { } sha) originals.TryAdd(sha.ToLowerInvariant(), frame);
}
var records = (await remote.ListFramesAsync(remoteId, ct).ConfigureAwait(false)).ToDictionary(f => f.Id);
var photos = SyncRules.Photos(frames);
var camera = new SidecarCamera { Make = local.CameraMake, Model = local.CameraModel, Serial = local.CameraSerial };
var decoder = sync.Options.Archive.Decoder;
var progress = new TransferProgress(context, wanted.Count, 0);
@@ -116,7 +133,12 @@ internal sealed class SyncTransfers(SyncService sync)
{
await Parallel.ForEachAsync(wanted, Workers(sync.Options.Uploads, refused.Token), async (frame, token) =>
{
var jpeg = originals.TryGetValue(frame.Sha256.ToLowerInvariant(), out var original) && records.TryGetValue(frame.Id, out var record)
records.TryGetValue(frame.Id, out var record);
// A frame the server has not hashed yet is this PC's original of its size and capture time.
var original = frame.Sha256.Length == 0
? SyncRules.ProxyOriginal(frame, record?.CapturedAt, frames, photos)
: originals.GetValueOrDefault(frame.Sha256.ToLowerInvariant());
var jpeg = original is not null && record is not null
? await Task.Run(() => MakeProxy(decoder, paths.FromRelative(original.RelativePath), RenderNodeClient.ToFrame(record), camera, spec, frame.FileName,
token), token).ConfigureAwait(false)
: null;
@@ -182,8 +204,14 @@ internal sealed class SyncTransfers(SyncService sync)
var manifest = await remote.GetManifestAsync(remoteId, ct).ConfigureAwait(false);
var captured = (await remote.ListFramesAsync(remoteId, ct).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt);
var (have, restore) = local is null ? ([], []) : await LocalContentAsync(archive, local, ct).ConfigureAwait(false);
var wanted = manifest.Frames.Where(f => !have.Contains(f.Sha256.ToLowerInvariant())).DistinctBy(f => f.Sha256.ToLowerInvariant()).ToList();
var (have, restore, photos) = local is null ? ([], [], new FramePhotos([])) : await LocalContentAsync(archive, local, ct).ConfigureAwait(false);
// An original the server has not hashed yet (adopted there, not verified) is here when an original of its size and
// capture time is; each one is fetched on its own and hashed here.
var wanted = manifest.Frames
.Where(f => f.Sha256.Length == 0
? photos.IndexOf(new FramePhoto(null, f.Size, captured.GetValueOrDefault(f.Id))) is null
: !have.Contains(f.Sha256.ToLowerInvariant()))
.DistinctBy(f => f.Sha256.Length == 0 ? f.Id.ToString("N") : f.Sha256.ToLowerInvariant()).ToList();
EnsureSpace(paths.Root, wanted.Sum(f => f.Size));
var staging = Path.Combine(paths.StagingDirectory, "sync-" + remoteId.ToString("N"));
@@ -195,7 +223,8 @@ internal sealed class SyncTransfers(SyncService sync)
if (local is null && wanted.Count > 0)
{
// The first original creates the local sequence (grouped by the server id); the others join it.
var first = await CommitAsync(remote, remoteId, archive.Id, null, wanted[0], staging, captured, ct).ConfigureAwait(false);
var (staged, sha) = await FetchOriginalAsync(remote, wanted[0], staging, ct).ConfigureAwait(false);
var first = await CommitAsync(remoteId, archive.Id, null, wanted[0], staged, sha, captured, ct).ConfigureAwait(false);
local = await db.Sequences.GetAsync(first.SequenceId, ct).ConfigureAwait(false)
?? throw new InvalidOperationException(Loc.L("Errors.Sync.LocalMissing"));
await sync.LinkAsync(remote.Server, remoteId, local, ct).ConfigureAwait(false);
@@ -208,14 +237,15 @@ internal sealed class SyncTransfers(SyncService sync)
var restored = 0;
await Parallel.ForEachAsync(rest, Workers(sync.Options.Downloads, ct), async (frame, token) =>
{
if (restore.TryGetValue(frame.Sha256.ToLowerInvariant(), out var place))
var (staged, sha) = await FetchOriginalAsync(remote, frame, staging, token).ConfigureAwait(false);
if (restore.TryGetValue(sha, out var place))
{
await RestoreAsync(remote, frame, staging, place, token).ConfigureAwait(false);
Restore(staged, place);
Interlocked.Increment(ref restored);
}
else
{
await CommitAsync(remote, remoteId, archive.Id, sequenceId, frame, staging, captured, token).ConfigureAwait(false);
await CommitAsync(remoteId, archive.Id, sequenceId, frame, staged, sha, captured, token).ConfigureAwait(false);
}
await progress.StepAsync().ConfigureAwait(false);
}).ConfigureAwait(false);
@@ -234,11 +264,12 @@ internal sealed class SyncTransfers(SyncService sync)
}
/// <summary>
/// The originals a local copy holds (lower-case SHA-256) and where each original flagged missing belongs. Frames
/// not hashed yet (an adopted folder never verified) are hashed first through the archive's verify, so the
/// server's copies of them are recognised instead of committed again as duplicates.
/// The originals a local copy holds (lower-case SHA-256, and their photos for server frames not hashed yet) and where
/// each original flagged missing belongs. Frames not hashed yet (an adopted folder never verified) are hashed first
/// through the archive's verify, so the server's copies of them are recognised instead of committed again as duplicates.
/// </summary>
private async Task<(HashSet<string> Have, Dictionary<string, string> Restore)> LocalContentAsync(Archive archive, Sequence local, CancellationToken ct)
private async Task<(HashSet<string> Have, Dictionary<string, string> Restore, FramePhotos Photos)> LocalContentAsync(Archive archive, Sequence local,
CancellationToken ct)
{
var frames = await SequenceFrames.ListAsync(sync.Database, local.Id, ct).ConfigureAwait(false);
if (frames.Any(f => f.Sha256 is null && (f.Flags & FrameFlags.Missing) == 0))
@@ -255,16 +286,16 @@ internal sealed class SyncTransfers(SyncService sync)
var sha = frame.Sha256!.ToLowerInvariant();
if (!have.Contains(sha)) restore.TryAdd(sha, paths.FromRelative(frame.RelativePath));
}
return (have, restore);
var photos = SyncRules.Photos([.. frames.Where(f => (f.Flags & FrameFlags.Missing) == 0)]);
return (have, restore, photos);
}
private Task VerifyAsync(Archive archive, Guid sequenceId, CancellationToken ct) =>
sync.Archives.Verifier.VerifyAsync(archive, [sequenceId], default, (_, _, _) => ValueTask.CompletedTask, cancellationToken: ct);
/// <summary>Puts a verified copy of an original flagged missing back where its record says; a file that reappeared meanwhile is kept.</summary>
private static async Task RestoreAsync(ISyncRemote remote, ManifestFrame frame, string staging, string place, CancellationToken cancellationToken)
private static void Restore(string staged, string place)
{
var staged = await FetchOriginalAsync(remote, frame, staging, cancellationToken).ConfigureAwait(false);
if (File.Exists(place))
{
File.Delete(staged);
@@ -397,22 +428,26 @@ internal sealed class SyncTransfers(SyncService sync)
var assets = manifest.Frames.ToDictionary(f => f.Id);
var folder = sync.Proxies.Folder(remote.Server, remoteId);
Directory.CreateDirectory(folder);
var cachedKinds = sync.Proxies.Kinds(remote.Server, remoteId);
ProxyCache.Prune(folder, frames.Select(f => ProxyCache.FileName(f.Id)).ToHashSet(StringComparer.Ordinal));
EnsureSpace(folder, frames.Count(f => !File.Exists(Path.Combine(folder, ProxyCache.FileName(f.Id)))) * ProxyEstimate);
var files = new string?[frames.Count];
var kinds = new string?[frames.Count];
var progress = new TransferProgress(context, frames.Count, 0);
await progress.ReportAsync().ConfigureAwait(false);
await Parallel.ForEachAsync(Enumerable.Range(0, frames.Count), Workers(sync.Options.Downloads, ct), async (i, token) =>
{
IReadOnlyList<string> kinds = assets.TryGetValue(frames[i].Id, out var asset) ? Kinds(asset) : [];
files[i] = await FetchProxyAsync(remote, frames[i].Id, kinds, folder, token).ConfigureAwait(false);
IReadOnlyList<string> offered = assets.TryGetValue(frames[i].Id, out var asset) ? Kinds(asset) : [];
var fetched = await FetchProxyAsync(remote, frames[i].Id, offered, cachedKinds.GetValueOrDefault(frames[i].Id), folder, token).ConfigureAwait(false);
files[i] = fetched?.Name;
kinds[i] = fetched?.Kind;
await progress.StepAsync().ConfigureAwait(false);
}).ConfigureAwait(false);
sync.Proxies.Save(remote.Server, remoteId, new ProxyCacheIndex(dto, manifest.SettingsJson, manifest.FramesVersion, frames, files));
sync.Proxies.Save(remote.Server, remoteId, new ProxyCacheIndex(dto, manifest.SettingsJson, manifest.FramesVersion, frames, files, kinds));
var cached = files.Count(f => f is not null);
await sync.SetProxiesAsync(remote.Server, dto, cached, manifest.FramesVersion, ct).ConfigureAwait(false);
await sync.SetProxiesAsync(remote.Server, dto, cached, kinds.Count(k => k == ProxyCache.Thumb), manifest.FramesVersion, ct).ConfigureAwait(false);
if (cached < frames.Count) context.Log($"{frames.Count - cached} frame(s) have neither proxy nor thumbnail on the server");
}
@@ -476,13 +511,12 @@ internal sealed class SyncTransfers(SyncService sync)
?? new CompleteUploadResponse(Guid.Empty, sequenceId ?? Guid.Empty, -1);
}
/// <summary>Downloads one original into staging and commits it into the local sequence (created from the server id when null).</summary>
private async Task<IngestResult> CommitAsync(ISyncRemote remote, Guid remoteId, Guid archiveId, Guid? sequenceId, ManifestFrame frame, string staging,
/// <summary>Commits one original from staging into the local sequence (created from the server id when null).</summary>
private async Task<IngestResult> CommitAsync(Guid remoteId, Guid archiveId, Guid? sequenceId, ManifestFrame frame, string staged, string sha,
IReadOnlyDictionary<Guid, DateTime?> captured, CancellationToken cancellationToken)
{
var staged = await FetchOriginalAsync(remote, frame, staging, cancellationToken).ConfigureAwait(false);
var request = new IngestRequest(archiveId, sequenceId, null, sequenceId is null ? SyncService.SessionKey(remoteId) : null, staged, frame.FileName,
frame.Size, frame.Sha256.ToLowerInvariant(), captured.GetValueOrDefault(frame.Id), null);
frame.Size, sha, captured.GetValueOrDefault(frame.Id), null);
var result = await sync.Archives.Ingest.CommitAsync(request, cancellationToken).ConfigureAwait(false);
// A duplicate stays in staging (the sequence already holds that content).
if (result.Duplicate) File.Delete(staged);
@@ -490,71 +524,115 @@ internal sealed class SyncTransfers(SyncService sync)
}
/// <summary>
/// A verified copy in staging: resumed from a partial download, accepted only with the manifest's SHA-256 (two
/// attempts). A part as long as the file (a job stopped while hashing it) is only hashed again; a part the server can
/// no longer resume (416) starts over.
/// A verified copy in staging and its lower-case SHA-256: resumed from a partial download, accepted only with the
/// manifest's SHA-256 (two attempts). A part as long as the file (a job stopped while hashing it) is only hashed again;
/// a part the server can no longer resume (416) starts over.
/// </summary>
private static async Task<string> FetchOriginalAsync(ISyncRemote remote, ManifestFrame frame, string staging, CancellationToken cancellationToken)
private static async Task<(string Path, string Sha256)> FetchOriginalAsync(ISyncRemote remote, ManifestFrame frame, string staging,
CancellationToken cancellationToken)
{
if (frame.Sha256.Length == 0) return await FetchUnhashedAsync(remote, frame, staging, cancellationToken).ConfigureAwait(false);
var sha = frame.Sha256.ToLowerInvariant();
if (sha.Length != 64 || !sha.All(char.IsAsciiHexDigitLower)) throw new InvalidDataException(Loc.L("Errors.Sync.Hash", frame.FileName));
var target = Path.Combine(staging, sha + Path.GetExtension(frame.FileName).ToLowerInvariant());
if (File.Exists(target)) return target;
if (File.Exists(target)) return (target, sha);
var part = target + ".part";
for (var attempt = 1; ; attempt++)
{
if (!File.Exists(part) || new FileInfo(part).Length < frame.Size)
{
try
{
await using (var file = new FileStream(part, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
await remote.DownloadFrameAsync(frame.Id, "original", file, cancellationToken).ConfigureAwait(false);
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.RequestedRangeNotSatisfiable && attempt == 1)
{
File.Delete(part);
continue;
}
}
if (!await FetchPartAsync(remote, frame, part, attempt, cancellationToken).ConfigureAwait(false)) continue;
if (await TitanoClient.HashFileAsync(part, cancellationToken).ConfigureAwait(false) == sha)
{
File.Move(part, target, overwrite: true);
return target;
return (target, sha);
}
File.Delete(part);
if (attempt == 2) throw new InvalidDataException(Loc.L("Errors.Sync.Hash", frame.FileName));
}
}
/// <summary>The cached proxy's file name, downloading the first asset kind the server has; null when it has none.</summary>
private static async Task<string?> FetchProxyAsync(ISyncRemote remote, Guid frameId, IReadOnlyList<string> kinds, string folder, CancellationToken cancellationToken)
/// <summary>
/// An original the server has not hashed yet (a folder it adopted and did not verify): nothing to check it against
/// but its size, so a copy of another size is fetched again once; it is hashed here, and the archive ingest files it
/// by that hash like any other. Kept in staging under the frame's id, as several such originals may share content.
/// </summary>
private static async Task<(string Path, string Sha256)> FetchUnhashedAsync(ISyncRemote remote, ManifestFrame frame, string staging,
CancellationToken cancellationToken)
{
var target = Path.Combine(staging, frame.Id.ToString("N") + Path.GetExtension(frame.FileName).ToLowerInvariant());
var part = target + ".part";
for (var attempt = 1; !File.Exists(target); attempt++)
{
if (!await FetchPartAsync(remote, frame, part, attempt, cancellationToken).ConfigureAwait(false)) continue;
if (new FileInfo(part).Length == frame.Size)
{
File.Move(part, target, overwrite: true);
break;
}
File.Delete(part);
if (attempt == 2) throw new InvalidDataException(Loc.L("Errors.Sync.Hash", frame.FileName));
}
return (target, await TitanoClient.HashFileAsync(target, cancellationToken).ConfigureAwait(false));
}
/// <summary>
/// Downloads an original into <paramref name="part"/>, resuming after what it holds; a part as long as the file is
/// kept as it is. False when the server can no longer resume it (416) on the first attempt: the part is gone and the
/// next attempt starts over.
/// </summary>
private static async Task<bool> FetchPartAsync(ISyncRemote remote, ManifestFrame frame, string part, int attempt, CancellationToken cancellationToken)
{
if (File.Exists(part) && new FileInfo(part).Length >= frame.Size) return true;
try
{
await using (var file = new FileStream(part, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
await remote.DownloadFrameAsync(frame.Id, "original", file, cancellationToken).ConfigureAwait(false);
return true;
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.RequestedRangeNotSatisfiable && attempt == 1)
{
File.Delete(part);
return false;
}
}
/// <summary>
/// The cached file of a frame and what it is, downloading the first asset kind the server has
/// (<paramref name="offered"/>, the proxy first); null when it has none. A cached proxy stays. A cached thumbnail,
/// or a file of a cache that did not record its kind (<paramref name="cachedKind"/> null), stands in only until the
/// server has a proxy of the frame, which then replaces it; until then it stays as the thumbnail.
/// </summary>
private static async Task<(string Name, string Kind)?> FetchProxyAsync(ISyncRemote remote, Guid frameId, IReadOnlyList<string> offered, string? cachedKind,
string folder, CancellationToken cancellationToken)
{
var name = ProxyCache.FileName(frameId);
var path = Path.Combine(folder, name);
if (new FileInfo(path) is { Exists: true, Length: > 0 }) return name;
var cached = new FileInfo(path) is { Exists: true, Length: > 0 };
if (cached && (cachedKind == ProxyCache.Proxy || !offered.Contains(ProxyCache.Proxy))) return (name, cachedKind ?? ProxyCache.Thumb);
var part = path + ".part";
foreach (var kind in kinds)
foreach (var kind in offered)
{
// The cached file is as good as the server's thumbnail.
if (cached && kind == ProxyCache.Thumb) break;
try
{
await using (var file = new FileStream(part, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
await remote.DownloadFrameAsync(frameId, kind, file, cancellationToken).ConfigureAwait(false);
File.Move(part, path, overwrite: true);
return name;
return (name, kind);
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
File.Delete(part);
}
}
return null;
return cached ? (name, ProxyCache.Thumb) : null;
}
private static string[] Kinds(ManifestFrame frame) => (frame.HasProxy, frame.HasThumb) switch
{
(true, true) => ["proxy", "thumb"],
(true, false) => ["proxy"],
(false, true) => ["thumb"],
(true, true) => [ProxyCache.Proxy, ProxyCache.Thumb],
(true, false) => [ProxyCache.Proxy],
(false, true) => [ProxyCache.Thumb],
_ => [],
};
+4 -1
View File
@@ -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>
+38 -5
View File
@@ -27,6 +27,9 @@ public static class SequenceEndpoints
private const int MaxNotes = 2000;
private const int MaxTags = 50;
/// <summary>Listings of a sequence's frames read without a lock before one is read under its row lock (<see cref="SnapshotAsync"/>).</summary>
private const int SnapshotAttempts = 3;
public static void Map(RouteGroupBuilder api)
{
// Uploaders list sequences to pick an upload target.
@@ -140,14 +143,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));
@@ -216,14 +223,16 @@ public static class SequenceEndpoints
/// <summary>
/// Everything a client needs to mirror a sequence and detect changes (BRIEF §14.5), with the proxies the server asks
/// for (<see cref="ServerProxies"/>); ETag over the version counters and the number of proxies asked for.
/// for (<see cref="ServerProxies"/>); ETag over the version counters and the number of proxies asked for. The frames,
/// the frames version and the settings whose positions name those frames are of one frames version (<see cref="SnapshotAsync"/>).
/// </summary>
private static async Task<IResult> ManifestAsync(HttpContext context, Guid id, TitanoDatabase db, ServerArchive archive)
{
var ct = context.RequestAborted;
if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
var spec = ServerProxies.Spec(archive.Current);
var frames = await ServerProxies.FramesAsync(db, archive.Current, sequence, spec, ct);
if (await SnapshotAsync(db, id, (on, s, c) => ServerProxies.FramesAsync(on, archive.Current, s, spec, c), ct) is not { } snapshot)
return ApiErrors.NotFound(context, "sequence");
var (sequence, frames) = snapshot;
var etag = string.Create(CultureInfo.InvariantCulture,
$"\"m{sequence.SettingsVersion}-{sequence.FramesVersion}-{sequence.RenderedCount}-{frames.Count(f => f.WantsProxy)}\"");
if (context.Request.Headers.IfNoneMatch == etag) return Results.StatusCode(StatusCodes.Status304NotModified);
@@ -234,6 +243,30 @@ public static class SequenceEndpoints
[.. renders.Select(Dto.Render)], spec), ProtocolJson.Default.SequenceManifest);
}
/// <summary>
/// The sequence and its frames as of one frames version: a client pairs the settings' frame positions with these
/// frames. <paramref name="listFrames"/> reads them in pages, and a commit of earlier photos renumbers them and moves
/// the settings' positions at once, so a listing read across one would mix two orders. It is read again while the
/// frames version moved during it, and then inside a transaction holding the sequence's row, which every commit of
/// frames locks first (on SQLite, the write lock: the listing runs on that transaction's own connection). Null when
/// the sequence is gone.
/// </summary>
internal static async Task<(Sequence Sequence, List<ManifestFrame> Frames)?> SnapshotAsync(TitanoDatabase db, Guid id,
Func<TitanoRepositories, Sequence, CancellationToken, Task<List<ManifestFrame>>> listFrames, CancellationToken cancellationToken)
{
for (var attempt = 0; attempt < SnapshotAttempts; attempt++)
{
if (await db.Sequences.GetAsync(id, cancellationToken) is not { } sequence) return null;
var frames = await listFrames(db, sequence, cancellationToken);
if (await db.Sequences.GetAsync(id, cancellationToken) is not { } after) return null;
if (after.FramesVersion == sequence.FramesVersion) return (sequence, frames);
}
// Commits keep landing (an upload of earlier photos): the frames are listed while none can.
await using var tx = await db.BeginAsync(cancellationToken);
if (await tx.Sequences.GetForUpdateAsync(id, cancellationToken) is not { } locked) return null;
return (locked, await listFrames(tx, locked, cancellationToken));
}
private static async Task<IResult> FramesAsync(HttpContext context, Guid id, string? cursor, int? limit, TitanoDatabase db)
{
var ct = context.RequestAborted;
+1 -1
View File
@@ -49,7 +49,7 @@ public static class ServerProxies
/// added or renumbered since keep it until the next proxy pass), and wants one otherwise (unless it is missing or
/// damaged, or <paramref name="spec"/> is null); any other frame has one when the server built them all.
/// </summary>
public static async Task<List<ManifestFrame>> FramesAsync(TitanoDatabase db, Archive archive, Sequence sequence, ProxySpec? spec,
public static async Task<List<ManifestFrame>> FramesAsync(TitanoRepositories db, Archive archive, Sequence sequence, ProxySpec? spec,
CancellationToken cancellationToken)
{
var proxies = sequence.Status.HasFlag(SequenceStatus.ProxiesBuilt);
@@ -167,6 +167,157 @@ public sealed class ProjectSettingsTests
Assert.Null(ProjectSettings.MoveFramePositions("""{ "heroFrame": 1, "HeroFrame": 1 }""", new Dictionary<int, int> { [1] = 2 }));
}
[Test]
public void PositionsCrossToAnotherCopyByPhotoAndWaitForPhotosItLacks()
{
// The server holds six photos; this copy only the last four, and one of its own the server lacks.
var photos = Enumerable.Range(0, 7).Select(Photo).ToList();
var server = Frames(photos[..6]);
var here = Frames([.. photos[2..6], photos[6]]);
var project = new ProjectSettings
{
ExcludedFrames = [0, 3],
HeroFrame = 1,
Camera = new CameraSettings { Keyframes = [new CameraKey(0, 0.5, 0.5, 1, 0), new CameraKey(4, 0.4, 0.5, 1.5, 0)] },
Exposure = new ExposureSettings { DeflickerWindow = new Auto<int>().WithManual(41) },
};
var taken = ProjectSettings.FromJson(Assert.NotNull(ProjectSettings.TranslateFramePositions(project.ToJson(), server, here)));
Assert.SequenceEqual([1], taken.ExcludedFrames);
Assert.Null(taken.HeroFrame);
Assert.SequenceEqual([2], taken.Camera.Keyframes.Select(k => k.Frame));
Assert.Equal(1.5, taken.Camera.Keyframes[0].Zoom);
Assert.Equal(41, taken.Exposure.DeflickerWindow.Manual);
var pending = Assert.NotNull(taken.PendingFrames);
Assert.Equal(2, pending.Count);
var first = Assert.Contains(pending, p => p.Sha256 == photos[0].Sha256);
Assert.True(first.Excluded && !first.Hero);
Assert.Count(1, first.Keyframes);
Assert.Equal(0.5, first.Keyframes[0].CenterX);
Assert.True(Assert.Contains(pending, p => p.Sha256 == photos[1].Sha256).Hero);
Assert.True(taken.HeroPending);
// The two photos arrive (inserted before the others): what waited takes its place, and the rest moved with its frames.
var arrived = Frames(photos);
var moved = ProjectSettings.MoveFramePositions(taken.ToJson(), new Dictionary<int, int> { [0] = 2, [1] = 3, [2] = 4, [3] = 5, [4] = 6 })!;
var placed = ProjectSettings.FromJson(Assert.NotNull(ProjectSettings.TranslateFramePositions(moved, null, arrived)));
Assert.SequenceEqual([0, 3], placed.ExcludedFrames);
Assert.Equal(1, placed.HeroFrame);
Assert.SequenceEqual([0, 4], placed.Camera.Keyframes.Select(k => k.Frame));
Assert.Null(placed.PendingFrames);
Assert.Null(ProjectSettings.TranslateFramePositions(placed.ToJson(), null, arrived));
}
[Test]
public void SettingsSentBackLandOnTheSamePhotos()
{
var photos = Enumerable.Range(0, 5).Select(Photo).ToList();
var server = Frames(photos[1..]);
var here = Frames(photos);
// Photo 0 is only here: its exclusion waits on the server, and comes back as a position.
var project = new ProjectSettings { ExcludedFrames = [0, 2], HeroFrame = 4 };
var sent = Assert.NotNull(ProjectSettings.TranslateFramePositions(project.ToJson(), here, server));
var back = ProjectSettings.FromJson(Assert.NotNull(ProjectSettings.TranslateFramePositions(sent, server, here)));
Assert.SequenceEqual([1], ProjectSettings.FromJson(sent).ExcludedFrames);
Assert.Equal(3, ProjectSettings.FromJson(sent).HeroFrame);
Assert.Equal(project.ToJson(), back.ToJson());
}
[Test]
public void AHeroOrKeyframeChosenSinceIsNewerThanTheOneThatWaited()
{
var photos = Enumerable.Range(0, 3).Select(Photo).ToList();
var waiting = new ProjectSettings
{
HeroFrame = 2,
Camera = new CameraSettings { Keyframes = [new CameraKey(0, 0.2, 0.2, 2, 0)] },
PendingFrames = [new PendingFrame { Sha256 = photos[0].Sha256, Size = photos[0].Size, Hero = true, Keyframes = [new CameraKey(9, 0.7, 0.7, 1, 0)] }],
};
var placed = ProjectSettings.FromJson(Assert.NotNull(ProjectSettings.TranslateFramePositions(waiting.ToJson(), null, Frames(photos))));
Assert.Equal(2, placed.HeroFrame);
Assert.Count(1, placed.Camera.Keyframes);
Assert.Equal(0.2, placed.Camera.Keyframes[0].CenterX);
Assert.Null(placed.PendingFrames);
}
[Test]
public void AHeroChosenSinceAnotherWaitedStaysTheHeroWhenItMustWaitToo()
{
// This PC chose photo 3 as the hero before the server had it, so it waits there; an editor on the server then
// chose photo 2, which this PC lacks.
var photos = Enumerable.Range(0, 4).Select(Photo).ToList();
var server = Frames(photos[..3]);
var here = Frames([photos[0], photos[1], photos[3]]);
var edited = new ProjectSettings
{
ExcludedFrames = [0],
HeroFrame = 2,
PendingFrames = [new PendingFrame { Sha256 = photos[3].Sha256, Size = photos[3].Size, CapturedAt = photos[3].CapturedAt, Hero = true }],
};
var taken = ProjectSettings.FromJson(Assert.NotNull(ProjectSettings.TranslateFramePositions(edited.ToJson(), server, here)));
Assert.Null(taken.HeroFrame);
Assert.SequenceEqual([0], taken.ExcludedFrames);
var waiting = Assert.NotNull(taken.PendingFrames);
Assert.Count(1, waiting);
Assert.True(waiting[0].Hero && waiting[0].Sha256 == photos[2].Sha256, "the newer hero waits for its photo");
Assert.True(taken.HeroPending);
// Its photo arrives: it is the hero again.
var arrived = Frames([photos[0], photos[1], photos[2], photos[3]]);
var moved = ProjectSettings.MoveFramePositions(taken.ToJson(), new Dictionary<int, int> { [2] = 3 }) ?? taken.ToJson();
var placed = ProjectSettings.FromJson(Assert.NotNull(ProjectSettings.TranslateFramePositions(moved, null, arrived)));
Assert.Equal(2, placed.HeroFrame);
Assert.Null(placed.PendingFrames);
// A hero chosen here while one waits clears the waiting one, even before its photo arrives.
var chosen = (taken with { HeroFrame = 1 }).ToJson();
var cleared = ProjectSettings.FromJson(Assert.NotNull(ProjectSettings.TranslateFramePositions(chosen, null, here)));
Assert.Equal(1, cleared.HeroFrame);
Assert.Null(cleared.PendingFrames);
}
[Test]
public void AProjectNamingNoFrameCrossesAsItIs()
{
var json = new ProjectSettings { Exposure = new ExposureSettings { DeflickerWindow = new Auto<int>().WithManual(41) } }.ToJson();
Assert.False(ProjectSettings.NamesFrames(json));
Assert.False(json.Contains("pendingFrames", StringComparison.OrdinalIgnoreCase), "an old project reads and writes as it did");
Assert.False(ProjectSettings.NamesFrames("not json"));
Assert.True(ProjectSettings.NamesFrames("""{ "HeroFrame": 0 }"""));
Assert.Null(ProjectSettings.TranslateFramePositions(json, Frames([Photo(1)]), Frames([Photo(2)])));
Assert.Null(ProjectSettings.TranslateFramePositions("[1]", null, Frames([])));
}
[Test]
public void PhotosMatchByHashElseBySizeAndCaptureTime()
{
var time = new DateTime(2026, 9, 28, 18, 0, 0, 123);
var hashed = new FramePhoto(new string('a', 64), 100, time);
Assert.True(hashed.Matches(new FramePhoto(new string('A', 64), 1, null)));
Assert.False(hashed.Matches(new FramePhoto(new string('b', 64), 100, time)));
Assert.True(hashed.Matches(new FramePhoto("", 100, time.AddTicks(9_999))));
Assert.False(hashed.Matches(new FramePhoto(null, 100, time.AddMilliseconds(1))));
Assert.False(new FramePhoto(null, 100, null).Matches(new FramePhoto(null, 100, null)));
var frames = Frames([new FramePhoto(null, 100, time), hashed]);
Assert.Equal(1, frames.IndexOf(new FramePhoto(new string('a', 64), 100, null)));
Assert.Equal(0, frames.IndexOf(new FramePhoto(null, 100, time)));
Assert.Null(frames.IndexOf(new FramePhoto(null, 101, time)));
}
private static FramePhoto Photo(int seed) =>
new(Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData([(byte)seed])), 1000 + seed, new DateTime(2026, 9, 28, 18, 0, 0).AddSeconds(10 * seed));
private static FramePhotos Frames(IEnumerable<FramePhoto> photos) => new(photos.Select((p, i) => (i, p)));
[Test]
public void BuiltInPresetIdsAreUnique() =>
Assert.Equal(ExportPresets.BuiltIn.Count, ExportPresets.BuiltIn.Select(p => p.Id).Distinct().Count());
@@ -485,6 +485,51 @@ public sealed class ArchiveIngestTests(TestContext context)
Assert.True(JsonNode.DeepEquals(JsonNode.Parse(row.SettingsJson!), JsonNode.Parse(File.ReadAllText(folder.ProjectPath))), "project.json mirrors the index");
}
[Test]
public async Task PositionsWaitingForTheirPhotosTakeTheirPlaceWhenTheyArrive()
{
await using var fx = await CreateAsync(context);
var results = new List<IngestResult>();
for (var i = 0; i < 3; i++) results.Add(await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start.AddMinutes(1 + i), 30 + i)), fx.Ct));
var sequenceId = results[0].SequenceId;
var folder = fx.Paths.Sequence((await fx.Db.Sequences.GetAsync(sequenceId))!.Folder);
// Settings synced from a copy that also holds an earlier and a later photo: what names them waits for them.
var early = fx.Stage(Start, 40);
var late = fx.Stage(Start.AddMinutes(9), 41);
var project = new ProjectSettings
{
ExcludedFrames = [1],
Camera = new CameraSettings { Keyframes = [new CameraKey(0, 0.5, 0.5, 1, 0)] },
PendingFrames =
[
new PendingFrame { Sha256 = early.Sha256, Size = early.Size, Excluded = true },
new PendingFrame { Sha256 = late.Sha256, Size = late.Size, Hero = true, Keyframes = [new CameraKey(0, 0.3, 0.6, 2, 0)] },
],
}.ToJson();
AtomicFile.WriteAllText(folder.ProjectPath, project);
var version = (await fx.Db.Sequences.EditAsync(sequenceId, new SequenceEdit { SettingsJson = project }, null, fx.Ct)).Sequence!.SettingsVersion;
// The later photo is appended in step with the index; the earlier one is inserted before every other.
var appended = await fx.Service.Ingest.CommitAsync(Request(fx, late), fx.Ct);
var halfway = ProjectSettings.FromJson((await fx.Db.Sequences.GetAsync(sequenceId))!.SettingsJson!);
Assert.Equal(3, halfway.HeroFrame);
Assert.Count(1, halfway.PendingFrames!);
Assert.Equal(early.Sha256, halfway.PendingFrames![0].Sha256);
var inserted = await fx.Service.Ingest.CommitAsync(Request(fx, early), fx.Ct);
var row = (await fx.Db.Sequences.GetAsync(sequenceId))!;
var frames = await fx.Db.Frames.ListBySequenceAsync(sequenceId);
var placed = ProjectSettings.FromJson(row.SettingsJson!);
Assert.SequenceEqual([inserted.FrameId, results[1].FrameId], placed.ExcludedFrames.Select(i => frames[i].Id));
Assert.Equal(appended.FrameId, frames[placed.HeroFrame!.Value].Id);
Assert.SequenceEqual([results[0].FrameId, appended.FrameId], placed.Camera.Keyframes.Select(k => frames[k.Frame].Id));
Assert.Equal(0.3, placed.Camera.Keyframes[1].CenterX);
Assert.Null(placed.PendingFrames);
Assert.Equal(appended.FrameId, row.HeroFrameId);
Assert.Equal(version, row.SettingsVersion);
Assert.True(JsonNode.DeepEquals(JsonNode.Parse(row.SettingsJson!), JsonNode.Parse(File.ReadAllText(folder.ProjectPath))), "project.json mirrors the index");
}
[Test]
public async Task PhotosAFolderScanFindsMoveTheProjectPositionsButUnknownMembersStay()
{
@@ -69,6 +69,38 @@ public abstract class SequenceEditTests(TestContext context) : RepositoryTest(co
Assert.Equal(SequenceEditOutcome.Conflict, result.Outcome);
Assert.Null((await db.Sequences.GetAsync(sequence.Id, Ct))!.HeroFrameId);
}
[Test]
public async Task AnEditWaitsForARowWrittenBackFromALockedRead()
{
var db = await OpenTitanoAsync();
var archive = TestData.Archive();
await db.Archives.UpsertAsync(archive, Ct);
var sequence = TestData.Sequence(archive.Id);
await db.Sequences.UpsertAsync(sequence, Ct);
// An index commit reads the row and writes it back with its frames; a settings edit (the server's PATCH) arrives meanwhile.
Task<SequenceEditResult> edit;
await using (var tx = await db.BeginAsync(Ct))
{
var read = Assert.NotNull(await tx.Sequences.GetForUpdateAsync(sequence.Id, Ct));
edit = db.Sequences.EditAsync(sequence.Id, new SequenceEdit { SettingsJson = """{"excludedFrames":[1]}""" }, read.SettingsVersion, read.FramesVersion, Ct);
await Task.WhenAny(edit, Task.Delay(300, Ct));
Assert.False(edit.IsCompleted, "the edit waits for the row");
await tx.Sequences.UpsertAsync(read with { FramesVersion = read.FramesVersion + 1 }, Ct);
await tx.CommitAsync(Ct);
}
// It then finds the frames changed: written against the old ones, it is refused rather than undone.
var result = await edit;
Assert.Equal(SequenceEditOutcome.Conflict, result.Outcome);
var stored = (await db.Sequences.GetAsync(sequence.Id, Ct))!;
Assert.Equal((sequence.SettingsVersion, sequence.FramesVersion + 1), (stored.SettingsVersion, stored.FramesVersion));
// Without frames in question, it applies on top of the committed row.
var later = await db.Sequences.EditAsync(sequence.Id, new SequenceEdit { Rating = 3 }, stored.SettingsVersion, Ct);
Assert.Equal((sequence.SettingsVersion + 1, sequence.FramesVersion + 1, 3), (later.Sequence!.SettingsVersion, later.Sequence.FramesVersion, later.Sequence.Rating));
}
}
public sealed class SqliteSequenceEditTests(TestContext context) : SequenceEditTests(context)
+33 -10
View File
@@ -2,6 +2,7 @@ using System.Net;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Threading.Channels;
using Titano.Core.Metadata;
using Titano.Core.Model;
using Titano.Data.Sync;
using Titano.Protocol;
@@ -41,6 +42,9 @@ internal sealed class FakeSyncRemote : ISyncRemote
/// <summary>Proxies clients sent, by frame id (for sequences the server cannot decode).</summary>
public Dictionary<Guid, byte[]> SentProxies { get; } = [];
/// <summary>Edits the server accepted, in order.</summary>
public List<UpdateSequenceRequest> Updates { get; } = [];
public FakeSequence Add(string? title, IEnumerable<byte[]> originals, string? settingsJson = null,
SequenceStatus status = SequenceStatus.ProxiesBuilt | SequenceStatus.ThumbsBuilt)
{
@@ -105,7 +109,11 @@ internal sealed class FakeSyncRemote : ISyncRemote
public Task<IReadOnlyList<FrameDto>> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken)
{
lock (_gate) return Task.FromResult<IReadOnlyList<FrameDto>>([.. Find(sequenceId).Frames.Select((f, i) => f.Dto(sequenceId, i))]);
lock (_gate)
{
var sequence = Find(sequenceId);
return Task.FromResult<IReadOnlyList<FrameDto>>([.. sequence.Frames.Select(sequence.FrameDto)]);
}
}
public Task<SequenceDto> UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken)
@@ -115,6 +123,9 @@ internal sealed class FakeSyncRemote : ISyncRemote
var s = Find(id);
if (request.ExpectedSettingsVersion is { } expected && expected != s.SettingsVersion)
throw new TitanoApiException(HttpStatusCode.Conflict, new ApiError("settings_conflict", "changed"));
if (request.ExpectedFramesVersion is { } frames && frames != s.FramesVersion)
throw new TitanoApiException(HttpStatusCode.Conflict, new ApiError("frames_conflict", "changed"));
Updates.Add(request);
if (request.Title is not null) s.Title = request.Title.Length == 0 ? null : request.Title;
if (request.Tags is not null) s.Tags = [.. request.Tags];
if (request.Rating is { } rating) s.Rating = rating;
@@ -135,7 +146,8 @@ internal sealed class FakeSyncRemote : ISyncRemote
throw new TitanoApiException(HttpStatusCode.BadRequest, new ApiError("hash_mismatch", "hash"));
lock (_gate)
{
if (Sequences.Values.SelectMany(s => s.Frames).FirstOrDefault(f => f.Sha256 == sha256) is { } existing)
// Originals it never hashed are not recognised by content.
if (Sequences.Values.Where(s => !s.Unhashed).SelectMany(s => s.Frames).FirstOrDefault(f => f.Sha256 == sha256) is { } existing)
return new CompleteUploadResponse(existing.Id, sequenceId ?? Guid.Empty, -1);
FakeSequence target;
if (sequenceId is { } id) target = Find(id);
@@ -244,16 +256,25 @@ internal sealed class FakeSequence
/// <summary>The server cannot decode these originals (HEIF): its manifest asks for proxies of them.</summary>
public bool Undecodable { get; set; }
/// <summary>The server adopted these originals and never verified them: it lists no SHA-256 for them.</summary>
public bool Unhashed { get; set; }
public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow;
public DateTime? FirstCapture { get; set; }
public string? CameraModel { get; set; } = "Canon EOS R5";
public List<FakeFrame> Frames { get; } = [];
public List<FakeRender> Renders { get; } = [];
public FakeFrame AddFrame(byte[] bytes, string? name = null, DateTime? capturedAt = null)
/// <summary>Like the server, the capture time comes from the photo's Exif data when none is given.</summary>
public FakeFrame AddFrame(byte[] bytes, string? name = null, DateTime? capturedAt = null) => InsertFrame(Frames.Count, bytes, name, capturedAt);
/// <summary>A photo filed at <paramref name="index"/> (captured before the frames after it): those move up by one.</summary>
public FakeFrame InsertFrame(int index, byte[] bytes, string? name = null, DateTime? capturedAt = null)
{
var frame = new FakeFrame(Guid.CreateVersion7(), name ?? $"IMG_{Frames.Count + 1:0000}.JPG", bytes, capturedAt);
Frames.Add(frame);
name ??= $"IMG_{Frames.Count + 1:0000}.JPG";
using var stream = new MemoryStream(bytes);
var frame = new FakeFrame(Guid.CreateVersion7(), name, bytes, capturedAt ?? MetadataReader.Read(stream, name).CapturedAt);
Frames.Insert(index, frame);
FramesVersion++;
UpdatedAt = DateTimeOffset.UtcNow;
return frame;
@@ -263,9 +284,11 @@ internal sealed class FakeSequence
Frames.Sum(f => (long)f.Bytes.Length), (long)Status, Renders.Count, null, Tags, Rating, Notes, SettingsVersion, FramesVersion, 0, null, UpdatedAt);
public SequenceManifest Manifest(Func<Guid, bool> proxySent) => new(Id, FramesVersion, SettingsVersion, SettingsJson, Tags,
[.. Frames.Select((f, i) => new ManifestFrame(f.Id, i, f.FileName, f.Bytes.Length, f.Sha256, (Status & SequenceStatus.ProxiesBuilt) != 0 || proxySent(f.Id),
(Status & SequenceStatus.ThumbsBuilt) != 0, WantsProxy: Undecodable && !proxySent(f.Id)))], [.. Renders.Select(r => r.Dto())],
Undecodable ? new ProxySpec(1280, 90) : null);
[.. Frames.Select((f, i) => new ManifestFrame(f.Id, i, f.FileName, f.Bytes.Length, Unhashed ? string.Empty : f.Sha256,
(Status & SequenceStatus.ProxiesBuilt) != 0 || proxySent(f.Id), (Status & SequenceStatus.ThumbsBuilt) != 0, WantsProxy: Undecodable && !proxySent(f.Id)))],
[.. Renders.Select(r => r.Dto())], Undecodable ? new ProxySpec(1280, 90) : null);
public FrameDto FrameDto(FakeFrame frame) => frame.Dto(Id, Frames.IndexOf(frame), Unhashed);
}
internal sealed record FakeRender(Guid Id, string FileName, string PresetName, byte[] Bytes)
@@ -280,6 +303,6 @@ internal sealed record FakeFrame(Guid Id, string FileName, byte[] Bytes, DateTim
/// <summary>The original stands in for its proxy: a real JPEG the decoders read.</summary>
public byte[] Proxy => Bytes;
public FrameDto Dto(Guid sequenceId, int index) =>
new(Id, sequenceId, index, FileName, Bytes.Length, Sha256, CapturedAt, null, 1.0 / 250, 8, 100, 24, 1, 48, 32, "jpeg", 0);
public FrameDto Dto(Guid sequenceId, int index, bool unhashed = false) =>
new(Id, sequenceId, index, FileName, Bytes.Length, unhashed ? null : Sha256, CapturedAt, null, 1.0 / 250, 8, 100, 24, 1, 48, 32, "jpeg", 0);
}
@@ -74,6 +74,18 @@ internal sealed class SyncFixture : IAsyncDisposable
return sequence;
}
/// <summary>Files one more original into a local sequence through the archive ingest (an earlier photo lands before the others).</summary>
public async Task AddLocalAsync(Guid sequenceId, byte[] original)
{
var staging = Path.Combine(Archive.Paths.StagingDirectory, "test");
Directory.CreateDirectory(staging);
var path = Path.Combine(staging, $"{Guid.NewGuid():N}.part");
await File.WriteAllBytesAsync(path, original, Ct);
var sha = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(original));
await Archive.Service.Ingest.CommitAsync(new IngestRequest(Archive.Archive.Id, sequenceId, null, null, path, $"IMG_{sha[..8]}.JPG", original.Length, sha,
null, null), Ct);
}
/// <summary>An edit on this PC, as the editor makes it (project file and index, settings version + 1).</summary>
public async Task<Sequence> EditLocalSettingsAsync(Guid id, string settingsJson)
{
@@ -1,6 +1,7 @@
using Titano.Core.Imaging;
using Titano.Core.Imaging.Decoders;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Data.Sync;
using Titano.Protocol;
using Titano.Testing;
@@ -66,6 +67,46 @@ public sealed class SyncRulesTests
Assert.Equal((1, 0), SyncRules.CompareOriginals([null, null], ["bb"]));
}
[Test]
public void FramesEitherSideHasNotHashedAreMatchedBySizeAndCaptureTime()
{
var time = new DateTime(2026, 9, 28, 18, 0, 0);
FramePhoto Photo(string? sha, long size, int second) => new(sha, size, time.AddSeconds(second));
// A folder the server adopted and never verified: each of its frames counts on its own, matched by size and time.
Assert.Equal((0, 0), SyncRules.CompareOriginals([Photo("aa", 100, 0), Photo("bb", 200, 10)], [Photo("", 100, 0), Photo("", 200, 10)]));
Assert.Equal((1, 2), SyncRules.CompareOriginals([Photo("aa", 100, 0), Photo("bb", 200, 10)], [Photo("", 100, 0), Photo("", 300, 20), Photo("", 400, 30)]));
Assert.Equal((0, 3), SyncRules.CompareOriginals(Array.Empty<string?>(), ["", "", ""]));
// Hashed on both sides, the hash decides even when size and time agree.
Assert.Equal((1, 1), SyncRules.CompareOriginals([Photo("aa", 100, 0)], [Photo("cc", 100, 0)]));
// A photo the adopted folder holds twice ('IMG_0001.JPG' and 'IMG_0001 (1).JPG') is here in this PC's one copy,
// as the download finds it: nothing is left to fetch.
Assert.Equal((0, 0), SyncRules.CompareOriginals([Photo("aa", 100, 0)], [Photo("", 100, 0), Photo("", 100, 0)]));
Assert.Equal((0, 0), SyncRules.CompareOriginals([Photo(null, 100, 0)], [Photo("", 100, 0), Photo("", 100, 0)]));
Assert.Equal((0, 1), SyncRules.CompareOriginals([Photo("aa", 100, 0)], [Photo("", 100, 0), Photo("", 100, 0), Photo("", 100, 10)]));
}
[Test]
public void ProxiesOfFramesTheServerHasNotHashedAreCountedByCaptureTime()
{
var heif = new ImageDecoder([new NativeHeif()]);
var time = new DateTime(2026, 9, 28, 18, 0, 0);
List<Frame> local =
[
Original("aa", 100, ImageFileFormat.Heif) with { CapturedAt = time },
Original("bb", 200, ImageFileFormat.Heif) with { CapturedAt = time.AddSeconds(10) },
];
var first = Wanted(string.Empty, 100, "IMG_0001.HEIC");
var second = Wanted(string.Empty, 200, "IMG_0002.HEIC");
var manifest = new SequenceManifest(Guid.CreateVersion7(), 1, 1, null, [], [first, second], [], new ProxySpec(1920, 90));
var captured = new Dictionary<Guid, DateTime?> { [first.Id] = time, [second.Id] = time.AddSeconds(11) };
Assert.Equal(1, SyncRules.ProxiesToSend(manifest, local, heif, captured));
Assert.Equal(0, SyncRules.ProxiesToSend(manifest, local, heif));
Assert.Same(local[0], SyncRules.ProxyOriginal(first, time, local, SyncRules.Photos(local)));
Assert.Null(SyncRules.ProxyOriginal(second, time.AddSeconds(11), local, SyncRules.Photos(local)));
}
[Test]
public void ProxiesTheServerAsksForAreCountedForOriginalsThisPcReads()
{
@@ -1,4 +1,5 @@
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Data.Sync;
using Titano.Protocol;
using Titano.Protocol.Client;
@@ -94,6 +95,132 @@ public sealed class SyncServiceTests(TestContext context)
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
}
[Test]
public async Task PositionsSentToTheServerNameItsFramesAndWaitForPhotosItLacks()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(5);
var local = await f.LocalAsync("Harbour", photos);
// The server lacks the earliest photo (not uploaded yet).
var remote = f.Remote.Add("Harbour", photos[1..]);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
await f.EditLocalSettingsAsync(local.Id, new ProjectSettings { ExcludedFrames = [0, 2], HeroFrame = 4 }.ToJson());
await f.RefreshAsync();
var sent = ProjectSettings.FromJson(remote.SettingsJson!);
Assert.SequenceEqual([Sha(photos[2])], sent.ExcludedFrames.Select(i => remote.Frames[i].Sha256));
Assert.Equal(Sha(photos[4]), remote.Frames[sent.HeroFrame!.Value].Sha256);
Assert.Count(1, sent.PendingFrames!);
var waiting = sent.PendingFrames![0];
Assert.True(waiting.Excluded && waiting.Sha256 == Sha(photos[0]), "the exclusion of the photo the server lacks waits for it");
Assert.Equal(remote.FramesVersion, f.Remote.Updates[^1].ExpectedFramesVersion);
// This PC's project keeps its own positions.
Assert.SequenceEqual([0, 2], ProjectSettings.FromJson((await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson!).ExcludedFrames);
Assert.Equal(SyncStatus.LocalAhead, (await f.EntryAsync("Harbour")).Status);
Assert.Equal(1, (await f.EntryAsync("Harbour")).Link!.MissingRemote);
}
[Test]
public async Task SettingsSentWhileTheServersFramesChangeAreTranslatedAgain()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(4);
var local = await f.LocalAsync("Harbour", photos[1..]);
var remote = f.Remote.Add("Harbour", photos[1..]);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
await f.EditLocalSettingsAsync(local.Id, new ProjectSettings { ExcludedFrames = [1] }.ToJson());
// An earlier photo is filed on the server after the manifest was read, before the settings arrive.
var racing = new RacingRemote(f.Remote, () => remote.InsertFrame(0, photos[0]), beforeUpdate: true);
await f.Sync.RefreshAsync(racing, new SyncPolicy(), f.Ct);
Assert.Empty(f.Remote.Updates);
Assert.Equal(SyncStatus.LocalAhead, (await f.EntryAsync("Harbour")).Status);
await f.RefreshAsync();
Assert.SequenceEqual([Sha(photos[2])], ProjectSettings.FromJson(remote.SettingsJson!).ExcludedFrames.Select(i => remote.Frames[i].Sha256));
Assert.Equal((SyncStatus.ServerAhead, 1), ((await f.EntryAsync("Harbour")).Status, (await f.EntryAsync("Harbour")).Link!.MissingLocal));
}
[Test]
public async Task SettingsSentWhileAnImportHereMovesTheirPositionsStayOnTheirPhotos()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(4);
var local = await f.LocalAsync("Harbour", photos[1..]);
var remote = f.Remote.Add("Harbour", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
await f.EditLocalSettingsAsync(local.Id, new ProjectSettings { ExcludedFrames = [1], HeroFrame = 2 }.ToJson());
// The earliest photo is imported here after the comparison read this copy, before its settings are translated.
var racing = new RacingRemote(f.Remote, () => f.AddLocalAsync(local.Id, photos[0]).GetAwaiter().GetResult(), beforeManifest: true);
await f.Sync.RefreshAsync(racing, new SyncPolicy(), f.Ct);
var mine = ProjectSettings.FromJson((await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson!);
Assert.SequenceEqual([2], mine.ExcludedFrames);
Assert.Equal(3, mine.HeroFrame);
var sent = ProjectSettings.FromJson(remote.SettingsJson!);
Assert.SequenceEqual([Sha(photos[2])], sent.ExcludedFrames.Select(i => remote.Frames[i].Sha256));
Assert.Equal(Sha(photos[3]), remote.Frames[sent.HeroFrame!.Value].Sha256);
Assert.Null(sent.PendingFrames);
}
[Test]
public async Task SettingsComparedWhileAnImportHereMovesTheirPositionsAreAgreed()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(4);
var local = await f.LocalAsync("Harbour", photos[1..]);
var remote = f.Remote.Add("Harbour", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
// Both sides exclude the same photo, each by its own frames.
await f.EditLocalSettingsAsync(local.Id, new ProjectSettings { ExcludedFrames = [1] }.ToJson());
f.Remote.EditSettings(remote.Id, new ProjectSettings { ExcludedFrames = [2] }.ToJson());
var racing = new RacingRemote(f.Remote, () => f.AddLocalAsync(local.Id, photos[0]).GetAwaiter().GetResult(), beforeManifest: true);
await f.Sync.RefreshAsync(racing, new SyncPolicy(), f.Ct);
var entry = await f.EntryAsync("Harbour");
Assert.Null(entry.Link!.ConflictRemote);
Assert.Equal(entry.Local!.SettingsVersion, entry.Link.BaseLocalSettings);
Assert.Equal(remote.SettingsVersion, entry.Link.BaseRemoteSettings);
Assert.SequenceEqual([2], ProjectSettings.FromJson(entry.Local.SettingsJson!).ExcludedFrames);
}
[Test]
public async Task TheSameSettingsFromTheServerAreAgreedWhileTheArchiveIsOffline()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Harbour", photos, SyncFixture.Window41);
var remote = f.Remote.Add("Harbour", photos, SyncFixture.Window41);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
// The server's version moves with the same content (another PC sent the same values); the archive's drive is unplugged.
f.Remote.EditSettings(remote.Id, SyncFixture.Window41);
var aside = f.Archive.Paths.ManifestPath + ".unplugged";
File.Move(f.Archive.Paths.ManifestPath, aside);
try
{
await f.RefreshAsync();
}
finally
{
File.Move(aside, f.Archive.Paths.ManifestPath);
}
var entry = await f.EntryAsync("Harbour");
Assert.Null(entry.Link!.Error);
Assert.Equal(SyncStatus.InSync, entry.Status);
Assert.Equal(local.SettingsVersion, entry.Local!.SettingsVersion);
}
[Test]
public async Task AnEditSavedHereDuringTheComparisonIsNotReplacedByTheServers()
{
@@ -441,6 +568,8 @@ public sealed class SyncServiceTests(TestContext context)
Assert.Equal(originals.Id, (await f.EntryAsync("Construction cam")).Transfer!.Id);
}
private static string Sha(byte[] bytes) => Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(bytes));
/// <summary>A linked sequence whose settings changed differently on both sides since they last agreed (41 here, 33 on the server).</summary>
private static async Task<(Sequence Local, FakeSequence Remote)> ConflictAsync(SyncFixture f)
{
@@ -3,6 +3,7 @@ using Titano.Core.Imaging;
using Titano.Core.Imaging.Decoders;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Core.Render;
using Titano.Data.Sync;
using Titano.Testing;
@@ -264,6 +265,161 @@ public sealed class SyncTransferTests(TestContext context)
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
}
[Test]
public async Task OriginalsTheServerHasNotHashedAreDownloadedAndHashedHere()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(3);
// A folder the server adopted and never verified: its manifest lists no SHA-256.
var remote = f.Remote.Add("Adopted on the server", photos);
remote.Unhashed = true;
await f.RefreshAsync();
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Adopted on the server", SyncDownloadMode.Originals, f.Archive.Archive.Id);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var entry = await f.EntryAsync("Adopted on the server");
var frames = await f.Db.Frames.ListBySequenceAsync(entry.Local!.Id, cancellationToken: f.Ct);
Assert.True(frames.Select(r => r.Sha256).ToHashSet().SetEquals(photos.Select(Sha)), "every original arrived, hashed here");
// Matched by size and capture time, the copies are the server's originals.
Assert.Equal((SyncStatus.InSync, 0, 0), (entry.Status, entry.Link!.MissingRemote, entry.Link.MissingLocal));
// One more photo adopted there: only that one travels.
remote.AddFrame(f.NewPhotos(1)[0]);
await f.RefreshAsync();
Assert.Equal(1, (await f.EntryAsync("Adopted on the server")).Link!.MissingLocal);
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Adopted on the server", SyncDownloadMode.Originals, null);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
Assert.Equal(4, (await f.Db.Frames.ListBySequenceAsync(entry.Local.Id, cancellationToken: f.Ct)).Count);
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Adopted on the server")).Status);
}
[Test]
public async Task AnUploadDoesNotSendAgainWhatTheServerHoldsWithoutAHash()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(4);
var local = await f.LocalAsync("Harbour", photos);
// The server adopted the first three photos and never verified them: it cannot recognise them by content.
var remote = f.Remote.Add("Harbour", photos[..3]);
remote.Unhashed = true;
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
var ahead = (await f.EntryAsync("Harbour")).Link!;
Assert.Equal((1, 0), (ahead.MissingRemote, ahead.MissingLocal));
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
var done = await f.Archive.WaitForAsync(job.Id, JobState.Done);
Assert.Equal((4L, 4L), (done.ProgressDone, done.ProgressTotal));
Assert.SequenceEqual(photos.Select(Sha), remote.Frames.Select(r => r.Sha256));
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
}
[Test]
public async Task ProxiesOfFramesTheServerHasNotHashedAreSentToo()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Holy grail", photos);
// The server adopted the same originals, cannot decode them and has not hashed them.
var remote = f.Remote.Add("Holy grail", photos);
remote.Undecodable = true;
remote.Unhashed = true;
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
Assert.Equal(3, (await f.EntryAsync("Holy grail")).Link!.MissingRemote);
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
Assert.True(f.Remote.SentProxies.Keys.ToHashSet().SetEquals(remote.Frames.Select(r => r.Id)), "a proxy of every frame");
Assert.Equal((SyncStatus.InSync, 0), ((await f.EntryAsync("Holy grail")).Status, (await f.EntryAsync("Holy grail")).Link!.MissingRemote));
}
[Test]
public async Task PositionsTakenFromTheServerStayOnTheirPhotosWhenTheOriginalsArrive()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(6);
var local = await f.LocalAsync("Harbour", photos[1..5]);
var remote = f.Remote.Add("Harbour", photos[1..5]);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
// Another PC sends the server an earlier and a later photo; then an editor there excludes two photos, picks the
// hero and keys the camera, by the server's frames.
remote.InsertFrame(0, photos[0]);
remote.AddFrame(photos[5]);
f.Remote.EditSettings(remote.Id, new ProjectSettings
{
ExcludedFrames = [0, 3],
HeroFrame = 5,
Camera = new CameraSettings { Keyframes = [new CameraKey(2, 0.4, 0.5, 1.5, 0)] },
}.ToJson());
await f.RefreshAsync();
var taken = await NamedAsync(f, local.Id);
Assert.SequenceEqual([Sha(photos[3])], taken.Excluded);
Assert.Null(taken.Hero);
Assert.SequenceEqual([Sha(photos[2])], taken.Keyframes);
Assert.True(taken.Pending.ToHashSet().SetEquals([Sha(photos[0]), Sha(photos[5])]), "the photos this copy lacks wait for them");
// Each waits with its capture time too, whichever side hashed what: the same project reads the same either way.
var waiting = ProjectSettings.FromJson((await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson!).PendingFrames!;
Assert.True(waiting.All(p => p.CapturedAt is not null), "a photo waits with its capture time");
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Harbour", SyncDownloadMode.Originals, null);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
// The same photos as on the server, and nothing waits any more.
var arrived = await NamedAsync(f, local.Id);
Assert.SequenceEqual([Sha(photos[0]), Sha(photos[3])], arrived.Excluded);
Assert.Equal(Sha(photos[5]), arrived.Hero);
Assert.SequenceEqual([Sha(photos[2])], arrived.Keyframes);
Assert.Empty(arrived.Pending);
var row = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
var frames = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
Assert.Equal(Sha(photos[5]), frames.Single(fr => fr.Id == row.HeroFrameId).Sha256);
Assert.True(SyncRules.SameSettings(row.SettingsJson, await File.ReadAllTextAsync(f.Archive.Paths.Sequence(row.Folder).ProjectPath, f.Ct)),
"project.json mirrors the index");
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
// An edit here later sends the server the same photos, by its frames.
var edited = ProjectSettings.FromJson(row.SettingsJson!) with { Exposure = new ExposureSettings { DeflickerWindow = new Auto<int>().WithManual(41) } };
await f.EditLocalSettingsAsync(local.Id, edited.ToJson());
await f.RefreshAsync();
var server = ProjectSettings.FromJson(remote.SettingsJson!);
Assert.Equal(41, server.Exposure.DeflickerWindow.Manual);
Assert.SequenceEqual([Sha(photos[0]), Sha(photos[3])], server.ExcludedFrames.Select(i => remote.Frames[i].Sha256));
Assert.Equal(Sha(photos[5]), remote.Frames[server.HeroFrame!.Value].Sha256);
Assert.SequenceEqual([Sha(photos[2])], server.Camera.Keyframes.Select(k => remote.Frames[k.Frame].Sha256));
}
[Test]
public async Task ACachedThumbnailIsReplacedOnceTheServerHasTheProxy()
{
await using var f = await SyncFixture.CreateAsync(context);
var remote = f.Remote.Add("Fog", f.NewPhotos(2), status: SequenceStatus.ThumbsBuilt);
await f.RefreshAsync();
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Fog", SyncDownloadMode.Proxies, null);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
Assert.True(Assert.NotNull(f.Sync.OpenRemote(f.Server, remote.Id)).Files.All(file => new FileInfo(file!).Length == 64), "thumbnails stand in");
Assert.True((await f.EntryAsync("Fog")).Link!.ProxiesStale, "the cache is filled again once the server has proxies");
// Proxies arrive on the server (a client or render node sent them); the frames did not change.
remote.Status |= SequenceStatus.ProxiesBuilt;
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Fog", SyncDownloadMode.Proxies, null);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var opened = Assert.NotNull(f.Sync.OpenRemote(f.Server, remote.Id));
Assert.SequenceEqual(remote.Frames.Select(r => (long)r.Proxy.Length), opened.Files.Select(file => new FileInfo(file!).Length));
Assert.False((await f.EntryAsync("Fog")).Link!.ProxiesStale);
}
[Test]
public async Task TheServersRendersAreFetchedIntoTheLocalExports()
{
@@ -407,4 +563,13 @@ public sealed class SyncTransferTests(TestContext context)
}
private static string Sha(byte[] bytes) => Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(bytes));
/// <summary>The photos (SHA-256) the local copy's project excludes, shows as hero, keys the camera on, and waits for.</summary>
private static async Task<(string[] Excluded, string? Hero, string[] Keyframes, string[] Pending)> NamedAsync(SyncFixture f, Guid localId)
{
var project = ProjectSettings.FromJson((await f.Db.Sequences.GetAsync(localId, f.Ct))!.SettingsJson!);
var frames = await f.Db.Frames.ListBySequenceAsync(localId, cancellationToken: f.Ct);
return ([.. project.ExcludedFrames.Select(i => frames[i].Sha256!)], project.HeroFrame is { } hero ? frames[hero].Sha256 : null,
[.. project.Camera.Keyframes.Select(k => frames[k.Frame].Sha256!)], [.. (project.PendingFrames ?? []).Select(p => p.Sha256!)]);
}
}
@@ -1,7 +1,9 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using Titano.Data;
using Titano.Protocol;
using Titano.Server.Api;
using Titano.Testing;
namespace Titano.Server.Tests.Api;
@@ -60,6 +62,32 @@ public sealed class SequenceTests(TestContext context)
await invalid.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_settings");
}
[Test]
public async Task SettingsWrittenAgainstFramesThatChangedAreRefused()
{
await using var server = await TestServer.StartAsync(context);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var first = await Uploads.UploadAsync(editor, Uploads.Photo(2000, 41), "a.CR3", sessionKey: "k");
using var read = await editor.GetAsync($"/api/v1/sequences/{first.SequenceId}");
var sequence = await read.ReadAsync(ProtocolJson.Default.SequenceDto);
// Another photo arrives after this client read the frames its positions name.
await Uploads.UploadAsync(editor, Uploads.Photo(2000, 42), "b.CR3", sessionKey: "k");
using (var stale = await editor.PatchAsJsonAsync($"/api/v1/sequences/{sequence.Id}",
new UpdateSequenceRequest(null, null, null, null, """{"excludedFrames":[0]}""", sequence.SettingsVersion, ExpectedFramesVersion: sequence.FramesVersion),
ProtocolJson.Default.UpdateSequenceRequest))
{
var error = await stale.ExpectErrorAsync(HttpStatusCode.Conflict, "frames_conflict");
Assert.Equal((sequence.FramesVersion + 1).ToString(System.Globalization.CultureInfo.InvariantCulture), error.Details);
}
using var fresh = await editor.PatchAsJsonAsync($"/api/v1/sequences/{sequence.Id}",
new UpdateSequenceRequest(null, null, null, null, """{"excludedFrames":[1]}""", sequence.SettingsVersion, ExpectedFramesVersion: sequence.FramesVersion + 1),
ProtocolJson.Default.UpdateSequenceRequest);
await fresh.ExpectAsync(HttpStatusCode.OK);
Assert.Equal(sequence.SettingsVersion + 1, (await fresh.ReadAsync(ProtocolJson.Default.SequenceDto)).SettingsVersion);
}
[Test]
public async Task TheManifestCarriesHashesAndAnEtag()
{
@@ -88,6 +116,59 @@ public sealed class SequenceTests(TestContext context)
Assert.Count(3, (await changed.ReadAsync(ProtocolJson.Default.SequenceManifest)).Frames);
}
[Test]
public async Task TheManifestListsTheFramesOfOneFramesVersion()
{
await using var server = await TestServer.StartAsync(context);
await FramesOfOneVersionAsync(server);
}
/// <summary>The manifest's frames are read again while frames are committed, then under the row lock (also run on PostgreSQL).</summary>
internal static async Task FramesOfOneVersionAsync(TestServer server)
{
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var first = await Uploads.UploadAsync(editor, Uploads.Photo(2000, 51), "a.CR3", sessionKey: "k");
var db = server.Database;
var id = first.SequenceId;
var start = (await db.Sequences.GetAsync(id))!.FramesVersion;
// Frames are committed while the first listing is read: it is read again.
var listings = new List<int>();
var snapshot = await SequenceEndpoints.SnapshotAsync(db, id, async (_, sequence, ct) =>
{
listings.Add(sequence.FramesVersion);
if (listings.Count == 1) await db.Sequences.RefreshStatsAsync(id, ct);
return [];
}, CancellationToken.None);
Assert.SequenceEqual([start, start + 1], listings);
Assert.Equal(start + 1, Assert.NotNull(snapshot).Sequence.FramesVersion);
// Commits keep landing: the last listing is read while none can.
Task? waiting = null;
listings.Clear();
var locked = await SequenceEndpoints.SnapshotAsync(db, id, async (on, sequence, ct) =>
{
listings.Add(sequence.FramesVersion);
if (listings.Count <= 3)
{
await db.Sequences.RefreshStatsAsync(id, ct);
return [];
}
// Listed on the transaction that holds the row (on SQLite, the only connection that may while it writes).
Assert.True(on is TitanoTransaction, "the frames are listed inside the locking transaction");
Assert.Count(1, await on.Frames.ListBySequenceAsync(id, cancellationToken: ct));
waiting = db.Sequences.RefreshStatsAsync(id, ct);
await Task.WhenAny(waiting, Task.Delay(300, ct));
Assert.False(waiting.IsCompleted, "a commit of frames waits until the frames are listed");
return [];
}, CancellationToken.None);
await Assert.NotNull(waiting);
Assert.SequenceEqual([start + 1, start + 2, start + 3, start + 4], listings);
Assert.Equal(start + 4, Assert.NotNull(locked).Sequence.FramesVersion);
Assert.Equal(start + 5, (await db.Sequences.GetAsync(id))!.FramesVersion);
Assert.Null(await SequenceEndpoints.SnapshotAsync(db, Guid.NewGuid(), (_, _, _) => Task.FromResult(new List<ManifestFrame>()), CancellationToken.None));
}
[Test]
public async Task ListingFiltersAndPagesWithACursor()
{
@@ -54,6 +54,19 @@ public sealed class PostgresServerTests(TestContext context)
Assert.Equal("ok", (await health.ReadAsync(ProtocolJson.Default.HealthStatus)).Checks["database"]);
}
[Test]
public async Task TheManifestListsTheFramesOfOneFramesVersionOnPostgres()
{
await using var schema = await Schema.CreateAsync(context);
await using var server = await TestServer.StartAsync(context, o =>
{
o.Database = DatabaseKind.Postgres;
o.DbConnectionString = schema.ConnectionString;
});
Assert.Equal(Dialect.Postgres, server.Database.Dialect);
await Api.SequenceTests.FramesOfOneVersionAsync(server);
}
/// <summary>A throw-away schema on the test server, selected through <c>Search Path</c>.</summary>
private sealed class Schema : IAsyncDisposable
{
@@ -85,6 +85,26 @@ internal sealed class SyncClient : IAsyncDisposable
return edited.Sequence!;
}
/// <summary>One more photo imported into a local sequence, captured at <paramref name="captured"/> (before others: it is inserted).</summary>
public async Task<IngestResult> AddPhotoAsync(Guid sequenceId, byte[] photo, DateTime captured)
{
var staging = Path.Combine(Archive.RootPath, ".titano", "staging", "test");
Directory.CreateDirectory(staging);
var path = Path.Combine(staging, $"{Guid.NewGuid():N}.part");
await File.WriteAllBytesAsync(path, photo, Ct);
return await Archives.Ingest.CommitAsync(new IngestRequest(Archive.Id, sequenceId, null, null, path, $"IMG_{captured:HHmmss}.JPG", photo.Length, Sha(photo),
captured, null), Ct);
}
/// <summary>An edit on this PC, as the editor makes it (project file and index, settings version + 1).</summary>
public async Task<Sequence> EditSettingsAsync(Guid sequenceId, string settingsJson)
{
var sequence = (await Db.Sequences.GetAsync(sequenceId, Ct))!;
await File.WriteAllTextAsync(new Titano.Core.Archiving.ArchivePaths(Archive.RootPath).Sequence(sequence.Folder).ProjectPath, settingsJson, Ct);
return (await Db.Sequences.EditAsync(sequenceId, new Titano.Data.Repositories.SequenceEdit { SettingsJson = settingsJson }, sequence.SettingsVersion, Ct))
.Sequence!;
}
/// <summary>A render of <paramref name="sequence"/> made on this PC: its file in the sequence's exports and its row.</summary>
public async Task<Render> RenderAsync(Sequence sequence, string fileName, byte[] bytes)
{
@@ -249,6 +249,117 @@ public sealed class SyncServerTests(TestContext context)
Assert.Equal(0, (await laptop.EntryAsync("Star trails")).Link!.ExportsToGet);
}
[Test]
public async Task PositionsEditedOnTheServerStayOnTheirPhotosWhenAnotherPcDownloadsTheInsertedFrames()
{
await using var server = await StartServerAsync();
var (http, _, token) = await server.UserAsync("alberto", "editor");
await using var studio = await SyncClient.StartAsync(context, server, token, "studio");
await using var laptop = await SyncClient.StartAsync(context, server, token, "laptop");
var photos = Enumerable.Range(60, 5).Select(SyncClient.Photo).ToList();
// Both PCs hold the last four photos, the third of them excluded.
var local = await studio.LocalAsync("Harbour at dawn", photos[1..], new ProjectSettings { ExcludedFrames = [2] }.ToJson());
await studio.WaitAsync((await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local)).Id);
var remoteId = (await studio.EntryAsync("Harbour at dawn")).Link!.RemoteId;
await ServerIdleAsync(server);
await laptop.Sync.RefreshAsync(laptop.Remote, new SyncPolicy(), context.Cancellation);
await laptop.WaitAsync((await laptop.Sync.EnqueueDownloadAsync(laptop.Engine, laptop.Server, remoteId, "Harbour at dawn", SyncDownloadMode.Originals,
laptop.Archive.Id)).Id);
var copy = (await laptop.EntryAsync("Harbour at dawn")).Local!;
// The studio files an earlier photo and uploads it: the server inserts it first and moves its own positions.
await studio.AddPhotoAsync(local.Id, photos[0], new DateTime(2026, 9, 28, 17, 59, 50));
await studio.WaitAsync((await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local)).Id);
await ServerIdleAsync(server);
Assert.SequenceEqual([SyncClient.Sha(photos[3])], (await ServerNamedAsync(server, remoteId)).Excluded);
// An editor on the server excludes the new photo too, by the server's frames, and changes the deflicker window.
var row = (await server.Database.Sequences.GetAsync(remoteId))!;
var current = ProjectSettings.FromJson(row.SettingsJson!);
var edit = current with
{
ExcludedFrames = [0, .. current.ExcludedFrames],
Exposure = current.Exposure with { DeflickerWindow = new Auto<int>().WithManual(33) },
};
using (var patch = await http.PatchAsJsonAsync($"/api/v1/sequences/{remoteId}",
new UpdateSequenceRequest(null, null, null, null, edit.ToJson(), row.SettingsVersion), ProtocolJson.Default.UpdateSequenceRequest))
await patch.ExpectAsync(HttpStatusCode.OK);
// The laptop takes the edit while it still lacks the new photo, then downloads it.
await laptop.Sync.RefreshAsync(laptop.Remote, new SyncPolicy(), context.Cancellation);
var taken = await LocalNamedAsync(laptop, copy.Id);
Assert.Equal(33, taken.Project.Exposure.DeflickerWindow.Manual);
Assert.SequenceEqual([SyncClient.Sha(photos[3])], taken.Excluded);
Assert.True(taken.Project.PendingFrames is [{ Excluded: true } waiting] && waiting.Sha256 == SyncClient.Sha(photos[0]), "the new photo's exclusion waits for it");
await laptop.WaitAsync((await laptop.Sync.EnqueueDownloadAsync(laptop.Engine, laptop.Server, remoteId, "Harbour at dawn", SyncDownloadMode.Originals,
null)).Id);
var onServer = await ServerNamedAsync(server, remoteId);
var here = await LocalNamedAsync(laptop, copy.Id);
Assert.SequenceEqual([SyncClient.Sha(photos[0]), SyncClient.Sha(photos[3])], here.Excluded);
Assert.SequenceEqual(onServer.Excluded, here.Excluded);
Assert.Equal(onServer.Hero, here.Hero);
Assert.Null(here.Project.PendingFrames);
await laptop.Sync.RefreshAsync(laptop.Remote, new SyncPolicy(), context.Cancellation);
Assert.Equal(SyncStatus.InSync, (await laptop.EntryAsync("Harbour at dawn")).Status);
}
[Test]
public async Task PositionsSentBeforeTheirPhotosStayOnThemWhenTheUploadArrives()
{
await using var server = await StartServerAsync();
var (_, _, token) = await server.UserAsync("alberto", "editor");
await using var studio = await SyncClient.StartAsync(context, server, token, "studio");
var photos = Enumerable.Range(70, 5).Select(SyncClient.Photo).ToList();
var local = await studio.LocalAsync("Pier", photos[1..]);
await studio.WaitAsync((await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local)).Id);
var remoteId = (await studio.EntryAsync("Pier")).Link!.RemoteId;
await ServerIdleAsync(server);
await studio.Sync.RefreshAsync(studio.Remote, new SyncPolicy(), context.Cancellation);
// This PC files an earlier photo and, before uploading it, excludes it and a later one and picks the hero.
await studio.AddPhotoAsync(local.Id, photos[0], new DateTime(2026, 9, 28, 17, 59, 50));
var project = ProjectSettings.FromJson((await studio.Db.Sequences.GetAsync(local.Id))!.SettingsJson ?? "{}");
await studio.EditSettingsAsync(local.Id, (project with { ExcludedFrames = [0, 3], HeroFrame = 1 }).ToJson());
await studio.Sync.RefreshAsync(studio.Remote, new SyncPolicy(), context.Cancellation);
var sent = await ServerNamedAsync(server, remoteId);
Assert.SequenceEqual([SyncClient.Sha(photos[3])], sent.Excluded);
Assert.Equal(SyncClient.Sha(photos[1]), sent.Hero);
Assert.True(sent.Project.PendingFrames is [{ Excluded: true } waiting] && waiting.Sha256 == SyncClient.Sha(photos[0]), "the exclusion waits for its photo");
await studio.WaitAsync((await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local)).Id);
await ServerIdleAsync(server);
var arrived = await ServerNamedAsync(server, remoteId);
Assert.SequenceEqual([SyncClient.Sha(photos[0]), SyncClient.Sha(photos[3])], arrived.Excluded);
Assert.Equal(SyncClient.Sha(photos[1]), arrived.Hero);
Assert.Null(arrived.Project.PendingFrames);
var heroFrame = (await server.Database.Sequences.GetAsync(remoteId))!.HeroFrameId;
Assert.Equal(SyncClient.Sha(photos[1]), (await server.Database.Frames.ListBySequenceAsync(remoteId)).Single(f => f.Id == heroFrame).Sha256);
var here = await LocalNamedAsync(studio, local.Id);
Assert.SequenceEqual(arrived.Excluded, here.Excluded);
Assert.Equal(arrived.Hero, here.Hero);
await studio.Sync.RefreshAsync(studio.Remote, new SyncPolicy(), context.Cancellation);
Assert.Equal(SyncStatus.InSync, (await studio.EntryAsync("Pier")).Status);
}
/// <summary>The server's project and the photos (SHA-256) it excludes and shows as hero.</summary>
private static async Task<(ProjectSettings Project, string?[] Excluded, string? Hero)> ServerNamedAsync(TestServer server, Guid remoteId)
{
var project = ProjectSettings.FromJson((await server.Database.Sequences.GetAsync(remoteId))!.SettingsJson ?? "{}");
var frames = await server.Database.Frames.ListBySequenceAsync(remoteId);
return (project, [.. project.ExcludedFrames.Select(i => frames[i].Sha256)], project.HeroFrame is { } hero ? frames[hero].Sha256 : null);
}
/// <summary>A PC's project and the photos (SHA-256) it excludes and shows as hero.</summary>
private static async Task<(ProjectSettings Project, string?[] Excluded, string? Hero)> LocalNamedAsync(SyncClient client, Guid localId)
{
var project = ProjectSettings.FromJson((await client.Db.Sequences.GetAsync(localId))!.SettingsJson ?? "{}");
var frames = await client.Db.Frames.ListBySequenceAsync(localId);
return (project, [.. project.ExcludedFrames.Select(i => frames[i].Sha256)], project.HeroFrame is { } hero ? frames[hero].Sha256 : null);
}
private Task<TestServer> StartServerAsync() => TestServer.StartAsync(context, o => o.ChunkSizeBytes = 64 * 1024, ArchiveModule.Register);
/// <summary>Waits until the server's engines finished what the commits queued (thumbnails, proxies, analysis, which may edit settings).</summary>