diff --git a/docs/cultnet-transport-parity.md b/docs/cultnet-transport-parity.md index d9248f13..0ebe3cab 100644 --- a/docs/cultnet-transport-parity.md +++ b/docs/cultnet-transport-parity.md @@ -24,7 +24,7 @@ CultNet owns cross-runtime transport semantics: | Runtime | Current data transport | Discovery | Transport authority today | | --- | --- | --- | --- | -| C# `GameCult.Networking` | LiteNetLib UDP `NetManager` / `NetPeer`; sends legacy union messages and schema-v0 messages with `DeliveryMethod.ReliableOrdered` | LiteNetLib connection requests and app-level peer/catalog surfaces | C# owns the production-shaped realtime semantics | +| C# `GameCult.Networking` | LiteNetLib UDP `NetManager` / `NetPeer`; sends legacy union messages and schema-v0 messages with `DeliveryMethod.ReliableOrdered`; single-peer RUDP socket transport exists in the library | LiteNetLib connection requests and app-level peer/catalog surfaces | Production LiteNetLib path plus UDP socket binding for the shared RUDP reliability owner | | C# interop peer | TCP stream with 4-byte length-prefixed MessagePack frames | UDP multicast probe/announce | Test harness only | | TypeScript `cultnet-ts` | `CultNetPeer` over any Node `Duplex`, TCP-framed transport, or single-peer RUDP socket transport; interop uses TCP | UDP multicast probe/announce in the interop peer | First UDP socket binding for the shared RUDP reliability owner | | Rust `cultnet-rs` | Interop example uses TCP length-prefixed MessagePack frames; single-peer RUDP socket transport exists in the library | UDP multicast probe/announce | UDP socket binding for the shared RUDP reliability owner | @@ -165,16 +165,15 @@ Current progress: ack/ack-mask accounting, reliable resend scheduling, duplicate suppression, and reliable ordered channel delivery. It is in-memory and socket-free so the behavior can be tested before any runtime binds it to UDP I/O. -- TypeScript, Rust, and Python now have socket-backed RUDP transport +- C#, TypeScript, Rust, and Python now have socket-backed RUDP transport connections that bind a single UDP peer to the shared RUDP session. TypeScript emits the same `frame` events as the TCP-framed transport and can carry - `CultNetPeer` schema messages over reliable ordered `schema` frames; Rust and - Python expose the same transport frame/stats shape through synchronous socket - polling. + `CultNetPeer` schema messages over reliable ordered `schema` frames; C#, + Rust, and Python expose the same transport frame/stats shape through + synchronous socket polling. - The remaining parity work is to add the equivalent port to Kotlin, deepen Python's server-side use of its port, and move each runtime's existing - TCP/LiteNetLib/WebSocket bodies behind those ports, then bind the shared RUDP - reliability state machine to UDP sockets in C#. + TCP/LiteNetLib/WebSocket bodies behind those ports. ## RUDP Packet Contract V0 diff --git a/src/GameCult.Networking/CultNetTransport.cs b/src/GameCult.Networking/CultNetTransport.cs index 81fa400a..e9b08871 100644 --- a/src/GameCult.Networking/CultNetTransport.cs +++ b/src/GameCult.Networking/CultNetTransport.cs @@ -3,6 +3,8 @@ using System.Buffers.Binary; using System.Collections.Generic; using System.Linq; using System.IO; +using System.Net; +using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -486,6 +488,68 @@ namespace GameCult.Networking public long NowMs { get; set; } } + /// + /// Role for a single-peer CultNet RUDP socket transport. + /// + public enum CultNetRudpSocketMode + { + /// + /// Initiates the connect packet. + /// + Client, + /// + /// Accepts the first connect packet from a remote endpoint. + /// + Server + } + + /// + /// Options for binding a CultNet RUDP session to a UDP socket. + /// + public sealed class CultNetRudpSocketTransportOptions + { + /// + /// Gets or sets the runtime id advertised by this transport. + /// + public string RuntimeId { get; set; } = string.Empty; + /// + /// Gets or sets the bound UDP socket. + /// + public Socket Socket { get; set; } = null!; + /// + /// Gets or sets whether this side initiates or accepts the handshake. + /// + public CultNetRudpSocketMode Mode { get; set; } + /// + /// Gets or sets the expected remote endpoint. Servers may leave this unset until the first connect packet. + /// + public EndPoint? RemoteEndPoint { get; set; } + /// + /// Gets or sets the RUDP connection/session binding id. + /// + public uint ConnectionId { get; set; } + /// + /// Gets or sets the first local packet sequence. + /// + public uint InitialSequence { get; set; } = 1; + /// + /// Gets or sets the 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 maximum payload size for RUDP channels. + /// + public int? MaxPayloadBytes { get; set; } + /// + /// Gets or sets the maximum fragment size for RUDP channels. + /// + public int? MaxFragmentBytes { get; set; } + } + /// /// Socket-free reliability state machine for CultNet RUDP. /// @@ -821,6 +885,205 @@ namespace GameCult.Networking } } + /// + /// Single-peer UDP socket binding for the CultNet RUDP reliability session. + /// + public sealed class CultNetRudpSocketTransportConnection : IDisposable + { + private readonly Socket _socket; + private readonly CultNetRudpSession _session; + private readonly CultNetRudpSocketMode _mode; + private readonly CultNetTransportStats _stats = new CultNetTransportStats(); + private readonly Queue _deliveredFrames = new Queue(); + private EndPoint? _remoteEndPoint; + private bool _disposed; + + /// + /// Initializes a UDP socket binding around a CultNet RUDP session. + /// + public CultNetRudpSocketTransportConnection(CultNetRudpSocketTransportOptions options) + { + if (options == null) throw new ArgumentNullException(nameof(options)); + if (string.IsNullOrWhiteSpace(options.RuntimeId)) throw new ArgumentException("Runtime id is required.", nameof(options)); + _socket = options.Socket ?? throw new ArgumentNullException(nameof(options.Socket)); + _mode = options.Mode; + _remoteEndPoint = options.RemoteEndPoint; + _session = new CultNetRudpSession(new CultNetRudpSessionOptions + { + ConnectionId = options.ConnectionId, + InitialSequence = options.InitialSequence, + ResendDelayMs = options.ResendDelayMs + }); + + var local = _socket.LocalEndPoint as IPEndPoint; + Profile = CultNetTransportProfiles.CreateRudp( + options.RuntimeId, + new RudpTransportProfileOptions + { + TransportId = options.TransportId, + Host = local?.Address.ToString(), + Port = local?.Port, + MaxPayloadBytes = options.MaxPayloadBytes, + MaxFragmentBytes = options.MaxFragmentBytes + }); + } + + /// + /// Gets the profile this connection implements. + /// + public CultNetTransportProfile Profile { get; } + + /// + /// Gets whether the RUDP handshake has completed. + /// + public bool Connected => _session.Connected; + + /// + /// Gets a snapshot of the current transfer counters. + /// + public CultNetTransportStats Stats => _stats.Snapshot(); + + /// + /// Sends the client connect packet. + /// + public void Connect(byte[]? payload = null) + { + if (_mode != CultNetRudpSocketMode.Client) + { + throw new InvalidOperationException("Only a client RUDP socket transport can initiate connect."); + } + + SendPacket(_session.CreateConnect(NowMs(), payload ?? Array.Empty())); + } + + /// + /// Sends a logical transport frame through the RUDP session. + /// + public void Send(string channelId, byte[] payload) + { + var packet = _session.Send(channelId, payload, ChannelSendOptions(channelId)); + SendPacket(packet); + _stats.FramesSent++; + } + + /// + /// Polls the UDP socket once and returns the next delivered transport frame if one is available. + /// + public CultNetTransportFrame? ReceiveOnce() + { + if (_deliveredFrames.Count > 0) + { + return _deliveredFrames.Dequeue(); + } + + var buffer = new byte[65535]; + EndPoint remote = new IPEndPoint(IPAddress.Any, 0); + int received; + try + { + received = _socket.ReceiveFrom(buffer, ref remote); + } + catch (SocketException error) when ( + error.SocketErrorCode == SocketError.WouldBlock || + error.SocketErrorCode == SocketError.TimedOut) + { + return null; + } + + _stats.BytesReceived += received; + if (_remoteEndPoint == null) + { + _remoteEndPoint = remote; + } + else if (!_remoteEndPoint.Equals(remote)) + { + return null; + } + + var wire = new byte[received]; + Array.Copy(buffer, wire, received); + var packet = CultNetRudpPacketCodec.Decode(wire); + if (_mode == CultNetRudpSocketMode.Server && packet.PacketType == CultNetRudpPacketType.Connect) + { + SendPacket(_session.AcceptConnect(packet, NowMs())); + return null; + } + + var result = _session.Receive(packet, NowMs()); + if (result.Reply != null) + { + SendPacket(result.Reply); + } + + foreach (var frame in result.Delivered) + { + _deliveredFrames.Enqueue(new CultNetTransportFrame + { + ChannelId = frame.ChannelId, + Payload = frame.Payload + }); + _stats.FramesReceived++; + } + + var delivered = _deliveredFrames.Count > 0 ? _deliveredFrames.Dequeue() : null; + if (packet.PacketType == CultNetRudpPacketType.Accept || delivered != null) + { + SendPacket(_session.CreateAck()); + } + + return delivered; + } + + /// + /// Sends any reliable packets whose resend timers are due. + /// + public void PollResends() + { + foreach (var packet in _session.DueResends(NowMs())) + { + SendPacket(packet); + } + } + + /// + public void Dispose() + { + if (_disposed) + { + return; + } + + _disposed = true; + _socket.Dispose(); + } + + private void SendPacket(CultNetRudpPacket packet) + { + if (_remoteEndPoint == null) + { + throw new InvalidOperationException("RUDP socket transport does not have a remote endpoint."); + } + + var wire = CultNetRudpPacketCodec.Encode(packet); + var sent = _socket.SendTo(wire, _remoteEndPoint); + _stats.BytesSent += sent; + } + + private static CultNetRudpSendOptions ChannelSendOptions(string channelId) + { + return string.Equals(channelId, "schema", StringComparison.Ordinal) + ? new CultNetRudpSendOptions { Reliable = true, Ordered = true, NowMs = NowMs() } + : string.Equals(channelId, "latest", StringComparison.Ordinal) + ? new CultNetRudpSendOptions { Sequenced = true, NowMs = NowMs() } + : new CultNetRudpSendOptions { NowMs = NowMs() }; + } + + private static long NowMs() + { + return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + } + } + /// /// Transport connection for the current TCP length-prefixed CultNet schema lane. /// diff --git a/tests/GameCult.Networking.Tests/NetworkingTests.cs b/tests/GameCult.Networking.Tests/NetworkingTests.cs index ba673e34..e613f61d 100644 --- a/tests/GameCult.Networking.Tests/NetworkingTests.cs +++ b/tests/GameCult.Networking.Tests/NetworkingTests.cs @@ -3,6 +3,8 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Net; +using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading.Tasks; @@ -19,6 +21,51 @@ namespace GameCult.Networking.Tests private static readonly ServerSecurityOptions DevelopmentServerSecurity = ServerSecurityOptions.Development(); private static readonly ClientSecurityOptions DevelopmentClientSecurity = ClientSecurityOptions.Development(); + private static Socket BindUdpSocket() + { + var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); + socket.ReceiveTimeout = 20; + return socket; + } + + private static void PumpRudpHandshake( + CultNetRudpSocketTransportConnection client, + CultNetRudpSocketTransportConnection server) + { + for (var attempt = 0; attempt < 20; attempt++) + { + server.ReceiveOnce(); + client.ReceiveOnce(); + server.ReceiveOnce(); + if (client.Connected && server.Connected) + { + return; + } + + Task.Delay(5).GetAwaiter().GetResult(); + } + + Assert.Fail("RUDP socket handshake did not complete."); + } + + private static CultNetTransportFrame ReceiveRudpFrame(CultNetRudpSocketTransportConnection transport) + { + for (var attempt = 0; attempt < 20; attempt++) + { + var frame = transport.ReceiveOnce(); + if (frame != null) + { + return frame; + } + + Task.Delay(5).GetAwaiter().GetResult(); + } + + Assert.Fail("RUDP socket frame was not delivered."); + throw new InvalidOperationException("Unreachable."); + } + [Test] public void EncryptDecrypt_Roundtrip() { @@ -447,6 +494,52 @@ namespace GameCult.Networking.Tests Is.EqualTo(new[] { "second", "third" })); } + [Test] + public void RudpSocketTransport_HandshakesAndCarriesReliableOrderedSchemaFrames() + { + using var serverSocket = BindUdpSocket(); + using var clientSocket = BindUdpSocket(); + var serverEndPoint = serverSocket.LocalEndPoint!; + const uint connectionId = 0x10203040; + using var server = new CultNetRudpSocketTransportConnection(new CultNetRudpSocketTransportOptions + { + RuntimeId = "csharp-rudp-server", + Socket = serverSocket, + Mode = CultNetRudpSocketMode.Server, + ConnectionId = connectionId, + InitialSequence = 100, + ResendDelayMs = 25 + }); + using var client = new CultNetRudpSocketTransportConnection(new CultNetRudpSocketTransportOptions + { + RuntimeId = "csharp-rudp-client", + Socket = clientSocket, + Mode = CultNetRudpSocketMode.Client, + RemoteEndPoint = serverEndPoint, + ConnectionId = connectionId, + InitialSequence = 1, + ResendDelayMs = 25 + }); + + client.Connect(Encoding.UTF8.GetBytes("join")); + PumpRudpHandshake(client, server); + Assert.That(client.Connected, Is.True); + Assert.That(server.Connected, Is.True); + + client.Send("schema", 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")); + + server.Send("schema", Encoding.UTF8.GetBytes("server-state")); + var clientFrame = ReceiveRudpFrame(client); + Assert.That(clientFrame.ChannelId, Is.EqualTo("schema")); + Assert.That(Encoding.UTF8.GetString(clientFrame.Payload), Is.EqualTo("server-state")); + Assert.That(server.Profile.Transports[0].Protocol, Is.EqualTo("rudp")); + Assert.That(client.Stats.FramesSent, Is.EqualTo(1)); + Assert.That(server.Stats.FramesReceived, Is.EqualTo(1)); + } + [Test] public void CultNetSchemaMessageSerialization_RoundTrips_RawSnapshotResponse() {