diff --git a/src/Titano.App/Editor/RemoteSequenceSource.cs b/src/Titano.App/Editor/RemoteSequenceSource.cs index c581489b..97993e95 100644 --- a/src/Titano.App/Editor/RemoteSequenceSource.cs +++ b/src/Titano.App/Editor/RemoteSequenceSource.cs @@ -31,7 +31,8 @@ namespace Titano.App.Editor; /// local archive. Analyses and renders are server jobs; their state and progress come from the server's events. /// Project settings name frames by position, so the cached frames must be the server's: a load that finds other frames /// throws , and frames that change on the server while the sequence is open make -/// it (read-only, nothing saved or rendered). +/// it (read-only, nothing saved or rendered). Saves name the frames version the editor's frames +/// are at, so the server refuses one made against frames it no longer has even before its event arrives. /// public sealed class RemoteSequenceSource : ISequenceSource { @@ -150,19 +151,24 @@ public sealed class RemoteSequenceSource : ISequenceSource if (changedThere && ProjectMerge.Conflicts(basis, project, stored) is { Count: > 0 } conflicts) throw new ProjectConflictException(Loc.L("Editor.Error.SaveConflict"), stored, conflicts); var hero = merged.HeroFrame == stored.HeroFrame ? (Guid?)null : HeroFrameId(merged); + // The positions name the frames this editor holds: the server refuses them (409 frames_conflict) once its + // frames changed, also before its event says so. A server that predates the check ignores it. + var request = new UpdateSequenceRequest(null, null, null, null, merged.ToJson(), version, hero, Volatile.Read(ref _framesVersion)); try { - var updated = await Call(() => _api.UpdateSequenceAsync(Id, new UpdateSequenceRequest(null, null, null, null, merged.ToJson(), version, hero), - cancellationToken)); + var updated = await Call(() => _api.UpdateSequenceAsync(Id, request, cancellationToken)); Volatile.Write(ref _stored, new Stored(merged, updated.SettingsVersion)); return merged; } catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict) { - // Changed on the server since this editor read it: merge again on top of the server's settings. - if (attempt == SaveAttempts) throw new EditorException(Loc.L("Editor.Error.SaveConflict"), ex); + // Changed on the server since this editor read it, its settings or its frames: other frames make the + // editor outdated (its proxies are not the server's), otherwise the edit merges again on top of the + // server's settings, at the frames version they are at. var manifest = await Call(() => _api.GetManifestAsync(Id, cancellationToken)); if (!SameFrames(manifest)) throw Outdated(); + if (attempt == SaveAttempts) throw new EditorException(Loc.L("Editor.Error.SaveConflict"), ex); + Volatile.Write(ref _framesVersion, manifest.FramesVersion); Volatile.Write(ref _stored, new Stored(Parse(manifest.SettingsJson), manifest.SettingsVersion)); } } @@ -219,7 +225,7 @@ public sealed class RemoteSequenceSource : ISequenceSource /// /// Follows the server's events until the editor closes, reconnecting with a growing delay (job states lost meanwhile - /// are read back from the jobs). Nothing that fails on the way ends it. + /// are read back from the jobs, and the frames are compared again). Nothing that fails on the way ends it. /// private async Task ListenAsync(CancellationToken cancellationToken) { @@ -244,6 +250,8 @@ public sealed class RemoteSequenceSource : ISequenceSource var delay = Math.Min(MaxBackoff.Ticks, MinBackoff.Ticks << Math.Min(failures++, 10)); await Task.Delay(TimeSpan.FromTicks(delay), cancellationToken).ConfigureAwait(false); await RefreshTrackedAsync(cancellationToken).ConfigureAwait(false); + // A frames change announced while the socket was down is found now rather than at the next save. + if (Volatile.Read(ref _framesVersion) >= 0) await CheckFramesAsync(cancellationToken).ConfigureAwait(false); } catch (Exception ex) when (ex is not OutOfMemoryException) { diff --git a/tests/Titano.App.Tests/Editor/FakeRemoteSequenceApi.cs b/tests/Titano.App.Tests/Editor/FakeRemoteSequenceApi.cs index 495f7cfe..05a9c11c 100644 --- a/tests/Titano.App.Tests/Editor/FakeRemoteSequenceApi.cs +++ b/tests/Titano.App.Tests/Editor/FakeRemoteSequenceApi.cs @@ -1,4 +1,5 @@ using System.Collections.Concurrent; +using System.IO; using System.Net; using System.Runtime.CompilerServices; using System.Threading.Channels; @@ -17,7 +18,7 @@ namespace Titano.App.Tests.Editor; internal sealed class FakeRemoteSequenceApi(Sequence sequence, IReadOnlyList frames) : IRemoteSequenceApi { private readonly Lock _gate = new(); - private readonly Channel _events = Channel.CreateUnbounded(); + private Channel _events = Channel.CreateUnbounded(); /// The server's frames in order (another list when frames are added or removed on the server). public IReadOnlyList Frames { get; set; } = frames; @@ -59,7 +60,10 @@ internal sealed class FakeRemoteSequenceApi(Sequence sequence, IReadOnlyList _events.Writer.TryWrite(e); + public void Publish(ServerEvent e) => Volatile.Read(ref _events).Writer.TryWrite(e); + + /// The event socket drops: the stream open now fails, and the next one starts empty. + public void DropEvents() => Interlocked.Exchange(ref _events, Channel.CreateUnbounded()).Writer.TryComplete(new IOException("connection lost")); public Task GetSequenceAsync(Guid id, CancellationToken cancellationToken) { @@ -98,6 +102,11 @@ internal sealed class FakeRemoteSequenceApi(Sequence sequence, IReadOnlyList EventsAsync([EnumeratorCancellation] CancellationToken cancellationToken) { - while (await _events.Reader.WaitToReadAsync(cancellationToken)) + var events = Volatile.Read(ref _events).Reader; + while (await events.WaitToReadAsync(cancellationToken)) { - while (_events.Reader.TryRead(out var e)) yield return e; + while (events.TryRead(out var e)) yield return e; } } diff --git a/tests/Titano.App.Tests/Editor/RemoteSequenceSourceTests.cs b/tests/Titano.App.Tests/Editor/RemoteSequenceSourceTests.cs index 1ef3ec8a..9a6c9043 100644 --- a/tests/Titano.App.Tests/Editor/RemoteSequenceSourceTests.cs +++ b/tests/Titano.App.Tests/Editor/RemoteSequenceSourceTests.cs @@ -433,6 +433,51 @@ public sealed class RemoteSequenceSourceTests(TestContext context) } } + [Test] + public async Task SavesNameTheirFramesAndTheServerRefusesThemOnceItsFramesChanged() + { + var (source, api, remote) = Open(); + await using (source) + { + var content = await source.LoadAsync(context.Cancellation); + var stored = await source.SaveProjectAsync(content.Project with { ExcludedFrames = [1] }, content.Project, context.Cancellation); + + // A new frames version over the same frames: the save goes through at that version. + api.FramesVersion = 2; + stored = await source.SaveProjectAsync(stored with { HeroFrame = 2 }, stored, context.Cancellation); + Assert.SequenceEqual([1, 1, 2], api.Edits.Select(e => e.Request.ExpectedFramesVersion ?? -1)); + Assert.SequenceEqual([true, false, true], api.Edits.Select(e => e.Accepted)); + + // An earlier photo reaches the server (a scan, an upload) and its positions move with their frames, before + // any event reaches this editor: the server refuses the edit made on the old frames, which stays unsaved. + api.Frames = [Guid.CreateVersion7(), .. remote.Frames.Select(f => f.Id)]; + api.FramesVersion = 3; + api.SettingsJson = (ProjectSettings.FromJson(api.SettingsJson!) with { ExcludedFrames = [2], HeroFrame = 3 }).ToJson(); + var refused = await Assert.ThrowsAsync(() => + source.SaveProjectAsync(stored with { ExcludedFrames = [1, 4] }, stored, context.Cancellation)); + Assert.Equal(Loc.L("Editor.Error.FramesChanged"), refused.Message); + Assert.True(source.IsOutdated); + Assert.False(api.Edits[^1].Accepted); + Assert.SequenceEqual([2], ProjectSettings.FromJson(api.SettingsJson!).ExcludedFrames, "the server keeps the positions it moved"); + } + } + + [Test] + public async Task FramesChangedWhileTheEventsWereLostAreFoundOnReconnecting() + { + var (source, api, remote) = Open(); + await using (source) + { + await source.LoadAsync(context.Cancellation); + api.DropEvents(); + api.Frames = [.. remote.Frames.Skip(1).Select(f => f.Id)]; + api.FramesVersion = 2; + // The listener reconnects after its first delay (2 s) and compares the frames again. + await WaitAsync(() => source.IsOutdated); + Assert.True(source.IsReadOnly); + } + } + [Test] public async Task AConflictFoundOnOtherFramesIsNotMergedOntoThem() {