Add C# CultMesh RUDP facade helpers

This commit is contained in:
Meta Vens 2026-06-16 16:57:35 +01:00
commit 6510419439
7 changed files with 379 additions and 2 deletions

View file

@ -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

View file

@ -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 |

View file

@ -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
}
}
/// <summary>
/// Parsed CultMesh RUDP endpoint.
/// </summary>
public sealed class CultMeshRudpEndpoint
{
/// <summary>
/// Creates a parsed RUDP endpoint.
/// </summary>
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;
}
/// <summary>Gets the endpoint host.</summary>
public string Host { get; }
/// <summary>Gets the endpoint port.</summary>
public int Port { get; }
/// <summary>Gets the normalized rudp:// URI.</summary>
public string Uri { get; }
}
/// <summary>
/// Options for CultMesh-branded RUDP socket helpers.
/// </summary>
public sealed class CultMeshRudpSocketOptions
{
/// <summary>Gets or sets the local bind host.</summary>
public string BindHost { get; set; } = "127.0.0.1";
/// <summary>Gets or sets the local bind port.</summary>
public int BindPort { get; set; }
/// <summary>Gets or sets a caller-owned bound socket.</summary>
public Socket? Socket { get; set; }
/// <summary>Gets or sets the first local packet sequence.</summary>
public uint InitialSequence { get; set; } = 1;
/// <summary>Gets or sets the reliable resend delay in milliseconds.</summary>
public long ResendDelayMs { get; set; } = 250;
/// <summary>Gets or sets the advertised transport id.</summary>
public string TransportId { get; set; } = "rudp";
/// <summary>Gets or sets the advertised maximum payload size.</summary>
public int? MaxPayloadBytes { get; set; }
/// <summary>Gets or sets the maximum RUDP fragment size.</summary>
public int? MaxFragmentBytes { get; set; }
/// <summary>Gets or sets the maximum pending reliable packet count.</summary>
public int? MaxPendingReliablePackets { get; set; }
/// <summary>Gets or sets the advertised reconnect policy.</summary>
public CultNetReconnectPolicy? ReconnectPolicy { get; set; }
}
/// <summary>
/// Public CultMesh entrypoints.
/// </summary>
@ -220,6 +282,139 @@ namespace GameCult.Mesh
return new CultMeshStreamCatalog();
}
/// <summary>
/// Parses a rudp://host:port endpoint into its host/port parts.
/// </summary>
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}");
}
/// <summary>
/// Creates a CultNet RUDP server transport with CultMesh-branded defaults.
/// </summary>
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
});
}
/// <summary>
/// Creates a CultNet RUDP client transport for a parsed endpoint.
/// </summary>
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
});
}
/// <summary>
/// Creates a CultNet RUDP client transport for a rudp://host:port endpoint.
/// </summary>
public static CultNetRudpSocketTransportConnection CreateRudpClient(
string runtimeId,
uint connectionId,
string endpoint,
CultMeshRudpSocketOptions? options = null)
{
return CreateRudpClient(runtimeId, connectionId, ParseRudpEndpoint(endpoint), options);
}
/// <summary>
/// Creates a CultNet RUDP client transport from a peer-card contact hint.
/// </summary>
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);
}
/// <summary>
/// Creates a CultNet RUDP client transport from the first peer authorized for a Verse role.
/// </summary>
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);
}
/// <summary>
/// Creates a committer for writing quorum simulation facts to a mesh database.
/// </summary>
@ -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}.");
}
}
}

View file

@ -190,6 +190,34 @@ namespace GameCult.Mesh
.ToArray();
}
/// <summary>Finds peers that advertise a Verse role and are authorized by the supplied lease catalog.</summary>
public IReadOnlyList<CultMeshPeerCard> 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();
}
/// <summary>Returns the first peer that advertises a Verse role and is authorized by the supplied lease catalog.</summary>
public CultMeshPeerCard? FirstAuthorized(
string verseId,
string role,
CultMeshAuthorityLeaseCatalog leases,
string? shardId = null,
DateTimeOffset? at = null)
{
return FindAuthorized(verseId, role, leases, shardId, at).FirstOrDefault();
}
/// <inheritdoc />
public void Dispose()
{

View file

@ -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

View file

@ -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

View file

@ -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<InvalidOperationException>(() => 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()
{