diff --git a/src/GameCult.Mesh/CultMeshClient.cs b/src/GameCult.Mesh/CultMeshClient.cs index e1252e0c..804dc0d0 100644 --- a/src/GameCult.Mesh/CultMeshClient.cs +++ b/src/GameCult.Mesh/CultMeshClient.cs @@ -35,6 +35,7 @@ namespace GameCult.Mesh private readonly CultMeshDiscoveryService _discovery; private readonly CultMeshSessionManager _sessions; private readonly ConcurrentDictionary>> _documents = new(StringComparer.Ordinal); + private readonly ConcurrentDictionary>> _collections = new(StringComparer.Ordinal); private readonly ConcurrentBag _documentResources = new(); private bool _disposed; @@ -113,12 +114,39 @@ namespace GameCult.Mesh } } + /// Opens a live collection of one typed schema by stable provider identity. + public async Task> CollectionAsync( + string endpointId, + CancellationToken cancellationToken = default) + where TDocument : class + { + ThrowIfDisposed(); + if (string.IsNullOrWhiteSpace(endpointId)) throw new ArgumentException("Endpoint identity is required.", nameof(endpointId)); + var identity = endpointId.Trim(); + var key = identity + "\u001f" + typeof(TDocument).AssemblyQualifiedName; + var lazy = _collections.GetOrAdd(key, _ => new Lazy>( + async () => await OpenCollectionAsync(identity).ConfigureAwait(false), + LazyThreadSafetyMode.ExecutionAndPublication)); + try + { + var binding = (RemoteCollectionBinding)await AwaitForCallerAsync(lazy.Value, cancellationToken) + .ConfigureAwait(false); + return binding.Handle; + } + catch + { + _collections.TryRemove(key, out _); + throw; + } + } + public void Dispose() { if (_disposed) return; _disposed = true; foreach (var resource in _documentResources) resource.Dispose(); _documents.Clear(); + _collections.Clear(); _sessions.Dispose(); _discovery.Dispose(); } @@ -146,6 +174,24 @@ namespace GameCult.Mesh } } + private async Task OpenCollectionAsync(string endpointId) + where TDocument : class + { + var session = await ConnectAsync(endpointId, CultMeshProtocols.Documents).ConfigureAwait(false); + var binding = new RemoteCollectionBinding(session, endpointId); + 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); @@ -224,6 +270,67 @@ namespace GameCult.Mesh } } + private sealed class RemoteCollectionBinding : IDisposable where TDocument : class + { + private readonly CultMeshSession _session; + 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 RemoteCollectionBinding(CultMeshSession session, string endpointId) + { + _session = session; + _subscriptionId = "cultmesh-collection:" + endpointId + ":" + typeof(TDocument).FullName; + 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.Collection( + _cache, + routeHint: new CultMeshRouteHint(CultMeshLocalityKind.Network, endpointId)); + } + + public CultMeshCollectionHandle 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, + 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/tests/GameCult.Mesh.Tests/CultMeshClientTests.cs b/tests/GameCult.Mesh.Tests/CultMeshClientTests.cs index 2cef8645..7507017e 100644 --- a/tests/GameCult.Mesh.Tests/CultMeshClientTests.cs +++ b/tests/GameCult.Mesh.Tests/CultMeshClientTests.cs @@ -90,6 +90,24 @@ public sealed class CultMeshClientTests connector.Clients[1].SubscribeCount.Should().Be(1); } + [Test] + public async Task Collection_ReplicatesAllDocumentsOfTypedSchema() + { + 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 collection = await mesh.CollectionAsync("aetheria"); + + (await collection.LatestAsync()).Should().ContainSingle() + .Which.Text.Should().Be("pilot surface 1"); + connector.SubscribeCount.Should().Be(1); + } + private sealed class RendezvousClient : ICultNetSchemaClient { private readonly List> _handlers = new();