From 469b9729d2d39030bd0a5c4c0275ef936e4eff51 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 12 Jul 2026 20:24:25 +0100 Subject: [PATCH] Introduce CultMesh session ownership --- src/GameCult.Mesh/CultMeshSessions.cs | 341 ++++++++++++++++++ .../CultMeshSessionManagerTests.cs | 197 ++++++++++ 2 files changed, 538 insertions(+) create mode 100644 src/GameCult.Mesh/CultMeshSessions.cs create mode 100644 tests/GameCult.Mesh.Tests/CultMeshSessionManagerTests.cs diff --git a/src/GameCult.Mesh/CultMeshSessions.cs b/src/GameCult.Mesh/CultMeshSessions.cs new file mode 100644 index 00000000..51e32db5 --- /dev/null +++ b/src/GameCult.Mesh/CultMeshSessions.cs @@ -0,0 +1,341 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using GameCult.Networking; +using R3; + +namespace GameCult.Mesh +{ + public sealed class CultMeshEndpointId : IEquatable + { + private CultMeshEndpointId(string value) { Value = value; } + public string Value { get; } + public static CultMeshEndpointId Parse(string value) => new CultMeshEndpointId( + string.IsNullOrWhiteSpace(value) ? throw new FormatException("CultMesh endpoint identity must be non-empty.") : value.Trim()); + public bool Equals(CultMeshEndpointId? other) => other != null && string.Equals(Value, other.Value, StringComparison.Ordinal); + public override bool Equals(object? obj) => Equals(obj as CultMeshEndpointId); + public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(Value); + public override string ToString() => Value; + } + + public sealed class CultMeshProtocolId : IEquatable + { + public CultMeshProtocolId(string value) { Value = string.IsNullOrWhiteSpace(value) ? throw new ArgumentException("Protocol identity is required.", nameof(value)) : value; } + public string Value { get; } + public bool Equals(CultMeshProtocolId? other) => other != null && string.Equals(Value, other.Value, StringComparison.Ordinal); + public override bool Equals(object? obj) => Equals(obj as CultMeshProtocolId); + public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(Value); + public override string ToString() => Value; + } + + public static class CultMeshProtocols + { + public static CultMeshProtocolId Documents { get; } = new CultMeshProtocolId("cultmesh.documents.v1"); + public static CultMeshProtocolId Discovery { get; } = new CultMeshProtocolId("cultmesh.discovery.v1"); + public static CultMeshProtocolId PeerExchange { get; } = new CultMeshProtocolId("cultmesh.peer_exchange.v1"); + public static CultMeshProtocolId Subscriptions { get; } = new CultMeshProtocolId("cultmesh.subscriptions.v1"); + } + + public enum CultMeshTransportPathKind { Direct, Relay, Tunnel } + + public sealed class CultMeshTransportCandidate + { + public CultMeshTransportCandidate(string endpoint, CultMeshTransportPathKind pathKind = CultMeshTransportPathKind.Direct, int priority = 0) + { + Endpoint = string.IsNullOrWhiteSpace(endpoint) ? throw new ArgumentException("Physical endpoint is required.", nameof(endpoint)) : endpoint; + PathKind = pathKind; + Priority = priority; + } + public string Endpoint { get; } + public CultMeshTransportPathKind PathKind { get; } + public int Priority { get; } + } + + public enum CultMeshSessionStatus { Connecting, Online, Degraded, Reconnecting, Offline } + public enum CultMeshSessionFailureReason { Resolution, Authentication, Transport, Protocol, Timeout, Cancellation, Authority, UnsupportedPath } + + public sealed class CultMeshSessionFailure + { + public CultMeshSessionFailure(CultMeshSessionFailureReason reason, string message, string endpoint = "") + { + Reason = reason; + Message = message ?? ""; + Endpoint = endpoint ?? ""; + } + public CultMeshSessionFailureReason Reason { get; } + public string Message { get; } + public string Endpoint { get; } + } + + public sealed class CultMeshSessionState + { + public CultMeshSessionState( + CultMeshSessionStatus status, + DateTimeOffset observedAtUtc, + CultMeshTransportCandidate? path = null, + CultMeshSessionFailure? failure = null) + { + Status = status; + ObservedAtUtc = observedAtUtc; + Path = path; + Failure = failure; + } + public CultMeshSessionStatus Status { get; } + public DateTimeOffset ObservedAtUtc { get; } + public CultMeshTransportCandidate? Path { get; } + public CultMeshSessionFailure? Failure { get; } + } + + public sealed class CultMeshSessionException : Exception + { + public CultMeshSessionException(CultMeshSessionFailure failure, Exception? inner = null) + : base(failure?.Message, inner) { Failure = failure ?? throw new ArgumentNullException(nameof(failure)); } + public CultMeshSessionFailure Failure { get; } + } + + public interface ICultMeshTransportConnector + { + string ConnectorId { get; } + bool CanConnect(CultMeshTransportCandidate candidate); + Task ConnectAsync( + CultMeshTransportCandidate candidate, + CultMeshProtocolId protocol, + CancellationToken cancellationToken = default); + } + + public sealed class CultMeshSchemaTransportConnector : ICultMeshTransportConnector + { + private readonly Func _createClient; + private readonly ICultMeshClock _clock; + private readonly TimeSpan _connectTimeout; + + public CultMeshSchemaTransportConnector( + Func? createClient = null, + ICultMeshClock? clock = null, + TimeSpan? connectTimeout = null) + { + _createClient = createClient ?? (endpoint => CultNetSchemaClients.CreateForEndpoint(endpoint)); + _clock = clock ?? CultMeshSystemClock.Instance; + _connectTimeout = connectTimeout ?? TimeSpan.FromSeconds(5); + } + + public string ConnectorId => "cultnet-schema"; + public bool CanConnect(CultMeshTransportCandidate candidate) => + Uri.TryCreate(candidate.Endpoint, UriKind.Absolute, out var uri) && + (string.Equals(uri.Scheme, "rudp", StringComparison.OrdinalIgnoreCase) || + string.Equals(uri.Scheme, "cultnet", StringComparison.OrdinalIgnoreCase)); + + public async Task ConnectAsync( + CultMeshTransportCandidate candidate, + CultMeshProtocolId protocol, + CancellationToken cancellationToken = default) + { + if (!CanConnect(candidate)) throw new NotSupportedException($"Unsupported CultNet endpoint '{candidate.Endpoint}'."); + var client = _createClient(candidate.Endpoint); + try + { + var (host, port) = CultNetSchemaWriteForwarder.ParseEndpoint(candidate.Endpoint); + client.Connect(host, port); + var deadline = _clock.UtcNow + _connectTimeout; + while (!client.Connected) + { + cancellationToken.ThrowIfCancellationRequested(); + if (_clock.UtcNow >= deadline) + throw new TimeoutException($"Timed out connecting to '{candidate.Endpoint}'."); + await _clock.DelayAsync(TimeSpan.FromMilliseconds(25), cancellationToken).ConfigureAwait(false); + } + return client; + } + catch + { + client.Dispose(); + throw; + } + } + } + + public sealed class CultMeshSession : IDisposable + { + private readonly Subject _states = new(); + private bool _disposed; + internal CultMeshSession(CultMeshEndpointId endpointId, CultMeshProtocolId protocol, ICultNetSchemaClient channel, CultMeshSessionState state) + { + EndpointId = endpointId; + Protocol = protocol; + Channel = channel; + State = state; + } + public CultMeshEndpointId EndpointId { get; } + public CultMeshProtocolId Protocol { get; } + public ICultNetSchemaClient Channel { get; } + public CultMeshSessionState State { get; private set; } + public Observable WatchState() => _states; + internal void Transition(CultMeshSessionState state) { State = state; _states.OnNext(state); } + public void Dispose() + { + if (_disposed) return; + _disposed = true; + Channel.Dispose(); + _states.Dispose(); + } + } + + public sealed class CultMeshSessionManagerOptions + { + public ICultMeshClock Clock { get; set; } = CultMeshSystemClock.Instance; + public ICultMeshDiagnosticSink Diagnostics { get; set; } = CultMeshNullDiagnosticSink.Instance; + public int MaxRacedCandidates { get; set; } = 2; + } + + public sealed class CultMeshSessionManager : IDisposable + { + private readonly CultMeshDiscoveryService _discovery; + private readonly ICultMeshTransportConnector[] _connectors; + private readonly CultMeshSessionManagerOptions _options; + private readonly ConcurrentDictionary>> _sessions = new(StringComparer.Ordinal); + private long _diagnosticSequence; + private bool _disposed; + + public CultMeshSessionManager( + CultMeshDiscoveryService discovery, + IEnumerable connectors, + CultMeshSessionManagerOptions? options = null) + { + _discovery = discovery ?? throw new ArgumentNullException(nameof(discovery)); + _connectors = connectors?.ToArray() ?? throw new ArgumentNullException(nameof(connectors)); + _options = options ?? new CultMeshSessionManagerOptions(); + if (_options.MaxRacedCandidates <= 0) throw new ArgumentOutOfRangeException(nameof(options)); + } + + public async Task ConnectAsync( + CultMeshEndpointId endpointId, + CultMeshProtocolId protocol, + CancellationToken cancellationToken = default) + { + if (endpointId == null) throw new ArgumentNullException(nameof(endpointId)); + if (protocol == null) throw new ArgumentNullException(nameof(protocol)); + ThrowIfDisposed(); + var key = endpointId.Value + "\u001f" + protocol.Value; + while (true) + { + var lazy = _sessions.GetOrAdd(key, _ => new Lazy>( + () => ConnectOwnedAsync(key, endpointId, protocol), LazyThreadSafetyMode.ExecutionAndPublication)); + try + { + var session = await AwaitForCallerAsync(lazy.Value, cancellationToken).ConfigureAwait(false); + if (session.State.Status == CultMeshSessionStatus.Online) return session; + _sessions.TryRemove(key, out _); + } + catch + { + _sessions.TryRemove(key, out _); + throw; + } + } + } + + private async Task ConnectOwnedAsync(string key, CultMeshEndpointId endpointId, CultMeshProtocolId protocol) + { + var discovery = await _discovery.ResolveAsync(new CultMeshDiscoveryQuery(endpointId.Value)).ConfigureAwait(false); + var candidates = discovery.Candidates.SelectMany(candidate => candidate.Descriptor.DiscoveryEndpoints) + .Distinct(StringComparer.Ordinal) + .Select(endpoint => new CultMeshTransportCandidate(endpoint)) + .OrderBy(candidate => candidate.Priority) + .Take(_options.MaxRacedCandidates) + .ToArray(); + if (candidates.Length == 0) + throw Failure(CultMeshSessionFailureReason.Resolution, $"No route candidates for '{endpointId}'."); + + var attempts = candidates.Select(candidate => ConnectCandidateAsync(candidate, protocol)).ToList(); + var failures = new List(); + while (attempts.Count > 0) + { + var completed = await Task.WhenAny(attempts).ConfigureAwait(false); + attempts.Remove(completed); + try + { + var result = await completed.ConfigureAwait(false); + foreach (var loser in attempts) + _ = loser.ContinueWith(task => { if (task.Status == TaskStatus.RanToCompletion) task.Result.Client.Dispose(); }, TaskScheduler.Default); + var session = new CultMeshSession(endpointId, protocol, result.Client, + new CultMeshSessionState(CultMeshSessionStatus.Online, _options.Clock.UtcNow, result.Candidate)); + if (result.Client is ICultNetSchemaClientHealth health) + { + _ = health.BackgroundFailure.ContinueWith(task => + { + var error = task.Status == TaskStatus.RanToCompletion ? task.Result : task.Exception; + session.Transition(new CultMeshSessionState( + CultMeshSessionStatus.Offline, + _options.Clock.UtcNow, + result.Candidate, + new CultMeshSessionFailure( + CultMeshSessionFailureReason.Transport, + error?.Message ?? "Transport background loop stopped.", + result.Candidate.Endpoint))); + _sessions.TryRemove(key, out _); + }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + } + Emit(endpointId, protocol, "online", result.Candidate.Endpoint); + return session; + } + catch (Exception error) { failures.Add(error); } + } + var last = failures.LastOrDefault(); + throw Failure(last is TimeoutException ? CultMeshSessionFailureReason.Timeout : CultMeshSessionFailureReason.Transport, + $"No transport path connected for '{endpointId}' and protocol '{protocol}'.", last); + } + + private async Task ConnectCandidateAsync(CultMeshTransportCandidate candidate, CultMeshProtocolId protocol) + { + var connector = _connectors.FirstOrDefault(item => item.CanConnect(candidate)); + if (connector == null) throw Failure(CultMeshSessionFailureReason.UnsupportedPath, $"No connector supports '{candidate.Endpoint}'."); + var client = await connector.ConnectAsync(candidate, protocol).ConfigureAwait(false); + return new ConnectedPath(candidate, client); + } + + 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 CultMeshSessionException Failure(CultMeshSessionFailureReason reason, string message, Exception? inner = null) => + new CultMeshSessionException(new CultMeshSessionFailure(reason, message), inner); + + private void Emit(CultMeshEndpointId endpoint, CultMeshProtocolId protocol, string state, string path) + { + _options.Diagnostics.Emit(new CultMeshDiagnosticEvent( + Interlocked.Increment(ref _diagnosticSequence), _options.Clock.UtcNow, + CultMeshReliabilityOrgan.Session, CultMeshDiagnosticKind.PathChanged, + endpoint.Value + ":" + protocol.Value, endpoint.Value, state, + sourceId: "session-manager", endpoint: path)); + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + foreach (var lazy in _sessions.Values) + if (lazy.IsValueCreated && lazy.Value.Status == TaskStatus.RanToCompletion) lazy.Value.Result.Dispose(); + _sessions.Clear(); + } + + private void ThrowIfDisposed() { if (_disposed) throw new ObjectDisposedException(nameof(CultMeshSessionManager)); } + + private sealed class ConnectedPath + { + public ConnectedPath(CultMeshTransportCandidate candidate, ICultNetSchemaClient client) { Candidate = candidate; Client = client; } + public CultMeshTransportCandidate Candidate { get; } + public ICultNetSchemaClient Client { get; } + } + } +} diff --git a/tests/GameCult.Mesh.Tests/CultMeshSessionManagerTests.cs b/tests/GameCult.Mesh.Tests/CultMeshSessionManagerTests.cs new file mode 100644 index 00000000..c47944e2 --- /dev/null +++ b/tests/GameCult.Mesh.Tests/CultMeshSessionManagerTests.cs @@ -0,0 +1,197 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using FluentAssertions; +using GameCult.Networking; +using NUnit.Framework; + +namespace GameCult.Mesh.Tests; + +public sealed class CultMeshSessionManagerTests +{ + [Test] + public async Task Connect_ReusesInflightAndEstablishedSession() + { + var clock = new ManualSessionClock(); + using var discovery = Discovery(clock, () => new[] { "rudp://direct:3076" }); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var connector = new FakeConnector(async (_, _) => { await release.Task; return new FakeSchemaClient(); }); + using var manager = new CultMeshSessionManager(discovery, new[] { connector }, new CultMeshSessionManagerOptions { Clock = clock }); + var endpoint = CultMeshEndpointId.Parse("odin:aetheria"); + + var first = manager.ConnectAsync(endpoint, CultMeshProtocols.Documents); + var second = manager.ConnectAsync(endpoint, CultMeshProtocols.Documents); + await WaitUntilAsync(() => connector.ConnectCount == 1); + release.TrySetResult(); + var sessions = await Task.WhenAll(first, second); + var third = await manager.ConnectAsync(endpoint, CultMeshProtocols.Documents); + + sessions[0].Should().BeSameAs(sessions[1]).And.BeSameAs(third); + connector.ConnectCount.Should().Be(1); + } + + [Test] + public async Task Connect_RacesPathsAndDisposesSuccessfulLoser() + { + var clock = new ManualSessionClock(); + using var discovery = Discovery(clock, () => new[] { "rudp://slow:3076", "rudp://fast:3076" }); + var slowRelease = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var slowClient = new FakeSchemaClient(); + var fastClient = new FakeSchemaClient(); + var connector = new FakeConnector(async (candidate, _) => + { + if (candidate.Endpoint.Contains("slow")) { await slowRelease.Task; return slowClient; } + return fastClient; + }); + using var manager = new CultMeshSessionManager(discovery, new[] { connector }, new CultMeshSessionManagerOptions { Clock = clock }); + + var session = await manager.ConnectAsync(CultMeshEndpointId.Parse("odin:aetheria"), CultMeshProtocols.Documents); + session.State.Path!.Endpoint.Should().Be("rudp://fast:3076"); + slowRelease.TrySetResult(); + await WaitUntilAsync(() => slowClient.DisposeCount == 1); + fastClient.DisposeCount.Should().Be(0); + } + + [Test] + public async Task Connect_CallerCancellationDoesNotCancelSharedAttempt() + { + var clock = new ManualSessionClock(); + using var discovery = Discovery(clock, () => new[] { "rudp://direct:3076" }); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var connector = new FakeConnector(async (_, token) => + { + token.CanBeCanceled.Should().BeFalse(); + await release.Task; + return new FakeSchemaClient(); + }); + using var manager = new CultMeshSessionManager(discovery, new[] { connector }, new CultMeshSessionManagerOptions { Clock = clock }); + using var cancellation = new CancellationTokenSource(); + var endpoint = CultMeshEndpointId.Parse("odin:aetheria"); + + var cancelled = manager.ConnectAsync(endpoint, CultMeshProtocols.Documents, cancellation.Token); + var survivor = manager.ConnectAsync(endpoint, CultMeshProtocols.Documents); + await WaitUntilAsync(() => connector.ConnectCount == 1); + cancellation.Cancel(); + Assert.ThrowsAsync(async () => await cancelled); + release.TrySetResult(); + + (await survivor).State.Status.Should().Be(CultMeshSessionStatus.Online); + connector.ConnectCount.Should().Be(1); + } + + [Test] + public async Task BackgroundFailureEvictsSessionAndEndpointRotationReconnects() + { + var clock = new ManualSessionClock(); + var route = "rudp://first:3076"; + using var discovery = Discovery(clock, () => new[] { route }, TimeSpan.FromSeconds(5)); + var clients = new List(); + var connector = new FakeConnector((_, _) => + { + var client = new FakeSchemaClient(); + clients.Add(client); + return Task.FromResult(client); + }); + using var manager = new CultMeshSessionManager(discovery, new[] { connector }, new CultMeshSessionManagerOptions { Clock = clock }); + var endpoint = CultMeshEndpointId.Parse("odin:aetheria"); + var first = await manager.ConnectAsync(endpoint, CultMeshProtocols.Documents); + + route = "rudp://second:3076"; + clock.Advance(TimeSpan.FromSeconds(6)); + clients[0].Fail(new IOException("partition")); + await WaitUntilAsync(() => first.State.Status == CultMeshSessionStatus.Offline); + var second = await manager.ConnectAsync(endpoint, CultMeshProtocols.Documents); + + second.Should().NotBeSameAs(first); + second.State.Path!.Endpoint.Should().Be("rudp://second:3076"); + connector.ConnectCount.Should().Be(2); + } + + [Test] + public void Connect_ReportsUnsupportedPathPrecisely() + { + var clock = new ManualSessionClock(); + using var discovery = Discovery(clock, () => new[] { "quic://unimplemented:443" }); + using var manager = new CultMeshSessionManager(discovery, Array.Empty(), new CultMeshSessionManagerOptions { Clock = clock }); + + var error = Assert.ThrowsAsync(() => + manager.ConnectAsync(CultMeshEndpointId.Parse("odin:aetheria"), CultMeshProtocols.Documents)); + + error!.Failure.Reason.Should().Be(CultMeshSessionFailureReason.Transport); + error.InnerException.Should().BeOfType() + .Which.Failure.Reason.Should().Be(CultMeshSessionFailureReason.UnsupportedPath); + } + + private static CultMeshDiscoveryService Discovery( + ManualSessionClock clock, + Func endpoints, + TimeSpan? ttl = null) + { + return new CultMeshDiscoveryService( + new[] { new RouteSource(clock, endpoints, ttl ?? TimeSpan.FromMinutes(1)) }, + new CultMeshDiscoveryServiceOptions { Clock = clock }); + } + + 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(); + } + + private sealed class RouteSource : ICultMeshLookupSource + { + private readonly ManualSessionClock _clock; + private readonly Func _endpoints; + private readonly TimeSpan _ttl; + public RouteSource(ManualSessionClock clock, Func endpoints, TimeSpan ttl) { _clock = clock; _endpoints = endpoints; _ttl = ttl; } + public string SourceId => "odin"; + public Task> LookupAsync(CultMeshDiscoveryQuery query, CancellationToken cancellationToken = default) => + Task.FromResult>(new[] + { + new CultMeshDiscoveryObservation( + new CultMeshVerseDescriptor("aetheria", "Aetheria", CultMeshVerseAuthorityModel.OperatorCluster, + new CultMeshVerseCompatibility("cultmesh.v0", "rules"), _endpoints()), + SourceId, _clock.UtcNow, _clock.UtcNow + _ttl, CultMeshDiscoveryTrust.Signed) + }); + } + + private sealed class FakeConnector : ICultMeshTransportConnector + { + private readonly Func> _connect; + private int _connectCount; + public FakeConnector(Func> connect) { _connect = connect; } + public string ConnectorId => "fake"; + 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 _connect(candidate, cancellationToken); + } + } + + private sealed class FakeSchemaClient : ICultNetSchemaClient, ICultNetSchemaClientHealth + { + private readonly TaskCompletionSource _failure = new(TaskCreationOptions.RunContinuationsAsynchronously); + private int _disposeCount; + public bool Connected => true; + public Task BackgroundFailure => _failure.Task; + public int DisposeCount => Volatile.Read(ref _disposeCount); + 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() => Interlocked.Increment(ref _disposeCount); + public void Fail(Exception error) => _failure.TrySetResult(error); + } + + private sealed class ManualSessionClock : ICultMeshClock + { + public DateTimeOffset UtcNow { get; private set; } = new DateTimeOffset(2026, 7, 12, 21, 0, 0, TimeSpan.Zero); + public Task DelayAsync(TimeSpan delay, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); UtcNow += delay; return Task.CompletedTask; } + public void Advance(TimeSpan delay) => UtcNow += delay; + } +}