merge: sync and project position fixes (V-9, V-10, V-21, V-29, CD-2)

Merge branch fix2/sync-positions into the verification branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-12 17:10:58 +00:00
commit 51acc7f91b
32 files changed
+1843 -153

No files matched your search

@@ -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>