Bind CultMesh authority identity to physical routes

This commit is contained in:
Meta Vens 2026-08-18 17:21:58 +02:00
commit 6c848bd6c0
45 changed files with 1671 additions and 194 deletions

View file

@ -42,11 +42,11 @@ namespace GameCult.Mesh.Quic.Native
public async Task<ICultMeshRealtimeTransport> ConnectAsync(
CultMeshTransportCandidate candidate,
CultMeshEndpointId endpointId,
CultMeshSessionTarget target,
CancellationToken cancellationToken = default)
{
if (candidate == null) throw new ArgumentNullException(nameof(candidate));
if (endpointId == null) throw new ArgumentNullException(nameof(endpointId));
if (target == null) throw new ArgumentNullException(nameof(target));
if (!TryParseEndpoint(candidate.Endpoint, out var host, out var port, out var pin))
throw new NotSupportedException($"Native QUIC connector does not support '{candidate.Endpoint}'.");
@ -72,7 +72,9 @@ namespace GameCult.Mesh.Quic.Native
var transport = new CultMeshNativeQuicRealtimeTransport(
candidate.Endpoint,
handle,
_options.PollInterval);
_options.PollInterval,
target,
candidate.Generation);
try
{
await transport.WaitUntilConnectedAsync(_options.HandshakeTimeout, cancellationToken).ConfigureAwait(false);
@ -122,23 +124,42 @@ namespace GameCult.Mesh.Quic.Native
}
}
internal sealed class CultMeshNativeQuicRealtimeTransport : ICultMeshRealtimeTransport
internal sealed class CultMeshNativeQuicRealtimeTransport : ICultMeshRealtimeTransport, ICultMeshVerifiedTransport
{
private readonly object _gate = new object();
private readonly TimeSpan _pollInterval;
private IntPtr _handle;
private readonly CultMeshSessionTarget _target;
private readonly string _routeGeneration;
private bool _disposed;
public CultMeshNativeQuicRealtimeTransport(string endpoint, IntPtr handle, TimeSpan pollInterval)
public CultMeshNativeQuicRealtimeTransport(
string endpoint,
IntPtr handle,
TimeSpan pollInterval,
CultMeshSessionTarget target,
string routeGeneration)
{
Endpoint = endpoint;
_handle = handle;
_pollInterval = pollInterval;
_target = target;
_routeGeneration = routeGeneration ?? string.Empty;
}
public string TransportId => "msquic-native-realtime";
public string Endpoint { get; }
public bool IsVerifiedFor(
string verseId,
string authorityRuntimeId,
string protocolId,
string routeGeneration) =>
string.Equals(_target.VerseId, verseId, StringComparison.Ordinal) &&
string.Equals(_target.AuthorityRuntimeId, authorityRuntimeId, StringComparison.Ordinal) &&
string.Equals(CultMeshProtocols.RealtimeState.Value, protocolId, StringComparison.Ordinal) &&
string.Equals(_routeGeneration, routeGeneration, StringComparison.Ordinal);
public Task SendAsync(CultMeshRealtimeFrame frame, CancellationToken cancellationToken = default) =>
Task.FromException(new NotSupportedException(
"The Unity-compatible native QUIC connector currently owns provider-to-client state only."));

View file

@ -22,7 +22,7 @@ public sealed class CultMeshQuicRealtimeConnectorOptions
/// <summary>
/// Optional provider-aware certificate validator. Standard TLS validation is used when omitted.
/// </summary>
public Func<CultMeshEndpointId, X509Certificate2?, X509Chain?, SslPolicyErrors, bool>?
public Func<CultMeshRuntimeId, X509Certificate2?, X509Chain?, SslPolicyErrors, bool>?
ValidateProviderCertificate { get; set; }
}
@ -55,11 +55,11 @@ public sealed class CultMeshQuicRealtimeTransportConnector : ICultMeshRealtimeTr
/// <inheritdoc />
public async Task<ICultMeshRealtimeTransport> ConnectAsync(
CultMeshTransportCandidate candidate,
CultMeshEndpointId endpointId,
CultMeshSessionTarget target,
CancellationToken cancellationToken = default)
{
if (candidate == null) throw new ArgumentNullException(nameof(candidate));
if (endpointId == null) throw new ArgumentNullException(nameof(endpointId));
if (target == null) throw new ArgumentNullException(nameof(target));
if (!QuicConnection.IsSupported)
throw new PlatformNotSupportedException("QUIC is unavailable. Install a supported MsQuic runtime.");
if (!TryParseEndpoint(candidate.Endpoint, out var host, out var port))
@ -84,14 +84,15 @@ public sealed class CultMeshQuicRealtimeTransportConnector : ICultMeshRealtimeTr
{
var providerCertificate = certificate as X509Certificate2 ??
(certificate == null ? null : new X509Certificate2(certificate));
return validator?.Invoke(endpointId, providerCertificate, chain, errors) ??
return validator?.Invoke(CultMeshRuntimeId.Parse(target.AuthorityRuntimeId), providerCertificate, chain, errors) ??
errors == SslPolicyErrors.None ||
MatchesAdvertisedCertificatePin(candidate.Endpoint, providerCertificate);
}
}
}, cancellationToken).ConfigureAwait(false);
return new CultMeshQuicRealtimeTransport(candidate.Endpoint, connection);
return new CultMeshQuicRealtimeTransport(
candidate.Endpoint, connection, target: target, routeGeneration: candidate.Generation);
}
private static bool TryParseEndpoint(string? endpoint, out string host, out int port)
@ -308,7 +309,7 @@ public sealed class CultMeshQuicRealtimeServer : IAsyncDisposable
}
}
internal sealed class CultMeshQuicRealtimeTransport : ICultMeshRealtimeTransport
internal sealed class CultMeshQuicRealtimeTransport : ICultMeshRealtimeTransport, ICultMeshVerifiedTransport
{
private readonly QuicConnection _connection;
private readonly CancellationTokenSource _shutdown = new();
@ -318,6 +319,8 @@ internal sealed class CultMeshQuicRealtimeTransport : ICultMeshRealtimeTransport
private readonly SemaphoreSlim _reliableSendGate = new(1, 1);
private readonly CultMeshRealtimeInbox _outbound = new();
private readonly Action<CultMeshRealtimeFrame>? _observer;
private readonly CultMeshSessionTarget? _target;
private readonly string _routeGeneration;
private readonly Task _acceptLoop;
private readonly Task _outboundLoop;
private readonly Task _completion;
@ -328,11 +331,15 @@ internal sealed class CultMeshQuicRealtimeTransport : ICultMeshRealtimeTransport
public CultMeshQuicRealtimeTransport(
string endpoint,
QuicConnection connection,
Action<CultMeshRealtimeFrame>? observer = null)
Action<CultMeshRealtimeFrame>? observer = null,
CultMeshSessionTarget? target = null,
string routeGeneration = "")
{
Endpoint = endpoint;
_connection = connection;
_observer = observer;
_target = target;
_routeGeneration = routeGeneration ?? string.Empty;
_acceptLoop = AcceptStreamsAsync(_shutdown.Token);
_outboundLoop = SendPublishedFramesAsync(_shutdown.Token);
_completion = Task.WhenAll(_acceptLoop, _outboundLoop);
@ -342,6 +349,17 @@ internal sealed class CultMeshQuicRealtimeTransport : ICultMeshRealtimeTransport
public string Endpoint { get; }
public Task Completion => _completion;
public bool IsVerifiedFor(
string verseId,
string authorityRuntimeId,
string protocolId,
string routeGeneration) =>
_target != null &&
string.Equals(_target.VerseId, verseId, StringComparison.Ordinal) &&
string.Equals(_target.AuthorityRuntimeId, authorityRuntimeId, StringComparison.Ordinal) &&
string.Equals(CultMeshProtocols.RealtimeState.Value, protocolId, StringComparison.Ordinal) &&
string.Equals(_routeGeneration, routeGeneration, StringComparison.Ordinal);
internal bool TryPublishLatest(CultMeshRealtimeFrame frame)
{
if (_disposed || frame.Delivery != CultMeshRealtimeDelivery.LatestOnly) return false;

View file

@ -391,7 +391,8 @@ namespace GameCult.Mesh
PayloadSchema = requestSchema.Trim(),
PayloadEncoding = "messagepack-base64",
Payload = Convert.ToBase64String(MessagePackSerializer.Serialize(request, CultNetSchemaMessageSerialization.Options)),
SourceRuntimeId = sourceRuntimeId.Trim()
SourceRuntimeId = sourceRuntimeId.Trim(),
TargetRuntimeId = target.AuthorityRuntimeId
};
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(_operationResponseTimeout);
@ -441,6 +442,11 @@ namespace GameCult.Mesh
if (!string.Equals(envelope.ServiceId, expectedService, StringComparison.Ordinal) ||
!string.Equals(envelope.Operation, expectedOperation, StringComparison.Ordinal))
throw new InvalidOperationException("CultMesh operation response did not match the requested service and operation.");
if (!string.Equals(envelope.SourceRuntimeId, target.AuthorityRuntimeId, StringComparison.Ordinal))
throw new CultMeshSessionException(new CultMeshSessionFailure(
CultMeshSessionFailureReason.Authority,
$"CultMesh operation response came from runtime '{envelope.SourceRuntimeId ?? "(missing)"}', " +
$"not selected authority '{target.AuthorityRuntimeId}'."));
if (string.Equals(envelope.PayloadSchema, CultNetOperationServer.FailureSchemaId, StringComparison.Ordinal))
{
if (!string.Equals(envelope.PayloadEncoding, "messagepack-base64", StringComparison.Ordinal))
@ -795,7 +801,7 @@ namespace GameCult.Mesh
_cache,
new CultRecordKey(recordKey),
CultMesh.Verse(target.VerseId, "cultmesh-client").Context,
routeHint: new CultMeshRouteHint(CultMeshLocalityKind.Network, target.ProviderRuntimeId));
routeHint: new CultMeshRouteHint(CultMeshLocalityKind.Network, target.AuthorityRuntimeId));
}
public CultMeshDocumentHandle<TDocument> Handle { get; }
@ -897,7 +903,7 @@ namespace GameCult.Mesh
_subscription = new CultNetDatabaseSubscriptionClient(session.OpenSchemaClient(), _cache, networkRegistry);
Handle = CultMesh.Collection<TDocument>(
_cache,
routeHint: new CultMeshRouteHint(CultMeshLocalityKind.Network, target.ProviderRuntimeId));
routeHint: new CultMeshRouteHint(CultMeshLocalityKind.Network, target.AuthorityRuntimeId));
}
public CultMeshCollectionHandle<TDocument> Handle { get; }

View file

@ -122,31 +122,56 @@ namespace GameCult.Mesh
public async Task<ICultMeshContentTransport> ConnectAsync(
CultMeshTransportCandidate candidate,
CultMeshEndpointId endpointId,
CultMeshSessionTarget target,
CancellationToken cancellationToken = default)
{
if (!CanConnect(candidate))
throw new NotSupportedException($"Legacy RUDP content connector does not support '{candidate.Endpoint}'.");
var client = await _schemaConnector.ConnectAsync(candidate, CultMeshProtocols.Content, cancellationToken)
.ConfigureAwait(false);
return new LegacyRudpContentTransport(candidate.Endpoint, client, _options);
try
{
await CultMeshSessionIdentityClient.VerifyAsync(
client,
"cultmesh-content-client",
target,
CultMeshProtocols.Content,
candidate.Generation,
_options.ResponseTimeout,
cancellationToken).ConfigureAwait(false);
return new LegacyRudpContentTransport(
candidate.Endpoint, client, _options, target, candidate.Generation);
}
catch
{
client.Dispose();
throw;
}
}
private sealed class LegacyRudpContentTransport : ICultMeshContentTransport
private sealed class LegacyRudpContentTransport : ICultMeshContentTransport, ICultMeshVerifiedTransport
{
private readonly ICultNetSchemaClient _client;
private readonly CultMeshLegacyRudpContentTransportOptions _options;
private readonly string _verseId;
private readonly string _authorityRuntimeId;
private readonly string _routeGeneration;
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, TaskCompletionSource<CultMeshContentChunkResponseMessage>> _pending = new(StringComparer.Ordinal);
private bool _disposed;
public LegacyRudpContentTransport(
string endpoint,
ICultNetSchemaClient client,
CultMeshLegacyRudpContentTransportOptions options)
CultMeshLegacyRudpContentTransportOptions options,
CultMeshSessionTarget target,
string routeGeneration)
{
Endpoint = endpoint;
_client = client;
_options = options;
_verseId = target.VerseId;
_authorityRuntimeId = target.AuthorityRuntimeId;
_routeGeneration = routeGeneration ?? string.Empty;
_client.OnCultNet<CultMeshContentChunkResponseMessage>(OnResponse);
_client.OnCultNet<CultNetErrorMessage>(OnError);
}
@ -154,6 +179,16 @@ namespace GameCult.Mesh
public string TransportId => "legacy-rudp-content";
public string Endpoint { get; }
public bool IsVerifiedFor(
string verseId,
string authorityRuntimeId,
string protocolId,
string routeGeneration) =>
string.Equals(_verseId, verseId, StringComparison.Ordinal) &&
string.Equals(_authorityRuntimeId, authorityRuntimeId, StringComparison.Ordinal) &&
string.Equals(CultMeshProtocols.Content.Value, protocolId, StringComparison.Ordinal) &&
string.Equals(_routeGeneration, routeGeneration, StringComparison.Ordinal);
public async Task CopyChunkToAsync(
CultMeshCdnChunkRef chunk,
Stream destination,

View file

@ -36,7 +36,7 @@ namespace GameCult.Mesh
bool CanConnect(CultMeshTransportCandidate candidate);
Task<ICultMeshContentTransport> ConnectAsync(
CultMeshTransportCandidate candidate,
CultMeshEndpointId endpointId,
CultMeshSessionTarget target,
CancellationToken cancellationToken = default);
}

View file

@ -267,7 +267,8 @@ namespace GameCult.Mesh
var observations = results.SelectMany(result => result.Observations)
.Where(observation => query.VerseIds.Count == 0 || query.VerseIds.Contains(observation.Candidate.VerseId, StringComparer.Ordinal))
.Where(observation => query.AuthorityRuntimeId == null ||
observation.Candidate.AuthorityRuntimeIds.Contains(query.AuthorityRuntimeId, StringComparer.Ordinal))
observation.Candidate.AuthorityRoutes.Any(route =>
string.Equals(route.AuthorityRuntimeId, query.AuthorityRuntimeId, StringComparison.Ordinal)))
.ToArray();
foreach (var rejected in observations.Where(observation => observation.Trust == CultMeshDiscoveryTrust.Rejected))

View file

@ -59,7 +59,7 @@ namespace GameCult.Mesh
bool CanConnect(CultMeshTransportCandidate candidate);
Task<ICultMeshRealtimeTransport> ConnectAsync(
CultMeshTransportCandidate candidate,
CultMeshEndpointId endpointId,
CultMeshSessionTarget target,
CancellationToken cancellationToken = default);
}

View file

@ -0,0 +1,213 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using GameCult.Networking;
namespace GameCult.Mesh
{
/// <summary>
/// Optional transport proof surfaced by connectors that already authenticate
/// the peer during their native handshake. Other schema clients must complete
/// the portable CultMesh handshake before use.
/// </summary>
public interface ICultMeshVerifiedSchemaClient
{
bool IsVerifiedFor(
string verseId,
string authorityRuntimeId,
string protocolId,
string routeGeneration);
}
/// <summary>
/// Proof exposed by content and realtime transports after their native or
/// portable handshake has bound the physical channel to an Odin route.
/// </summary>
public interface ICultMeshVerifiedTransport
{
bool IsVerifiedFor(
string verseId,
string authorityRuntimeId,
string protocolId,
string routeGeneration);
}
internal static class CultMeshTransportIdentity
{
public static void RequireVerified(
object transport,
CultMeshSessionTarget target,
CultMeshProtocolId protocol,
CultMeshTransportCandidate candidate)
{
if (transport is ICultMeshVerifiedTransport verified &&
verified.IsVerifiedFor(
target.VerseId,
target.AuthorityRuntimeId,
protocol.Value,
candidate.Generation))
return;
throw new CultMeshSessionException(new CultMeshSessionFailure(
CultMeshSessionFailureReason.Authority,
$"Transport did not prove CultMesh authority '{target}' for protocol '{protocol}'.",
candidate.Endpoint));
}
}
/// <summary>
/// Owns the server side of the transport-neutral CultMesh session identity
/// handshake. Application messages are not authority proof; providers attach
/// this gate to every schema transport they advertise.
/// </summary>
public sealed class CultMeshSessionIdentityServer : IDisposable
{
private readonly ICultNetSchemaServer _server;
private readonly string _authorityRuntimeId;
private readonly HashSet<string> _verseIds;
private readonly HashSet<string> _protocolIds;
private readonly HashSet<string> _routeGenerations;
private readonly Func<CultMeshSessionOpenMessage, ICultNetSchemaServerPeer, Task> _handler;
private bool _disposed;
public CultMeshSessionIdentityServer(
ICultNetSchemaServer server,
string authorityRuntimeId,
IEnumerable<string> verseIds,
IEnumerable<string> protocolIds,
IEnumerable<string> routeGenerations)
{
_server = server ?? throw new ArgumentNullException(nameof(server));
_authorityRuntimeId = Require(authorityRuntimeId, nameof(authorityRuntimeId));
_verseIds = Clean(verseIds, nameof(verseIds));
_protocolIds = Clean(protocolIds, nameof(protocolIds));
_routeGenerations = Clean(routeGenerations, nameof(routeGenerations));
_handler = HandleAsync;
_server.OnCultNet(_handler);
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_server.RemoveCultNetMessageListener<CultMeshSessionOpenMessage>(_handler);
}
private Task HandleAsync(CultMeshSessionOpenMessage request, ICultNetSchemaServerPeer peer)
{
var error = Validate(request);
peer.SendCultNet(new CultMeshSessionAcceptedMessage
{
MessageId = request.MessageId ?? string.Empty,
Accepted = error == null,
VerseId = request.VerseId ?? string.Empty,
AuthorityRuntimeId = _authorityRuntimeId,
ProtocolId = request.ProtocolId ?? string.Empty,
RouteGeneration = request.RouteGeneration ?? string.Empty,
Error = error
});
return Task.CompletedTask;
}
private string? Validate(CultMeshSessionOpenMessage request)
{
if (string.IsNullOrWhiteSpace(request.MessageId)) return "session-message-id-required";
if (string.IsNullOrWhiteSpace(request.SourceRuntimeId)) return "source-runtime-id-required";
if (!string.Equals(request.AuthorityRuntimeId, _authorityRuntimeId, StringComparison.Ordinal))
return "target-runtime-mismatch";
if (!_verseIds.Contains(request.VerseId ?? string.Empty)) return "verse-not-served";
if (!_protocolIds.Contains(request.ProtocolId ?? string.Empty)) return "protocol-not-served";
if (!_routeGenerations.Contains(request.RouteGeneration ?? string.Empty)) return "route-generation-not-served";
return null;
}
private static HashSet<string> Clean(IEnumerable<string> values, string name)
{
if (values == null) throw new ArgumentNullException(name);
var result = new HashSet<string>(
values.Where(value => !string.IsNullOrWhiteSpace(value)).Select(value => value.Trim()),
StringComparer.Ordinal);
if (result.Count == 0) throw new ArgumentException("At least one identity is required.", name);
return result;
}
private static string Require(string value, string name) =>
string.IsNullOrWhiteSpace(value)
? throw new ArgumentException("Value must be non-empty.", name)
: value.Trim();
}
internal static class CultMeshSessionIdentityClient
{
public static async Task VerifyAsync(
ICultNetSchemaClient client,
string sourceRuntimeId,
CultMeshSessionTarget target,
CultMeshProtocolId protocol,
string routeGeneration,
TimeSpan timeout,
CancellationToken cancellationToken = default)
{
if (client == null) throw new ArgumentNullException(nameof(client));
if (client is ICultMeshVerifiedSchemaClient verified)
{
if (!verified.IsVerifiedFor(
target.VerseId,
target.AuthorityRuntimeId,
protocol.Value,
routeGeneration ?? string.Empty))
{
throw new CultMeshSessionException(new CultMeshSessionFailure(
CultMeshSessionFailureReason.Authority,
$"Native transport identity did not match CultMesh target '{target}' for '{protocol}'."));
}
return;
}
var messageId = Guid.NewGuid().ToString("N");
var completion = new TaskCompletionSource<CultMeshSessionAcceptedMessage>(
TaskCreationOptions.RunContinuationsAsynchronously);
client.OnCultNet<CultMeshSessionAcceptedMessage>(response =>
{
if (string.Equals(response.MessageId, messageId, StringComparison.Ordinal))
completion.TrySetResult(response);
});
client.SendCultNet(new CultMeshSessionOpenMessage
{
MessageId = messageId,
SourceRuntimeId = sourceRuntimeId,
VerseId = target.VerseId,
AuthorityRuntimeId = target.AuthorityRuntimeId,
ProtocolId = protocol.Value,
RouteGeneration = routeGeneration ?? string.Empty
});
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
deadline.CancelAfter(timeout);
var cancelled = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
using (deadline.Token.Register(() => cancelled.TrySetResult(true)))
{
if (await Task.WhenAny(completion.Task, cancelled.Task).ConfigureAwait(false) != completion.Task)
{
cancellationToken.ThrowIfCancellationRequested();
throw new CultMeshSessionException(new CultMeshSessionFailure(
CultMeshSessionFailureReason.Timeout,
$"Timed out verifying authority runtime '{target.AuthorityRuntimeId}'."));
}
}
var accepted = await completion.Task.ConfigureAwait(false);
if (!accepted.Accepted ||
!string.Equals(accepted.VerseId, target.VerseId, StringComparison.Ordinal) ||
!string.Equals(accepted.AuthorityRuntimeId, target.AuthorityRuntimeId, StringComparison.Ordinal) ||
!string.Equals(accepted.ProtocolId, protocol.Value, StringComparison.Ordinal) ||
!string.Equals(accepted.RouteGeneration, routeGeneration ?? string.Empty, StringComparison.Ordinal))
{
throw new CultMeshSessionException(new CultMeshSessionFailure(
CultMeshSessionFailureReason.Authority,
$"Route did not prove CultMesh authority '{target}' for protocol '{protocol}': " +
(accepted.Error ?? "identity-mismatch")));
}
}
}
}

View file

@ -9,14 +9,14 @@ using R3;
namespace GameCult.Mesh
{
public sealed class CultMeshEndpointId : IEquatable<CultMeshEndpointId>
public sealed class CultMeshRuntimeId : IEquatable<CultMeshRuntimeId>
{
private CultMeshEndpointId(string value) { Value = value; }
private CultMeshRuntimeId(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 static CultMeshRuntimeId Parse(string value) => new CultMeshRuntimeId(
string.IsNullOrWhiteSpace(value) ? throw new FormatException("CultMesh runtime identity must be non-empty.") : value.Trim());
public bool Equals(CultMeshRuntimeId? other) => other != null && string.Equals(Value, other.Value, StringComparison.Ordinal);
public override bool Equals(object? obj) => Equals(obj as CultMeshRuntimeId);
public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(Value);
public override string ToString() => Value;
}
@ -28,31 +28,32 @@ namespace GameCult.Mesh
public sealed class CultMeshSessionTarget : IEquatable<CultMeshSessionTarget>
{
/// <summary>Creates one stable provider target inside one Verse.</summary>
public CultMeshSessionTarget(string verseId, string providerRuntimeId)
public CultMeshSessionTarget(string verseId, string authorityRuntimeId)
{
VerseId = string.IsNullOrWhiteSpace(verseId)
? throw new ArgumentException("Verse identity is required.", nameof(verseId))
: verseId.Trim();
ProviderEndpointId = CultMeshEndpointId.Parse(providerRuntimeId);
ProviderRuntimeId = ProviderEndpointId.Value;
AuthorityRuntimeId = CultMeshRuntimeId.Parse(authorityRuntimeId).Value;
}
/// <summary>Gets the stable Verse identity.</summary>
public string VerseId { get; }
/// <summary>Gets the stable provider runtime identity advertised by that Verse.</summary>
public string ProviderRuntimeId { get; }
internal CultMeshEndpointId ProviderEndpointId { get; }
internal string SessionKey => VerseId + "\u001f" + ProviderRuntimeId;
/// <summary>Gets the stable authority runtime identity advertised by that Verse.</summary>
public string AuthorityRuntimeId { get; }
/// <summary>Compatibility projection. Use <see cref="AuthorityRuntimeId"/>.</summary>
[Obsolete("Use AuthorityRuntimeId. Provider identity is not a physical endpoint.")]
public string ProviderRuntimeId => AuthorityRuntimeId;
internal string SessionKey => VerseId + "\u001f" + AuthorityRuntimeId;
public bool Equals(CultMeshSessionTarget? other) =>
other != null &&
string.Equals(VerseId, other.VerseId, StringComparison.Ordinal) &&
string.Equals(ProviderRuntimeId, other.ProviderRuntimeId, StringComparison.Ordinal);
string.Equals(AuthorityRuntimeId, other.AuthorityRuntimeId, StringComparison.Ordinal);
public override bool Equals(object? obj) => Equals(obj as CultMeshSessionTarget);
public override int GetHashCode() => HashCode.Combine(
StringComparer.Ordinal.GetHashCode(VerseId),
StringComparer.Ordinal.GetHashCode(ProviderRuntimeId));
public override string ToString() => VerseId + "/" + ProviderRuntimeId;
StringComparer.Ordinal.GetHashCode(AuthorityRuntimeId));
public override string ToString() => VerseId + "/" + AuthorityRuntimeId;
}
public sealed class CultMeshProtocolId : IEquatable<CultMeshProtocolId>
@ -80,15 +81,24 @@ namespace GameCult.Mesh
public sealed class CultMeshTransportCandidate
{
public CultMeshTransportCandidate(string endpoint, CultMeshTransportPathKind pathKind = CultMeshTransportPathKind.Direct, int priority = 0)
public CultMeshTransportCandidate(
string endpoint,
CultMeshTransportPathKind pathKind = CultMeshTransportPathKind.Direct,
int priority = 0,
string authorityRuntimeId = "",
string generation = "")
{
Endpoint = string.IsNullOrWhiteSpace(endpoint) ? throw new ArgumentException("Physical endpoint is required.", nameof(endpoint)) : endpoint;
PathKind = pathKind;
Priority = priority;
AuthorityRuntimeId = authorityRuntimeId?.Trim() ?? string.Empty;
Generation = generation?.Trim() ?? string.Empty;
}
public string Endpoint { get; }
public CultMeshTransportPathKind PathKind { get; }
public int Priority { get; }
public string AuthorityRuntimeId { get; }
public string Generation { get; }
}
public enum CultMeshSessionStatus { Connecting, Online, Degraded, Reconnecting, Offline }
@ -522,6 +532,8 @@ namespace GameCult.Mesh
public ICultMeshClock Clock { get; set; } = CultMeshSystemClock.Instance;
public ICultMeshDiagnosticSink Diagnostics { get; set; } = CultMeshNullDiagnosticSink.Instance;
public int MaxRacedCandidates { get; set; } = 2;
public string RuntimeId { get; set; } = "cultmesh-client";
public TimeSpan IdentityHandshakeTimeout { get; set; } = TimeSpan.FromSeconds(5);
}
public sealed class CultMeshSessionManager : IDisposable
@ -581,6 +593,8 @@ namespace GameCult.Mesh
throw new ArgumentException("Realtime transport connectors cannot contain null entries.", nameof(realtimeConnectors));
_options = options ?? new CultMeshSessionManagerOptions();
if (_options.MaxRacedCandidates <= 0) throw new ArgumentOutOfRangeException(nameof(options));
if (string.IsNullOrWhiteSpace(_options.RuntimeId)) throw new ArgumentException("Client runtime identity is required.", nameof(options));
if (_options.IdentityHandshakeTimeout <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(options));
}
public async Task<CultMeshSession> ConnectAsync(
@ -661,14 +675,10 @@ namespace GameCult.Mesh
"No streaming content connectors are configured. Register the TCP content connector or the explicit legacy RUDP connector.");
var discovery = await _discovery.ResolveAsync(new CultMeshDiscoveryQuery(
target.ProviderRuntimeId,
target.AuthorityRuntimeId,
new[] { target.VerseId },
target.ProviderRuntimeId)).ConfigureAwait(false);
var candidates = discovery.Candidates
.SelectMany(candidate => candidate.Descriptor.DiscoveryEndpoints)
.Distinct(StringComparer.Ordinal)
.Select(endpoint => new CultMeshTransportCandidate(endpoint))
.ToArray();
target.AuthorityRuntimeId)).ConfigureAwait(false);
var candidates = BoundCandidates(discovery, target, CultMeshProtocols.Content);
var routes = candidates
.SelectMany(candidate => _contentConnectors
.Where(connector => connector.CanConnect(candidate))
@ -685,7 +695,7 @@ namespace GameCult.Mesh
foreach (var tier in routes.GroupBy(route => route.Connector.Priority).OrderBy(group => group.Key))
{
var attempts = tier.Take(_options.MaxRacedCandidates)
.Select(route => ConnectContentCandidateAsync(target.ProviderEndpointId, route))
.Select(route => ConnectContentCandidateAsync(target, route))
.ToList();
while (attempts.Count > 0)
{
@ -709,18 +719,33 @@ namespace GameCult.Mesh
}
var last = failures.LastOrDefault();
var reason = last is CultMeshSessionException typed
? typed.Failure.Reason
: last is TimeoutException
? CultMeshSessionFailureReason.Timeout
: CultMeshSessionFailureReason.Transport;
throw Failure(
last is TimeoutException ? CultMeshSessionFailureReason.Timeout : CultMeshSessionFailureReason.Transport,
reason,
$"No streaming content path connected for '{target}'.",
last);
}
private static async Task<ConnectedContentPath> ConnectContentCandidateAsync(
CultMeshEndpointId endpointId,
CultMeshSessionTarget target,
ContentRoute route)
{
var transport = await route.Connector.ConnectAsync(route.Candidate, endpointId).ConfigureAwait(false);
return new ConnectedContentPath(route.Candidate, transport);
var transport = await route.Connector.ConnectAsync(route.Candidate, target).ConfigureAwait(false);
try
{
CultMeshTransportIdentity.RequireVerified(
transport, target, CultMeshProtocols.Content, route.Candidate);
return new ConnectedContentPath(route.Candidate, transport);
}
catch
{
transport.Dispose();
throw;
}
}
private void InvalidateContentSession(string key, CultMeshContentSession session)
@ -790,13 +815,10 @@ namespace GameCult.Mesh
"No realtime state connectors are configured. Register a QUIC connector explicitly.");
var discovery = await _discovery.ResolveAsync(new CultMeshDiscoveryQuery(
target.ProviderRuntimeId,
target.AuthorityRuntimeId,
new[] { target.VerseId },
target.ProviderRuntimeId)).ConfigureAwait(false);
var routes = discovery.Candidates
.SelectMany(candidate => candidate.Descriptor.DiscoveryEndpoints)
.Distinct(StringComparer.Ordinal)
.Select(endpoint => new CultMeshTransportCandidate(endpoint))
target.AuthorityRuntimeId)).ConfigureAwait(false);
var routes = BoundCandidates(discovery, target, CultMeshProtocols.RealtimeState)
.SelectMany(candidate => _realtimeConnectors
.Where(connector => connector.CanConnect(candidate))
.Select(connector => new RealtimeRoute(candidate, connector)))
@ -812,7 +834,7 @@ namespace GameCult.Mesh
foreach (var tier in routes.GroupBy(route => route.Connector.Priority).OrderBy(group => group.Key))
{
var attempts = tier.Take(_options.MaxRacedCandidates)
.Select(route => ConnectRealtimeCandidateAsync(target.ProviderEndpointId, route))
.Select(route => ConnectRealtimeCandidateAsync(target, route))
.ToList();
while (attempts.Count > 0)
{
@ -836,18 +858,33 @@ namespace GameCult.Mesh
}
var last = failures.LastOrDefault();
var reason = last is CultMeshSessionException typed
? typed.Failure.Reason
: last is TimeoutException
? CultMeshSessionFailureReason.Timeout
: CultMeshSessionFailureReason.Transport;
throw Failure(
last is TimeoutException ? CultMeshSessionFailureReason.Timeout : CultMeshSessionFailureReason.Transport,
reason,
$"No realtime state path connected for '{target}'.",
last);
}
private static async Task<ConnectedRealtimePath> ConnectRealtimeCandidateAsync(
CultMeshEndpointId endpointId,
CultMeshSessionTarget target,
RealtimeRoute route)
{
var transport = await route.Connector.ConnectAsync(route.Candidate, endpointId).ConfigureAwait(false);
return new ConnectedRealtimePath(route.Candidate, transport);
var transport = await route.Connector.ConnectAsync(route.Candidate, target).ConfigureAwait(false);
try
{
CultMeshTransportIdentity.RequireVerified(
transport, target, CultMeshProtocols.RealtimeState, route.Candidate);
return new ConnectedRealtimePath(route.Candidate, transport);
}
catch
{
transport.Dispose();
throw;
}
}
private void InvalidateRealtimeSession(string key, CultMeshRealtimeSession session)
@ -880,13 +917,10 @@ namespace GameCult.Mesh
private async Task<ConnectedPath> ResolveConnectedPathAsync(CultMeshSessionTarget target, CultMeshProtocolId protocol)
{
var discovery = await _discovery.ResolveAsync(new CultMeshDiscoveryQuery(
target.ProviderRuntimeId,
target.AuthorityRuntimeId,
new[] { target.VerseId },
target.ProviderRuntimeId)).ConfigureAwait(false);
var candidates = discovery.Candidates.SelectMany(candidate => candidate.Descriptor.DiscoveryEndpoints)
.Distinct(StringComparer.Ordinal)
.Select(endpoint => new CultMeshTransportCandidate(endpoint))
.ToArray();
target.AuthorityRuntimeId)).ConfigureAwait(false);
var candidates = BoundCandidates(discovery, target, protocol);
var routes = candidates
.SelectMany(candidate => _connectors
.Where(connector => connector.CanConnect(candidate))
@ -908,7 +942,7 @@ namespace GameCult.Mesh
foreach (var tier in routes.GroupBy(route => route.Connector.Priority).OrderBy(group => group.Key))
{
var attempts = tier.Take(_options.MaxRacedCandidates)
.Select(route => ConnectCandidateAsync(route, protocol))
.Select(route => ConnectCandidateAsync(target, route, protocol))
.ToList();
while (attempts.Count > 0)
{
@ -925,7 +959,12 @@ namespace GameCult.Mesh
}
}
var last = failures.LastOrDefault();
throw Failure(last is TimeoutException ? CultMeshSessionFailureReason.Timeout : CultMeshSessionFailureReason.Transport,
var reason = last is CultMeshSessionException typed
? typed.Failure.Reason
: last is TimeoutException
? CultMeshSessionFailureReason.Timeout
: CultMeshSessionFailureReason.Transport;
throw Failure(reason,
$"No transport path connected for '{target}' and protocol '{protocol}'.", last);
}
@ -960,9 +999,9 @@ namespace GameCult.Mesh
try
{
_discovery.Invalidate(new CultMeshDiscoveryQuery(
session.Target.ProviderRuntimeId,
session.Target.AuthorityRuntimeId,
new[] { session.Target.VerseId },
session.Target.ProviderRuntimeId));
session.Target.AuthorityRuntimeId));
var replacement = await ResolveConnectedPathAsync(session.Target, session.Protocol).ConfigureAwait(false);
session.ReplacePhysicalChannel(replacement.Client);
session.Transition(new CultMeshSessionState(
@ -987,10 +1026,28 @@ namespace GameCult.Mesh
}
}
private static async Task<ConnectedPath> ConnectCandidateAsync(SchemaRoute route, CultMeshProtocolId protocol)
private async Task<ConnectedPath> ConnectCandidateAsync(
CultMeshSessionTarget target,
SchemaRoute route,
CultMeshProtocolId protocol)
{
var client = await route.Connector.ConnectAsync(route.Candidate, protocol).ConfigureAwait(false);
return new ConnectedPath(route.Candidate, client);
try
{
await CultMeshSessionIdentityClient.VerifyAsync(
client,
_options.RuntimeId,
target,
protocol,
route.Candidate.Generation,
_options.IdentityHandshakeTimeout).ConfigureAwait(false);
return new ConnectedPath(route.Candidate, client);
}
catch
{
client.Dispose();
throw;
}
}
private static async Task<T> AwaitForCallerAsync<T>(Task<T> shared, CancellationToken cancellationToken)
@ -1008,12 +1065,36 @@ namespace GameCult.Mesh
private CultMeshSessionException Failure(CultMeshSessionFailureReason reason, string message, Exception? inner = null) =>
new CultMeshSessionException(new CultMeshSessionFailure(reason, message), inner);
private static CultMeshTransportCandidate[] BoundCandidates(
CultMeshDiscoveryState discovery,
CultMeshSessionTarget target,
CultMeshProtocolId protocol)
{
return discovery.Candidates
.SelectMany(candidate => candidate.Descriptor.AuthorityRoutes)
.Where(route => string.Equals(
route.AuthorityRuntimeId,
target.AuthorityRuntimeId,
StringComparison.Ordinal))
.Where(route => route.Supports(protocol))
.GroupBy(route => route.Endpoint, StringComparer.Ordinal)
.Select(group => group.OrderBy(route => route.Priority).First())
.Select(route => new CultMeshTransportCandidate(
route.Endpoint,
priority: route.Priority,
authorityRuntimeId: route.AuthorityRuntimeId,
generation: route.Generation))
.OrderBy(candidate => candidate.Priority)
.ThenBy(candidate => candidate.Endpoint, StringComparer.Ordinal)
.ToArray();
}
private void Emit(CultMeshSessionTarget target, CultMeshProtocolId protocol, string state, string path)
{
_options.Diagnostics.Emit(new CultMeshDiagnosticEvent(
Interlocked.Increment(ref _diagnosticSequence), _options.Clock.UtcNow,
CultMeshReliabilityOrgan.Session, CultMeshDiagnosticKind.PathChanged,
target.SessionKey + ":" + protocol.Value, target.ProviderRuntimeId, state,
target.SessionKey + ":" + protocol.Value, target.AuthorityRuntimeId, state,
sourceId: "session-manager", endpoint: path));
}

View file

@ -102,7 +102,7 @@ namespace GameCult.Mesh
CultNetDocumentRegistry? registry)
{
_sharedSession = session ?? throw new ArgumentNullException(nameof(session));
_endpoint = session.State.Path?.Endpoint ?? session.Target.ProviderRuntimeId;
_endpoint = session.State.Path?.Endpoint ?? session.Target.AuthorityRuntimeId;
_defaults = CultMesh.CloneSnapshotRequestOptions(options);
_registry = registry ?? new CultNetDocumentRegistry();
_client = session.Channel;

View file

@ -11,6 +11,21 @@ using GameCult.Networking;
namespace GameCult.Mesh
{
/// <summary>Identity served by one dedicated content listener.</summary>
public sealed class CultMeshTcpContentServerOptions
{
public string VerseId { get; set; } = string.Empty;
public string AuthorityRuntimeId { get; set; } = string.Empty;
public string RouteGeneration { get; set; } = string.Empty;
internal void Validate()
{
if (string.IsNullOrWhiteSpace(VerseId)) throw new InvalidOperationException("Content Verse identity is required.");
if (string.IsNullOrWhiteSpace(AuthorityRuntimeId)) throw new InvalidOperationException("Content authority runtime identity is required.");
if (string.IsNullOrWhiteSpace(RouteGeneration)) throw new InvalidOperationException("Content route generation is required.");
}
}
/// <summary>Creates dedicated TCP streams for immutable CultMesh content.</summary>
public sealed class CultMeshTcpContentTransportConnector : ICultMeshContentTransportConnector
{
@ -33,11 +48,11 @@ namespace GameCult.Mesh
public async Task<ICultMeshContentTransport> ConnectAsync(
CultMeshTransportCandidate candidate,
CultMeshEndpointId endpointId,
CultMeshSessionTarget target,
CancellationToken cancellationToken = default)
{
if (candidate == null) throw new ArgumentNullException(nameof(candidate));
if (endpointId == null) throw new ArgumentNullException(nameof(endpointId));
if (target == null) throw new ArgumentNullException(nameof(target));
if (!TryParseEndpoint(candidate.Endpoint, out var host, out var port))
throw new NotSupportedException($"TCP content connector does not support '{candidate.Endpoint}'.");
@ -48,8 +63,10 @@ namespace GameCult.Mesh
{
await CultMeshTcpContentWire.AwaitAsync(client.ConnectAsync(host, port), timeout.Token)
.ConfigureAwait(false);
await CultMeshTcpContentWire.VerifyAuthorityAsync(
client.GetStream(), target, candidate, timeout.Token).ConfigureAwait(false);
Interlocked.Increment(ref _connectCount);
return new CultMeshTcpContentTransport(candidate.Endpoint, client);
return new CultMeshTcpContentTransport(candidate.Endpoint, client, target, candidate.Generation);
}
catch
{
@ -72,7 +89,7 @@ namespace GameCult.Mesh
}
}
internal sealed class CultMeshTcpContentTransport : ICultMeshContentTransport
internal sealed class CultMeshTcpContentTransport : ICultMeshContentTransport, ICultMeshVerifiedTransport
{
private readonly TcpClient _client;
private readonly NetworkStream _stream;
@ -80,12 +97,22 @@ namespace GameCult.Mesh
private readonly ConcurrentDictionary<string, PendingCopy> _pending = new(StringComparer.Ordinal);
private readonly CancellationTokenSource _shutdown = new();
private readonly Task _receiveLoop;
private readonly string _verseId;
private readonly string _authorityRuntimeId;
private readonly string _routeGeneration;
private bool _disposed;
public CultMeshTcpContentTransport(string endpoint, TcpClient client)
public CultMeshTcpContentTransport(
string endpoint,
TcpClient client,
CultMeshSessionTarget target,
string routeGeneration)
{
Endpoint = endpoint;
_client = client ?? throw new ArgumentNullException(nameof(client));
_verseId = target?.VerseId ?? throw new ArgumentNullException(nameof(target));
_authorityRuntimeId = target.AuthorityRuntimeId;
_routeGeneration = routeGeneration ?? string.Empty;
_stream = client.GetStream();
_receiveLoop = ReceiveLoopAsync(_shutdown.Token);
}
@ -93,6 +120,16 @@ namespace GameCult.Mesh
public string TransportId => "tcp-content";
public string Endpoint { get; }
public bool IsVerifiedFor(
string verseId,
string authorityRuntimeId,
string protocolId,
string routeGeneration) =>
string.Equals(_verseId, verseId, StringComparison.Ordinal) &&
string.Equals(_authorityRuntimeId, authorityRuntimeId, StringComparison.Ordinal) &&
string.Equals(CultMeshProtocols.Content.Value, protocolId, StringComparison.Ordinal) &&
string.Equals(_routeGeneration, routeGeneration, StringComparison.Ordinal);
public async Task CopyChunkToAsync(
CultMeshCdnChunkRef chunk,
Stream destination,
@ -212,6 +249,7 @@ namespace GameCult.Mesh
private readonly TcpListener _listener;
private readonly Func<string, CultMeshCdnArtifactChunk?> _resolveChunk;
private readonly Func<string, bool> _canServeHash;
private readonly CultMeshTcpContentServerOptions _options;
private readonly CancellationTokenSource _shutdown = new();
private readonly ConcurrentDictionary<TcpClient, byte> _clients = new();
private readonly Task _acceptLoop;
@ -221,8 +259,9 @@ namespace GameCult.Mesh
public CultMeshTcpContentServer(
TcpListener listener,
CultCache content,
CultMeshTcpContentServerOptions options,
Func<string, bool>? canServeHash = null)
: this(listener, CreateCacheResolver(content), canServeHash)
: this(listener, CreateCacheResolver(content), options, canServeHash)
{
}
@ -234,10 +273,13 @@ namespace GameCult.Mesh
public CultMeshTcpContentServer(
TcpListener listener,
Func<string, CultMeshCdnArtifactChunk?> resolveChunk,
CultMeshTcpContentServerOptions options,
Func<string, bool>? canServeHash = null)
{
_listener = listener ?? throw new ArgumentNullException(nameof(listener));
_resolveChunk = resolveChunk ?? throw new ArgumentNullException(nameof(resolveChunk));
_options = options ?? throw new ArgumentNullException(nameof(options));
_options.Validate();
_canServeHash = canServeHash ?? (_ => true);
_listener.Start();
_acceptLoop = AcceptLoopAsync(_shutdown.Token);
@ -278,6 +320,7 @@ namespace GameCult.Mesh
try
{
using var stream = client.GetStream();
if (!await AcceptAuthorityAsync(stream, cancellationToken).ConfigureAwait(false)) return;
while (!cancellationToken.IsCancellationRequested)
{
var requestBytes = await CultMeshTcpContentWire.ReadFrameAsync(stream, cancellationToken).ConfigureAwait(false);
@ -296,6 +339,32 @@ namespace GameCult.Mesh
}
}
private async Task<bool> AcceptAuthorityAsync(Stream stream, CancellationToken cancellationToken)
{
var requestBytes = await CultMeshTcpContentWire.ReadFrameAsync(stream, cancellationToken).ConfigureAwait(false);
var request = CultNetSchemaMessageSerialization.Deserialize(requestBytes) as CultMeshSessionOpenMessage
?? throw new InvalidDataException("TCP content session did not begin with an authority handshake.");
var accepted = string.Equals(request.VerseId, _options.VerseId, StringComparison.Ordinal) &&
string.Equals(request.AuthorityRuntimeId, _options.AuthorityRuntimeId, StringComparison.Ordinal) &&
string.Equals(request.ProtocolId, CultMeshProtocols.Content.Value, StringComparison.Ordinal) &&
string.Equals(request.RouteGeneration, _options.RouteGeneration, StringComparison.Ordinal);
var response = new CultMeshSessionAcceptedMessage
{
MessageId = request.MessageId,
Accepted = accepted,
VerseId = _options.VerseId,
AuthorityRuntimeId = _options.AuthorityRuntimeId,
ProtocolId = CultMeshProtocols.Content.Value,
RouteGeneration = _options.RouteGeneration,
Error = accepted ? null : "Content session target does not match this authority route."
};
await CultMeshTcpContentWire.WriteFrameAsync(
stream,
CultNetSchemaMessageSerialization.Serialize(response),
cancellationToken).ConfigureAwait(false);
return accepted;
}
private async Task SendChunkAsync(
Stream stream,
CultMeshContentChunkRequestMessage request,
@ -391,6 +460,38 @@ namespace GameCult.Mesh
await stream.FlushAsync(cancellationToken).ConfigureAwait(false);
}
public static async Task VerifyAuthorityAsync(
Stream stream,
CultMeshSessionTarget target,
CultMeshTransportCandidate candidate,
CancellationToken cancellationToken)
{
var request = new CultMeshSessionOpenMessage
{
MessageId = Guid.NewGuid().ToString("N"),
SourceRuntimeId = "cultmesh-content-client",
VerseId = target.VerseId,
AuthorityRuntimeId = target.AuthorityRuntimeId,
ProtocolId = CultMeshProtocols.Content.Value,
RouteGeneration = candidate.Generation
};
await WriteFrameAsync(stream, CultNetSchemaMessageSerialization.Serialize(request), cancellationToken)
.ConfigureAwait(false);
var responseBytes = await ReadFrameAsync(stream, cancellationToken).ConfigureAwait(false);
var response = CultNetSchemaMessageSerialization.Deserialize(responseBytes) as CultMeshSessionAcceptedMessage
?? throw new InvalidDataException("TCP content authority handshake returned an unexpected schema.");
if (!string.Equals(response.MessageId, request.MessageId, StringComparison.Ordinal) ||
!response.Accepted ||
!string.Equals(response.VerseId, target.VerseId, StringComparison.Ordinal) ||
!string.Equals(response.AuthorityRuntimeId, target.AuthorityRuntimeId, StringComparison.Ordinal) ||
!string.Equals(response.ProtocolId, CultMeshProtocols.Content.Value, StringComparison.Ordinal) ||
!string.Equals(response.RouteGeneration, candidate.Generation, StringComparison.Ordinal))
throw new CultMeshSessionException(new CultMeshSessionFailure(
CultMeshSessionFailureReason.Authority,
response.Error ?? "TCP content endpoint did not prove the selected authority route.",
candidate.Endpoint));
}
public static async Task<byte[]> ReadFrameAsync(Stream stream, CancellationToken cancellationToken)
{
var header = new byte[HeaderBytes];

View file

@ -91,6 +91,53 @@ namespace GameCult.Mesh
}
}
/// <summary>
/// Binds one authoritative runtime to one physical route. This relationship is
/// the routing authority; the legacy endpoint/runtime lists are projections only.
/// </summary>
public sealed class CultMeshAuthorityRoute
{
public CultMeshAuthorityRoute(
string authorityRuntimeId,
string endpoint,
IEnumerable<string>? protocolIds = null,
int priority = 0,
string? generation = null)
{
AuthorityRuntimeId = RequireNonEmpty(authorityRuntimeId, nameof(authorityRuntimeId));
Endpoint = RequireNonEmpty(endpoint, nameof(endpoint));
ProtocolIds = Clean(protocolIds);
if (priority < 0) throw new ArgumentOutOfRangeException(nameof(priority));
Priority = priority;
Generation = string.IsNullOrWhiteSpace(generation)
? AuthorityRuntimeId + "@" + Endpoint
: generation!.Trim();
}
public string AuthorityRuntimeId { get; }
public string Endpoint { get; }
public IReadOnlyList<string> ProtocolIds { get; }
public int Priority { get; }
public string Generation { get; }
public bool Supports(CultMeshProtocolId protocol) =>
protocol != null &&
(ProtocolIds.Count == 0 || ProtocolIds.Contains(protocol.Value, StringComparer.Ordinal));
private static string[] Clean(IEnumerable<string>? values) =>
values?.Where(value => !string.IsNullOrWhiteSpace(value))
.Select(value => value.Trim())
.Distinct(StringComparer.Ordinal)
.OrderBy(value => value, StringComparer.Ordinal)
.ToArray()
?? Array.Empty<string>();
private static string RequireNonEmpty(string value, string paramName) =>
string.IsNullOrWhiteSpace(value)
? throw new ArgumentException("Value must be non-empty.", paramName)
: value.Trim();
}
/// <summary>
/// Describes one CultMesh Verse: a rule-bearing consensus graph.
/// </summary>
@ -107,14 +154,36 @@ namespace GameCult.Mesh
IEnumerable<string>? discoveryEndpoints = null,
IEnumerable<string>? authorityRuntimeIds = null,
string? parentVerseId = null,
string? description = null)
string? description = null,
IEnumerable<CultMeshAuthorityRoute>? authorityRoutes = null)
{
VerseId = RequireNonEmpty(verseId, nameof(verseId));
DisplayName = RequireNonEmpty(displayName, nameof(displayName));
AuthorityModel = authorityModel;
Compatibility = compatibility ?? throw new ArgumentNullException(nameof(compatibility));
DiscoveryEndpoints = Clean(discoveryEndpoints);
AuthorityRuntimeIds = Clean(authorityRuntimeIds);
var legacyEndpoints = Clean(discoveryEndpoints);
var legacyRuntimeIds = Clean(authorityRuntimeIds);
var suppliedRoutes = authorityRoutes?.ToArray();
if (suppliedRoutes?.Any(route => route == null) == true)
throw new ArgumentException("Authority routes cannot contain null.", nameof(authorityRoutes));
if (suppliedRoutes != null && (legacyEndpoints.Length > 0 || legacyRuntimeIds.Length > 0))
throw new ArgumentException(
"Supply bound authority routes or legacy endpoint/runtime lists, never both.",
nameof(authorityRoutes));
if (suppliedRoutes == null && legacyEndpoints.Length > 0 && legacyRuntimeIds.Length > 1)
throw new InvalidOperationException(
"Legacy Verse routing with multiple authority runtimes is ambiguous. " +
"Publish explicit CultMeshAuthorityRoute bindings.");
AuthorityRoutes = NormalizeRoutes(suppliedRoutes ??
(legacyRuntimeIds.Length == 1
? legacyEndpoints.Select(endpoint => new CultMeshAuthorityRoute(legacyRuntimeIds[0], endpoint))
: Array.Empty<CultMeshAuthorityRoute>()));
DiscoveryEndpoints = AuthorityRoutes.Count > 0
? AuthorityRoutes.Select(route => route.Endpoint).Distinct(StringComparer.Ordinal).ToArray()
: legacyEndpoints;
AuthorityRuntimeIds = AuthorityRoutes.Select(route => route.AuthorityRuntimeId)
.Distinct(StringComparer.Ordinal).OrderBy(value => value, StringComparer.Ordinal).ToArray();
ParentVerseId = parentVerseId;
Description = description;
}
@ -143,6 +212,8 @@ namespace GameCult.Mesh
/// Gets known authoritative runtime ids, when authority is cluster-shaped.
/// </summary>
public IReadOnlyList<string> AuthorityRuntimeIds { get; }
/// <summary>Gets exact authority-to-route bindings used for identity-sensitive resolution.</summary>
public IReadOnlyList<CultMeshAuthorityRoute> AuthorityRoutes { get; }
/// <summary>
/// Gets the parent Verse id for subscribed overlays or branches.
/// </summary>
@ -177,10 +248,29 @@ namespace GameCult.Mesh
private static string[] Clean(IEnumerable<string>? values)
{
return values?.Where(value => !string.IsNullOrWhiteSpace(value)).Distinct(StringComparer.Ordinal).ToArray()
return values?.Where(value => !string.IsNullOrWhiteSpace(value))
.Select(value => value.Trim())
.Distinct(StringComparer.Ordinal)
.ToArray()
?? Array.Empty<string>();
}
private static CultMeshAuthorityRoute[] NormalizeRoutes(IEnumerable<CultMeshAuthorityRoute> routes)
{
return routes
.GroupBy(route => new
{
route.AuthorityRuntimeId,
route.Endpoint,
Protocols = string.Join("\u001f", route.ProtocolIds)
})
.Select(group => group.OrderBy(route => route.Priority).First())
.OrderBy(route => route.Priority)
.ThenBy(route => route.AuthorityRuntimeId, StringComparer.Ordinal)
.ThenBy(route => route.Endpoint, StringComparer.Ordinal)
.ToArray();
}
private static string RequireNonEmpty(string value, string paramName)
{
if (string.IsNullOrWhiteSpace(value))

View file

@ -33,6 +33,14 @@ namespace GameCult.Mesh
},
DiscoveryEndpoints = verse.DiscoveryEndpoints.ToArray(),
AuthorityRuntimeIds = verse.AuthorityRuntimeIds.ToArray(),
AuthorityRoutes = verse.AuthorityRoutes.Select(route => new CultMeshAuthorityRouteMessage
{
AuthorityRuntimeId = route.AuthorityRuntimeId,
Endpoint = route.Endpoint,
ProtocolIds = route.ProtocolIds.ToArray(),
Priority = route.Priority,
Generation = route.Generation
}).ToArray(),
ParentVerseId = verse.ParentVerseId,
Description = verse.Description
};
@ -50,6 +58,12 @@ namespace GameCult.Mesh
out var parsed)
? parsed
: CultMeshVerseAuthorityModel.SubscribedOverlay;
var routes = message.AuthorityRoutes?.Select(route => new CultMeshAuthorityRoute(
route.AuthorityRuntimeId,
route.Endpoint,
route.ProtocolIds,
route.Priority,
route.Generation)).ToArray();
return new CultMeshVerseDescriptor(
message.VerseId,
message.DisplayName,
@ -60,10 +74,11 @@ namespace GameCult.Mesh
message.Compatibility.CompatibleVerseIds,
message.Compatibility.RequiredPluginIds,
message.Compatibility.OptionalPluginIds),
message.DiscoveryEndpoints,
message.AuthorityRuntimeIds,
routes is { Length: > 0 } ? null : message.DiscoveryEndpoints,
routes is { Length: > 0 } ? null : message.AuthorityRuntimeIds,
message.ParentVerseId,
message.Description);
message.Description,
routes is { Length: > 0 } ? routes : null);
}
/// <summary>Creates the canonical filtered Verse catalog response for any CultNet transport adapter.</summary>

View file

@ -50,8 +50,12 @@ not the brand surface.
### Verses
`CultMeshVerseDescriptor` describes a rule-bearing consensus graph. It includes
transport compatibility, rules hash, authority model, discovery endpoints,
known authority runtimes, optional parent Verse id, and plugin requirements.
transport compatibility, rules hash, authority model, exact authority-route
bindings, optional parent Verse id, and plugin requirements. Each route binds
an authority runtime to one endpoint, protocol set, priority, and generation.
The old endpoint/runtime arrays are derived projections; a legacy descriptor
with several authority runtimes is rejected because it cannot identify which
runtime owns which route.
`CultMeshVerseCatalog` is the local reactive catalog for discovered Verses.
It can publish discovery updates and find compatible transfer targets.

View file

@ -9,7 +9,8 @@ be equally good at files, realtime state, and same-machine memory access.
registered connector for each traffic class. A connector owns only its physical
connection and byte movement.
**Inputs:** stable Verse/provider identity, advertised physical candidates,
**Inputs:** stable Verse/authority-runtime identity, exact Odin-bound physical
routes with protocol and generation,
connector support and priority, caller cancellation, and locality evidence for
body negotiation.
@ -63,13 +64,22 @@ operation.
transport diagnostics. None of these grant provider authority or become content
identity.
Before a schema, content, or realtime session becomes online, the transport
must prove that the connected peer matches the selected Verse, authority
runtime, protocol, and route generation. TCP schema and content lanes use the
portable CultNet session-open handshake. QUIC uses the exact Odin-bound route
plus its TLS endpoint/certificate proof. A connector that returns bytes without
authority proof is rejected; racing every endpoint in a Verse descriptor is
not route selection.
**Forbidden writers:** applications and renderers do not choose unadvertised
endpoints, implement reconnect loops, or bypass verification. Schema messages
must not carry bulk bodies. RUDP/LiteNetLib cannot become an implicit default
for any traffic class. QUIC does not own schemas or immutable files merely
because it can transport bytes.
**Shared paths:** discovery and identity resolution remain common. Each traffic
**Shared paths:** exact route resolution and peer verification remain common.
Each traffic
class has its own connector set, connection cache, priority tiers, and failure
state. All content connectors feed the same transfer and promotion owner.

View file

@ -21,8 +21,10 @@ The same transport can carry many Verses:
subscribed overlay
- `Compatibility`: transport version, rules hash, compatible Verse ids, and
plugin requirements
- `DiscoveryEndpoints`: endpoints where nodes for the Verse can be found
- `AuthorityRuntimeIds`: known authoritative runtimes when cluster-shaped
- `AuthorityRoutes`: exact authority-runtime, endpoint, protocol, priority, and
generation bindings. This is the routing authority.
- `DiscoveryEndpoints`: read-only endpoint projection for legacy inspection
- `AuthorityRuntimeIds`: read-only authority projection for legacy inspection
- `ParentVerseId`: source Verse for overlays or branches
## Compatibility
@ -57,6 +59,13 @@ static config, cloud discovery, peer gossip, or mod portals. It does not care
where the descriptor came from. That keeps discovery pluggable while the Verse
model stays stable.
An endpoint and an authority id are not two independent facts. A descriptor
with explicit routes binds them. The legacy parallel arrays are accepted only
when exactly one authority runtime exists; a multi-authority legacy descriptor
is ambiguous and fails closed. Session establishment then requires the selected
physical route to prove the exact Verse, authority runtime, protocol, and route
generation before the session becomes online.
Peer exchange is the torrent-shaped layer under Verse discovery. A Verse
catalog says which graph exists; a peer catalog says which nodes can currently
serve or observe parts of that graph. Peer cards can advertise discovery,

View file

@ -164,6 +164,16 @@ namespace GameCult.Networking
if (_disposed) return;
if (request == null) throw new ArgumentNullException(nameof(request));
if (peer == null) throw new ArgumentNullException(nameof(peer));
if (_sourceRuntimeId != null &&
!string.Equals(request.TargetRuntimeId, _sourceRuntimeId, StringComparison.Ordinal))
{
peer.SendCultNet(Failure(
request,
"denied",
"target-runtime-mismatch",
$"Operation targeted runtime '{request.TargetRuntimeId ?? "(missing)"}', not '{_sourceRuntimeId}'."));
return;
}
Route route;
try

View file

@ -72,6 +72,8 @@ namespace GameCult.Networking
CultNetSchemaVersions.SimulationConsensusCandidate => Deserialize<CultNetSimulationConsensusCandidateMessage>(payload),
CultNetSchemaVersions.VerseCatalogRequest => Deserialize<CultMeshVerseCatalogRequestMessage>(payload),
CultNetSchemaVersions.VerseCatalogResponse => Deserialize<CultMeshVerseCatalogResponseMessage>(payload),
CultNetSchemaVersions.SessionOpen => Deserialize<CultMeshSessionOpenMessage>(payload),
CultNetSchemaVersions.SessionAccepted => Deserialize<CultMeshSessionAcceptedMessage>(payload),
CultNetSchemaVersions.PeerExchangeRequest => Deserialize<CultMeshPeerExchangeRequestMessage>(payload),
CultNetSchemaVersions.PeerExchangeResponse => Deserialize<CultMeshPeerExchangeResponseMessage>(payload),
CultNetSchemaVersions.ContentChunkRequest => Deserialize<CultMeshContentChunkRequestMessage>(payload),

View file

@ -135,6 +135,10 @@ namespace GameCult.Networking
/// CultMesh Verse catalog response contract identifier.
/// </summary>
public const string VerseCatalogResponse = "cultmesh.verse_catalog_response.v0";
/// <summary>CultMesh session identity request contract identifier.</summary>
public const string SessionOpen = "cultmesh.session_open.v1";
/// <summary>CultMesh verified session identity response contract identifier.</summary>
public const string SessionAccepted = "cultmesh.session_accepted.v1";
/// <summary>
/// CultMesh peer exchange request contract identifier.
/// </summary>
@ -1179,6 +1183,33 @@ namespace GameCult.Networking
}
}
/// <summary>Requests an identity-bound CultMesh session before application traffic begins.</summary>
[MessagePackObject]
public class CultMeshSessionOpenMessage : ICultNetSchemaMessage
{
[Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.SessionOpen;
[Key("messageId")] public string MessageId { get; set; } = string.Empty;
[Key("sourceRuntimeId")] public string SourceRuntimeId { get; set; } = string.Empty;
[Key("verseId")] public string VerseId { get; set; } = string.Empty;
[Key("authorityRuntimeId")] public string AuthorityRuntimeId { get; set; } = string.Empty;
[Key("protocolId")] public string ProtocolId { get; set; } = string.Empty;
[Key("routeGeneration")] public string RouteGeneration { get; set; } = string.Empty;
}
/// <summary>Accepts or rejects a CultMesh session with the server's actual identity.</summary>
[MessagePackObject]
public class CultMeshSessionAcceptedMessage : ICultNetSchemaMessage
{
[Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.SessionAccepted;
[Key("messageId")] public string MessageId { get; set; } = string.Empty;
[Key("accepted")] public bool Accepted { get; set; }
[Key("verseId")] public string VerseId { get; set; } = string.Empty;
[Key("authorityRuntimeId")] public string AuthorityRuntimeId { get; set; } = string.Empty;
[Key("protocolId")] public string ProtocolId { get; set; } = string.Empty;
[Key("routeGeneration")] public string RouteGeneration { get; set; } = string.Empty;
[Key("error")] public string? Error { get; set; }
}
/// <summary>
/// Requests known CultMesh Verses from a peer.
/// </summary>
@ -1254,6 +1285,11 @@ namespace GameCult.Networking
/// </summary>
[Key("authorityRuntimeIds")] public string[] AuthorityRuntimeIds { get; set; } = Array.Empty<string>();
/// <summary>
/// Gets or sets exact authoritative-runtime route bindings. This is the
/// routing authority; the parallel legacy arrays are projections only.
/// </summary>
[Key("authorityRoutes")] public CultMeshAuthorityRouteMessage[] AuthorityRoutes { get; set; } = Array.Empty<CultMeshAuthorityRouteMessage>();
/// <summary>
/// Gets or sets the parent Verse id for overlays or branches.
/// </summary>
[Key("parentVerseId")] public string? ParentVerseId { get; set; }
@ -1263,6 +1299,17 @@ namespace GameCult.Networking
[Key("description")] public string? Description { get; set; }
}
/// <summary>Wire representation of one authority-bound CultMesh route.</summary>
[MessagePackObject]
public class CultMeshAuthorityRouteMessage
{
[Key("authorityRuntimeId")] public string AuthorityRuntimeId { get; set; } = string.Empty;
[Key("endpoint")] public string Endpoint { get; set; } = string.Empty;
[Key("protocolIds")] public string[] ProtocolIds { get; set; } = Array.Empty<string>();
[Key("priority")] public int Priority { get; set; }
[Key("generation")] public string Generation { get; set; } = string.Empty;
}
/// <summary>
/// Wire representation of CultMesh Verse compatibility.
/// </summary>