diff --git a/packages/cultmesh-rs/src/lib.rs b/packages/cultmesh-rs/src/lib.rs index 67584781..9c3e4d90 100644 --- a/packages/cultmesh-rs/src/lib.rs +++ b/packages/cultmesh-rs/src/lib.rs @@ -12,7 +12,6 @@ use cultnet_rs::CultNetRudpSocketTransportOptions; use cultnet_rs::CultNetWireContract; use cultnet_rs::decode_cultnet_message_from_slice; use cultnet_rs::encode_cultnet_message_to_vec; -use cultnet_rs::random_initial_sequence; use serde::Serialize; use std::collections::BTreeMap; use std::collections::hash_map::RandomState; @@ -962,7 +961,7 @@ fn connect_rudp_client( mode: cultnet_rs::CultNetRudpSocketMode::Client, remote_addr: Some(target), connection_id: fresh_rudp_connection_epoch(), - initial_sequence: random_initial_sequence(), + initial_sequence: None, resend_delay_ms, transport_id: Some(transport_id.to_string()), max_payload_bytes: None, @@ -1407,7 +1406,7 @@ mod tests { let mut session = cultnet_rs::CultNetRudpSession::new(cultnet_rs::CultNetRudpSessionOptions { connection_id: connect.connection_id, - initial_sequence: 1, + initial_sequence: Some(1), resend_delay_ms: 5, max_pending_reliable_packets: Some(64), }); diff --git a/packages/cultmesh-rs/src/rudp_document_server.rs b/packages/cultmesh-rs/src/rudp_document_server.rs index 1f1b295f..47348bfe 100644 --- a/packages/cultmesh-rs/src/rudp_document_server.rs +++ b/packages/cultmesh-rs/src/rudp_document_server.rs @@ -3,7 +3,7 @@ use cultnet_rs::{ CultNetMessage, CultNetRawDocumentRecord, CultNetRudpPacket, CultNetRudpPacketType, CultNetRudpSendOptions, CultNetRudpSession, CultNetRudpSessionOptions, CultNetWireContract, decode_cultnet_message_from_slice, decode_rudp_packet, encode_cultnet_message_to_vec, - encode_rudp_packet, random_initial_sequence, + encode_rudp_packet, }; use std::collections::BTreeMap; use std::io::ErrorKind; @@ -437,7 +437,7 @@ where } let mut session = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: key.connection_id, - initial_sequence: random_initial_sequence(), + initial_sequence: None, resend_delay_ms: duration_millis(self.options.resend_delay), max_pending_reliable_packets: Some( self.options.max_pending_reliable_packets_per_session, diff --git a/packages/cultmesh-rs/tests/rudp_document_server.rs b/packages/cultmesh-rs/tests/rudp_document_server.rs index 0f26a8be..e43e4e59 100644 --- a/packages/cultmesh-rs/tests/rudp_document_server.rs +++ b/packages/cultmesh-rs/tests/rudp_document_server.rs @@ -177,7 +177,7 @@ fn client_on( mode: CultNetRudpSocketMode::Client, remote_addr: Some(target), connection_id: id, - initial_sequence, + initial_sequence: Some(initial_sequence), resend_delay_ms: 10, transport_id: None, max_payload_bytes: None, @@ -343,7 +343,7 @@ fn a_restarted_client_on_the_same_address_and_connection_id_is_admitted() -> Res let target = server.local_addr()?; let shared = UdpSocket::bind("127.0.0.1:0")?; let twin = shared.try_clone()?; - let mut first = client_on(shared, target, 93, 50)?; + let mut first = client_on(shared, target, 93, 50_000)?; connect(&mut server, &mut [&mut first])?; for index in 0..3 { send( @@ -402,7 +402,7 @@ fn a_restarted_client_starts_with_a_fresh_payload_budget() -> Result<()> { let target = server.local_addr()?; let shared = UdpSocket::bind("127.0.0.1:0")?; let twin = shared.try_clone()?; - let mut first = client_on(shared, target, 94, 50)?; + let mut first = client_on(shared, target, 94, 50_000)?; connect(&mut server, &mut [&mut first])?; send(&mut first, &put("put-a"))?; for _ in 0..20 { @@ -675,7 +675,7 @@ fn a_connect_storm_and_stray_frames_are_dropped_not_fatal() -> Result<()> { let session = |id| { CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: id, - initial_sequence: 1, + initial_sequence: Some(1), resend_delay_ms: 10, max_pending_reliable_packets: None, }) diff --git a/packages/cultnet-rs/examples/cultnet_interop_peer.rs b/packages/cultnet-rs/examples/cultnet_interop_peer.rs index bd9ff774..a2a4847e 100644 --- a/packages/cultnet-rs/examples/cultnet_interop_peer.rs +++ b/packages/cultnet-rs/examples/cultnet_interop_peer.rs @@ -507,7 +507,7 @@ fn rudp_serve_once(options: &BTreeMap) -> Result<()> { let local_port = socket.local_addr()?.port(); let mut transport_options = CultNetRudpSocketTransportOptions::server("rust-rudp-interop", socket, 0x22446688); - transport_options.initial_sequence = 100; + transport_options.initial_sequence = Some(100); transport_options.resend_delay_ms = 25; transport_options.max_fragment_bytes = max_fragment_bytes; let mut transport = CultNetRudpSocketTransportConnection::new(transport_options)?; @@ -608,7 +608,7 @@ fn rudp_serve_message_once(options: &BTreeMap) -> Result<()> { let local_port = socket.local_addr()?.port(); let mut transport_options = CultNetRudpSocketTransportOptions::server("rust-rudp-message-interop", socket, 0x22446689); - transport_options.initial_sequence = 100; + transport_options.initial_sequence = Some(100); transport_options.resend_delay_ms = 25; let mut transport = CultNetRudpSocketTransportConnection::new(transport_options)?; @@ -967,7 +967,7 @@ fn run_rudp_server( let peer = peers.entry(remote_addr).or_insert_with(|| RudpPeerSession { session: CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: RUDP_INTEROP_CONNECTION_ID, - initial_sequence: 100, + initial_sequence: Some(100), resend_delay_ms: RUDP_INTEROP_RESEND_DELAY_MS, max_pending_reliable_packets: None, }), diff --git a/packages/cultnet-rs/src/cultmesh.rs b/packages/cultnet-rs/src/cultmesh.rs index 309a262f..900f4744 100644 --- a/packages/cultnet-rs/src/cultmesh.rs +++ b/packages/cultnet-rs/src/cultmesh.rs @@ -243,7 +243,7 @@ pub struct CultMeshRudpSocketOptions { pub bind_host: String, pub bind_port: u16, pub read_timeout: Option, - pub initial_sequence: u32, + pub initial_sequence: Option, pub resend_delay_ms: u64, pub max_payload_bytes: Option, pub max_fragment_bytes: Option, @@ -256,7 +256,7 @@ impl Default for CultMeshRudpSocketOptions { bind_host: "127.0.0.1".to_string(), bind_port: 0, read_timeout: Some(Duration::from_millis(20)), - initial_sequence: crate::rudp::random_initial_sequence(), + initial_sequence: None, resend_delay_ms: 250, max_payload_bytes: None, max_fragment_bytes: None, diff --git a/packages/cultnet-rs/src/rudp.rs b/packages/cultnet-rs/src/rudp.rs index 1da422dd..ffcd0569 100644 --- a/packages/cultnet-rs/src/rudp.rs +++ b/packages/cultnet-rs/src/rudp.rs @@ -43,6 +43,12 @@ const RUDP_MAX_TRACKED_CHANNELS: usize = 64; /// ahead of the current highest would otherwise advance the receive state past /// every legitimate sequence still in flight and starve the session. const RUDP_RECEIVE_AHEAD_WINDOW: u32 = 1_024; +/// How long a client keeps retransmitting a Connect nobody answered before it +/// abandons that attempt for a fresh one. A Connect the server answers with an +/// Ack, never an Accept, is one the server judged stale (see +/// `accept_connect`); retransmitting the same sequence would never change its +/// mind. +const RUDP_CONNECT_ATTEMPT_MS: u64 = 3_000; const RUDP_MAX_ORDERED_BUFFERED_FRAMES: usize = 1_024; const RUDP_MAX_ORDERED_BUFFERED_BYTES: usize = 4 * 1024 * 1024; @@ -95,7 +101,10 @@ pub struct CultNetRudpReceiveResult { #[derive(Clone, Debug, PartialEq, Eq)] pub struct CultNetRudpSessionOptions { pub connection_id: u32, - pub initial_sequence: u32, + /// The first sequence this session issues. Unset, the session draws its + /// own at random: every session is a new identity to its peer, and an + /// options object reused for several must not give them one sequence. + pub initial_sequence: Option, pub resend_delay_ms: u64, pub max_pending_reliable_packets: Option, } @@ -104,20 +113,32 @@ impl Default for CultNetRudpSessionOptions { fn default() -> Self { Self { connection_id: 0, - initial_sequence: random_initial_sequence(), + initial_sequence: None, resend_delay_ms: 250, max_pending_reliable_packets: None, } } } -/// A fresh default initial sequence, drawn from a secure source in [1, 2^31). -/// The Connect's sequence is what tells a peer whether a Connect repeats one it -/// already accepted or starts a new session, so two sessions must not share -/// one by default. At least 2^31 sequences remain before the space is -/// exhausted. -pub fn random_initial_sequence() -> u32 { - rand::random_range(1..(1_u32 << 31)) +/// A sequence drawn at random from [`floor`, 2^31). The Connect's sequence is +/// what tells a peer whether a Connect repeats one it already accepted or +/// starts a new session, so two sessions must not share one by default. At +/// least 2^31 sequences remain before the space is exhausted. A floor above +/// the range draws nothing new: the caller keeps its own sequence. +fn draw_sequence(floor: u32) -> u32 { + let floor = floor.max(1); + if floor >= 1_u32 << 31 { + return floor; + } + rand::random_range(floor..(1_u32 << 31)) +} + +/// Whether `sequence` is at or before `mark` in serial order, within the +/// receive window. The compare is modular, so it holds across the wrap of the +/// 32-bit space; a sequence further back than the window is the duplicate +/// test's below-window clause, and one ahead of the mark is never before it. +fn at_or_before(sequence: u32, mark: u32) -> bool { + mark.wrapping_sub(sequence) < RUDP_RECEIVED_SEQUENCE_WINDOW as u32 } /// Whether the packet's ack field, or its mask, names `sequence`. @@ -206,6 +227,9 @@ pub struct CultNetRudpSession { connect_sequence: Option, /// A Connect this side sent is unanswered. Only then is an Accept honoured. awaiting_accept: bool, + /// When the unanswered Connect first went out; `due_resends` abandons it + /// for a fresh attempt once `RUDP_CONNECT_ATTEMPT_MS` has passed. + connect_started_at_ms: u64, connection_id: u32, resend_delay_ms: u64, max_pending_reliable_packets: Option, @@ -244,12 +268,13 @@ impl CultNetRudpSession { ended: false, connect_sequence: None, awaiting_accept: false, + connect_started_at_ms: 0, connection_id: options.connection_id, resend_delay_ms: options.resend_delay_ms, max_pending_reliable_packets: options.max_pending_reliable_packets, max_payload_bytes: None, max_pending_fragment_sets: 64, - next_sequence: options.initial_sequence, + next_sequence: options.initial_sequence.unwrap_or_else(|| draw_sequence(1)), next_sequenced_by_channel: BTreeMap::new(), next_fragment_id: 1, connected: false, @@ -444,26 +469,45 @@ impl CultNetRudpSession { self.ended = false; self.connect_sequence = Some(packet.sequence); self.awaiting_accept = true; + self.connect_started_at_ms = now_ms; self.track_reliable(packet.clone(), now_ms, None); Ok(packet) } - /// Whether `packet` is a retransmit of the Connect that started this - /// session's current generation: the session is connected and the Connect - /// carries that Connect's sequence. Servers that keep one session per peer - /// ask this to tell a repeat from a new session; anything else that - /// reaches `accept_connect` starts a new generation. + /// Whether `packet` is a Connect this session's current generation already + /// owns: a retransmit of the Connect that started it (the session is + /// connected and the sequence is that Connect's), or a stale copy of an + /// earlier attempt by the same client (a sequence before it, within the + /// receive window). Servers that keep one session per peer ask this to tell + /// a Connect that starts a new session from one that does not; anything + /// else that reaches `accept_connect` starts a new generation. pub fn connect_repeats(&self, packet: &CultNetRudpPacket) -> bool { packet.packet_type == CultNetRudpPacketType::Connect && self.connected - && self.connect_sequence == Some(packet.sequence) + && self.connect_sequence.is_some_and(|connect| { + connect == packet.sequence || self.connect_is_stale(packet.sequence, connect) + }) + } + + /// A Connect that precedes the current generation's within the receive + /// window is the client's earlier attempt, delayed in the network: a + /// client that retried never sends a lower sequence again. Restarting on + /// it would strand the client, which honours only the Accept for its + /// newest Connect. The rule is TCP's answer to a delayed SYN (RFC 5961's + /// challenge ACK): keep the connection and answer with an Ack. A restarted + /// client whose random initial sequence lands in this window is answered + /// the same way and abandons the attempt for a fresh draw + /// (`RUDP_CONNECT_ATTEMPT_MS`). + fn connect_is_stale(&self, sequence: u32, current: u32) -> bool { + sequence != current && at_or_before(sequence, current) } /// Answers a Connect. A repeat of the accepted one queues nothing, so a /// Connect storm cannot grow the reliable queue: the reply is the Accept - /// still awaiting acknowledgement, or an Ack once it was acknowledged. - /// Any other Connect ends the current generation, forgets the peer and - /// accepts a new one. + /// still awaiting acknowledgement, or an Ack once it was acknowledged. A + /// stale copy of an earlier attempt gets the same reply and changes + /// nothing else: it is not evidence the peer is alive. Any other Connect + /// ends the current generation, forgets the peer and accepts a new one. pub fn accept_connect( &mut self, packet: &CultNetRudpPacket, @@ -479,9 +523,11 @@ impl CultNetRudpSession { } if self.connect_repeats(packet) { - self.apply_acknowledgements(packet); - self.remember_received(packet.sequence); - self.last_received_at_ms = Some(now_ms); + if self.connect_sequence == Some(packet.sequence) { + self.apply_acknowledgements(packet); + self.remember_received(packet.sequence); + self.last_received_at_ms = Some(now_ms); + } return Ok(self .pending_accept_for_resend(now_ms) .unwrap_or_else(|| self.create_ack())); @@ -740,12 +786,7 @@ impl CultNetRudpSession { }); } - let duplicate = packet.reliable - && (self.received_sequences.contains(&packet.sequence) - || self.highest_received_sequence.is_some_and(|highest| { - packet.sequence < highest - && highest - packet.sequence >= RUDP_RECEIVED_SEQUENCE_WINDOW as u32 - })); + let duplicate = packet.reliable && self.was_received(packet.sequence); if packet.reliable { self.remember_received(packet.sequence); } @@ -891,6 +932,9 @@ impl CultNetRudpSession { } pub fn due_resends(&mut self, now_ms: u64) -> Vec { + if let Some(fresh) = self.abandon_unanswered_connect(now_ms) { + return vec![fresh]; + } let mut due = Vec::new(); for pending in self.pending_reliable.values_mut() { if now_ms.saturating_sub(pending.last_sent_at_ms) >= self.resend_delay_ms { @@ -902,6 +946,26 @@ impl CultNetRudpSession { due } + /// A Connect unanswered for `RUDP_CONNECT_ATTEMPT_MS` is replaced, not + /// retransmitted further, by a Connect with a newly drawn sequence and the + /// same payload. Nothing was ever sent in an unanswered generation, so no + /// sequence issued so far is owed; the draw stays above them, so a frame + /// the peer still remembers from an earlier generation of this session + /// stays at or before the new Connect. + fn abandon_unanswered_connect(&mut self, now_ms: u64) -> Option { + if !self.awaiting_accept + || now_ms.saturating_sub(self.connect_started_at_ms) < RUDP_CONNECT_ATTEMPT_MS + { + return None; + } + let payload = self + .connect_sequence + .and_then(|sequence| self.pending_reliable.get(&sequence)) + .map(|pending| pending.packet.payload.clone())?; + self.next_sequence = draw_sequence(self.next_sequence); + self.create_connect(now_ms, payload).ok() + } + fn create_packet( &mut self, packet_type: CultNetRudpPacketType, @@ -1099,13 +1163,20 @@ impl CultNetRudpSession { } } - /// True for a sequence in the window that was received, and for one below - /// the window, which `receive` treats as a duplicate of something received. + /// The one duplicate test: true for a sequence in the window that was + /// received, for one below the window, and for one at or before the + /// watermark. The watermark starts at the handshake's seed, so a frame the + /// peer sent in an earlier generation (every sequence it issued is below + /// the Connect that began this one) is a duplicate of something already + /// delivered and is acknowledged, never delivered again. fn was_received(&self, sequence: u32) -> bool { self.received_sequences.contains(&sequence) || self.highest_received_sequence.is_some_and(|highest| { sequence < highest && highest - sequence >= RUDP_RECEIVED_SEQUENCE_WINDOW as u32 }) + || self + .received_through + .is_some_and(|through| at_or_before(sequence, through)) } fn ack_state(&self) -> (u32, u32) { @@ -1314,7 +1385,7 @@ pub struct CultNetRudpSocketTransportOptions { pub mode: CultNetRudpSocketMode, pub remote_addr: Option, pub connection_id: u32, - pub initial_sequence: u32, + pub initial_sequence: Option, pub resend_delay_ms: u64, pub transport_id: Option, pub max_payload_bytes: Option, @@ -1341,7 +1412,7 @@ impl CultNetRudpSocketTransportOptions { mode: CultNetRudpSocketMode::Client, remote_addr: Some(remote_addr), connection_id, - initial_sequence: random_initial_sequence(), + initial_sequence: None, resend_delay_ms: 250, transport_id: None, max_payload_bytes: None, @@ -1360,7 +1431,7 @@ impl CultNetRudpSocketTransportOptions { mode: CultNetRudpSocketMode::Server, remote_addr: None, connection_id, - initial_sequence: random_initial_sequence(), + initial_sequence: None, resend_delay_ms: 250, transport_id: None, max_payload_bytes: None, @@ -1388,7 +1459,7 @@ pub struct CultNetRudpServerHubOptions { pub runtime_id: String, pub socket: UdpSocket, pub connection_id: u32, - pub initial_sequence: u32, + pub initial_sequence: Option, pub resend_delay_ms: u64, pub transport_id: Option, pub max_payload_bytes: Option, @@ -1408,7 +1479,7 @@ impl CultNetRudpServerHubOptions { runtime_id: runtime_id.into(), socket, connection_id, - initial_sequence: random_initial_sequence(), + initial_sequence: None, resend_delay_ms: 250, transport_id: None, max_payload_bytes: None, @@ -1463,7 +1534,7 @@ struct CultNetRudpServerPeer { pub struct CultNetRudpServerHub { socket: UdpSocket, connection_id: u32, - initial_sequence: u32, + initial_sequence: Option, resend_delay_ms: u64, max_pending_reliable_packets: Option, max_payload_bytes: usize, @@ -2122,12 +2193,17 @@ impl CultNetRudpSocketTransportConnection { self.stats.packets_dropped += 1; return Ok(true); } + // A Connect from another endpoint is a new client, whatever sequence it + // carries: the endpoint moves and the Connect starts a new generation. + // Only a Connect from the peer's own endpoint can be its repeat. + let mut connect_from_new_endpoint = false; if let Some(expected) = self.remote_addr { if expected != remote_addr { if self.mode == CultNetRudpSocketMode::Server && packet.packet_type == CultNetRudpPacketType::Connect { self.remote_addr = Some(remote_addr); + connect_from_new_endpoint = true; } else { self.stats.packets_dropped += 1; return Ok(true); @@ -2146,6 +2222,9 @@ impl CultNetRudpSocketTransportConnection { && packet.packet_type == CultNetRudpPacketType::Connect { self.disconnect_reason = None; + if connect_from_new_endpoint { + self.session.reset_peer_state(); + } let Ok(accept) = self.session.accept_connect(&packet, now_ms(), Vec::new()) else { self.stats.packets_dropped += 1; return Ok(true); @@ -2318,10 +2397,10 @@ const SESSION_TIMED_OUT_REASON: &[u8] = b"session timed out"; /// A session cannot admit a Connect when its sequence space starts exhausted or /// its reliable queue holds nothing, so neither is a usable configuration. fn validate_rudp_session_limits( - initial_sequence: u32, + initial_sequence: Option, max_pending_reliable_packets: Option, ) -> Result<()> { - if initial_sequence == u32::MAX { + if initial_sequence == Some(u32::MAX) { return Err(anyhow!( "RUDP initial_sequence must leave room for a reliable packet" )); diff --git a/packages/cultnet-rs/tests/cultnet.rs b/packages/cultnet-rs/tests/cultnet.rs index 916422da..b76a5263 100644 --- a/packages/cultnet-rs/tests/cultnet.rs +++ b/packages/cultnet-rs/tests/cultnet.rs @@ -558,13 +558,13 @@ fn rudp_reconnect_loop_consumes_shared_controller() -> Result<()> { fn rudp_session_handshake_acks_reliable_connect_and_accept_packets() -> Result<()> { let mut client = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 0x0a0b0c0d, - initial_sequence: 1, + initial_sequence: Some(1), resend_delay_ms: 50, ..CultNetRudpSessionOptions::default() }); let mut server = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 0x0a0b0c0d, - initial_sequence: 100, + initial_sequence: Some(100), resend_delay_ms: 50, ..CultNetRudpSessionOptions::default() }); @@ -595,13 +595,13 @@ fn rudp_session_handshake_acks_reliable_connect_and_accept_packets() -> Result<( fn rudp_session_computes_ack_masks_and_clears_pending_reliable_packets() -> Result<()> { let mut sender = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 7, - initial_sequence: 10, + initial_sequence: Some(10), resend_delay_ms: 100, ..CultNetRudpSessionOptions::default() }); let mut receiver = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 7, - initial_sequence: 200, + initial_sequence: Some(200), resend_delay_ms: 100, ..CultNetRudpSessionOptions::default() }); @@ -640,7 +640,7 @@ fn rudp_session_computes_ack_masks_and_clears_pending_reliable_packets() -> Resu fn rudp_session_schedules_reliable_resends_until_acked() -> Result<()> { let mut session = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 99, - initial_sequence: 1, + initial_sequence: Some(1), resend_delay_ms: 100, ..CultNetRudpSessionOptions::default() }); @@ -693,12 +693,12 @@ fn rudp_session_schedules_reliable_resends_until_acked() -> Result<()> { fn rudp_session_pings_and_detects_receive_timeout() -> Result<()> { let mut client = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 101, - initial_sequence: 1, + initial_sequence: Some(1), ..CultNetRudpSessionOptions::default() }); let mut server = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 101, - initial_sequence: 100, + initial_sequence: Some(100), ..CultNetRudpSessionOptions::default() }); let connect = client.create_connect(0, b"join".to_vec())?; @@ -724,12 +724,12 @@ fn rudp_session_pings_and_detects_receive_timeout() -> Result<()> { fn rudp_lossy_packets_cannot_create_reliable_ordered_gaps() -> Result<()> { let mut client = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 198, - initial_sequence: 1, + initial_sequence: Some(1), ..CultNetRudpSessionOptions::default() }); let mut server = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 198, - initial_sequence: 100, + initial_sequence: Some(100), ..CultNetRudpSessionOptions::default() }); let connect = client.create_connect(0, Vec::new())?; @@ -780,12 +780,12 @@ fn rudp_lossy_packets_cannot_create_reliable_ordered_gaps() -> Result<()> { fn rudp_unreliable_sequenced_delivery_is_scoped_to_its_channel() -> Result<()> { let mut sender = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 197, - initial_sequence: 50, + initial_sequence: Some(50), ..CultNetRudpSessionOptions::default() }); let mut receiver = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 197, - initial_sequence: 100, + initial_sequence: Some(100), ..CultNetRudpSessionOptions::default() }); let connect = sender.create_connect(0, Vec::new())?; @@ -834,7 +834,7 @@ fn rudp_rejects_unreliable_ordered_delivery() -> Result<()> { fn rudp_session_bounds_pending_reliable_packets_before_enqueue() -> Result<()> { let mut session = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 102, - initial_sequence: 1, + initial_sequence: Some(1), max_pending_reliable_packets: Some(2), ..CultNetRudpSessionOptions::default() }); @@ -873,7 +873,7 @@ fn rudp_session_bounds_pending_reliable_packets_before_enqueue() -> Result<()> { let mut fragmented = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 103, - initial_sequence: 1, + initial_sequence: Some(1), max_pending_reliable_packets: Some(3), ..CultNetRudpSessionOptions::default() }); @@ -900,12 +900,12 @@ fn rudp_session_suppresses_duplicates_and_delivers_reliable_ordered_payloads_in_ -> Result<()> { let mut sender = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 123, - initial_sequence: 1, + initial_sequence: Some(1), ..CultNetRudpSessionOptions::default() }); let mut receiver = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 123, - initial_sequence: 100, + initial_sequence: Some(100), ..CultNetRudpSessionOptions::default() }); let connect = sender.create_connect(0, Vec::new())?; @@ -948,12 +948,12 @@ fn rudp_session_suppresses_duplicates_and_delivers_reliable_ordered_payloads_in_ fn rudp_session_skips_control_packets_while_ordering_schema_payloads() -> Result<()> { let mut sender = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 124, - initial_sequence: 1, + initial_sequence: Some(1), ..CultNetRudpSessionOptions::default() }); let mut receiver = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 124, - initial_sequence: 100, + initial_sequence: Some(100), ..CultNetRudpSessionOptions::default() }); let connect = sender.create_connect(0, Vec::new())?; @@ -997,12 +997,12 @@ fn rudp_session_skips_control_packets_while_ordering_schema_payloads() -> Result fn rudp_session_fragments_and_reassembles_reliable_ordered_payloads() -> Result<()> { let mut sender = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 456, - initial_sequence: 1, + initial_sequence: Some(1), ..CultNetRudpSessionOptions::default() }); let mut receiver = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 456, - initial_sequence: 100, + initial_sequence: Some(100), ..CultNetRudpSessionOptions::default() }); let connect = sender.create_connect(0, Vec::new())?; @@ -1065,7 +1065,7 @@ fn rudp_socket_transport_handshakes_and_carries_reliable_ordered_schema_frames() mode: CultNetRudpSocketMode::Server, remote_addr: None, connection_id, - initial_sequence: 100, + initial_sequence: Some(100), resend_delay_ms: 25, transport_id: None, max_payload_bytes: None, @@ -1082,7 +1082,7 @@ fn rudp_socket_transport_handshakes_and_carries_reliable_ordered_schema_frames() mode: CultNetRudpSocketMode::Client, remote_addr: Some(server_addr), connection_id, - initial_sequence: 1, + initial_sequence: Some(1), resend_delay_ms: 25, transport_id: None, max_payload_bytes: None, @@ -1159,7 +1159,7 @@ fn rudp_socket_transport_carries_fragmented_reliable_ordered_schema_frames() -> mode: CultNetRudpSocketMode::Server, remote_addr: None, connection_id, - initial_sequence: 100, + initial_sequence: Some(100), resend_delay_ms: 25, transport_id: None, max_payload_bytes: None, @@ -1176,7 +1176,7 @@ fn rudp_socket_transport_carries_fragmented_reliable_ordered_schema_frames() -> mode: CultNetRudpSocketMode::Client, remote_addr: Some(server_addr), connection_id, - initial_sequence: 1, + initial_sequence: Some(1), resend_delay_ms: 25, transport_id: None, max_payload_bytes: None, @@ -1204,13 +1204,13 @@ fn rudp_session_advances_large_fragment_sets_through_a_bounded_reliable_window() let connection_id = 0x1020_3042; let mut sender = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id, - initial_sequence: 1, + initial_sequence: Some(1), resend_delay_ms: 25, max_pending_reliable_packets: None, }); let mut receiver = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id, - initial_sequence: 100, + initial_sequence: Some(100), resend_delay_ms: 25, max_pending_reliable_packets: None, }); @@ -1274,7 +1274,7 @@ fn rudp_socket_flush_waits_for_large_fragment_delivery() -> Result<()> { mode: CultNetRudpSocketMode::Server, remote_addr: None, connection_id, - initial_sequence: 100, + initial_sequence: Some(100), resend_delay_ms: 25, transport_id: None, max_payload_bytes: None, @@ -1291,7 +1291,7 @@ fn rudp_socket_flush_waits_for_large_fragment_delivery() -> Result<()> { mode: CultNetRudpSocketMode::Client, remote_addr: Some(server_addr), connection_id, - initial_sequence: 1, + initial_sequence: Some(1), resend_delay_ms: 25, transport_id: None, max_payload_bytes: None, @@ -2398,12 +2398,12 @@ fn schema_discovery_round_trips_over_legacy_gamecult_contract_when_inline_schema fn rudp_sequenced_channel_tracking_is_bounded() -> Result<()> { let mut sender = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 401, - initial_sequence: 1, + initial_sequence: Some(1), ..CultNetRudpSessionOptions::default() }); let mut receiver = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 401, - initial_sequence: 100, + initial_sequence: Some(100), ..CultNetRudpSessionOptions::default() }); let connect = sender.create_connect(0, Vec::new())?; @@ -2438,12 +2438,12 @@ fn rudp_sequenced_channel_tracking_is_bounded() -> Result<()> { fn rudp_ordered_channel_tracking_is_bounded() -> Result<()> { let mut sender = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 402, - initial_sequence: 1, + initial_sequence: Some(1), ..CultNetRudpSessionOptions::default() }); let mut receiver = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 402, - initial_sequence: 100, + initial_sequence: Some(100), ..CultNetRudpSessionOptions::default() }); let connect = sender.create_connect(0, Vec::new())?; @@ -2496,12 +2496,12 @@ fn rudp_ordered_channel_tracking_is_bounded() -> Result<()> { fn rudp_ordered_hold_buffer_is_bounded() -> Result<()> { let mut sender = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 403, - initial_sequence: 1, + initial_sequence: Some(1), ..CultNetRudpSessionOptions::default() }); let mut receiver = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 403, - initial_sequence: 100, + initial_sequence: Some(100), ..CultNetRudpSessionOptions::default() }); let connect = sender.create_connect(0, Vec::new())?; @@ -2542,12 +2542,12 @@ fn rudp_ordered_hold_buffer_is_bounded() -> Result<()> { fn rudp_ordered_pair() -> Result<(CultNetRudpSession, CultNetRudpSession)> { let mut client = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 410, - initial_sequence: 1, + initial_sequence: Some(1), ..CultNetRudpSessionOptions::default() }); let mut server = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 410, - initial_sequence: 500, + initial_sequence: Some(500), ..CultNetRudpSessionOptions::default() }); let connect = client.create_connect(0, Vec::new())?; @@ -2654,7 +2654,7 @@ fn rudp_reset_forgets_held_frames_and_reseeds_the_watermark_from_the_next_handsh receiver.reset_peer_state(); let mut next = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 410, - initial_sequence: 100, + initial_sequence: Some(100), ..CultNetRudpSessionOptions::default() }); let accept = receiver.accept_connect(&next.create_connect(0, Vec::new())?, 2, Vec::new())?; @@ -2723,12 +2723,12 @@ fn rudp_ordered_hold_buffer_is_bounded_in_bytes() -> Result<()> { fn rudp_far_ahead_sequence_cannot_starve_the_session() -> Result<()> { let mut sender = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 404, - initial_sequence: 1, + initial_sequence: Some(1), ..CultNetRudpSessionOptions::default() }); let mut receiver = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 404, - initial_sequence: 100, + initial_sequence: Some(100), ..CultNetRudpSessionOptions::default() }); let connect = sender.create_connect(0, Vec::new())?; @@ -2777,12 +2777,12 @@ fn rudp_reliable_sequence_exhaustion_is_reported_not_fatal() -> Result<()> { connection_id: 405, // One sequence left: the handshake takes it, so the next send is the // first allocation with nowhere to go. - initial_sequence: u32::MAX - 1, + initial_sequence: Some(u32::MAX - 1), ..CultNetRudpSessionOptions::default() }); let mut receiver = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 405, - initial_sequence: 100, + initial_sequence: Some(100), ..CultNetRudpSessionOptions::default() }); let connect = sender.create_connect(0, Vec::new())?; @@ -2846,7 +2846,7 @@ fn tcp_framed_receive_refuses_a_length_beyond_the_advertised_maximum() -> Result fn rudp_reliable_expiry_drops_late_packets_and_leaves_durable_sends_alone() -> Result<()> { let mut sender = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 7, - initial_sequence: 10, + initial_sequence: Some(10), resend_delay_ms: 100, ..CultNetRudpSessionOptions::default() }); @@ -2910,7 +2910,7 @@ fn rudp_reliable_expiry_drops_late_packets_and_leaves_durable_sends_alone() -> R fn rudp_reliable_expiry_also_reclaims_the_send_backlog() -> Result<()> { let mut sender = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 9, - initial_sequence: 10, + initial_sequence: Some(10), resend_delay_ms: 100, ..CultNetRudpSessionOptions::default() }); @@ -2999,12 +2999,12 @@ fn rudp_profile_expires_only_the_media_channels() -> Result<()> { fn connected_rudp_pair() -> Result<(CultNetRudpSession, CultNetRudpSession)> { let mut client = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 311, - initial_sequence: 1, + initial_sequence: Some(1), ..CultNetRudpSessionOptions::default() }); let mut server = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: 311, - initial_sequence: 100, + initial_sequence: Some(100), ..CultNetRudpSessionOptions::default() }); let connect = client.create_connect(0, Vec::new())?; diff --git a/packages/cultnet-rs/tests/rudp_connect_generation.rs b/packages/cultnet-rs/tests/rudp_connect_generation.rs index 2327ec53..ff8bb5ab 100644 --- a/packages/cultnet-rs/tests/rudp_connect_generation.rs +++ b/packages/cultnet-rs/tests/rudp_connect_generation.rs @@ -20,7 +20,7 @@ fn socket() -> Result { fn session(initial_sequence: u32) -> CultNetRudpSession { CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: CONNECTION_ID, - initial_sequence, + initial_sequence: Some(initial_sequence), resend_delay_ms: 250, max_pending_reliable_packets: None, }) @@ -222,7 +222,7 @@ fn a_full_queue_owed_to_a_vanished_peer_does_not_refuse_a_new_generation() -> Re let bounded = |initial_sequence: u32| { CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: CONNECTION_ID, - initial_sequence, + initial_sequence: Some(initial_sequence), resend_delay_ms: 250, max_pending_reliable_packets: Some(1), }) @@ -298,10 +298,12 @@ fn ordered_frames_after_the_accept_are_delivered_in_order_whatever_arrives_first Ok(()) } +/// The options say nothing about the initial sequence; each session draws its +/// own, so one options object serves many sessions without giving them one +/// sequence. #[test] -fn default_initial_sequences_are_drawn_at_random_from_one_to_two_to_the_thirty_first() -> Result<()> { - fn assert_random(label: &str, draw: &dyn Fn() -> u32) { - let draws: BTreeSet = (0..64).map(|_| draw()).collect(); +fn sessions_from_one_options_object_each_draw_their_own_initial_sequence() -> Result<()> { + fn assert_random(label: &str, draws: &BTreeSet) { assert!(draws.len() > 32, "{label} does not draw at random: {draws:?}"); assert!( draws.iter().all(|value| (1..(1_u32 << 31)).contains(value)), @@ -309,25 +311,69 @@ fn default_initial_sequences_are_drawn_at_random_from_one_to_two_to_the_thirty_f ); } let address: SocketAddr = "127.0.0.1:9".parse()?; - assert_random("random_initial_sequence", &random_initial_sequence); - assert_random("session options", &|| { - CultNetRudpSessionOptions::default().initial_sequence - }); - assert_random("client options", &|| { - CultNetRudpSocketTransportOptions::client("c", UdpSocket::bind("127.0.0.1:0").unwrap(), address, 1) - .initial_sequence - }); - assert_random("server options", &|| { - CultNetRudpSocketTransportOptions::server("s", UdpSocket::bind("127.0.0.1:0").unwrap(), 1) - .initial_sequence - }); - assert_random("hub options", &|| { - CultNetRudpServerHubOptions::new("h", UdpSocket::bind("127.0.0.1:0").unwrap(), 1) - .initial_sequence - }); - assert_random("cultmesh options", &|| { - CultMeshRudpSocketOptions::default().initial_sequence - }); + assert_eq!(CultNetRudpSessionOptions::default().initial_sequence, None); + assert_eq!( + CultNetRudpSocketTransportOptions::client("c", socket()?, address, 1).initial_sequence, + None + ); + assert_eq!( + CultNetRudpSocketTransportOptions::server("s", socket()?, 1).initial_sequence, + None + ); + assert_eq!( + CultNetRudpServerHubOptions::new("h", socket()?, 1).initial_sequence, + None + ); + assert_eq!(CultMeshRudpSocketOptions::default().initial_sequence, None); + + let options = CultNetRudpSessionOptions { + connection_id: CONNECTION_ID, + ..Default::default() + }; + let connects: BTreeSet = (0..64) + .map(|_| Ok(CultNetRudpSession::new(options.clone()).create_connect(0, Vec::new())?.sequence)) + .collect::>()?; + assert_random("sessions from one options object", &connects); + Ok(()) +} + +/// A transport built from the same options each time (a reconnect loop's +/// factory) opens each connection with its own Connect sequence. +#[test] +fn a_reused_options_object_yields_a_different_connect_sequence_for_each_transport() -> Result<()> { + let listener = socket()?; + let endpoint = CultNetRudpEndpoint { host: "127.0.0.1".into(), port: listener.local_addr()?.port() }; + let options = CultMeshRudpSocketOptions::default(); + let mut sequences = BTreeSet::new(); + for _ in 0..8 { + let mut client = + CultMesh::create_rudp_client("client", CONNECTION_ID, &endpoint, options.clone())?; + client.connect(Vec::new())?; + let mut buffer = vec![0_u8; 65_535]; + let (received, _) = listener.recv_from(&mut buffer)?; + sequences.insert(decode_rudp_packet(&buffer[..received])?.sequence); + } + assert_eq!(sequences.len(), 8, "two connections opened with one Connect sequence: {sequences:?}"); + Ok(()) +} + +/// A hub builds a session for every client it admits; each draws its own +/// sequence, so no two clients are accepted with the same one. +#[test] +fn a_hub_accepts_each_client_with_its_own_sequence() -> Result<()> { + let mut hub = CultNetRudpServerHub::new(CultNetRudpServerHubOptions::new("hub", socket()?, CONNECTION_ID))?; + let hub_addr = hub.local_addr()?; + let mut accepts = BTreeSet::new(); + for _ in 0..8 { + let peer = socket()?; + let connect = session(1).create_connect(0, Vec::new())?; + peer.send_to(&encode_rudp_packet(&connect)?, hub_addr)?; + hub_event_matching(&mut hub, |event| matches!(event, CultNetRudpServerEvent::Connected { .. }))?; + let mut buffer = vec![0_u8; 65_535]; + let (received, _) = peer.recv_from(&mut buffer)?; + accepts.insert(decode_rudp_packet(&buffer[..received])?.sequence); + } + assert_eq!(accepts.len(), 8, "two clients were accepted with one sequence: {accepts:?}"); Ok(()) } @@ -353,7 +399,7 @@ fn client_on( initial_sequence: u32, ) -> Result { let mut options = CultNetRudpSocketTransportOptions::client("client", socket, remote, CONNECTION_ID); - options.initial_sequence = initial_sequence; + options.initial_sequence = Some(initial_sequence); CultNetRudpSocketTransportConnection::new(options) } @@ -366,7 +412,7 @@ fn the_hub_admits_a_restarted_client_with_the_same_address_id_and_payload() -> R let hub_addr = hub.local_addr()?; let shared = socket()?; let twin = shared.try_clone()?; - let mut first = client_on(shared, hub_addr, 50)?; + let mut first = client_on(shared, hub_addr, 50_000)?; first.connect(b"same".to_vec())?; let CultNetRudpServerEvent::Connected { session: original } = hub_event_matching(&mut hub, |event| matches!(event, CultNetRudpServerEvent::Connected { .. }))? @@ -418,7 +464,7 @@ fn server_mode_admits_a_restarted_client_and_delivers_its_frames() -> Result<()> ))?; let shared = socket()?; let twin = shared.try_clone()?; - let mut first = client_on(shared, server_addr, 50)?; + let mut first = client_on(shared, server_addr, 50_000)?; first.connect(b"same".to_vec())?; assert!(server.receive_once()?.is_none()); first.receive_once()?; @@ -572,3 +618,255 @@ fn the_hold_buffer_takes_exactly_64_channels_and_refuses_the_next() -> Result<() assert!(error.to_string().contains("too many ordered channels"), "{error}"); Ok(()) } + +// Ack Cut 1d: a frame from an earlier generation is a duplicate, a delayed +// Connect from an earlier attempt is stale, a Connect from a new endpoint is a +// new client. + +/// Whether an acknowledgement names `sequence` by its ack field or its mask. +fn names_sequence(ack: &CultNetRudpPacket, sequence: u32) -> bool { + ack.ack == sequence + || (0..32).any(|bit| { + ack.ack_mask & (1_u32 << bit) != 0 && ack.ack > bit && ack.ack - bit - 1 == sequence + }) +} + +/// A frame the client's old generation already delivered, retransmitted after +/// the client reconnected, is acknowledged and not delivered into the new +/// generation. Every sequence the old generation issued is below the new +/// Connect. +#[test] +fn a_frame_from_the_clients_earlier_generation_is_acknowledged_not_delivered_again() -> Result<()> { + let mut client = session(10); + let mut server = session(500); + handshake(&mut client, &mut server)?; + let old = send(&mut client, "old")?; + assert_eq!(names(&server.receive(&old, 1)?.delivered), ["old"]); + + let connect = client.create_connect(2, Vec::new())?; + let accept = server.accept_connect(&connect, 2, Vec::new())?; + client.receive(&accept, 2)?; + assert!(old.sequence < connect.sequence); + let late = server.receive(&old, 3)?; + assert!(late.delivered.is_empty(), "an earlier generation's frame was delivered again"); + let ack = server.create_ack_for_received(old.sequence); + assert!(names_sequence(&ack, old.sequence), "the duplicate was not acknowledged: {ack:?}"); + + let fresh = send(&mut client, "fresh")?; + assert_eq!(names(&server.receive(&fresh, 4)?.delivered), ["fresh"]); + Ok(()) +} + +/// The other direction: the server's frame delivered before the client +/// reconnected is not delivered to the client's new generation. +#[test] +fn a_frame_from_the_servers_earlier_generation_is_acknowledged_not_delivered_again() -> Result<()> { + let mut client = session(10); + let mut server = session(500); + handshake(&mut client, &mut server)?; + let old = send(&mut server, "old")?; + assert_eq!(names(&client.receive(&old, 1)?.delivered), ["old"]); + + let connect = client.create_connect(2, Vec::new())?; + let accept = server.accept_connect(&connect, 2, Vec::new())?; + client.receive(&accept, 2)?; + let late = client.receive(&old, 3)?; + assert!(late.delivered.is_empty(), "an earlier generation's frame was delivered again"); + assert!(names_sequence(&client.create_ack_for_received(old.sequence), old.sequence)); + + let fresh = send(&mut server, "fresh")?; + assert_eq!(names(&client.receive(&fresh, 4)?.delivered), ["fresh"]); + Ok(()) +} + +/// A frame far below the receiver's highest sequence is a duplicate that is +/// acknowledged by name; without the acknowledgement its sender retransmits it +/// for ever. +#[test] +fn a_duplicate_below_the_receive_window_is_acknowledged_by_name() -> Result<()> { + let mut client = session(10); + let mut server = session(500); + handshake(&mut client, &mut server)?; + let first = send(&mut client, "first")?; + assert_eq!(names(&server.receive(&first, 1)?.delivered), ["first"]); + for _ in 0..4_200 { + let packet = send(&mut client, "x")?; + server.receive(&packet, 1)?; + client.receive(&server.create_ack(), 1)?; + } + let again = server.receive(&first, 2)?; + assert!(again.delivered.is_empty()); + let ack = server.create_ack_for_received(first.sequence); + assert_eq!(ack.ack, first.sequence, "a duplicate below the window was not acknowledged by name"); + Ok(()) +} + +/// A Connect delayed from an earlier attempt of the client that is now +/// connected does not restart the session: the server answers with an Ack and +/// the client's ordered frames keep flowing. +#[test] +fn a_delayed_connect_from_an_earlier_attempt_does_not_strand_the_client() -> Result<()> { + let mut client = session(10); + let mut server = session(500); + let earlier = client.create_connect(0, Vec::new())?; + let retried = client.create_connect(300, Vec::new())?; + let accept = server.accept_connect(&retried, 301, Vec::new())?; + client.receive(&accept, 302)?; + server.receive(&client.create_ack_for_received(accept.sequence), 302)?; + assert!(client.connected()); + let a = send(&mut client, "a")?; + assert_eq!(names(&server.receive(&a, 303)?.delivered), ["a"]); + client.receive(&server.create_ack_for_received(a.sequence), 303)?; + + assert!(server.connect_repeats(&earlier), "the delayed Connect starts nothing"); + let reply = server.accept_connect(&earlier, 304, Vec::new())?; + assert_eq!(reply.packet_type, CultNetRudpPacketType::Ack); + client.receive(&reply, 305)?; + assert!(client.connected()); + + let b = send(&mut client, "b")?; + assert_eq!(names(&server.receive(&b, 306)?.delivered), ["b"], "the delayed Connect reset the server"); + client.receive(&server.create_ack_for_received(b.sequence), 307)?; + assert!(!client.pending_reliable_sequences().contains(&b.sequence)); + Ok(()) +} + +/// A stale Connect is the peer's echo from the past, not evidence it is alive; +/// a retransmit of the accepted Connect is. +#[test] +fn a_repeated_connect_refreshes_liveness_and_a_stale_one_does_not() -> Result<()> { + let mut client = session(10); + let mut server = session(500); + let earlier = client.create_connect(0, Vec::new())?; + let current = client.create_connect(1, Vec::new())?; + server.accept_connect(¤t, 0, Vec::new())?; + + server.accept_connect(¤t, 900, Vec::new())?; + assert!(!server.check_timeout(1_000, 500), "a repeated Connect did not refresh liveness"); + + server.accept_connect(&earlier, 1_400, Vec::new())?; + assert!(server.check_timeout(1_600, 500), "a stale Connect refreshed liveness"); + Ok(()) +} + +/// The window is serial: a sequence just before the current Connect's is stale +/// across the wrap of the 32-bit space, one just after is a new client. +#[test] +fn stale_connects_are_recognised_by_serial_arithmetic() -> Result<()> { + let mut server = session(500); + let current = session(3).create_connect(0, Vec::new())?; + server.accept_connect(¤t, 0, Vec::new())?; + let before_the_wrap = session(u32::MAX - 1).create_connect(0, Vec::new())?; + assert!(server.connect_repeats(&before_the_wrap)); + let after = session(4).create_connect(0, Vec::new())?; + assert!(!server.connect_repeats(&after)); + let beyond_the_window = session(3 + 4_096).create_connect(0, Vec::new())?; + assert!(!server.connect_repeats(&beyond_the_window)); + let just_inside = session(3_u32.wrapping_sub(4_095)).create_connect(0, Vec::new())?; + assert!(server.connect_repeats(&just_inside)); + let just_outside = session(3_u32.wrapping_sub(4_096)).create_connect(0, Vec::new())?; + assert!(!server.connect_repeats(&just_outside)); + Ok(()) +} + +/// A restarted client whose random first sequence lands just before the +/// server's current Connect is answered with an Ack, never an Accept. It does +/// not retransmit that Connect for ever: once the attempt times out it starts +/// a fresh one with a newly drawn sequence, and is admitted. +#[test] +fn a_restarted_client_whose_first_sequence_is_stale_connects_after_redrawing() -> Result<()> { + let mut server = session(500); + let mut old = session(1_000); + let connect = old.create_connect(0, Vec::new())?; + let old_accept = server.accept_connect(&connect, 0, Vec::new())?; + old.receive(&old_accept, 0)?; + + let mut restarted = session(900); + let first = restarted.create_connect(0, b"join".to_vec())?; + // The old client has not acknowledged its Accept yet, so that is the reply: + // it names the old Connect, not this one. + let reply = server.accept_connect(&first, 1, Vec::new())?; + assert_eq!(reply.packet_type, CultNetRudpPacketType::Accept); + restarted.receive(&reply, 1)?; + assert!(!restarted.connected(), "an Accept for another Connect connected the client"); + server.receive(&old.create_ack_for_received(old_accept.sequence), 1)?; + let reply = server.accept_connect(&first, 2, Vec::new())?; + assert_eq!(reply.packet_type, CultNetRudpPacketType::Ack); + restarted.receive(&reply, 2)?; + assert!(!restarted.connected()); + + let retransmitted = restarted.due_resends(1_000); + assert_eq!(retransmitted.len(), 1); + assert_eq!(retransmitted[0].sequence, first.sequence, "the attempt is still young"); + + let fresh = restarted.due_resends(3_500); + assert_eq!(fresh.len(), 1); + assert_eq!(fresh[0].packet_type, CultNetRudpPacketType::Connect); + assert_ne!(fresh[0].sequence, first.sequence, "the same Connect was retransmitted for ever"); + assert_eq!(fresh[0].payload, b"join", "the fresh attempt lost the Connect payload"); + + let accept = server.accept_connect(&fresh[0], 3_500, Vec::new())?; + assert_eq!(accept.packet_type, CultNetRudpPacketType::Accept); + restarted.receive(&accept, 3_500)?; + assert!(restarted.connected()); + let frame = send(&mut restarted, "hello")?; + assert_eq!(names(&server.receive(&frame, 3_501)?.delivered), ["hello"]); + Ok(()) +} + +/// A client whose Connect was answered is not given a new Connect by the +/// clock: the attempt timeout belongs to an unanswered Connect. +#[test] +fn an_answered_connect_is_never_replaced_by_the_attempt_timeout() -> Result<()> { + let mut client = session(10); + let mut server = session(500); + let (connect, _) = handshake(&mut client, &mut server)?; + let resent = client.due_resends(60_000); + assert!( + resent.iter().all(|packet| packet.packet_type != CultNetRudpPacketType::Connect + || packet.sequence == connect.sequence), + "a connected client started a new attempt" + ); + assert!(client.connected()); + Ok(()) +} + +/// A pinned client that restarts on a new port against a server-mode transport +/// is a new client: the Connect starts a new generation and the client is +/// admitted, though its sequence is the one the old client's Connect carried. +#[test] +fn server_mode_admits_a_pinned_client_that_restarts_on_a_new_port() -> Result<()> { + let server_socket = socket()?; + let server_addr = server_socket.local_addr()?; + let mut server = CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions::server( + "server", + server_socket, + CONNECTION_ID, + ))?; + let mut first = client_on(socket()?, server_addr, 1)?; + first.connect(b"join".to_vec())?; + assert!(server.receive_once()?.is_none()); + first.receive_once()?; + first.send("schema", b"hello".to_vec())?; + assert_eq!(server.receive_once()?.expect("first client frame").payload, b"hello"); + drop(first); + + let mut second = client_on(socket()?, server_addr, 1)?; + second.connect(b"join".to_vec())?; + assert!(server.receive_once()?.is_none()); + second.receive_once()?; + assert!(second.connected(), "the restarted client on a new port was not admitted"); + second.send("schema", b"after".to_vec())?; + assert_eq!(server.receive_once()?.expect("restarted client frame").payload, b"after"); + Ok(()) +} + +/// An accepted peer that never speaks again times out: accepting a Connect is +/// the first thing heard from it. +#[test] +fn an_accepted_peer_that_goes_silent_times_out() -> Result<()> { + let mut server = session(500); + server.accept_connect(&session(10).create_connect(0, Vec::new())?, 0, Vec::new())?; + assert!(server.check_timeout(100_000, 1_000)); + Ok(()) +} diff --git a/packages/cultnet-rs/tests/rudp_server_hub.rs b/packages/cultnet-rs/tests/rudp_server_hub.rs index e18e20a5..ab4ea71c 100644 --- a/packages/cultnet-rs/tests/rudp_server_hub.rs +++ b/packages/cultnet-rs/tests/rudp_server_hub.rs @@ -247,7 +247,7 @@ fn identical_connect_retransmit_reuses_pending_accept_after_loss() -> Result<()> let client_socket = socket()?; let mut client_session = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: CONNECTION_ID, - initial_sequence: 1, + initial_sequence: Some(1), resend_delay_ms: 250, max_pending_reliable_packets: None, }); @@ -286,13 +286,13 @@ fn identical_connect_retransmit_reuses_pending_accept_after_loss() -> Result<()> fn exact_reliable_acks_clear_more_than_one_ack_window_of_fragments() -> Result<()> { let mut sender = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: CONNECTION_ID, - initial_sequence: 1, + initial_sequence: Some(1), resend_delay_ms: 250, max_pending_reliable_packets: None, }); let mut receiver = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: CONNECTION_ID, - initial_sequence: 1, + initial_sequence: Some(1), resend_delay_ms: 250, max_pending_reliable_packets: None, }); @@ -346,7 +346,7 @@ fn exact_reliable_acks_clear_more_than_one_ack_window_of_fragments() -> Result<( fn session_and_hub_reject_configured_memory_bounds() -> Result<()> { let mut receiver = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: CONNECTION_ID, - initial_sequence: 1, + initial_sequence: Some(1), resend_delay_ms: 250, max_pending_reliable_packets: None, }); @@ -354,7 +354,7 @@ fn session_and_hub_reject_configured_memory_bounds() -> Result<()> { receiver.set_max_pending_fragment_sets(1)?; let mut sender = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: CONNECTION_ID, - initial_sequence: 1, + initial_sequence: Some(1), resend_delay_ms: 250, max_pending_reliable_packets: None, }); @@ -422,13 +422,13 @@ fn session_and_hub_reject_configured_memory_bounds() -> Result<()> { fn replay_history_is_bounded_and_idle_hub_sessions_expire() -> Result<()> { let mut sender = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: CONNECTION_ID, - initial_sequence: 1, + initial_sequence: Some(1), resend_delay_ms: 250, max_pending_reliable_packets: None, }); let mut receiver = CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id: CONNECTION_ID, - initial_sequence: 1, + initial_sequence: Some(1), resend_delay_ms: 250, max_pending_reliable_packets: None, }); diff --git a/packages/cultnet-rs/tests/rudp_stray_packets.rs b/packages/cultnet-rs/tests/rudp_stray_packets.rs index 21162ef2..a64097de 100644 --- a/packages/cultnet-rs/tests/rudp_stray_packets.rs +++ b/packages/cultnet-rs/tests/rudp_stray_packets.rs @@ -36,7 +36,7 @@ fn raw_session(connection_id: u32) -> CultNetRudpSession { fn raw_session_from(connection_id: u32, initial_sequence: u32) -> CultNetRudpSession { CultNetRudpSession::new(CultNetRudpSessionOptions { connection_id, - initial_sequence, + initial_sequence: Some(initial_sequence), resend_delay_ms: 250, max_pending_reliable_packets: None, }) @@ -446,7 +446,7 @@ fn server_mode_ends_the_session_when_the_session_refuses_a_packet() -> Result<() #[test] fn constructors_reject_limits_that_make_a_connect_unadmittable() -> Result<()> { let mut hub = CultNetRudpServerHubOptions::new("hub", socket()?, CONNECTION_ID); - hub.initial_sequence = u32::MAX; + hub.initial_sequence = Some(u32::MAX); assert!(CultNetRudpServerHub::new(hub).is_err()); let mut hub = CultNetRudpServerHubOptions::new("hub", socket()?, CONNECTION_ID); hub.max_pending_reliable_packets = Some(0); @@ -459,13 +459,13 @@ fn constructors_reject_limits_that_make_a_connect_unadmittable() -> Result<()> { ] { let addr = "127.0.0.1:9".parse()?; let mut options = build(socket()?, addr); - options.initial_sequence = u32::MAX; + options.initial_sequence = Some(u32::MAX); assert!(CultNetRudpSocketTransportConnection::new(options).is_err()); let mut options = build(socket()?, addr); options.max_pending_reliable_packets = Some(0); assert!(CultNetRudpSocketTransportConnection::new(options).is_err()); let mut options = build(socket()?, addr); - options.initial_sequence = u32::MAX - 1; + options.initial_sequence = Some(u32::MAX - 1); options.max_pending_reliable_packets = Some(1); assert!(CultNetRudpSocketTransportConnection::new(options).is_ok()); }