Add RUDP reliable queue bounds across runtimes
This commit is contained in:
parent
8287926921
commit
c85b5fb561
19 changed files with 411 additions and 23 deletions
|
|
@ -204,10 +204,16 @@ Current progress:
|
|||
silent receive window. The TypeScript interop harness proves ping/pong payload
|
||||
echo against C#/Kotlin/Python/Rust UDP peers; local runtime tests prove timeout
|
||||
state transitions.
|
||||
- TypeScript, C#, Rust, Python, and Kotlin now share bounded reliable-send
|
||||
backpressure for RUDP sessions. `maxPendingReliablePackets` is advertised on
|
||||
RUDP transport-profile channels and enforced by the session before reliable
|
||||
connect, accept, single-packet sends, or fragmented sends enqueue anything;
|
||||
TCP-framed profiles do not publish the field because they do not own the RUDP
|
||||
pending-reliable queue.
|
||||
- The remaining parity work is to deepen Python's server-side use of its port
|
||||
and move each runtime's existing TCP/LiteNetLib/WebSocket bodies behind those
|
||||
ports, then broaden RUDP interop into reconnect policy, backpressure, and the
|
||||
wider schema-message matrix.
|
||||
ports, then broaden RUDP interop into reconnect policy and the wider
|
||||
schema-message matrix.
|
||||
|
||||
## RUDP Packet Contract V0
|
||||
|
||||
|
|
|
|||
|
|
@ -242,6 +242,7 @@ def shared_contract_schema_json(schema_id: str, title: str, schema_version: str)
|
|||
"ordering": {"type": "string", "enum": ["ordered", "unordered", "sequenced"]},
|
||||
"maxPayloadBytes": {"type": "integer", "minimum": 1},
|
||||
"maxFragmentBytes": {"type": "integer", "minimum": 1},
|
||||
"maxPendingReliablePackets": {"type": "integer", "minimum": 1},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
|
|
|||
|
|
@ -115,6 +115,7 @@ class CultNetRudpSessionOptions:
|
|||
connection_id: int
|
||||
initial_sequence: int = 1
|
||||
resend_delay_ms: int = 250
|
||||
max_pending_reliable_packets: int | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
|
@ -142,6 +143,7 @@ class CultNetRudpSocketTransportOptions:
|
|||
transport_id: str = "rudp"
|
||||
max_payload_bytes: int | None = None
|
||||
max_fragment_bytes: int | None = None
|
||||
max_pending_reliable_packets: int | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
|
|
@ -170,6 +172,7 @@ def create_rudp_transport_profile(
|
|||
port: int | None = None,
|
||||
max_payload_bytes: int | None = None,
|
||||
max_fragment_bytes: int | None = None,
|
||||
max_pending_reliable_packets: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
def channel(channel_id: str, delivery: str, ordering: str) -> dict[str, Any]:
|
||||
value: dict[str, Any] = {
|
||||
|
|
@ -181,6 +184,8 @@ def create_rudp_transport_profile(
|
|||
value["maxPayloadBytes"] = max_payload_bytes
|
||||
if max_fragment_bytes is not None:
|
||||
value["maxFragmentBytes"] = max_fragment_bytes
|
||||
if max_pending_reliable_packets is not None:
|
||||
value["maxPendingReliablePackets"] = max_pending_reliable_packets
|
||||
return value
|
||||
|
||||
transport: dict[str, Any] = {
|
||||
|
|
@ -209,6 +214,9 @@ class CultNetRudpSession:
|
|||
def __init__(self, options: CultNetRudpSessionOptions) -> None:
|
||||
self.connection_id = _uint32(options.connection_id, "connection_id")
|
||||
self.resend_delay_ms = options.resend_delay_ms
|
||||
if options.max_pending_reliable_packets is not None and options.max_pending_reliable_packets <= 0:
|
||||
raise ValueError("RUDP max_pending_reliable_packets must be greater than zero")
|
||||
self.max_pending_reliable_packets = options.max_pending_reliable_packets
|
||||
self._next_sequence = _uint32(options.initial_sequence, "initial_sequence")
|
||||
self._next_fragment_id = 1
|
||||
self._connected = False
|
||||
|
|
@ -233,6 +241,7 @@ class CultNetRudpSession:
|
|||
return tuple(sorted(self._pending_reliable))
|
||||
|
||||
def create_connect(self, now_ms: int = 0, payload: bytes = b"") -> CultNetRudpPacket:
|
||||
self._ensure_reliable_capacity(1)
|
||||
packet = self._create_packet(
|
||||
CultNetRudpPacketType.CONNECT,
|
||||
"control",
|
||||
|
|
@ -253,6 +262,7 @@ class CultNetRudpSession:
|
|||
if packet.packet_type != CultNetRudpPacketType.CONNECT:
|
||||
raise ValueError(f"Expected RUDP connect packet, got {packet.packet_type.value}")
|
||||
|
||||
self._ensure_reliable_capacity(1)
|
||||
self._remember_received(packet.sequence)
|
||||
self._connected = True
|
||||
response = self._create_packet(
|
||||
|
|
@ -289,6 +299,7 @@ class CultNetRudpSession:
|
|||
raise ValueError("RUDP max_fragment_bytes must be greater than zero")
|
||||
|
||||
if max_fragment_bytes is None or len(payload) <= max_fragment_bytes:
|
||||
self._ensure_reliable_capacity(1 if options.reliable else 0)
|
||||
packet = self._create_packet(
|
||||
CultNetRudpPacketType.DATA,
|
||||
channel_id,
|
||||
|
|
@ -304,6 +315,7 @@ class CultNetRudpSession:
|
|||
fragment_count = (len(payload) + max_fragment_bytes - 1) // max_fragment_bytes
|
||||
if fragment_count > 0xFFFF:
|
||||
raise ValueError("RUDP payload requires more than 65535 fragments")
|
||||
self._ensure_reliable_capacity(fragment_count if options.reliable else 0)
|
||||
|
||||
fragment_id = self._allocate_fragment_id()
|
||||
packets: list[CultNetRudpPacket] = []
|
||||
|
|
@ -459,6 +471,12 @@ class CultNetRudpSession:
|
|||
last_sent_at_ms=now_ms,
|
||||
)
|
||||
|
||||
def _ensure_reliable_capacity(self, packet_count: int) -> None:
|
||||
if packet_count == 0 or self.max_pending_reliable_packets is None:
|
||||
return
|
||||
if len(self._pending_reliable) + packet_count > self.max_pending_reliable_packets:
|
||||
raise ValueError("RUDP reliable send queue is full")
|
||||
|
||||
def _apply_acknowledgements(self, packet: CultNetRudpPacket) -> None:
|
||||
self._pending_reliable.pop(packet.ack, None)
|
||||
for bit in range(32):
|
||||
|
|
@ -576,6 +594,7 @@ class CultNetRudpSocketTransportConnection:
|
|||
connection_id=options.connection_id,
|
||||
initial_sequence=options.initial_sequence,
|
||||
resend_delay_ms=options.resend_delay_ms,
|
||||
max_pending_reliable_packets=options.max_pending_reliable_packets,
|
||||
)
|
||||
)
|
||||
host, port = self.socket.getsockname()[:2]
|
||||
|
|
@ -586,6 +605,7 @@ class CultNetRudpSocketTransportConnection:
|
|||
port=port,
|
||||
max_payload_bytes=options.max_payload_bytes,
|
||||
max_fragment_bytes=options.max_fragment_bytes,
|
||||
max_pending_reliable_packets=options.max_pending_reliable_packets,
|
||||
)
|
||||
self._bytes_received = 0
|
||||
self._bytes_sent = 0
|
||||
|
|
|
|||
|
|
@ -795,6 +795,30 @@ class CultCacheTests(unittest.TestCase):
|
|||
self.assertTrue(client.check_timeout(91, 50))
|
||||
self.assertFalse(client.connected)
|
||||
|
||||
def test_cultnet_rudp_session_bounds_pending_reliable_packets_before_enqueue(self) -> None:
|
||||
session = CultNetRudpSession(
|
||||
CultNetRudpSessionOptions(connection_id=102, initial_sequence=1, max_pending_reliable_packets=2)
|
||||
)
|
||||
session.receive(CultNetRudpPacket(CultNetRudpPacketType.ACCEPT, 102, 50, 0, 0, "control"))
|
||||
session.send("schema", b"first", CultNetRudpSendOptions(reliable=True, ordered=True))
|
||||
session.send("schema", b"second", CultNetRudpSendOptions(reliable=True, ordered=True))
|
||||
with self.assertRaisesRegex(ValueError, "reliable send queue is full"):
|
||||
session.send("schema", b"third", CultNetRudpSendOptions(reliable=True, ordered=True))
|
||||
self.assertEqual(session.pending_reliable_sequences, (1, 2))
|
||||
|
||||
fragmented = CultNetRudpSession(
|
||||
CultNetRudpSessionOptions(connection_id=103, initial_sequence=1, max_pending_reliable_packets=3)
|
||||
)
|
||||
fragmented.receive(CultNetRudpPacket(CultNetRudpPacketType.ACCEPT, 103, 50, 0, 0, "control"))
|
||||
with self.assertRaisesRegex(ValueError, "reliable send queue is full"):
|
||||
fragmented.send_many(
|
||||
"schema",
|
||||
b"fragment-me",
|
||||
CultNetRudpSendOptions(reliable=True, ordered=True),
|
||||
max_fragment_bytes=3,
|
||||
)
|
||||
self.assertEqual(fragmented.pending_reliable_sequences, ())
|
||||
|
||||
def test_cultnet_rudp_session_suppresses_duplicates_and_delivers_reliable_ordered_payloads(self) -> None:
|
||||
sender = CultNetRudpSession(CultNetRudpSessionOptions(connection_id=123, initial_sequence=1))
|
||||
receiver = CultNetRudpSession(CultNetRudpSessionOptions(connection_id=123, initial_sequence=100))
|
||||
|
|
|
|||
|
|
@ -94,6 +94,7 @@ data class CultNetTransportChannel(
|
|||
val ordering: String,
|
||||
val maxPayloadBytes: Int? = null,
|
||||
val maxFragmentBytes: Int? = null,
|
||||
val maxPendingReliablePackets: Int? = null,
|
||||
)
|
||||
|
||||
fun createRudpTransportProfile(
|
||||
|
|
@ -103,6 +104,7 @@ fun createRudpTransportProfile(
|
|||
port: Int? = null,
|
||||
maxPayloadBytes: Int? = null,
|
||||
maxFragmentBytes: Int? = null,
|
||||
maxPendingReliablePackets: Int? = null,
|
||||
): CultNetTransportProfile = CultNetTransportProfile(
|
||||
runtimeId = runtimeId,
|
||||
transports = listOf(
|
||||
|
|
@ -112,9 +114,9 @@ fun createRudpTransportProfile(
|
|||
host = host,
|
||||
port = port,
|
||||
channels = listOf(
|
||||
CultNetTransportChannel("schema", "reliable", "ordered", maxPayloadBytes, maxFragmentBytes),
|
||||
CultNetTransportChannel("latest", "unreliable", "sequenced", maxPayloadBytes, maxFragmentBytes),
|
||||
CultNetTransportChannel("realtime", "unreliable", "unordered", maxPayloadBytes, maxFragmentBytes),
|
||||
CultNetTransportChannel("schema", "reliable", "ordered", maxPayloadBytes, maxFragmentBytes, maxPendingReliablePackets),
|
||||
CultNetTransportChannel("latest", "unreliable", "sequenced", maxPayloadBytes, maxFragmentBytes, maxPendingReliablePackets),
|
||||
CultNetTransportChannel("realtime", "unreliable", "unordered", maxPayloadBytes, maxFragmentBytes, maxPendingReliablePackets),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
|
@ -165,6 +167,7 @@ data class CultNetRudpSessionOptions(
|
|||
val connectionId: Long,
|
||||
val initialSequence: Long = 1,
|
||||
val resendDelayMs: Long = 250,
|
||||
val maxPendingReliablePackets: Int? = null,
|
||||
)
|
||||
|
||||
data class CultNetRudpSendOptions(
|
||||
|
|
@ -187,6 +190,7 @@ private data class FragmentBuffer(
|
|||
class CultNetRudpSession(options: CultNetRudpSessionOptions) {
|
||||
val connectionId: Long = uint32(options.connectionId, "connectionId")
|
||||
val resendDelayMs: Long = options.resendDelayMs
|
||||
private val maxPendingReliablePackets: Int? = options.maxPendingReliablePackets
|
||||
private var nextSequence = uint32(options.initialSequence, "initialSequence")
|
||||
private var nextFragmentId = 1
|
||||
var connected: Boolean = false
|
||||
|
|
@ -203,7 +207,14 @@ class CultNetRudpSession(options: CultNetRudpSessionOptions) {
|
|||
val pendingReliableSequences: List<Long>
|
||||
get() = pendingReliable.keys.sorted()
|
||||
|
||||
init {
|
||||
if (maxPendingReliablePackets != null && maxPendingReliablePackets <= 0) {
|
||||
throw IOException("RUDP maxPendingReliablePackets must be greater than zero")
|
||||
}
|
||||
}
|
||||
|
||||
fun createConnect(nowMs: Long = 0, payload: ByteArray = ByteArray(0)): CultNetRudpPacket {
|
||||
ensureReliableCapacity(1)
|
||||
val packet = createPacket(CultNetRudpPacketType.Connect, "control", payload, reliable = true, ordered = true)
|
||||
trackReliable(packet, nowMs)
|
||||
return packet
|
||||
|
|
@ -212,6 +223,7 @@ class CultNetRudpSession(options: CultNetRudpSessionOptions) {
|
|||
fun acceptConnect(packet: CultNetRudpPacket, nowMs: Long = 0, payload: ByteArray = ByteArray(0)): CultNetRudpPacket {
|
||||
requireConnection(packet)
|
||||
if (packet.packetType != CultNetRudpPacketType.Connect) throw IOException("Expected RUDP connect packet, got ${packet.packetType}")
|
||||
ensureReliableCapacity(1)
|
||||
rememberReceived(packet.sequence)
|
||||
connected = true
|
||||
val response = createPacket(CultNetRudpPacketType.Accept, "control", payload, reliable = true, ordered = true)
|
||||
|
|
@ -234,6 +246,7 @@ class CultNetRudpSession(options: CultNetRudpSessionOptions) {
|
|||
if (maxFragmentBytes != null && payload.size > maxFragmentBytes) {
|
||||
val fragmentCount = (payload.size + maxFragmentBytes - 1) / maxFragmentBytes
|
||||
if (fragmentCount > 0xffff) throw IOException("RUDP payload requires more than 65535 fragments")
|
||||
ensureReliableCapacity(if (options.reliable) fragmentCount else 0)
|
||||
val fragmentId = allocateFragmentId()
|
||||
return (0 until fragmentCount).map { index ->
|
||||
val start = index * maxFragmentBytes
|
||||
|
|
@ -252,6 +265,7 @@ class CultNetRudpSession(options: CultNetRudpSessionOptions) {
|
|||
packet
|
||||
}
|
||||
}
|
||||
ensureReliableCapacity(if (options.reliable) 1 else 0)
|
||||
val packet = createPacket(channelId = channelId, packetType = CultNetRudpPacketType.Data, payload = payload, reliable = options.reliable, ordered = options.ordered, sequenced = options.sequenced)
|
||||
if (packet.reliable) trackReliable(packet, options.nowMs)
|
||||
return listOf(packet)
|
||||
|
|
@ -342,6 +356,13 @@ class CultNetRudpSession(options: CultNetRudpSessionOptions) {
|
|||
pendingReliable[packet.sequence] = PendingReliablePacket(packet.copy(payload = packet.payload.copyOf()), nowMs)
|
||||
}
|
||||
|
||||
private fun ensureReliableCapacity(packetCount: Int) {
|
||||
if (packetCount == 0 || maxPendingReliablePackets == null) return
|
||||
if (pendingReliable.size + packetCount > maxPendingReliablePackets) {
|
||||
throw IOException("RUDP reliable send queue is full")
|
||||
}
|
||||
}
|
||||
|
||||
private fun applyAcknowledgements(packet: CultNetRudpPacket) {
|
||||
pendingReliable.remove(packet.ack)
|
||||
for (bit in 0 until 32) {
|
||||
|
|
@ -447,8 +468,9 @@ class CultNetRudpSocketTransportConnection(
|
|||
initialSequence: Long = 1,
|
||||
resendDelayMs: Long = 250,
|
||||
private val maxFragmentBytes: Int? = null,
|
||||
maxPendingReliablePackets: Int? = null,
|
||||
) : AutoCloseable {
|
||||
private val session = CultNetRudpSession(CultNetRudpSessionOptions(connectionId, initialSequence, resendDelayMs))
|
||||
private val session = CultNetRudpSession(CultNetRudpSessionOptions(connectionId, initialSequence, resendDelayMs, maxPendingReliablePackets))
|
||||
private var remote = remoteAddress
|
||||
private val delivered = ArrayDeque<CultNetTransportFrame>()
|
||||
private val pongPayloads = ArrayDeque<ByteArray>()
|
||||
|
|
@ -464,6 +486,7 @@ class CultNetRudpSocketTransportConnection(
|
|||
host = socket.localAddress.hostAddress,
|
||||
port = socket.localPort,
|
||||
maxFragmentBytes = maxFragmentBytes,
|
||||
maxPendingReliablePackets = maxPendingReliablePackets,
|
||||
)
|
||||
val connected: Boolean get() = session.connected
|
||||
val stats: CultNetTransportStats get() = CultNetTransportStats(bytesReceived, bytesSent, framesReceived, framesSent)
|
||||
|
|
@ -633,6 +656,7 @@ fun main(args: Array<String>) {
|
|||
if (args.isEmpty()) {
|
||||
rudpPacketCodecUsesDeterministicReliableOrderedFixture()
|
||||
rudpSessionPingsAndDetectsReceiveTimeout()
|
||||
rudpSessionBoundsPendingReliablePacketsBeforeEnqueue()
|
||||
rudpSessionFragmentsAndReassemblesReliableOrderedPayloads()
|
||||
rudpSocketTransportHandshakesAndCarriesReliableOrderedSchemaFrames()
|
||||
rudpSocketTransportCarriesFragmentedReliableOrderedSchemaFrames()
|
||||
|
|
@ -814,6 +838,33 @@ private fun rudpSessionPingsAndDetectsReceiveTimeout() {
|
|||
check(!client.connected)
|
||||
}
|
||||
|
||||
private fun rudpSessionBoundsPendingReliablePacketsBeforeEnqueue() {
|
||||
val session = CultNetRudpSession(CultNetRudpSessionOptions(connectionId = 102, initialSequence = 1, maxPendingReliablePackets = 2))
|
||||
session.receive(CultNetRudpPacket(CultNetRudpPacketType.Accept, 102, 50, 0, 0, "control"))
|
||||
session.send("schema", "first".toByteArray(StandardCharsets.UTF_8), CultNetRudpSendOptions(reliable = true, ordered = true))
|
||||
session.send("schema", "second".toByteArray(StandardCharsets.UTF_8), CultNetRudpSendOptions(reliable = true, ordered = true))
|
||||
val third = runCatching {
|
||||
session.send("schema", "third".toByteArray(StandardCharsets.UTF_8), CultNetRudpSendOptions(reliable = true, ordered = true))
|
||||
}.exceptionOrNull()
|
||||
check(third is IOException)
|
||||
check(third.message?.contains("reliable send queue is full") == true)
|
||||
check(session.pendingReliableSequences == listOf(1L, 2L))
|
||||
|
||||
val fragmented = CultNetRudpSession(CultNetRudpSessionOptions(connectionId = 103, initialSequence = 1, maxPendingReliablePackets = 3))
|
||||
fragmented.receive(CultNetRudpPacket(CultNetRudpPacketType.Accept, 103, 50, 0, 0, "control"))
|
||||
val fragmentError = runCatching {
|
||||
fragmented.sendMany(
|
||||
"schema",
|
||||
"fragment-me".toByteArray(StandardCharsets.UTF_8),
|
||||
CultNetRudpSendOptions(reliable = true, ordered = true),
|
||||
maxFragmentBytes = 3,
|
||||
)
|
||||
}.exceptionOrNull()
|
||||
check(fragmentError is IOException)
|
||||
check(fragmentError.message?.contains("reliable send queue is full") == true)
|
||||
check(fragmented.pendingReliableSequences.isEmpty())
|
||||
}
|
||||
|
||||
private fun rudpSessionFragmentsAndReassemblesReliableOrderedPayloads() {
|
||||
val sender = CultNetRudpSession(CultNetRudpSessionOptions(connectionId = 456, initialSequence = 1))
|
||||
val receiver = CultNetRudpSession(CultNetRudpSessionOptions(connectionId = 456, initialSequence = 100))
|
||||
|
|
|
|||
|
|
@ -69,7 +69,8 @@
|
|||
]
|
||||
},
|
||||
"maxPayloadBytes": { "type": "integer", "minimum": 1 },
|
||||
"maxFragmentBytes": { "type": "integer", "minimum": 1 }
|
||||
"maxFragmentBytes": { "type": "integer", "minimum": 1 },
|
||||
"maxPendingReliablePackets": { "type": "integer", "minimum": 1 }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -126,6 +126,8 @@ pub struct CultNetTransportChannel {
|
|||
pub max_payload_bytes: Option<u32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub max_fragment_bytes: Option<u32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub max_pending_reliable_packets: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
|
|
|||
|
|
@ -72,6 +72,7 @@ pub struct CultNetRudpSessionOptions {
|
|||
pub connection_id: u32,
|
||||
pub initial_sequence: u32,
|
||||
pub resend_delay_ms: u64,
|
||||
pub max_pending_reliable_packets: Option<usize>,
|
||||
}
|
||||
|
||||
impl Default for CultNetRudpSessionOptions {
|
||||
|
|
@ -80,6 +81,7 @@ impl Default for CultNetRudpSessionOptions {
|
|||
connection_id: 0,
|
||||
initial_sequence: 1,
|
||||
resend_delay_ms: 250,
|
||||
max_pending_reliable_packets: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -116,6 +118,7 @@ struct FragmentBuffer {
|
|||
pub struct CultNetRudpSession {
|
||||
connection_id: u32,
|
||||
resend_delay_ms: u64,
|
||||
max_pending_reliable_packets: Option<usize>,
|
||||
next_sequence: u32,
|
||||
next_fragment_id: u16,
|
||||
connected: bool,
|
||||
|
|
@ -133,6 +136,7 @@ impl CultNetRudpSession {
|
|||
Self {
|
||||
connection_id: options.connection_id,
|
||||
resend_delay_ms: options.resend_delay_ms,
|
||||
max_pending_reliable_packets: options.max_pending_reliable_packets,
|
||||
next_sequence: options.initial_sequence,
|
||||
next_fragment_id: 1,
|
||||
connected: false,
|
||||
|
|
@ -166,7 +170,8 @@ impl CultNetRudpSession {
|
|||
self.last_received_at_ms
|
||||
}
|
||||
|
||||
pub fn create_connect(&mut self, now_ms: u64, payload: Vec<u8>) -> CultNetRudpPacket {
|
||||
pub fn create_connect(&mut self, now_ms: u64, payload: Vec<u8>) -> Result<CultNetRudpPacket> {
|
||||
self.ensure_reliable_capacity(1)?;
|
||||
let packet = self.create_packet(
|
||||
CultNetRudpPacketType::Connect,
|
||||
"control",
|
||||
|
|
@ -176,7 +181,7 @@ impl CultNetRudpSession {
|
|||
false,
|
||||
);
|
||||
self.track_reliable(packet.clone(), now_ms);
|
||||
packet
|
||||
Ok(packet)
|
||||
}
|
||||
|
||||
pub fn accept_connect(
|
||||
|
|
@ -193,6 +198,7 @@ impl CultNetRudpSession {
|
|||
));
|
||||
}
|
||||
|
||||
self.ensure_reliable_capacity(1)?;
|
||||
self.remember_received(packet.sequence);
|
||||
self.connected = true;
|
||||
let response = self.create_packet(
|
||||
|
|
@ -241,6 +247,7 @@ impl CultNetRudpSession {
|
|||
if fragment_count > u16::MAX as usize {
|
||||
return Err(anyhow!("RUDP payload requires more than 65535 fragments"));
|
||||
}
|
||||
self.ensure_reliable_capacity(if options.reliable { fragment_count } else { 0 })?;
|
||||
let fragment_id = self.allocate_fragment_id();
|
||||
let mut packets = Vec::new();
|
||||
for index in 0..fragment_count {
|
||||
|
|
@ -266,6 +273,7 @@ impl CultNetRudpSession {
|
|||
}
|
||||
}
|
||||
|
||||
self.ensure_reliable_capacity(if options.reliable { 1 } else { 0 })?;
|
||||
let packet = self.create_packet(
|
||||
CultNetRudpPacketType::Data,
|
||||
channel_id,
|
||||
|
|
@ -533,6 +541,18 @@ impl CultNetRudpSession {
|
|||
);
|
||||
}
|
||||
|
||||
fn ensure_reliable_capacity(&self, packet_count: usize) -> Result<()> {
|
||||
if packet_count == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(limit) = self.max_pending_reliable_packets {
|
||||
if self.pending_reliable.len() + packet_count > limit {
|
||||
return Err(anyhow!("RUDP reliable send queue is full"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_acknowledgements(&mut self, packet: &CultNetRudpPacket) {
|
||||
self.pending_reliable.remove(&packet.ack);
|
||||
for bit in 0..32 {
|
||||
|
|
@ -745,6 +765,7 @@ pub struct CultNetRudpSocketTransportOptions {
|
|||
pub transport_id: Option<String>,
|
||||
pub max_payload_bytes: Option<u32>,
|
||||
pub max_fragment_bytes: Option<u32>,
|
||||
pub max_pending_reliable_packets: Option<u32>,
|
||||
}
|
||||
|
||||
impl CultNetRudpSocketTransportOptions {
|
||||
|
|
@ -765,6 +786,7 @@ impl CultNetRudpSocketTransportOptions {
|
|||
transport_id: None,
|
||||
max_payload_bytes: None,
|
||||
max_fragment_bytes: None,
|
||||
max_pending_reliable_packets: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -780,6 +802,7 @@ impl CultNetRudpSocketTransportOptions {
|
|||
transport_id: None,
|
||||
max_payload_bytes: None,
|
||||
max_fragment_bytes: None,
|
||||
max_pending_reliable_packets: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -808,14 +831,19 @@ impl CultNetRudpSocketTransportConnection {
|
|||
port: Some(local_addr.port()),
|
||||
max_payload_bytes: options.max_payload_bytes,
|
||||
max_fragment_bytes: options.max_fragment_bytes,
|
||||
max_pending_reliable_packets: options.max_pending_reliable_packets,
|
||||
},
|
||||
);
|
||||
let max_pending_reliable_packets = options
|
||||
.max_pending_reliable_packets
|
||||
.map(|value| value as usize);
|
||||
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,
|
||||
max_pending_reliable_packets,
|
||||
}),
|
||||
mode: options.mode,
|
||||
remote_addr: options.remote_addr,
|
||||
|
|
@ -850,7 +878,7 @@ impl CultNetRudpSocketTransportConnection {
|
|||
"Only a client RUDP socket transport can initiate connect"
|
||||
));
|
||||
}
|
||||
let packet = self.session.create_connect(now_ms(), payload);
|
||||
let packet = self.session.create_connect(now_ms(), payload)?;
|
||||
self.send_packet(&packet)
|
||||
}
|
||||
|
||||
|
|
@ -969,6 +997,7 @@ pub struct RudpTransportProfileOptions {
|
|||
pub port: Option<u16>,
|
||||
pub max_payload_bytes: Option<u32>,
|
||||
pub max_fragment_bytes: Option<u32>,
|
||||
pub max_pending_reliable_packets: Option<u32>,
|
||||
}
|
||||
|
||||
pub fn create_rudp_transport_profile(
|
||||
|
|
@ -993,6 +1022,7 @@ pub fn create_rudp_transport_profile(
|
|||
ordering: CultNetTransportOrdering::Ordered,
|
||||
max_payload_bytes: options.max_payload_bytes,
|
||||
max_fragment_bytes: options.max_fragment_bytes,
|
||||
max_pending_reliable_packets: options.max_pending_reliable_packets,
|
||||
},
|
||||
CultNetTransportChannel {
|
||||
channel_id: "latest".to_string(),
|
||||
|
|
@ -1000,6 +1030,7 @@ pub fn create_rudp_transport_profile(
|
|||
ordering: CultNetTransportOrdering::Sequenced,
|
||||
max_payload_bytes: options.max_payload_bytes,
|
||||
max_fragment_bytes: options.max_fragment_bytes,
|
||||
max_pending_reliable_packets: options.max_pending_reliable_packets,
|
||||
},
|
||||
CultNetTransportChannel {
|
||||
channel_id: "realtime".to_string(),
|
||||
|
|
@ -1007,6 +1038,7 @@ pub fn create_rudp_transport_profile(
|
|||
ordering: CultNetTransportOrdering::Unordered,
|
||||
max_payload_bytes: options.max_payload_bytes,
|
||||
max_fragment_bytes: options.max_fragment_bytes,
|
||||
max_pending_reliable_packets: options.max_pending_reliable_packets,
|
||||
},
|
||||
],
|
||||
}],
|
||||
|
|
|
|||
|
|
@ -58,6 +58,7 @@ pub fn create_tcp_framed_transport_profile(
|
|||
ordering: CultNetTransportOrdering::Ordered,
|
||||
max_payload_bytes: options.max_payload_bytes,
|
||||
max_fragment_bytes: options.max_fragment_bytes,
|
||||
max_pending_reliable_packets: None,
|
||||
}],
|
||||
}],
|
||||
}
|
||||
|
|
|
|||
|
|
@ -164,6 +164,7 @@ fn cultnet_schema_messages_round_trip_through_messagepack_frames() -> Result<()>
|
|||
ordering: CultNetTransportOrdering::Ordered,
|
||||
max_payload_bytes: None,
|
||||
max_fragment_bytes: None,
|
||||
max_pending_reliable_packets: None,
|
||||
}],
|
||||
}],
|
||||
}]),
|
||||
|
|
@ -269,6 +270,7 @@ fn rudp_transport_profile_advertises_state_and_realtime_channels() {
|
|||
port: Some(7777),
|
||||
max_payload_bytes: Some(1200),
|
||||
max_fragment_bytes: Some(1000),
|
||||
max_pending_reliable_packets: Some(64),
|
||||
},
|
||||
);
|
||||
|
||||
|
|
@ -284,6 +286,7 @@ fn rudp_transport_profile_advertises_state_and_realtime_channels() {
|
|||
channel.channel_id.as_str(),
|
||||
channel.delivery,
|
||||
channel.ordering,
|
||||
channel.max_pending_reliable_packets,
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
|
@ -293,17 +296,20 @@ fn rudp_transport_profile_advertises_state_and_realtime_channels() {
|
|||
(
|
||||
"schema",
|
||||
CultNetTransportDelivery::Reliable,
|
||||
CultNetTransportOrdering::Ordered
|
||||
CultNetTransportOrdering::Ordered,
|
||||
Some(64)
|
||||
),
|
||||
(
|
||||
"latest",
|
||||
CultNetTransportDelivery::Unreliable,
|
||||
CultNetTransportOrdering::Sequenced
|
||||
CultNetTransportOrdering::Sequenced,
|
||||
Some(64)
|
||||
),
|
||||
(
|
||||
"realtime",
|
||||
CultNetTransportDelivery::Unreliable,
|
||||
CultNetTransportOrdering::Unordered
|
||||
CultNetTransportOrdering::Unordered,
|
||||
Some(64)
|
||||
),
|
||||
]
|
||||
);
|
||||
|
|
@ -315,14 +321,16 @@ fn rudp_session_handshake_acks_reliable_connect_and_accept_packets() -> Result<(
|
|||
connection_id: 0x0a0b0c0d,
|
||||
initial_sequence: 1,
|
||||
resend_delay_ms: 50,
|
||||
..CultNetRudpSessionOptions::default()
|
||||
});
|
||||
let mut server = CultNetRudpSession::new(CultNetRudpSessionOptions {
|
||||
connection_id: 0x0a0b0c0d,
|
||||
initial_sequence: 100,
|
||||
resend_delay_ms: 50,
|
||||
..CultNetRudpSessionOptions::default()
|
||||
});
|
||||
|
||||
let connect = client.create_connect(0, b"join".to_vec());
|
||||
let connect = client.create_connect(0, b"join".to_vec())?;
|
||||
assert_eq!(connect.packet_type, CultNetRudpPacketType::Connect);
|
||||
assert_eq!(connect.sequence, 1);
|
||||
assert_eq!(client.pending_reliable_sequences(), vec![1]);
|
||||
|
|
@ -350,11 +358,13 @@ fn rudp_session_computes_ack_masks_and_clears_pending_reliable_packets() -> Resu
|
|||
connection_id: 7,
|
||||
initial_sequence: 10,
|
||||
resend_delay_ms: 100,
|
||||
..CultNetRudpSessionOptions::default()
|
||||
});
|
||||
let mut receiver = CultNetRudpSession::new(CultNetRudpSessionOptions {
|
||||
connection_id: 7,
|
||||
initial_sequence: 200,
|
||||
resend_delay_ms: 100,
|
||||
..CultNetRudpSessionOptions::default()
|
||||
});
|
||||
sender.receive(
|
||||
&CultNetRudpPacket {
|
||||
|
|
@ -426,6 +436,7 @@ fn rudp_session_schedules_reliable_resends_until_acked() -> Result<()> {
|
|||
connection_id: 99,
|
||||
initial_sequence: 1,
|
||||
resend_delay_ms: 100,
|
||||
..CultNetRudpSessionOptions::default()
|
||||
});
|
||||
session.receive(
|
||||
&CultNetRudpPacket {
|
||||
|
|
@ -501,7 +512,7 @@ fn rudp_session_pings_and_detects_receive_timeout() -> Result<()> {
|
|||
initial_sequence: 100,
|
||||
..CultNetRudpSessionOptions::default()
|
||||
});
|
||||
let connect = client.create_connect(0, b"join".to_vec());
|
||||
let connect = client.create_connect(0, b"join".to_vec())?;
|
||||
let accept = server.accept_connect(&connect, 10, Vec::new())?;
|
||||
client.receive(&accept, 20)?;
|
||||
|
||||
|
|
@ -520,6 +531,105 @@ fn rudp_session_pings_and_detects_receive_timeout() -> Result<()> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rudp_session_bounds_pending_reliable_packets_before_enqueue() -> Result<()> {
|
||||
let mut session = CultNetRudpSession::new(CultNetRudpSessionOptions {
|
||||
connection_id: 102,
|
||||
initial_sequence: 1,
|
||||
max_pending_reliable_packets: Some(2),
|
||||
..CultNetRudpSessionOptions::default()
|
||||
});
|
||||
session.receive(
|
||||
&CultNetRudpPacket {
|
||||
packet_type: CultNetRudpPacketType::Accept,
|
||||
connection_id: 102,
|
||||
sequence: 50,
|
||||
ack: 0,
|
||||
ack_mask: 0,
|
||||
channel_id: "control".to_string(),
|
||||
reliable: false,
|
||||
ordered: false,
|
||||
sequenced: false,
|
||||
fragment_id: 0,
|
||||
fragment_index: 0,
|
||||
fragment_count: 0,
|
||||
payload: Vec::new(),
|
||||
},
|
||||
0,
|
||||
)?;
|
||||
session.send(
|
||||
"schema",
|
||||
b"first".to_vec(),
|
||||
CultNetRudpSendOptions {
|
||||
reliable: true,
|
||||
ordered: true,
|
||||
..CultNetRudpSendOptions::default()
|
||||
},
|
||||
)?;
|
||||
session.send(
|
||||
"schema",
|
||||
b"second".to_vec(),
|
||||
CultNetRudpSendOptions {
|
||||
reliable: true,
|
||||
ordered: true,
|
||||
..CultNetRudpSendOptions::default()
|
||||
},
|
||||
)?;
|
||||
let error = session
|
||||
.send(
|
||||
"schema",
|
||||
b"third".to_vec(),
|
||||
CultNetRudpSendOptions {
|
||||
reliable: true,
|
||||
ordered: true,
|
||||
..CultNetRudpSendOptions::default()
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("reliable send queue is full"));
|
||||
assert_eq!(session.pending_reliable_sequences(), vec![1, 2]);
|
||||
|
||||
let mut fragmented = CultNetRudpSession::new(CultNetRudpSessionOptions {
|
||||
connection_id: 103,
|
||||
initial_sequence: 1,
|
||||
max_pending_reliable_packets: Some(3),
|
||||
..CultNetRudpSessionOptions::default()
|
||||
});
|
||||
fragmented.receive(
|
||||
&CultNetRudpPacket {
|
||||
packet_type: CultNetRudpPacketType::Accept,
|
||||
connection_id: 103,
|
||||
sequence: 50,
|
||||
ack: 0,
|
||||
ack_mask: 0,
|
||||
channel_id: "control".to_string(),
|
||||
reliable: false,
|
||||
ordered: false,
|
||||
sequenced: false,
|
||||
fragment_id: 0,
|
||||
fragment_index: 0,
|
||||
fragment_count: 0,
|
||||
payload: Vec::new(),
|
||||
},
|
||||
0,
|
||||
)?;
|
||||
let error = fragmented
|
||||
.send_many(
|
||||
"schema",
|
||||
b"fragment-me".to_vec(),
|
||||
CultNetRudpSendOptions {
|
||||
reliable: true,
|
||||
ordered: true,
|
||||
..CultNetRudpSendOptions::default()
|
||||
},
|
||||
Some(3),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("reliable send queue is full"));
|
||||
assert!(fragmented.pending_reliable_sequences().is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rudp_session_suppresses_duplicates_and_delivers_reliable_ordered_payloads_in_sequence()
|
||||
-> Result<()> {
|
||||
|
|
@ -711,6 +821,7 @@ fn rudp_socket_transport_handshakes_and_carries_reliable_ordered_schema_frames()
|
|||
transport_id: None,
|
||||
max_payload_bytes: None,
|
||||
max_fragment_bytes: None,
|
||||
max_pending_reliable_packets: None,
|
||||
})?;
|
||||
let mut client =
|
||||
CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions {
|
||||
|
|
@ -724,6 +835,7 @@ fn rudp_socket_transport_handshakes_and_carries_reliable_ordered_schema_frames()
|
|||
transport_id: None,
|
||||
max_payload_bytes: None,
|
||||
max_fragment_bytes: None,
|
||||
max_pending_reliable_packets: None,
|
||||
})?;
|
||||
|
||||
client.connect(b"join".to_vec())?;
|
||||
|
|
@ -768,6 +880,7 @@ fn rudp_socket_transport_carries_fragmented_reliable_ordered_schema_frames() ->
|
|||
transport_id: None,
|
||||
max_payload_bytes: None,
|
||||
max_fragment_bytes: Some(8),
|
||||
max_pending_reliable_packets: None,
|
||||
})?;
|
||||
let mut client =
|
||||
CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions {
|
||||
|
|
@ -781,6 +894,7 @@ fn rudp_socket_transport_carries_fragmented_reliable_ordered_schema_frames() ->
|
|||
transport_id: None,
|
||||
max_payload_bytes: None,
|
||||
max_fragment_bytes: Some(8),
|
||||
max_pending_reliable_packets: None,
|
||||
})?;
|
||||
|
||||
client.connect(b"join".to_vec())?;
|
||||
|
|
|
|||
|
|
@ -69,7 +69,8 @@
|
|||
]
|
||||
},
|
||||
"maxPayloadBytes": { "type": "integer", "minimum": 1 },
|
||||
"maxFragmentBytes": { "type": "integer", "minimum": 1 }
|
||||
"maxFragmentBytes": { "type": "integer", "minimum": 1 },
|
||||
"maxPendingReliablePackets": { "type": "integer", "minimum": 1 }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -79,6 +79,7 @@ export interface CultNetTransportChannel {
|
|||
ordering: "ordered" | "unordered" | "sequenced";
|
||||
maxPayloadBytes?: number;
|
||||
maxFragmentBytes?: number;
|
||||
maxPendingReliablePackets?: number;
|
||||
}
|
||||
|
||||
export interface CultNetDocumentRecord<TPayload = unknown> {
|
||||
|
|
|
|||
|
|
@ -44,6 +44,7 @@ export interface CultNetRudpSessionOptions {
|
|||
connectionId: number;
|
||||
initialSequence?: number;
|
||||
resendDelayMs?: number;
|
||||
maxPendingReliablePackets?: number;
|
||||
}
|
||||
|
||||
export interface CultNetRudpReceiveResult {
|
||||
|
|
@ -81,6 +82,7 @@ export interface RudpTransportProfileOptions {
|
|||
port?: number;
|
||||
maxPayloadBytes?: number;
|
||||
maxFragmentBytes?: number;
|
||||
maxPendingReliablePackets?: number;
|
||||
}
|
||||
|
||||
export interface CultNetRudpSocketTransportOptions {
|
||||
|
|
@ -96,6 +98,7 @@ export interface CultNetRudpSocketTransportOptions {
|
|||
transportId?: string;
|
||||
maxPayloadBytes?: number;
|
||||
maxFragmentBytes?: number;
|
||||
maxPendingReliablePackets?: number;
|
||||
}
|
||||
|
||||
const packetTypeToCode: Record<CultNetRudpPacketType, number> = {
|
||||
|
|
@ -118,6 +121,7 @@ export class CultNetRudpSession {
|
|||
#nextSequence: number;
|
||||
#nextFragmentId = 1;
|
||||
#connected = false;
|
||||
readonly #maxPendingReliablePackets: number | undefined;
|
||||
#lastReceivedAtMs: number | undefined;
|
||||
#highestReceivedSequence: number | undefined;
|
||||
readonly #receivedSequences = new Set<number>();
|
||||
|
|
@ -130,6 +134,10 @@ export class CultNetRudpSession {
|
|||
this.connectionId = toUint32(options.connectionId, "connectionId");
|
||||
this.#nextSequence = toUint32(options.initialSequence ?? 1, "initialSequence");
|
||||
this.resendDelayMs = options.resendDelayMs ?? 250;
|
||||
if (options.maxPendingReliablePackets !== undefined && options.maxPendingReliablePackets <= 0) {
|
||||
throw new Error("RUDP maxPendingReliablePackets must be greater than zero.");
|
||||
}
|
||||
this.#maxPendingReliablePackets = options.maxPendingReliablePackets;
|
||||
}
|
||||
|
||||
get connected(): boolean {
|
||||
|
|
@ -145,6 +153,7 @@ export class CultNetRudpSession {
|
|||
}
|
||||
|
||||
createConnect(nowMs = 0, payload = new Uint8Array()): CultNetRudpPacket {
|
||||
this.#ensureReliableCapacity(1);
|
||||
const packet = this.#createPacket({
|
||||
packetType: "connect",
|
||||
channelId: "control",
|
||||
|
|
@ -162,6 +171,7 @@ export class CultNetRudpSession {
|
|||
throw new Error(`Expected RUDP connect packet, got ${packet.packetType}.`);
|
||||
}
|
||||
|
||||
this.#ensureReliableCapacity(1);
|
||||
this.#rememberReceived(packet.sequence);
|
||||
this.#connected = true;
|
||||
const response = this.#createPacket({
|
||||
|
|
@ -204,6 +214,7 @@ export class CultNetRudpSession {
|
|||
}
|
||||
|
||||
if (maxFragmentBytes === undefined || payload.byteLength <= maxFragmentBytes) {
|
||||
this.#ensureReliableCapacity(options.reliable ? 1 : 0);
|
||||
const packet = this.#createPacket({
|
||||
packetType: "data",
|
||||
channelId,
|
||||
|
|
@ -222,6 +233,7 @@ export class CultNetRudpSession {
|
|||
if (fragmentCount > 0xffff) {
|
||||
throw new Error("RUDP payload requires more than 65535 fragments.");
|
||||
}
|
||||
this.#ensureReliableCapacity(options.reliable ? fragmentCount : 0);
|
||||
|
||||
const fragmentId = this.#allocateFragmentId();
|
||||
const packets: CultNetRudpPacket[] = [];
|
||||
|
|
@ -397,6 +409,15 @@ export class CultNetRudpSession {
|
|||
});
|
||||
}
|
||||
|
||||
#ensureReliableCapacity(packetCount: number): void {
|
||||
if (packetCount === 0 || this.#maxPendingReliablePackets === undefined) {
|
||||
return;
|
||||
}
|
||||
if (this.#pendingReliable.size + packetCount > this.#maxPendingReliablePackets) {
|
||||
throw new Error("RUDP reliable send queue is full.");
|
||||
}
|
||||
}
|
||||
|
||||
#applyAcknowledgements(packet: CultNetRudpPacket): void {
|
||||
this.#pendingReliable.delete(packet.ack);
|
||||
for (let bit = 0; bit < 32; bit += 1) {
|
||||
|
|
@ -598,6 +619,7 @@ export class CultNetRudpSocketTransportConnection extends EventEmitter implement
|
|||
connectionId: options.connectionId,
|
||||
initialSequence: options.initialSequence,
|
||||
resendDelayMs: options.resendDelayMs,
|
||||
maxPendingReliablePackets: options.maxPendingReliablePackets,
|
||||
});
|
||||
const address = this.#socket.address();
|
||||
const localPort = typeof address === "string" ? undefined : address.port;
|
||||
|
|
@ -608,6 +630,7 @@ export class CultNetRudpSocketTransportConnection extends EventEmitter implement
|
|||
port: localPort,
|
||||
maxPayloadBytes: options.maxPayloadBytes,
|
||||
maxFragmentBytes: options.maxFragmentBytes,
|
||||
maxPendingReliablePackets: options.maxPendingReliablePackets,
|
||||
});
|
||||
|
||||
this.#socket.on("message", (wire, remote) => this.#receiveDatagram(wire, remote));
|
||||
|
|
@ -755,6 +778,9 @@ export function createRudpTransportProfile(
|
|||
if (options.maxFragmentBytes !== undefined) {
|
||||
value.maxFragmentBytes = options.maxFragmentBytes;
|
||||
}
|
||||
if (options.maxPendingReliablePackets !== undefined) {
|
||||
value.maxPendingReliablePackets = options.maxPendingReliablePackets;
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -360,6 +360,27 @@ test("rudp session pings and detects receive timeout", () => {
|
|||
assert.equal(client.connected, false);
|
||||
});
|
||||
|
||||
test("rudp session bounds pending reliable packets before enqueue", () => {
|
||||
const session = new CultNetRudpSession({ connectionId: 102, initialSequence: 1, maxPendingReliablePackets: 2 });
|
||||
session.receive({ packetType: "accept", connectionId: 102, sequence: 50, ack: 0, ackMask: 0, channelId: "control" });
|
||||
|
||||
session.send("schema", Buffer.from("first"), { reliable: true, ordered: true });
|
||||
session.send("schema", Buffer.from("second"), { reliable: true, ordered: true });
|
||||
assert.throws(
|
||||
() => session.send("schema", Buffer.from("third"), { reliable: true, ordered: true }),
|
||||
/reliable send queue is full/,
|
||||
);
|
||||
assert.deepEqual(session.pendingReliableSequences, [1, 2]);
|
||||
|
||||
const fragmented = new CultNetRudpSession({ connectionId: 103, initialSequence: 1, maxPendingReliablePackets: 3 });
|
||||
fragmented.receive({ packetType: "accept", connectionId: 103, sequence: 50, ack: 0, ackMask: 0, channelId: "control" });
|
||||
assert.throws(
|
||||
() => fragmented.sendMany("schema", Buffer.from("fragment-me"), { reliable: true, ordered: true, maxFragmentBytes: 3 }),
|
||||
/reliable send queue is full/,
|
||||
);
|
||||
assert.deepEqual(fragmented.pendingReliableSequences, []);
|
||||
});
|
||||
|
||||
test("rudp session suppresses duplicates and delivers reliable ordered payloads in sequence", () => {
|
||||
const sender = new CultNetRudpSession({ connectionId: 123, initialSequence: 1 });
|
||||
const receiver = new CultNetRudpSession({ connectionId: 123, initialSequence: 100 });
|
||||
|
|
|
|||
|
|
@ -249,6 +249,7 @@ export const discoveryTransportProfileSchema = z.object({
|
|||
ordering: z.enum(["ordered", "unordered", "sequenced"]),
|
||||
maxPayloadBytes: z.number().int().min(1).nullable().optional(),
|
||||
maxFragmentBytes: z.number().int().min(1).nullable().optional(),
|
||||
maxPendingReliablePackets: z.number().int().min(1).nullable().optional(),
|
||||
})),
|
||||
})),
|
||||
});
|
||||
|
|
|
|||
|
|
@ -69,7 +69,8 @@
|
|||
]
|
||||
},
|
||||
"maxPayloadBytes": { "type": "integer", "minimum": 1 },
|
||||
"maxFragmentBytes": { "type": "integer", "minimum": 1 }
|
||||
"maxFragmentBytes": { "type": "integer", "minimum": 1 },
|
||||
"maxPendingReliablePackets": { "type": "integer", "minimum": 1 }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -349,6 +349,10 @@ namespace GameCult.Networking
|
|||
/// Gets or sets the maximum fragment bytes.
|
||||
/// </summary>
|
||||
[Key("maxFragmentBytes")] public int? MaxFragmentBytes { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum pending reliable packet count.
|
||||
/// </summary>
|
||||
[Key("maxPendingReliablePackets")] public int? MaxPendingReliablePackets { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
|
|||
|
|
@ -112,6 +112,10 @@ namespace GameCult.Networking
|
|||
/// Gets or sets the maximum fragment size for RUDP channels.
|
||||
/// </summary>
|
||||
public int? MaxFragmentBytes { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum pending reliable packet count for RUDP channels.
|
||||
/// </summary>
|
||||
public int? MaxPendingReliablePackets { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -189,7 +193,8 @@ namespace GameCult.Networking
|
|||
Delivery = "reliable",
|
||||
Ordering = "ordered",
|
||||
MaxPayloadBytes = options.MaxPayloadBytes,
|
||||
MaxFragmentBytes = options.MaxFragmentBytes
|
||||
MaxFragmentBytes = options.MaxFragmentBytes,
|
||||
MaxPendingReliablePackets = options.MaxPendingReliablePackets
|
||||
},
|
||||
new CultNetTransportChannel
|
||||
{
|
||||
|
|
@ -197,7 +202,8 @@ namespace GameCult.Networking
|
|||
Delivery = "unreliable",
|
||||
Ordering = "sequenced",
|
||||
MaxPayloadBytes = options.MaxPayloadBytes,
|
||||
MaxFragmentBytes = options.MaxFragmentBytes
|
||||
MaxFragmentBytes = options.MaxFragmentBytes,
|
||||
MaxPendingReliablePackets = options.MaxPendingReliablePackets
|
||||
},
|
||||
new CultNetTransportChannel
|
||||
{
|
||||
|
|
@ -205,7 +211,8 @@ namespace GameCult.Networking
|
|||
Delivery = "unreliable",
|
||||
Ordering = "unordered",
|
||||
MaxPayloadBytes = options.MaxPayloadBytes,
|
||||
MaxFragmentBytes = options.MaxFragmentBytes
|
||||
MaxFragmentBytes = options.MaxFragmentBytes,
|
||||
MaxPendingReliablePackets = options.MaxPendingReliablePackets
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -479,6 +486,10 @@ namespace GameCult.Networking
|
|||
/// Gets or sets the resend delay in milliseconds.
|
||||
/// </summary>
|
||||
public long ResendDelayMs { get; set; } = 250;
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum pending reliable packet count.
|
||||
/// </summary>
|
||||
public int? MaxPendingReliablePackets { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -564,6 +575,10 @@ namespace GameCult.Networking
|
|||
/// Gets or sets the maximum fragment size for RUDP channels.
|
||||
/// </summary>
|
||||
public int? MaxFragmentBytes { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum pending reliable packet count for RUDP channels.
|
||||
/// </summary>
|
||||
public int? MaxPendingReliablePackets { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -594,6 +609,7 @@ namespace GameCult.Networking
|
|||
|
||||
private uint _nextSequence;
|
||||
private ushort _nextFragmentId = 1;
|
||||
private readonly int? _maxPendingReliablePackets;
|
||||
private bool _connected;
|
||||
private long? _lastReceivedAtMs;
|
||||
private uint? _highestReceivedSequence;
|
||||
|
|
@ -610,9 +626,15 @@ namespace GameCult.Networking
|
|||
public CultNetRudpSession(CultNetRudpSessionOptions options)
|
||||
{
|
||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||
if (options.MaxPendingReliablePackets.HasValue && options.MaxPendingReliablePackets.Value <= 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(options), "RUDP MaxPendingReliablePackets must be greater than zero.");
|
||||
}
|
||||
|
||||
ConnectionId = options.ConnectionId;
|
||||
_nextSequence = options.InitialSequence;
|
||||
ResendDelayMs = options.ResendDelayMs;
|
||||
_maxPendingReliablePackets = options.MaxPendingReliablePackets;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -641,6 +663,7 @@ namespace GameCult.Networking
|
|||
/// </summary>
|
||||
public CultNetRudpPacket CreateConnect(long nowMs = 0, byte[]? payload = null)
|
||||
{
|
||||
EnsureReliableCapacity(1);
|
||||
var packet = CreatePacket(CultNetRudpPacketType.Connect, "control", payload ?? Array.Empty<byte>(), reliable: true, ordered: true, sequenced: false);
|
||||
TrackReliable(packet, nowMs);
|
||||
return packet;
|
||||
|
|
@ -657,6 +680,7 @@ namespace GameCult.Networking
|
|||
throw new InvalidOperationException($"Expected RUDP connect packet, got {packet.PacketType}.");
|
||||
}
|
||||
|
||||
EnsureReliableCapacity(1);
|
||||
RememberReceived(packet.Sequence);
|
||||
_connected = true;
|
||||
var response = CreatePacket(CultNetRudpPacketType.Accept, "control", payload ?? Array.Empty<byte>(), reliable: true, ordered: true, sequenced: false);
|
||||
|
|
@ -697,6 +721,7 @@ namespace GameCult.Networking
|
|||
throw new InvalidOperationException("RUDP payload requires more than 65535 fragments.");
|
||||
}
|
||||
|
||||
EnsureReliableCapacity(options.Reliable ? fragmentCount : 0);
|
||||
var fragmentId = AllocateFragmentId();
|
||||
var packets = new List<CultNetRudpPacket>();
|
||||
for (var index = 0; index < fragmentCount; index++)
|
||||
|
|
@ -724,6 +749,7 @@ namespace GameCult.Networking
|
|||
return packets;
|
||||
}
|
||||
|
||||
EnsureReliableCapacity(options.Reliable ? 1 : 0);
|
||||
var packet = CreatePacket(
|
||||
CultNetRudpPacketType.Data,
|
||||
channelId,
|
||||
|
|
@ -933,6 +959,19 @@ namespace GameCult.Networking
|
|||
};
|
||||
}
|
||||
|
||||
private void EnsureReliableCapacity(int packetCount)
|
||||
{
|
||||
if (packetCount == 0 || !_maxPendingReliablePackets.HasValue)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_pendingReliable.Count + packetCount > _maxPendingReliablePackets.Value)
|
||||
{
|
||||
throw new InvalidOperationException("RUDP reliable send queue is full.");
|
||||
}
|
||||
}
|
||||
|
||||
private void ApplyAcknowledgements(CultNetRudpPacket packet)
|
||||
{
|
||||
_pendingReliable.Remove(packet.Ack);
|
||||
|
|
@ -1168,7 +1207,8 @@ namespace GameCult.Networking
|
|||
{
|
||||
ConnectionId = options.ConnectionId,
|
||||
InitialSequence = options.InitialSequence,
|
||||
ResendDelayMs = options.ResendDelayMs
|
||||
ResendDelayMs = options.ResendDelayMs,
|
||||
MaxPendingReliablePackets = options.MaxPendingReliablePackets
|
||||
});
|
||||
|
||||
var local = _socket.LocalEndPoint as IPEndPoint;
|
||||
|
|
@ -1180,7 +1220,8 @@ namespace GameCult.Networking
|
|||
Host = local?.Address.ToString(),
|
||||
Port = local?.Port,
|
||||
MaxPayloadBytes = options.MaxPayloadBytes,
|
||||
MaxFragmentBytes = options.MaxFragmentBytes
|
||||
MaxFragmentBytes = options.MaxFragmentBytes,
|
||||
MaxPendingReliablePackets = options.MaxPendingReliablePackets
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -354,7 +354,8 @@ namespace GameCult.Networking.Tests
|
|||
Host = "127.0.0.1",
|
||||
Port = 7777,
|
||||
MaxPayloadBytes = 1200,
|
||||
MaxFragmentBytes = 1000
|
||||
MaxFragmentBytes = 1000,
|
||||
MaxPendingReliablePackets = 64
|
||||
});
|
||||
|
||||
Assert.That(profile.Transports[0].Protocol, Is.EqualTo("rudp"));
|
||||
|
|
@ -366,6 +367,9 @@ namespace GameCult.Networking.Tests
|
|||
"latest:unreliable:sequenced",
|
||||
"realtime:unreliable:unordered"
|
||||
}));
|
||||
Assert.That(
|
||||
profile.Transports[0].Channels.Select(channel => channel.MaxPendingReliablePackets).ToArray(),
|
||||
Is.EqualTo(new int?[] { 64, 64, 64 }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
|
|
@ -494,6 +498,42 @@ namespace GameCult.Networking.Tests
|
|||
Assert.That(client.Connected, Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RudpSession_BoundsPendingReliablePacketsBeforeEnqueue()
|
||||
{
|
||||
var session = new CultNetRudpSession(new CultNetRudpSessionOptions
|
||||
{
|
||||
ConnectionId = 102,
|
||||
InitialSequence = 1,
|
||||
MaxPendingReliablePackets = 2
|
||||
});
|
||||
session.Receive(new CultNetRudpPacket { PacketType = CultNetRudpPacketType.Accept, ConnectionId = 102, Sequence = 50, ChannelId = "control" });
|
||||
session.Send("schema", Encoding.UTF8.GetBytes("first"), new CultNetRudpSendOptions { Reliable = true, Ordered = true });
|
||||
session.Send("schema", Encoding.UTF8.GetBytes("second"), new CultNetRudpSendOptions { Reliable = true, Ordered = true });
|
||||
|
||||
var error = Assert.Throws<InvalidOperationException>(() =>
|
||||
session.Send("schema", Encoding.UTF8.GetBytes("third"), new CultNetRudpSendOptions { Reliable = true, Ordered = true }));
|
||||
Assert.That(error!.Message, Does.Contain("reliable send queue is full"));
|
||||
Assert.That(session.PendingReliableSequences, Is.EqualTo(new uint[] { 1, 2 }));
|
||||
|
||||
var fragmented = new CultNetRudpSession(new CultNetRudpSessionOptions
|
||||
{
|
||||
ConnectionId = 103,
|
||||
InitialSequence = 1,
|
||||
MaxPendingReliablePackets = 3
|
||||
});
|
||||
fragmented.Receive(new CultNetRudpPacket { PacketType = CultNetRudpPacketType.Accept, ConnectionId = 103, Sequence = 50, ChannelId = "control" });
|
||||
|
||||
error = Assert.Throws<InvalidOperationException>(() =>
|
||||
fragmented.SendMany(
|
||||
"schema",
|
||||
Encoding.UTF8.GetBytes("fragment-me"),
|
||||
new CultNetRudpSendOptions { Reliable = true, Ordered = true },
|
||||
maxFragmentBytes: 3));
|
||||
Assert.That(error!.Message, Does.Contain("reliable send queue is full"));
|
||||
Assert.That(fragmented.PendingReliableSequences, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RudpSession_SuppressesDuplicatesAndDeliversReliableOrderedPayloadsInSequence()
|
||||
{
|
||||
|
|
|
|||
Loading…
Reference in a new issue