Add TypeScript RUDP socket transport
This commit is contained in:
parent
343802dacf
commit
7335435255
5 changed files with 377 additions and 52 deletions
|
|
@ -26,7 +26,7 @@ CultNet owns cross-runtime transport semantics:
|
|||
| --- | --- | --- | --- |
|
||||
| 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# 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`; interop uses TCP | UDP multicast probe/announce in the interop peer | Byte-stream abstraction plus socket-free RUDP reliability owner; no UDP socket binding yet |
|
||||
| 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 | UDP multicast probe/announce | Example harness plus socket-free RUDP reliability owner; no UDP socket binding yet |
|
||||
| Python `cultcache-py` | TCP sockets with 4-byte length-prefixed MessagePack frames for local CultMesh/CultNet server and client | Endpoint lists and CultMesh peer/Verse catalogs | Local framed service body plus socket-free RUDP reliability owner; no UDP socket binding yet |
|
||||
| Kotlin `cultmesh-kotlin` | Minimal WebSocket-like lane over TCP socket | None found in the live package | Thin client surface |
|
||||
|
|
@ -165,10 +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 now has the first socket-backed RUDP transport connection:
|
||||
`CultNetRudpSocketTransportConnection` binds a single UDP peer to the shared
|
||||
RUDP session, emits the same `frame` events as the TCP-framed transport, and
|
||||
can carry `CultNetPeer` schema messages over reliable ordered `schema`
|
||||
frames.
|
||||
- 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.
|
||||
reliability state machine to UDP sockets in C#, Rust, and Python.
|
||||
|
||||
## RUDP Packet Contract V0
|
||||
|
||||
|
|
|
|||
|
|
@ -70,10 +70,12 @@ export {
|
|||
decodeRudpPacket,
|
||||
encodeRudpPacket,
|
||||
CultNetRudpSession,
|
||||
CultNetRudpSocketTransportConnection,
|
||||
type CultNetRudpDeliveredFrame,
|
||||
type CultNetRudpPacket,
|
||||
type CultNetRudpPacketType,
|
||||
type CultNetRudpReceiveResult,
|
||||
type CultNetRudpSocketTransportOptions,
|
||||
type CultNetRudpSessionOptions,
|
||||
type RudpTransportProfileOptions,
|
||||
} from "./rudp";
|
||||
|
|
|
|||
|
|
@ -1,4 +1,8 @@
|
|||
import { EventEmitter } from "node:events";
|
||||
import { type RemoteInfo, type Socket } from "node:dgram";
|
||||
|
||||
import type { CultNetTransportProfile } from "./contracts";
|
||||
import type { CultNetTransportConnection, CultNetTransportFrame, CultNetTransportStats } from "./transport";
|
||||
|
||||
const RUDP_MAGIC = [0x43, 0x4e, 0x52, 0x30] as const; // CNR0
|
||||
const RUDP_VERSION = 0;
|
||||
|
|
@ -60,6 +64,21 @@ export interface RudpTransportProfileOptions {
|
|||
maxFragmentBytes?: number;
|
||||
}
|
||||
|
||||
export interface CultNetRudpSocketTransportOptions {
|
||||
runtimeId: string;
|
||||
socket: Socket;
|
||||
mode: "client" | "server";
|
||||
remoteHost?: string;
|
||||
remotePort?: number;
|
||||
connectionId: number;
|
||||
initialSequence?: number;
|
||||
resendDelayMs?: number;
|
||||
resendPollMs?: number;
|
||||
transportId?: string;
|
||||
maxPayloadBytes?: number;
|
||||
maxFragmentBytes?: number;
|
||||
}
|
||||
|
||||
const packetTypeToCode: Record<CultNetRudpPacketType, number> = {
|
||||
connect: 1,
|
||||
accept: 2,
|
||||
|
|
@ -336,48 +355,202 @@ export class CultNetRudpSession {
|
|||
}
|
||||
}
|
||||
|
||||
export class CultNetRudpSocketTransportConnection extends EventEmitter implements CultNetTransportConnection {
|
||||
readonly profile: CultNetTransportProfile;
|
||||
readonly #socket: Socket;
|
||||
readonly #session: CultNetRudpSession;
|
||||
readonly #mode: "client" | "server";
|
||||
readonly #resendTimer: NodeJS.Timeout;
|
||||
#remoteHost: string | undefined;
|
||||
#remotePort: number | undefined;
|
||||
#closed = false;
|
||||
readonly #stats: CultNetTransportStats = {
|
||||
bytesReceived: 0,
|
||||
bytesSent: 0,
|
||||
framesReceived: 0,
|
||||
framesSent: 0,
|
||||
};
|
||||
|
||||
constructor(options: CultNetRudpSocketTransportOptions) {
|
||||
super();
|
||||
this.#socket = options.socket;
|
||||
this.#mode = options.mode;
|
||||
this.#remoteHost = options.remoteHost;
|
||||
this.#remotePort = options.remotePort;
|
||||
this.#session = new CultNetRudpSession({
|
||||
connectionId: options.connectionId,
|
||||
initialSequence: options.initialSequence,
|
||||
resendDelayMs: options.resendDelayMs,
|
||||
});
|
||||
const address = this.#socket.address();
|
||||
const localPort = typeof address === "string" ? undefined : address.port;
|
||||
const localHost = typeof address === "string" ? undefined : address.address;
|
||||
this.profile = createRudpTransportProfile(options.runtimeId, {
|
||||
transportId: options.transportId,
|
||||
host: localHost,
|
||||
port: localPort,
|
||||
maxPayloadBytes: options.maxPayloadBytes,
|
||||
maxFragmentBytes: options.maxFragmentBytes,
|
||||
});
|
||||
|
||||
this.#socket.on("message", (wire, remote) => this.#receiveDatagram(wire, remote));
|
||||
this.#socket.on("close", () => {
|
||||
this.#closed = true;
|
||||
clearInterval(this.#resendTimer);
|
||||
this.emit("close");
|
||||
});
|
||||
this.#socket.on("error", (error) => this.emit("error", error instanceof Error ? error : new Error(String(error))));
|
||||
this.#resendTimer = setInterval(() => this.#sendDueResends(), options.resendPollMs ?? 25);
|
||||
this.#resendTimer.unref?.();
|
||||
}
|
||||
|
||||
get connected(): boolean {
|
||||
return this.#session.connected;
|
||||
}
|
||||
|
||||
get stats(): CultNetTransportStats {
|
||||
return { ...this.#stats };
|
||||
}
|
||||
|
||||
connect(payload = new Uint8Array()): void {
|
||||
if (this.#mode !== "client") {
|
||||
throw new Error("Only a client RUDP socket transport can initiate connect.");
|
||||
}
|
||||
this.#sendPacket(this.#session.createConnect(Date.now(), payload));
|
||||
}
|
||||
|
||||
send(channelId: string, payload: Uint8Array): void {
|
||||
const packet = this.#session.send(channelId, payload, {
|
||||
...channelOptions(channelId),
|
||||
nowMs: Date.now(),
|
||||
});
|
||||
this.#sendPacket(packet);
|
||||
this.#stats.framesSent += 1;
|
||||
}
|
||||
|
||||
close(): void {
|
||||
clearInterval(this.#resendTimer);
|
||||
if (!this.#closed) {
|
||||
this.#closed = true;
|
||||
this.#socket.close();
|
||||
}
|
||||
}
|
||||
|
||||
#receiveDatagram(wire: Buffer, remote: RemoteInfo): void {
|
||||
this.#stats.bytesReceived += wire.length;
|
||||
let packet: CultNetRudpPacket;
|
||||
try {
|
||||
packet = decodeRudpPacket(wire);
|
||||
} catch (error) {
|
||||
this.emit("error", error instanceof Error ? error : new Error(String(error)));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.#remoteHost || this.#remotePort === undefined) {
|
||||
this.#remoteHost = remote.address;
|
||||
this.#remotePort = remote.port;
|
||||
} else if (remote.address !== this.#remoteHost || remote.port !== this.#remotePort) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (this.#mode === "server" && packet.packetType === "connect") {
|
||||
this.#sendPacket(this.#session.acceptConnect(packet, Date.now()));
|
||||
return;
|
||||
}
|
||||
|
||||
const result = this.#session.receive(packet, Date.now());
|
||||
if (result.reply) {
|
||||
this.#sendPacket(result.reply);
|
||||
}
|
||||
for (const frame of result.delivered) {
|
||||
this.#stats.framesReceived += 1;
|
||||
this.emit("frame", {
|
||||
channelId: frame.channelId,
|
||||
payload: frame.payload,
|
||||
} satisfies CultNetTransportFrame);
|
||||
}
|
||||
if (packet.packetType === "accept" || result.delivered.length > 0) {
|
||||
this.#sendPacket(this.#session.createAck());
|
||||
}
|
||||
} catch (error) {
|
||||
this.emit("error", error instanceof Error ? error : new Error(String(error)));
|
||||
}
|
||||
}
|
||||
|
||||
#sendDueResends(): void {
|
||||
for (const packet of this.#session.dueResends(Date.now())) {
|
||||
this.#sendPacket(packet);
|
||||
}
|
||||
}
|
||||
|
||||
#sendPacket(packet: CultNetRudpPacket): void {
|
||||
if (!this.#remoteHost || this.#remotePort === undefined) {
|
||||
throw new Error("RUDP socket transport does not have a remote endpoint.");
|
||||
}
|
||||
const wire = encodeRudpPacket(packet);
|
||||
this.#stats.bytesSent += wire.length;
|
||||
this.#socket.send(wire, this.#remotePort, this.#remoteHost);
|
||||
}
|
||||
}
|
||||
|
||||
export function createRudpTransportProfile(
|
||||
runtimeId: string,
|
||||
options: RudpTransportProfileOptions = {},
|
||||
): CultNetTransportProfile {
|
||||
const channel = (
|
||||
channelId: string,
|
||||
delivery: "reliable" | "unreliable",
|
||||
ordering: "ordered" | "unordered" | "sequenced",
|
||||
): CultNetTransportProfile["transports"][number]["channels"][number] => {
|
||||
const value: CultNetTransportProfile["transports"][number]["channels"][number] = {
|
||||
channelId,
|
||||
delivery,
|
||||
ordering,
|
||||
};
|
||||
if (options.maxPayloadBytes !== undefined) {
|
||||
value.maxPayloadBytes = options.maxPayloadBytes;
|
||||
}
|
||||
if (options.maxFragmentBytes !== undefined) {
|
||||
value.maxFragmentBytes = options.maxFragmentBytes;
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
const transport: CultNetTransportProfile["transports"][number] = {
|
||||
transportId: options.transportId ?? "rudp",
|
||||
protocol: "rudp",
|
||||
wireContracts: ["cultnet.schema.v0"],
|
||||
channels: [
|
||||
channel("schema", "reliable", "ordered"),
|
||||
channel("latest", "unreliable", "sequenced"),
|
||||
channel("realtime", "unreliable", "unordered"),
|
||||
],
|
||||
};
|
||||
if (options.host !== undefined) {
|
||||
transport.host = options.host;
|
||||
}
|
||||
if (options.port !== undefined) {
|
||||
transport.port = options.port;
|
||||
}
|
||||
|
||||
return {
|
||||
schemaVersion: "cultnet.transport_profile.v0",
|
||||
runtimeId,
|
||||
transports: [
|
||||
{
|
||||
transportId: options.transportId ?? "rudp",
|
||||
protocol: "rudp",
|
||||
host: options.host,
|
||||
port: options.port,
|
||||
wireContracts: ["cultnet.schema.v0"],
|
||||
channels: [
|
||||
{
|
||||
channelId: "schema",
|
||||
delivery: "reliable",
|
||||
ordering: "ordered",
|
||||
maxPayloadBytes: options.maxPayloadBytes,
|
||||
maxFragmentBytes: options.maxFragmentBytes,
|
||||
},
|
||||
{
|
||||
channelId: "latest",
|
||||
delivery: "unreliable",
|
||||
ordering: "sequenced",
|
||||
maxPayloadBytes: options.maxPayloadBytes,
|
||||
maxFragmentBytes: options.maxFragmentBytes,
|
||||
},
|
||||
{
|
||||
channelId: "realtime",
|
||||
delivery: "unreliable",
|
||||
ordering: "unordered",
|
||||
maxPayloadBytes: options.maxPayloadBytes,
|
||||
maxFragmentBytes: options.maxFragmentBytes,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
transports: [transport],
|
||||
};
|
||||
}
|
||||
|
||||
function channelOptions(channelId: string): { reliable: boolean; ordered: boolean; sequenced: boolean } {
|
||||
if (channelId === "schema") {
|
||||
return { reliable: true, ordered: true, sequenced: false };
|
||||
}
|
||||
if (channelId === "latest") {
|
||||
return { reliable: false, ordered: false, sequenced: true };
|
||||
}
|
||||
return { reliable: false, ordered: false, sequenced: false };
|
||||
}
|
||||
|
||||
export function encodeRudpPacket(packet: CultNetRudpPacket): Uint8Array {
|
||||
const channelId = new TextEncoder().encode(packet.channelId);
|
||||
if (channelId.length > MAX_CHANNEL_ID_BYTES) {
|
||||
|
|
|
|||
|
|
@ -45,27 +45,35 @@ export function createTcpFramedTransportProfile(
|
|||
runtimeId: string,
|
||||
options: TcpFramedTransportProfileOptions = {},
|
||||
): CultNetTransportProfile {
|
||||
const channel: CultNetTransportProfile["transports"][number]["channels"][number] = {
|
||||
channelId: "schema",
|
||||
delivery: "reliable",
|
||||
ordering: "ordered",
|
||||
};
|
||||
if (options.maxPayloadBytes !== undefined) {
|
||||
channel.maxPayloadBytes = options.maxPayloadBytes;
|
||||
}
|
||||
if (options.maxFragmentBytes !== undefined) {
|
||||
channel.maxFragmentBytes = options.maxFragmentBytes;
|
||||
}
|
||||
|
||||
const transport: CultNetTransportProfile["transports"][number] = {
|
||||
transportId: options.transportId ?? "tcp-framed",
|
||||
protocol: "tcp_framed",
|
||||
wireContracts: ["cultnet.schema.v0"],
|
||||
channels: [channel],
|
||||
};
|
||||
if (options.host !== undefined) {
|
||||
transport.host = options.host;
|
||||
}
|
||||
if (options.port !== undefined) {
|
||||
transport.port = options.port;
|
||||
}
|
||||
|
||||
return {
|
||||
schemaVersion: "cultnet.transport_profile.v0",
|
||||
runtimeId,
|
||||
transports: [
|
||||
{
|
||||
transportId: options.transportId ?? "tcp-framed",
|
||||
protocol: "tcp_framed",
|
||||
host: options.host,
|
||||
port: options.port,
|
||||
wireContracts: ["cultnet.schema.v0"],
|
||||
channels: [
|
||||
{
|
||||
channelId: "schema",
|
||||
delivery: "reliable",
|
||||
ordering: "ordered",
|
||||
maxPayloadBytes: options.maxPayloadBytes,
|
||||
maxFragmentBytes: options.maxFragmentBytes,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
transports: [transport],
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { Duplex } from "node:stream";
|
||||
import dgram, { type Socket } from "node:dgram";
|
||||
import { rmSync, mkdtempSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
|
|
@ -17,6 +18,7 @@ import {
|
|||
CultNetDocumentRegistry,
|
||||
CultNetPeer,
|
||||
CultNetRudpSession,
|
||||
CultNetRudpSocketTransportConnection,
|
||||
CultNetSchemaRegistry,
|
||||
CultNetSecret,
|
||||
CultNetServerSecurityOptions,
|
||||
|
|
@ -74,6 +76,28 @@ function createDuplexPair(): { a: Duplex; b: Duplex } {
|
|||
return { a, b };
|
||||
}
|
||||
|
||||
async function bindUdpSocket(): Promise<Socket> {
|
||||
const socket = dgram.createSocket("udp4");
|
||||
await new Promise<void>((resolve) => socket.bind(0, "127.0.0.1", resolve));
|
||||
return socket;
|
||||
}
|
||||
|
||||
function udpPort(socket: Socket): number {
|
||||
const address = socket.address();
|
||||
assert.notEqual(typeof address, "string");
|
||||
return address.port;
|
||||
}
|
||||
|
||||
async function waitFor(predicate: () => boolean, description: string): Promise<void> {
|
||||
const startedAt = Date.now();
|
||||
while (!predicate()) {
|
||||
if (Date.now() - startedAt > 1_000) {
|
||||
throw new Error(`Timed out waiting for ${description}.`);
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
}
|
||||
}
|
||||
|
||||
test("CultNet secret helpers round-trip encrypted strings and validate sessions", () => {
|
||||
const serverSecurity = CultNetServerSecurityOptions.development();
|
||||
const clientSecurity = serverSecurity.toClientOptions();
|
||||
|
|
@ -335,6 +359,119 @@ test("rudp session suppresses duplicates and delivers reliable ordered payloads
|
|||
]);
|
||||
});
|
||||
|
||||
test("rudp socket transport handshakes and carries reliable ordered schema frames over UDP", async () => {
|
||||
const serverSocket = await bindUdpSocket();
|
||||
const clientSocket = await bindUdpSocket();
|
||||
const connectionId = 0x10203040;
|
||||
const server = new CultNetRudpSocketTransportConnection({
|
||||
runtimeId: "rudp-server",
|
||||
socket: serverSocket,
|
||||
mode: "server",
|
||||
connectionId,
|
||||
initialSequence: 100,
|
||||
resendDelayMs: 25,
|
||||
resendPollMs: 5,
|
||||
});
|
||||
const client = new CultNetRudpSocketTransportConnection({
|
||||
runtimeId: "rudp-client",
|
||||
socket: clientSocket,
|
||||
mode: "client",
|
||||
remoteHost: "127.0.0.1",
|
||||
remotePort: udpPort(serverSocket),
|
||||
connectionId,
|
||||
initialSequence: 1,
|
||||
resendDelayMs: 25,
|
||||
resendPollMs: 5,
|
||||
});
|
||||
|
||||
try {
|
||||
const serverFrame = new Promise<{ channelId: string; payload: Uint8Array }>((resolve, reject) => {
|
||||
server.once("frame", resolve);
|
||||
server.once("error", reject);
|
||||
});
|
||||
client.connect(Buffer.from("join", "utf8"));
|
||||
await waitFor(() => client.connected && server.connected, "RUDP socket handshake");
|
||||
client.send("schema", Buffer.from("client-state", "utf8"));
|
||||
|
||||
const receivedByServer = await serverFrame;
|
||||
assert.equal(receivedByServer.channelId, "schema");
|
||||
assert.equal(Buffer.from(receivedByServer.payload).toString("utf8"), "client-state");
|
||||
|
||||
const clientFrame = new Promise<{ channelId: string; payload: Uint8Array }>((resolve, reject) => {
|
||||
client.once("frame", resolve);
|
||||
client.once("error", reject);
|
||||
});
|
||||
server.send("schema", Buffer.from("server-state", "utf8"));
|
||||
const receivedByClient = await clientFrame;
|
||||
assert.equal(receivedByClient.channelId, "schema");
|
||||
assert.equal(Buffer.from(receivedByClient.payload).toString("utf8"), "server-state");
|
||||
assert.equal(client.stats.framesSent, 1);
|
||||
assert.equal(server.stats.framesReceived, 1);
|
||||
assert.equal(server.profile.transports[0]?.protocol, "rudp");
|
||||
} finally {
|
||||
client.close();
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("CultNet peer can speak schema messages through the RUDP socket transport", async () => {
|
||||
const serverSocket = await bindUdpSocket();
|
||||
const clientSocket = await bindUdpSocket();
|
||||
const connectionId = 0x50607080;
|
||||
const serverTransport = new CultNetRudpSocketTransportConnection({
|
||||
runtimeId: "rudp-peer-server",
|
||||
socket: serverSocket,
|
||||
mode: "server",
|
||||
connectionId,
|
||||
initialSequence: 500,
|
||||
resendDelayMs: 25,
|
||||
resendPollMs: 5,
|
||||
});
|
||||
const clientTransport = new CultNetRudpSocketTransportConnection({
|
||||
runtimeId: "rudp-peer-client",
|
||||
socket: clientSocket,
|
||||
mode: "client",
|
||||
remoteHost: "127.0.0.1",
|
||||
remotePort: udpPort(serverSocket),
|
||||
connectionId,
|
||||
initialSequence: 10,
|
||||
resendDelayMs: 25,
|
||||
resendPollMs: 5,
|
||||
});
|
||||
|
||||
try {
|
||||
const sender = new CultNetPeer(clientTransport, { wireContract: "cultnet.schema.v0" });
|
||||
const receiver = new CultNetPeer(serverTransport, { wireContract: "cultnet.schema.v0" });
|
||||
clientTransport.connect();
|
||||
await waitFor(() => clientTransport.connected && serverTransport.connected, "RUDP peer socket handshake");
|
||||
|
||||
const message = await new Promise<ReturnType<typeof parseCultNetMessage>>((resolve, reject) => {
|
||||
receiver.once("message", resolve);
|
||||
receiver.once("invalidMessage", reject);
|
||||
clientTransport.once("error", reject);
|
||||
serverTransport.once("error", reject);
|
||||
sender.sendHello({
|
||||
schemaVersion: "cultnet.hello.v0",
|
||||
runtimeId: "rudp-peer-client",
|
||||
runtimeKind: "node-worker",
|
||||
transportProfiles: [clientTransport.profile],
|
||||
});
|
||||
});
|
||||
|
||||
assert.equal(message.schemaVersion, "cultnet.hello.v0");
|
||||
if (message.schemaVersion === "cultnet.hello.v0") {
|
||||
assert.equal(message.runtimeId, "rudp-peer-client");
|
||||
assert.equal(message.transportProfiles?.[0]?.transports[0]?.protocol, "rudp");
|
||||
}
|
||||
|
||||
sender.close();
|
||||
receiver.close();
|
||||
} finally {
|
||||
clientTransport.close();
|
||||
serverTransport.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("CultNet peer can speak through a transport connection", async () => {
|
||||
const { a, b } = createDuplexPair();
|
||||
const leftTransport = new TcpFramedTransportConnection(a, createTcpFramedTransportProfile("left"));
|
||||
|
|
|
|||
Loading…
Reference in a new issue