From 6403744ada350be0f5fde1b4d82e4176603db52b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 12 Jul 2026 20:56:45 +0100 Subject: [PATCH] Add identity-first CultMesh application client --- src/GameCult.Mesh/CultMeshClient.cs | 139 ++++++++++++++++++ .../getting-started/02-connect-by-identity.md | 30 ++-- .../CultMeshClientTests.cs | 106 +++++++++++++ 3 files changed, 255 insertions(+), 20 deletions(-) create mode 100644 src/GameCult.Mesh/CultMeshClient.cs create mode 100644 tests/GameCult.Mesh.Tests/CultMeshClientTests.cs diff --git a/src/GameCult.Mesh/CultMeshClient.cs b/src/GameCult.Mesh/CultMeshClient.cs new file mode 100644 index 00000000..9b87ddd4 --- /dev/null +++ b/src/GameCult.Mesh/CultMeshClient.cs @@ -0,0 +1,139 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using GameCult.Networking; + +namespace GameCult.Mesh +{ + /// Configures one application-lifetime CultMesh client. + public sealed class CultMeshClientOptions + { + /// Gets or sets the rendezvous endpoints used to bootstrap stable identities. + public IReadOnlyList RendezvousEndpoints { get; set; } = Array.Empty(); + + /// Gets or sets Verse discovery transport and persistence options. + public CultMeshVerseDiscoveryClientOptions Discovery { get; set; } = new(); + + /// Gets or sets session path and diagnostic policy. + public CultMeshSessionManagerOptions Sessions { get; set; } = new(); + + /// Gets or sets optional transport connectors. The CultNet schema connector is used by default. + public IReadOnlyList? Connectors { get; set; } + } + + /// + /// Owns discovery and reusable sessions for one application lifetime. + /// Applications address stable identities; CultMesh owns physical routes and reconnection. + /// + public sealed class CultMeshClient : IDisposable + { + private readonly CultMeshDiscoveryService _discovery; + private readonly CultMeshSessionManager _sessions; + private bool _disposed; + + public CultMeshClient(CultMeshClientOptions options) + { + if (options == null) throw new ArgumentNullException(nameof(options)); + var endpoints = options.RendezvousEndpoints + .Where(endpoint => !string.IsNullOrWhiteSpace(endpoint)) + .Distinct(StringComparer.Ordinal) + .ToArray(); + if (endpoints.Length == 0) + throw new ArgumentException("At least one CultMesh rendezvous endpoint is required.", nameof(options)); + + var discoveryClient = new CultMeshVerseDiscoveryClient(options.Discovery); + _discovery = new CultMeshDiscoveryService( + endpoints.Select(endpoint => new RendezvousLookupSource(endpoint, discoveryClient, options.Discovery)), + new CultMeshDiscoveryServiceOptions + { + Clock = options.Discovery.Clock, + Diagnostics = options.Discovery.Diagnostics, + Store = options.Discovery.DiscoveryStore + }); + _sessions = new CultMeshSessionManager( + _discovery, + options.Connectors ?? new ICultMeshTransportConnector[] + { + new CultMeshSchemaTransportConnector(clock: options.Sessions.Clock) + }, + options.Sessions); + } + + /// Connects to a stable endpoint identity using one application protocol. + public Task ConnectAsync( + string endpointId, + CultMeshProtocolId protocol, + CancellationToken cancellationToken = default) + { + ThrowIfDisposed(); + return _sessions.ConnectAsync(CultMeshEndpointId.Parse(endpointId), protocol, cancellationToken); + } + + /// Connects to a stable endpoint identity using one application protocol. + public Task ConnectAsync( + CultMeshEndpointId endpointId, + CultMeshProtocolId protocol, + CancellationToken cancellationToken = default) + { + ThrowIfDisposed(); + return _sessions.ConnectAsync(endpointId, protocol, cancellationToken); + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + _sessions.Dispose(); + _discovery.Dispose(); + } + + private void ThrowIfDisposed() + { + if (_disposed) throw new ObjectDisposedException(nameof(CultMeshClient)); + } + + private sealed class RendezvousLookupSource : ICultMeshLookupSource + { + private readonly string _endpoint; + private readonly CultMeshVerseDiscoveryClient _client; + private readonly CultMeshVerseDiscoveryClientOptions _options; + + public RendezvousLookupSource( + string endpoint, + CultMeshVerseDiscoveryClient client, + CultMeshVerseDiscoveryClientOptions options) + { + _endpoint = endpoint; + _client = client; + _options = options; + } + + public string SourceId => "rendezvous:" + _endpoint; + + public async Task> LookupAsync( + CultMeshDiscoveryQuery query, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + var response = await _client.FetchAsync( + _endpoint, + new CultMeshVerseCatalogRequestMessage + { + VerseIds = query.VerseIds.Count == 0 ? null : query.VerseIds.ToArray(), + TransportVersion = "cultmesh.v0" + }).ConfigureAwait(false); + cancellationToken.ThrowIfCancellationRequested(); + var observedAt = _options.Clock.UtcNow; + return response.Verses.Select(message => new CultMeshDiscoveryObservation( + message.ToVerseDescriptor(), + SourceId, + observedAt, + observedAt + _options.ObservationTtl, + CultMeshDiscoveryTrust.Unsigned, + response.SchemaVersion)).ToArray(); + } + } + } +} 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 8dec4c63..31096bac 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 @@ -7,31 +7,22 @@ path rotation, and transport failure state. ```csharp using GameCult.Mesh; -using var discovery = new CultMeshDiscoveryService(new ICultMeshLookupSource[] +using var mesh = new CultMeshClient(new CultMeshClientOptions { - odinLookupSource + RendezvousEndpoints = new[] { "rudp://odin.gamecult.net:3076" } }); -using var sessions = new CultMeshSessionManager( - discovery, - new ICultMeshTransportConnector[] - { - new CultMeshSchemaTransportConnector() - }); - -var provider = CultMeshEndpointId.Parse("aetheria.daemon"); -var session = await sessions.ConnectAsync( - provider, +var session = await mesh.ConnectAsync( + "aetheria.daemon", CultMeshProtocols.Documents, cancellationToken); using var client = session.OpenSchemaClient(); ``` -Keep `discovery` and `sessions` for the application lifetime. Do not construct -them per request. `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. +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: @@ -49,9 +40,8 @@ Verification: dotnet test tests/GameCult.Mesh.Tests/GameCult.Mesh.Tests.csproj --filter FullyQualifiedName~CultMeshSessionManagerTests ``` -The explicit organ construction above is the current low-level API. The -identity-first `mesh.ConnectAsync(...)` facade remains planned work; this guide -will collapse to that form when it lands. +Advanced hosts may inject lookup sources, connectors, clocks, persistence, and +diagnostics through the lower-level discovery and session APIs. Application +features should not need them. Next: [publish one Eve surface to multiple runtimes](03-publish-an-eve-surface.md). - diff --git a/tests/GameCult.Mesh.Tests/CultMeshClientTests.cs b/tests/GameCult.Mesh.Tests/CultMeshClientTests.cs new file mode 100644 index 00000000..cd7068d3 --- /dev/null +++ b/tests/GameCult.Mesh.Tests/CultMeshClientTests.cs @@ -0,0 +1,106 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using FluentAssertions; +using GameCult.Networking; +using NUnit.Framework; + +namespace GameCult.Mesh.Tests; + +public sealed class CultMeshClientTests +{ + [Test] + public void Construction_RequiresOneRendezvousEndpoint() + { + var create = () => new CultMeshClient(new CultMeshClientOptions()); + + create.Should().Throw() + .WithMessage("*rendezvous endpoint*"); + } + + [Test] + public async Task Connect_ResolvesStableIdentityAndReusesOneSession() + { + var discoveryClients = 0; + var connector = new RecordingConnector(); + using var mesh = new CultMeshClient(new CultMeshClientOptions + { + RendezvousEndpoints = new[] { "rudp://odin:3076" }, + Discovery = new CultMeshVerseDiscoveryClientOptions + { + CreateClient = () => + { + Interlocked.Increment(ref discoveryClients); + return new RendezvousClient(); + } + }, + Connectors = new[] { connector } + }); + + var first = await mesh.ConnectAsync("aetheria", CultMeshProtocols.Documents); + var second = await mesh.ConnectAsync("aetheria", CultMeshProtocols.Documents); + + first.Should().BeSameAs(second); + first.EndpointId.Value.Should().Be("aetheria"); + first.State.Path!.Endpoint.Should().Be("rudp://aetheria:3081"); + discoveryClients.Should().Be(1); + connector.ConnectCount.Should().Be(1); + } + + private sealed class RendezvousClient : ICultNetSchemaClient + { + private readonly List> _handlers = new(); + public bool Connected => true; + public void Connect(string host, int port) { } + public void SendCultNet(T message) where T : ICultNetSchemaMessage + { + var request = (CultMeshVerseCatalogRequestMessage)(object)message; + var response = new CultMeshVerseCatalogResponseMessage + { + MessageId = request.MessageId, + Verses = new[] + { + new CultMeshVerseDescriptor( + "aetheria", + "Aetheria", + CultMeshVerseAuthorityModel.OperatorCluster, + new CultMeshVerseCompatibility("cultmesh.v0", "rules"), + new[] { "rudp://aetheria:3081" }).ToMessage() + } + }; + foreach (var handler in _handlers.ToArray()) handler(response); + } + public void OnCultNet(Action callback) where T : ICultNetSchemaMessage + { + if (typeof(T) == typeof(CultMeshVerseCatalogResponseMessage)) + _handlers.Add(response => callback((T)(object)response)); + } + public void Dispose() { } + } + + private sealed class RecordingConnector : ICultMeshTransportConnector + { + private int _connectCount; + public string ConnectorId => "test"; + public int ConnectCount => Volatile.Read(ref _connectCount); + public bool CanConnect(CultMeshTransportCandidate candidate) => true; + public Task ConnectAsync( + CultMeshTransportCandidate candidate, + CultMeshProtocolId protocol, + CancellationToken cancellationToken = default) + { + Interlocked.Increment(ref _connectCount); + return Task.FromResult(new ConnectedClient()); + } + } + + private sealed class ConnectedClient : ICultNetSchemaClient + { + public bool Connected => true; + public void Connect(string host, int port) { } + public void SendCultNet(T message) where T : ICultNetSchemaMessage { } + public void OnCultNet(Action callback) where T : ICultNetSchemaMessage { } + public void Dispose() { } + } +}