Replay live bindings across initial reconnect

This commit is contained in:
Meta Vens 2026-07-12 23:27:21 +01:00
commit 34bd95f5b9
3 changed files with 125 additions and 16 deletions

View file

@ -210,10 +210,10 @@ namespace GameCult.Mesh
{
var session = await ConnectAsync(endpointId, CultMeshProtocols.Documents).ConfigureAwait(false);
var binding = new RemoteDocumentBinding<TDocument>(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<TDocument>(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<bool> _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<TDocument>().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<bool> _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<TDocument>().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();
}
}

View file

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

View file

@ -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<ClientTestDocument>("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<ClientTestDocument>("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<ClientTestDocument>("aetheria", "surface:pilot");
await WaitUntilAsync(() => connector.Clients.Count == 1 && connector.Clients[0].SubscribeCount == 1);
mesh.Dispose();
Func<Task> awaitOpening = async () => await opening;
await awaitOpening.Should().ThrowAsync<ObjectDisposedException>();
}
private sealed class RendezvousClient : ICultNetSchemaClient
{
private readonly List<Action<CultMeshVerseCatalogResponseMessage>> _handlers = new();
@ -167,6 +231,7 @@ public sealed class CultMeshClientTests
private sealed class DocumentConnector : ICultMeshTransportConnector
{
public List<DocumentClient> 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<ICultNetSchemaClient>(client);
}
@ -187,9 +254,11 @@ public sealed class CultMeshClientTests
private readonly CultNetDocumentRegistry _documents;
private readonly string _text;
private readonly TaskCompletionSource<Exception> _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<ClientTestDocument>(new CultRecordKey("surface:pilot")),