diff --git a/docs/cultnet-transport-parity.md b/docs/cultnet-transport-parity.md index e790393d..f723e319 100644 --- a/docs/cultnet-transport-parity.md +++ b/docs/cultnet-transport-parity.md @@ -154,21 +154,23 @@ Current progress: `TcpFramedTransportConnection` with schema-channel `send`, `receive`, and transfer stats. The Rust interop peer advertises and uses that shared port instead of owning raw TCP frame I/O directly. -- TypeScript now has the first `cultnet.transport.rudp.v0` packet codec and a - deterministic reliable ordered data-packet fixture. This is not the RUDP - runtime yet; it is the binary packet language the runtimes must converge on. +- TypeScript, C#, Rust, and Python now share the first + `cultnet.transport.rudp.v0` packet codec fixture: the same reliable ordered + fragmented data packet encodes to the same bytes in every runtime. This is not + the RUDP runtime yet; it is the binary packet language the runtimes must + converge on before resend loops, windows, and timeout behavior are allowed to + claim parity. - 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, port the RUDP packet - fixture into C#/Rust/Python, then implement `rudp`. + TCP/LiteNetLib/WebSocket bodies behind those ports, then implement `rudp`. ## RUDP Packet Contract V0 `cultnet.transport.rudp.v0` packets start with a fixed binary header, followed by a UTF-8 channel id and payload bytes. All integer fields are unsigned -big-endian. The first deterministic fixture lives in TypeScript and must be -ported byte-for-byte before runtime-specific resend loops are allowed to claim -parity. +big-endian. The first deterministic fixture is live in TypeScript, C#, Rust, +and Python; every future runtime must port it byte-for-byte before +runtime-specific resend loops are allowed to claim parity. | Offset | Size | Field | Notes | | --- | ---: | --- | --- | diff --git a/packages/cultcache-py/src/cultnet_py/__init__.py b/packages/cultcache-py/src/cultnet_py/__init__.py index 4b33e74e..b2b14fb8 100644 --- a/packages/cultcache-py/src/cultnet_py/__init__.py +++ b/packages/cultcache-py/src/cultnet_py/__init__.py @@ -66,10 +66,15 @@ from .shard_replication import ( from .snapshot import CultNetRawDocumentRecord, CultNetRawSnapshotResponse from .subscription import CultNetDatabaseChange from .transport import ( + CultNetRudpPacket, + CultNetRudpPacketType, CultNetTransportFrame, CultNetTransportStats, TcpFramedTransportConnection, + create_rudp_transport_profile, create_tcp_framed_transport_profile, + decode_rudp_packet, + encode_rudp_packet, ) from .simulation import ( CultNetSimulationConsensus, @@ -118,6 +123,8 @@ __all__ = [ "CultNetSimulationConsensusOptions", "CultNetSimulationObservation", "CultNetSimulationObservationHub", + "CultNetRudpPacket", + "CultNetRudpPacketType", "CultNetTransportFrame", "CultNetTransportStats", "TcpFramedTransportConnection", @@ -126,15 +133,18 @@ __all__ = [ "apply_raw_snapshot", "apply_shard_log_response", "compute_simulation_claim_hash", + "create_rudp_transport_profile", "create_tcp_framed_transport_profile", "database_subscribe", "database_unsubscribe", "decode_witness_artifact_bundle_payload", "decode_frame", + "decode_rudp_packet", "document_delete", "document_put_raw", "encode_witness_artifact_bundle_payload", "encode_frame", + "encode_rudp_packet", "hello", "INTEROP_WIRE_CONTRACT", "login", diff --git a/packages/cultcache-py/src/cultnet_py/transport.py b/packages/cultcache-py/src/cultnet_py/transport.py index 3053825e..ccd92f2b 100644 --- a/packages/cultcache-py/src/cultnet_py/transport.py +++ b/packages/cultcache-py/src/cultnet_py/transport.py @@ -1,10 +1,16 @@ from __future__ import annotations from dataclasses import dataclass +from enum import Enum from typing import Any, BinaryIO from .framing import read_frame, write_frame +RUDP_MAGIC = b"CNR0" +RUDP_VERSION = 0 +RUDP_FIXED_HEADER_BYTES = 36 +MAX_RUDP_CHANNEL_ID_BYTES = 255 + @dataclass(frozen=True) class CultNetTransportStats: @@ -57,6 +63,176 @@ def create_tcp_framed_transport_profile( } +class CultNetRudpPacketType(str, Enum): + CONNECT = "connect" + ACCEPT = "accept" + DATA = "data" + ACK = "ack" + PING = "ping" + PONG = "pong" + DISCONNECT = "disconnect" + + +@dataclass(frozen=True) +class CultNetRudpPacket: + packet_type: CultNetRudpPacketType + connection_id: int + sequence: int + ack: int + ack_mask: int + channel_id: str + reliable: bool = False + ordered: bool = False + sequenced: bool = False + fragment_id: int = 0 + fragment_index: int = 0 + fragment_count: int = 0 + payload: bytes = b"" + + +_RUDP_PACKET_TYPE_TO_CODE = { + CultNetRudpPacketType.CONNECT: 1, + CultNetRudpPacketType.ACCEPT: 2, + CultNetRudpPacketType.DATA: 3, + CultNetRudpPacketType.ACK: 4, + CultNetRudpPacketType.PING: 5, + CultNetRudpPacketType.PONG: 6, + CultNetRudpPacketType.DISCONNECT: 7, +} +_RUDP_PACKET_TYPE_FROM_CODE = {value: key for key, value in _RUDP_PACKET_TYPE_TO_CODE.items()} + + +def create_rudp_transport_profile( + runtime_id: str, + *, + transport_id: str = "rudp", + host: str | None = None, + port: int | None = None, + max_payload_bytes: int | None = None, + max_fragment_bytes: int | None = None, +) -> dict[str, Any]: + def channel(channel_id: str, delivery: str, ordering: str) -> dict[str, Any]: + value: dict[str, Any] = { + "channelId": channel_id, + "delivery": delivery, + "ordering": ordering, + } + if max_payload_bytes is not None: + value["maxPayloadBytes"] = max_payload_bytes + if max_fragment_bytes is not None: + value["maxFragmentBytes"] = max_fragment_bytes + return value + + transport: dict[str, Any] = { + "transportId": transport_id, + "protocol": "rudp", + "wireContracts": ["cultnet.schema.v0"], + "channels": [ + channel("schema", "reliable", "ordered"), + channel("latest", "unreliable", "sequenced"), + channel("realtime", "unreliable", "unordered"), + ], + } + if host is not None: + transport["host"] = host + if port is not None: + transport["port"] = port + + return { + "schemaVersion": "cultnet.transport_profile.v0", + "runtimeId": runtime_id, + "transports": [transport], + } + + +def encode_rudp_packet(packet: CultNetRudpPacket) -> bytes: + channel_id = packet.channel_id.encode("utf-8") + if len(channel_id) > MAX_RUDP_CHANNEL_ID_BYTES: + raise ValueError("CultNet RUDP channel id cannot exceed 255 UTF-8 bytes") + payload = bytes(packet.payload) + header_bytes = RUDP_FIXED_HEADER_BYTES + len(channel_id) + return b"".join( + [ + RUDP_MAGIC, + RUDP_VERSION.to_bytes(1, "big"), + _RUDP_PACKET_TYPE_TO_CODE[packet.packet_type].to_bytes(1, "big"), + _encode_rudp_flags(packet).to_bytes(1, "big"), + header_bytes.to_bytes(1, "big"), + _uint32(packet.connection_id, "connection_id").to_bytes(4, "big"), + _uint32(packet.sequence, "sequence").to_bytes(4, "big"), + _uint32(packet.ack, "ack").to_bytes(4, "big"), + _uint32(packet.ack_mask, "ack_mask").to_bytes(4, "big"), + _uint16(packet.fragment_id, "fragment_id").to_bytes(2, "big"), + _uint16(packet.fragment_index, "fragment_index").to_bytes(2, "big"), + _uint16(packet.fragment_count, "fragment_count").to_bytes(2, "big"), + _uint32(len(payload), "payload length").to_bytes(4, "big"), + len(channel_id).to_bytes(1, "big"), + b"\x00", + channel_id, + payload, + ] + ) + + +def decode_rudp_packet(wire: bytes) -> CultNetRudpPacket: + if len(wire) < RUDP_FIXED_HEADER_BYTES: + raise ValueError("CultNet RUDP packet is shorter than the fixed header") + if wire[:4] != RUDP_MAGIC: + raise ValueError("CultNet RUDP packet has the wrong magic") + if wire[4] != RUDP_VERSION: + raise ValueError(f"Unsupported CultNet RUDP packet version {wire[4]}") + try: + packet_type = _RUDP_PACKET_TYPE_FROM_CODE[wire[5]] + except KeyError as error: + raise ValueError(f"Unsupported CultNet RUDP packet type {wire[5]}") from error + + header_bytes = wire[7] + channel_id_length = wire[34] + if header_bytes != RUDP_FIXED_HEADER_BYTES + channel_id_length: + raise ValueError("CultNet RUDP packet header length does not match the channel id length") + payload_length = int.from_bytes(wire[30:34], "big") + if len(wire) != header_bytes + payload_length: + raise ValueError("CultNet RUDP packet payload length does not match the packet size") + + flags = wire[6] + return CultNetRudpPacket( + packet_type=packet_type, + connection_id=int.from_bytes(wire[8:12], "big"), + sequence=int.from_bytes(wire[12:16], "big"), + ack=int.from_bytes(wire[16:20], "big"), + ack_mask=int.from_bytes(wire[20:24], "big"), + fragment_id=int.from_bytes(wire[24:26], "big"), + fragment_index=int.from_bytes(wire[26:28], "big"), + fragment_count=int.from_bytes(wire[28:30], "big"), + channel_id=wire[RUDP_FIXED_HEADER_BYTES:header_bytes].decode("utf-8"), + reliable=bool(flags & 0b0000_0001), + ordered=bool(flags & 0b0000_0010), + sequenced=bool(flags & 0b0000_0100), + payload=wire[header_bytes:], + ) + + +def _encode_rudp_flags(packet: CultNetRudpPacket) -> int: + return ( + (0b0000_0001 if packet.reliable else 0) + | (0b0000_0010 if packet.ordered else 0) + | (0b0000_0100 if packet.sequenced else 0) + | (0b0000_1000 if packet.fragment_count > 0 else 0) + ) + + +def _uint32(value: int, field_name: str) -> int: + if value < 0 or value > 0xFFFFFFFF: + raise ValueError(f"CultNet RUDP {field_name} must fit in uint32") + return value + + +def _uint16(value: int, field_name: str) -> int: + if value < 0 or value > 0xFFFF: + raise ValueError(f"CultNet RUDP {field_name} must fit in uint16") + return value + + class TcpFramedTransportConnection: def __init__(self, stream: BinaryIO, *, profile: dict[str, Any]) -> None: self.stream = stream diff --git a/packages/cultcache-py/tests/test_cultcache.py b/packages/cultcache-py/tests/test_cultcache.py index 0d2c27ca..3fd06289 100644 --- a/packages/cultcache-py/tests/test_cultcache.py +++ b/packages/cultcache-py/tests/test_cultcache.py @@ -67,19 +67,24 @@ from cultnet_py import ( CultNetSimulationConsensusCandidate, CultNetSimulationObservation, CultNetSimulationObservationHub, + CultNetRudpPacket, + CultNetRudpPacketType, TcpFramedTransportConnection, CultNetWitnessArtifactBundle, apply_raw_document_record, apply_raw_snapshot, apply_shard_log_response, + create_rudp_transport_profile, create_tcp_framed_transport_profile, database_subscribe, database_unsubscribe, decode_frame, + decode_rudp_packet, decode_witness_artifact_bundle_payload, document_delete, document_put_raw, encode_frame, + encode_rudp_packet, encode_witness_artifact_bundle_payload, hello, login, @@ -580,6 +585,67 @@ class CultCacheTests(unittest.TestCase): self.assertEqual(receiver.stats.bytes_received, len(payload) + 4) self.assertEqual(receiver.profile["transports"][0]["protocol"], "tcp_framed") + def test_cultnet_rudp_packet_codec_uses_deterministic_reliable_ordered_fixture(self) -> None: + encoded = encode_rudp_packet( + CultNetRudpPacket( + packet_type=CultNetRudpPacketType.DATA, + connection_id=0x01020304, + sequence=0x0000002A, + ack=0x00000029, + ack_mask=0x80000001, + channel_id="schema", + reliable=True, + ordered=True, + fragment_id=7, + fragment_index=1, + fragment_count=3, + payload=b"hello", + ) + ) + + self.assertEqual( + encoded.hex(), + "434e523000030b2a010203040000002a0000002980000001000700010003000000050600736368656d6168656c6c6f", + ) + + decoded = decode_rudp_packet(encoded) + self.assertEqual(decoded.packet_type, CultNetRudpPacketType.DATA) + self.assertEqual(decoded.connection_id, 0x01020304) + self.assertEqual(decoded.sequence, 0x0000002A) + self.assertEqual(decoded.ack, 0x00000029) + self.assertEqual(decoded.ack_mask, 0x80000001) + self.assertEqual(decoded.channel_id, "schema") + self.assertTrue(decoded.reliable) + self.assertTrue(decoded.ordered) + self.assertFalse(decoded.sequenced) + self.assertEqual(decoded.fragment_id, 7) + self.assertEqual(decoded.fragment_index, 1) + self.assertEqual(decoded.fragment_count, 3) + self.assertEqual(decoded.payload, b"hello") + + def test_cultnet_rudp_transport_profile_advertises_state_and_realtime_channels(self) -> None: + profile = create_rudp_transport_profile( + "python-rudp", + transport_id="public-rudp", + host="127.0.0.1", + port=7777, + max_payload_bytes=1200, + max_fragment_bytes=1000, + ) + + self.assertEqual(profile["transports"][0]["protocol"], "rudp") + self.assertEqual( + [ + (channel["channelId"], channel["delivery"], channel["ordering"]) + for channel in profile["transports"][0]["channels"] + ], + [ + ("schema", "reliable", "ordered"), + ("latest", "unreliable", "sequenced"), + ("realtime", "unreliable", "unordered"), + ], + ) + def test_cultnet_database_subscription_helpers_match_schema_v0_shape(self) -> None: subscribe = database_subscribe( message_id="sub-message", diff --git a/packages/cultnet-rs/src/lib.rs b/packages/cultnet-rs/src/lib.rs index 6c087bd2..bc804d39 100644 --- a/packages/cultnet-rs/src/lib.rs +++ b/packages/cultnet-rs/src/lib.rs @@ -1,6 +1,7 @@ mod contracts; mod framing; mod replication; +mod rudp; mod schema_discovery; mod security; mod transport; @@ -8,6 +9,7 @@ mod transport; pub use contracts::*; pub use framing::*; pub use replication::*; +pub use rudp::*; pub use schema_discovery::*; pub use security::*; pub use transport::*; diff --git a/packages/cultnet-rs/src/rudp.rs b/packages/cultnet-rs/src/rudp.rs new file mode 100644 index 00000000..dc35559f --- /dev/null +++ b/packages/cultnet-rs/src/rudp.rs @@ -0,0 +1,207 @@ +use anyhow::Result; +use anyhow::anyhow; + +use crate::CultNetTransportChannel; +use crate::CultNetTransportDelivery; +use crate::CultNetTransportDescriptor; +use crate::CultNetTransportOrdering; +use crate::CultNetTransportProfile; +use crate::CultNetTransportProtocol; + +const RUDP_MAGIC: [u8; 4] = [0x43, 0x4e, 0x52, 0x30]; +const RUDP_VERSION: u8 = 0; +const RUDP_FIXED_HEADER_BYTES: usize = 36; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CultNetRudpPacketType { + Connect, + Accept, + Data, + Ack, + Ping, + Pong, + Disconnect, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CultNetRudpPacket { + pub packet_type: CultNetRudpPacketType, + pub connection_id: u32, + pub sequence: u32, + pub ack: u32, + pub ack_mask: u32, + pub channel_id: String, + pub reliable: bool, + pub ordered: bool, + pub sequenced: bool, + pub fragment_id: u16, + pub fragment_index: u16, + pub fragment_count: u16, + pub payload: Vec, +} + +#[derive(Clone, Debug, Default)] +pub struct RudpTransportProfileOptions { + pub transport_id: Option, + pub host: Option, + pub port: Option, + pub max_payload_bytes: Option, + pub max_fragment_bytes: Option, +} + +pub fn create_rudp_transport_profile( + runtime_id: impl Into, + options: RudpTransportProfileOptions, +) -> CultNetTransportProfile { + CultNetTransportProfile { + schema_version: "cultnet.transport_profile.v0".to_string(), + runtime_id: runtime_id.into(), + transports: vec![CultNetTransportDescriptor { + transport_id: options.transport_id.unwrap_or_else(|| "rudp".to_string()), + protocol: CultNetTransportProtocol::Rudp, + host: options.host, + port: options.port, + path: None, + discovery_group: None, + wire_contracts: Some(vec!["cultnet.schema.v0".to_string()]), + channels: vec![ + CultNetTransportChannel { + channel_id: "schema".to_string(), + delivery: CultNetTransportDelivery::Reliable, + ordering: CultNetTransportOrdering::Ordered, + max_payload_bytes: options.max_payload_bytes, + max_fragment_bytes: options.max_fragment_bytes, + }, + CultNetTransportChannel { + channel_id: "latest".to_string(), + delivery: CultNetTransportDelivery::Unreliable, + ordering: CultNetTransportOrdering::Sequenced, + max_payload_bytes: options.max_payload_bytes, + max_fragment_bytes: options.max_fragment_bytes, + }, + CultNetTransportChannel { + channel_id: "realtime".to_string(), + delivery: CultNetTransportDelivery::Unreliable, + ordering: CultNetTransportOrdering::Unordered, + max_payload_bytes: options.max_payload_bytes, + max_fragment_bytes: options.max_fragment_bytes, + }, + ], + }], + } +} + +pub fn encode_rudp_packet(packet: &CultNetRudpPacket) -> Result> { + let channel_id = packet.channel_id.as_bytes(); + if channel_id.len() > u8::MAX as usize { + return Err(anyhow!( + "CultNet RUDP channel id cannot exceed 255 UTF-8 bytes" + )); + } + + let header_bytes = RUDP_FIXED_HEADER_BYTES + channel_id.len(); + let mut wire = vec![0_u8; header_bytes + packet.payload.len()]; + wire[..4].copy_from_slice(&RUDP_MAGIC); + wire[4] = RUDP_VERSION; + wire[5] = packet_type_to_code(packet.packet_type); + wire[6] = encode_flags(packet); + wire[7] = header_bytes as u8; + wire[8..12].copy_from_slice(&packet.connection_id.to_be_bytes()); + wire[12..16].copy_from_slice(&packet.sequence.to_be_bytes()); + wire[16..20].copy_from_slice(&packet.ack.to_be_bytes()); + wire[20..24].copy_from_slice(&packet.ack_mask.to_be_bytes()); + wire[24..26].copy_from_slice(&packet.fragment_id.to_be_bytes()); + wire[26..28].copy_from_slice(&packet.fragment_index.to_be_bytes()); + wire[28..30].copy_from_slice(&packet.fragment_count.to_be_bytes()); + wire[30..34].copy_from_slice(&(packet.payload.len() as u32).to_be_bytes()); + wire[34] = channel_id.len() as u8; + wire[35] = 0; + wire[RUDP_FIXED_HEADER_BYTES..header_bytes].copy_from_slice(channel_id); + wire[header_bytes..].copy_from_slice(&packet.payload); + Ok(wire) +} + +pub fn decode_rudp_packet(wire: &[u8]) -> Result { + if wire.len() < RUDP_FIXED_HEADER_BYTES { + return Err(anyhow!( + "CultNet RUDP packet is shorter than the fixed header" + )); + } + if wire[..4] != RUDP_MAGIC { + return Err(anyhow!("CultNet RUDP packet has the wrong magic")); + } + if wire[4] != RUDP_VERSION { + return Err(anyhow!( + "Unsupported CultNet RUDP packet version {}", + wire[4] + )); + } + + let packet_type = packet_type_from_code(wire[5])?; + let header_bytes = wire[7] as usize; + let channel_id_len = wire[34] as usize; + if header_bytes != RUDP_FIXED_HEADER_BYTES + channel_id_len { + return Err(anyhow!( + "CultNet RUDP packet header length does not match the channel id length" + )); + } + let payload_len = u32::from_be_bytes(wire[30..34].try_into()?) as usize; + if wire.len() != header_bytes + payload_len { + return Err(anyhow!( + "CultNet RUDP packet payload length does not match the packet size" + )); + } + + let flags = wire[6]; + Ok(CultNetRudpPacket { + packet_type, + reliable: (flags & 0b0000_0001) != 0, + ordered: (flags & 0b0000_0010) != 0, + sequenced: (flags & 0b0000_0100) != 0, + connection_id: u32::from_be_bytes(wire[8..12].try_into()?), + sequence: u32::from_be_bytes(wire[12..16].try_into()?), + ack: u32::from_be_bytes(wire[16..20].try_into()?), + ack_mask: u32::from_be_bytes(wire[20..24].try_into()?), + fragment_id: u16::from_be_bytes(wire[24..26].try_into()?), + fragment_index: u16::from_be_bytes(wire[26..28].try_into()?), + fragment_count: u16::from_be_bytes(wire[28..30].try_into()?), + channel_id: String::from_utf8(wire[RUDP_FIXED_HEADER_BYTES..header_bytes].to_vec())?, + payload: wire[header_bytes..].to_vec(), + }) +} + +fn encode_flags(packet: &CultNetRudpPacket) -> u8 { + (if packet.reliable { 0b0000_0001 } else { 0 }) + | (if packet.ordered { 0b0000_0010 } else { 0 }) + | (if packet.sequenced { 0b0000_0100 } else { 0 }) + | (if packet.fragment_count > 0 { + 0b0000_1000 + } else { + 0 + }) +} + +fn packet_type_to_code(packet_type: CultNetRudpPacketType) -> u8 { + match packet_type { + CultNetRudpPacketType::Connect => 1, + CultNetRudpPacketType::Accept => 2, + CultNetRudpPacketType::Data => 3, + CultNetRudpPacketType::Ack => 4, + CultNetRudpPacketType::Ping => 5, + CultNetRudpPacketType::Pong => 6, + CultNetRudpPacketType::Disconnect => 7, + } +} + +fn packet_type_from_code(code: u8) -> Result { + match code { + 1 => Ok(CultNetRudpPacketType::Connect), + 2 => Ok(CultNetRudpPacketType::Accept), + 3 => Ok(CultNetRudpPacketType::Data), + 4 => Ok(CultNetRudpPacketType::Ack), + 5 => Ok(CultNetRudpPacketType::Ping), + 6 => Ok(CultNetRudpPacketType::Pong), + 7 => Ok(CultNetRudpPacketType::Disconnect), + _ => Err(anyhow!("Unsupported CultNet RUDP packet type {code}")), + } +} diff --git a/packages/cultnet-rs/tests/cultnet.rs b/packages/cultnet-rs/tests/cultnet.rs index ae9d76aa..a0037fc4 100644 --- a/packages/cultnet-rs/tests/cultnet.rs +++ b/packages/cultnet-rs/tests/cultnet.rs @@ -11,6 +11,8 @@ use cultnet_rs::CultNetDocumentPutOptions; use cultnet_rs::CultNetDocumentRegistry; use cultnet_rs::CultNetMessage; use cultnet_rs::CultNetMutationAuthority; +use cultnet_rs::CultNetRudpPacket; +use cultnet_rs::CultNetRudpPacketType; use cultnet_rs::CultNetSchemaKind; use cultnet_rs::CultNetSchemaRegistry; use cultnet_rs::CultNetSecret; @@ -26,11 +28,14 @@ use cultnet_rs::LengthPrefixedMessageFramer; use cultnet_rs::TcpFramedTransportConnection; use cultnet_rs::TcpFramedTransportProfileOptions; use cultnet_rs::builtin_schema_registry; +use cultnet_rs::create_rudp_transport_profile; use cultnet_rs::create_tcp_framed_transport_profile; use cultnet_rs::decode_cultnet_message_from_slice; +use cultnet_rs::decode_rudp_packet; use cultnet_rs::encode_cultnet_message_for_wire; use cultnet_rs::encode_cultnet_message_to_vec; use cultnet_rs::encode_frame; +use cultnet_rs::encode_rudp_packet; use pretty_assertions::assert_eq; const TS_HELLO_FRAME: &[u8] = include_bytes!("fixtures/cultnet-ts-hello.frame"); @@ -167,6 +172,99 @@ fn tcp_framed_transport_carries_schema_payloads_with_stats() -> Result<()> { Ok(()) } +#[test] +fn rudp_packet_codec_uses_deterministic_reliable_ordered_fixture() -> Result<()> { + let encoded = encode_rudp_packet(&CultNetRudpPacket { + packet_type: CultNetRudpPacketType::Data, + connection_id: 0x01020304, + sequence: 0x0000002a, + ack: 0x00000029, + ack_mask: 0x80000001, + channel_id: "schema".to_string(), + reliable: true, + ordered: true, + sequenced: false, + fragment_id: 7, + fragment_index: 1, + fragment_count: 3, + payload: b"hello".to_vec(), + })?; + + assert_eq!( + encoded, + vec![ + 67, 78, 82, 48, 0, 3, 11, 42, 1, 2, 3, 4, 0, 0, 0, 42, 0, 0, 0, 41, 128, 0, 0, 1, 0, 7, + 0, 1, 0, 3, 0, 0, 0, 5, 6, 0, 115, 99, 104, 101, 109, 97, 104, 101, 108, 108, 111, + ] + ); + + let decoded = decode_rudp_packet(&encoded)?; + assert_eq!(decoded.packet_type, CultNetRudpPacketType::Data); + assert_eq!(decoded.connection_id, 0x01020304); + assert_eq!(decoded.sequence, 0x0000002a); + assert_eq!(decoded.ack, 0x00000029); + assert_eq!(decoded.ack_mask, 0x80000001); + assert_eq!(decoded.channel_id, "schema"); + assert!(decoded.reliable); + assert!(decoded.ordered); + assert!(!decoded.sequenced); + assert_eq!(decoded.fragment_id, 7); + assert_eq!(decoded.fragment_index, 1); + assert_eq!(decoded.fragment_count, 3); + assert_eq!(decoded.payload, b"hello"); + Ok(()) +} + +#[test] +fn rudp_transport_profile_advertises_state_and_realtime_channels() { + let profile = create_rudp_transport_profile( + "rust-rudp", + cultnet_rs::RudpTransportProfileOptions { + transport_id: Some("public-rudp".to_string()), + host: Some("127.0.0.1".to_string()), + port: Some(7777), + max_payload_bytes: Some(1200), + max_fragment_bytes: Some(1000), + }, + ); + + assert_eq!( + profile.transports[0].protocol, + CultNetTransportProtocol::Rudp + ); + let channels = profile.transports[0] + .channels + .iter() + .map(|channel| { + ( + channel.channel_id.as_str(), + channel.delivery, + channel.ordering, + ) + }) + .collect::>(); + assert_eq!( + channels, + vec![ + ( + "schema", + CultNetTransportDelivery::Reliable, + CultNetTransportOrdering::Ordered + ), + ( + "latest", + CultNetTransportDelivery::Unreliable, + CultNetTransportOrdering::Sequenced + ), + ( + "realtime", + CultNetTransportDelivery::Unreliable, + CultNetTransportOrdering::Unordered + ), + ] + ); +} + #[test] fn legacy_gamecult_networking_contract_round_trips_login_union() -> Result<()> { let message = CultNetMessage::Login { diff --git a/src/GameCult.Networking/CultNetTransport.cs b/src/GameCult.Networking/CultNetTransport.cs index cfafa6b3..423d7675 100644 --- a/src/GameCult.Networking/CultNetTransport.cs +++ b/src/GameCult.Networking/CultNetTransport.cs @@ -1,6 +1,7 @@ using System; using System.Buffers.Binary; using System.IO; +using System.Text; using System.Threading; using System.Threading.Tasks; @@ -82,6 +83,33 @@ namespace GameCult.Networking public int? MaxFragmentBytes { get; set; } } + /// + /// Options for creating a CultNet RUDP transport profile. + /// + public sealed class RudpTransportProfileOptions + { + /// + /// Gets or sets the advertised transport id. + /// + public string TransportId { get; set; } = "rudp"; + /// + /// Gets or sets the advertised host. + /// + public string? Host { get; set; } + /// + /// Gets or sets the advertised port. + /// + public int? Port { get; set; } + /// + /// 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; } + } + /// /// Helpers for creating CultNet transport profile documents. /// @@ -125,6 +153,259 @@ namespace GameCult.Networking ] }; } + + /// + /// Creates a profile for the CultNet reliable UDP transport. + /// + public static CultNetTransportProfile CreateRudp( + string runtimeId, + RudpTransportProfileOptions? options = null) + { + if (string.IsNullOrWhiteSpace(runtimeId)) throw new ArgumentException("Runtime id is required.", nameof(runtimeId)); + options ??= new RudpTransportProfileOptions(); + return new CultNetTransportProfile + { + RuntimeId = runtimeId, + Transports = + [ + new CultNetTransportDescriptor + { + TransportId = string.IsNullOrWhiteSpace(options.TransportId) + ? "rudp" + : options.TransportId, + Protocol = "rudp", + Host = options.Host, + Port = options.Port, + WireContracts = [CultNetWireContracts.SchemaV0], + Channels = + [ + new CultNetTransportChannel + { + ChannelId = "schema", + Delivery = "reliable", + Ordering = "ordered", + MaxPayloadBytes = options.MaxPayloadBytes, + MaxFragmentBytes = options.MaxFragmentBytes + }, + new CultNetTransportChannel + { + ChannelId = "latest", + Delivery = "unreliable", + Ordering = "sequenced", + MaxPayloadBytes = options.MaxPayloadBytes, + MaxFragmentBytes = options.MaxFragmentBytes + }, + new CultNetTransportChannel + { + ChannelId = "realtime", + Delivery = "unreliable", + Ordering = "unordered", + MaxPayloadBytes = options.MaxPayloadBytes, + MaxFragmentBytes = options.MaxFragmentBytes + } + ] + } + ] + }; + } + } + + /// + /// Packet type codes for CultNet reliable UDP transport packets. + /// + public enum CultNetRudpPacketType : byte + { + /// Connection request packet. + Connect = 1, + /// Connection accepted packet. + Accept = 2, + /// Payload data packet. + Data = 3, + /// Selective acknowledgement packet. + Ack = 4, + /// Ping packet. + Ping = 5, + /// Pong packet. + Pong = 6, + /// Disconnect packet. + Disconnect = 7 + } + + /// + /// Binary packet for the CultNet reliable UDP transport. + /// + public sealed class CultNetRudpPacket + { + /// + /// Gets or sets the packet type. + /// + public CultNetRudpPacketType PacketType { get; set; } + /// + /// Gets or sets the connection/session binding id. + /// + public uint ConnectionId { get; set; } + /// + /// Gets or sets the packet sequence number. + /// + public uint Sequence { get; set; } + /// + /// Gets or sets the latest sequence acknowledged by this packet. + /// + public uint Ack { get; set; } + /// + /// Gets or sets the selective acknowledgement mask. + /// + public uint AckMask { get; set; } + /// + /// Gets or sets the logical channel id. + /// + public string ChannelId { get; set; } = string.Empty; + /// + /// Gets or sets whether the packet participates in reliable delivery. + /// + public bool Reliable { get; set; } + /// + /// Gets or sets whether the packet participates in ordered delivery. + /// + public bool Ordered { get; set; } + /// + /// Gets or sets whether the packet is a latest-state sequenced packet. + /// + public bool Sequenced { get; set; } + /// + /// Gets or sets the fragment id, or zero when unfragmented. + /// + public ushort FragmentId { get; set; } + /// + /// Gets or sets the zero-based fragment index. + /// + public ushort FragmentIndex { get; set; } + /// + /// Gets or sets the fragment count, or zero when unfragmented. + /// + public ushort FragmentCount { get; set; } + /// + /// Gets or sets the transport-neutral payload bytes. + /// + public byte[] Payload { get; set; } = Array.Empty(); + } + + /// + /// Encodes and decodes CultNet reliable UDP packet bytes. + /// + public static class CultNetRudpPacketCodec + { + private const int FixedHeaderBytes = 36; + private const byte Version = 0; + private static readonly byte[] Magic = [0x43, 0x4e, 0x52, 0x30]; + + /// + /// Encodes a RUDP packet into the canonical binary envelope. + /// + public static byte[] Encode(CultNetRudpPacket packet) + { + if (packet == null) throw new ArgumentNullException(nameof(packet)); + var channelId = Encoding.UTF8.GetBytes(packet.ChannelId ?? string.Empty); + if (channelId.Length > 255) + { + throw new InvalidOperationException("CultNet RUDP channel id cannot exceed 255 UTF-8 bytes."); + } + + var payload = packet.Payload ?? Array.Empty(); + var headerBytes = checked(FixedHeaderBytes + channelId.Length); + var wire = new byte[checked(headerBytes + payload.Length)]; + Magic.CopyTo(wire, 0); + wire[4] = Version; + wire[5] = (byte)packet.PacketType; + wire[6] = EncodeFlags(packet); + wire[7] = checked((byte)headerBytes); + BinaryPrimitives.WriteUInt32BigEndian(wire.AsSpan(8, 4), packet.ConnectionId); + BinaryPrimitives.WriteUInt32BigEndian(wire.AsSpan(12, 4), packet.Sequence); + BinaryPrimitives.WriteUInt32BigEndian(wire.AsSpan(16, 4), packet.Ack); + BinaryPrimitives.WriteUInt32BigEndian(wire.AsSpan(20, 4), packet.AckMask); + BinaryPrimitives.WriteUInt16BigEndian(wire.AsSpan(24, 2), packet.FragmentId); + BinaryPrimitives.WriteUInt16BigEndian(wire.AsSpan(26, 2), packet.FragmentIndex); + BinaryPrimitives.WriteUInt16BigEndian(wire.AsSpan(28, 2), packet.FragmentCount); + BinaryPrimitives.WriteUInt32BigEndian(wire.AsSpan(30, 4), checked((uint)payload.Length)); + wire[34] = checked((byte)channelId.Length); + wire[35] = 0; + channelId.CopyTo(wire.AsSpan(FixedHeaderBytes)); + payload.CopyTo(wire.AsSpan(headerBytes)); + return wire; + } + + /// + /// Decodes a RUDP packet from the canonical binary envelope. + /// + public static CultNetRudpPacket Decode(byte[] wire) + { + if (wire == null) throw new ArgumentNullException(nameof(wire)); + if (wire.Length < FixedHeaderBytes) + { + throw new InvalidOperationException("CultNet RUDP packet is shorter than the fixed header."); + } + + for (var index = 0; index < Magic.Length; index++) + { + if (wire[index] != Magic[index]) + { + throw new InvalidOperationException("CultNet RUDP packet has the wrong magic."); + } + } + + if (wire[4] != Version) + { + throw new InvalidOperationException($"Unsupported CultNet RUDP packet version {wire[4]}."); + } + + var type = (CultNetRudpPacketType)wire[5]; + if (!Enum.IsDefined(typeof(CultNetRudpPacketType), type)) + { + throw new InvalidOperationException($"Unsupported CultNet RUDP packet type {wire[5]}."); + } + + var headerBytes = wire[7]; + var channelIdLength = wire[34]; + if (headerBytes != FixedHeaderBytes + channelIdLength) + { + throw new InvalidOperationException("CultNet RUDP packet header length does not match the channel id length."); + } + + var payloadLength = checked((int)BinaryPrimitives.ReadUInt32BigEndian(wire.AsSpan(30, 4))); + if (wire.Length != headerBytes + payloadLength) + { + throw new InvalidOperationException("CultNet RUDP packet payload length does not match the packet size."); + } + + var flags = wire[6]; + var payload = new byte[payloadLength]; + Array.Copy(wire, headerBytes, payload, 0, payload.Length); + return new CultNetRudpPacket + { + PacketType = type, + Reliable = (flags & 0b0000_0001) != 0, + Ordered = (flags & 0b0000_0010) != 0, + Sequenced = (flags & 0b0000_0100) != 0, + ConnectionId = BinaryPrimitives.ReadUInt32BigEndian(wire.AsSpan(8, 4)), + Sequence = BinaryPrimitives.ReadUInt32BigEndian(wire.AsSpan(12, 4)), + Ack = BinaryPrimitives.ReadUInt32BigEndian(wire.AsSpan(16, 4)), + AckMask = BinaryPrimitives.ReadUInt32BigEndian(wire.AsSpan(20, 4)), + FragmentId = BinaryPrimitives.ReadUInt16BigEndian(wire.AsSpan(24, 2)), + FragmentIndex = BinaryPrimitives.ReadUInt16BigEndian(wire.AsSpan(26, 2)), + FragmentCount = BinaryPrimitives.ReadUInt16BigEndian(wire.AsSpan(28, 2)), + ChannelId = Encoding.UTF8.GetString(wire, FixedHeaderBytes, channelIdLength), + Payload = payload + }; + } + + private static byte EncodeFlags(CultNetRudpPacket packet) + { + return (byte)( + (packet.Reliable ? 0b0000_0001 : 0) | + (packet.Ordered ? 0b0000_0010 : 0) | + (packet.Sequenced ? 0b0000_0100 : 0) | + (packet.FragmentCount > 0 ? 0b0000_1000 : 0)); + } } /// diff --git a/tests/GameCult.Networking.Tests/NetworkingTests.cs b/tests/GameCult.Networking.Tests/NetworkingTests.cs index f2ba6880..70c69fc6 100644 --- a/tests/GameCult.Networking.Tests/NetworkingTests.cs +++ b/tests/GameCult.Networking.Tests/NetworkingTests.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; @@ -256,6 +257,70 @@ namespace GameCult.Networking.Tests Assert.That(receiver.Profile.Transports[0].Protocol, Is.EqualTo("tcp_framed")); } + [Test] + public void RudpPacketCodec_UsesDeterministicReliableOrderedFixture() + { + var encoded = CultNetRudpPacketCodec.Encode(new CultNetRudpPacket + { + PacketType = CultNetRudpPacketType.Data, + ConnectionId = 0x01020304, + Sequence = 0x0000002a, + Ack = 0x00000029, + AckMask = 0x80000001, + ChannelId = "schema", + Reliable = true, + Ordered = true, + FragmentId = 7, + FragmentIndex = 1, + FragmentCount = 3, + Payload = Encoding.UTF8.GetBytes("hello") + }); + + Assert.That( + Convert.ToHexString(encoded).ToLowerInvariant(), + Is.EqualTo("434e523000030b2a010203040000002a0000002980000001000700010003000000050600736368656d6168656c6c6f")); + + var decoded = CultNetRudpPacketCodec.Decode(encoded); + Assert.That(decoded.PacketType, Is.EqualTo(CultNetRudpPacketType.Data)); + Assert.That(decoded.ConnectionId, Is.EqualTo(0x01020304)); + Assert.That(decoded.Sequence, Is.EqualTo(0x0000002a)); + Assert.That(decoded.Ack, Is.EqualTo(0x00000029)); + Assert.That(decoded.AckMask, Is.EqualTo(0x80000001)); + Assert.That(decoded.ChannelId, Is.EqualTo("schema")); + Assert.That(decoded.Reliable, Is.True); + Assert.That(decoded.Ordered, Is.True); + Assert.That(decoded.Sequenced, Is.False); + Assert.That(decoded.FragmentId, Is.EqualTo(7)); + Assert.That(decoded.FragmentIndex, Is.EqualTo(1)); + Assert.That(decoded.FragmentCount, Is.EqualTo(3)); + Assert.That(Encoding.UTF8.GetString(decoded.Payload), Is.EqualTo("hello")); + } + + [Test] + public void RudpTransportProfile_AdvertisesStateAndRealtimeChannels() + { + var profile = CultNetTransportProfiles.CreateRudp( + "csharp-rudp", + new RudpTransportProfileOptions + { + TransportId = "public-rudp", + Host = "127.0.0.1", + Port = 7777, + MaxPayloadBytes = 1200, + MaxFragmentBytes = 1000 + }); + + Assert.That(profile.Transports[0].Protocol, Is.EqualTo("rudp")); + Assert.That( + profile.Transports[0].Channels.Select(channel => $"{channel.ChannelId}:{channel.Delivery}:{channel.Ordering}").ToArray(), + Is.EqualTo(new[] + { + "schema:reliable:ordered", + "latest:unreliable:sequenced", + "realtime:unreliable:unordered" + })); + } + [Test] public void CultNetSchemaMessageSerialization_RoundTrips_RawSnapshotResponse() {