diff --git a/src/GameCult.Mesh/CultMeshClient.cs b/src/GameCult.Mesh/CultMeshClient.cs index 64fd4c3b..08260e8a 100644 --- a/src/GameCult.Mesh/CultMeshClient.cs +++ b/src/GameCult.Mesh/CultMeshClient.cs @@ -210,10 +210,10 @@ namespace GameCult.Mesh { var session = await ConnectAsync(endpointId, CultMeshProtocols.Documents).ConfigureAwait(false); var binding = new RemoteDocumentBinding(session, endpointId, recordKey); + _documentResources.Add(binding); try { await binding.StartAsync().ConfigureAwait(false); - _documentResources.Add(binding); return binding; } catch @@ -228,10 +228,10 @@ namespace GameCult.Mesh { var session = await ConnectAsync(endpointId, CultMeshProtocols.Documents).ConfigureAwait(false); var binding = new RemoteCollectionBinding(session, endpointId); + _documentResources.Add(binding); try { await binding.StartAsync().ConfigureAwait(false); - _documentResources.Add(binding); return binding; } catch @@ -260,7 +260,7 @@ namespace GameCult.Mesh private readonly string _subscriptionId; private readonly CultCache _cache; private readonly CultNetDatabaseSubscriptionClient _subscription; - private readonly SemaphoreSlim _subscribeGate = new(1, 1); + private readonly TaskCompletionSource _ready = new(TaskCreationOptions.RunContinuationsAsynchronously); private IDisposable? _stateWatch; private bool _disposed; @@ -284,15 +284,15 @@ namespace GameCult.Mesh public async Task StartAsync() { - await SubscribeAsync().ConfigureAwait(false); _stateWatch = _session.WatchState() .Where(state => state.Status == CultMeshSessionStatus.Online) .Subscribe(state => { _ = SubscribeAsync(); }); + _ = SubscribeAsync(); + await _ready.Task.ConfigureAwait(false); } private async Task SubscribeAsync() { - await _subscribeGate.WaitAsync().ConfigureAwait(false); try { if (_disposed) return; @@ -301,10 +301,10 @@ namespace GameCult.Mesh recordKeys: new[] { _recordKey }, schemaIds: new[] { CultDocumentRegistry.Shared.GetRequired().SchemaId }) .ConfigureAwait(false); + _ready.TrySetResult(true); } - finally + catch (ObjectDisposedException) when (_disposed) { - _subscribeGate.Release(); } } @@ -314,8 +314,8 @@ namespace GameCult.Mesh _disposed = true; _stateWatch?.Dispose(); _subscription.Dispose(); + _ready.TrySetException(new ObjectDisposedException(GetType().FullName)); _cache.Dispose(); - _subscribeGate.Dispose(); } } @@ -325,7 +325,7 @@ namespace GameCult.Mesh private readonly string _subscriptionId; private readonly CultCache _cache; private readonly CultNetDatabaseSubscriptionClient _subscription; - private readonly SemaphoreSlim _subscribeGate = new(1, 1); + private readonly TaskCompletionSource _ready = new(TaskCreationOptions.RunContinuationsAsynchronously); private IDisposable? _stateWatch; private bool _disposed; @@ -346,15 +346,15 @@ namespace GameCult.Mesh public async Task StartAsync() { - await SubscribeAsync().ConfigureAwait(false); _stateWatch = _session.WatchState() .Where(state => state.Status == CultMeshSessionStatus.Online) .Subscribe(state => { _ = SubscribeAsync(); }); + _ = SubscribeAsync(); + await _ready.Task.ConfigureAwait(false); } private async Task SubscribeAsync() { - await _subscribeGate.WaitAsync().ConfigureAwait(false); try { if (_disposed) return; @@ -362,10 +362,10 @@ namespace GameCult.Mesh _subscriptionId, schemaIds: new[] { CultDocumentRegistry.Shared.GetRequired().SchemaId }) .ConfigureAwait(false); + _ready.TrySetResult(true); } - finally + catch (ObjectDisposedException) when (_disposed) { - _subscribeGate.Release(); } } @@ -375,8 +375,8 @@ namespace GameCult.Mesh _disposed = true; _stateWatch?.Dispose(); _subscription.Dispose(); + _ready.TrySetException(new ObjectDisposedException(GetType().FullName)); _cache.Dispose(); - _subscribeGate.Dispose(); } } diff --git a/src/GameCult.Mesh/docs/reliability-migration-plan.md b/src/GameCult.Mesh/docs/reliability-migration-plan.md index a1c990d6..83bc49df 100644 --- a/src/GameCult.Mesh/docs/reliability-migration-plan.md +++ b/src/GameCult.Mesh/docs/reliability-migration-plan.md @@ -410,6 +410,45 @@ transient outage, or hand-assemble snapshot options from physical topology. unsupported-path result. - The legacy request path cannot open a second competing session. +### Phase 2 Body Map + +**Owner:** `CultMeshSessionManager` owns physical path selection, replacement, +and reconnect. A live document or collection binding owns only its logical +subscription intent and readiness promise. + +**Inputs:** stable endpoint and protocol identity, discovery candidates, +connector results, session state transitions, typed schema and record filters, +and client disposal. + +**Outputs:** one reusable logical session, subscription replay on each new +online physical incarnation, cache-backed typed handles, and readiness after +the first successful snapshot from any incarnation. + +**Derived state:** physical client identity, attempt count, cached snapshots, +and online/reconnecting/offline projections. No individual request owns the +logical handle. + +**Forbidden writers:** bindings and schema clients cannot choose endpoints, +replace channels, reconnect, or declare session state. An abandoned initial +subscribe request cannot block a replacement request from satisfying logical +readiness. + +**Shared paths:** initial open and reconnect both use session-manager path +resolution. Document and collection activation both replay the same binding +intent when the logical session returns online. + +**Cut line:** the initial subscribe no longer runs before reconnect observation, +and a per-binding semaphore no longer lets an unanswered physical request hold +all later replay attempts. Bindings become client-owned resources before +waiting for readiness, so disposal terminates pending opens. + +**Verification layer:** Mesh tests lose the first document and collection +snapshot, fail the physical client, and prove the replacement snapshot opens +the same logical handle exactly once. A disposal test proves a pending open +cannot survive its owning client. The Aetheria/EveUnity witness proves provider +discovery, live SoA state, commands, receipts, and assets through the migrated +session path. + ## Phase 3: Authority as a Mandatory Boundary ### Cut first diff --git a/tests/GameCult.Mesh.Tests/CultMeshClientTests.cs b/tests/GameCult.Mesh.Tests/CultMeshClientTests.cs index 7507017e..d4f38dfc 100644 --- a/tests/GameCult.Mesh.Tests/CultMeshClientTests.cs +++ b/tests/GameCult.Mesh.Tests/CultMeshClientTests.cs @@ -90,6 +90,28 @@ public sealed class CultMeshClientTests connector.Clients[1].SubscribeCount.Should().Be(1); } + [Test] + public async Task Document_InitialReadinessCanBeSatisfiedByReconnectReplay() + { + var connector = new DocumentConnector { SuppressFirstSnapshot = true }; + using var mesh = new CultMeshClient(new CultMeshClientOptions + { + RendezvousEndpoints = new[] { "rudp://odin:3076" }, + Discovery = new CultMeshVerseDiscoveryClientOptions { CreateClient = () => new RendezvousClient() }, + Connectors = new[] { connector } + }); + + var opening = mesh.DocumentAsync("aetheria", "surface:pilot"); + await WaitUntilAsync(() => connector.Clients.Count == 1 && connector.Clients[0].SubscribeCount == 1); + connector.Clients[0].Fail(new InvalidOperationException("path lost before initial snapshot")); + + var document = await opening; + + (await document.LatestAsync()).Text.Should().Be("pilot surface 2"); + connector.Clients.Should().HaveCount(2); + connector.Clients[1].SubscribeCount.Should().Be(1); + } + [Test] public async Task Collection_ReplicatesAllDocumentsOfTypedSchema() { @@ -108,6 +130,48 @@ public sealed class CultMeshClientTests connector.SubscribeCount.Should().Be(1); } + [Test] + public async Task Collection_InitialReadinessCanBeSatisfiedByReconnectReplay() + { + var connector = new DocumentConnector { SuppressFirstSnapshot = true }; + using var mesh = new CultMeshClient(new CultMeshClientOptions + { + RendezvousEndpoints = new[] { "rudp://odin:3076" }, + Discovery = new CultMeshVerseDiscoveryClientOptions { CreateClient = () => new RendezvousClient() }, + Connectors = new[] { connector } + }); + + var opening = mesh.CollectionAsync("aetheria"); + await WaitUntilAsync(() => connector.Clients.Count == 1 && connector.Clients[0].SubscribeCount == 1); + connector.Clients[0].Fail(new InvalidOperationException("path lost before initial collection snapshot")); + + var collection = await opening; + + (await collection.LatestAsync()).Should().ContainSingle() + .Which.Text.Should().Be("pilot surface 2"); + connector.Clients.Should().HaveCount(2); + connector.Clients[1].SubscribeCount.Should().Be(1); + } + + [Test] + public async Task Dispose_TerminatesDocumentWaitingForInitialSnapshot() + { + var connector = new DocumentConnector { SuppressFirstSnapshot = true }; + var mesh = new CultMeshClient(new CultMeshClientOptions + { + RendezvousEndpoints = new[] { "rudp://odin:3076" }, + Discovery = new CultMeshVerseDiscoveryClientOptions { CreateClient = () => new RendezvousClient() }, + Connectors = new[] { connector } + }); + var opening = mesh.DocumentAsync("aetheria", "surface:pilot"); + await WaitUntilAsync(() => connector.Clients.Count == 1 && connector.Clients[0].SubscribeCount == 1); + + mesh.Dispose(); + + Func awaitOpening = async () => await opening; + await awaitOpening.Should().ThrowAsync(); + } + private sealed class RendezvousClient : ICultNetSchemaClient { private readonly List> _handlers = new(); @@ -167,6 +231,7 @@ public sealed class CultMeshClientTests private sealed class DocumentConnector : ICultMeshTransportConnector { public List Clients { get; } = new(); + public bool SuppressFirstSnapshot { get; set; } public string ConnectorId => "document-test"; public int SubscribeCount => Clients.Sum(client => client.SubscribeCount); public bool CanConnect(CultMeshTransportCandidate candidate) => true; @@ -175,7 +240,9 @@ public sealed class CultMeshClientTests CultMeshProtocolId protocol, CancellationToken cancellationToken = default) { - var client = new DocumentClient("pilot surface " + (Clients.Count + 1)); + var client = new DocumentClient( + "pilot surface " + (Clients.Count + 1), + respondToSubscribe: !SuppressFirstSnapshot || Clients.Count > 0); Clients.Add(client); return Task.FromResult(client); } @@ -187,9 +254,11 @@ public sealed class CultMeshClientTests private readonly CultNetDocumentRegistry _documents; private readonly string _text; private readonly TaskCompletionSource _failure = new(TaskCreationOptions.RunContinuationsAsynchronously); - public DocumentClient(string text) + private readonly bool _respondToSubscribe; + public DocumentClient(string text, bool respondToSubscribe = true) { _text = text; + _respondToSubscribe = respondToSubscribe; var cache = CultMesh.CreateCultCacheDocumentRegistry(typeof(ClientTestDocument)); _documents = CultMesh.CreateCultNetDocumentRegistry(new[] { typeof(ClientTestDocument) }, cache); } @@ -201,6 +270,7 @@ public sealed class CultMeshClientTests { if (message is not CultNetDatabaseSubscribeMessage request) return; SubscribeCount++; + if (!_respondToSubscribe) return; var put = _documents.CreateRawDocumentPutMessage( "test-put", new CultRecordHandle(new CultRecordKey("surface:pilot")),