Skip to main content

Peer

Struct Peer 

Source
pub struct Peer {
    pub last_heard: Instant,
    pub last_sent: Instant,
    pub remote_address: SocketAddr,
    /* private fields */
}
Expand description

Represents a remote peer in the network. Tracks network quality, processes packets, and manages connection state.

Fields§

§last_heard: Instant

Last time we received a packet from this client

§last_sent: Instant

Last time we sent a packet to this client

§remote_address: SocketAddr

The address of the remote endpoint

Implementations§

Source§

impl Peer

Source

pub fn process_command_packet( &mut self, data: &[u8], time: Instant, ) -> Result<IncomingPackets>

Decodes and processes an incoming command packet. This is the command-based alternative to process_incoming. Returns all user packets that resulted from processing the commands. Validates CRC32 checksum if enabled, then decompresses if needed.

Source

pub fn process_command( &mut self, command: &ProtocolCommand, time: Instant, ) -> Result<IncomingPackets>

Processes an incoming protocol command and returns resulting actions. This is the command-based alternative to process_incoming. Automatically enqueues response commands (ACK, Pong) when appropriate.

Source§

impl Peer

Source

pub fn encode_queued_commands(&mut self) -> Result<Vec<u8>>

Encodes all queued commands into a CommandPacket and returns the bytes. Drains the command queue in the process. Applies compression if enabled, then appends CRC32 checksum if enabled.

Source

pub fn encode_queued_commands_bounded( &mut self, max_size: usize, ) -> Result<Option<Vec<u8>>>

Encodes up to max_size bytes worth of queued commands into a single datagram.

  • Returns Ok(None) if there are no queued commands.
  • Returns Ok(Some(bytes)) where bytes.len() <= max_size when data was produced.

This prevents producing UDP payloads larger than the configured receive buffer (and typical MTUs), avoiding OS-level EMSGSIZE errors and IP fragmentation.

Source§

impl Peer

Source

pub fn enqueue_reliable_data( &mut self, channel_id: u8, data: Arc<[u8]>, ordered: bool, ) -> u16

Enqueues reliable data, automatically fragmenting if necessary. Returns the sequence number used for the packet(s).

Source

pub fn enqueue_unreliable_data( &mut self, channel_id: u8, data: Arc<[u8]>, ) -> u16

Enqueues unreliable data, automatically fragmenting if necessary. Returns the sequence number used for reassembly.

Source§

impl Peer

Source

pub fn new(addr: SocketAddr, config: &Config, time: Instant) -> Peer

Creates and returns a new peer for the provided socket address.

Source

pub fn record_send(&mut self) -> bool

Records that this connection has sent a packet. Returns whether the connection has become acknowledged because of this send.

Source

pub fn record_recv(&mut self) -> bool

Records that this connection has received a packet. Returns whether the connection has become acknowledged because of this receive.

Source

pub fn is_established(&self) -> bool

Returns if the connection has been established

Source

pub fn state(&self) -> PeerState

Returns the current peer state

Source

pub fn disconnect(&mut self)

Initiates graceful disconnect

Source

pub fn initiate_connect(&mut self)

Initiates a connection handshake by sending CONNECT command (step 1 of 3). Should be called when transitioning from Idle to Connecting.

Source

pub fn packets_in_flight(&self) -> u16

Returns the current number of not yet acknowledged packets

Source

pub fn last_heard(&self, time: Instant) -> Duration

Returns a Duration representing the interval since we last heard from the client

Source

pub fn last_sent(&self, time: Instant) -> Duration

Returns a Duration representing the interval since we last sent to the client

Source

pub fn rtt(&self) -> Duration

Returns the current round-trip time for this connection.

Source

pub fn rto(&self) -> Duration

Returns the retransmission timeout for this connection.

Source

pub fn loss_rate(&self) -> f32

Returns the current packet loss rate (0.0 to 1.0).

Source

pub fn throttle(&self) -> f32

Returns the current congestion throttle value (0.0 to 1.0).

Source

pub fn update_throttle(&mut self, time: Instant) -> bool

Updates the congestion throttle based on current network conditions.

Source

pub fn config(&self) -> &Config

Returns the configuration for this peer.

Source

pub fn gather_dropped_packets(&mut self) -> Vec<SentPacket>

Gathers dropped packets from the acknowledgment handler.

Source

pub fn statistics(&self) -> &PeerStatistics

Returns a reference to the peer’s statistics.

Source

pub fn statistics_mut(&mut self) -> &mut PeerStatistics

Returns a mutable reference to the peer’s statistics.

Source

pub fn current_fragment_size(&self) -> u16

Returns current per-peer fragment size in bytes.

Source

pub fn handle_pmtu(&mut self, time: Instant)

Handles PMTU probing state machine (enqueue probes, process timeouts).

Source

pub fn window_size(&self) -> u32

Returns the current window size (in packets).

Source

pub fn reliable_data_in_transit(&self) -> u32

Returns the amount of reliable data currently in transit (in bytes).

Source

pub fn set_window_size(&mut self, window_size: u32)

Sets the window size (for negotiation during handshake).

Source

pub fn record_reliable_data_sent(&mut self, data_size: u32)

Records reliable data being sent (adds to in-transit counter).

Source

pub fn record_reliable_data_acked(&mut self, data_size: u32)

Records reliable data being acknowledged (removes from in-transit counter).

Source

pub fn can_send_reliable(&self) -> bool

Checks if we can send more data based on window-based flow control. Returns true if we have room in the window.

Source

pub fn adjust_window_size(&mut self)

Dynamically adjusts the window size based on network conditions. Called periodically to adapt to changing network conditions.

Source

pub fn update_bandwidth_window(&mut self, time: Instant) -> bool

Updates bandwidth tracking window, resetting counters if window expired. Returns true if the window was reset.

Source

pub fn record_bytes_sent(&mut self, bytes: u32)

Records bytes sent for bandwidth tracking.

Source

pub fn record_bytes_received(&mut self, bytes: u32)

Records bytes received for bandwidth tracking.

Source

pub fn can_send_within_bandwidth(&self) -> bool

Checks if we can send based on outgoing bandwidth limit. Returns true if we’re under the limit or if throttling is disabled (limit == 0).

Source

pub fn bandwidth_utilization(&self) -> f32

Returns current bandwidth utilization (0.0 to 1.0+). Returns 0.0 if bandwidth limiting is disabled.

Source

pub fn can_receive_within_bandwidth(&self) -> bool

Checks if we can receive based on incoming bandwidth limit. Returns true if we’re under the limit or if throttling is disabled (limit == 0).

Source

pub fn incoming_bandwidth_utilization(&self) -> f32

Returns current incoming bandwidth utilization (0.0 to 1.0+). Returns 0.0 if bandwidth limiting is disabled.

Source

pub fn next_unsequenced_group(&mut self) -> u16

Gets the next outgoing unsequenced group ID and increments the counter.

Source

pub fn is_unsequenced_duplicate(&self, group: u16) -> bool

Checks if an incoming unsequenced group is a duplicate or within the window. Returns true if this is a duplicate (already received), false if new.

Source

pub fn mark_unsequenced_received(&mut self, group: u16)

Marks an incoming unsequenced group as received in the window. Advances the window base if necessary.

Source

pub fn cleanup_stale_fragments(&mut self, time: Instant)

Cleans up stale fragment buffers that haven’t been completed within the timeout period. This prevents memory leaks from incomplete fragments (e.g., due to packet loss or malicious behavior).

Call this periodically (e.g., once per second) to prevent accumulation of stale buffers. Default timeout is 5 seconds after the first fragment is received.

Source

pub fn enqueue_command(&mut self, command: ProtocolCommand) -> bool

Enqueues a protocol command for batching. Returns true if the queue should be flushed (reached max size). Returns false and drops the command if it would exceed max_waiting_data limit.

Source

pub fn enqueue_ack_command(&mut self, sent_time: Option<u32>)

Generates and enqueues an Acknowledge command based on current state. This should be called after receiving reliable packets to send ACKs back.

Source

pub fn enqueue_ping_command(&mut self, timestamp: u32)

Generates and enqueues a Ping command with the current timestamp.

Source

pub fn enqueue_pong_command(&mut self, timestamp: u32)

Generates and enqueues a Pong command in response to a Ping.

Source

pub fn drain_commands(&mut self) -> impl Iterator<Item = ProtocolCommand> + '_

Drains all pending commands from the queue. Resets the total_waiting_data counter since commands are being sent.

Source

pub fn queued_commands_count(&self) -> usize

Returns the number of queued commands.

Source

pub fn has_queued_commands(&self) -> bool

Returns true if the command queue is empty.

Trait Implementations§

Source§

impl Debug for Peer

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Peer

§

impl RefUnwindSafe for Peer

§

impl Send for Peer

§

impl Sync for Peer

§

impl Unpin for Peer

§

impl UnsafeUnpin for Peer

§

impl UnwindSafe for Peer

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more