Add identity-first CultMesh application client
This commit is contained in:
parent
bc8270ecc3
commit
6403744ada
3 changed files with 255 additions and 20 deletions
139
src/GameCult.Mesh/CultMeshClient.cs
Normal file
139
src/GameCult.Mesh/CultMeshClient.cs
Normal file
|
|
@ -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
|
||||
{
|
||||
/// <summary>Configures one application-lifetime CultMesh client.</summary>
|
||||
public sealed class CultMeshClientOptions
|
||||
{
|
||||
/// <summary>Gets or sets the rendezvous endpoints used to bootstrap stable identities.</summary>
|
||||
public IReadOnlyList<string> RendezvousEndpoints { get; set; } = Array.Empty<string>();
|
||||
|
||||
/// <summary>Gets or sets Verse discovery transport and persistence options.</summary>
|
||||
public CultMeshVerseDiscoveryClientOptions Discovery { get; set; } = new();
|
||||
|
||||
/// <summary>Gets or sets session path and diagnostic policy.</summary>
|
||||
public CultMeshSessionManagerOptions Sessions { get; set; } = new();
|
||||
|
||||
/// <summary>Gets or sets optional transport connectors. The CultNet schema connector is used by default.</summary>
|
||||
public IReadOnlyList<ICultMeshTransportConnector>? Connectors { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Owns discovery and reusable sessions for one application lifetime.
|
||||
/// Applications address stable identities; CultMesh owns physical routes and reconnection.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Connects to a stable endpoint identity using one application protocol.</summary>
|
||||
public Task<CultMeshSession> ConnectAsync(
|
||||
string endpointId,
|
||||
CultMeshProtocolId protocol,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
return _sessions.ConnectAsync(CultMeshEndpointId.Parse(endpointId), protocol, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Connects to a stable endpoint identity using one application protocol.</summary>
|
||||
public Task<CultMeshSession> 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<IReadOnlyList<CultMeshDiscoveryObservation>> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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).
|
||||
|
||||
|
|
|
|||
106
tests/GameCult.Mesh.Tests/CultMeshClientTests.cs
Normal file
106
tests/GameCult.Mesh.Tests/CultMeshClientTests.cs
Normal file
|
|
@ -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<ArgumentException>()
|
||||
.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<Action<CultMeshVerseCatalogResponseMessage>> _handlers = new();
|
||||
public bool Connected => true;
|
||||
public void Connect(string host, int port) { }
|
||||
public void SendCultNet<T>(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<T>(Action<T> 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<ICultNetSchemaClient> ConnectAsync(
|
||||
CultMeshTransportCandidate candidate,
|
||||
CultMeshProtocolId protocol,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
Interlocked.Increment(ref _connectCount);
|
||||
return Task.FromResult<ICultNetSchemaClient>(new ConnectedClient());
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class ConnectedClient : ICultNetSchemaClient
|
||||
{
|
||||
public bool Connected => true;
|
||||
public void Connect(string host, int port) { }
|
||||
public void SendCultNet<T>(T message) where T : ICultNetSchemaMessage { }
|
||||
public void OnCultNet<T>(Action<T> callback) where T : ICultNetSchemaMessage { }
|
||||
public void Dispose() { }
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue