From 3deabd706da128759c91eec3de31d1b56c25b966 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 16 Jun 2026 16:37:16 +0100 Subject: [PATCH] Add TS CultMesh RUDP factories --- docs/cultnet-transport-parity.md | 4 +- docs/runtime-parity-scope.md | 2 +- packages/cultmesh-ts/README.md | 27 +++++ packages/cultmesh-ts/src/index.ts | 123 +++++++++++++++++++++ packages/cultmesh-ts/test/cultmesh.test.ts | 70 ++++++++++++ 5 files changed, 224 insertions(+), 2 deletions(-) diff --git a/docs/cultnet-transport-parity.md b/docs/cultnet-transport-parity.md index b803ca53..72a2e622 100644 --- a/docs/cultnet-transport-parity.md +++ b/docs/cultnet-transport-parity.md @@ -320,7 +320,9 @@ Current progress: `CultMesh` facade also creates schema catalogs, built-in schema catalogs, and shard catalogs by delegating to the existing `cultnet-ts` owners, so callers do not have to leave the CultMesh entrypoint for schema discovery or shard - topology. + topology. The facade now also parses `rudp://host:port` endpoints and creates + RUDP client/server transports from endpoint or peer-card contact hints while + leaving packet/session semantics in `cultnet-ts`. - TypeScript now also has a `CultNetSchemaCatalog` for remote schema descriptors plus `CultNetPeer` request/fetch/sync helpers for `cultnet.schema_catalog_request.v0` / `cultnet.schema_catalog_response.v0`. diff --git a/docs/runtime-parity-scope.md b/docs/runtime-parity-scope.md index 7c0472ce..8867d157 100644 --- a/docs/runtime-parity-scope.md +++ b/docs/runtime-parity-scope.md @@ -32,7 +32,7 @@ CultMesh. | --- | --- | --- | --- | | 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 | | 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 ergonomics, 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 ergonomics | Full C# game session/server stack | +| 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 | 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 | | Kotlin | JVM/Android client substrate | Typed MessagePack cache, built-in schema catalog advertisement, schema/shard catalogs with shared schema-message transport fetch/sync helpers, authority leases, stream catalog, branded `CultMesh` facade, WebSocket transport profile/connection helper, RUDP client/server sugar, RUDP reconnect policy/controller and reconnect-loop helper, schema-v0 MessagePack over RUDP evidence | C# SoA store, full C# server daemon, or Unity hot-loop memory layout | diff --git a/packages/cultmesh-ts/README.md b/packages/cultmesh-ts/README.md index 5a925197..0a1b65d5 100644 --- a/packages/cultmesh-ts/README.md +++ b/packages/cultmesh-ts/README.md @@ -69,6 +69,33 @@ Schema and shard catalog factories delegate to `cultnet-ts`; the branded `CultMesh` entrypoint does not create a second owner for schema discovery or topology truth. +## RUDP Helpers + +Node runtimes can build the shared CultNet reliable-UDP transport from the +branded CultMesh entrypoint while the transport semantics stay owned by +`cultnet-ts`: + +```ts +const server = await CultMesh.createRudpServer("ts-server", 0x1020_3040); +const endpoint = CultMesh.parseRudpEndpoint( + `rudp://127.0.0.1:${server.profile.transports[0]?.port}`, +); + +const peer = { + peerId: "ts-server", + verseId: "local", + endpoints: [endpoint.uri], + roles: ["schema"], +}; + +const client = await CultMesh.createRudpClientForPeer( + "ts-client", + 0x1020_3040, + peer, +); +client.connect(new TextEncoder().encode("join")); +``` + ## Streaming Mode CultMesh streaming mode is for audio, video, tensor, and opaque byte frames that diff --git a/packages/cultmesh-ts/src/index.ts b/packages/cultmesh-ts/src/index.ts index f285d41d..1af2dc32 100644 --- a/packages/cultmesh-ts/src/index.ts +++ b/packages/cultmesh-ts/src/index.ts @@ -1,3 +1,5 @@ +import { createSocket, type Socket } from "node:dgram"; + import { CultCache, SingleFileMessagePackBackingStore, @@ -7,11 +9,13 @@ import { } from "cultcache-ts"; import { CultNetDocumentRegistry, + CultNetRudpSocketTransportConnection, CultNetSchemaCatalog, CultNetShardCatalog, cultNetBuiltinSchemaRegistry, defineCultNetDocumentBinding, type CultNetDocumentBinding, + type CultNetReconnectPolicy, type CultNetSchemaCatalogOptions, } from "cultnet-ts"; @@ -103,6 +107,26 @@ export interface CultMeshPeerCard { authorityLeaseId?: string; } +export interface CultMeshRudpEndpoint { + host: string; + port: number; + uri: string; +} + +export interface CultMeshRudpSocketOptions { + bindHost?: string; + bindPort?: number; + socket?: Socket; + initialSequence?: number; + resendDelayMs?: number; + resendPollMs?: number; + transportId?: string; + maxPayloadBytes?: number; + maxFragmentBytes?: number; + maxPendingReliablePackets?: number; + reconnectPolicy?: CultNetReconnectPolicy; +} + export class CultMeshPeerCatalog { readonly #peers = new Map(); readonly #subscribers = new Set<(peer: CultMeshPeerCard) => void>(); @@ -496,6 +520,91 @@ export class CultMesh { public static createShardCatalog(): CultNetShardCatalog { return new CultNetShardCatalog(); } + + public static parseRudpEndpoint(endpoint: string): CultMeshRudpEndpoint { + requireNonEmpty(endpoint, "endpoint"); + const parsed = new URL(endpoint); + if (parsed.protocol.toLowerCase() !== "rudp:") { + throw new Error("RUDP endpoint must use the rudp:// scheme."); + } + if (!parsed.hostname || !parsed.port) { + throw new Error("RUDP endpoint must include a host and port."); + } + const port = Number.parseInt(parsed.port, 10); + if (!Number.isInteger(port) || port <= 0 || port > 65535) { + throw new Error("RUDP endpoint port must be between 1 and 65535."); + } + const host = parsed.hostname; + const uriHost = + host.includes(":") && !host.startsWith("[") ? `[${host}]` : host; + return { host, port, uri: `rudp://${uriHost}:${port}` }; + } + + public static async createRudpServer( + runtimeId: string, + connectionId: number, + options: CultMeshRudpSocketOptions = {}, + ): Promise { + requireNonEmpty(runtimeId, "runtimeId"); + const socket = options.socket ?? (await bindRudpSocket(options)); + return new CultNetRudpSocketTransportConnection({ + runtimeId, + socket, + mode: "server", + connectionId, + initialSequence: options.initialSequence, + resendDelayMs: options.resendDelayMs, + resendPollMs: options.resendPollMs, + transportId: options.transportId, + maxPayloadBytes: options.maxPayloadBytes, + maxFragmentBytes: options.maxFragmentBytes, + maxPendingReliablePackets: options.maxPendingReliablePackets, + reconnectPolicy: options.reconnectPolicy, + }); + } + + public static async createRudpClient( + runtimeId: string, + connectionId: number, + endpoint: string | CultMeshRudpEndpoint, + options: CultMeshRudpSocketOptions = {}, + ): Promise { + requireNonEmpty(runtimeId, "runtimeId"); + const parsedEndpoint = + typeof endpoint === "string" ? CultMesh.parseRudpEndpoint(endpoint) : endpoint; + const socket = options.socket ?? (await bindRudpSocket(options)); + return new CultNetRudpSocketTransportConnection({ + runtimeId, + socket, + mode: "client", + remoteHost: parsedEndpoint.host, + remotePort: parsedEndpoint.port, + connectionId, + initialSequence: options.initialSequence, + resendDelayMs: options.resendDelayMs, + resendPollMs: options.resendPollMs, + transportId: options.transportId, + maxPayloadBytes: options.maxPayloadBytes, + maxFragmentBytes: options.maxFragmentBytes, + maxPendingReliablePackets: options.maxPendingReliablePackets, + reconnectPolicy: options.reconnectPolicy, + }); + } + + public static async createRudpClientForPeer( + runtimeId: string, + connectionId: number, + peer: CultMeshPeerCard, + options: CultMeshRudpSocketOptions = {}, + ): Promise { + const endpoint = peer.endpoints.find((value) => + value.toLowerCase().startsWith("rudp://"), + ); + if (!endpoint) { + throw new Error(`Peer ${peer.peerId} does not advertise a RUDP endpoint.`); + } + return CultMesh.createRudpClient(runtimeId, connectionId, endpoint, options); + } } function requireNonEmpty(value: string, name: string): void { @@ -504,6 +613,20 @@ function requireNonEmpty(value: string, name: string): void { } } +async function bindRudpSocket(options: CultMeshRudpSocketOptions): Promise { + const socket = createSocket("udp4"); + const host = options.bindHost ?? "127.0.0.1"; + const port = options.bindPort ?? 0; + await new Promise((resolve, reject) => { + socket.once("error", reject); + socket.bind(port, host, () => { + socket.off("error", reject); + resolve(); + }); + }); + return socket; +} + function copyBudgetFor( transport: CultMeshStreamBodyTransport, ): CultMeshStreamNegotiation["copyBudget"] { diff --git a/packages/cultmesh-ts/test/cultmesh.test.ts b/packages/cultmesh-ts/test/cultmesh.test.ts index 8d3af235..506a8f3a 100644 --- a/packages/cultmesh-ts/test/cultmesh.test.ts +++ b/packages/cultmesh-ts/test/cultmesh.test.ts @@ -17,6 +17,16 @@ const noteDocument = defineDocumentType({ name: "noteId", }); +async function waitFor(predicate: () => boolean, description: string): Promise { + 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("CultMesh TS opens a durable local node and registers document bindings", async () => { const filePath = join(await mkdtemp(join(tmpdir(), "cultmesh-ts-")), "node.ccmp"); const first = await CultMesh.startNode(filePath, { @@ -188,6 +198,66 @@ test("CultMesh TS branded facade exposes schema and shard catalogs", () => { ); }); +test("CultMesh TS branded facade creates RUDP clients from peer endpoints", async () => { + const connectionId = 0x10203044; + const server = await CultMesh.createRudpServer( + "cultmesh-ts-rudp-server", + connectionId, + { + resendDelayMs: 25, + resendPollMs: 5, + maxFragmentBytes: 1024, + maxPendingReliablePackets: 16, + }, + ); + const serverPort = server.profile.transports[0]?.port; + assert.equal(typeof serverPort, "number"); + const endpoint = CultMesh.parseRudpEndpoint(`rudp://127.0.0.1:${serverPort}`); + assert.equal(endpoint.host, "127.0.0.1"); + assert.equal(endpoint.port, serverPort); + + const peer = { + peerId: "cultmesh-ts-rudp-server", + verseId: "local", + endpoints: [endpoint.uri], + roles: ["schema"], + }; + const client = await CultMesh.createRudpClientForPeer( + "cultmesh-ts-rudp-client", + connectionId, + peer, + { + resendDelayMs: 25, + resendPollMs: 5, + maxFragmentBytes: 1024, + maxPendingReliablePackets: 16, + }, + ); + + 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, + "CultMesh RUDP 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"); + assert.equal(server.profile.transports[0]?.protocol, "rudp"); + assert.equal(client.profile.transports[0]?.protocol, "rudp"); + } finally { + client.close(); + server.close(); + } +}); + test("CultMesh TS negotiates streaming frame body transports explicitly", () => { const streams = CultMesh.createStreamCatalog(); const streamUpdates: string[] = [];