using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Data.Archiving;
using Chronos.Data.Processing;
using Chronos.Data.Repositories;
using Chronos.Data.Tests.Infrastructure;
using Chronos.Data.Tests.Processing;
using Chronos.Testing;
namespace Chronos.Data.Tests.Repositories;
/// Client edits of a sequence row () on both dialects: the hero frame the Library shows.
public abstract class SequenceEditTests(TestContext context) : RepositoryTest(context)
{
[Test]
public async Task TheHeroFrameIsSetKeptAndCleared()
{
var db = await OpenChronosAsync();
var archive = TestData.Archive();
await db.Archives.UpsertAsync(archive, Ct);
var sequence = TestData.Sequence(archive.Id);
await db.Sequences.UpsertAsync(sequence, Ct);
var frames = Enumerable.Range(0, 5).Select(i => TestData.Frame(sequence.Id, i)).ToList();
await db.Frames.BulkInsertAsync(frames, Ct);
var set = await db.Sequences.EditAsync(sequence.Id, new SequenceEdit { SettingsJson = "{\"heroFrame\":3}", HeroFrameId = frames[3].Id }, null, Ct);
Assert.Equal(SequenceEditOutcome.Updated, set.Outcome);
Assert.Equal(frames[3].Id, set.Sequence!.HeroFrameId);
Assert.Equal(frames[3].Id, (await db.Sequences.GetAsync(sequence.Id, Ct))!.HeroFrameId);
var kept = await db.Sequences.EditAsync(sequence.Id, new SequenceEdit { Rating = 4 }, set.Sequence.SettingsVersion, Ct);
Assert.Equal(frames[3].Id, kept.Sequence!.HeroFrameId, "an edit without a hero leaves it alone");
var cleared = await db.Sequences.EditAsync(sequence.Id, new SequenceEdit { HeroFrameId = Guid.Empty }, null, Ct);
Assert.Null(cleared.Sequence!.HeroFrameId, "Guid.Empty goes back to the first frame");
}
[Test]
public async Task AFrameOfAnotherSequenceIsNotAHero()
{
var db = await OpenChronosAsync();
var archive = TestData.Archive();
await db.Archives.UpsertAsync(archive, Ct);
var mine = TestData.Sequence(archive.Id, title: "Mine");
var other = TestData.Sequence(archive.Id, title: "Other");
await db.Sequences.UpsertAsync(mine, Ct);
await db.Sequences.UpsertAsync(other, Ct);
var own = TestData.Frame(mine.Id, 0);
var foreign = TestData.Frame(other.Id, 0);
await db.Frames.BulkInsertAsync([own, foreign], Ct);
await db.Sequences.EditAsync(mine.Id, new SequenceEdit { HeroFrameId = own.Id }, null, Ct);
var result = await db.Sequences.EditAsync(mine.Id, new SequenceEdit { HeroFrameId = foreign.Id }, null, Ct);
Assert.Equal(SequenceEditOutcome.Updated, result.Outcome);
Assert.Equal(own.Id, result.Sequence!.HeroFrameId);
}
[Test]
public async Task AConflictLeavesTheHeroAsItWas()
{
var db = await OpenChronosAsync();
var archive = TestData.Archive();
await db.Archives.UpsertAsync(archive, Ct);
var sequence = TestData.Sequence(archive.Id);
await db.Sequences.UpsertAsync(sequence, Ct);
var frame = TestData.Frame(sequence.Id, 0);
await db.Frames.BulkInsertAsync([frame], Ct);
var result = await db.Sequences.EditAsync(sequence.Id, new SequenceEdit { HeroFrameId = frame.Id }, sequence.SettingsVersion + 7, Ct);
Assert.Equal(SequenceEditOutcome.Conflict, result.Outcome);
Assert.Null((await db.Sequences.GetAsync(sequence.Id, Ct))!.HeroFrameId);
}
[Test]
public async Task AnEditWaitsForARowWrittenBackFromALockedRead()
{
var db = await OpenChronosAsync();
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 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));
}
[Test]
public async Task WritersOfSequencesSharingTagsListedInOppositeOrdersBothComplete()
{
var db = await OpenChronosAsync(multiConnection: true);
var archive = TestData.Archive();
await db.Archives.UpsertAsync(archive, Ct);
var tagged = TestData.Sequence(archive.Id, title: "Tagged");
var first = TestData.Sequence(archive.Id, title: "First");
var second = TestData.Sequence(archive.Id, title: "Second");
await db.Sequences.UpsertAsync(tagged with { Tags = ["Alps", "sunset"] }, Ct);
await db.Sequences.UpsertAsync(first, Ct);
await db.Sequences.UpsertAsync(second, Ct);
var alps = (await db.Tags.ListAsync(Ct)).Single(t => t.Name == "Alps");
// A transaction holds the first of the two tags (SQLite: its write lock), so both writers below wait until it ends.
Task forward, backward;
await using (var tx = await db.BeginAsync(Ct))
{
if (Dialect == Dialect.Postgres)
Assert.Equal(alps.Id, await tx.Session.ScalarAsync("SELECT id FROM tags WHERE id = $1 FOR UPDATE", [alps.Id], Ct));
else
Assert.True(await tx.Tags.RenameAsync(alps.Id, "Alps", Ct));
forward = db.Sequences.EditAsync(first.Id, new SequenceEdit { Tags = ["Alps", "sunset"] }, null, Ct);
await Task.WhenAny(forward, Task.Delay(300, Ct));
// The other writer lists the tags the other way round (a PATCH sends them in any order).
backward = db.Sequences.EditAsync(second.Id, new SequenceEdit { Tags = ["SUNSET", "alps"] }, null, Ct);
await Task.WhenAny(backward, Task.Delay(300, Ct));
Assert.False(forward.IsCompleted || backward.IsCompleted, "both writers wait for the tag");
if (Dialect == Dialect.Postgres)
{
// A writer whose tags are already the stored ones takes no tag at all.
var unchanged = db.Sequences.EditAsync(tagged.Id, new SequenceEdit { Tags = ["sunset", "ALPS"], Rating = 2 }, null, Ct);
Assert.Equal(unchanged, await Task.WhenAny(unchanged, Task.Delay(TimeSpan.FromSeconds(20), Ct)));
Assert.Equal(SequenceEditOutcome.Updated, (await unchanged).Outcome);
}
await tx.CommitAsync(Ct);
}
// Both take the tags in one order: neither is aborted for a deadlock.
Assert.Equal((SequenceEditOutcome.Updated, SequenceEditOutcome.Updated), ((await forward).Outcome, (await backward).Outcome));
foreach (var sequence in new[] { tagged, first, second })
Assert.SequenceEqual(["Alps", "sunset"], (await db.Sequences.GetAsync(sequence.Id, Ct))!.Tags);
Assert.Count(2, await db.Tags.ListAsync(Ct));
}
}
public sealed class SqliteSequenceEditTests(TestContext context) : SequenceEditTests(context)
{
protected override Backend Backend => Backend.SqliteMemory;
}
[RequiresEnvironment(PgTestServer.Variable)]
public sealed class PostgresSequenceEditTests(TestContext context) : SequenceEditTests(context)
{
protected override Backend Backend => Backend.Postgres;
}
/// Project writes of the engine (advice, sync) carry the project's hero frame to the index, so the Library shows it.
public sealed class ProjectStoreHeroTests(TestContext context)
{
[Test]
public async Task AdviceThatPicksAHeroReachesTheIndex()
{
await using var fixture = await ProcessingFixture.CreateAsync(context);
var sequence = await fixture.AddAsync(SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 64, Height = 48, FrameCount = 6 }));
var frames = await fixture.Db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: fixture.Ct);
var store = new ProjectStore(fixture.Db, new SequenceWriter(new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) }));
Assert.True(await store.UpdateAsync(fixture.Archive.Paths, sequence, p => p with { HeroFrame = 4 }, fixture.Ct));
Assert.Equal(frames[4].Id, (await fixture.Db.Sequences.GetAsync(sequence.Id, fixture.Ct))!.HeroFrameId);
Assert.True(await store.UpdateAsync(fixture.Archive.Paths, sequence, p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.5 } }, fixture.Ct));
Assert.Equal(frames[4].Id, (await fixture.Db.Sequences.GetAsync(sequence.Id, fixture.Ct))!.HeroFrameId, "other changes keep the hero");
Assert.True(await store.UpdateAsync(fixture.Archive.Paths, sequence, p => p with { HeroFrame = null }, fixture.Ct));
Assert.Null((await fixture.Db.Sequences.GetAsync(sequence.Id, fixture.Ct))!.HeroFrameId);
Assert.True(await store.UpdateAsync(fixture.Archive.Paths, sequence, p => p with { HeroFrame = 99 }, fixture.Ct));
Assert.Null((await fixture.Db.Sequences.GetAsync(sequence.Id, fixture.Ct))!.HeroFrameId, "an index past the last frame shows the first");
}
}