Add Rust RUDP socket transport
This commit is contained in:
parent
7335435255
commit
41bc58a3f6
3 changed files with 338 additions and 7 deletions
|
|
@ -27,7 +27,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`, 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 |
|
||||
| Rust `cultnet-rs` | Interop example uses TCP length-prefixed MessagePack frames; single-peer RUDP socket transport exists in the library | UDP multicast probe/announce | UDP socket binding for the shared RUDP reliability owner |
|
||||
| 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,15 +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.
|
||||
- TypeScript and Rust now have socket-backed RUDP transport connections that
|
||||
bind a single UDP peer to the shared RUDP session. TypeScript emits the same
|
||||
`frame` events as the TCP-framed transport and can carry `CultNetPeer` schema
|
||||
messages over reliable ordered `schema` frames; Rust exposes the same
|
||||
transport frame/stats shape through synchronous socket polling.
|
||||
- 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 in C#, Rust, and Python.
|
||||
reliability state machine to UDP sockets in C# and Python.
|
||||
|
||||
## RUDP Packet Contract V0
|
||||
|
||||
|
|
|
|||
|
|
@ -2,13 +2,21 @@ use anyhow::Result;
|
|||
use anyhow::anyhow;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::VecDeque;
|
||||
use std::io::ErrorKind;
|
||||
use std::net::SocketAddr;
|
||||
use std::net::UdpSocket;
|
||||
use std::time::SystemTime;
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
use crate::CultNetTransportChannel;
|
||||
use crate::CultNetTransportDelivery;
|
||||
use crate::CultNetTransportDescriptor;
|
||||
use crate::CultNetTransportFrame;
|
||||
use crate::CultNetTransportOrdering;
|
||||
use crate::CultNetTransportProfile;
|
||||
use crate::CultNetTransportProtocol;
|
||||
use crate::CultNetTransportStats;
|
||||
|
||||
const RUDP_MAGIC: [u8; 4] = [0x43, 0x4e, 0x52, 0x30];
|
||||
const RUDP_VERSION: u8 = 0;
|
||||
|
|
@ -436,6 +444,201 @@ impl CultNetRudpSession {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CultNetRudpSocketMode {
|
||||
Client,
|
||||
Server,
|
||||
}
|
||||
|
||||
pub struct CultNetRudpSocketTransportOptions {
|
||||
pub runtime_id: String,
|
||||
pub socket: UdpSocket,
|
||||
pub mode: CultNetRudpSocketMode,
|
||||
pub remote_addr: Option<SocketAddr>,
|
||||
pub connection_id: u32,
|
||||
pub initial_sequence: u32,
|
||||
pub resend_delay_ms: u64,
|
||||
pub transport_id: Option<String>,
|
||||
pub max_payload_bytes: Option<u32>,
|
||||
pub max_fragment_bytes: Option<u32>,
|
||||
}
|
||||
|
||||
impl CultNetRudpSocketTransportOptions {
|
||||
pub fn client(
|
||||
runtime_id: impl Into<String>,
|
||||
socket: UdpSocket,
|
||||
remote_addr: SocketAddr,
|
||||
connection_id: u32,
|
||||
) -> Self {
|
||||
Self {
|
||||
runtime_id: runtime_id.into(),
|
||||
socket,
|
||||
mode: CultNetRudpSocketMode::Client,
|
||||
remote_addr: Some(remote_addr),
|
||||
connection_id,
|
||||
initial_sequence: 1,
|
||||
resend_delay_ms: 250,
|
||||
transport_id: None,
|
||||
max_payload_bytes: None,
|
||||
max_fragment_bytes: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn server(runtime_id: impl Into<String>, socket: UdpSocket, connection_id: u32) -> Self {
|
||||
Self {
|
||||
runtime_id: runtime_id.into(),
|
||||
socket,
|
||||
mode: CultNetRudpSocketMode::Server,
|
||||
remote_addr: None,
|
||||
connection_id,
|
||||
initial_sequence: 1,
|
||||
resend_delay_ms: 250,
|
||||
transport_id: None,
|
||||
max_payload_bytes: None,
|
||||
max_fragment_bytes: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CultNetRudpSocketTransportConnection {
|
||||
socket: UdpSocket,
|
||||
session: CultNetRudpSession,
|
||||
mode: CultNetRudpSocketMode,
|
||||
remote_addr: Option<SocketAddr>,
|
||||
pub profile: CultNetTransportProfile,
|
||||
stats: CultNetTransportStats,
|
||||
delivered_frames: VecDeque<CultNetTransportFrame>,
|
||||
}
|
||||
|
||||
impl CultNetRudpSocketTransportConnection {
|
||||
pub fn new(options: CultNetRudpSocketTransportOptions) -> Result<Self> {
|
||||
let local_addr = options.socket.local_addr()?;
|
||||
let profile = create_rudp_transport_profile(
|
||||
options.runtime_id,
|
||||
RudpTransportProfileOptions {
|
||||
transport_id: options.transport_id,
|
||||
host: Some(local_addr.ip().to_string()),
|
||||
port: Some(local_addr.port()),
|
||||
max_payload_bytes: options.max_payload_bytes,
|
||||
max_fragment_bytes: options.max_fragment_bytes,
|
||||
},
|
||||
);
|
||||
Ok(Self {
|
||||
socket: options.socket,
|
||||
session: CultNetRudpSession::new(CultNetRudpSessionOptions {
|
||||
connection_id: options.connection_id,
|
||||
initial_sequence: options.initial_sequence,
|
||||
resend_delay_ms: options.resend_delay_ms,
|
||||
}),
|
||||
mode: options.mode,
|
||||
remote_addr: options.remote_addr,
|
||||
profile,
|
||||
stats: CultNetTransportStats::default(),
|
||||
delivered_frames: VecDeque::new(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn connected(&self) -> bool {
|
||||
self.session.connected()
|
||||
}
|
||||
|
||||
pub fn stats(&self) -> CultNetTransportStats {
|
||||
self.stats.clone()
|
||||
}
|
||||
|
||||
pub fn connect(&mut self, payload: Vec<u8>) -> Result<()> {
|
||||
if self.mode != CultNetRudpSocketMode::Client {
|
||||
return Err(anyhow!(
|
||||
"Only a client RUDP socket transport can initiate connect"
|
||||
));
|
||||
}
|
||||
let packet = self.session.create_connect(now_ms(), payload);
|
||||
self.send_packet(&packet)
|
||||
}
|
||||
|
||||
pub fn send(&mut self, channel_id: &str, payload: Vec<u8>) -> Result<()> {
|
||||
let options = channel_send_options(channel_id, now_ms());
|
||||
let packet = self.session.send(channel_id, payload, options)?;
|
||||
self.send_packet(&packet)?;
|
||||
self.stats.frames_sent += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn receive_once(&mut self) -> Result<Option<CultNetTransportFrame>> {
|
||||
if let Some(frame) = self.delivered_frames.pop_front() {
|
||||
return Ok(Some(frame));
|
||||
}
|
||||
|
||||
let mut wire = vec![0_u8; 65_535];
|
||||
let (received, remote_addr) = match self.socket.recv_from(&mut wire) {
|
||||
Ok(value) => value,
|
||||
Err(error)
|
||||
if error.kind() == ErrorKind::WouldBlock || error.kind() == ErrorKind::TimedOut =>
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
wire.truncate(received);
|
||||
self.stats.bytes_received += received as u64;
|
||||
|
||||
if let Some(expected) = self.remote_addr {
|
||||
if expected != remote_addr {
|
||||
return Ok(None);
|
||||
}
|
||||
} else {
|
||||
self.remote_addr = Some(remote_addr);
|
||||
}
|
||||
|
||||
let packet = decode_rudp_packet(&wire)?;
|
||||
if self.mode == CultNetRudpSocketMode::Server
|
||||
&& packet.packet_type == CultNetRudpPacketType::Connect
|
||||
{
|
||||
let accept = self.session.accept_connect(&packet, now_ms(), Vec::new())?;
|
||||
self.send_packet(&accept)?;
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let result = self.session.receive(&packet, now_ms())?;
|
||||
if let Some(reply) = result.reply {
|
||||
self.send_packet(&reply)?;
|
||||
}
|
||||
|
||||
for frame in result.delivered {
|
||||
self.delivered_frames.push_back(CultNetTransportFrame {
|
||||
channel_id: frame.channel_id,
|
||||
payload: frame.payload,
|
||||
});
|
||||
self.stats.frames_received += 1;
|
||||
}
|
||||
let frame = self.delivered_frames.pop_front();
|
||||
if packet.packet_type == CultNetRudpPacketType::Accept || frame.is_some() {
|
||||
let ack = self.session.create_ack();
|
||||
self.send_packet(&ack)?;
|
||||
}
|
||||
Ok(frame)
|
||||
}
|
||||
|
||||
pub fn poll_resends(&mut self) -> Result<()> {
|
||||
for packet in self.session.due_resends(now_ms()) {
|
||||
self.send_packet(&packet)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn send_packet(&mut self, packet: &CultNetRudpPacket) -> Result<()> {
|
||||
let Some(remote_addr) = self.remote_addr else {
|
||||
return Err(anyhow!(
|
||||
"RUDP socket transport does not have a remote endpoint"
|
||||
));
|
||||
};
|
||||
let wire = encode_rudp_packet(packet)?;
|
||||
let sent = self.socket.send_to(&wire, remote_addr)?;
|
||||
self.stats.bytes_sent += sent as u64;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct RudpTransportProfileOptions {
|
||||
pub transport_id: Option<String>,
|
||||
|
|
@ -589,6 +792,36 @@ fn packet_type_to_code(packet_type: CultNetRudpPacketType) -> u8 {
|
|||
}
|
||||
}
|
||||
|
||||
fn channel_send_options(channel_id: &str, now_ms: u64) -> CultNetRudpSendOptions {
|
||||
match channel_id {
|
||||
"schema" => CultNetRudpSendOptions {
|
||||
reliable: true,
|
||||
ordered: true,
|
||||
sequenced: false,
|
||||
now_ms,
|
||||
},
|
||||
"latest" => CultNetRudpSendOptions {
|
||||
reliable: false,
|
||||
ordered: false,
|
||||
sequenced: true,
|
||||
now_ms,
|
||||
},
|
||||
_ => CultNetRudpSendOptions {
|
||||
reliable: false,
|
||||
ordered: false,
|
||||
sequenced: false,
|
||||
now_ms,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn now_ms() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|duration| duration.as_millis() as u64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
fn packet_type_from_code(code: u8) -> Result<CultNetRudpPacketType> {
|
||||
match code {
|
||||
1 => Ok(CultNetRudpPacketType::Connect),
|
||||
|
|
|
|||
|
|
@ -16,6 +16,9 @@ use cultnet_rs::CultNetRudpPacketType;
|
|||
use cultnet_rs::CultNetRudpSendOptions;
|
||||
use cultnet_rs::CultNetRudpSession;
|
||||
use cultnet_rs::CultNetRudpSessionOptions;
|
||||
use cultnet_rs::CultNetRudpSocketMode;
|
||||
use cultnet_rs::CultNetRudpSocketTransportConnection;
|
||||
use cultnet_rs::CultNetRudpSocketTransportOptions;
|
||||
use cultnet_rs::CultNetSchemaKind;
|
||||
use cultnet_rs::CultNetSchemaRegistry;
|
||||
use cultnet_rs::CultNetSecret;
|
||||
|
|
@ -23,6 +26,7 @@ use cultnet_rs::CultNetServerSecurityOptions;
|
|||
use cultnet_rs::CultNetTransportChannel;
|
||||
use cultnet_rs::CultNetTransportDelivery;
|
||||
use cultnet_rs::CultNetTransportDescriptor;
|
||||
use cultnet_rs::CultNetTransportFrame;
|
||||
use cultnet_rs::CultNetTransportOrdering;
|
||||
use cultnet_rs::CultNetTransportProfile;
|
||||
use cultnet_rs::CultNetTransportProtocol;
|
||||
|
|
@ -40,10 +44,47 @@ use cultnet_rs::encode_cultnet_message_to_vec;
|
|||
use cultnet_rs::encode_frame;
|
||||
use cultnet_rs::encode_rudp_packet;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::net::UdpSocket;
|
||||
use std::thread;
|
||||
use std::time::Duration as StdDuration;
|
||||
|
||||
const TS_HELLO_FRAME: &[u8] = include_bytes!("fixtures/cultnet-ts-hello.frame");
|
||||
const TS_LEGACY_LOGIN_FRAME: &[u8] = include_bytes!("fixtures/cultnet-ts-legacy-login.frame");
|
||||
|
||||
fn bind_udp_socket() -> Result<UdpSocket> {
|
||||
let socket = UdpSocket::bind("127.0.0.1:0")?;
|
||||
socket.set_read_timeout(Some(StdDuration::from_millis(20)))?;
|
||||
Ok(socket)
|
||||
}
|
||||
|
||||
fn pump_rudp_handshake(
|
||||
client: &mut CultNetRudpSocketTransportConnection,
|
||||
server: &mut CultNetRudpSocketTransportConnection,
|
||||
) -> Result<()> {
|
||||
for _ in 0..20 {
|
||||
let _ = server.receive_once()?;
|
||||
let _ = client.receive_once()?;
|
||||
let _ = server.receive_once()?;
|
||||
if client.connected() && server.connected() {
|
||||
return Ok(());
|
||||
}
|
||||
thread::sleep(StdDuration::from_millis(5));
|
||||
}
|
||||
anyhow::bail!("RUDP socket handshake did not complete");
|
||||
}
|
||||
|
||||
fn receive_rudp_frame(
|
||||
transport: &mut CultNetRudpSocketTransportConnection,
|
||||
) -> Result<CultNetTransportFrame> {
|
||||
for _ in 0..20 {
|
||||
if let Some(frame) = transport.receive_once()? {
|
||||
return Ok(frame);
|
||||
}
|
||||
thread::sleep(StdDuration::from_millis(5));
|
||||
}
|
||||
anyhow::bail!("RUDP socket frame was not delivered")
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "ghostlight.agent-state",
|
||||
|
|
@ -530,6 +571,63 @@ fn rudp_session_suppresses_duplicates_and_delivers_reliable_ordered_payloads_in_
|
|||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rudp_socket_transport_handshakes_and_carries_reliable_ordered_schema_frames() -> Result<()> {
|
||||
let server_socket = bind_udp_socket()?;
|
||||
let client_socket = bind_udp_socket()?;
|
||||
let server_addr = server_socket.local_addr()?;
|
||||
let connection_id = 0x1020_3040;
|
||||
let mut server =
|
||||
CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions {
|
||||
runtime_id: "rust-rudp-server".to_string(),
|
||||
socket: server_socket,
|
||||
mode: CultNetRudpSocketMode::Server,
|
||||
remote_addr: None,
|
||||
connection_id,
|
||||
initial_sequence: 100,
|
||||
resend_delay_ms: 25,
|
||||
transport_id: None,
|
||||
max_payload_bytes: None,
|
||||
max_fragment_bytes: None,
|
||||
})?;
|
||||
let mut client =
|
||||
CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions {
|
||||
runtime_id: "rust-rudp-client".to_string(),
|
||||
socket: client_socket,
|
||||
mode: CultNetRudpSocketMode::Client,
|
||||
remote_addr: Some(server_addr),
|
||||
connection_id,
|
||||
initial_sequence: 1,
|
||||
resend_delay_ms: 25,
|
||||
transport_id: None,
|
||||
max_payload_bytes: None,
|
||||
max_fragment_bytes: None,
|
||||
})?;
|
||||
|
||||
client.connect(b"join".to_vec())?;
|
||||
pump_rudp_handshake(&mut client, &mut server)?;
|
||||
assert!(client.connected());
|
||||
assert!(server.connected());
|
||||
|
||||
client.send("schema", b"client-state".to_vec())?;
|
||||
let server_frame = receive_rudp_frame(&mut server)?;
|
||||
assert_eq!(server_frame.channel_id, "schema");
|
||||
assert_eq!(server_frame.payload, b"client-state");
|
||||
|
||||
server.send("schema", b"server-state".to_vec())?;
|
||||
let client_frame = receive_rudp_frame(&mut client)?;
|
||||
assert_eq!(client_frame.channel_id, "schema");
|
||||
assert_eq!(client_frame.payload, b"server-state");
|
||||
assert_eq!(
|
||||
server.profile.transports[0].protocol,
|
||||
CultNetTransportProtocol::Rudp
|
||||
);
|
||||
assert_eq!(client.stats().frames_sent, 1);
|
||||
assert_eq!(server.stats().frames_received, 1);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_gamecult_networking_contract_round_trips_login_union() -> Result<()> {
|
||||
let message = CultNetMessage::Login {
|
||||
|
|
|
|||
Loading…
Reference in a new issue