From 651041943914e773fe234bfb9e62990a38acc063 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 16 Jun 2026 16:57:35 +0100 Subject: [PATCH] Add C# CultMesh RUDP facade helpers --- docs/cultnet-transport-parity.md | 6 + docs/runtime-parity-scope.md | 2 +- src/GameCult.Mesh/CultMesh.cs | 216 ++++++++++++++++++ src/GameCult.Mesh/CultMeshPeerExchange.cs | 28 +++ src/GameCult.Mesh/README.md | 20 ++ src/GameCult.Mesh/docs/public-api.md | 18 +- .../NetworkingTests.cs | 91 ++++++++ 7 files changed, 379 insertions(+), 2 deletions(-) diff --git a/docs/cultnet-transport-parity.md b/docs/cultnet-transport-parity.md index 3f894093..0da9b5ad 100644 --- a/docs/cultnet-transport-parity.md +++ b/docs/cultnet-transport-parity.md @@ -282,6 +282,12 @@ Current progress: `ReconnectIfDue(nowMs)` inside their own scheduler, and the shared controller owns retry delay/exhaustion state while the caller-owned factory opens the next `CultNetRudpSocketTransportConnection`. +- C# `GameCult.Mesh` now mirrors the branded RUDP facade shape used by + TypeScript, Python, Kotlin, and Rust: it parses `rudp://host:port` endpoints, + creates RUDP client/server transports from endpoint or peer-card contact + hints, and can create a RUDP client from the first peer authorized by the + authority lease catalog for a Verse role. RUDP packet/session behavior remains + owned by `GameCult.Networking`. - TypeScript now has a `CultNetRudpReconnectLoop` that consumes the shared controller while keeping socket construction caller-owned. A closed RUDP transport schedules the next attempt with the portable policy, opens a fresh diff --git a/docs/runtime-parity-scope.md b/docs/runtime-parity-scope.md index 0dc8a841..aaa0cf9d 100644 --- a/docs/runtime-parity-scope.md +++ b/docs/runtime-parity-scope.md @@ -30,7 +30,7 @@ CultMesh. | Runtime | Role | Claimed parity | Not claimed | | --- | --- | --- | --- | -| C# | Reference implementation and production game/server substrate | CultCache typed documents and SoA, CultNet schema-v0, LiteNetLib production path with adapter profile, shared transport profiles, shared RUDP socket transport, RUDP reconnect policy/controller and reconnect-loop helper, LiteNetLib client reconnect-controller adoption, schema-client transport port for service request/response clients, CultMesh node/session/catalog/stream/simulation surfaces | No need to abandon LiteNetLib before the CultNet adapter fully owns production service adoption | +| C# | Reference implementation and production game/server substrate | CultCache typed documents and SoA, CultNet schema-v0, LiteNetLib production path with adapter profile, shared transport profiles, shared RUDP socket transport, RUDP reconnect policy/controller and reconnect-loop helper, LiteNetLib client reconnect-controller adoption, schema-client transport port for service request/response clients, CultMesh node/session/catalog/stream/simulation/RUDP surfaces, authorized peer lookup | No need to abandon LiteNetLib before the CultNet adapter fully owns production service adoption | | Python | Package runtime, local daemon endpoint, raw interop peer, typed state participant | CultCache/CultNet/CultMesh package surface, branded CultMesh node/schema/shard/Verse/peer/authority/stream/RUDP ergonomics, authorized peer lookup, shard catalogs/logs, schema-transport factory for raw client request/subscription flows, local TCP CultMesh server, session/prediction/simulation fact helpers, RUDP codec/session/socket transport, RUDP reconnect policy/controller and reconnect-loop helper, schema-v0 MessagePack over RUDP evidence, benchmark evidence against C# cache paths | Universal C# throughput, full C# daemon/server stack, and RUDP as the only public service pipe | | TypeScript | Node/browser-adjacent projection and interop runtime | CultCache parity tests, CultNet schema-v0 peer, advertised schema/shard catalog wire contracts plus request/sync helpers, transport profiles, TCP-framed transport port and peer helper, shared RUDP socket transport, RUDP reconnect policy/controller, RUDP reconnect-loop helper, branded CultMesh node/schema/shard/Verse/peer/authority/stream/RUDP ergonomics, authorized peer lookup | Full C# game session/server stack | | Rust | Low-level cache/transport/runtime substrate | CultCache/CultNet interop lane, schema and shard catalog helpers, transport profiles, TCP-framed port, shared RUDP codec/session/socket transport, RUDP reconnect policy/controller and reconnect-loop helper, schema-v0 MessagePack over RUDP evidence, small CultMesh facade for schema registry, shard catalog, peer cards, authority leases, RUDP endpoint parsing, and peer-card RUDP client construction | Full CultMesh game-session/server facade, stream catalog, or production game-session server | diff --git a/src/GameCult.Mesh/CultMesh.cs b/src/GameCult.Mesh/CultMesh.cs index 8cbeec76..e672f8bd 100644 --- a/src/GameCult.Mesh/CultMesh.cs +++ b/src/GameCult.Mesh/CultMesh.cs @@ -1,5 +1,8 @@ using System; using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; using System.Threading.Tasks; using GameCult.Caching; using GameCult.Caching.MessagePack; @@ -162,6 +165,65 @@ namespace GameCult.Mesh } } + /// + /// Parsed CultMesh RUDP endpoint. + /// + public sealed class CultMeshRudpEndpoint + { + /// + /// Creates a parsed RUDP endpoint. + /// + public CultMeshRudpEndpoint(string host, int port, string uri) + { + Host = string.IsNullOrWhiteSpace(host) + ? throw new ArgumentException("Host must be non-empty.", nameof(host)) + : host; + if (port <= 0 || port > 65535) + { + throw new ArgumentOutOfRangeException(nameof(port), "Port must be between 1 and 65535."); + } + + Port = port; + Uri = string.IsNullOrWhiteSpace(uri) + ? throw new ArgumentException("Uri must be non-empty.", nameof(uri)) + : uri; + } + + /// Gets the endpoint host. + public string Host { get; } + /// Gets the endpoint port. + public int Port { get; } + /// Gets the normalized rudp:// URI. + public string Uri { get; } + } + + /// + /// Options for CultMesh-branded RUDP socket helpers. + /// + public sealed class CultMeshRudpSocketOptions + { + /// Gets or sets the local bind host. + public string BindHost { get; set; } = "127.0.0.1"; + /// Gets or sets the local bind port. + public int BindPort { get; set; } + /// Gets or sets a caller-owned bound socket. + public Socket? Socket { get; set; } + /// Gets or sets the first local packet sequence. + public uint InitialSequence { get; set; } = 1; + /// Gets or sets the reliable resend delay in milliseconds. + public long ResendDelayMs { get; set; } = 250; + /// Gets or sets the advertised transport id. + public string TransportId { get; set; } = "rudp"; + /// Gets or sets the advertised maximum payload size. + public int? MaxPayloadBytes { get; set; } + /// Gets or sets the maximum RUDP fragment size. + public int? MaxFragmentBytes { get; set; } + /// Gets or sets the maximum pending reliable packet count. + public int? MaxPendingReliablePackets { get; set; } + /// Gets or sets the advertised reconnect policy. + public CultNetReconnectPolicy? ReconnectPolicy { get; set; } + } + /// /// Public CultMesh entrypoints. /// @@ -220,6 +282,139 @@ namespace GameCult.Mesh return new CultMeshStreamCatalog(); } + /// + /// Parses a rudp://host:port endpoint into its host/port parts. + /// + public static CultMeshRudpEndpoint ParseRudpEndpoint(string endpoint) + { + if (string.IsNullOrWhiteSpace(endpoint)) throw new ArgumentException("Value must be non-empty.", nameof(endpoint)); + if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) || + !string.Equals(uri.Scheme, "rudp", StringComparison.OrdinalIgnoreCase)) + { + throw new ArgumentException("RUDP endpoint must use the rudp:// scheme.", nameof(endpoint)); + } + + if (string.IsNullOrWhiteSpace(uri.Host) || uri.Port <= 0 || uri.Port > 65535) + { + throw new ArgumentException("RUDP endpoint must include a host and port.", nameof(endpoint)); + } + + var host = uri.Host; + var uriHost = host.Contains(':', StringComparison.Ordinal) && !host.StartsWith("[", StringComparison.Ordinal) + ? $"[{host}]" + : host; + return new CultMeshRudpEndpoint(host, uri.Port, $"rudp://{uriHost}:{uri.Port}"); + } + + /// + /// Creates a CultNet RUDP server transport with CultMesh-branded defaults. + /// + public static CultNetRudpSocketTransportConnection CreateRudpServer( + string runtimeId, + uint connectionId, + CultMeshRudpSocketOptions? options = null) + { + options ??= new CultMeshRudpSocketOptions(); + return new CultNetRudpSocketTransportConnection(new CultNetRudpSocketTransportOptions + { + RuntimeId = runtimeId, + Socket = options.Socket ?? BindRudpSocket(options.BindHost, options.BindPort), + Mode = CultNetRudpSocketMode.Server, + ConnectionId = connectionId, + InitialSequence = options.InitialSequence, + ResendDelayMs = options.ResendDelayMs, + TransportId = options.TransportId, + MaxPayloadBytes = options.MaxPayloadBytes, + MaxFragmentBytes = options.MaxFragmentBytes, + MaxPendingReliablePackets = options.MaxPendingReliablePackets, + ReconnectPolicy = options.ReconnectPolicy + }); + } + + /// + /// Creates a CultNet RUDP client transport for a parsed endpoint. + /// + public static CultNetRudpSocketTransportConnection CreateRudpClient( + string runtimeId, + uint connectionId, + CultMeshRudpEndpoint endpoint, + CultMeshRudpSocketOptions? options = null) + { + if (endpoint == null) throw new ArgumentNullException(nameof(endpoint)); + options ??= new CultMeshRudpSocketOptions(); + return new CultNetRudpSocketTransportConnection(new CultNetRudpSocketTransportOptions + { + RuntimeId = runtimeId, + Socket = options.Socket ?? BindRudpSocket(options.BindHost, options.BindPort), + Mode = CultNetRudpSocketMode.Client, + RemoteEndPoint = new IPEndPoint(ResolveRudpAddress(endpoint.Host), endpoint.Port), + ConnectionId = connectionId, + InitialSequence = options.InitialSequence, + ResendDelayMs = options.ResendDelayMs, + TransportId = options.TransportId, + MaxPayloadBytes = options.MaxPayloadBytes, + MaxFragmentBytes = options.MaxFragmentBytes, + MaxPendingReliablePackets = options.MaxPendingReliablePackets, + ReconnectPolicy = options.ReconnectPolicy + }); + } + + /// + /// Creates a CultNet RUDP client transport for a rudp://host:port endpoint. + /// + public static CultNetRudpSocketTransportConnection CreateRudpClient( + string runtimeId, + uint connectionId, + string endpoint, + CultMeshRudpSocketOptions? options = null) + { + return CreateRudpClient(runtimeId, connectionId, ParseRudpEndpoint(endpoint), options); + } + + /// + /// Creates a CultNet RUDP client transport from a peer-card contact hint. + /// + public static CultNetRudpSocketTransportConnection CreateRudpClientForPeer( + string runtimeId, + uint connectionId, + CultMeshPeerCard peer, + CultMeshRudpSocketOptions? options = null) + { + if (peer == null) throw new ArgumentNullException(nameof(peer)); + var endpoint = peer.Endpoints.FirstOrDefault(value => value.StartsWith("rudp://", StringComparison.OrdinalIgnoreCase)); + if (endpoint == null) + { + throw new InvalidOperationException($"Peer {peer.PeerId} does not advertise a RUDP endpoint."); + } + + return CreateRudpClient(runtimeId, connectionId, endpoint, options); + } + + /// + /// Creates a CultNet RUDP client transport from the first peer authorized for a Verse role. + /// + public static CultNetRudpSocketTransportConnection CreateRudpClientForAuthorizedPeer( + string runtimeId, + uint connectionId, + CultMeshPeerCatalog peers, + CultMeshAuthorityLeaseCatalog leases, + string verseId, + string role, + string? shardId = null, + DateTimeOffset? at = null, + CultMeshRudpSocketOptions? options = null) + { + if (peers == null) throw new ArgumentNullException(nameof(peers)); + if (leases == null) throw new ArgumentNullException(nameof(leases)); + var peer = peers.FirstAuthorized(verseId, role, leases, shardId, at); + if (peer == null) + { + throw new InvalidOperationException($"No authorized RUDP peer for role {role} in Verse {verseId}."); + } + + return CreateRudpClientForPeer(runtimeId, connectionId, peer, options); + } + /// /// Creates a committer for writing quorum simulation facts to a mesh database. /// @@ -297,5 +492,26 @@ namespace GameCult.Mesh { return CultNetLocal.ConnectClient(host, port, security, configureClient); } + + private static Socket BindRudpSocket(string host, int port) + { + var address = ResolveRudpAddress(host); + var socket = new Socket(address.AddressFamily, SocketType.Dgram, ProtocolType.Udp); + socket.Bind(new IPEndPoint(address, port)); + socket.ReceiveTimeout = 20; + return socket; + } + + private static IPAddress ResolveRudpAddress(string host) + { + if (string.IsNullOrWhiteSpace(host)) throw new ArgumentException("Value must be non-empty.", nameof(host)); + if (IPAddress.TryParse(host, out var parsed)) + { + return parsed; + } + + return Dns.GetHostAddresses(host).FirstOrDefault() + ?? throw new InvalidOperationException($"Could not resolve RUDP host {host}."); + } } } diff --git a/src/GameCult.Mesh/CultMeshPeerExchange.cs b/src/GameCult.Mesh/CultMeshPeerExchange.cs index 7a26d892..afffb776 100644 --- a/src/GameCult.Mesh/CultMeshPeerExchange.cs +++ b/src/GameCult.Mesh/CultMeshPeerExchange.cs @@ -190,6 +190,34 @@ namespace GameCult.Mesh .ToArray(); } + /// Finds peers that advertise a Verse role and are authorized by the supplied lease catalog. + public IReadOnlyList FindAuthorized( + string verseId, + string role, + CultMeshAuthorityLeaseCatalog leases, + string? shardId = null, + DateTimeOffset? at = null) + { + ThrowIfDisposed(); + if (string.IsNullOrWhiteSpace(verseId)) throw new ArgumentException("Value must be non-empty.", nameof(verseId)); + if (string.IsNullOrWhiteSpace(role)) throw new ArgumentException("Value must be non-empty.", nameof(role)); + if (leases == null) throw new ArgumentNullException(nameof(leases)); + return Find(verseId, role) + .Where(peer => leases.IsAuthorized(peer, role, shardId, at)) + .ToArray(); + } + + /// Returns the first peer that advertises a Verse role and is authorized by the supplied lease catalog. + public CultMeshPeerCard? FirstAuthorized( + string verseId, + string role, + CultMeshAuthorityLeaseCatalog leases, + string? shardId = null, + DateTimeOffset? at = null) + { + return FindAuthorized(verseId, role, leases, shardId, at).FirstOrDefault(); + } + /// public void Dispose() { diff --git a/src/GameCult.Mesh/README.md b/src/GameCult.Mesh/README.md index 72f286ff..f08d3066 100644 --- a/src/GameCult.Mesh/README.md +++ b/src/GameCult.Mesh/README.md @@ -112,6 +112,26 @@ leases.Upsert(new CultMeshAuthorityLease( signature: "operator-signature")); ``` +`CultMeshPeerCatalog.FindAuthorized(...)` and `FirstAuthorized(...)` compose +peer lookup with the lease catalog, so contact gossip stays separate from +trust. The branded RUDP helpers use the same boundary: + +```csharp +using var rudpClient = CultMesh.CreateRudpClientForAuthorizedPeer( + "aetheria-client", + connectionId: 0x10203040, + peers, + leases, + "aetheria-main", + CultMeshPeerRoles.ShardPrimary, + shardId: "players-us-east"); +``` + +`CreateRudpServer(...)`, `ParseRudpEndpoint(...)`, +`CreateRudpClient(...)`, and `CreateRudpClientForPeer(...)` delegate to the +CultNet RUDP socket transport. CultMesh owns peer/authority ergonomics; CultNet +owns packet reliability, resend pressure, and channel semantics. + Clients can fetch more peers from known peers: ```csharp diff --git a/src/GameCult.Mesh/docs/public-api.md b/src/GameCult.Mesh/docs/public-api.md index 51351f51..7145d433 100644 --- a/src/GameCult.Mesh/docs/public-api.md +++ b/src/GameCult.Mesh/docs/public-api.md @@ -15,6 +15,11 @@ Namespace: `GameCult.Mesh` - `CultMesh.CreateVerseDiscoveryClient(...)` - `CultMesh.CreatePeerExchangeClient(...)` - `CultMesh.CreateAuthorityLeaseCatalog()` +- `CultMesh.ParseRudpEndpoint(...)` +- `CultMesh.CreateRudpServer(...)` +- `CultMesh.CreateRudpClient(...)` +- `CultMesh.CreateRudpClientForPeer(...)` +- `CultMesh.CreateRudpClientForAuthorizedPeer(...)` - `CultMesh.CreateSimulationFactCommitter(...)` - `CultMesh.CreateGameSession(...)` - `CultMesh.CreateClient(...)` @@ -67,7 +72,9 @@ responses to a node. The wire contracts are `CultMeshPeerExchangeClient` can fetch peer cards from known endpoints and upsert them into a local catalog. Peer cards are discovery hints; authority still requires a valid lease or -signature for the target Verse. +signature for the target Verse. `CultMeshPeerCatalog.FindAuthorized(...)` and +`FirstAuthorized(...)` compose peer lookup with +`CultMeshAuthorityLeaseCatalog.IsAuthorized(...)`. ### Authority Leases @@ -77,6 +84,15 @@ whether a peer card is authorized for a requested role and shard. This keeps peer exchange separate from authority instead of letting contact gossip mutate the world. +### RUDP Helpers + +`CultMesh.ParseRudpEndpoint(...)`, `CreateRudpServer(...)`, +`CreateRudpClient(...)`, `CreateRudpClientForPeer(...)`, and +`CreateRudpClientForAuthorizedPeer(...)` provide the branded CultMesh path to +the native CultNet RUDP socket transport. These helpers parse endpoint contact +hints and choose authorized peers; `GameCult.Networking` still owns the RUDP +packet codec, session state, resend, fragmentation, and channel semantics. + ### Shard Authority Each shard has one primary writer for now. Non-primary writes are rejected or diff --git a/tests/GameCult.Networking.Tests/NetworkingTests.cs b/tests/GameCult.Networking.Tests/NetworkingTests.cs index e360b5e4..b5efa9db 100644 --- a/tests/GameCult.Networking.Tests/NetworkingTests.cs +++ b/tests/GameCult.Networking.Tests/NetworkingTests.cs @@ -2059,6 +2059,7 @@ namespace GameCult.Networking.Tests { var now = DateTimeOffset.Parse("2026-05-20T12:00:00.0000000Z"); var catalog = CultMesh.CreateAuthorityLeaseCatalog(); + using var peers = CultMesh.CreatePeerCatalog(); var peer = new CultMeshPeerCard( "peer-primary", "aetheria-main", @@ -2066,6 +2067,9 @@ namespace GameCult.Networking.Tests roles: [CultMeshPeerRoles.ShardPrimary], shardIds: ["players-us-east"], authorityLeaseId: "lease-primary"); + peers.Upsert(peer); + + Assert.That(peers.FindAuthorized("aetheria-main", CultMeshPeerRoles.ShardPrimary, catalog, "players-us-east", now), Is.Empty); catalog.Upsert(new CultMeshAuthorityLease( "lease-primary", "aetheria-main", @@ -2078,11 +2082,98 @@ namespace GameCult.Networking.Tests signature: "sig")); Assert.That(catalog.IsAuthorized(peer, CultMeshPeerRoles.ShardPrimary, "players-us-east", now), Is.True); + Assert.That(peers.FindAuthorized("aetheria-main", CultMeshPeerRoles.ShardPrimary, catalog, "players-us-east", now).Single(), Is.SameAs(peer)); + Assert.That(peers.FirstAuthorized("aetheria-main", CultMeshPeerRoles.ShardPrimary, catalog, "players-us-east", now), Is.SameAs(peer)); + Assert.That(peers.FirstAuthorized("aetheria-main", CultMeshPeerRoles.ReadReplica, catalog, "players-us-east", now), Is.Null); Assert.That(catalog.IsAuthorized(peer, CultMeshPeerRoles.ShardPrimary, "players-eu", now), Is.False); Assert.That(catalog.IsAuthorized(peer, CultMeshPeerRoles.ReadReplica, "players-us-east", now), Is.False); Assert.That(catalog.IsAuthorized(peer, CultMeshPeerRoles.ShardPrimary, "players-us-east", now.AddMinutes(6)), Is.False); } + [Test] + public void CultMeshRudpFacade_CreatesAuthorizedClientFromPeerEndpoint() + { + var connectionId = 0x10203045u; + using var server = CultMesh.CreateRudpServer( + "csharp-cultmesh-rudp-server", + connectionId, + new CultMeshRudpSocketOptions + { + InitialSequence = 100, + ResendDelayMs = 25, + MaxFragmentBytes = 1024, + MaxPendingReliablePackets = 16 + }); + var serverPort = server.Profile.Transports[0].Port; + Assert.That(serverPort, Is.Not.Null); + var endpoint = CultMesh.ParseRudpEndpoint($"rudp://127.0.0.1:{serverPort}"); + Assert.That(endpoint.Host, Is.EqualTo("127.0.0.1")); + Assert.That(endpoint.Port, Is.EqualTo(serverPort)); + + using var peers = CultMesh.CreatePeerCatalog(); + var leases = CultMesh.CreateAuthorityLeaseCatalog(); + var now = DateTimeOffset.UtcNow; + var peer = new CultMeshPeerCard( + "csharp-cultmesh-rudp-server", + "local", + [endpoint.Uri], + roles: ["schema"], + authorityLeaseId: "lease:csharp-cultmesh-rudp-server"); + peers.Upsert(peer); + + Assert.Throws(() => CultMesh.CreateRudpClientForAuthorizedPeer( + "csharp-cultmesh-rudp-client", + connectionId, + peers, + leases, + "local", + "schema", + at: now, + options: new CultMeshRudpSocketOptions + { + ResendDelayMs = 25, + MaxFragmentBytes = 1024, + MaxPendingReliablePackets = 16 + })); + + leases.Upsert(new CultMeshAuthorityLease( + "lease:csharp-cultmesh-rudp-server", + "local", + "csharp-cultmesh-rudp-server", + ["schema"], + [], + "csharp-authority", + now.AddSeconds(-1), + now.AddSeconds(30))); + + using var client = CultMesh.CreateRudpClientForAuthorizedPeer( + "csharp-cultmesh-rudp-client", + connectionId, + peers, + leases, + "local", + "schema", + at: now, + options: new CultMeshRudpSocketOptions + { + ResendDelayMs = 25, + MaxFragmentBytes = 1024, + MaxPendingReliablePackets = 16 + }); + + client.Connect(Encoding.UTF8.GetBytes("join")); + PumpRudpHandshake(client, server); + Assert.That(client.Connected, Is.True); + Assert.That(server.Connected, Is.True); + + client.SendSchema(Encoding.UTF8.GetBytes("client-state")); + var serverFrame = ReceiveRudpFrame(server); + Assert.That(serverFrame.ChannelId, Is.EqualTo("schema")); + Assert.That(Encoding.UTF8.GetString(serverFrame.Payload), Is.EqualTo("client-state")); + Assert.That(server.Profile.Transports[0].Protocol, Is.EqualTo("rudp")); + Assert.That(client.Profile.Transports[0].Protocol, Is.EqualTo("rudp")); + } + [Test] public async Task CultMeshNode_CanEnable_DurableShardLogs_WithDefaultPath() {