A repeat of a packet the session already took, and a packet too far ahead to be remembered, delivered no frame and so drew the superseded-write refusal again on every send, breaking write-receipt rule 1. The refusal now applies only to the first packet the session takes for a sequence; CultNetRudpSession::has_received exposes that test. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
3004 lines
113 KiB
Rust
3004 lines
113 KiB
Rust
use anyhow::Result;
|
|
use anyhow::anyhow;
|
|
use std::collections::BTreeMap;
|
|
use std::collections::BTreeSet;
|
|
use std::collections::VecDeque;
|
|
use std::io::ErrorKind;
|
|
use std::net::SocketAddr;
|
|
use std::net::UdpSocket;
|
|
use std::thread;
|
|
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
|
|
|
use crate::CultNetMessage;
|
|
use crate::CultNetReconnectController;
|
|
use crate::CultNetReconnectDecision;
|
|
use crate::CultNetReconnectPolicy;
|
|
use crate::CultNetTransportChannel;
|
|
use crate::CultNetTransportDelivery;
|
|
use crate::CultNetTransportDescriptor;
|
|
use crate::CultNetTransportFrame;
|
|
use crate::CultNetTransportOrdering;
|
|
use crate::CultNetTransportProfile;
|
|
use crate::CultNetTransportProtocol;
|
|
use crate::CultNetTransportStats;
|
|
use crate::CultNetWireContract;
|
|
use crate::GAMECULT_MEDIA_CHANNEL;
|
|
use crate::GAMECULT_MEDIA_MAX_WIRE_BYTES;
|
|
use crate::create_reconnect_policy;
|
|
use crate::decode_cultnet_message_from_slice;
|
|
use crate::encode_cultnet_message_to_vec;
|
|
|
|
#[cfg(test)]
|
|
mod send_failure_tests;
|
|
|
|
const RUDP_MAGIC: [u8; 4] = [0x43, 0x4e, 0x52, 0x30];
|
|
const RUDP_VERSION: u8 = 0;
|
|
pub(crate) const RUDP_FIXED_HEADER_BYTES: usize = 36;
|
|
pub const CULTNET_RUDP_DEFAULT_MAX_PAYLOAD_BYTES: usize = 16 * 1024 * 1024;
|
|
pub const CULTNET_RUDP_RELIABLE_SEND_WINDOW_PACKETS: usize = 32;
|
|
const RUDP_RECEIVED_SEQUENCE_WINDOW: usize = 4_096;
|
|
/// Live media tolerates loss but not lateness: a frame retransmitted after this
|
|
/// long describes a moment that has already passed. State channels never
|
|
/// expire, so this default applies only to the media channel.
|
|
const DEFAULT_MEDIA_RELIABLE_EXPIRE_AFTER_MS: u64 = 75;
|
|
/// A peer chooses its own channel ids and its own send order, so the per-channel
|
|
/// maps and the out-of-order hold buffer are both attacker-sized unless capped.
|
|
const RUDP_MAX_TRACKED_CHANNELS: usize = 64;
|
|
/// A peer cannot be trusted to pick the next sequence honestly. One packet far
|
|
/// 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;
|
|
/// The sender's flow window: a reliable packet goes on the wire only while its
|
|
/// sequence is at most this far above the lowest unacked one, and the payload
|
|
/// above that sequence stays within the byte bound. A receiver holds
|
|
/// `RUDP_RECEIVE_AHEAD_WINDOW - 1` sequences and `RUDP_MAX_ORDERED_BUFFERED_BYTES`
|
|
/// beyond its watermark, so a sender that obeys this never overruns it.
|
|
const RUDP_FLOW_WINDOW_SEQUENCES: u32 = RUDP_RECEIVE_AHEAD_WINDOW - 1;
|
|
const RUDP_FLOW_WINDOW_BYTES: usize = RUDP_MAX_ORDERED_BUFFERED_BYTES;
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum CultNetRudpPacketType {
|
|
Connect,
|
|
Accept,
|
|
Data,
|
|
Ack,
|
|
Ping,
|
|
Pong,
|
|
Disconnect,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub struct CultNetRudpPacket {
|
|
pub packet_type: CultNetRudpPacketType,
|
|
pub connection_id: u32,
|
|
pub sequence: u32,
|
|
pub ack: u32,
|
|
pub ack_mask: u32,
|
|
pub channel_id: String,
|
|
pub reliable: bool,
|
|
pub ordered: bool,
|
|
pub sequenced: bool,
|
|
pub fragment_id: u16,
|
|
pub fragment_index: u16,
|
|
pub fragment_count: u16,
|
|
pub payload: Vec<u8>,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub struct CultNetRudpDeliveredFrame {
|
|
pub channel_id: String,
|
|
pub payload: Vec<u8>,
|
|
pub sequence: u32,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub struct CultNetRudpReceiveResult {
|
|
pub delivered: Vec<CultNetRudpDeliveredFrame>,
|
|
pub ready_to_send: Vec<CultNetRudpPacket>,
|
|
pub reply: Option<CultNetRudpPacket>,
|
|
pub pong: bool,
|
|
pub pong_payload: Vec<u8>,
|
|
pub disconnected: bool,
|
|
pub disconnect_reason: Vec<u8>,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub struct CultNetRudpSessionOptions {
|
|
pub connection_id: 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<u32>,
|
|
pub resend_delay_ms: u64,
|
|
pub max_pending_reliable_packets: Option<usize>,
|
|
}
|
|
|
|
impl Default for CultNetRudpSessionOptions {
|
|
fn default() -> Self {
|
|
Self {
|
|
connection_id: 0,
|
|
initial_sequence: None,
|
|
resend_delay_ms: 250,
|
|
max_pending_reliable_packets: None,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A sequence drawn at random from [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.
|
|
fn draw_sequence() -> u32 {
|
|
rand::random_range(1..(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`.
|
|
fn packet_acknowledges(packet: &CultNetRudpPacket, sequence: u32) -> bool {
|
|
if packet.ack == sequence {
|
|
return true;
|
|
}
|
|
(0..32).any(|bit| {
|
|
packet.ack_mask & (1_u32 << bit) != 0
|
|
&& packet.ack > bit
|
|
&& packet.ack - bit - 1 == sequence
|
|
})
|
|
}
|
|
|
|
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
|
pub struct CultNetRudpSendOptions {
|
|
pub reliable: bool,
|
|
pub ordered: bool,
|
|
pub sequenced: bool,
|
|
pub now_ms: u64,
|
|
/// Drop a reliable packet instead of retransmitting it once this many
|
|
/// milliseconds have passed since the send call. `None` retransmits until
|
|
/// acknowledged, which is correct for state and wrong for live media, where
|
|
/// a late frame is worse than a missing one.
|
|
pub reliable_expire_after_ms: Option<u64>,
|
|
}
|
|
|
|
/// Identifies every transport packet belonging to one non-expiring reliable
|
|
/// send. A write belongs to the session generation it was issued in, and every
|
|
/// way a generation can end (a Disconnect from the peer, a local `disconnect()`,
|
|
/// a timeout, a refused packet) invalidates the receipts it issued for good.
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub struct CultNetRudpReliableSendReceipt {
|
|
session_id: u64,
|
|
generation: u64,
|
|
sequences: Vec<u32>,
|
|
}
|
|
|
|
impl CultNetRudpReliableSendReceipt {
|
|
pub fn packet_sequences(&self) -> &[u32] {
|
|
&self.sequences
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum CultNetRudpReliableSendStatus {
|
|
Pending,
|
|
Acknowledged,
|
|
Invalidated,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
struct PendingReliablePacket {
|
|
packet: CultNetRudpPacket,
|
|
last_sent_at_ms: u64,
|
|
expires_at_ms: Option<u64>,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
struct FragmentBuffer {
|
|
channel_id: String,
|
|
ordered: bool,
|
|
fragment_count: u16,
|
|
payloads: BTreeMap<u16, Vec<u8>>,
|
|
sequences: BTreeMap<u16, u32>,
|
|
/// Session-local arrival ordinal of the newest fragment in this set. A
|
|
/// set that stops being touched is one that lost a fragment; it is the
|
|
/// first to go when the pending-set bound is reached.
|
|
last_touched: u64,
|
|
}
|
|
|
|
pub struct CultNetRudpSession {
|
|
/// Random per session. A receipt carries its session's id, so one asked of
|
|
/// another session reads `Invalidated` instead of borrowing that session's
|
|
/// generation numbers.
|
|
session_id: u64,
|
|
/// Advances every time a generation ends. Everything issued in a generation
|
|
/// (writes, receipts, flushes) belongs to it and dies with it.
|
|
generation: u64,
|
|
/// True from the end of a generation until the next Connect or Accept begins
|
|
/// one. A flush started in that interval has no live generation to wait on.
|
|
ended: bool,
|
|
/// The sequence of the Connect that started the current generation: sent
|
|
/// by this side, or accepted from the peer. A Connect repeats exactly when
|
|
/// the session is connected and the Connect carries this sequence.
|
|
connect_sequence: Option<u32>,
|
|
/// A Connect this side sent is unanswered. Only then is an Accept honoured.
|
|
awaiting_accept: bool,
|
|
/// The payload of the Connect this side sent, kept so a fresh attempt can
|
|
/// always be built whatever became of the pending packet.
|
|
connect_payload: Vec<u8>,
|
|
/// 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<usize>,
|
|
max_payload_bytes: Option<usize>,
|
|
max_pending_fragment_sets: usize,
|
|
next_sequence: u32,
|
|
next_sequenced_by_channel: BTreeMap<String, u32>,
|
|
next_fragment_id: u16,
|
|
connected: bool,
|
|
last_received_at_ms: Option<u64>,
|
|
highest_received_sequence: Option<u32>,
|
|
received_sequences: BTreeSet<u32>,
|
|
latest_sequenced_by_channel: BTreeMap<String, u32>,
|
|
pending_reliable: BTreeMap<u32, PendingReliablePacket>,
|
|
/// Payload sizes of acknowledged reliable sequences above the lowest
|
|
/// unacknowledged one. The receiver still holds those bytes behind the gap,
|
|
/// so the flow window keeps counting them until the lowest sequence
|
|
/// advances past them.
|
|
acked_above_lowest: BTreeMap<u32, usize>,
|
|
queued_reliable: VecDeque<(CultNetRudpPacket, Option<u64>)>,
|
|
reliable_packets_expired: u64,
|
|
/// Every reliable sequence up to and including this one has been received
|
|
/// since the peer state was last reset. Only the handshake seeds it: the
|
|
/// peer's Connect on the accepting side, the peer's Accept on the
|
|
/// connecting side. Reliable data that arrives before that is refused.
|
|
received_through: Option<u32>,
|
|
/// Ordered frames received but not yet deliverable, keyed by first
|
|
/// sequence. A frame is held for exactly one reason: a reliable sequence
|
|
/// below it has not arrived.
|
|
ordered_held: BTreeMap<u32, CultNetRudpDeliveredFrame>,
|
|
fragment_buffers: BTreeMap<(String, u16), FragmentBuffer>,
|
|
fragment_touches: u64,
|
|
fragment_sets_evicted: u64,
|
|
}
|
|
|
|
impl CultNetRudpSession {
|
|
pub fn new(options: CultNetRudpSessionOptions) -> Self {
|
|
Self {
|
|
session_id: rand::random(),
|
|
generation: 0,
|
|
ended: false,
|
|
connect_sequence: None,
|
|
awaiting_accept: false,
|
|
connect_payload: Vec::new(),
|
|
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.unwrap_or_else(draw_sequence),
|
|
next_sequenced_by_channel: BTreeMap::new(),
|
|
next_fragment_id: 1,
|
|
connected: false,
|
|
last_received_at_ms: None,
|
|
highest_received_sequence: None,
|
|
received_sequences: BTreeSet::new(),
|
|
latest_sequenced_by_channel: BTreeMap::new(),
|
|
pending_reliable: BTreeMap::new(),
|
|
acked_above_lowest: BTreeMap::new(),
|
|
queued_reliable: VecDeque::new(),
|
|
reliable_packets_expired: 0,
|
|
received_through: None,
|
|
ordered_held: BTreeMap::new(),
|
|
fragment_buffers: BTreeMap::new(),
|
|
fragment_touches: 0,
|
|
fragment_sets_evicted: 0,
|
|
}
|
|
}
|
|
|
|
pub fn connection_id(&self) -> u32 {
|
|
self.connection_id
|
|
}
|
|
|
|
pub fn resend_delay_ms(&self) -> u64 {
|
|
self.resend_delay_ms
|
|
}
|
|
|
|
pub fn connected(&self) -> bool {
|
|
self.connected
|
|
}
|
|
|
|
pub fn assume_connected(&mut self, now_ms: u64) {
|
|
self.connected = true;
|
|
self.ended = false;
|
|
self.last_received_at_ms = Some(now_ms);
|
|
}
|
|
|
|
pub fn pending_reliable_sequences(&self) -> Vec<u32> {
|
|
self.pending_reliable.keys().copied().collect()
|
|
}
|
|
|
|
/// Reliable packets dropped by their expiry deadline rather than
|
|
/// acknowledged. A rising count means the peer is not keeping up.
|
|
pub fn reliable_packets_expired(&self) -> u64 {
|
|
self.reliable_packets_expired
|
|
}
|
|
|
|
/// Incomplete fragment sets discarded to admit a newer one. Each is a
|
|
/// payload that lost at least one fragment on the wire; a rising count is
|
|
/// the link's loss rate multiplied by the fragment count, and the reason
|
|
/// media payloads should fit in one packet.
|
|
pub fn fragment_sets_evicted(&self) -> u64 {
|
|
self.fragment_sets_evicted
|
|
}
|
|
|
|
pub fn queued_reliable_packet_count(&self) -> usize {
|
|
self.queued_reliable.len()
|
|
}
|
|
|
|
pub fn outstanding_reliable_packet_count(&self) -> usize {
|
|
self.pending_reliable.len() + self.queued_reliable.len()
|
|
}
|
|
|
|
fn pending_accept_for_resend(&mut self, now_ms: u64) -> Option<CultNetRudpPacket> {
|
|
let pending = self
|
|
.pending_reliable
|
|
.values_mut()
|
|
.find(|pending| pending.packet.packet_type == CultNetRudpPacketType::Accept)?;
|
|
pending.last_sent_at_ms = now_ms;
|
|
Some(pending.packet.clone())
|
|
}
|
|
|
|
fn generation(&self) -> u64 {
|
|
self.generation
|
|
}
|
|
|
|
fn ended(&self) -> bool {
|
|
self.ended
|
|
}
|
|
|
|
/// The one way a session generation ends. The session stops being
|
|
/// connected and what it still owed the peer dies with it: a write not yet
|
|
/// acknowledged is dropped, so no later session retransmits it or credits an
|
|
/// ack to it, and its receipt can never become Acknowledged. What was
|
|
/// learned from the peer is not touched: the peer may not know the session
|
|
/// ended, and forgetting what it sent would let its retransmits be
|
|
/// delivered twice.
|
|
fn end_session(&mut self) {
|
|
self.connected = false;
|
|
self.ended = true;
|
|
self.awaiting_accept = false;
|
|
self.generation += 1;
|
|
self.pending_reliable.clear();
|
|
self.acked_above_lowest.clear();
|
|
self.queued_reliable.clear();
|
|
}
|
|
|
|
fn reliable_send_status(
|
|
&self,
|
|
receipt: &CultNetRudpReliableSendReceipt,
|
|
) -> CultNetRudpReliableSendStatus {
|
|
if receipt.session_id != self.session_id || receipt.generation != self.generation {
|
|
return CultNetRudpReliableSendStatus::Invalidated;
|
|
}
|
|
if receipt
|
|
.sequences
|
|
.iter()
|
|
.any(|sequence| self.pending_reliable.contains_key(sequence))
|
|
{
|
|
CultNetRudpReliableSendStatus::Pending
|
|
} else {
|
|
CultNetRudpReliableSendStatus::Acknowledged
|
|
}
|
|
}
|
|
|
|
fn non_expiring_reliable_receipt(
|
|
&self,
|
|
packets: &[CultNetRudpPacket],
|
|
) -> Result<CultNetRudpReliableSendReceipt> {
|
|
if packets.is_empty() || packets.iter().any(|packet| !packet.reliable) {
|
|
return Err(anyhow!(
|
|
"RUDP acknowledgement receipts require a non-empty reliable packet set"
|
|
));
|
|
}
|
|
Ok(CultNetRudpReliableSendReceipt {
|
|
session_id: self.session_id,
|
|
generation: self.generation,
|
|
sequences: packets.iter().map(|packet| packet.sequence).collect(),
|
|
})
|
|
}
|
|
|
|
pub fn last_received_at_ms(&self) -> Option<u64> {
|
|
self.last_received_at_ms
|
|
}
|
|
|
|
pub fn set_max_payload_bytes(&mut self, max_payload_bytes: Option<usize>) {
|
|
self.max_payload_bytes = max_payload_bytes;
|
|
}
|
|
|
|
pub fn set_max_pending_fragment_sets(
|
|
&mut self,
|
|
max_pending_fragment_sets: usize,
|
|
) -> Result<()> {
|
|
if max_pending_fragment_sets == 0 {
|
|
return Err(anyhow!(
|
|
"RUDP max_pending_fragment_sets must be greater than zero"
|
|
));
|
|
}
|
|
self.max_pending_fragment_sets = max_pending_fragment_sets;
|
|
Ok(())
|
|
}
|
|
|
|
/// Forgets everything learned from the peer. Sequence numbers and fragment
|
|
/// ids already issued stay issued: a peer that still remembers them must
|
|
/// never see one reused.
|
|
pub fn reset_peer_state(&mut self) {
|
|
self.end_session();
|
|
self.next_sequenced_by_channel.clear();
|
|
self.last_received_at_ms = None;
|
|
self.highest_received_sequence = None;
|
|
self.received_sequences.clear();
|
|
self.latest_sequenced_by_channel.clear();
|
|
self.received_through = None;
|
|
self.ordered_held.clear();
|
|
self.fragment_buffers.clear();
|
|
}
|
|
|
|
/// Ends a session that refused a packet. `receive` has already recorded the
|
|
/// refused packet's reliable sequence, so the session cannot be kept: a
|
|
/// retransmit would be acknowledged and the frame silently lost. Returns the
|
|
/// goodbye for the peer, built after the reset or its ack field would
|
|
/// acknowledge the very frame that was refused.
|
|
pub fn end_refused_session(&mut self) -> CultNetRudpPacket {
|
|
self.reset_peer_state();
|
|
self.create_disconnect(RUDP_REFUSED_PACKET_REASON.to_vec())
|
|
}
|
|
|
|
/// Ends a session because the server itself could not answer a write it owes an answer to (its answer
|
|
/// could not be encoded, queued or sent). The peer did nothing wrong: this goodbye is not the
|
|
/// "session refused a packet" of a protocol refusal.
|
|
pub fn end_local_failure_session(&mut self) -> CultNetRudpPacket {
|
|
self.reset_peer_state();
|
|
self.create_disconnect(RUDP_LOCAL_FAILURE_REASON.to_vec())
|
|
}
|
|
|
|
/// Ends a session that owes its peer a packet that can never be sent as
|
|
/// built (see `is_permanent_send_error`). Resending it would fail forever,
|
|
/// and dropping it would leave a reliable sequence the peer waits on for
|
|
/// good, so the session cannot be kept. Returns the goodbye for the peer;
|
|
/// its reason names the failure by its fixed name (`send_error_code`).
|
|
pub fn end_unsendable_session(&mut self, error: &std::io::Error) -> CultNetRudpPacket {
|
|
self.reset_peer_state();
|
|
self.create_disconnect(
|
|
format!(
|
|
"{RUDP_UNSENDABLE_PACKET_REASON}: {}",
|
|
send_error_code(error)
|
|
)
|
|
.into_bytes(),
|
|
)
|
|
}
|
|
|
|
/// Undoes a send that never reached the wire: every packet it created at
|
|
/// or after `first_sequence`, pending or queued, leaves no trace and its
|
|
/// sequences are reissued, so the peer never sees a gap. Only valid while
|
|
/// nothing else has been sent since.
|
|
fn withdraw_send(&mut self, first_sequence: u32) {
|
|
self.pending_reliable
|
|
.retain(|sequence, _| *sequence < first_sequence);
|
|
self.queued_reliable
|
|
.retain(|(packet, _)| packet.sequence < first_sequence);
|
|
self.next_sequence = first_sequence;
|
|
}
|
|
|
|
pub fn create_connect(&mut self, now_ms: u64, payload: Vec<u8>) -> Result<CultNetRudpPacket> {
|
|
// A session that has had a peer starts a new generation: nothing it
|
|
// learned from that peer describes the one this Connect reaches, and
|
|
// what it still owed that peer no longer takes room in the queue.
|
|
if self.connect_sequence.is_some() {
|
|
self.reset_peer_state();
|
|
}
|
|
self.ensure_reliable_capacity(1)?;
|
|
let packet = self.create_packet(
|
|
CultNetRudpPacketType::Connect,
|
|
"control",
|
|
payload,
|
|
true,
|
|
true,
|
|
false,
|
|
);
|
|
self.ended = false;
|
|
self.connect_sequence = Some(packet.sequence);
|
|
self.awaiting_accept = true;
|
|
self.connect_started_at_ms = now_ms;
|
|
self.connect_payload = packet.payload.clone();
|
|
self.track_reliable(packet.clone(), now_ms, None);
|
|
Ok(packet)
|
|
}
|
|
|
|
/// 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.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. 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,
|
|
now_ms: u64,
|
|
payload: Vec<u8>,
|
|
) -> Result<CultNetRudpPacket> {
|
|
self.require_connection(packet)?;
|
|
if packet.packet_type != CultNetRudpPacketType::Connect {
|
|
return Err(anyhow!(
|
|
"Expected RUDP connect packet, got {:?}",
|
|
packet.packet_type
|
|
));
|
|
}
|
|
|
|
if self.connect_repeats(packet) {
|
|
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()));
|
|
}
|
|
|
|
self.reset_peer_state();
|
|
self.ensure_reliable_capacity(1)?;
|
|
self.seed_received(packet.sequence);
|
|
self.last_received_at_ms = Some(now_ms);
|
|
self.connect_sequence = Some(packet.sequence);
|
|
self.connected = true;
|
|
self.ended = false;
|
|
let response = self.create_packet(
|
|
CultNetRudpPacketType::Accept,
|
|
"control",
|
|
payload,
|
|
true,
|
|
true,
|
|
false,
|
|
);
|
|
self.track_reliable(response.clone(), now_ms, None);
|
|
Ok(response)
|
|
}
|
|
|
|
pub fn send(
|
|
&mut self,
|
|
channel_id: &str,
|
|
payload: Vec<u8>,
|
|
options: CultNetRudpSendOptions,
|
|
) -> Result<CultNetRudpPacket> {
|
|
// Measure the window as `send_many` will: without the deadline-passed
|
|
// sends it is about to reclaim.
|
|
if options.reliable {
|
|
self.purge_expired_reliable(options.now_ms);
|
|
}
|
|
if options.reliable
|
|
&& (!self.queued_reliable.is_empty()
|
|
|| !self.window_admits(self.next_sequence, payload.len()))
|
|
{
|
|
return Err(anyhow!(
|
|
"RUDP reliable send window is full; receive acknowledgements before sending"
|
|
));
|
|
}
|
|
self.send_many(channel_id, payload, options, None)?
|
|
.into_iter()
|
|
.next()
|
|
.ok_or_else(|| anyhow!("RUDP send produced no packets"))
|
|
}
|
|
|
|
pub fn send_many(
|
|
&mut self,
|
|
channel_id: &str,
|
|
payload: Vec<u8>,
|
|
options: CultNetRudpSendOptions,
|
|
max_fragment_bytes: Option<usize>,
|
|
) -> Result<Vec<CultNetRudpPacket>> {
|
|
if !self.connected {
|
|
return Err(anyhow!(
|
|
"Cannot send RUDP data before the session is connected"
|
|
));
|
|
}
|
|
if options.ordered && !options.reliable {
|
|
return Err(anyhow!("RUDP ordered delivery requires reliability"));
|
|
}
|
|
self.require_payload_size(channel_id, payload.len())?;
|
|
// Reclaim deadline-passed sends before measuring window capacity, so an
|
|
// expiring stream cannot be refused for a backlog it no longer owns.
|
|
self.purge_expired_reliable(options.now_ms);
|
|
let expires_at_ms = options
|
|
.reliable_expire_after_ms
|
|
.map(|ttl| options.now_ms.saturating_add(ttl));
|
|
|
|
if let Some(max_fragment_bytes) = max_fragment_bytes {
|
|
if max_fragment_bytes == 0 {
|
|
return Err(anyhow!("RUDP max_fragment_bytes must be greater than zero"));
|
|
}
|
|
if payload.len() > max_fragment_bytes {
|
|
let fragment_count = payload.len().div_ceil(max_fragment_bytes);
|
|
if fragment_count > u16::MAX as usize {
|
|
return Err(anyhow!("RUDP payload requires more than 65535 fragments"));
|
|
}
|
|
self.ensure_reliable_capacity(if options.reliable { fragment_count } else { 0 })?;
|
|
let fragment_id = self.allocate_fragment_id();
|
|
let mut packets = Vec::new();
|
|
for index in 0..fragment_count {
|
|
let start = index * max_fragment_bytes;
|
|
let end = (start + max_fragment_bytes).min(payload.len());
|
|
let packet = self.create_packet_with_fragments(
|
|
CultNetRudpPacketType::Data,
|
|
channel_id,
|
|
payload[start..end].to_vec(),
|
|
options.reliable,
|
|
options.ordered,
|
|
options.sequenced,
|
|
fragment_id,
|
|
index as u16,
|
|
fragment_count as u16,
|
|
);
|
|
packets.push(packet);
|
|
}
|
|
return Ok(if options.reliable {
|
|
self.admit_reliable_packets(packets, options.now_ms, expires_at_ms)
|
|
} else {
|
|
packets
|
|
});
|
|
}
|
|
}
|
|
|
|
self.ensure_reliable_capacity(if options.reliable { 1 } else { 0 })?;
|
|
let packet = self.create_packet(
|
|
CultNetRudpPacketType::Data,
|
|
channel_id,
|
|
payload,
|
|
options.reliable,
|
|
options.ordered,
|
|
options.sequenced,
|
|
);
|
|
if packet.reliable {
|
|
return Ok(self.admit_reliable_packets(vec![packet], options.now_ms, expires_at_ms));
|
|
}
|
|
Ok(vec![packet])
|
|
}
|
|
|
|
pub fn receive(
|
|
&mut self,
|
|
packet: &CultNetRudpPacket,
|
|
now_ms: u64,
|
|
) -> Result<CultNetRudpReceiveResult> {
|
|
self.require_connection(packet)?;
|
|
// An Accept counts only while this side's Connect is unanswered and the
|
|
// Accept names it. A late or duplicate one, or one from an earlier
|
|
// generation, must not seed the watermark or revive an ended session.
|
|
let honours_accept = packet.packet_type == CultNetRudpPacketType::Accept
|
|
&& self.awaiting_accept
|
|
&& self
|
|
.connect_sequence
|
|
.is_some_and(|connect| packet_acknowledges(packet, connect));
|
|
if packet.packet_type == CultNetRudpPacketType::Accept && !honours_accept {
|
|
return Ok(CultNetRudpReceiveResult {
|
|
delivered: Vec::new(),
|
|
ready_to_send: Vec::new(),
|
|
reply: None,
|
|
pong: false,
|
|
pong_payload: Vec::new(),
|
|
disconnected: false,
|
|
disconnect_reason: Vec::new(),
|
|
});
|
|
}
|
|
// While this side's Connect awaits its Accept, only the Accept it
|
|
// honours retires it: an Ack that names the Connect (a server's reply
|
|
// to a repeat or a stale copy) says the server did not start a session.
|
|
if honours_accept || !self.awaiting_accept {
|
|
self.apply_acknowledgements(packet);
|
|
}
|
|
self.purge_expired_reliable(now_ms);
|
|
let ready_to_send = self.promote_queued_reliable(now_ms);
|
|
self.last_received_at_ms = Some(now_ms);
|
|
|
|
if honours_accept {
|
|
self.awaiting_accept = false;
|
|
self.seed_received(packet.sequence);
|
|
self.connected = true;
|
|
return Ok(CultNetRudpReceiveResult {
|
|
delivered: Vec::new(),
|
|
ready_to_send,
|
|
reply: None,
|
|
pong: false,
|
|
pong_payload: Vec::new(),
|
|
disconnected: false,
|
|
disconnect_reason: Vec::new(),
|
|
});
|
|
}
|
|
|
|
if packet.packet_type == CultNetRudpPacketType::Ping {
|
|
return Ok(CultNetRudpReceiveResult {
|
|
delivered: Vec::new(),
|
|
ready_to_send,
|
|
reply: Some(self.create_packet(
|
|
CultNetRudpPacketType::Pong,
|
|
"control",
|
|
packet.payload.clone(),
|
|
false,
|
|
false,
|
|
false,
|
|
)),
|
|
pong: false,
|
|
pong_payload: Vec::new(),
|
|
disconnected: false,
|
|
disconnect_reason: Vec::new(),
|
|
});
|
|
}
|
|
|
|
if packet.packet_type == CultNetRudpPacketType::Ack
|
|
|| packet.packet_type == CultNetRudpPacketType::Pong
|
|
{
|
|
return Ok(CultNetRudpReceiveResult {
|
|
delivered: Vec::new(),
|
|
ready_to_send,
|
|
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(),
|
|
});
|
|
}
|
|
|
|
if packet.packet_type == CultNetRudpPacketType::Disconnect {
|
|
self.end_session();
|
|
return Ok(CultNetRudpReceiveResult {
|
|
delivered: Vec::new(),
|
|
ready_to_send,
|
|
reply: None,
|
|
pong: false,
|
|
pong_payload: Vec::new(),
|
|
disconnected: true,
|
|
disconnect_reason: packet.payload.clone(),
|
|
});
|
|
}
|
|
|
|
if packet.packet_type != CultNetRudpPacketType::Data {
|
|
return Ok(CultNetRudpReceiveResult {
|
|
delivered: Vec::new(),
|
|
ready_to_send,
|
|
reply: None,
|
|
pong: false,
|
|
pong_payload: Vec::new(),
|
|
disconnected: false,
|
|
disconnect_reason: Vec::new(),
|
|
});
|
|
}
|
|
|
|
// Reliable data before the handshake has seeded the watermark has no
|
|
// place in the order: refuse it unremembered, so it is not acknowledged
|
|
// and the sender retransmits it once the handshake is done.
|
|
if packet.reliable && self.received_through.is_none() {
|
|
return Ok(CultNetRudpReceiveResult {
|
|
delivered: Vec::new(),
|
|
ready_to_send,
|
|
reply: None,
|
|
pong: false,
|
|
pong_payload: Vec::new(),
|
|
disconnected: false,
|
|
disconnect_reason: Vec::new(),
|
|
});
|
|
}
|
|
|
|
let far_ahead = packet.reliable
|
|
&& self.highest_received_sequence.is_some_and(|highest| {
|
|
packet.sequence > highest
|
|
&& packet.sequence - highest > RUDP_RECEIVE_AHEAD_WINDOW
|
|
});
|
|
if far_ahead {
|
|
// Refuse without remembering. Recording it would move the highest
|
|
// received sequence out of reach of everything still in flight.
|
|
return Ok(CultNetRudpReceiveResult {
|
|
delivered: Vec::new(),
|
|
ready_to_send,
|
|
reply: None,
|
|
pong: false,
|
|
pong_payload: Vec::new(),
|
|
disconnected: false,
|
|
disconnect_reason: Vec::new(),
|
|
});
|
|
}
|
|
|
|
let duplicate = packet.reliable && self.was_received(packet.sequence);
|
|
if packet.reliable {
|
|
self.remember_received(packet.sequence);
|
|
}
|
|
if duplicate {
|
|
return Ok(CultNetRudpReceiveResult {
|
|
delivered: Vec::new(),
|
|
ready_to_send,
|
|
reply: None,
|
|
pong: false,
|
|
pong_payload: Vec::new(),
|
|
disconnected: false,
|
|
disconnect_reason: Vec::new(),
|
|
});
|
|
}
|
|
|
|
let mut delivered = Vec::new();
|
|
if let Some((frame, ordered, next_sequence)) = self.reassemble(packet)? {
|
|
if ordered {
|
|
self.ordered_held.insert(frame.sequence, frame);
|
|
} else if packet.sequenced {
|
|
if !self
|
|
.latest_sequenced_by_channel
|
|
.contains_key(&frame.channel_id)
|
|
&& self.latest_sequenced_by_channel.len() >= RUDP_MAX_TRACKED_CHANNELS
|
|
{
|
|
return Err(anyhow!("RUDP session has too many sequenced channels"));
|
|
}
|
|
let latest = self
|
|
.latest_sequenced_by_channel
|
|
.get(&frame.channel_id)
|
|
.copied();
|
|
let newest_sequence = next_sequence.saturating_sub(1);
|
|
if !latest.is_some_and(|latest| newest_sequence <= latest) {
|
|
self.latest_sequenced_by_channel
|
|
.insert(frame.channel_id.clone(), newest_sequence);
|
|
delivered.push(frame);
|
|
}
|
|
} else {
|
|
delivered.push(frame);
|
|
}
|
|
}
|
|
// Any reliable packet may have advanced the watermark, a fragment or an
|
|
// unordered frame as much as an ordered one, so the drain runs after all
|
|
// of them.
|
|
delivered.extend(self.drain_ordered()?);
|
|
Ok(CultNetRudpReceiveResult {
|
|
delivered,
|
|
ready_to_send,
|
|
reply: None,
|
|
pong: false,
|
|
pong_payload: Vec::new(),
|
|
disconnected: false,
|
|
disconnect_reason: Vec::new(),
|
|
})
|
|
}
|
|
|
|
pub fn create_ack(&mut self) -> CultNetRudpPacket {
|
|
let (ack, ack_mask) = self.ack_state();
|
|
CultNetRudpPacket {
|
|
packet_type: CultNetRudpPacketType::Ack,
|
|
connection_id: self.connection_id,
|
|
sequence: 0,
|
|
ack,
|
|
ack_mask,
|
|
channel_id: "control".to_string(),
|
|
reliable: false,
|
|
ordered: false,
|
|
sequenced: false,
|
|
fragment_id: 0,
|
|
fragment_index: 0,
|
|
fragment_count: 0,
|
|
payload: Vec::new(),
|
|
}
|
|
}
|
|
|
|
pub fn create_ack_for(&self, sequence: u32) -> CultNetRudpPacket {
|
|
CultNetRudpPacket {
|
|
packet_type: CultNetRudpPacketType::Ack,
|
|
connection_id: self.connection_id,
|
|
sequence: 0,
|
|
ack: sequence,
|
|
ack_mask: 0,
|
|
channel_id: "control".to_string(),
|
|
reliable: false,
|
|
ordered: false,
|
|
sequenced: false,
|
|
fragment_id: 0,
|
|
fragment_index: 0,
|
|
fragment_count: 0,
|
|
payload: Vec::new(),
|
|
}
|
|
}
|
|
|
|
/// The acknowledgement for a reliable packet `receive` just handled. What
|
|
/// `receive` refused is not acknowledged by name (the ack carries only what
|
|
/// was received), so its sender retransmits it.
|
|
pub fn create_ack_for_received(&mut self, sequence: u32) -> CultNetRudpPacket {
|
|
let (ack, _) = self.ack_state();
|
|
if !self.was_received(sequence) {
|
|
self.create_ack()
|
|
} else if ack >= sequence && ack - sequence <= 32 {
|
|
self.create_ack()
|
|
} else {
|
|
self.create_ack_for(sequence)
|
|
}
|
|
}
|
|
|
|
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.end_session();
|
|
self.create_packet(
|
|
CultNetRudpPacketType::Disconnect,
|
|
"control",
|
|
reason,
|
|
false,
|
|
false,
|
|
false,
|
|
)
|
|
}
|
|
|
|
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.end_session();
|
|
true
|
|
}
|
|
|
|
pub fn due_resends(&mut self, now_ms: u64) -> Vec<CultNetRudpPacket> {
|
|
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 {
|
|
pending.last_sent_at_ms = now_ms;
|
|
due.push(pending.packet.clone());
|
|
}
|
|
}
|
|
due.sort_by_key(|packet| packet.sequence);
|
|
due
|
|
}
|
|
|
|
/// A Connect unanswered for `RUDP_CONNECT_ATTEMPT_MS` is replaced, not
|
|
/// retransmitted further, by a Connect with the same payload and the
|
|
/// abandoned sequence plus the receive window less one. Nothing was ever
|
|
/// sent in an unanswered generation, so no sequence issued so far is owed.
|
|
/// The jump keeps a late copy of the abandoned Connect inside the new one's
|
|
/// stale window, so a server that took the new Connect answers the copy
|
|
/// with an Ack instead of restarting; and it leaves the stale window of
|
|
/// whatever generation the server holds, unless that generation sits
|
|
/// exactly at the jump, and then the next attempt leaves it. The first
|
|
/// Connect of a session is the only one drawn at random.
|
|
fn abandon_unanswered_connect(&mut self, now_ms: u64) -> Option<CultNetRudpPacket> {
|
|
if !self.awaiting_accept
|
|
|| now_ms.saturating_sub(self.connect_started_at_ms) < RUDP_CONNECT_ATTEMPT_MS
|
|
{
|
|
return None;
|
|
}
|
|
let abandoned = self.connect_sequence?;
|
|
self.next_sequence = abandoned
|
|
.saturating_add(RUDP_RECEIVED_SEQUENCE_WINDOW as u32 - 1)
|
|
.min(u32::MAX - 1);
|
|
let payload = self.connect_payload.clone();
|
|
self.create_connect(now_ms, payload).ok()
|
|
}
|
|
|
|
fn create_packet(
|
|
&mut self,
|
|
packet_type: CultNetRudpPacketType,
|
|
channel_id: &str,
|
|
payload: Vec<u8>,
|
|
reliable: bool,
|
|
ordered: bool,
|
|
sequenced: bool,
|
|
) -> CultNetRudpPacket {
|
|
self.create_packet_with_fragments(
|
|
packet_type,
|
|
channel_id,
|
|
payload,
|
|
reliable,
|
|
ordered,
|
|
sequenced,
|
|
0,
|
|
0,
|
|
0,
|
|
)
|
|
}
|
|
|
|
#[allow(clippy::too_many_arguments)]
|
|
fn create_packet_with_fragments(
|
|
&mut self,
|
|
packet_type: CultNetRudpPacketType,
|
|
channel_id: &str,
|
|
payload: Vec<u8>,
|
|
reliable: bool,
|
|
ordered: bool,
|
|
sequenced: bool,
|
|
fragment_id: u16,
|
|
fragment_index: u16,
|
|
fragment_count: u16,
|
|
) -> CultNetRudpPacket {
|
|
let sequence = if reliable {
|
|
let sequence = self.next_sequence;
|
|
self.next_sequence = self
|
|
.next_sequence
|
|
.saturating_add(1);
|
|
sequence
|
|
} else if sequenced {
|
|
let next = self
|
|
.next_sequenced_by_channel
|
|
.entry(channel_id.to_string())
|
|
.or_insert(1);
|
|
let sequence = *next;
|
|
*next = next.saturating_add(1);
|
|
sequence
|
|
} else {
|
|
0
|
|
};
|
|
let (ack, ack_mask) = self.ack_state();
|
|
CultNetRudpPacket {
|
|
packet_type,
|
|
connection_id: self.connection_id,
|
|
sequence,
|
|
ack,
|
|
ack_mask,
|
|
channel_id: channel_id.to_string(),
|
|
reliable,
|
|
ordered,
|
|
sequenced,
|
|
fragment_id,
|
|
fragment_index,
|
|
fragment_count,
|
|
payload,
|
|
}
|
|
}
|
|
|
|
fn track_reliable(
|
|
&mut self,
|
|
packet: CultNetRudpPacket,
|
|
now_ms: u64,
|
|
expires_at_ms: Option<u64>,
|
|
) {
|
|
self.pending_reliable.insert(
|
|
packet.sequence,
|
|
PendingReliablePacket {
|
|
packet,
|
|
last_sent_at_ms: now_ms,
|
|
expires_at_ms,
|
|
},
|
|
);
|
|
}
|
|
|
|
/// Drop pending and queued reliable packets past their deadline. The
|
|
/// deadline is fixed when the send is admitted, so time spent waiting in
|
|
/// the backlog counts against it exactly as time spent awaiting an ACK does.
|
|
fn purge_expired_reliable(&mut self, now_ms: u64) {
|
|
let before = self.pending_reliable.len() + self.queued_reliable.len();
|
|
self.pending_reliable
|
|
.retain(|_, pending| pending.expires_at_ms.is_none_or(|at| now_ms <= at));
|
|
self.queued_reliable
|
|
.retain(|(_, expires_at_ms)| expires_at_ms.is_none_or(|at| now_ms <= at));
|
|
let after = self.pending_reliable.len() + self.queued_reliable.len();
|
|
if after != before {
|
|
self.forget_acked_below_lowest();
|
|
}
|
|
self.reliable_packets_expired = self
|
|
.reliable_packets_expired
|
|
.saturating_add((before - after) as u64);
|
|
}
|
|
|
|
/// Whether a reliable packet may go on the wire now: the window has a slot,
|
|
/// and its sequence and the payload above the lowest unacked sequence stay
|
|
/// inside the flow window. With nothing pending, any packet is admissible.
|
|
fn window_admits(&self, sequence: u32, payload_len: usize) -> bool {
|
|
if self.pending_reliable.len() >= CULTNET_RUDP_RELIABLE_SEND_WINDOW_PACKETS {
|
|
return false;
|
|
}
|
|
let Some((&lowest, _)) = self.pending_reliable.first_key_value() else {
|
|
return true;
|
|
};
|
|
let pending_bytes: usize = self
|
|
.pending_reliable
|
|
.iter()
|
|
.filter(|(pending_sequence, _)| **pending_sequence > lowest)
|
|
.map(|(_, pending)| pending.packet.payload.len())
|
|
.sum();
|
|
let acked_bytes: usize = self.acked_above_lowest.values().sum();
|
|
let bytes_above = pending_bytes + acked_bytes;
|
|
sequence.saturating_sub(lowest) <= RUDP_FLOW_WINDOW_SEQUENCES
|
|
&& bytes_above + payload_len <= RUDP_FLOW_WINDOW_BYTES
|
|
}
|
|
|
|
fn admit_reliable_packets(
|
|
&mut self,
|
|
packets: Vec<CultNetRudpPacket>,
|
|
now_ms: u64,
|
|
expires_at_ms: Option<u64>,
|
|
) -> Vec<CultNetRudpPacket> {
|
|
let mut ready = Vec::new();
|
|
for packet in packets {
|
|
if self.queued_reliable.is_empty()
|
|
&& self.window_admits(packet.sequence, packet.payload.len())
|
|
{
|
|
self.track_reliable(packet.clone(), now_ms, expires_at_ms);
|
|
ready.push(packet);
|
|
} else {
|
|
self.queued_reliable.push_back((packet, expires_at_ms));
|
|
}
|
|
}
|
|
ready
|
|
}
|
|
|
|
fn promote_queued_reliable(&mut self, now_ms: u64) -> Vec<CultNetRudpPacket> {
|
|
let mut ready = Vec::new();
|
|
while self
|
|
.queued_reliable
|
|
.front()
|
|
.is_some_and(|(packet, _)| self.window_admits(packet.sequence, packet.payload.len()))
|
|
{
|
|
let Some((packet, expires_at_ms)) = self.queued_reliable.pop_front() else {
|
|
break;
|
|
};
|
|
self.track_reliable(packet.clone(), now_ms, expires_at_ms);
|
|
ready.push(packet);
|
|
}
|
|
ready
|
|
}
|
|
|
|
fn ensure_reliable_capacity(&self, packet_count: usize) -> Result<()> {
|
|
if packet_count == 0 {
|
|
return Ok(());
|
|
}
|
|
if let Some(limit) = self.max_pending_reliable_packets {
|
|
if self.outstanding_reliable_packet_count() + packet_count > limit {
|
|
return Err(anyhow!("RUDP reliable send queue is full"));
|
|
}
|
|
}
|
|
// Refuse before allocation rather than at it. A session that runs out of
|
|
// reliable sequence space must report it, not abort the process.
|
|
let required = u32::try_from(packet_count)
|
|
.ok()
|
|
.filter(|required| self.next_sequence.checked_add(*required).is_some());
|
|
if required.is_none() {
|
|
return Err(anyhow!("RUDP reliable sequence space is exhausted"));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn apply_acknowledgements(&mut self, packet: &CultNetRudpPacket) {
|
|
self.acknowledge(packet.ack);
|
|
for bit in 0..32 {
|
|
if (packet.ack_mask & (1_u32 << bit)) != 0 && packet.ack > bit {
|
|
self.acknowledge(packet.ack - bit - 1);
|
|
}
|
|
}
|
|
self.forget_acked_below_lowest();
|
|
}
|
|
|
|
fn acknowledge(&mut self, sequence: u32) {
|
|
if let Some(pending) = self.pending_reliable.remove(&sequence) {
|
|
self.acked_above_lowest
|
|
.insert(sequence, pending.packet.payload.len());
|
|
}
|
|
}
|
|
|
|
/// Acknowledged sizes stop counting once the lowest unacknowledged
|
|
/// sequence passes them, and all of them stop when nothing is unacknowledged.
|
|
fn forget_acked_below_lowest(&mut self) {
|
|
match self.pending_reliable.first_key_value() {
|
|
Some((&lowest, _)) => self.acked_above_lowest.retain(|sequence, _| *sequence > lowest),
|
|
None => self.acked_above_lowest.clear(),
|
|
}
|
|
}
|
|
|
|
/// The handshake's one act on the watermark: the peer's Connect or Accept
|
|
/// is the first sequence of the session, whatever else it has sent.
|
|
fn seed_received(&mut self, sequence: u32) {
|
|
self.received_through = Some(sequence);
|
|
self.remember_received(sequence);
|
|
}
|
|
|
|
fn remember_received(&mut self, sequence: u32) {
|
|
self.received_sequences.insert(sequence);
|
|
if let Some(mut through) = self.received_through {
|
|
while let Some(next) = through.checked_add(1) {
|
|
if !self.received_sequences.contains(&next) {
|
|
break;
|
|
}
|
|
through = next;
|
|
}
|
|
self.received_through = Some(through);
|
|
}
|
|
if self
|
|
.highest_received_sequence
|
|
.is_none_or(|highest| sequence > highest)
|
|
{
|
|
self.highest_received_sequence = Some(sequence);
|
|
}
|
|
if self.received_sequences.len() > RUDP_RECEIVED_SEQUENCE_WINDOW {
|
|
let keep_from = self
|
|
.highest_received_sequence
|
|
.unwrap_or(sequence)
|
|
.saturating_sub(RUDP_RECEIVED_SEQUENCE_WINDOW as u32 - 1);
|
|
self.received_sequences = self.received_sequences.split_off(&keep_from);
|
|
}
|
|
}
|
|
|
|
/// Whether `receive` has taken this reliable sequence: delivered, held, superseded or a duplicate. A packet
|
|
/// `receive` refused unremembered (too far ahead, or before the handshake) is not, and its sender resends it.
|
|
pub fn has_received(&self, sequence: u32) -> bool {
|
|
self.was_received(sequence)
|
|
}
|
|
|
|
/// 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) {
|
|
let ack = self.highest_received_sequence.unwrap_or(0);
|
|
let mut ack_mask = 0_u32;
|
|
for bit in 0..32 {
|
|
if ack > bit && self.received_sequences.contains(&(ack - bit - 1)) {
|
|
ack_mask |= 1_u32 << bit;
|
|
}
|
|
}
|
|
(ack, ack_mask)
|
|
}
|
|
|
|
fn reassemble(
|
|
&mut self,
|
|
packet: &CultNetRudpPacket,
|
|
) -> Result<Option<(CultNetRudpDeliveredFrame, bool, u32)>> {
|
|
if packet.fragment_count == 0 {
|
|
self.require_payload_size(&packet.channel_id, packet.payload.len())?;
|
|
return Ok(Some((
|
|
CultNetRudpDeliveredFrame {
|
|
channel_id: packet.channel_id.clone(),
|
|
payload: packet.payload.clone(),
|
|
sequence: packet.sequence,
|
|
},
|
|
packet.ordered,
|
|
packet.sequence + 1,
|
|
)));
|
|
}
|
|
if packet.fragment_id == 0 {
|
|
return Err(anyhow!(
|
|
"RUDP fragmented packet must have a non-zero fragment id"
|
|
));
|
|
}
|
|
if packet.fragment_index >= packet.fragment_count {
|
|
return Err(anyhow!(
|
|
"RUDP fragment index must be lower than fragment count"
|
|
));
|
|
}
|
|
|
|
let key = (packet.channel_id.clone(), packet.fragment_id);
|
|
if !self.fragment_buffers.contains_key(&key)
|
|
&& self.fragment_buffers.len() >= self.max_pending_fragment_sets
|
|
{
|
|
// A set that is still incomplete when the bound is reached has
|
|
// almost certainly lost a fragment; its siblings were delivered
|
|
// long ago. Drop the one untouched longest so the session keeps
|
|
// receiving. Erroring here made any lossy fragmenting channel a
|
|
// countdown to a dead receiver.
|
|
let stalest = self
|
|
.fragment_buffers
|
|
.iter()
|
|
.min_by_key(|(_, buffer)| buffer.last_touched)
|
|
.map(|(key, _)| key.clone())
|
|
.expect("bound reached implies a pending set exists");
|
|
self.fragment_buffers.remove(&stalest);
|
|
self.fragment_sets_evicted += 1;
|
|
}
|
|
let buffered_bytes = self
|
|
.fragment_buffers
|
|
.get(&key)
|
|
.map(|buffer| {
|
|
buffer
|
|
.payloads
|
|
.iter()
|
|
.filter(|(index, _)| **index != packet.fragment_index)
|
|
.map(|(_, payload)| payload.len())
|
|
.sum::<usize>()
|
|
})
|
|
.unwrap_or(0);
|
|
if let Err(error) = self.require_payload_size(&packet.channel_id, buffered_bytes + packet.payload.len()) {
|
|
self.fragment_buffers.remove(&key);
|
|
return Err(error);
|
|
}
|
|
let buffer = self
|
|
.fragment_buffers
|
|
.entry(key.clone())
|
|
.or_insert_with(|| FragmentBuffer {
|
|
channel_id: packet.channel_id.clone(),
|
|
ordered: packet.ordered,
|
|
fragment_count: packet.fragment_count,
|
|
payloads: BTreeMap::new(),
|
|
sequences: BTreeMap::new(),
|
|
last_touched: 0,
|
|
});
|
|
if buffer.fragment_count != packet.fragment_count || buffer.ordered != packet.ordered {
|
|
return Err(anyhow!(
|
|
"RUDP fragment metadata changed within a fragment set"
|
|
));
|
|
}
|
|
self.fragment_touches += 1;
|
|
buffer.last_touched = self.fragment_touches;
|
|
buffer
|
|
.payloads
|
|
.insert(packet.fragment_index, packet.payload.clone());
|
|
buffer
|
|
.sequences
|
|
.insert(packet.fragment_index, packet.sequence);
|
|
if buffer.payloads.len() < packet.fragment_count as usize {
|
|
return Ok(None);
|
|
}
|
|
|
|
let mut payload = Vec::new();
|
|
let mut sequences = Vec::new();
|
|
for index in 0..packet.fragment_count {
|
|
let Some(chunk) = buffer.payloads.get(&index) else {
|
|
return Ok(None);
|
|
};
|
|
let Some(sequence) = buffer.sequences.get(&index) else {
|
|
return Ok(None);
|
|
};
|
|
payload.extend_from_slice(chunk);
|
|
sequences.push(*sequence);
|
|
}
|
|
let channel_id = buffer.channel_id.clone();
|
|
let ordered = buffer.ordered;
|
|
self.fragment_buffers.remove(&key);
|
|
Ok(Some((
|
|
CultNetRudpDeliveredFrame {
|
|
channel_id,
|
|
payload,
|
|
sequence: *sequences.iter().min().unwrap(),
|
|
},
|
|
ordered,
|
|
sequences.iter().max().unwrap() + 1,
|
|
)))
|
|
}
|
|
|
|
/// The session's cap, tightened on the media channel to the ceiling every
|
|
/// media record is held to (`GAMECULT_MEDIA_MAX_WIRE_BYTES`), so media
|
|
/// reassembly never buffers more than a record may be.
|
|
fn require_payload_size(&self, channel_id: &str, payload_bytes: usize) -> Result<()> {
|
|
let limit = channel_payload_limit(channel_id, self.max_payload_bytes);
|
|
if limit.is_some_and(|limit| payload_bytes > limit) {
|
|
return Err(anyhow!("RUDP payload exceeds max_payload_bytes"));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Delivers, in sequence order, every held ordered frame whose first
|
|
/// sequence is at most one past the watermark, then bounds what is still
|
|
/// held. Ordered delivery has one owner: the watermark. A frame this call
|
|
/// does not deliver waits for the sequence below it, and nothing else
|
|
/// releases it.
|
|
fn drain_ordered(&mut self) -> Result<Vec<CultNetRudpDeliveredFrame>> {
|
|
let Some(through) = self.received_through else {
|
|
return Ok(Vec::new());
|
|
};
|
|
let still_held = match through.checked_add(1) {
|
|
Some(next) => self.ordered_held.split_off(&next.saturating_add(1)),
|
|
None => BTreeMap::new(),
|
|
};
|
|
let deliverable = std::mem::replace(&mut self.ordered_held, still_held);
|
|
if self.ordered_held.len() > RUDP_MAX_ORDERED_BUFFERED_FRAMES
|
|
|| self
|
|
.ordered_held
|
|
.values()
|
|
.map(|frame| frame.payload.len())
|
|
.sum::<usize>()
|
|
> RUDP_MAX_ORDERED_BUFFERED_BYTES
|
|
{
|
|
return Err(anyhow!("RUDP ordered hold buffer is full"));
|
|
}
|
|
let held_channels: BTreeSet<&str> = self
|
|
.ordered_held
|
|
.values()
|
|
.map(|frame| frame.channel_id.as_str())
|
|
.collect();
|
|
if held_channels.len() > RUDP_MAX_TRACKED_CHANNELS {
|
|
return Err(anyhow!("RUDP session has too many ordered channels"));
|
|
}
|
|
Ok(deliverable.into_values().collect())
|
|
}
|
|
|
|
fn allocate_fragment_id(&mut self) -> u16 {
|
|
let fragment_id = self.next_fragment_id;
|
|
// Wrap, never saturate: `saturating_add` parked every set after the
|
|
// 65,535th on one shared id, and the reassembler stitched them together.
|
|
self.next_fragment_id = self.next_fragment_id.wrapping_add(1);
|
|
if self.next_fragment_id == 0 {
|
|
self.next_fragment_id = 1;
|
|
}
|
|
fragment_id
|
|
}
|
|
|
|
fn require_connection(&self, packet: &CultNetRudpPacket) -> Result<()> {
|
|
if packet.connection_id != self.connection_id {
|
|
return Err(anyhow!(
|
|
"RUDP packet connection id {} does not match {}",
|
|
packet.connection_id,
|
|
self.connection_id
|
|
));
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum CultNetRudpSocketMode {
|
|
Client,
|
|
Server,
|
|
}
|
|
|
|
pub struct CultNetRudpSocketTransportOptions {
|
|
pub runtime_id: String,
|
|
pub socket: UdpSocket,
|
|
pub mode: CultNetRudpSocketMode,
|
|
pub remote_addr: Option<SocketAddr>,
|
|
pub connection_id: u32,
|
|
pub initial_sequence: Option<u32>,
|
|
pub resend_delay_ms: u64,
|
|
pub transport_id: Option<String>,
|
|
pub max_payload_bytes: Option<u32>,
|
|
pub max_fragment_bytes: Option<u32>,
|
|
pub max_pending_reliable_packets: Option<u32>,
|
|
pub reconnect_policy: Option<CultNetReconnectPolicy>,
|
|
pub media_reliable_expire_after_ms: Option<u64>,
|
|
/// `None` means the historical default, `Reliable`.
|
|
pub media_delivery: Option<CultNetTransportDelivery>,
|
|
}
|
|
|
|
impl CultNetRudpSocketTransportOptions {
|
|
pub fn client(
|
|
runtime_id: impl Into<String>,
|
|
socket: UdpSocket,
|
|
remote_addr: SocketAddr,
|
|
connection_id: u32,
|
|
) -> Self {
|
|
Self {
|
|
media_reliable_expire_after_ms: Some(DEFAULT_MEDIA_RELIABLE_EXPIRE_AFTER_MS),
|
|
media_delivery: None,
|
|
runtime_id: runtime_id.into(),
|
|
socket,
|
|
mode: CultNetRudpSocketMode::Client,
|
|
remote_addr: Some(remote_addr),
|
|
connection_id,
|
|
initial_sequence: None,
|
|
resend_delay_ms: 250,
|
|
transport_id: None,
|
|
max_payload_bytes: None,
|
|
max_fragment_bytes: None,
|
|
max_pending_reliable_packets: None,
|
|
reconnect_policy: None,
|
|
}
|
|
}
|
|
|
|
pub fn server(runtime_id: impl Into<String>, socket: UdpSocket, connection_id: u32) -> Self {
|
|
Self {
|
|
media_reliable_expire_after_ms: Some(DEFAULT_MEDIA_RELIABLE_EXPIRE_AFTER_MS),
|
|
media_delivery: None,
|
|
runtime_id: runtime_id.into(),
|
|
socket,
|
|
mode: CultNetRudpSocketMode::Server,
|
|
remote_addr: None,
|
|
connection_id,
|
|
initial_sequence: None,
|
|
resend_delay_ms: 250,
|
|
transport_id: None,
|
|
max_payload_bytes: None,
|
|
max_fragment_bytes: None,
|
|
max_pending_reliable_packets: None,
|
|
reconnect_policy: None,
|
|
}
|
|
}
|
|
}
|
|
|
|
pub struct CultNetRudpSocketTransportConnection {
|
|
socket: UdpSocket,
|
|
session: CultNetRudpSession,
|
|
mode: CultNetRudpSocketMode,
|
|
remote_addr: Option<SocketAddr>,
|
|
pub profile: CultNetTransportProfile,
|
|
stats: CultNetTransportStats,
|
|
delivered_frames: VecDeque<CultNetTransportFrame>,
|
|
max_fragment_bytes: Option<usize>,
|
|
disconnect_reason: Option<Vec<u8>>,
|
|
pong_payloads: VecDeque<Vec<u8>>,
|
|
}
|
|
|
|
pub struct CultNetRudpServerHubOptions {
|
|
pub runtime_id: String,
|
|
pub socket: UdpSocket,
|
|
pub connection_id: u32,
|
|
pub initial_sequence: Option<u32>,
|
|
pub resend_delay_ms: u64,
|
|
pub transport_id: Option<String>,
|
|
pub max_payload_bytes: Option<u32>,
|
|
pub max_fragment_bytes: Option<u32>,
|
|
pub max_pending_reliable_packets: Option<u32>,
|
|
pub max_peers: usize,
|
|
pub media_reliable_expire_after_ms: Option<u64>,
|
|
/// `None` means the historical default, `Reliable`.
|
|
pub media_delivery: Option<CultNetTransportDelivery>,
|
|
}
|
|
|
|
impl CultNetRudpServerHubOptions {
|
|
pub fn new(runtime_id: impl Into<String>, socket: UdpSocket, connection_id: u32) -> Self {
|
|
Self {
|
|
media_reliable_expire_after_ms: Some(DEFAULT_MEDIA_RELIABLE_EXPIRE_AFTER_MS),
|
|
media_delivery: None,
|
|
runtime_id: runtime_id.into(),
|
|
socket,
|
|
connection_id,
|
|
initial_sequence: None,
|
|
resend_delay_ms: 250,
|
|
transport_id: None,
|
|
max_payload_bytes: None,
|
|
max_fragment_bytes: None,
|
|
max_pending_reliable_packets: None,
|
|
max_peers: 256,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub struct CultNetRudpServerSessionContext {
|
|
pub remote_addr: SocketAddr,
|
|
pub connection_id: u32,
|
|
/// Server-minted generation used to fence work from an older session at
|
|
/// the same UDP endpoint.
|
|
pub session_generation: u64,
|
|
/// Exact bytes supplied by the peer's most recently accepted Connect packet.
|
|
/// CultNet does not interpret these bytes; higher layers may use them as
|
|
/// transport evidence when making their own authorization decision.
|
|
pub connect_payload: Vec<u8>,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub enum CultNetRudpServerEvent {
|
|
Connected {
|
|
session: CultNetRudpServerSessionContext,
|
|
},
|
|
Frame {
|
|
session: CultNetRudpServerSessionContext,
|
|
frame: CultNetTransportFrame,
|
|
},
|
|
Pong {
|
|
session: CultNetRudpServerSessionContext,
|
|
payload: Vec<u8>,
|
|
},
|
|
Disconnected {
|
|
session: CultNetRudpServerSessionContext,
|
|
reason: Vec<u8>,
|
|
},
|
|
}
|
|
|
|
struct CultNetRudpServerPeer {
|
|
session: CultNetRudpSession,
|
|
context: CultNetRudpServerSessionContext,
|
|
}
|
|
|
|
/// One UDP listener with an independent reliable session for every remote peer.
|
|
///
|
|
/// The hub owns packet/session mechanics only. Registration, leases, commands,
|
|
/// and all other application policy belong to the service using the hub.
|
|
pub struct CultNetRudpServerHub {
|
|
socket: UdpSocket,
|
|
connection_id: u32,
|
|
initial_sequence: Option<u32>,
|
|
resend_delay_ms: u64,
|
|
max_pending_reliable_packets: Option<usize>,
|
|
max_payload_bytes: usize,
|
|
max_fragment_bytes: Option<usize>,
|
|
max_peers: usize,
|
|
next_session_generation: u64,
|
|
peers: BTreeMap<SocketAddr, CultNetRudpServerPeer>,
|
|
pending_events: VecDeque<CultNetRudpServerEvent>,
|
|
pub profile: CultNetTransportProfile,
|
|
stats: CultNetTransportStats,
|
|
/// Peers whose every datagram fails to send, standing in for an unroutable
|
|
/// or full path that a loopback peer cannot be made to have.
|
|
#[cfg(test)]
|
|
failing_peers: BTreeSet<SocketAddr>,
|
|
/// Peers whose next datagram after this many fails permanently, once.
|
|
#[cfg(test)]
|
|
unsendable_after: BTreeMap<SocketAddr, usize>,
|
|
}
|
|
|
|
impl CultNetRudpServerHub {
|
|
pub fn new(options: CultNetRudpServerHubOptions) -> Result<Self> {
|
|
validate_rudp_session_limits(
|
|
options.initial_sequence,
|
|
options.max_pending_reliable_packets,
|
|
)?;
|
|
let local_addr = options.socket.local_addr()?;
|
|
if options.max_peers == 0 {
|
|
return Err(anyhow!(
|
|
"RUDP server hub max_peers must be greater than zero"
|
|
));
|
|
}
|
|
let max_payload_bytes = options
|
|
.max_payload_bytes
|
|
.or(Some(CULTNET_RUDP_DEFAULT_MAX_PAYLOAD_BYTES as u32));
|
|
let profile = create_rudp_transport_profile(
|
|
options.runtime_id,
|
|
RudpTransportProfileOptions {
|
|
media_reliable_expire_after_ms: options.media_reliable_expire_after_ms,
|
|
media_delivery: options.media_delivery,
|
|
transport_id: options.transport_id,
|
|
host: Some(local_addr.ip().to_string()),
|
|
port: Some(local_addr.port()),
|
|
max_payload_bytes,
|
|
max_fragment_bytes: options.max_fragment_bytes,
|
|
max_pending_reliable_packets: options.max_pending_reliable_packets,
|
|
reconnect_policy: None,
|
|
},
|
|
);
|
|
Ok(Self {
|
|
socket: options.socket,
|
|
connection_id: options.connection_id,
|
|
initial_sequence: options.initial_sequence,
|
|
resend_delay_ms: options.resend_delay_ms,
|
|
max_pending_reliable_packets: options
|
|
.max_pending_reliable_packets
|
|
.map(|value| value as usize),
|
|
max_payload_bytes: max_payload_bytes.expect("RUDP hub has an effective payload limit")
|
|
as usize,
|
|
max_fragment_bytes: options.max_fragment_bytes.map(|value| value as usize),
|
|
max_peers: options.max_peers,
|
|
next_session_generation: 1,
|
|
peers: BTreeMap::new(),
|
|
pending_events: VecDeque::new(),
|
|
profile,
|
|
stats: CultNetTransportStats::default(),
|
|
#[cfg(test)]
|
|
failing_peers: BTreeSet::new(),
|
|
#[cfg(test)]
|
|
unsendable_after: BTreeMap::new(),
|
|
})
|
|
}
|
|
|
|
pub fn local_addr(&self) -> Result<SocketAddr> {
|
|
Ok(self.socket.local_addr()?)
|
|
}
|
|
|
|
pub fn stats(&self) -> CultNetTransportStats {
|
|
let mut stats = self.stats.clone();
|
|
stats.reliable_packets_expired = self
|
|
.peers
|
|
.values()
|
|
.map(|peer| peer.session.reliable_packets_expired())
|
|
.fold(0_u64, |total, expired| total.saturating_add(expired));
|
|
stats.fragment_sets_evicted = self
|
|
.peers
|
|
.values()
|
|
.map(|peer| peer.session.fragment_sets_evicted())
|
|
.fold(0_u64, |total, evicted| total.saturating_add(evicted));
|
|
stats
|
|
}
|
|
|
|
pub fn sessions(&self) -> Vec<CultNetRudpServerSessionContext> {
|
|
self.peers
|
|
.values()
|
|
.map(|peer| peer.context.clone())
|
|
.collect()
|
|
}
|
|
|
|
pub fn session(&self, remote_addr: SocketAddr) -> Option<&CultNetRudpServerSessionContext> {
|
|
self.peers.get(&remote_addr).map(|peer| &peer.context)
|
|
}
|
|
|
|
pub fn send(
|
|
&mut self,
|
|
session: &CultNetRudpServerSessionContext,
|
|
channel_id: &str,
|
|
payload: Vec<u8>,
|
|
) -> Result<()> {
|
|
let remote_addr = session.remote_addr;
|
|
let (first_sequence, packets) = {
|
|
let peer = self
|
|
.peers
|
|
.get_mut(&remote_addr)
|
|
.ok_or_else(|| anyhow!("Unknown RUDP server peer {remote_addr}"))?;
|
|
if peer.context.session_generation != session.session_generation {
|
|
return Err(anyhow!(
|
|
"RUDP server session generation {} is no longer active",
|
|
session.session_generation
|
|
));
|
|
}
|
|
let first_sequence = peer.session.next_sequence;
|
|
let packets = peer.session.send_many(
|
|
channel_id,
|
|
payload,
|
|
channel_send_options(
|
|
channel_id,
|
|
now_ms(),
|
|
channel_reliable_expire_after_ms(&self.profile, channel_id),
|
|
channel_delivery(&self.profile, channel_id),
|
|
),
|
|
self.max_fragment_bytes,
|
|
)?;
|
|
(first_sequence, packets)
|
|
};
|
|
for (index, packet) in packets.iter().enumerate() {
|
|
let Some(error) = self.send_packet(remote_addr, packet)? else {
|
|
continue;
|
|
};
|
|
// A caller-directed send that can never succeed is the caller's
|
|
// error and queues nothing. Only when earlier fragments are already
|
|
// on the wire has the peer seen part of it, and then the session
|
|
// cannot be kept.
|
|
if index == 0 {
|
|
if let Some(peer) = self.peers.get_mut(&remote_addr) {
|
|
peer.session.withdraw_send(first_sequence);
|
|
}
|
|
} else {
|
|
self.end_unsendable_peer(remote_addr, &error)?;
|
|
}
|
|
return Err(error.into());
|
|
}
|
|
self.stats.frames_sent += 1;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn send_schema_message(
|
|
&mut self,
|
|
session: &CultNetRudpServerSessionContext,
|
|
message: &CultNetMessage,
|
|
) -> Result<()> {
|
|
let payload = encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0)?;
|
|
self.send(session, "schema", payload)
|
|
}
|
|
|
|
pub fn disconnect(
|
|
&mut self,
|
|
session: &CultNetRudpServerSessionContext,
|
|
reason: Vec<u8>,
|
|
) -> Result<bool> {
|
|
let Some(peer) = self.peers.get(&session.remote_addr) else {
|
|
return Ok(false);
|
|
};
|
|
if peer.context.session_generation != session.session_generation {
|
|
return Ok(false);
|
|
}
|
|
let mut peer = self
|
|
.peers
|
|
.remove(&session.remote_addr)
|
|
.expect("validated RUDP peer exists");
|
|
let packet = peer.session.create_disconnect(reason);
|
|
if let Some(error) = self.send_packet(session.remote_addr, &packet)? {
|
|
return Err(error.into());
|
|
}
|
|
Ok(true)
|
|
}
|
|
|
|
/// The next event, or `None` only when nothing is waiting on the socket.
|
|
///
|
|
/// Packets that carry no event for the caller — acknowledgements, pings,
|
|
/// a repeated Connect, a fragment that completes nothing yet — are
|
|
/// consumed here and reading continues. Returning `None` after one of
|
|
/// those made a caller that polls once per send fall behind its own
|
|
/// peers' acknowledgements, and a reliable channel then resent everything.
|
|
pub fn receive_event_once(&mut self) -> Result<Option<CultNetRudpServerEvent>> {
|
|
loop {
|
|
if let Some(event) = self.pending_events.pop_front() {
|
|
return Ok(Some(event));
|
|
}
|
|
if !self.receive_packet_once()? {
|
|
return Ok(None);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Reads one datagram and applies it. `false` when the socket is empty.
|
|
fn receive_packet_once(&mut self) -> Result<bool> {
|
|
let mut wire = vec![0_u8; 65_535];
|
|
let (received, remote_addr) = match self.socket.recv_from(&mut wire) {
|
|
Ok(value) => value,
|
|
Err(error)
|
|
if error.kind() == ErrorKind::WouldBlock
|
|
|| error.kind() == ErrorKind::TimedOut
|
|
|| error.kind() == ErrorKind::ConnectionReset =>
|
|
{
|
|
return Ok(false);
|
|
}
|
|
Err(error) => return Err(error.into()),
|
|
};
|
|
wire.truncate(received);
|
|
self.stats.bytes_received += received as u64;
|
|
// What a datagram carries is the sender's business, not a fault of this
|
|
// process: a malformed frame, another session's id and a sender no
|
|
// Connect admitted are dropped and counted. Only the socket ends a loop.
|
|
let Ok(packet) = decode_rudp_packet(&wire) else {
|
|
self.stats.packets_dropped += 1;
|
|
return Ok(true);
|
|
};
|
|
if packet.connection_id != self.connection_id {
|
|
self.stats.packets_dropped += 1;
|
|
return Ok(true);
|
|
}
|
|
|
|
if packet.packet_type == CultNetRudpPacketType::Connect {
|
|
if let Some(peer) = self.peers.get_mut(&remote_addr)
|
|
&& peer.session.connect_repeats(&packet)
|
|
{
|
|
let Ok(reply) = peer.session.accept_connect(&packet, now_ms(), Vec::new()) else {
|
|
self.end_refusing_peer(remote_addr)?;
|
|
return Ok(true);
|
|
};
|
|
self.send_in_poll(remote_addr, &reply)?;
|
|
return Ok(true);
|
|
}
|
|
if !self.peers.contains_key(&remote_addr) && self.peers.len() >= self.max_peers {
|
|
self.stats.packets_dropped += 1;
|
|
return Ok(true);
|
|
}
|
|
let mut session = CultNetRudpSession::new(CultNetRudpSessionOptions {
|
|
connection_id: self.connection_id,
|
|
initial_sequence: self.initial_sequence,
|
|
resend_delay_ms: self.resend_delay_ms,
|
|
max_pending_reliable_packets: self.max_pending_reliable_packets,
|
|
});
|
|
session.set_max_payload_bytes(Some(self.max_payload_bytes));
|
|
let generation = self.next_session_generation;
|
|
self.next_session_generation = self
|
|
.next_session_generation
|
|
.checked_add(1)
|
|
.ok_or_else(|| anyhow!("RUDP server session generation exhausted"))?;
|
|
let context = CultNetRudpServerSessionContext {
|
|
remote_addr,
|
|
connection_id: packet.connection_id,
|
|
session_generation: generation,
|
|
connect_payload: packet.payload.clone(),
|
|
};
|
|
let Ok(accept) = session.accept_connect(&packet, now_ms(), Vec::new()) else {
|
|
self.stats.packets_dropped += 1;
|
|
return Ok(true);
|
|
};
|
|
if self.send_packet(remote_addr, &accept)?.is_some() {
|
|
// The peer cannot be answered, so no session starts.
|
|
self.stats.packets_dropped += 1;
|
|
return Ok(true);
|
|
}
|
|
let replaced = self.peers.insert(
|
|
remote_addr,
|
|
CultNetRudpServerPeer {
|
|
session,
|
|
context: context.clone(),
|
|
},
|
|
);
|
|
if let Some(replaced) = replaced {
|
|
self.pending_events
|
|
.push_back(CultNetRudpServerEvent::Disconnected {
|
|
session: replaced.context,
|
|
reason: b"replaced by a new Connect generation".to_vec(),
|
|
});
|
|
}
|
|
self.pending_events
|
|
.push_back(CultNetRudpServerEvent::Connected { session: context });
|
|
return Ok(true);
|
|
}
|
|
|
|
let Some(peer) = self.peers.get_mut(&remote_addr) else {
|
|
self.stats.packets_dropped += 1;
|
|
return Ok(true);
|
|
};
|
|
let Ok(result) = peer.session.receive(&packet, now_ms()) else {
|
|
self.end_refusing_peer(remote_addr)?;
|
|
return Ok(true);
|
|
};
|
|
let context = peer.context.clone();
|
|
let ack = if packet.reliable {
|
|
Some(peer.session.create_ack_for_received(packet.sequence))
|
|
} else {
|
|
None
|
|
};
|
|
let mut unsendable = None;
|
|
for packet in result
|
|
.reply
|
|
.iter()
|
|
.chain(&result.ready_to_send)
|
|
.chain(ack.iter())
|
|
{
|
|
unsendable = self.send_packet(remote_addr, packet)?;
|
|
if unsendable.is_some() {
|
|
break;
|
|
}
|
|
}
|
|
if result.pong {
|
|
self.pending_events.push_back(CultNetRudpServerEvent::Pong {
|
|
session: context.clone(),
|
|
payload: result.pong_payload,
|
|
});
|
|
}
|
|
for delivered in result.delivered {
|
|
self.stats.frames_received += 1;
|
|
self.pending_events
|
|
.push_back(CultNetRudpServerEvent::Frame {
|
|
session: context.clone(),
|
|
frame: CultNetTransportFrame {
|
|
channel_id: delivered.channel_id,
|
|
payload: delivered.payload,
|
|
},
|
|
});
|
|
}
|
|
if result.disconnected {
|
|
self.pending_events
|
|
.push_back(CultNetRudpServerEvent::Disconnected {
|
|
session: context,
|
|
reason: result.disconnect_reason,
|
|
});
|
|
self.peers.remove(&remote_addr);
|
|
} else if let Some(error) = unsendable {
|
|
self.end_unsendable_peer(remote_addr, &error)?;
|
|
}
|
|
Ok(true)
|
|
}
|
|
|
|
/// An admitted peer sent a packet its session refuses. `receive` has
|
|
/// already recorded the packet's reliable sequence, so the session cannot be
|
|
/// kept: a retransmit would be acknowledged and the frame silently lost.
|
|
/// The session ends, the peer is told, and the caller sees `Disconnected`.
|
|
fn end_refusing_peer(&mut self, remote_addr: SocketAddr) -> Result<()> {
|
|
self.stats.packets_dropped += 1;
|
|
let Some(mut peer) = self.peers.remove(&remote_addr) else {
|
|
return Ok(());
|
|
};
|
|
let goodbye = peer.session.end_refused_session();
|
|
self.pending_events
|
|
.push_back(CultNetRudpServerEvent::Disconnected {
|
|
session: peer.context,
|
|
reason: goodbye.payload.clone(),
|
|
});
|
|
self.send_packet(remote_addr, &goodbye)?;
|
|
Ok(())
|
|
}
|
|
|
|
/// An admitted peer owes a packet that can never be sent as built. Inside a
|
|
/// poll that ends the peer's session, never the poll: the peer is told, and
|
|
/// the caller sees `Disconnected` with a reason that names the error.
|
|
fn end_unsendable_peer(
|
|
&mut self,
|
|
remote_addr: SocketAddr,
|
|
error: &std::io::Error,
|
|
) -> Result<()> {
|
|
let Some(mut peer) = self.peers.remove(&remote_addr) else {
|
|
return Ok(());
|
|
};
|
|
let goodbye = peer.session.end_unsendable_session(error);
|
|
self.pending_events
|
|
.push_back(CultNetRudpServerEvent::Disconnected {
|
|
session: peer.context,
|
|
reason: goodbye.payload.clone(),
|
|
});
|
|
self.send_packet(remote_addr, &goodbye)?;
|
|
Ok(())
|
|
}
|
|
|
|
/// A send inside a poll: a permanent failure ends that peer's session.
|
|
fn send_in_poll(&mut self, remote_addr: SocketAddr, packet: &CultNetRudpPacket) -> Result<()> {
|
|
if let Some(error) = self.send_packet(remote_addr, packet)? {
|
|
self.end_unsendable_peer(remote_addr, &error)?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub fn poll_resends(&mut self) -> Result<()> {
|
|
let now = now_ms();
|
|
let mut packets = Vec::new();
|
|
for (remote_addr, peer) in &mut self.peers {
|
|
packets.extend(
|
|
peer.session
|
|
.due_resends(now)
|
|
.into_iter()
|
|
.map(|packet| (*remote_addr, packet)),
|
|
);
|
|
}
|
|
for (remote_addr, packet) in packets {
|
|
// A peer ended earlier in this loop has nothing left to resend.
|
|
if self.peers.contains_key(&remote_addr) {
|
|
self.send_in_poll(remote_addr, &packet)?;
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub fn remove_timed_out_sessions(
|
|
&mut self,
|
|
timeout_ms: u64,
|
|
) -> Vec<CultNetRudpServerSessionContext> {
|
|
let now = now_ms();
|
|
let timed_out = self
|
|
.peers
|
|
.iter_mut()
|
|
.filter_map(|(remote_addr, peer)| {
|
|
peer.session
|
|
.check_timeout(now, timeout_ms)
|
|
.then_some((*remote_addr, peer.context.clone()))
|
|
})
|
|
.collect::<Vec<_>>();
|
|
for (remote_addr, _) in &timed_out {
|
|
self.peers.remove(remote_addr);
|
|
}
|
|
timed_out.into_iter().map(|(_, context)| context).collect()
|
|
}
|
|
|
|
/// A transient send failure is that peer's lost datagram: counted, never an
|
|
/// error. A reliable packet stays pending and is resent; an unreliable one
|
|
/// was allowed to be lost. A permanent failure (`is_permanent_send_error`)
|
|
/// is returned as `Some`: the datagram can never be sent as built, and the
|
|
/// caller decides between refusing the send and ending the peer's session.
|
|
/// Only an encode failure, the hub's own bug, is an error.
|
|
fn send_packet(
|
|
&mut self,
|
|
remote_addr: SocketAddr,
|
|
packet: &CultNetRudpPacket,
|
|
) -> Result<Option<std::io::Error>> {
|
|
let wire = encode_rudp_packet(packet)?;
|
|
match self.send_datagram(&wire, remote_addr) {
|
|
Ok(sent) => self.stats.bytes_sent += sent as u64,
|
|
Err(error) if is_permanent_send_error(&error) => return Ok(Some(error)),
|
|
Err(_) => self.stats.send_failures += 1,
|
|
}
|
|
Ok(None)
|
|
}
|
|
|
|
fn send_datagram(&mut self, wire: &[u8], remote_addr: SocketAddr) -> std::io::Result<usize> {
|
|
#[cfg(test)]
|
|
{
|
|
match self.unsendable_after.get(&remote_addr).copied() {
|
|
Some(0) => {
|
|
self.unsendable_after.remove(&remote_addr);
|
|
return Err(std::io::Error::from(ErrorKind::InvalidInput));
|
|
}
|
|
Some(remaining) => {
|
|
self.unsendable_after.insert(remote_addr, remaining - 1);
|
|
}
|
|
None => {}
|
|
}
|
|
if self.failing_peers.contains(&remote_addr) {
|
|
return Err(std::io::Error::other("injected send failure"));
|
|
}
|
|
}
|
|
self.socket.send_to(wire, remote_addr)
|
|
}
|
|
}
|
|
|
|
impl CultNetRudpSocketTransportConnection {
|
|
pub fn new(options: CultNetRudpSocketTransportOptions) -> Result<Self> {
|
|
validate_rudp_session_limits(
|
|
options.initial_sequence,
|
|
options.max_pending_reliable_packets,
|
|
)?;
|
|
let local_addr = options.socket.local_addr()?;
|
|
let max_payload_bytes = options
|
|
.max_payload_bytes
|
|
.or(Some(CULTNET_RUDP_DEFAULT_MAX_PAYLOAD_BYTES as u32));
|
|
let profile = create_rudp_transport_profile(
|
|
options.runtime_id,
|
|
RudpTransportProfileOptions {
|
|
media_reliable_expire_after_ms: options.media_reliable_expire_after_ms,
|
|
media_delivery: options.media_delivery,
|
|
transport_id: options.transport_id,
|
|
host: Some(local_addr.ip().to_string()),
|
|
port: Some(local_addr.port()),
|
|
max_payload_bytes,
|
|
max_fragment_bytes: options.max_fragment_bytes,
|
|
max_pending_reliable_packets: options.max_pending_reliable_packets,
|
|
reconnect_policy: options.reconnect_policy,
|
|
},
|
|
);
|
|
let max_pending_reliable_packets = options
|
|
.max_pending_reliable_packets
|
|
.map(|value| value as usize);
|
|
let mut session = CultNetRudpSession::new(CultNetRudpSessionOptions {
|
|
connection_id: options.connection_id,
|
|
initial_sequence: options.initial_sequence,
|
|
resend_delay_ms: options.resend_delay_ms,
|
|
max_pending_reliable_packets,
|
|
});
|
|
session.set_max_payload_bytes(max_payload_bytes.map(|value| value as usize));
|
|
Ok(Self {
|
|
socket: options.socket,
|
|
session,
|
|
mode: options.mode,
|
|
remote_addr: options.remote_addr,
|
|
profile,
|
|
stats: CultNetTransportStats::default(),
|
|
delivered_frames: VecDeque::new(),
|
|
max_fragment_bytes: options.max_fragment_bytes.map(|value| value as usize),
|
|
disconnect_reason: None,
|
|
pong_payloads: VecDeque::new(),
|
|
})
|
|
}
|
|
|
|
pub fn connected(&self) -> bool {
|
|
self.session.connected()
|
|
}
|
|
|
|
pub fn stats(&self) -> CultNetTransportStats {
|
|
let mut stats = self.stats.clone();
|
|
stats.reliable_packets_expired = self.session.reliable_packets_expired();
|
|
stats.fragment_sets_evicted = self.session.fragment_sets_evicted();
|
|
stats
|
|
}
|
|
|
|
pub fn disconnect_reason(&self) -> Option<&[u8]> {
|
|
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!(
|
|
"Only a client RUDP socket transport can initiate connect"
|
|
));
|
|
}
|
|
let packet = self.session.create_connect(now_ms(), payload)?;
|
|
self.disconnect_reason = None;
|
|
self.send_packet(&packet)
|
|
}
|
|
|
|
/// Fire-and-forget: an ack or a return is not admission; read the result frame.
|
|
pub fn send(&mut self, channel_id: &str, payload: Vec<u8>) -> Result<()> {
|
|
let options =
|
|
channel_send_options(
|
|
channel_id,
|
|
now_ms(),
|
|
channel_reliable_expire_after_ms(&self.profile, channel_id),
|
|
channel_delivery(&self.profile, channel_id),
|
|
);
|
|
let packets =
|
|
self.session
|
|
.send_many(channel_id, payload, options, self.max_fragment_bytes)?;
|
|
self.send_data_packets(&packets)?;
|
|
self.stats.frames_sent += 1;
|
|
Ok(())
|
|
}
|
|
|
|
/// Sends one frame on a reliable channel whose packets cannot expire and
|
|
/// returns the transport receipt used to observe its exact acknowledgement.
|
|
///
|
|
/// Fire-and-forget: an ack or a return is not admission; read the result frame.
|
|
pub fn send_reliable(
|
|
&mut self,
|
|
channel_id: &str,
|
|
payload: Vec<u8>,
|
|
) -> Result<CultNetRudpReliableSendReceipt> {
|
|
let options =
|
|
channel_send_options(
|
|
channel_id,
|
|
now_ms(),
|
|
channel_reliable_expire_after_ms(&self.profile, channel_id),
|
|
channel_delivery(&self.profile, channel_id),
|
|
);
|
|
// This lineage has no reliable-expiry concept, so every reliable channel is
|
|
// already non-expiring. Restore the expiry half of this guard if one is added.
|
|
if !options.reliable {
|
|
return Err(anyhow!(
|
|
"RUDP acknowledgement receipts require a non-expiring reliable channel"
|
|
));
|
|
}
|
|
let packets =
|
|
self.session
|
|
.send_many(channel_id, payload, options, self.max_fragment_bytes)?;
|
|
self.send_data_packets(&packets)?;
|
|
let receipt = self.session.non_expiring_reliable_receipt(&packets)?;
|
|
self.stats.frames_sent += 1;
|
|
Ok(receipt)
|
|
}
|
|
|
|
pub fn reliable_send_status(
|
|
&self,
|
|
receipt: &CultNetRudpReliableSendReceipt,
|
|
) -> CultNetRudpReliableSendStatus {
|
|
self.session.reliable_send_status(receipt)
|
|
}
|
|
|
|
fn send_data_packets(&mut self, packets: &[CultNetRudpPacket]) -> Result<()> {
|
|
let fragmented = packets.len() > 1;
|
|
for (index, packet) in packets.iter().enumerate() {
|
|
self.send_packet(packet)?;
|
|
if fragmented && (index + 1) % 16 == 0 {
|
|
thread::sleep(Duration::from_millis(1));
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub fn send_schema_message(&mut self, message: &CultNetMessage) -> Result<()> {
|
|
let payload = encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0)?;
|
|
self.send("schema", payload)
|
|
}
|
|
|
|
pub fn receive_schema_message_once(&mut self) -> Result<Option<CultNetMessage>> {
|
|
let Some(frame) = self.receive_once()? else {
|
|
return Ok(None);
|
|
};
|
|
if frame.channel_id != "schema" {
|
|
return Err(anyhow!(
|
|
"Expected RUDP schema frame, received channel {}",
|
|
frame.channel_id
|
|
));
|
|
}
|
|
Ok(Some(decode_cultnet_message_from_slice(
|
|
&frame.payload,
|
|
CultNetWireContract::CultNetSchemaV0,
|
|
)?))
|
|
}
|
|
|
|
pub fn disconnect(&mut self, reason: Vec<u8>) -> Result<()> {
|
|
let packet = self.session.create_disconnect(reason);
|
|
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 {
|
|
let timed_out = self.session.check_timeout(now_ms(), timeout_ms);
|
|
if timed_out {
|
|
self.disconnect_reason = Some(SESSION_TIMED_OUT_REASON.to_vec());
|
|
}
|
|
timed_out
|
|
}
|
|
|
|
pub fn pending_reliable_packet_count(&self) -> usize {
|
|
self.session.pending_reliable_sequences().len()
|
|
}
|
|
|
|
pub fn outstanding_reliable_packet_count(&self) -> usize {
|
|
self.session.outstanding_reliable_packet_count()
|
|
}
|
|
|
|
/// Waits until every reliable write is acknowledged by the transport.
|
|
///
|
|
/// Fire-and-forget: an ack or a return is not admission; read the result frame.
|
|
pub fn flush_reliable(&mut self, timeout: Duration) -> Result<()> {
|
|
let original_timeout = self.socket.read_timeout()?;
|
|
let poll_timeout = original_timeout
|
|
.map(|configured| configured.min(Duration::from_millis(10)))
|
|
.unwrap_or(Duration::from_millis(10));
|
|
self.socket.set_read_timeout(Some(poll_timeout))?;
|
|
|
|
let deadline = Instant::now() + timeout;
|
|
// A flush belongs to the generation it started in: whatever ends that
|
|
// generation, and whatever begins after it, the writes being waited on
|
|
// are gone.
|
|
let generation = self.session.generation();
|
|
let mut preserved_frames = VecDeque::new();
|
|
let result = (|| {
|
|
loop {
|
|
// An ended session forgot its unacknowledged writes; reporting
|
|
// them flushed would be a lie.
|
|
if self.session.ended() || self.session.generation() != generation {
|
|
return Err(anyhow!(
|
|
"RUDP session ended before its reliable writes were acknowledged: {}",
|
|
String::from_utf8_lossy(self.disconnect_reason.as_deref().unwrap_or(b"no reason given"))
|
|
));
|
|
}
|
|
if self.outstanding_reliable_packet_count() == 0 {
|
|
return Ok(());
|
|
}
|
|
if Instant::now() >= deadline {
|
|
return Err(anyhow!(
|
|
"RUDP reliable flush timed out with {} packets outstanding",
|
|
self.outstanding_reliable_packet_count()
|
|
));
|
|
}
|
|
if let Some(frame) = self.receive_once()? {
|
|
preserved_frames.push_back(frame);
|
|
}
|
|
self.poll_resends()?;
|
|
}
|
|
})();
|
|
|
|
preserved_frames.append(&mut self.delivered_frames);
|
|
self.delivered_frames = preserved_frames;
|
|
let restore = self.socket.set_read_timeout(original_timeout);
|
|
match (result, restore) {
|
|
(Err(error), _) => Err(error),
|
|
(Ok(()), Err(error)) => Err(error.into()),
|
|
(Ok(()), Ok(())) => Ok(()),
|
|
}
|
|
}
|
|
|
|
/// The next delivered frame, or `None` only when nothing is waiting on
|
|
/// the socket. Acknowledgements, pongs and incomplete fragments are
|
|
/// consumed and reading continues; see the hub's `receive_event_once`.
|
|
pub fn receive_once(&mut self) -> Result<Option<CultNetTransportFrame>> {
|
|
loop {
|
|
if let Some(frame) = self.delivered_frames.pop_front() {
|
|
return Ok(Some(frame));
|
|
}
|
|
if !self.receive_packet_once()? {
|
|
return Ok(None);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Reads one datagram and applies it. `false` when the socket is empty
|
|
/// or the session has been disconnected.
|
|
fn receive_packet_once(&mut self) -> Result<bool> {
|
|
let mut wire = vec![0_u8; 65_535];
|
|
let (received, remote_addr) = match self.socket.recv_from(&mut wire) {
|
|
Ok(value) => value,
|
|
Err(error)
|
|
if error.kind() == ErrorKind::WouldBlock
|
|
|| error.kind() == ErrorKind::TimedOut
|
|
|| error.kind() == ErrorKind::ConnectionReset =>
|
|
{
|
|
return Ok(false);
|
|
}
|
|
Err(error) => return Err(error.into()),
|
|
};
|
|
wire.truncate(received);
|
|
self.stats.bytes_received += received as u64;
|
|
|
|
// What a datagram carries is the sender's business, not a fault of this
|
|
// process: a malformed frame, another session's id, a sender that is not
|
|
// this transport's peer and a packet the session refuses are dropped and
|
|
// counted. Only the socket ends a loop. The id is checked before the
|
|
// peer endpoint or session state is touched, so a stray Connect can
|
|
// neither move the endpoint nor reset the session.
|
|
let Ok(packet) = decode_rudp_packet(&wire) else {
|
|
self.stats.packets_dropped += 1;
|
|
return Ok(true);
|
|
};
|
|
if packet.connection_id != self.session.connection_id() {
|
|
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);
|
|
}
|
|
}
|
|
} else {
|
|
if self.mode == CultNetRudpSocketMode::Server
|
|
&& packet.packet_type != CultNetRudpPacketType::Connect
|
|
{
|
|
self.stats.packets_dropped += 1;
|
|
return Ok(true);
|
|
}
|
|
self.remote_addr = Some(remote_addr);
|
|
}
|
|
if self.mode == CultNetRudpSocketMode::Server
|
|
&& 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);
|
|
};
|
|
self.send_packet(&accept)?;
|
|
return Ok(true);
|
|
}
|
|
|
|
let Ok(result) = self.session.receive(&packet, now_ms()) else {
|
|
// End the session and tell the peer. A server-mode transport also
|
|
// forgets its peer: only a Connect can claim it again.
|
|
self.stats.packets_dropped += 1;
|
|
let goodbye = self.session.end_refused_session();
|
|
self.disconnect_reason = Some(goodbye.payload.clone());
|
|
let sent = self.send_packet(&goodbye);
|
|
if self.mode == CultNetRudpSocketMode::Server {
|
|
self.remote_addr = None;
|
|
}
|
|
sent?;
|
|
return Ok(false);
|
|
};
|
|
if let Some(reply) = result.reply {
|
|
self.send_packet(&reply)?;
|
|
}
|
|
for ready in result.ready_to_send {
|
|
self.send_packet(&ready)?;
|
|
}
|
|
if result.pong {
|
|
self.pong_payloads.push_back(result.pong_payload);
|
|
}
|
|
if result.disconnected {
|
|
self.disconnect_reason = Some(result.disconnect_reason);
|
|
return Ok(false);
|
|
}
|
|
|
|
for frame in result.delivered {
|
|
self.delivered_frames.push_back(CultNetTransportFrame {
|
|
channel_id: frame.channel_id,
|
|
payload: frame.payload,
|
|
});
|
|
self.stats.frames_received += 1;
|
|
}
|
|
// Only what the sender is waiting on is acknowledged. An unreliable
|
|
// frame carries no sequence, so an ACK for it tells the sender
|
|
// nothing and costs it one datagram to read for every one it sent.
|
|
if packet.reliable || packet.packet_type == CultNetRudpPacketType::Accept {
|
|
let ack = self.session.create_ack_for_received(packet.sequence);
|
|
self.send_packet(&ack)?;
|
|
}
|
|
Ok(true)
|
|
}
|
|
|
|
pub fn poll_resends(&mut self) -> Result<()> {
|
|
for packet in self.session.due_resends(now_ms()) {
|
|
self.send_packet(&packet)?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn send_packet(&mut self, packet: &CultNetRudpPacket) -> Result<()> {
|
|
let Some(remote_addr) = self.remote_addr else {
|
|
return Err(anyhow!(
|
|
"RUDP socket transport does not have a remote endpoint"
|
|
));
|
|
};
|
|
let wire = encode_rudp_packet(packet)?;
|
|
let sent = self.socket.send_to(&wire, remote_addr)?;
|
|
self.stats.bytes_sent += sent as u64;
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
pub struct CultNetRudpReconnectLoop<F>
|
|
where
|
|
F: FnMut() -> Result<CultNetRudpSocketTransportConnection>,
|
|
{
|
|
pub reconnect_controller: CultNetReconnectController,
|
|
create_transport: F,
|
|
connect_payload: Vec<u8>,
|
|
transport: Option<CultNetRudpSocketTransportConnection>,
|
|
stopped: bool,
|
|
}
|
|
|
|
impl<F> CultNetRudpReconnectLoop<F>
|
|
where
|
|
F: FnMut() -> Result<CultNetRudpSocketTransportConnection>,
|
|
{
|
|
pub fn new(
|
|
reconnect_policy: CultNetReconnectPolicy,
|
|
connect_payload: Vec<u8>,
|
|
create_transport: F,
|
|
) -> Self {
|
|
Self {
|
|
reconnect_controller: CultNetReconnectController::new(reconnect_policy),
|
|
create_transport,
|
|
connect_payload,
|
|
transport: None,
|
|
stopped: true,
|
|
}
|
|
}
|
|
|
|
pub fn with_default_policy(connect_payload: Vec<u8>, create_transport: F) -> Self {
|
|
Self::new(
|
|
create_reconnect_policy(Default::default()),
|
|
connect_payload,
|
|
create_transport,
|
|
)
|
|
}
|
|
|
|
pub fn transport(&self) -> Option<&CultNetRudpSocketTransportConnection> {
|
|
self.transport.as_ref()
|
|
}
|
|
|
|
pub fn transport_mut(&mut self) -> Option<&mut CultNetRudpSocketTransportConnection> {
|
|
self.transport.as_mut()
|
|
}
|
|
|
|
pub fn start(&mut self) -> Result<&mut CultNetRudpSocketTransportConnection> {
|
|
self.stopped = false;
|
|
self.reconnect_controller.reset();
|
|
self.open_transport()
|
|
}
|
|
|
|
pub fn stop(&mut self) {
|
|
self.stopped = true;
|
|
self.transport = None;
|
|
self.reconnect_controller.reset();
|
|
}
|
|
|
|
pub fn mark_connected(&mut self) {
|
|
self.reconnect_controller.reset();
|
|
}
|
|
|
|
pub fn handle_closed(
|
|
&mut self,
|
|
now_ms: u64,
|
|
jitter_ms: u64,
|
|
) -> Option<CultNetReconnectDecision> {
|
|
self.transport = None;
|
|
if self.stopped {
|
|
return None;
|
|
}
|
|
Some(self.reconnect_controller.record_failure(now_ms, jitter_ms))
|
|
}
|
|
|
|
pub fn reconnect_if_due(&mut self, now_ms: u64) -> Result<bool> {
|
|
if self.stopped || !self.reconnect_controller.can_attempt(now_ms) {
|
|
return Ok(false);
|
|
}
|
|
self.open_transport()?;
|
|
Ok(true)
|
|
}
|
|
|
|
fn open_transport(&mut self) -> Result<&mut CultNetRudpSocketTransportConnection> {
|
|
let mut transport = (self.create_transport)()?;
|
|
transport.connect(self.connect_payload.clone())?;
|
|
self.transport = Some(transport);
|
|
Ok(self
|
|
.transport
|
|
.as_mut()
|
|
.expect("RUDP reconnect loop opened a transport"))
|
|
}
|
|
}
|
|
|
|
/// Sent to a peer whose session refused one of its packets, and reported to
|
|
/// the local caller as the disconnect reason.
|
|
const RUDP_REFUSED_PACKET_REASON: &[u8] = b"session refused a packet";
|
|
/// Goodbye reason of a session whose server could not answer a write (`end_local_failure_session`).
|
|
const RUDP_LOCAL_FAILURE_REASON: &[u8] = b"server could not answer a write";
|
|
const SESSION_TIMED_OUT_REASON: &[u8] = b"session timed out";
|
|
/// Prefix of the goodbye reason for a session that owed a packet which can
|
|
/// never be sent; the failure's fixed name (`send_error_code`) follows it.
|
|
const RUDP_UNSENDABLE_PACKET_REASON: &str = "packet could not be sent";
|
|
|
|
/// Whether a failed `send_to` can never succeed for the datagram as built, so
|
|
/// resending it is pointless: it is too large for a datagram (`EMSGSIZE`), its
|
|
/// address is malformed for the socket (`EINVAL`), or belongs to another
|
|
/// address family (`EAFNOSUPPORT`). Everything else (no route, full buffers,
|
|
/// firewall drops, a refusal reported for an earlier datagram, an interrupted
|
|
/// call) is a property of the path or the moment and may pass, so it is a lost
|
|
/// datagram, not a reason to end a session.
|
|
pub fn is_permanent_send_error(error: &std::io::Error) -> bool {
|
|
send_error_code(error) != UNKNOWN_SEND_ERROR
|
|
}
|
|
|
|
const UNKNOWN_SEND_ERROR: &str = "UNKNOWN";
|
|
|
|
// `EMSGSIZE` and `EAFNOSUPPORT`, or their Winsock equivalents.
|
|
#[cfg(any(target_os = "linux", target_os = "android"))]
|
|
const PERMANENT_OS_ERRORS: Option<(i32, i32)> = Some((90, 97));
|
|
#[cfg(any(
|
|
target_os = "macos",
|
|
target_os = "ios",
|
|
target_os = "freebsd",
|
|
target_os = "netbsd",
|
|
target_os = "openbsd",
|
|
target_os = "dragonfly"
|
|
))]
|
|
const PERMANENT_OS_ERRORS: Option<(i32, i32)> = Some((40, 47));
|
|
#[cfg(windows)]
|
|
const PERMANENT_OS_ERRORS: Option<(i32, i32)> = Some((10040, 10047));
|
|
#[cfg(not(any(
|
|
target_os = "linux",
|
|
target_os = "android",
|
|
target_os = "macos",
|
|
target_os = "ios",
|
|
target_os = "freebsd",
|
|
target_os = "netbsd",
|
|
target_os = "openbsd",
|
|
target_os = "dragonfly",
|
|
windows
|
|
)))]
|
|
const PERMANENT_OS_ERRORS: Option<(i32, i32)> = None;
|
|
|
|
/// The fixed name of a failed send's cause: `EMSGSIZE`, `EINVAL` or
|
|
/// `EAFNOSUPPORT` for a failure that can never pass
|
|
/// (`is_permanent_send_error`), `UNKNOWN` for anything else. An unsendable
|
|
/// session's goodbye carries this name, never the error's own text, which is
|
|
/// the platform's wording and can differ by the packet that failed.
|
|
pub fn send_error_code(error: &std::io::Error) -> &'static str {
|
|
if let (Some(code), Some((message_size, address_family))) =
|
|
(error.raw_os_error(), PERMANENT_OS_ERRORS)
|
|
{
|
|
if code == message_size {
|
|
return "EMSGSIZE";
|
|
}
|
|
if code == address_family {
|
|
return "EAFNOSUPPORT";
|
|
}
|
|
}
|
|
// `InvalidInput` is `EINVAL` and `WSAEINVAL`.
|
|
if error.kind() == ErrorKind::InvalidInput {
|
|
return "EINVAL";
|
|
}
|
|
UNKNOWN_SEND_ERROR
|
|
}
|
|
|
|
/// 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: Option<u32>,
|
|
max_pending_reliable_packets: Option<u32>,
|
|
) -> Result<()> {
|
|
if initial_sequence == Some(u32::MAX) {
|
|
return Err(anyhow!(
|
|
"RUDP initial_sequence must leave room for a reliable packet"
|
|
));
|
|
}
|
|
if max_pending_reliable_packets == Some(0) {
|
|
return Err(anyhow!(
|
|
"RUDP max_pending_reliable_packets must be greater than zero"
|
|
));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[derive(Clone, Debug, Default)]
|
|
pub struct RudpTransportProfileOptions {
|
|
pub transport_id: Option<String>,
|
|
pub host: Option<String>,
|
|
pub port: Option<u16>,
|
|
pub max_payload_bytes: Option<u32>,
|
|
pub max_fragment_bytes: Option<u32>,
|
|
pub max_pending_reliable_packets: Option<u32>,
|
|
pub reconnect_policy: Option<CultNetReconnectPolicy>,
|
|
pub media_reliable_expire_after_ms: Option<u64>,
|
|
/// `None` means the historical default, `Reliable`.
|
|
pub media_delivery: Option<CultNetTransportDelivery>,
|
|
}
|
|
|
|
/// The largest payload a channel accepts: the session-wide cap, tightened on
|
|
/// the media channel to the media ceiling.
|
|
fn channel_payload_limit(channel_id: &str, session_limit: Option<usize>) -> Option<usize> {
|
|
if channel_id == GAMECULT_MEDIA_CHANNEL {
|
|
Some(session_limit.map_or(GAMECULT_MEDIA_MAX_WIRE_BYTES, |limit| {
|
|
limit.min(GAMECULT_MEDIA_MAX_WIRE_BYTES)
|
|
}))
|
|
} else {
|
|
session_limit
|
|
}
|
|
}
|
|
|
|
pub fn create_rudp_transport_profile(
|
|
runtime_id: impl Into<String>,
|
|
options: RudpTransportProfileOptions,
|
|
) -> CultNetTransportProfile {
|
|
CultNetTransportProfile {
|
|
schema_version: "cultnet.transport_profile.v0".to_string(),
|
|
runtime_id: runtime_id.into(),
|
|
transports: vec![CultNetTransportDescriptor {
|
|
transport_id: options.transport_id.unwrap_or_else(|| "rudp".to_string()),
|
|
protocol: CultNetTransportProtocol::Rudp,
|
|
host: options.host,
|
|
port: options.port,
|
|
path: None,
|
|
discovery_group: None,
|
|
wire_contracts: Some(vec!["cultnet.schema.v0".to_string()]),
|
|
reconnect_policy: Some(
|
|
options
|
|
.reconnect_policy
|
|
.unwrap_or_else(|| create_reconnect_policy(Default::default())),
|
|
),
|
|
channels: vec![
|
|
CultNetTransportChannel {
|
|
channel_id: "schema".to_string(),
|
|
delivery: CultNetTransportDelivery::Reliable,
|
|
ordering: CultNetTransportOrdering::Ordered,
|
|
max_payload_bytes: options.max_payload_bytes,
|
|
max_fragment_bytes: options.max_fragment_bytes,
|
|
max_pending_reliable_packets: options.max_pending_reliable_packets,
|
|
reliable_expire_after_ms: None,
|
|
},
|
|
CultNetTransportChannel {
|
|
channel_id: "latest".to_string(),
|
|
delivery: CultNetTransportDelivery::Unreliable,
|
|
ordering: CultNetTransportOrdering::Sequenced,
|
|
max_payload_bytes: options.max_payload_bytes,
|
|
max_fragment_bytes: options.max_fragment_bytes,
|
|
max_pending_reliable_packets: options.max_pending_reliable_packets,
|
|
reliable_expire_after_ms: None,
|
|
},
|
|
CultNetTransportChannel {
|
|
channel_id: "realtime".to_string(),
|
|
delivery: CultNetTransportDelivery::Unreliable,
|
|
ordering: CultNetTransportOrdering::Unordered,
|
|
max_payload_bytes: options.max_payload_bytes,
|
|
max_fragment_bytes: options.max_fragment_bytes,
|
|
max_pending_reliable_packets: options.max_pending_reliable_packets,
|
|
reliable_expire_after_ms: None,
|
|
},
|
|
CultNetTransportChannel {
|
|
channel_id: GAMECULT_MEDIA_CHANNEL.to_string(),
|
|
delivery: options
|
|
.media_delivery
|
|
.unwrap_or(CultNetTransportDelivery::Reliable),
|
|
ordering: CultNetTransportOrdering::Unordered,
|
|
max_payload_bytes: channel_payload_limit(
|
|
GAMECULT_MEDIA_CHANNEL,
|
|
options.max_payload_bytes.map(|limit| limit as usize),
|
|
)
|
|
.map(|limit| limit as u32),
|
|
max_fragment_bytes: options.max_fragment_bytes,
|
|
max_pending_reliable_packets: options.max_pending_reliable_packets,
|
|
reliable_expire_after_ms: options.media_reliable_expire_after_ms,
|
|
},
|
|
],
|
|
}],
|
|
}
|
|
}
|
|
|
|
pub fn encode_rudp_packet(packet: &CultNetRudpPacket) -> Result<Vec<u8>> {
|
|
let channel_id = packet.channel_id.as_bytes();
|
|
if channel_id.len() > u8::MAX as usize {
|
|
return Err(anyhow!(
|
|
"CultNet RUDP channel id cannot exceed 255 UTF-8 bytes"
|
|
));
|
|
}
|
|
|
|
let header_bytes = RUDP_FIXED_HEADER_BYTES + channel_id.len();
|
|
let mut wire = vec![0_u8; header_bytes + packet.payload.len()];
|
|
wire[..4].copy_from_slice(&RUDP_MAGIC);
|
|
wire[4] = RUDP_VERSION;
|
|
wire[5] = packet_type_to_code(packet.packet_type);
|
|
wire[6] = encode_flags(packet);
|
|
wire[7] = header_bytes as u8;
|
|
wire[8..12].copy_from_slice(&packet.connection_id.to_be_bytes());
|
|
wire[12..16].copy_from_slice(&packet.sequence.to_be_bytes());
|
|
wire[16..20].copy_from_slice(&packet.ack.to_be_bytes());
|
|
wire[20..24].copy_from_slice(&packet.ack_mask.to_be_bytes());
|
|
wire[24..26].copy_from_slice(&packet.fragment_id.to_be_bytes());
|
|
wire[26..28].copy_from_slice(&packet.fragment_index.to_be_bytes());
|
|
wire[28..30].copy_from_slice(&packet.fragment_count.to_be_bytes());
|
|
wire[30..34].copy_from_slice(&(packet.payload.len() as u32).to_be_bytes());
|
|
wire[34] = channel_id.len() as u8;
|
|
wire[35] = 0;
|
|
wire[RUDP_FIXED_HEADER_BYTES..header_bytes].copy_from_slice(channel_id);
|
|
wire[header_bytes..].copy_from_slice(&packet.payload);
|
|
Ok(wire)
|
|
}
|
|
|
|
pub fn decode_rudp_packet(wire: &[u8]) -> Result<CultNetRudpPacket> {
|
|
if wire.len() < RUDP_FIXED_HEADER_BYTES {
|
|
return Err(anyhow!(
|
|
"CultNet RUDP packet is shorter than the fixed header"
|
|
));
|
|
}
|
|
if wire[..4] != RUDP_MAGIC {
|
|
return Err(anyhow!("CultNet RUDP packet has the wrong magic"));
|
|
}
|
|
if wire[4] != RUDP_VERSION {
|
|
return Err(anyhow!(
|
|
"Unsupported CultNet RUDP packet version {}",
|
|
wire[4]
|
|
));
|
|
}
|
|
|
|
let packet_type = packet_type_from_code(wire[5])?;
|
|
let header_bytes = wire[7] as usize;
|
|
let channel_id_len = wire[34] as usize;
|
|
if header_bytes != RUDP_FIXED_HEADER_BYTES + channel_id_len {
|
|
return Err(anyhow!(
|
|
"CultNet RUDP packet header length does not match the channel id length"
|
|
));
|
|
}
|
|
let payload_len = u32::from_be_bytes(wire[30..34].try_into()?) as usize;
|
|
if wire.len() != header_bytes + payload_len {
|
|
return Err(anyhow!(
|
|
"CultNet RUDP packet payload length does not match the packet size"
|
|
));
|
|
}
|
|
|
|
let flags = wire[6];
|
|
Ok(CultNetRudpPacket {
|
|
packet_type,
|
|
reliable: (flags & 0b0000_0001) != 0,
|
|
ordered: (flags & 0b0000_0010) != 0,
|
|
sequenced: (flags & 0b0000_0100) != 0,
|
|
connection_id: u32::from_be_bytes(wire[8..12].try_into()?),
|
|
sequence: u32::from_be_bytes(wire[12..16].try_into()?),
|
|
ack: u32::from_be_bytes(wire[16..20].try_into()?),
|
|
ack_mask: u32::from_be_bytes(wire[20..24].try_into()?),
|
|
fragment_id: u16::from_be_bytes(wire[24..26].try_into()?),
|
|
fragment_index: u16::from_be_bytes(wire[26..28].try_into()?),
|
|
fragment_count: u16::from_be_bytes(wire[28..30].try_into()?),
|
|
channel_id: String::from_utf8(wire[RUDP_FIXED_HEADER_BYTES..header_bytes].to_vec())?,
|
|
payload: wire[header_bytes..].to_vec(),
|
|
})
|
|
}
|
|
|
|
fn encode_flags(packet: &CultNetRudpPacket) -> u8 {
|
|
(if packet.reliable { 0b0000_0001 } else { 0 })
|
|
| (if packet.ordered { 0b0000_0010 } else { 0 })
|
|
| (if packet.sequenced { 0b0000_0100 } else { 0 })
|
|
| (if packet.fragment_count > 0 {
|
|
0b0000_1000
|
|
} else {
|
|
0
|
|
})
|
|
}
|
|
|
|
fn packet_type_to_code(packet_type: CultNetRudpPacketType) -> u8 {
|
|
match packet_type {
|
|
CultNetRudpPacketType::Connect => 1,
|
|
CultNetRudpPacketType::Accept => 2,
|
|
CultNetRudpPacketType::Data => 3,
|
|
CultNetRudpPacketType::Ack => 4,
|
|
CultNetRudpPacketType::Ping => 5,
|
|
CultNetRudpPacketType::Pong => 6,
|
|
CultNetRudpPacketType::Disconnect => 7,
|
|
}
|
|
}
|
|
|
|
/// The advertised profile owns each channel's expiry. Resolving it here keeps
|
|
/// one answer for what a channel does, rather than a runtime field that can
|
|
/// disagree with the profile the peer was shown.
|
|
fn channel_reliable_expire_after_ms(
|
|
profile: &CultNetTransportProfile,
|
|
channel_id: &str,
|
|
) -> Option<u64> {
|
|
profile
|
|
.transports
|
|
.iter()
|
|
.flat_map(|transport| transport.channels.iter())
|
|
.find(|channel| channel.channel_id == channel_id)
|
|
.and_then(|channel| channel.reliable_expire_after_ms)
|
|
}
|
|
|
|
/// The advertised profile owns each channel's delivery, for the same reason it
|
|
/// owns expiry: a send path that hardcodes reliability can disagree with the
|
|
/// profile the peer was shown, and then no one can say what the channel does.
|
|
///
|
|
/// Falls back to `Reliable` for a channel the profile does not describe, which
|
|
/// is what every channel got before delivery was configurable.
|
|
fn channel_delivery(
|
|
profile: &CultNetTransportProfile,
|
|
channel_id: &str,
|
|
) -> CultNetTransportDelivery {
|
|
profile
|
|
.transports
|
|
.iter()
|
|
.flat_map(|transport| transport.channels.iter())
|
|
.find(|channel| channel.channel_id == channel_id)
|
|
.map(|channel| channel.delivery)
|
|
.unwrap_or(CultNetTransportDelivery::Reliable)
|
|
}
|
|
|
|
fn channel_send_options(
|
|
channel_id: &str,
|
|
now_ms: u64,
|
|
reliable_expire_after_ms: Option<u64>,
|
|
delivery: CultNetTransportDelivery,
|
|
) -> CultNetRudpSendOptions {
|
|
match channel_id {
|
|
"schema" => CultNetRudpSendOptions {
|
|
reliable: true,
|
|
ordered: true,
|
|
sequenced: false,
|
|
now_ms,
|
|
reliable_expire_after_ms: None,
|
|
},
|
|
"latest" => CultNetRudpSendOptions {
|
|
reliable: false,
|
|
ordered: false,
|
|
sequenced: true,
|
|
now_ms,
|
|
reliable_expire_after_ms: None,
|
|
},
|
|
// The one channel whose delivery a caller chooses. Media that has gone
|
|
// stale is worth dropping, not retransmitting: a reliable media channel
|
|
// under loss adds load exactly when the link has least to give.
|
|
"media" => CultNetRudpSendOptions {
|
|
reliable: matches!(delivery, CultNetTransportDelivery::Reliable),
|
|
ordered: false,
|
|
sequenced: false,
|
|
now_ms,
|
|
reliable_expire_after_ms,
|
|
},
|
|
_ => CultNetRudpSendOptions {
|
|
reliable: false,
|
|
ordered: false,
|
|
sequenced: false,
|
|
now_ms,
|
|
reliable_expire_after_ms: None,
|
|
},
|
|
}
|
|
}
|
|
|
|
fn now_ms() -> u64 {
|
|
SystemTime::now()
|
|
.duration_since(UNIX_EPOCH)
|
|
.map(|duration| duration.as_millis() as u64)
|
|
.unwrap_or(0)
|
|
}
|
|
|
|
fn packet_type_from_code(code: u8) -> Result<CultNetRudpPacketType> {
|
|
match code {
|
|
1 => Ok(CultNetRudpPacketType::Connect),
|
|
2 => Ok(CultNetRudpPacketType::Accept),
|
|
3 => Ok(CultNetRudpPacketType::Data),
|
|
4 => Ok(CultNetRudpPacketType::Ack),
|
|
5 => Ok(CultNetRudpPacketType::Ping),
|
|
6 => Ok(CultNetRudpPacketType::Pong),
|
|
7 => Ok(CultNetRudpPacketType::Disconnect),
|
|
_ => Err(anyhow!("Unsupported CultNet RUDP packet type {code}")),
|
|
}
|
|
}
|