diff --git a/src/GameCult.Mesh/CultMeshClient.cs b/src/GameCult.Mesh/CultMeshClient.cs index 9b87ddd4..e1252e0c 100644 --- a/src/GameCult.Mesh/CultMeshClient.cs +++ b/src/GameCult.Mesh/CultMeshClient.cs @@ -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>> _documents = new(StringComparer.Ordinal); + private readonly ConcurrentBag _documentResources = new(); private bool _disposed; public CultMeshClient(CultMeshClientOptions options) @@ -81,10 +86,39 @@ namespace GameCult.Mesh return _sessions.ConnectAsync(endpointId, protocol, cancellationToken); } + /// Opens one live typed document by stable provider identity and record key. + public async Task> DocumentAsync( + 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>( + async () => await OpenDocumentAsync(endpointId.Trim(), recordKey.Trim()).ConfigureAwait(false), + LazyThreadSafetyMode.ExecutionAndPublication)); + try + { + var binding = (RemoteDocumentBinding)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 OpenDocumentAsync(string endpointId, string recordKey) + where TDocument : class + { + var session = await ConnectAsync(endpointId, CultMeshProtocols.Documents).ConfigureAwait(false); + var binding = new RemoteDocumentBinding(session, endpointId, recordKey); + try + { + await binding.StartAsync().ConfigureAwait(false); + _documentResources.Add(binding); + return binding; + } + catch + { + binding.Dispose(); + throw; + } + } + + private static async Task AwaitForCallerAsync(Task shared, CancellationToken cancellationToken) + { + if (!cancellationToken.CanBeCanceled) return await shared.ConfigureAwait(false); + var cancelled = new TaskCompletionSource(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 : 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( + _cache, + new CultRecordKey(recordKey), + CultMesh.Verse(endpointId, "cultmesh-client").Context, + routeHint: new CultMeshRouteHint(CultMeshLocalityKind.Network, endpointId)); + } + + public CultMeshDocumentHandle 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().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; diff --git a/src/GameCult.Mesh/docs/getting-started/02-connect-by-identity.md b/src/GameCult.Mesh/docs/getting-started/02-connect-by-identity.md index 31096bac..9301b49f 100644 --- a/src/GameCult.Mesh/docs/getting-started/02-connect-by-identity.md +++ b/src/GameCult.Mesh/docs/getting-started/02-connect-by-identity.md @@ -12,21 +12,28 @@ using var mesh = new CultMeshClient(new CultMeshClientOptions RendezvousEndpoints = new[] { "rudp://odin.gamecult.net:3076" } }); +var pilotSurface = await mesh.DocumentAsync( + "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}")); ``` diff --git a/tests/GameCult.Mesh.Tests/CultMeshClientTests.cs b/tests/GameCult.Mesh.Tests/CultMeshClientTests.cs index cd7068d3..2cef8645 100644 --- a/tests/GameCult.Mesh.Tests/CultMeshClientTests.cs +++ b/tests/GameCult.Mesh.Tests/CultMeshClientTests.cs @@ -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("aetheria", "surface:pilot"); + var second = await mesh.DocumentAsync("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("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> _handlers = new(); @@ -103,4 +145,76 @@ public sealed class CultMeshClientTests public void OnCultNet(Action callback) where T : ICultNetSchemaMessage { } public void Dispose() { } } + + private sealed class DocumentConnector : ICultMeshTransportConnector + { + public List Clients { get; } = new(); + public string ConnectorId => "document-test"; + public int SubscribeCount => Clients.Sum(client => client.SubscribeCount); + public bool CanConnect(CultMeshTransportCandidate candidate) => true; + public Task ConnectAsync( + CultMeshTransportCandidate candidate, + CultMeshProtocolId protocol, + CancellationToken cancellationToken = default) + { + var client = new DocumentClient("pilot surface " + (Clients.Count + 1)); + Clients.Add(client); + return Task.FromResult(client); + } + } + + private sealed class DocumentClient : ICultNetSchemaClient, ICultNetSchemaClientHealth + { + private readonly List> _snapshots = new(); + private readonly CultNetDocumentRegistry _documents; + private readonly string _text; + private readonly TaskCompletionSource _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 BackgroundFailure => _failure.Task; + public int SubscribeCount { get; private set; } + public void Connect(string host, int port) { } + public void SendCultNet(T message) where T : ICultNetSchemaMessage + { + if (message is not CultNetDatabaseSubscribeMessage request) return; + SubscribeCount++; + var put = _documents.CreateRawDocumentPutMessage( + "test-put", + new CultRecordHandle(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(Action 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 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; + } }