Bind live typed documents through CultMesh client

This commit is contained in:
Meta Vens 2026-07-12 21:03:55 +01:00
commit bb4afc9ba1
3 changed files with 258 additions and 7 deletions

View file

@ -1,9 +1,12 @@
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using GameCult.Caching;
using GameCult.Networking;
using R3;
namespace GameCult.Mesh
{
@ -31,6 +34,8 @@ namespace GameCult.Mesh
{
private readonly CultMeshDiscoveryService _discovery;
private readonly CultMeshSessionManager _sessions;
private readonly ConcurrentDictionary<string, Lazy<Task<object>>> _documents = new(StringComparer.Ordinal);
private readonly ConcurrentBag<IDisposable> _documentResources = new();
private bool _disposed;
public CultMeshClient(CultMeshClientOptions options)
@ -81,10 +86,39 @@ namespace GameCult.Mesh
return _sessions.ConnectAsync(endpointId, protocol, cancellationToken);
}
/// <summary>Opens one live typed document by stable provider identity and record key.</summary>
public async Task<CultMeshDocumentHandle<TDocument>> DocumentAsync<TDocument>(
string endpointId,
string recordKey,
CancellationToken cancellationToken = default)
where TDocument : class
{
ThrowIfDisposed();
if (string.IsNullOrWhiteSpace(endpointId)) throw new ArgumentException("Endpoint identity is required.", nameof(endpointId));
if (string.IsNullOrWhiteSpace(recordKey)) throw new ArgumentException("Record key is required.", nameof(recordKey));
var key = endpointId.Trim() + "\u001f" + typeof(TDocument).AssemblyQualifiedName + "\u001f" + recordKey.Trim();
var lazy = _documents.GetOrAdd(key, _ => new Lazy<Task<object>>(
async () => await OpenDocumentAsync<TDocument>(endpointId.Trim(), recordKey.Trim()).ConfigureAwait(false),
LazyThreadSafetyMode.ExecutionAndPublication));
try
{
var binding = (RemoteDocumentBinding<TDocument>)await AwaitForCallerAsync(lazy.Value, cancellationToken)
.ConfigureAwait(false);
return binding.Handle;
}
catch
{
_documents.TryRemove(key, out _);
throw;
}
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
foreach (var resource in _documentResources) resource.Dispose();
_documents.Clear();
_sessions.Dispose();
_discovery.Dispose();
}
@ -94,6 +128,102 @@ namespace GameCult.Mesh
if (_disposed) throw new ObjectDisposedException(nameof(CultMeshClient));
}
private async Task<object> OpenDocumentAsync<TDocument>(string endpointId, string recordKey)
where TDocument : class
{
var session = await ConnectAsync(endpointId, CultMeshProtocols.Documents).ConfigureAwait(false);
var binding = new RemoteDocumentBinding<TDocument>(session, endpointId, recordKey);
try
{
await binding.StartAsync().ConfigureAwait(false);
_documentResources.Add(binding);
return binding;
}
catch
{
binding.Dispose();
throw;
}
}
private static async Task<T> AwaitForCallerAsync<T>(Task<T> shared, CancellationToken cancellationToken)
{
if (!cancellationToken.CanBeCanceled) return await shared.ConfigureAwait(false);
var cancelled = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
using (cancellationToken.Register(() => cancelled.TrySetResult(true)))
{
if (await Task.WhenAny(shared, cancelled.Task).ConfigureAwait(false) != shared)
throw new OperationCanceledException(cancellationToken);
}
return await shared.ConfigureAwait(false);
}
private sealed class RemoteDocumentBinding<TDocument> : IDisposable where TDocument : class
{
private readonly CultMeshSession _session;
private readonly string _recordKey;
private readonly string _subscriptionId;
private readonly CultCache _cache;
private readonly CultNetDatabaseSubscriptionClient _subscription;
private readonly SemaphoreSlim _subscribeGate = new(1, 1);
private IDisposable? _stateWatch;
private bool _disposed;
public RemoteDocumentBinding(CultMeshSession session, string endpointId, string recordKey)
{
_session = session;
_recordKey = recordKey;
_subscriptionId = "cultmesh-document:" + endpointId + ":" + recordKey;
var cacheRegistry = CultMesh.CreateCultCacheDocumentRegistry(typeof(TDocument));
var networkRegistry = CultMesh.CreateCultNetDocumentRegistry(new[] { typeof(TDocument) }, cacheRegistry);
_cache = new CultCache(cacheRegistry);
_subscription = new CultNetDatabaseSubscriptionClient(session.OpenSchemaClient(), _cache, networkRegistry);
Handle = CultMesh.Document<TDocument>(
_cache,
new CultRecordKey(recordKey),
CultMesh.Verse(endpointId, "cultmesh-client").Context,
routeHint: new CultMeshRouteHint(CultMeshLocalityKind.Network, endpointId));
}
public CultMeshDocumentHandle<TDocument> Handle { get; }
public async Task StartAsync()
{
await SubscribeAsync().ConfigureAwait(false);
_stateWatch = _session.WatchState()
.Where(state => state.Status == CultMeshSessionStatus.Online)
.Subscribe(state => { _ = SubscribeAsync(); });
}
private async Task SubscribeAsync()
{
await _subscribeGate.WaitAsync().ConfigureAwait(false);
try
{
if (_disposed) return;
await _subscription.SubscribeAsync(
_subscriptionId,
recordKeys: new[] { _recordKey },
schemaIds: new[] { CultDocumentRegistry.Shared.GetRequired<TDocument>().SchemaId })
.ConfigureAwait(false);
}
finally
{
_subscribeGate.Release();
}
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_stateWatch?.Dispose();
_subscription.Dispose();
_cache.Dispose();
_subscribeGate.Dispose();
}
}
private sealed class RendezvousLookupSource : ICultMeshLookupSource
{
private readonly string _endpoint;

View file

@ -12,21 +12,28 @@ using var mesh = new CultMeshClient(new CultMeshClientOptions
RendezvousEndpoints = new[] { "rudp://odin.gamecult.net:3076" }
});
var pilotSurface = await mesh.DocumentAsync<EveSurfaceDocument>(
"aetheria.daemon",
"eve:surface:aetheria.pilot",
cancellationToken);
using var surfaceWatch = pilotSurface.Watch().Subscribe(Render);
```
Keep `mesh` for the application lifetime. The document handle is stable: when
Odin advertises a new physical route after a partition, CultMesh migrates the
session, restores the server-side subscription, refreshes the typed snapshot,
and continues the same watch.
Open a session directly only when implementing infrastructure that needs
protocol-level state or diagnostics:
```csharp
var session = await mesh.ConnectAsync(
"aetheria.daemon",
CultMeshProtocols.Documents,
cancellationToken);
using var client = session.OpenSchemaClient();
```
Keep `mesh` for the application lifetime. `session` is the logical connection:
when Odin advertises a new physical route after a partition, the same session
migrates and retains its typed handler registrations.
Watch connection state for presentation and diagnostics:
```csharp
using var stateWatch = session.WatchState().Subscribe(state =>
Console.WriteLine($"{state.Status}: {state.Path?.Endpoint}"));
```

View file

@ -1,9 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using GameCult.Caching;
using GameCult.Networking;
using MessagePack;
using NUnit.Framework;
namespace GameCult.Mesh.Tests;
@ -48,6 +51,45 @@ public sealed class CultMeshClientTests
connector.ConnectCount.Should().Be(1);
}
[Test]
public async Task Document_ReplicatesTypedRecordBehindOneIntentDeclaration()
{
var connector = new DocumentConnector();
using var mesh = new CultMeshClient(new CultMeshClientOptions
{
RendezvousEndpoints = new[] { "rudp://odin:3076" },
Discovery = new CultMeshVerseDiscoveryClientOptions { CreateClient = () => new RendezvousClient() },
Connectors = new[] { connector }
});
var first = await mesh.DocumentAsync<ClientTestDocument>("aetheria", "surface:pilot");
var second = await mesh.DocumentAsync<ClientTestDocument>("aetheria", "surface:pilot");
first.Should().BeSameAs(second);
(await first.LatestAsync()).Text.Should().Be("pilot surface 1");
connector.SubscribeCount.Should().Be(1);
}
[Test]
public async Task Document_ReplaysSubscriptionAndRefreshesSameHandleAfterReconnect()
{
var connector = new DocumentConnector();
using var mesh = new CultMeshClient(new CultMeshClientOptions
{
RendezvousEndpoints = new[] { "rudp://odin:3076" },
Discovery = new CultMeshVerseDiscoveryClientOptions { CreateClient = () => new RendezvousClient() },
Connectors = new[] { connector }
});
var document = await mesh.DocumentAsync<ClientTestDocument>("aetheria", "surface:pilot");
connector.Clients[0].Fail(new InvalidOperationException("path lost"));
await WaitUntilAsync(() => connector.Clients.Count == 2 && connector.Clients[1].SubscribeCount == 1);
(await document.LatestAsync()).Text.Should().Be("pilot surface 2");
connector.Clients[0].SubscribeCount.Should().Be(1);
connector.Clients[1].SubscribeCount.Should().Be(1);
}
private sealed class RendezvousClient : ICultNetSchemaClient
{
private readonly List<Action<CultMeshVerseCatalogResponseMessage>> _handlers = new();
@ -103,4 +145,76 @@ public sealed class CultMeshClientTests
public void OnCultNet<T>(Action<T> callback) where T : ICultNetSchemaMessage { }
public void Dispose() { }
}
private sealed class DocumentConnector : ICultMeshTransportConnector
{
public List<DocumentClient> Clients { get; } = new();
public string ConnectorId => "document-test";
public int SubscribeCount => Clients.Sum(client => client.SubscribeCount);
public bool CanConnect(CultMeshTransportCandidate candidate) => true;
public Task<ICultNetSchemaClient> ConnectAsync(
CultMeshTransportCandidate candidate,
CultMeshProtocolId protocol,
CancellationToken cancellationToken = default)
{
var client = new DocumentClient("pilot surface " + (Clients.Count + 1));
Clients.Add(client);
return Task.FromResult<ICultNetSchemaClient>(client);
}
}
private sealed class DocumentClient : ICultNetSchemaClient, ICultNetSchemaClientHealth
{
private readonly List<Action<CultNetSnapshotResponseRawMessage>> _snapshots = new();
private readonly CultNetDocumentRegistry _documents;
private readonly string _text;
private readonly TaskCompletionSource<Exception> _failure = new(TaskCreationOptions.RunContinuationsAsynchronously);
public DocumentClient(string text)
{
_text = text;
var cache = CultMesh.CreateCultCacheDocumentRegistry(typeof(ClientTestDocument));
_documents = CultMesh.CreateCultNetDocumentRegistry(new[] { typeof(ClientTestDocument) }, cache);
}
public bool Connected => true;
public Task<Exception> BackgroundFailure => _failure.Task;
public int SubscribeCount { get; private set; }
public void Connect(string host, int port) { }
public void SendCultNet<T>(T message) where T : ICultNetSchemaMessage
{
if (message is not CultNetDatabaseSubscribeMessage request) return;
SubscribeCount++;
var put = _documents.CreateRawDocumentPutMessage(
"test-put",
new CultRecordHandle<ClientTestDocument>(new CultRecordKey("surface:pilot")),
new ClientTestDocument { Id = "surface:pilot", Text = _text });
var response = new CultNetSnapshotResponseRawMessage
{
MessageId = request.MessageId,
Documents = new[] { put.Document }
};
foreach (var handler in _snapshots.ToArray()) handler(response);
}
public void OnCultNet<T>(Action<T> callback) where T : ICultNetSchemaMessage
{
if (typeof(T) == typeof(CultNetSnapshotResponseRawMessage))
_snapshots.Add(response => callback((T)(object)response));
}
public void Dispose() { }
public void Fail(Exception error) => _failure.TrySetResult(error);
}
private static async Task WaitUntilAsync(Func<bool> condition)
{
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(2);
while (!condition() && DateTime.UtcNow < deadline) await Task.Delay(1);
condition().Should().BeTrue();
}
[CultDocument("tests.cultmesh_client_document", "tests.cultmesh_client_document.v1")]
[MessagePackObject]
public sealed class ClientTestDocument
{
[Key(0), CultName] public string Id { get; set; } = string.Empty;
[Key(1)] public string Text { get; set; } = string.Empty;
}
}