diff --git a/docs/cultnet-transport-parity.md b/docs/cultnet-transport-parity.md index 501acd44..d3161861 100644 --- a/docs/cultnet-transport-parity.md +++ b/docs/cultnet-transport-parity.md @@ -172,14 +172,15 @@ Current progress: Rust, Python, and Kotlin expose the same transport frame/stats shape through synchronous socket polling. - The TypeScript interop harness now proves bidirectional cross-runtime RUDP - socket exchange with Python and Rust: TypeScript can dial those UDP peers, - Python and Rust can dial a TypeScript UDP peer, and all sides exchange + socket exchange with C#, Python, and Rust: TypeScript can dial those UDP + peers, C#/Python/Rust can dial a TypeScript UDP peer, and all sides exchange reliable ordered `schema` frames through the shared handshake and packet language. - The remaining parity work is to deepen Python's server-side use of its port and move each runtime's existing TCP/LiteNetLib/WebSocket bodies behind those - ports, then broaden RUDP interop into the full C#/TS/Rust/Python/Kotlin loss, - reordering, fragmentation, reconnect, and schema-message matrix. + ports, then broaden RUDP interop into the full loss, reordering, + fragmentation, reconnect, and schema-message matrix. Kotlin still needs a + callable interop peer before it can join the cross-runtime socket harness. ## RUDP Packet Contract V0 diff --git a/packages/cultnet-ts/test/interop/cultnet-interop.test.ts b/packages/cultnet-ts/test/interop/cultnet-interop.test.ts index d9784f9d..705dee5e 100644 --- a/packages/cultnet-ts/test/interop/cultnet-interop.test.ts +++ b/packages/cultnet-ts/test/interop/cultnet-interop.test.ts @@ -57,6 +57,8 @@ const rustBinaryPath = resolve( ); const discoveryGroup = "239.77.44.11"; +let rustInteropPeerBuild: Promise | undefined; +let csharpInteropPeerBuild: Promise | undefined; const pythonRudpPeerScript = String.raw` import socket @@ -826,17 +828,99 @@ test("CultNet Rust and TypeScript exchange schema frames when Rust dials a TypeS } }); +test("CultNet TypeScript and C# exchange schema frames over the shared RUDP socket transport", async () => { + await buildCSharpInteropPeer(); + const csharpPeer = spawnCSharpRudpServer(); + const clientSocket = await bindUdpSocket(); + let client: CultNetRudpSocketTransportConnection | undefined; + + try { + const csharpPort = await csharpPeer.ready; + client = new CultNetRudpSocketTransportConnection({ + runtimeId: "ts-csharp-rudp-interop", + socket: clientSocket, + mode: "client", + remoteHost: "127.0.0.1", + remotePort: csharpPort, + connectionId: 0x33557799, + initialSequence: 1, + resendDelayMs: 25, + resendPollMs: 5, + }); + + const receivedFrame = once(client, "frame"); + client.connect(Buffer.from("ts-csharp-join")); + await waitFor(() => client?.connected === true, "TypeScript RUDP client to complete C# handshake"); + client.send("schema", Buffer.from("ts-csharp-client-state")); + + const [frame] = await withTimeout(receivedFrame, 2_000, "C# RUDP response frame"); + assert.equal(frame.channelId, "schema"); + assert.deepEqual(Buffer.from(frame.payload), Buffer.from("csharp-server-state")); + + const [exitCode] = await withTimeout(once(csharpPeer.child, "exit"), 2_000, "C# RUDP peer exit"); + assert.equal(exitCode, 0, csharpPeer.stderr.join("")); + } finally { + if (client) { + client.close(); + } else { + clientSocket.close(); + } + if (csharpPeer.child.exitCode === null && !csharpPeer.child.killed) { + csharpPeer.child.kill("SIGTERM"); + await once(csharpPeer.child, "exit").catch(() => undefined); + } + } +}); + +test("CultNet C# and TypeScript exchange schema frames when C# dials a TypeScript RUDP server", async () => { + await buildCSharpInteropPeer(); + const serverSocket = await bindUdpSocket(); + const server = new CultNetRudpSocketTransportConnection({ + runtimeId: "ts-csharp-rudp-server-interop", + socket: serverSocket, + mode: "server", + connectionId: 0x99775533, + initialSequence: 100, + resendDelayMs: 25, + resendPollMs: 5, + }); + const csharpClient = spawnCSharpRudpClient(udpSocketPort(serverSocket)); + + try { + const receivedFrame = once(server, "frame"); + const [frame] = await withTimeout(receivedFrame, 2_000, "C# RUDP client frame"); + assert.equal(frame.channelId, "schema"); + assert.deepEqual(Buffer.from(frame.payload), Buffer.from("csharp-client-state")); + server.send("schema", Buffer.from("ts-csharp-server-state")); + + const [exitCode] = await withTimeout(once(csharpClient.child, "exit"), 2_000, "C# RUDP client exit"); + assert.equal(exitCode, 0, csharpClient.stderr.join("")); + } finally { + server.close(); + if (csharpClient.child.exitCode === null && !csharpClient.child.killed) { + csharpClient.child.kill("SIGTERM"); + await once(csharpClient.child, "exit").catch(() => undefined); + } + } +}); + async function buildInteropPeers(): Promise { await buildRustInteropPeer(); - await execFileAsync(dotnetCommand, ["build", csharpProjectPath, "-nologo"], { - cwd: cultLibRoot, - }); + await buildCSharpInteropPeer(); } async function buildRustInteropPeer(): Promise { - await execFileAsync(cargoCommand, ["build", "--quiet", "--example", "cultnet_interop_peer"], { + rustInteropPeerBuild ??= execFileAsync(cargoCommand, ["build", "--quiet", "--example", "cultnet_interop_peer"], { cwd: cultnetRsRoot, - }); + }).then(() => undefined); + await rustInteropPeerBuild; +} + +async function buildCSharpInteropPeer(): Promise { + csharpInteropPeerBuild ??= execFileAsync(dotnetCommand, ["build", csharpProjectPath, "-nologo"], { + cwd: cultLibRoot, + }).then(() => undefined); + await csharpInteropPeerBuild; } function cleanInteropStores(runtimeIds: readonly string[]): void { @@ -1058,6 +1142,56 @@ function spawnRustRudpServer(): RunningPythonRudpPeer { return { child, ready, stderr }; } +function spawnCSharpRudpServer(): RunningPythonRudpPeer { + const child = spawn(dotnetCommand, [csharpDllPath, "rudp-serve-once", "--bind-host", "127.0.0.1"], { + cwd: cultLibRoot, + env: process.env, + stdio: ["ignore", "pipe", "pipe"], + }); + const stderr: string[] = []; + let stdoutBuffer = ""; + + const ready = new Promise((resolveReady, rejectReady) => { + child.stdout.setEncoding("utf8"); + child.stdout.on("data", (chunk: string) => { + stdoutBuffer += chunk; + while (true) { + const newline = stdoutBuffer.indexOf("\n"); + if (newline === -1) { + break; + } + + const line = stdoutBuffer.slice(0, newline).trim(); + stdoutBuffer = stdoutBuffer.slice(newline + 1); + if (!line) { + continue; + } + + try { + const parsed = JSON.parse(line) as { status?: string; port?: number }; + if (parsed.status === "ready" && typeof parsed.port === "number") { + resolveReady(parsed.port); + } else if (parsed.status !== "ok") { + rejectReady(new Error(`C# RUDP peer emitted unexpected stdout: ${line}`)); + } + } catch (error) { + rejectReady(new Error(`C# RUDP peer emitted non-JSON stdout: ${line}`)); + } + } + }); + child.stderr.setEncoding("utf8"); + child.stderr.on("data", (chunk: string) => { + stderr.push(chunk); + }); + child.once("exit", (code, signal) => { + rejectReady(new Error(`C# RUDP peer exited before publishing a port (code=${code}, signal=${signal}).\n${stderr.join("")}`)); + }); + child.once("error", rejectReady); + }); + + return { child, ready, stderr }; +} + function spawnPythonRudpClient(remotePort: number): Omit { const child = spawn(pythonCommand, ["-c", pythonRudpClientScript, String(remotePort)], { cwd: cultcachePyRoot, @@ -1073,6 +1207,26 @@ function spawnPythonRudpClient(remotePort: number): Omit { + const child = spawn(dotnetCommand, [ + csharpDllPath, + "rudp-dial-once", + "--target-host", "127.0.0.1", + "--target-port", String(remotePort), + ], { + cwd: cultLibRoot, + env: process.env, + stdio: ["ignore", "pipe", "pipe"], + }); + const stderr: string[] = []; + child.stderr.setEncoding("utf8"); + child.stderr.on("data", (chunk: string) => { + stderr.push(chunk); + }); + + return { child, stderr }; +} + function spawnRustRudpClient(remotePort: number): Omit { const child = spawn(rustBinaryPath, [ "rudp-dial-once", diff --git a/tests/GameCult.Networking.InteropPeer/Program.cs b/tests/GameCult.Networking.InteropPeer/Program.cs index 13e7d5f1..be918e2e 100644 --- a/tests/GameCult.Networking.InteropPeer/Program.cs +++ b/tests/GameCult.Networking.InteropPeer/Program.cs @@ -5,6 +5,7 @@ using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; +using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; @@ -20,7 +21,7 @@ static async Task ProgramMainAsync(string[] args) { if (args.Length == 0) { - throw new InvalidOperationException("Expected mode: serve | probe | dial"); + throw new InvalidOperationException("Expected mode: serve | probe | dial | rudp-serve-once | rudp-dial-once"); } var mode = args[0]; @@ -36,6 +37,12 @@ static async Task ProgramMainAsync(string[] args) case "dial": await DialAsync(ParseDialConfig(options)); return 0; + case "rudp-serve-once": + RudpServeOnce(options); + return 0; + case "rudp-dial-once": + RudpDialOnce(options); + return 0; default: throw new InvalidOperationException($"Unknown mode {mode}"); } @@ -570,6 +577,106 @@ static CultNetTransportProfile CreateTcpFramedTransportProfile(string runtimeId, }); } +static void RudpServeOnce(Dictionary options) +{ + var bindHost = options.TryGetValue("bind-host", out var configuredBindHost) ? configuredBindHost : "127.0.0.1"; + var bindPort = options.TryGetValue("bind-port", out var configuredBindPort) + ? int.Parse(configuredBindPort, CultureInfo.InvariantCulture) + : 0; + + using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + socket.Bind(new IPEndPoint(IPAddress.Parse(bindHost), bindPort)); + socket.ReceiveTimeout = 20; + var local = (IPEndPoint)socket.LocalEndPoint!; + using var transport = new CultNetRudpSocketTransportConnection(new CultNetRudpSocketTransportOptions + { + RuntimeId = "csharp-rudp-interop", + Socket = socket, + Mode = CultNetRudpSocketMode.Server, + ConnectionId = 0x33557799, + InitialSequence = 100, + ResendDelayMs = 25 + }); + + WriteJsonLine(new + { + status = "ready", + port = local.Port + }); + + var deadline = DateTimeOffset.UtcNow.AddSeconds(5); + while (DateTimeOffset.UtcNow < deadline) + { + var frame = transport.ReceiveOnce(); + if (frame != null) + { + RequireRudpFrame(frame, "schema", "ts-csharp-client-state"); + transport.Send("schema", Ascii("csharp-server-state")); + WriteJsonLine(new { status = "ok" }); + return; + } + + transport.PollResends(); + Thread.Sleep(5); + } + + throw new TimeoutException("Timed out waiting for TypeScript RUDP frame."); +} + +static void RudpDialOnce(Dictionary options) +{ + var targetHost = RequireArg(options, "target-host"); + var targetPort = ParseIntArg(options, "target-port"); + + using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); + socket.ReceiveTimeout = 20; + using var transport = new CultNetRudpSocketTransportConnection(new CultNetRudpSocketTransportOptions + { + RuntimeId = "csharp-rudp-client-interop", + Socket = socket, + Mode = CultNetRudpSocketMode.Client, + RemoteEndPoint = new IPEndPoint(IPAddress.Parse(targetHost), targetPort), + ConnectionId = 0x99775533, + InitialSequence = 1, + ResendDelayMs = 25 + }); + transport.Connect(Ascii("csharp-join")); + + var sent = false; + var deadline = DateTimeOffset.UtcNow.AddSeconds(5); + while (DateTimeOffset.UtcNow < deadline) + { + var frame = transport.ReceiveOnce(); + if (frame != null) + { + RequireRudpFrame(frame, "schema", "ts-csharp-server-state"); + WriteJsonLine(new { status = "ok" }); + return; + } + + transport.PollResends(); + if (transport.Connected && !sent) + { + transport.Send("schema", Ascii("csharp-client-state")); + sent = true; + } + Thread.Sleep(5); + } + + throw new TimeoutException("Timed out waiting for TypeScript RUDP response."); +} + +static void RequireRudpFrame(CultNetTransportFrame frame, string expectedChannelId, string expectedPayload) +{ + if (!string.Equals(frame.ChannelId, expectedChannelId, StringComparison.Ordinal) + || !frame.Payload.SequenceEqual(Ascii(expectedPayload))) + { + throw new InvalidOperationException( + $"Unexpected RUDP frame: channel={frame.ChannelId}, payload={Convert.ToHexString(frame.Payload)}."); + } +} + static async Task SendMessageAsync( TcpFramedTransportConnection transport, TMessage message, @@ -800,6 +907,11 @@ static void WriteJsonLine(object value) Console.Out.WriteLine(JsonSerializer.Serialize(value, InteropPeerShared.JsonOptions)); } +static byte[] Ascii(string value) +{ + return Encoding.ASCII.GetBytes(value); +} + static void WriteLog(string @event, object payload) { Console.Error.WriteLine(JsonSerializer.Serialize(new Dictionary