Add RUDP ping timeout parity
This commit is contained in:
parent
59146888c0
commit
8287926921
11 changed files with 449 additions and 8 deletions
|
|
@ -198,10 +198,16 @@ Current progress:
|
|||
raw reason bytes, socket transports surface the remote reason, and the
|
||||
TypeScript interop harness proves reason propagation from C#/Kotlin/Python/Rust
|
||||
one-shot UDP peers.
|
||||
- TypeScript, C#, Rust, Python, and Kotlin now share transport-level ping/pong
|
||||
and receive-timeout state: sessions create pings, answer pings with pongs,
|
||||
expose pong payloads, and mark themselves disconnected after a configured
|
||||
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.
|
||||
- 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, timeout detection,
|
||||
backpressure, and the wider schema-message matrix.
|
||||
ports, then broaden RUDP interop into reconnect policy, backpressure, and the
|
||||
wider schema-message matrix.
|
||||
|
||||
## RUDP Packet Contract V0
|
||||
|
||||
|
|
|
|||
|
|
@ -104,6 +104,8 @@ class CultNetRudpDeliveredFrame:
|
|||
class CultNetRudpReceiveResult:
|
||||
delivered: tuple[CultNetRudpDeliveredFrame, ...] = field(default_factory=tuple)
|
||||
reply: CultNetRudpPacket | None = None
|
||||
pong: bool = False
|
||||
pong_payload: bytes = b""
|
||||
disconnected: bool = False
|
||||
disconnect_reason: bytes = b""
|
||||
|
||||
|
|
@ -210,6 +212,7 @@ class CultNetRudpSession:
|
|||
self._next_sequence = _uint32(options.initial_sequence, "initial_sequence")
|
||||
self._next_fragment_id = 1
|
||||
self._connected = False
|
||||
self._last_received_at_ms: int | None = None
|
||||
self._highest_received_sequence: int | None = None
|
||||
self._received_sequences: set[int] = set()
|
||||
self._pending_reliable: dict[int, _PendingReliablePacket] = {}
|
||||
|
|
@ -221,6 +224,10 @@ class CultNetRudpSession:
|
|||
def connected(self) -> bool:
|
||||
return self._connected
|
||||
|
||||
@property
|
||||
def last_received_at_ms(self) -> int | None:
|
||||
return self._last_received_at_ms
|
||||
|
||||
@property
|
||||
def pending_reliable_sequences(self) -> tuple[int, ...]:
|
||||
return tuple(sorted(self._pending_reliable))
|
||||
|
|
@ -319,9 +326,9 @@ class CultNetRudpSession:
|
|||
return tuple(packets)
|
||||
|
||||
def receive(self, packet: CultNetRudpPacket, now_ms: int = 0) -> CultNetRudpReceiveResult:
|
||||
del now_ms
|
||||
self._require_connection(packet)
|
||||
self._apply_acknowledgements(packet)
|
||||
self._last_received_at_ms = now_ms
|
||||
expected_sequence_if_uninitialized = (
|
||||
packet.sequence
|
||||
if self._highest_received_sequence is None
|
||||
|
|
@ -341,7 +348,10 @@ class CultNetRudpSession:
|
|||
|
||||
if packet.packet_type in (CultNetRudpPacketType.ACK, CultNetRudpPacketType.PONG):
|
||||
self._remember_received(packet.sequence)
|
||||
return CultNetRudpReceiveResult()
|
||||
return CultNetRudpReceiveResult(
|
||||
pong=packet.packet_type == CultNetRudpPacketType.PONG,
|
||||
pong_payload=bytes(packet.payload) if packet.packet_type == CultNetRudpPacketType.PONG else b"",
|
||||
)
|
||||
|
||||
if packet.packet_type == CultNetRudpPacketType.DISCONNECT:
|
||||
self._remember_received(packet.sequence)
|
||||
|
|
@ -374,10 +384,21 @@ class CultNetRudpSession:
|
|||
def create_ack(self) -> CultNetRudpPacket:
|
||||
return self._create_packet(CultNetRudpPacketType.ACK, "control", b"")
|
||||
|
||||
def create_ping(self, payload: bytes = b"") -> CultNetRudpPacket:
|
||||
return self._create_packet(CultNetRudpPacketType.PING, "control", payload)
|
||||
|
||||
def create_disconnect(self, reason: bytes = b"") -> CultNetRudpPacket:
|
||||
self._connected = False
|
||||
return self._create_packet(CultNetRudpPacketType.DISCONNECT, "control", reason)
|
||||
|
||||
def check_timeout(self, now_ms: int, timeout_ms: int) -> bool:
|
||||
if not self._connected or self._last_received_at_ms is None:
|
||||
return False
|
||||
if now_ms - self._last_received_at_ms <= timeout_ms:
|
||||
return False
|
||||
self._connected = False
|
||||
return True
|
||||
|
||||
def due_resends(self, now_ms: int) -> tuple[CultNetRudpPacket, ...]:
|
||||
due: list[CultNetRudpPacket] = []
|
||||
for pending in self._pending_reliable.values():
|
||||
|
|
@ -573,6 +594,7 @@ class CultNetRudpSocketTransportConnection:
|
|||
self._delivered_frames: deque[CultNetTransportFrame] = deque()
|
||||
self._closed = False
|
||||
self.disconnect_reason: bytes | None = None
|
||||
self.pong_payloads: deque[bytes] = deque()
|
||||
|
||||
@property
|
||||
def connected(self) -> bool:
|
||||
|
|
@ -628,6 +650,8 @@ class CultNetRudpSocketTransportConnection:
|
|||
result = self.session.receive(packet, _now_ms())
|
||||
if result.reply is not None:
|
||||
self._send_packet(result.reply)
|
||||
if result.pong:
|
||||
self.pong_payloads.append(result.pong_payload)
|
||||
if result.disconnected:
|
||||
self.disconnect_reason = result.disconnect_reason
|
||||
return None
|
||||
|
|
@ -646,6 +670,12 @@ class CultNetRudpSocketTransportConnection:
|
|||
def disconnect(self, reason: bytes = b"") -> None:
|
||||
self._send_packet(self.session.create_disconnect(reason))
|
||||
|
||||
def ping(self, payload: bytes = b"") -> None:
|
||||
self._send_packet(self.session.create_ping(payload))
|
||||
|
||||
def check_timeout(self, timeout_ms: int, now_ms: int | None = None) -> bool:
|
||||
return self.session.check_timeout(_now_ms() if now_ms is None else now_ms, timeout_ms)
|
||||
|
||||
def poll_resends(self) -> None:
|
||||
for packet in self.session.due_resends(_now_ms()):
|
||||
self._send_packet(packet)
|
||||
|
|
|
|||
|
|
@ -775,6 +775,26 @@ class CultCacheTests(unittest.TestCase):
|
|||
)
|
||||
self.assertEqual(session.due_resends(250), ())
|
||||
|
||||
def test_cultnet_rudp_session_pings_and_detects_receive_timeout(self) -> None:
|
||||
client = CultNetRudpSession(CultNetRudpSessionOptions(connection_id=101, initial_sequence=1))
|
||||
server = CultNetRudpSession(CultNetRudpSessionOptions(connection_id=101, initial_sequence=100))
|
||||
connect = client.create_connect(0, b"join")
|
||||
accept = server.accept_connect(connect, 10)
|
||||
client.receive(accept, 20)
|
||||
|
||||
ping = client.create_ping(b"pulse")
|
||||
ping_result = server.receive(ping, 30)
|
||||
self.assertIsNotNone(ping_result.reply)
|
||||
self.assertEqual(ping_result.reply.packet_type, CultNetRudpPacketType.PONG)
|
||||
self.assertEqual(ping_result.reply.payload, b"pulse")
|
||||
|
||||
pong_result = client.receive(ping_result.reply, 40)
|
||||
self.assertTrue(pong_result.pong)
|
||||
self.assertEqual(pong_result.pong_payload, b"pulse")
|
||||
self.assertFalse(client.check_timeout(90, 50))
|
||||
self.assertTrue(client.check_timeout(91, 50))
|
||||
self.assertFalse(client.connected)
|
||||
|
||||
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))
|
||||
|
|
|
|||
|
|
@ -155,6 +155,8 @@ data class CultNetRudpDeliveredFrame(val channelId: String, val payload: ByteArr
|
|||
data class CultNetRudpReceiveResult(
|
||||
val delivered: List<CultNetRudpDeliveredFrame> = emptyList(),
|
||||
val reply: CultNetRudpPacket? = null,
|
||||
val pong: Boolean = false,
|
||||
val pongPayload: ByteArray = ByteArray(0),
|
||||
val disconnected: Boolean = false,
|
||||
val disconnectReason: ByteArray = ByteArray(0),
|
||||
)
|
||||
|
|
@ -189,6 +191,8 @@ class CultNetRudpSession(options: CultNetRudpSessionOptions) {
|
|||
private var nextFragmentId = 1
|
||||
var connected: Boolean = false
|
||||
private set
|
||||
var lastReceivedAtMs: Long? = null
|
||||
private set
|
||||
private var highestReceivedSequence: Long? = null
|
||||
private val receivedSequences = linkedSetOf<Long>()
|
||||
private val pendingReliable = linkedMapOf<Long, PendingReliablePacket>()
|
||||
|
|
@ -258,6 +262,7 @@ class CultNetRudpSession(options: CultNetRudpSessionOptions) {
|
|||
val ignoredNow = nowMs
|
||||
requireConnection(packet)
|
||||
applyAcknowledgements(packet)
|
||||
lastReceivedAtMs = nowMs
|
||||
val expectedSequenceIfUninitialized = (highestReceivedSequence ?: (packet.sequence - 1)) + 1
|
||||
when (packet.packetType) {
|
||||
CultNetRudpPacketType.Accept -> {
|
||||
|
|
@ -271,7 +276,10 @@ class CultNetRudpSession(options: CultNetRudpSessionOptions) {
|
|||
}
|
||||
CultNetRudpPacketType.Ack, CultNetRudpPacketType.Pong -> {
|
||||
rememberReceived(packet.sequence)
|
||||
return CultNetRudpReceiveResult()
|
||||
return CultNetRudpReceiveResult(
|
||||
pong = packet.packetType == CultNetRudpPacketType.Pong,
|
||||
pongPayload = if (packet.packetType == CultNetRudpPacketType.Pong) packet.payload.copyOf() else ByteArray(0),
|
||||
)
|
||||
}
|
||||
CultNetRudpPacketType.Disconnect -> {
|
||||
rememberReceived(packet.sequence)
|
||||
|
|
@ -291,11 +299,21 @@ class CultNetRudpSession(options: CultNetRudpSessionOptions) {
|
|||
|
||||
fun createAck(): CultNetRudpPacket = createPacket(CultNetRudpPacketType.Ack, "control", ByteArray(0))
|
||||
|
||||
fun createPing(payload: ByteArray = ByteArray(0)): CultNetRudpPacket =
|
||||
createPacket(CultNetRudpPacketType.Ping, "control", payload)
|
||||
|
||||
fun createDisconnect(reason: ByteArray = ByteArray(0)): CultNetRudpPacket {
|
||||
connected = false
|
||||
return createPacket(CultNetRudpPacketType.Disconnect, "control", reason)
|
||||
}
|
||||
|
||||
fun checkTimeout(nowMs: Long, timeoutMs: Long): Boolean {
|
||||
val lastReceived = lastReceivedAtMs ?: return false
|
||||
if (!connected || nowMs - lastReceived <= timeoutMs) return false
|
||||
connected = false
|
||||
return true
|
||||
}
|
||||
|
||||
fun dueResends(nowMs: Long): List<CultNetRudpPacket> =
|
||||
pendingReliable.values
|
||||
.filter { nowMs - it.lastSentAtMs >= resendDelayMs }
|
||||
|
|
@ -433,6 +451,7 @@ class CultNetRudpSocketTransportConnection(
|
|||
private val session = CultNetRudpSession(CultNetRudpSessionOptions(connectionId, initialSequence, resendDelayMs))
|
||||
private var remote = remoteAddress
|
||||
private val delivered = ArrayDeque<CultNetTransportFrame>()
|
||||
private val pongPayloads = ArrayDeque<ByteArray>()
|
||||
private var bytesReceived = 0L
|
||||
private var bytesSent = 0L
|
||||
private var framesReceived = 0L
|
||||
|
|
@ -463,6 +482,14 @@ class CultNetRudpSocketTransportConnection(
|
|||
sendPacket(session.createDisconnect(reason))
|
||||
}
|
||||
|
||||
fun ping(payload: ByteArray = ByteArray(0)) {
|
||||
sendPacket(session.createPing(payload))
|
||||
}
|
||||
|
||||
fun pollPongPayload(): ByteArray? = if (pongPayloads.isEmpty()) null else pongPayloads.removeFirst()
|
||||
|
||||
fun checkTimeout(timeoutMs: Long): Boolean = session.checkTimeout(nowMs(), timeoutMs)
|
||||
|
||||
fun receiveOnce(): CultNetTransportFrame? {
|
||||
if (!delivered.isEmpty()) return delivered.removeFirst()
|
||||
val buffer = ByteArray(65535)
|
||||
|
|
@ -486,6 +513,9 @@ class CultNetRudpSocketTransportConnection(
|
|||
}
|
||||
val result = session.receive(packet, nowMs())
|
||||
result.reply?.let { sendPacket(it) }
|
||||
if (result.pong) {
|
||||
pongPayloads.add(result.pongPayload.copyOf())
|
||||
}
|
||||
if (result.disconnected) {
|
||||
disconnectReason = result.disconnectReason.copyOf()
|
||||
return null
|
||||
|
|
@ -602,6 +632,7 @@ private fun nowMs(): Long = Instant.now().toEpochMilli()
|
|||
fun main(args: Array<String>) {
|
||||
if (args.isEmpty()) {
|
||||
rudpPacketCodecUsesDeterministicReliableOrderedFixture()
|
||||
rudpSessionPingsAndDetectsReceiveTimeout()
|
||||
rudpSessionFragmentsAndReassemblesReliableOrderedPayloads()
|
||||
rudpSocketTransportHandshakesAndCarriesReliableOrderedSchemaFrames()
|
||||
rudpSocketTransportCarriesFragmentedReliableOrderedSchemaFrames()
|
||||
|
|
@ -762,6 +793,27 @@ private fun rudpPacketCodecUsesDeterministicReliableOrderedFixture() {
|
|||
check(String(decoded.payload, StandardCharsets.UTF_8) == "hello")
|
||||
}
|
||||
|
||||
private fun rudpSessionPingsAndDetectsReceiveTimeout() {
|
||||
val client = CultNetRudpSession(CultNetRudpSessionOptions(connectionId = 101, initialSequence = 1))
|
||||
val server = CultNetRudpSession(CultNetRudpSessionOptions(connectionId = 101, initialSequence = 100))
|
||||
val connect = client.createConnect(0, "join".toByteArray(StandardCharsets.UTF_8))
|
||||
val accept = server.acceptConnect(connect, 10)
|
||||
client.receive(accept, 20)
|
||||
|
||||
val ping = client.createPing("pulse".toByteArray(StandardCharsets.UTF_8))
|
||||
val pingResult = server.receive(ping, 30)
|
||||
val pong = pingResult.reply ?: error("Ping did not produce a pong")
|
||||
check(pong.packetType == CultNetRudpPacketType.Pong)
|
||||
check(String(pong.payload, StandardCharsets.UTF_8) == "pulse")
|
||||
|
||||
val pongResult = client.receive(pong, 40)
|
||||
check(pongResult.pong)
|
||||
check(String(pongResult.pongPayload, StandardCharsets.UTF_8) == "pulse")
|
||||
check(!client.checkTimeout(90, 50))
|
||||
check(client.checkTimeout(91, 50))
|
||||
check(!client.connected)
|
||||
}
|
||||
|
||||
private fun rudpSessionFragmentsAndReassemblesReliableOrderedPayloads() {
|
||||
val sender = CultNetRudpSession(CultNetRudpSessionOptions(connectionId = 456, initialSequence = 1))
|
||||
val receiver = CultNetRudpSession(CultNetRudpSessionOptions(connectionId = 456, initialSequence = 100))
|
||||
|
|
|
|||
|
|
@ -61,6 +61,8 @@ pub struct CultNetRudpDeliveredFrame {
|
|||
pub struct CultNetRudpReceiveResult {
|
||||
pub delivered: Vec<CultNetRudpDeliveredFrame>,
|
||||
pub reply: Option<CultNetRudpPacket>,
|
||||
pub pong: bool,
|
||||
pub pong_payload: Vec<u8>,
|
||||
pub disconnected: bool,
|
||||
pub disconnect_reason: Vec<u8>,
|
||||
}
|
||||
|
|
@ -117,6 +119,7 @@ pub struct CultNetRudpSession {
|
|||
next_sequence: u32,
|
||||
next_fragment_id: u16,
|
||||
connected: bool,
|
||||
last_received_at_ms: Option<u64>,
|
||||
highest_received_sequence: Option<u32>,
|
||||
received_sequences: BTreeSet<u32>,
|
||||
pending_reliable: BTreeMap<u32, PendingReliablePacket>,
|
||||
|
|
@ -133,6 +136,7 @@ impl CultNetRudpSession {
|
|||
next_sequence: options.initial_sequence,
|
||||
next_fragment_id: 1,
|
||||
connected: false,
|
||||
last_received_at_ms: None,
|
||||
highest_received_sequence: None,
|
||||
received_sequences: BTreeSet::new(),
|
||||
pending_reliable: BTreeMap::new(),
|
||||
|
|
@ -158,6 +162,10 @@ impl CultNetRudpSession {
|
|||
self.pending_reliable.keys().copied().collect()
|
||||
}
|
||||
|
||||
pub fn last_received_at_ms(&self) -> Option<u64> {
|
||||
self.last_received_at_ms
|
||||
}
|
||||
|
||||
pub fn create_connect(&mut self, now_ms: u64, payload: Vec<u8>) -> CultNetRudpPacket {
|
||||
let packet = self.create_packet(
|
||||
CultNetRudpPacketType::Connect,
|
||||
|
|
@ -275,10 +283,11 @@ impl CultNetRudpSession {
|
|||
pub fn receive(
|
||||
&mut self,
|
||||
packet: &CultNetRudpPacket,
|
||||
_now_ms: u64,
|
||||
now_ms: u64,
|
||||
) -> Result<CultNetRudpReceiveResult> {
|
||||
self.require_connection(packet)?;
|
||||
self.apply_acknowledgements(packet);
|
||||
self.last_received_at_ms = Some(now_ms);
|
||||
let expected_sequence_if_uninitialized = self
|
||||
.highest_received_sequence
|
||||
.map(|sequence| sequence + 1)
|
||||
|
|
@ -290,6 +299,8 @@ impl CultNetRudpSession {
|
|||
return Ok(CultNetRudpReceiveResult {
|
||||
delivered: Vec::new(),
|
||||
reply: None,
|
||||
pong: false,
|
||||
pong_payload: Vec::new(),
|
||||
disconnected: false,
|
||||
disconnect_reason: Vec::new(),
|
||||
});
|
||||
|
|
@ -307,6 +318,8 @@ impl CultNetRudpSession {
|
|||
false,
|
||||
false,
|
||||
)),
|
||||
pong: false,
|
||||
pong_payload: Vec::new(),
|
||||
disconnected: false,
|
||||
disconnect_reason: Vec::new(),
|
||||
});
|
||||
|
|
@ -319,6 +332,12 @@ impl CultNetRudpSession {
|
|||
return Ok(CultNetRudpReceiveResult {
|
||||
delivered: Vec::new(),
|
||||
reply: None,
|
||||
pong: packet.packet_type == CultNetRudpPacketType::Pong,
|
||||
pong_payload: if packet.packet_type == CultNetRudpPacketType::Pong {
|
||||
packet.payload.clone()
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
disconnected: false,
|
||||
disconnect_reason: Vec::new(),
|
||||
});
|
||||
|
|
@ -330,6 +349,8 @@ impl CultNetRudpSession {
|
|||
return Ok(CultNetRudpReceiveResult {
|
||||
delivered: Vec::new(),
|
||||
reply: None,
|
||||
pong: false,
|
||||
pong_payload: Vec::new(),
|
||||
disconnected: true,
|
||||
disconnect_reason: packet.payload.clone(),
|
||||
});
|
||||
|
|
@ -339,6 +360,8 @@ impl CultNetRudpSession {
|
|||
return Ok(CultNetRudpReceiveResult {
|
||||
delivered: Vec::new(),
|
||||
reply: None,
|
||||
pong: false,
|
||||
pong_payload: Vec::new(),
|
||||
disconnected: false,
|
||||
disconnect_reason: Vec::new(),
|
||||
});
|
||||
|
|
@ -350,6 +373,8 @@ impl CultNetRudpSession {
|
|||
return Ok(CultNetRudpReceiveResult {
|
||||
delivered: Vec::new(),
|
||||
reply: None,
|
||||
pong: false,
|
||||
pong_payload: Vec::new(),
|
||||
disconnected: false,
|
||||
disconnect_reason: Vec::new(),
|
||||
});
|
||||
|
|
@ -359,6 +384,8 @@ impl CultNetRudpSession {
|
|||
return Ok(CultNetRudpReceiveResult {
|
||||
delivered: Vec::new(),
|
||||
reply: None,
|
||||
pong: false,
|
||||
pong_payload: Vec::new(),
|
||||
disconnected: false,
|
||||
disconnect_reason: Vec::new(),
|
||||
});
|
||||
|
|
@ -371,6 +398,8 @@ impl CultNetRudpSession {
|
|||
Ok(CultNetRudpReceiveResult {
|
||||
delivered,
|
||||
reply: None,
|
||||
pong: false,
|
||||
pong_payload: Vec::new(),
|
||||
disconnected: false,
|
||||
disconnect_reason: Vec::new(),
|
||||
})
|
||||
|
|
@ -387,6 +416,17 @@ impl CultNetRudpSession {
|
|||
)
|
||||
}
|
||||
|
||||
pub fn create_ping(&mut self, payload: Vec<u8>) -> CultNetRudpPacket {
|
||||
self.create_packet(
|
||||
CultNetRudpPacketType::Ping,
|
||||
"control",
|
||||
payload,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn create_disconnect(&mut self, reason: Vec<u8>) -> CultNetRudpPacket {
|
||||
self.connected = false;
|
||||
self.create_packet(
|
||||
|
|
@ -399,6 +439,20 @@ impl CultNetRudpSession {
|
|||
)
|
||||
}
|
||||
|
||||
pub fn check_timeout(&mut self, now_ms: u64, timeout_ms: u64) -> bool {
|
||||
if !self.connected {
|
||||
return false;
|
||||
}
|
||||
let Some(last_received_at_ms) = self.last_received_at_ms else {
|
||||
return false;
|
||||
};
|
||||
if now_ms.saturating_sub(last_received_at_ms) <= timeout_ms {
|
||||
return false;
|
||||
}
|
||||
self.connected = false;
|
||||
true
|
||||
}
|
||||
|
||||
pub fn due_resends(&mut self, now_ms: u64) -> Vec<CultNetRudpPacket> {
|
||||
let mut due = Vec::new();
|
||||
for pending in self.pending_reliable.values_mut() {
|
||||
|
|
@ -740,6 +794,7 @@ pub struct CultNetRudpSocketTransportConnection {
|
|||
delivered_frames: VecDeque<CultNetTransportFrame>,
|
||||
max_fragment_bytes: Option<usize>,
|
||||
disconnect_reason: Option<Vec<u8>>,
|
||||
pong_payloads: VecDeque<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl CultNetRudpSocketTransportConnection {
|
||||
|
|
@ -769,6 +824,7 @@ impl CultNetRudpSocketTransportConnection {
|
|||
delivered_frames: VecDeque::new(),
|
||||
max_fragment_bytes: options.max_fragment_bytes.map(|value| value as usize),
|
||||
disconnect_reason: None,
|
||||
pong_payloads: VecDeque::new(),
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -784,6 +840,10 @@ impl CultNetRudpSocketTransportConnection {
|
|||
self.disconnect_reason.as_deref()
|
||||
}
|
||||
|
||||
pub fn pop_pong_payload(&mut self) -> Option<Vec<u8>> {
|
||||
self.pong_payloads.pop_front()
|
||||
}
|
||||
|
||||
pub fn connect(&mut self, payload: Vec<u8>) -> Result<()> {
|
||||
if self.mode != CultNetRudpSocketMode::Client {
|
||||
return Err(anyhow!(
|
||||
|
|
@ -811,6 +871,15 @@ impl CultNetRudpSocketTransportConnection {
|
|||
self.send_packet(&packet)
|
||||
}
|
||||
|
||||
pub fn ping(&mut self, payload: Vec<u8>) -> Result<()> {
|
||||
let packet = self.session.create_ping(payload);
|
||||
self.send_packet(&packet)
|
||||
}
|
||||
|
||||
pub fn check_timeout(&mut self, timeout_ms: u64) -> bool {
|
||||
self.session.check_timeout(now_ms(), timeout_ms)
|
||||
}
|
||||
|
||||
pub fn receive_once(&mut self) -> Result<Option<CultNetTransportFrame>> {
|
||||
if let Some(frame) = self.delivered_frames.pop_front() {
|
||||
return Ok(Some(frame));
|
||||
|
|
@ -850,6 +919,9 @@ impl CultNetRudpSocketTransportConnection {
|
|||
if let Some(reply) = result.reply {
|
||||
self.send_packet(&reply)?;
|
||||
}
|
||||
if result.pong {
|
||||
self.pong_payloads.push_back(result.pong_payload);
|
||||
}
|
||||
if result.disconnected {
|
||||
self.disconnect_reason = Some(result.disconnect_reason);
|
||||
return Ok(None);
|
||||
|
|
|
|||
|
|
@ -489,6 +489,37 @@ fn rudp_session_schedules_reliable_resends_until_acked() -> Result<()> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rudp_session_pings_and_detects_receive_timeout() -> Result<()> {
|
||||
let mut client = CultNetRudpSession::new(CultNetRudpSessionOptions {
|
||||
connection_id: 101,
|
||||
initial_sequence: 1,
|
||||
..CultNetRudpSessionOptions::default()
|
||||
});
|
||||
let mut server = CultNetRudpSession::new(CultNetRudpSessionOptions {
|
||||
connection_id: 101,
|
||||
initial_sequence: 100,
|
||||
..CultNetRudpSessionOptions::default()
|
||||
});
|
||||
let connect = client.create_connect(0, b"join".to_vec());
|
||||
let accept = server.accept_connect(&connect, 10, Vec::new())?;
|
||||
client.receive(&accept, 20)?;
|
||||
|
||||
let ping = client.create_ping(b"pulse".to_vec());
|
||||
let ping_result = server.receive(&ping, 30)?;
|
||||
let pong = ping_result.reply.expect("ping should produce pong");
|
||||
assert_eq!(pong.packet_type, CultNetRudpPacketType::Pong);
|
||||
assert_eq!(pong.payload, b"pulse");
|
||||
|
||||
let pong_result = client.receive(&pong, 40)?;
|
||||
assert!(pong_result.pong);
|
||||
assert_eq!(pong_result.pong_payload, b"pulse");
|
||||
assert!(!client.check_timeout(90, 50));
|
||||
assert!(client.check_timeout(91, 50));
|
||||
assert!(!client.connected());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rudp_session_suppresses_duplicates_and_delivers_reliable_ordered_payloads_in_sequence()
|
||||
-> Result<()> {
|
||||
|
|
|
|||
|
|
@ -49,6 +49,8 @@ export interface CultNetRudpSessionOptions {
|
|||
export interface CultNetRudpReceiveResult {
|
||||
delivered: CultNetRudpDeliveredFrame[];
|
||||
reply?: CultNetRudpPacket;
|
||||
pong?: boolean;
|
||||
pongPayload?: Uint8Array;
|
||||
disconnected?: boolean;
|
||||
disconnectReason?: Uint8Array;
|
||||
}
|
||||
|
|
@ -116,6 +118,7 @@ export class CultNetRudpSession {
|
|||
#nextSequence: number;
|
||||
#nextFragmentId = 1;
|
||||
#connected = false;
|
||||
#lastReceivedAtMs: number | undefined;
|
||||
#highestReceivedSequence: number | undefined;
|
||||
readonly #receivedSequences = new Set<number>();
|
||||
readonly #pendingReliable = new Map<number, PendingReliablePacket>();
|
||||
|
|
@ -137,6 +140,10 @@ export class CultNetRudpSession {
|
|||
return [...this.#pendingReliable.keys()].sort((left, right) => left - right);
|
||||
}
|
||||
|
||||
get lastReceivedAtMs(): number | undefined {
|
||||
return this.#lastReceivedAtMs;
|
||||
}
|
||||
|
||||
createConnect(nowMs = 0, payload = new Uint8Array()): CultNetRudpPacket {
|
||||
const packet = this.#createPacket({
|
||||
packetType: "connect",
|
||||
|
|
@ -242,6 +249,7 @@ export class CultNetRudpSession {
|
|||
receive(packet: CultNetRudpPacket, nowMs = 0): CultNetRudpReceiveResult {
|
||||
this.#requireConnection(packet);
|
||||
this.#applyAcknowledgements(packet);
|
||||
this.#lastReceivedAtMs = nowMs;
|
||||
const expectedSequenceIfUninitialized = this.#highestReceivedSequence === undefined
|
||||
? packet.sequence
|
||||
: this.#highestReceivedSequence + 1;
|
||||
|
|
@ -266,7 +274,11 @@ export class CultNetRudpSession {
|
|||
|
||||
if (packet.packetType === "ack" || packet.packetType === "pong") {
|
||||
this.#rememberReceived(packet.sequence);
|
||||
return { delivered: [] };
|
||||
return {
|
||||
delivered: [],
|
||||
pong: packet.packetType === "pong",
|
||||
pongPayload: packet.packetType === "pong" ? packet.payload ?? new Uint8Array() : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
if (packet.packetType === "disconnect") {
|
||||
|
|
@ -308,6 +320,14 @@ export class CultNetRudpSession {
|
|||
});
|
||||
}
|
||||
|
||||
createPing(payload = new Uint8Array()): CultNetRudpPacket {
|
||||
return this.#createPacket({
|
||||
packetType: "ping",
|
||||
channelId: "control",
|
||||
payload,
|
||||
});
|
||||
}
|
||||
|
||||
createDisconnect(reason = new Uint8Array()): CultNetRudpPacket {
|
||||
this.#connected = false;
|
||||
return this.#createPacket({
|
||||
|
|
@ -317,6 +337,17 @@ export class CultNetRudpSession {
|
|||
});
|
||||
}
|
||||
|
||||
checkTimeout(nowMs: number, timeoutMs: number): boolean {
|
||||
if (!this.#connected || this.#lastReceivedAtMs === undefined) {
|
||||
return false;
|
||||
}
|
||||
if (nowMs - this.#lastReceivedAtMs <= timeoutMs) {
|
||||
return false;
|
||||
}
|
||||
this.#connected = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
dueResends(nowMs: number): CultNetRudpPacket[] {
|
||||
const due: CultNetRudpPacket[] = [];
|
||||
for (const pending of this.#pendingReliable.values()) {
|
||||
|
|
@ -617,6 +648,19 @@ export class CultNetRudpSocketTransportConnection extends EventEmitter implement
|
|||
this.#stats.framesSent += 1;
|
||||
}
|
||||
|
||||
ping(payload = new Uint8Array()): void {
|
||||
this.#sendPacket(this.#session.createPing(payload));
|
||||
}
|
||||
|
||||
checkTimeout(timeoutMs: number, nowMs = Date.now()): boolean {
|
||||
const timedOut = this.#session.checkTimeout(nowMs, timeoutMs);
|
||||
if (timedOut) {
|
||||
this.emit("timeout");
|
||||
this.emit("close");
|
||||
}
|
||||
return timedOut;
|
||||
}
|
||||
|
||||
close(): void {
|
||||
clearInterval(this.#resendTimer);
|
||||
if (!this.#closed) {
|
||||
|
|
@ -652,6 +696,9 @@ export class CultNetRudpSocketTransportConnection extends EventEmitter implement
|
|||
if (result.reply) {
|
||||
this.#sendPacket(result.reply);
|
||||
}
|
||||
if (result.pong) {
|
||||
this.emit("pong", { payload: result.pongPayload ?? new Uint8Array() });
|
||||
}
|
||||
for (const frame of result.delivered) {
|
||||
this.#stats.framesReceived += 1;
|
||||
this.emit("frame", {
|
||||
|
|
|
|||
|
|
@ -340,6 +340,26 @@ test("rudp session schedules reliable resends until acked", () => {
|
|||
assert.deepEqual(session.dueResends(250), []);
|
||||
});
|
||||
|
||||
test("rudp session pings and detects receive timeout", () => {
|
||||
const client = new CultNetRudpSession({ connectionId: 101, initialSequence: 1 });
|
||||
const server = new CultNetRudpSession({ connectionId: 101, initialSequence: 100 });
|
||||
const connect = client.createConnect(0, Buffer.from("join"));
|
||||
const accept = server.acceptConnect(connect, 10);
|
||||
client.receive(accept, 20);
|
||||
|
||||
const ping = client.createPing(Buffer.from("pulse"));
|
||||
const pingResult = server.receive(ping, 30);
|
||||
assert.equal(pingResult.reply?.packetType, "pong");
|
||||
assert.deepEqual(Buffer.from(pingResult.reply?.payload ?? []), Buffer.from("pulse"));
|
||||
|
||||
const pongResult = client.receive(pingResult.reply!, 40);
|
||||
assert.equal(pongResult.pong, true);
|
||||
assert.deepEqual(Buffer.from(pongResult.pongPayload ?? []), Buffer.from("pulse"));
|
||||
assert.equal(client.checkTimeout(90, 50), false);
|
||||
assert.equal(client.checkTimeout(91, 50), true);
|
||||
assert.equal(client.connected, false);
|
||||
});
|
||||
|
||||
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 });
|
||||
|
|
|
|||
|
|
@ -1396,6 +1396,59 @@ test("CultNet RUDP disconnect reasons cross runtime boundaries", async () => {
|
|||
}
|
||||
});
|
||||
|
||||
test("CultNet RUDP ping/pong keepalive crosses runtime boundaries", async () => {
|
||||
for (const peer of rudpServerInteropPeers()) {
|
||||
await peer.build();
|
||||
const serverPeer = peer.spawn();
|
||||
const clientSocket = await bindUdpSocket();
|
||||
let client: CultNetRudpSocketTransportConnection | undefined;
|
||||
|
||||
try {
|
||||
client = new CultNetRudpSocketTransportConnection({
|
||||
runtimeId: `ts-ping-${peer.name.replace(/\W/g, "").toLowerCase()}-rudp-interop`,
|
||||
socket: clientSocket,
|
||||
mode: "client",
|
||||
remoteHost: "127.0.0.1",
|
||||
remotePort: await serverPeer.ready,
|
||||
connectionId: peer.connectionId,
|
||||
initialSequence: 1,
|
||||
resendDelayMs: 25,
|
||||
resendPollMs: 5,
|
||||
});
|
||||
|
||||
const receivedPong = once(client, "pong");
|
||||
const receivedFrame = once(client, "frame");
|
||||
client.connect(Buffer.from(peer.joinPayload));
|
||||
await waitFor(() => client?.connected === true, `TypeScript RUDP client to complete ${peer.name} ping handshake`);
|
||||
|
||||
const pingPayload = Buffer.from(`${peer.name.toLowerCase()}-ping`);
|
||||
client.ping(pingPayload);
|
||||
const [pong] = await withTimeout(receivedPong, 2_000, `${peer.name} RUDP pong`);
|
||||
assert.deepEqual(Buffer.from(pong.payload), pingPayload);
|
||||
|
||||
assert.equal(client.checkTimeout(1_000), false);
|
||||
client.send("schema", Buffer.from(peer.clientPayload));
|
||||
|
||||
const [frame] = await withTimeout(receivedFrame, 2_000, `${peer.name} RUDP response frame after ping`);
|
||||
assert.equal(frame.channelId, "schema");
|
||||
assert.deepEqual(Buffer.from(frame.payload), Buffer.from(peer.expectedPayload));
|
||||
|
||||
const [exitCode] = await withTimeout(once(serverPeer.child, "exit"), 2_000, `${peer.name} RUDP peer exit after ping`);
|
||||
assert.equal(exitCode, 0, serverPeer.stderr.join(""));
|
||||
} finally {
|
||||
if (client) {
|
||||
client.close();
|
||||
} else {
|
||||
clientSocket.close();
|
||||
}
|
||||
if (serverPeer.child.exitCode === null && !serverPeer.child.killed) {
|
||||
serverPeer.child.kill("SIGTERM");
|
||||
await once(serverPeer.child, "exit").catch(() => undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
async function buildInteropPeers(): Promise<void> {
|
||||
await buildRustInteropPeer();
|
||||
await buildCSharpInteropPeer();
|
||||
|
|
|
|||
|
|
@ -445,6 +445,14 @@ namespace GameCult.Networking
|
|||
/// </summary>
|
||||
public CultNetRudpPacket? Reply { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets whether the packet was a pong response.
|
||||
/// </summary>
|
||||
public bool Pong { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the pong payload bytes.
|
||||
/// </summary>
|
||||
public byte[] PongPayload { get; set; } = Array.Empty<byte>();
|
||||
/// <summary>
|
||||
/// Gets or sets whether the remote peer sent a disconnect packet.
|
||||
/// </summary>
|
||||
public bool Disconnected { get; set; }
|
||||
|
|
@ -587,6 +595,7 @@ namespace GameCult.Networking
|
|||
private uint _nextSequence;
|
||||
private ushort _nextFragmentId = 1;
|
||||
private bool _connected;
|
||||
private long? _lastReceivedAtMs;
|
||||
private uint? _highestReceivedSequence;
|
||||
private readonly HashSet<uint> _receivedSequences = new HashSet<uint>();
|
||||
private readonly Dictionary<uint, PendingReliablePacket> _pendingReliable = new Dictionary<uint, PendingReliablePacket>();
|
||||
|
|
@ -619,6 +628,10 @@ namespace GameCult.Networking
|
|||
/// </summary>
|
||||
public bool Connected => _connected;
|
||||
/// <summary>
|
||||
/// Gets the logical time of the last received packet.
|
||||
/// </summary>
|
||||
public long? LastReceivedAtMs => _lastReceivedAtMs;
|
||||
/// <summary>
|
||||
/// Gets reliable packet sequences awaiting acknowledgement.
|
||||
/// </summary>
|
||||
public IReadOnlyList<uint> PendingReliableSequences => _pendingReliable.Keys.OrderBy(value => value).ToArray();
|
||||
|
|
@ -732,6 +745,7 @@ namespace GameCult.Networking
|
|||
{
|
||||
RequireConnection(packet);
|
||||
ApplyAcknowledgements(packet);
|
||||
_lastReceivedAtMs = nowMs;
|
||||
var expectedSequenceIfUninitialized = _highestReceivedSequence.HasValue
|
||||
? _highestReceivedSequence.Value + 1
|
||||
: packet.Sequence;
|
||||
|
|
@ -761,7 +775,13 @@ namespace GameCult.Networking
|
|||
if (packet.PacketType == CultNetRudpPacketType.Ack || packet.PacketType == CultNetRudpPacketType.Pong)
|
||||
{
|
||||
RememberReceived(packet.Sequence);
|
||||
return new CultNetRudpReceiveResult();
|
||||
return new CultNetRudpReceiveResult
|
||||
{
|
||||
Pong = packet.PacketType == CultNetRudpPacketType.Pong,
|
||||
PongPayload = packet.PacketType == CultNetRudpPacketType.Pong
|
||||
? packet.Payload ?? Array.Empty<byte>()
|
||||
: Array.Empty<byte>()
|
||||
};
|
||||
}
|
||||
|
||||
if (packet.PacketType == CultNetRudpPacketType.Disconnect)
|
||||
|
|
@ -809,6 +829,14 @@ namespace GameCult.Networking
|
|||
return CreatePacket(CultNetRudpPacketType.Ack, "control", Array.Empty<byte>(), reliable: false, ordered: false, sequenced: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a packet carrying a keepalive ping payload.
|
||||
/// </summary>
|
||||
public CultNetRudpPacket CreatePing(byte[]? payload = null)
|
||||
{
|
||||
return CreatePacket(CultNetRudpPacketType.Ping, "control", payload ?? Array.Empty<byte>(), reliable: false, ordered: false, sequenced: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a packet carrying a transport-level disconnect reason.
|
||||
/// </summary>
|
||||
|
|
@ -818,6 +846,23 @@ namespace GameCult.Networking
|
|||
return CreatePacket(CultNetRudpPacketType.Disconnect, "control", reason ?? Array.Empty<byte>(), reliable: false, ordered: false, sequenced: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks the session disconnected when no packet has arrived within the timeout window.
|
||||
/// </summary>
|
||||
public bool CheckTimeout(long nowMs, long timeoutMs)
|
||||
{
|
||||
if (!_connected || !_lastReceivedAtMs.HasValue)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (nowMs - _lastReceivedAtMs.Value <= timeoutMs)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
_connected = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns reliable packets due for resend at the supplied logical time.
|
||||
/// </summary>
|
||||
|
|
@ -1104,6 +1149,7 @@ namespace GameCult.Networking
|
|||
private readonly int? _maxFragmentBytes;
|
||||
private readonly CultNetTransportStats _stats = new CultNetTransportStats();
|
||||
private readonly Queue<CultNetTransportFrame> _deliveredFrames = new Queue<CultNetTransportFrame>();
|
||||
private readonly Queue<byte[]> _pongPayloads = new Queue<byte[]>();
|
||||
private EndPoint? _remoteEndPoint;
|
||||
private bool _disposed;
|
||||
|
||||
|
|
@ -1158,6 +1204,20 @@ namespace GameCult.Networking
|
|||
/// </summary>
|
||||
public byte[]? DisconnectReason { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to dequeue the next received pong payload.
|
||||
/// </summary>
|
||||
public bool TryDequeuePongPayload(out byte[] payload)
|
||||
{
|
||||
if (_pongPayloads.Count > 0)
|
||||
{
|
||||
payload = _pongPayloads.Dequeue();
|
||||
return true;
|
||||
}
|
||||
payload = Array.Empty<byte>();
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends the client connect packet.
|
||||
/// </summary>
|
||||
|
|
@ -1191,6 +1251,22 @@ namespace GameCult.Networking
|
|||
SendPacket(_session.CreateDisconnect(reason ?? Array.Empty<byte>()));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a transport-level ping packet.
|
||||
/// </summary>
|
||||
public void Ping(byte[]? payload = null)
|
||||
{
|
||||
SendPacket(_session.CreatePing(payload ?? Array.Empty<byte>()));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether the session has exceeded the receive timeout.
|
||||
/// </summary>
|
||||
public bool CheckTimeout(long timeoutMs)
|
||||
{
|
||||
return _session.CheckTimeout(NowMs(), timeoutMs);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Polls the UDP socket once and returns the next delivered transport frame if one is available.
|
||||
/// </summary>
|
||||
|
|
@ -1239,6 +1315,10 @@ namespace GameCult.Networking
|
|||
{
|
||||
SendPacket(result.Reply);
|
||||
}
|
||||
if (result.Pong)
|
||||
{
|
||||
_pongPayloads.Enqueue(result.PongPayload);
|
||||
}
|
||||
if (result.Disconnected)
|
||||
{
|
||||
DisconnectReason = result.DisconnectReason;
|
||||
|
|
|
|||
|
|
@ -464,6 +464,36 @@ namespace GameCult.Networking.Tests
|
|||
Assert.That(session.DueResends(250), Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RudpSession_PingsAndDetectsReceiveTimeout()
|
||||
{
|
||||
var client = new CultNetRudpSession(new CultNetRudpSessionOptions
|
||||
{
|
||||
ConnectionId = 101,
|
||||
InitialSequence = 1
|
||||
});
|
||||
var server = new CultNetRudpSession(new CultNetRudpSessionOptions
|
||||
{
|
||||
ConnectionId = 101,
|
||||
InitialSequence = 100
|
||||
});
|
||||
var connect = client.CreateConnect(0, Encoding.UTF8.GetBytes("join"));
|
||||
var accept = server.AcceptConnect(connect, 10);
|
||||
client.Receive(accept, 20);
|
||||
|
||||
var ping = client.CreatePing(Encoding.UTF8.GetBytes("pulse"));
|
||||
var pingResult = server.Receive(ping, 30);
|
||||
Assert.That(pingResult.Reply?.PacketType, Is.EqualTo(CultNetRudpPacketType.Pong));
|
||||
Assert.That(pingResult.Reply?.Payload, Is.EqualTo(Encoding.UTF8.GetBytes("pulse")));
|
||||
|
||||
var pongResult = client.Receive(pingResult.Reply!, 40);
|
||||
Assert.That(pongResult.Pong, Is.True);
|
||||
Assert.That(pongResult.PongPayload, Is.EqualTo(Encoding.UTF8.GetBytes("pulse")));
|
||||
Assert.That(client.CheckTimeout(90, 50), Is.False);
|
||||
Assert.That(client.CheckTimeout(91, 50), Is.True);
|
||||
Assert.That(client.Connected, Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RudpSession_SuppressesDuplicatesAndDeliversReliableOrderedPayloadsInSequence()
|
||||
{
|
||||
|
|
|
|||
Loading…
Reference in a new issue