Add C# RUDP schema message ergonomics
This commit is contained in:
parent
601fc770ca
commit
6373f8126b
4 changed files with 422 additions and 1 deletions
|
|
@ -986,6 +986,114 @@ test("CultNet C# and TypeScript exchange schema frames when C# dials a TypeScrip
|
|||
}
|
||||
});
|
||||
|
||||
test("CultNet TypeScript and C# exchange schema-v0 MessagePack messages over RUDP", async () => {
|
||||
await buildCSharpInteropPeer();
|
||||
const csharpPeer = spawnCSharpRudpMessageServer();
|
||||
const clientSocket = await bindUdpSocket();
|
||||
let client: CultNetRudpSocketTransportConnection | undefined;
|
||||
|
||||
try {
|
||||
const csharpPort = await csharpPeer.ready;
|
||||
client = new CultNetRudpSocketTransportConnection({
|
||||
runtimeId: "ts-csharp-rudp-message-interop",
|
||||
socket: clientSocket,
|
||||
mode: "client",
|
||||
remoteHost: "127.0.0.1",
|
||||
remotePort: csharpPort,
|
||||
connectionId: 0x3355779a,
|
||||
initialSequence: 1,
|
||||
resendDelayMs: 25,
|
||||
resendPollMs: 5,
|
||||
});
|
||||
|
||||
const receivedFrame = once(client, "frame");
|
||||
client.connect(Buffer.from("ts-csharp-message-join"));
|
||||
await waitFor(() => client?.connected === true, "TypeScript RUDP client to complete C# message handshake");
|
||||
client.send("schema", Buffer.from(encode({
|
||||
schemaVersion: "cultnet.schema_catalog_request.v0",
|
||||
messageId: "ts-csharp-schema-message",
|
||||
includeSchemaJson: false,
|
||||
schemaIds: [],
|
||||
kinds: ["wire_message"],
|
||||
})));
|
||||
|
||||
const [frame] = await withTimeout(receivedFrame, 2_000, "C# RUDP schema-v0 response frame");
|
||||
assert.equal(frame.channelId, "schema");
|
||||
const message = decode(frame.payload) as {
|
||||
schemaVersion?: string;
|
||||
runtimeId?: string;
|
||||
supportsSchemaCatalog?: boolean;
|
||||
transportProfiles?: Array<{ transports?: Array<{ protocol?: string; channels?: Array<{ channelId?: string }> }> }>;
|
||||
};
|
||||
assert.equal(message.schemaVersion, "cultnet.hello.v0");
|
||||
assert.equal(message.runtimeId, "csharp-rudp-message-interop");
|
||||
assert.equal(message.supportsSchemaCatalog, true);
|
||||
assert.equal(message.transportProfiles?.[0]?.transports?.[0]?.protocol, "rudp");
|
||||
assert.equal(message.transportProfiles?.[0]?.transports?.[0]?.channels?.[0]?.channelId, "schema");
|
||||
|
||||
const [exitCode] = await withTimeout(once(csharpPeer.child, "exit"), 2_000, "C# RUDP message 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-v0 MessagePack messages when C# dials", async () => {
|
||||
await buildCSharpInteropPeer();
|
||||
const serverSocket = await bindUdpSocket();
|
||||
const server = new CultNetRudpSocketTransportConnection({
|
||||
runtimeId: "ts-csharp-rudp-message-server",
|
||||
socket: serverSocket,
|
||||
mode: "server",
|
||||
connectionId: 0x99775534,
|
||||
initialSequence: 100,
|
||||
resendDelayMs: 25,
|
||||
resendPollMs: 5,
|
||||
});
|
||||
const csharpClient = spawnCSharpRudpMessageClient(udpSocketPort(serverSocket));
|
||||
|
||||
try {
|
||||
const receivedFrame = once(server, "frame");
|
||||
const [frame] = await withTimeout(receivedFrame, 2_000, "C# RUDP schema-v0 client frame");
|
||||
assert.equal(frame.channelId, "schema");
|
||||
const message = decode(frame.payload) as {
|
||||
schemaVersion?: string;
|
||||
messageId?: string;
|
||||
kinds?: string[];
|
||||
};
|
||||
assert.equal(message.schemaVersion, "cultnet.schema_catalog_request.v0");
|
||||
assert.equal(message.messageId, "csharp-ts-schema-message");
|
||||
assert.deepEqual(message.kinds, ["wire_message"]);
|
||||
server.send("schema", Buffer.from(encode({
|
||||
schemaVersion: "cultnet.hello.v0",
|
||||
runtimeId: "ts-csharp-rudp-message-server",
|
||||
runtimeKind: "typescript",
|
||||
supportedDocumentTypes: [],
|
||||
supportedMutationContracts: [],
|
||||
supportedMessageVersions: ["cultnet.hello.v0", "cultnet.schema_catalog_request.v0"],
|
||||
transportProfiles: [],
|
||||
supportsSchemaCatalog: true,
|
||||
})));
|
||||
|
||||
const [exitCode] = await withTimeout(once(csharpClient.child, "exit"), 2_000, "C# RUDP message 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);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("CultNet TypeScript and Kotlin exchange schema frames over the shared RUDP socket transport", async () => {
|
||||
await buildKotlinInteropPeer();
|
||||
const kotlinPeer = spawnKotlinRudpServer();
|
||||
|
|
@ -1882,6 +1990,60 @@ function spawnCSharpRudpServer(options: RudpServerSpawnOptions = {}): RunningPyt
|
|||
return { child, ready, stderr };
|
||||
}
|
||||
|
||||
function spawnCSharpRudpMessageServer(): RunningPythonRudpPeer {
|
||||
const child = spawn(dotnetCommand, [
|
||||
csharpDllPath,
|
||||
"rudp-serve-message-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<number>((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 message peer emitted unexpected stdout: ${line}`));
|
||||
}
|
||||
} catch (error) {
|
||||
rejectReady(new Error(`C# RUDP message 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 message peer exited before publishing a port (code=${code}, signal=${signal}).\n${stderr.join("")}`));
|
||||
});
|
||||
child.once("error", rejectReady);
|
||||
});
|
||||
|
||||
return { child, ready, stderr };
|
||||
}
|
||||
|
||||
function spawnKotlinRudpServer(options: RudpServerSpawnOptions = {}): RunningPythonRudpPeer {
|
||||
const child = spawn(kotlinJavaCommand, [
|
||||
"-cp", kotlinClasspath,
|
||||
|
|
@ -2074,6 +2236,26 @@ function spawnCSharpRudpClient(remotePort: number): Omit<RunningPythonRudpPeer,
|
|||
return { child, stderr };
|
||||
}
|
||||
|
||||
function spawnCSharpRudpMessageClient(remotePort: number): Omit<RunningPythonRudpPeer, "ready"> {
|
||||
const child = spawn(dotnetCommand, [
|
||||
csharpDllPath,
|
||||
"rudp-dial-message-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<RunningPythonRudpPeer, "ready"> {
|
||||
const child = spawn(rustBinaryPath, [
|
||||
"rudp-dial-once",
|
||||
|
|
|
|||
|
|
@ -1284,6 +1284,47 @@ namespace GameCult.Networking
|
|||
_stats.FramesSent++;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a CultNet schema-v0 message on the reliable ordered schema channel.
|
||||
/// </summary>
|
||||
public void SendSchemaMessage<TMessage>(TMessage message)
|
||||
where TMessage : ICultNetSchemaMessage
|
||||
{
|
||||
if (message == null) throw new ArgumentNullException(nameof(message));
|
||||
Send("schema", CultNetSchemaMessageSerialization.Serialize(message));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to receive the next CultNet schema-v0 message.
|
||||
/// </summary>
|
||||
public ICultNetSchemaMessage? ReceiveSchemaMessageOnce()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
var frame = ReceiveOnce();
|
||||
if (frame == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!string.Equals(frame.ChannelId, "schema", StringComparison.Ordinal))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
return CultNetSchemaMessageSerialization.Deserialize(frame.Payload);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to receive the next CultNet schema-v0 message of the requested type.
|
||||
/// </summary>
|
||||
public TMessage? ReceiveSchemaMessageOnce<TMessage>()
|
||||
where TMessage : class, ICultNetSchemaMessage
|
||||
{
|
||||
return ReceiveSchemaMessageOnce() as TMessage;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a transport-level disconnect packet.
|
||||
/// </summary>
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ static async Task<int> ProgramMainAsync(string[] args)
|
|||
{
|
||||
if (args.Length == 0)
|
||||
{
|
||||
throw new InvalidOperationException("Expected mode: serve | probe | dial | rudp-serve-once | rudp-dial-once");
|
||||
throw new InvalidOperationException("Expected mode: serve | probe | dial | rudp-serve-once | rudp-dial-once | rudp-serve-message-once | rudp-dial-message-once");
|
||||
}
|
||||
|
||||
var mode = args[0];
|
||||
|
|
@ -43,6 +43,12 @@ static async Task<int> ProgramMainAsync(string[] args)
|
|||
case "rudp-dial-once":
|
||||
RudpDialOnce(options);
|
||||
return 0;
|
||||
case "rudp-serve-message-once":
|
||||
RudpServeMessageOnce(options);
|
||||
return 0;
|
||||
case "rudp-dial-message-once":
|
||||
RudpDialMessageOnce(options);
|
||||
return 0;
|
||||
default:
|
||||
throw new InvalidOperationException($"Unknown mode {mode}");
|
||||
}
|
||||
|
|
@ -692,6 +698,123 @@ static void RudpDialOnce(Dictionary<string, string> options)
|
|||
throw new TimeoutException("Timed out waiting for TypeScript RUDP response.");
|
||||
}
|
||||
|
||||
static void RudpServeMessageOnce(Dictionary<string, string> 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-message-interop",
|
||||
Socket = socket,
|
||||
Mode = CultNetRudpSocketMode.Server,
|
||||
ConnectionId = 0x3355779a,
|
||||
InitialSequence = 100,
|
||||
ResendDelayMs = 25
|
||||
});
|
||||
|
||||
WriteJsonLine(new
|
||||
{
|
||||
status = "ready",
|
||||
port = local.Port
|
||||
});
|
||||
|
||||
var deadline = DateTimeOffset.UtcNow.AddSeconds(5);
|
||||
while (DateTimeOffset.UtcNow < deadline)
|
||||
{
|
||||
var message = transport.ReceiveSchemaMessageOnce();
|
||||
if (message != null)
|
||||
{
|
||||
if (message is not CultNetSchemaCatalogRequestMessage request ||
|
||||
!string.Equals(request.MessageId, "ts-csharp-schema-message", StringComparison.Ordinal))
|
||||
{
|
||||
throw new InvalidOperationException($"Unexpected RUDP schema message {message.SchemaVersion}.");
|
||||
}
|
||||
|
||||
transport.SendSchemaMessage(new CultNetHelloMessage
|
||||
{
|
||||
RuntimeId = "csharp-rudp-message-interop",
|
||||
RuntimeKind = "csharp",
|
||||
DisplayName = "C# RUDP Interop",
|
||||
SupportedMessageVersions =
|
||||
[
|
||||
CultNetSchemaVersions.Hello,
|
||||
CultNetSchemaVersions.SchemaCatalogRequest
|
||||
],
|
||||
TransportProfiles = [transport.Profile],
|
||||
SupportsSchemaCatalog = true
|
||||
});
|
||||
PollRudpAfterSend(transport, TimeSpan.FromMilliseconds(250));
|
||||
WriteJsonLine(new { status = "ok" });
|
||||
return;
|
||||
}
|
||||
|
||||
transport.PollResends();
|
||||
Thread.Sleep(5);
|
||||
}
|
||||
|
||||
throw new TimeoutException("Timed out waiting for TypeScript schema-v0 message.");
|
||||
}
|
||||
|
||||
static void RudpDialMessageOnce(Dictionary<string, string> 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-message-client-interop",
|
||||
Socket = socket,
|
||||
Mode = CultNetRudpSocketMode.Client,
|
||||
RemoteEndPoint = new IPEndPoint(IPAddress.Parse(targetHost), targetPort),
|
||||
ConnectionId = 0x99775534,
|
||||
InitialSequence = 1,
|
||||
ResendDelayMs = 25
|
||||
});
|
||||
transport.Connect(Ascii("csharp-message-join"));
|
||||
|
||||
var sent = false;
|
||||
var deadline = DateTimeOffset.UtcNow.AddSeconds(5);
|
||||
while (DateTimeOffset.UtcNow < deadline)
|
||||
{
|
||||
var message = transport.ReceiveSchemaMessageOnce();
|
||||
if (message != null)
|
||||
{
|
||||
if (message is not CultNetHelloMessage hello ||
|
||||
!string.Equals(hello.RuntimeId, "ts-csharp-rudp-message-server", StringComparison.Ordinal))
|
||||
{
|
||||
throw new InvalidOperationException($"Unexpected RUDP schema message {message.SchemaVersion}.");
|
||||
}
|
||||
|
||||
WriteJsonLine(new { status = "ok" });
|
||||
return;
|
||||
}
|
||||
|
||||
transport.PollResends();
|
||||
if (transport.Connected && !sent)
|
||||
{
|
||||
transport.SendSchemaMessage(new CultNetSchemaCatalogRequestMessage
|
||||
{
|
||||
MessageId = "csharp-ts-schema-message",
|
||||
Kinds = ["wire_message"]
|
||||
});
|
||||
sent = true;
|
||||
}
|
||||
Thread.Sleep(5);
|
||||
}
|
||||
|
||||
throw new TimeoutException("Timed out waiting for TypeScript schema-v0 response.");
|
||||
}
|
||||
|
||||
static void PollRudpAfterSend(CultNetRudpSocketTransportConnection transport, TimeSpan duration)
|
||||
{
|
||||
var deadline = DateTimeOffset.UtcNow.Add(duration);
|
||||
|
|
|
|||
|
|
@ -66,6 +66,24 @@ namespace GameCult.Networking.Tests
|
|||
throw new InvalidOperationException("Unreachable.");
|
||||
}
|
||||
|
||||
private static TMessage ReceiveRudpSchemaMessage<TMessage>(CultNetRudpSocketTransportConnection transport)
|
||||
where TMessage : class, ICultNetSchemaMessage
|
||||
{
|
||||
for (var attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
var message = transport.ReceiveSchemaMessageOnce<TMessage>();
|
||||
if (message != null)
|
||||
{
|
||||
return message;
|
||||
}
|
||||
|
||||
Task.Delay(5).GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
Assert.Fail($"RUDP schema message {typeof(TMessage).Name} was not delivered.");
|
||||
throw new InvalidOperationException("Unreachable.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EncryptDecrypt_Roundtrip()
|
||||
{
|
||||
|
|
@ -646,6 +664,63 @@ namespace GameCult.Networking.Tests
|
|||
Assert.That(server.Stats.FramesReceived, Is.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RudpSocketTransport_CarriesCultNetSchemaMessages()
|
||||
{
|
||||
using var serverSocket = BindUdpSocket();
|
||||
using var clientSocket = BindUdpSocket();
|
||||
var serverEndPoint = serverSocket.LocalEndPoint!;
|
||||
const uint connectionId = 0x10203043;
|
||||
using var server = new CultNetRudpSocketTransportConnection(new CultNetRudpSocketTransportOptions
|
||||
{
|
||||
RuntimeId = "csharp-rudp-schema-server",
|
||||
Socket = serverSocket,
|
||||
Mode = CultNetRudpSocketMode.Server,
|
||||
ConnectionId = connectionId,
|
||||
InitialSequence = 100,
|
||||
ResendDelayMs = 25
|
||||
});
|
||||
using var client = new CultNetRudpSocketTransportConnection(new CultNetRudpSocketTransportOptions
|
||||
{
|
||||
RuntimeId = "csharp-rudp-schema-client",
|
||||
Socket = clientSocket,
|
||||
Mode = CultNetRudpSocketMode.Client,
|
||||
RemoteEndPoint = serverEndPoint,
|
||||
ConnectionId = connectionId,
|
||||
InitialSequence = 1,
|
||||
ResendDelayMs = 25
|
||||
});
|
||||
|
||||
client.Connect(Encoding.UTF8.GetBytes("join"));
|
||||
PumpRudpHandshake(client, server);
|
||||
|
||||
client.SendSchemaMessage(new CultNetSchemaCatalogRequestMessage
|
||||
{
|
||||
MessageId = "schema-request",
|
||||
IncludeSchemaJson = true,
|
||||
Kinds = ["wire_message"]
|
||||
});
|
||||
var request = ReceiveRudpSchemaMessage<CultNetSchemaCatalogRequestMessage>(server);
|
||||
Assert.That(request.MessageId, Is.EqualTo("schema-request"));
|
||||
Assert.That(request.IncludeSchemaJson, Is.True);
|
||||
Assert.That(request.Kinds, Is.EqualTo(new[] { "wire_message" }));
|
||||
|
||||
server.SendSchemaMessage(new CultNetHelloMessage
|
||||
{
|
||||
RuntimeId = "csharp-rudp-schema-server",
|
||||
RuntimeKind = "csharp",
|
||||
DisplayName = "C# RUDP Schema Server",
|
||||
SupportsSchemaCatalog = true,
|
||||
TransportProfiles = [server.Profile]
|
||||
});
|
||||
var hello = ReceiveRudpSchemaMessage<CultNetHelloMessage>(client);
|
||||
Assert.That(hello.RuntimeId, Is.EqualTo("csharp-rudp-schema-server"));
|
||||
Assert.That(hello.SupportsSchemaCatalog, Is.True);
|
||||
Assert.That(hello.TransportProfiles, Is.Not.Null);
|
||||
var profile = hello.TransportProfiles!.Single();
|
||||
Assert.That(profile.Transports[0].Protocol, Is.EqualTo("rudp"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RudpSocketTransport_CarriesFragmentedReliableOrderedSchemaFrames()
|
||||
{
|
||||
|
|
|
|||
Loading…
Reference in a new issue