ca57bb00e2
EnetHostPeer is the accepting side, one peer per client address. The tests drive our EnetClient against it with simulated time, loss, duplication and reordering, plus a scripted client for the stock ENet 1.3 facts (verify connect fields, session ids, what is acknowledged when). They fail against the stubs.
951 lines
38 KiB
Rust
951 lines
38 KiB
Rust
//! The host side of ENet (`docs/PROTOCOL.md` 3.1, `enet::host`): our own [`EnetClient`] talks to an
|
|
//! [`EnetHostPeer`] over an in-memory wire with simulated time, loss, duplication and reordering; plus a scripted
|
|
//! client for the wire facts of stock ENet 1.3 (verify connect fields, session ids, what is acknowledged when).
|
|
|
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
|
|
|
mod common;
|
|
|
|
use core::time::Duration;
|
|
|
|
use common::wire::{Endpoint, Impair, Wire, at};
|
|
use domistream::enet::protocol::{
|
|
Command, CommandBody, ConnectParams, Datagram, MAX_DATAGRAM_BYTES, NO_PEER_ID, encode_datagram, parse_datagram,
|
|
};
|
|
use domistream::enet::{
|
|
Delivery, EnetClient, EnetConfig, EnetEvent, EnetHostConfig, EnetHostEvent, EnetHostPeer, EnetHostState,
|
|
EnetState, MAX_PACKET_BYTES, MAX_SEND_QUEUE, parse_connect_request,
|
|
};
|
|
use domistream::{Error, Instant};
|
|
use proptest::prelude::*;
|
|
|
|
// ================================================================================================ setup
|
|
|
|
const HOST_PEER_ID: u16 = 7;
|
|
|
|
fn host_config() -> EnetHostConfig {
|
|
EnetHostConfig {
|
|
peer_id: HOST_PEER_ID,
|
|
channel_limit: 0x30,
|
|
mtu: 1400,
|
|
ping_interval: Duration::from_millis(500),
|
|
timeout: Duration::from_secs(10),
|
|
}
|
|
}
|
|
|
|
fn client_config() -> EnetConfig {
|
|
EnetConfig {
|
|
channel_count: 2,
|
|
mtu: 1400,
|
|
connect_data: 0x0000_1234,
|
|
ping_interval: Duration::from_millis(500),
|
|
timeout: Duration::from_secs(10),
|
|
}
|
|
}
|
|
|
|
struct Client {
|
|
peer: EnetClient,
|
|
events: Vec<EnetEvent>,
|
|
count: usize,
|
|
}
|
|
|
|
impl Client {
|
|
fn new(config: EnetConfig, seed: u64) -> Self {
|
|
let peer = EnetClient::connect(config, Instant::ZERO, &mut common::SeqRng::new(seed)).unwrap();
|
|
Self { peer, events: Vec::new(), count: 0 }
|
|
}
|
|
|
|
fn drain(&mut self) {
|
|
while let Some(e) = self.peer.poll_event() {
|
|
self.count += usize::from(matches!(e, EnetEvent::Received { .. }));
|
|
self.events.push(e);
|
|
}
|
|
}
|
|
|
|
fn received(&self, channel: u8) -> Vec<Vec<u8>> {
|
|
self.events
|
|
.iter()
|
|
.filter_map(|e| match e {
|
|
EnetEvent::Received { channel: c, data } if *c == channel => Some(data.clone()),
|
|
_ => None,
|
|
})
|
|
.collect()
|
|
}
|
|
}
|
|
|
|
impl Endpoint for Client {
|
|
fn transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
|
|
self.peer.poll_transmit(now)
|
|
}
|
|
fn receive(&mut self, now: Instant, datagram: &[u8]) {
|
|
let _ = self.peer.handle_datagram(now, datagram);
|
|
self.drain();
|
|
}
|
|
fn deadline(&self) -> Option<Instant> {
|
|
self.peer.poll_timeout()
|
|
}
|
|
fn tick(&mut self, now: Instant) {
|
|
self.peer.handle_timeout(now).unwrap();
|
|
self.drain();
|
|
}
|
|
}
|
|
|
|
/// The caller of the host: one address, so one slot; the first datagram goes to `accept`.
|
|
struct Host {
|
|
config: EnetHostConfig,
|
|
peer: Option<EnetHostPeer>,
|
|
events: Vec<EnetHostEvent>,
|
|
refused: usize,
|
|
/// Every datagram the host sent, parsed.
|
|
sent: Vec<Datagram>,
|
|
count: usize,
|
|
}
|
|
|
|
impl Host {
|
|
fn new(config: EnetHostConfig) -> Self {
|
|
Self { config, peer: None, events: Vec::new(), refused: 0, sent: Vec::new(), count: 0 }
|
|
}
|
|
|
|
fn peer(&mut self) -> &mut EnetHostPeer {
|
|
self.peer.as_mut().expect("accepted")
|
|
}
|
|
|
|
fn drain(&mut self) {
|
|
if let Some(p) = self.peer.as_mut() {
|
|
while let Some(e) = p.poll_event() {
|
|
self.count += usize::from(matches!(e, EnetHostEvent::Received { .. }));
|
|
self.events.push(e);
|
|
}
|
|
}
|
|
}
|
|
|
|
fn received(&self, channel: u8) -> Vec<Vec<u8>> {
|
|
self.events
|
|
.iter()
|
|
.filter_map(|e| match e {
|
|
EnetHostEvent::Received { channel: c, data } if *c == channel => Some(data.clone()),
|
|
_ => None,
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
fn connected(&self) -> bool {
|
|
self.peer.as_ref().is_some_and(|p| p.state() == EnetHostState::Connected)
|
|
}
|
|
}
|
|
|
|
impl Endpoint for Host {
|
|
fn transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
|
|
let d = self.peer.as_mut()?.poll_transmit(now)?;
|
|
let mtu = self.peer.as_ref().unwrap().mtu();
|
|
assert!(d.len() <= mtu, "host datagram of {} over the MTU {mtu}", d.len());
|
|
self.sent.push(parse_datagram(&d).expect("the host's datagrams parse"));
|
|
Some(d)
|
|
}
|
|
fn receive(&mut self, now: Instant, datagram: &[u8]) {
|
|
match self.peer.as_mut() {
|
|
None => match EnetHostPeer::accept(self.config, now, datagram) {
|
|
Ok(p) => self.peer = Some(p),
|
|
Err(_) => self.refused += 1,
|
|
},
|
|
Some(p) => {
|
|
let _ = p.handle_datagram(now, datagram);
|
|
}
|
|
}
|
|
self.drain();
|
|
}
|
|
fn deadline(&self) -> Option<Instant> {
|
|
self.peer.as_ref()?.poll_timeout()
|
|
}
|
|
fn tick(&mut self, now: Instant) {
|
|
if let Some(p) = self.peer.as_mut() {
|
|
p.handle_timeout(now).unwrap();
|
|
}
|
|
self.drain();
|
|
}
|
|
}
|
|
|
|
type W = Wire<Client, Host>;
|
|
|
|
fn wire(to_host: Impair, to_client: Impair, seed: u64) -> W {
|
|
wire_with(client_config(), host_config(), to_host, to_client, seed)
|
|
}
|
|
|
|
fn wire_with(client: EnetConfig, host: EnetHostConfig, to_host: Impair, to_client: Impair, seed: u64) -> W {
|
|
Wire::new(Client::new(client, seed), Host::new(host), to_host, to_client, seed)
|
|
}
|
|
|
|
/// Long timeouts for the loss tests: a command lost many times in a row must not end the connection.
|
|
fn lossy_wire(to_host: Impair, to_client: Impair, seed: u64) -> W {
|
|
let client = EnetConfig { timeout: Duration::from_secs(60), ..client_config() };
|
|
let host = EnetHostConfig { timeout: Duration::from_secs(60), ..host_config() };
|
|
wire_with(client, host, to_host, to_client, seed)
|
|
}
|
|
|
|
fn both_connected(w: &mut W) -> bool {
|
|
w.client.peer.state() == EnetState::Connected && w.host.connected()
|
|
}
|
|
|
|
fn connected_wire(to_host: Impair, to_client: Impair, seed: u64) -> W {
|
|
let mut w = wire(to_host, to_client, seed);
|
|
assert!(w.run_until(30_000, both_connected), "no connection (seed {seed})");
|
|
w
|
|
}
|
|
|
|
fn now(w: &W) -> Instant {
|
|
at(w.now_ms)
|
|
}
|
|
|
|
// ================================================================================================ scripted client
|
|
|
|
fn cmd(acknowledge: bool, channel_id: u8, reliable_sequence: u16, body: CommandBody) -> Command {
|
|
Command { acknowledge, channel_id, reliable_sequence, body }
|
|
}
|
|
|
|
fn connect_params(connect_id: u32) -> ConnectParams {
|
|
ConnectParams {
|
|
outgoing_peer_id: 0,
|
|
incoming_session_id: 0xFF,
|
|
outgoing_session_id: 0xFF,
|
|
mtu: 1400,
|
|
window_size: 65536,
|
|
channel_count: 2,
|
|
incoming_bandwidth: 0,
|
|
outgoing_bandwidth: 0,
|
|
packet_throttle_interval: 5000,
|
|
packet_throttle_acceleration: 2,
|
|
packet_throttle_deceleration: 2,
|
|
connect_id,
|
|
}
|
|
}
|
|
|
|
fn connect_datagram(params: ConnectParams, data: u32) -> Vec<u8> {
|
|
encode_datagram(&Datagram {
|
|
peer_id: NO_PEER_ID,
|
|
session_id: 0,
|
|
sent_time: Some(1),
|
|
commands: vec![cmd(true, 0xFF, 1, CommandBody::Connect { params, data })],
|
|
})
|
|
.unwrap()
|
|
}
|
|
|
|
fn to_host(session_id: u8, sent_time: Option<u16>, commands: Vec<Command>) -> Vec<u8> {
|
|
encode_datagram(&Datagram { peer_id: HOST_PEER_ID, session_id, sent_time, commands }).unwrap()
|
|
}
|
|
|
|
fn transmitted(peer: &mut EnetHostPeer, t: Instant) -> Vec<Datagram> {
|
|
let mut out = Vec::new();
|
|
while let Some(d) = peer.poll_transmit(t) {
|
|
assert!(d.len() <= peer.mtu());
|
|
out.push(parse_datagram(&d).expect("host datagrams parse"));
|
|
assert!(out.len() < 10_000, "poll_transmit never ends");
|
|
}
|
|
out
|
|
}
|
|
|
|
fn events(peer: &mut EnetHostPeer) -> Vec<EnetHostEvent> {
|
|
let mut out = Vec::new();
|
|
while let Some(e) = peer.poll_event() {
|
|
out.push(e);
|
|
assert!(out.len() < 100_000);
|
|
}
|
|
out
|
|
}
|
|
|
|
fn verify_of(ds: &[Datagram]) -> (Command, ConnectParams) {
|
|
ds.iter()
|
|
.flat_map(|d| &d.commands)
|
|
.find_map(|c| match &c.body {
|
|
CommandBody::VerifyConnect(p) => Some((c.clone(), *p)),
|
|
_ => None,
|
|
})
|
|
.expect("a verify connect")
|
|
}
|
|
|
|
/// A host that accepted a hand-built connect and had its verify acknowledged at 2 ms.
|
|
fn scripted_connected() -> EnetHostPeer {
|
|
let mut h = EnetHostPeer::accept(host_config(), at(1), &connect_datagram(connect_params(0xABCD), 9)).unwrap();
|
|
let sent = transmitted(&mut h, at(1));
|
|
let (v, _) = verify_of(&sent);
|
|
let ack = cmd(
|
|
false,
|
|
0xFF,
|
|
v.reliable_sequence,
|
|
CommandBody::Acknowledge {
|
|
received_reliable_sequence: v.reliable_sequence,
|
|
received_sent_time: sent[0].sent_time.unwrap(),
|
|
},
|
|
);
|
|
h.handle_datagram(at(2), &to_host(0, Some(2), vec![ack])).unwrap();
|
|
assert_eq!(events(&mut h), vec![EnetHostEvent::Connected { data: 9 }]);
|
|
assert_eq!(h.state(), EnetHostState::Connected);
|
|
h
|
|
}
|
|
|
|
// ================================================================================================ handshake
|
|
|
|
#[test]
|
|
fn handshake_over_a_clean_wire() {
|
|
let mut w = wire(Impair::clean(5), Impair::clean(5), 1);
|
|
assert!(w.run_until(1_000, both_connected));
|
|
assert_eq!(w.host.events, vec![EnetHostEvent::Connected { data: client_config().connect_data }]);
|
|
assert_eq!(w.client.events, vec![EnetEvent::Connected]);
|
|
let p = w.host.peer();
|
|
assert_eq!(p.channel_count(), 2, "min(client 2, limit 0x30)");
|
|
assert_eq!(p.mtu(), 1400);
|
|
assert_eq!(w.host.refused, 0);
|
|
// Every host datagram is addressed to the client's peer id (0) after the handshake.
|
|
assert!(w.host.sent.iter().all(|d| d.peer_id == 0));
|
|
}
|
|
|
|
#[test]
|
|
fn verify_connect_fields() {
|
|
let params = connect_params(0xDEAD_BEEF);
|
|
let d = connect_datagram(params, 0x55);
|
|
assert_eq!(parse_connect_request(&d).unwrap().params, params);
|
|
assert_eq!(parse_connect_request(&d).unwrap().data, 0x55);
|
|
let cfg = EnetHostConfig { mtu: 1200, ..host_config() };
|
|
let mut h = EnetHostPeer::accept(cfg, at(3), &d).unwrap();
|
|
assert_eq!(h.state(), EnetHostState::AcknowledgingConnect);
|
|
assert_eq!(h.connect_id(), 0xDEAD_BEEF);
|
|
assert!(events(&mut h).is_empty(), "connected only once the verify is acknowledged");
|
|
let sent = transmitted(&mut h, at(3));
|
|
assert_eq!(sent.len(), 1);
|
|
let dg = &sent[0];
|
|
assert_eq!(dg.peer_id, params.outgoing_peer_id, "addressed to the client's peer id");
|
|
assert_eq!(dg.session_id, 0);
|
|
assert_eq!(dg.sent_time, Some(3));
|
|
// Stock ENet answers a connect with the verify only: the verify itself retires the client's connect.
|
|
assert_eq!(dg.commands.len(), 1, "{:?}", dg.commands);
|
|
let (c, v) = verify_of(&sent);
|
|
assert!(c.acknowledge, "verify connect is reliable");
|
|
assert_eq!(c.channel_id, 0xFF);
|
|
assert_eq!(c.reliable_sequence, 1);
|
|
assert_eq!(v.outgoing_peer_id, HOST_PEER_ID);
|
|
assert_eq!(v.connect_id, 0xDEAD_BEEF);
|
|
assert_eq!((v.incoming_session_id, v.outgoing_session_id), (0, 0));
|
|
assert_eq!(v.mtu, 1200, "min(client, host)");
|
|
assert_eq!(v.window_size, 65536);
|
|
assert_eq!(v.channel_count, 2);
|
|
assert_eq!((v.incoming_bandwidth, v.outgoing_bandwidth), (0, 0), "our bandwidth: unlimited");
|
|
assert_eq!(
|
|
(v.packet_throttle_interval, v.packet_throttle_acceleration, v.packet_throttle_deceleration),
|
|
(5000, 2, 2),
|
|
"throttle echoed"
|
|
);
|
|
assert_eq!(h.mtu(), 1200);
|
|
}
|
|
|
|
#[test]
|
|
fn verify_clamps_what_the_client_offers() {
|
|
for (mtu, window, channels, want_mtu, want_window, want_channels) in [
|
|
(100u32, 1000u32, 200u32, 576u32, 4096u32, 0x30u32),
|
|
(9000, 1 << 20, 1, 1400, 65536, 1),
|
|
(576, 4096, 255, 576, 4096, 0x30),
|
|
(u32::MAX, 0, 0x30, 1400, 4096, 0x30),
|
|
] {
|
|
let p = ConnectParams { mtu, window_size: window, channel_count: channels, ..connect_params(1) };
|
|
let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(p, 0)).unwrap();
|
|
let (_, v) = verify_of(&transmitted(&mut h, at(0)));
|
|
assert_eq!((v.mtu, v.window_size, v.channel_count), (want_mtu, want_window, want_channels), "{p:?}");
|
|
assert_eq!(u32::from(h.channel_count()), want_channels);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn session_ids_follow_stock_enet() {
|
|
// (client's incoming, outgoing) -> (verify incoming = host's outgoing, verify outgoing = host's incoming).
|
|
for (inc, out, want_in, want_out) in [(0xFFu8, 0xFFu8, 0u8, 0u8), (1, 2, 2, 3), (3, 0, 0, 1), (2, 2, 3, 3)] {
|
|
let p = ConnectParams { incoming_session_id: inc, outgoing_session_id: out, ..connect_params(5) };
|
|
let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(p, 0)).unwrap();
|
|
let sent = transmitted(&mut h, at(0));
|
|
let (c, v) = verify_of(&sent);
|
|
assert_eq!((v.incoming_session_id, v.outgoing_session_id), (want_in, want_out), "connect {inc}/{out}");
|
|
assert_eq!(sent[0].session_id, want_in, "the host sends with the session the client takes as incoming");
|
|
// The client must send with the host's incoming session id; anything else is ignored.
|
|
let ack = cmd(
|
|
false,
|
|
0xFF,
|
|
1,
|
|
CommandBody::Acknowledge { received_reliable_sequence: c.reliable_sequence, received_sent_time: 0 },
|
|
);
|
|
let wrong = (want_out + 1) & 3;
|
|
h.handle_datagram(at(1), &to_host(wrong, Some(1), vec![ack.clone()])).unwrap();
|
|
assert_eq!(h.state(), EnetHostState::AcknowledgingConnect, "wrong session {wrong} ignored");
|
|
h.handle_datagram(at(1), &to_host(want_out, Some(1), vec![ack])).unwrap();
|
|
assert_eq!(h.state(), EnetHostState::Connected);
|
|
assert_eq!(events(&mut h), vec![EnetHostEvent::Connected { data: 0 }]);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn accept_refuses_what_is_not_a_connect() {
|
|
let good = connect_datagram(connect_params(1), 0);
|
|
assert!(EnetHostPeer::accept(host_config(), at(0), &good).is_ok());
|
|
assert!(EnetHostPeer::accept(host_config(), at(0), &[]).is_err());
|
|
assert!(EnetHostPeer::accept(host_config(), at(0), &[0xFF; 3]).is_err());
|
|
let ping = encode_datagram(&Datagram {
|
|
peer_id: NO_PEER_ID,
|
|
session_id: 0,
|
|
sent_time: Some(0),
|
|
commands: vec![cmd(true, 0xFF, 1, CommandBody::Ping)],
|
|
})
|
|
.unwrap();
|
|
assert_err!(EnetHostPeer::accept(host_config(), at(0), &ping), Error::UnexpectedValue { .. }, "no connect");
|
|
let mut addressed = parse_datagram(&good).unwrap();
|
|
addressed.peer_id = HOST_PEER_ID;
|
|
assert_err!(
|
|
EnetHostPeer::accept(host_config(), at(0), &encode_datagram(&addressed).unwrap()),
|
|
Error::UnexpectedValue { .. },
|
|
"a connect addressed to a peer"
|
|
);
|
|
for channels in [0u32, 256, u32::MAX] {
|
|
let p = ConnectParams { channel_count: channels, ..connect_params(1) };
|
|
assert_err!(
|
|
EnetHostPeer::accept(host_config(), at(0), &connect_datagram(p, 0)),
|
|
Error::UnexpectedValue { .. },
|
|
"{channels} channels"
|
|
);
|
|
assert!(parse_connect_request(&connect_datagram(p, 0)).is_err());
|
|
}
|
|
for bad in [
|
|
EnetHostConfig { mtu: 575, ..host_config() },
|
|
EnetHostConfig { mtu: 4097, ..host_config() },
|
|
EnetHostConfig { channel_limit: 0, ..host_config() },
|
|
EnetHostConfig { peer_id: NO_PEER_ID, ..host_config() },
|
|
EnetHostConfig { peer_id: 0xFFFF, ..host_config() },
|
|
] {
|
|
assert_err!(EnetHostPeer::accept(bad, at(0), &good), Error::Malformed { .. }, "{bad:?}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn repeated_connect_is_ignored_and_a_new_connect_id_is_visible() {
|
|
let d = connect_datagram(connect_params(77), 0);
|
|
let mut h = EnetHostPeer::accept(host_config(), at(0), &d).unwrap();
|
|
let first = transmitted(&mut h, at(0));
|
|
assert_eq!(first.len(), 1);
|
|
// The client's connect retransmitted: no second verify, no new state.
|
|
assert_eq!(h.handle_datagram(at(5), &d), Ok(()));
|
|
assert!(transmitted(&mut h, at(5)).is_empty());
|
|
assert_eq!(h.state(), EnetHostState::AcknowledgingConnect);
|
|
// A client that restarted: the caller sees another connect id and replaces the peer.
|
|
let again = connect_datagram(connect_params(78), 0);
|
|
assert_eq!(h.handle_datagram(at(6), &again), Ok(()));
|
|
assert_eq!(h.connect_id(), 77);
|
|
assert_ne!(parse_connect_request(&again).unwrap().params.connect_id, h.connect_id());
|
|
}
|
|
|
|
#[test]
|
|
fn data_before_the_verify_ack_is_not_taken() {
|
|
let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(connect_params(3), 0)).unwrap();
|
|
let sent = transmitted(&mut h, at(0));
|
|
let (v, _) = verify_of(&sent);
|
|
let data = cmd(true, 0, 1, CommandBody::SendReliable(b"early".to_vec()));
|
|
h.handle_datagram(at(1), &to_host(0, Some(1), vec![data.clone()])).unwrap();
|
|
assert!(events(&mut h).is_empty());
|
|
assert!(
|
|
!transmitted(&mut h, at(1)).iter().flat_map(|d| &d.commands).any(|c| matches!(c.body, CommandBody::Acknowledge { .. })),
|
|
"not acknowledged, so the client sends it again"
|
|
);
|
|
let ack = cmd(
|
|
false,
|
|
0xFF,
|
|
1,
|
|
CommandBody::Acknowledge { received_reliable_sequence: v.reliable_sequence, received_sent_time: 0 },
|
|
);
|
|
h.handle_datagram(at(2), &to_host(0, Some(2), vec![ack, data])).unwrap();
|
|
assert_eq!(
|
|
events(&mut h),
|
|
vec![EnetHostEvent::Connected { data: 0 }, EnetHostEvent::Received { channel: 0, data: b"early".to_vec() }]
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn lost_verify_is_retransmitted() {
|
|
let mut w = wire(Impair::clean(5), Impair::clean(5), 2);
|
|
w.to_client.cut = true;
|
|
w.run_for(50);
|
|
assert!(w.host.peer.is_some() && !both_connected(&mut w));
|
|
w.to_client.cut = false;
|
|
assert!(w.run_until(5_000, both_connected), "the verify is sent again");
|
|
}
|
|
|
|
#[test]
|
|
fn verify_never_acknowledged_times_out() {
|
|
let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(connect_params(3), 0)).unwrap();
|
|
let mut verifies = 0;
|
|
let mut guard = 0;
|
|
while h.state() != EnetHostState::Disconnected {
|
|
let t = h.poll_timeout().expect("a deadline while waiting");
|
|
assert!(t <= at(host_config().timeout.as_millis() as u64 + 1), "no timeout by {t:?}");
|
|
h.handle_timeout(t).unwrap();
|
|
verifies += transmitted(&mut h, t)
|
|
.iter()
|
|
.flat_map(|d| &d.commands)
|
|
.filter(|c| matches!(c.body, CommandBody::VerifyConnect(_)))
|
|
.count();
|
|
guard += 1;
|
|
assert!(guard < 10_000);
|
|
}
|
|
assert!(verifies >= 3, "the verify was retransmitted ({verifies})");
|
|
assert_eq!(events(&mut h), vec![EnetHostEvent::TimedOut]);
|
|
assert_eq!(h.poll_timeout(), None);
|
|
assert_err!(h.handle_datagram(at(20_000), &[0x00, 0x07]), Error::Closed);
|
|
}
|
|
|
|
// ================================================================================================ data
|
|
|
|
#[test]
|
|
fn reliable_both_ways_in_order() {
|
|
let mut w = connected_wire(Impair::clean(3), Impair::clean(3), 3);
|
|
let t = now(&w);
|
|
for i in 0..50u32 {
|
|
w.client.peer.send(t, (i % 2) as u8, Delivery::Reliable, &i.to_le_bytes()).unwrap();
|
|
w.host.peer().send(t, (i % 2) as u8, Delivery::Reliable, &(1000 + i).to_le_bytes()).unwrap();
|
|
}
|
|
w.run_for(1_000);
|
|
for ch in 0..2u8 {
|
|
let want: Vec<Vec<u8>> = (0..50u32).filter(|i| i % 2 == u32::from(ch)).map(|i| i.to_le_bytes().to_vec()).collect();
|
|
assert_eq!(w.host.received(ch), want, "host, channel {ch}");
|
|
let want: Vec<Vec<u8>> =
|
|
(0..50u32).filter(|i| i % 2 == u32::from(ch)).map(|i| (1000 + i).to_le_bytes().to_vec()).collect();
|
|
assert_eq!(w.client.received(ch), want, "client, channel {ch}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn large_packets_fragment_both_ways() {
|
|
let mut w = connected_wire(Impair::clean(2), Impair::clean(2), 4);
|
|
let up: Vec<u8> = (0..5000u32).map(|i| (i * 7) as u8).collect();
|
|
let down: Vec<u8> = (0..MAX_PACKET_BYTES as u32).map(|i| (i * 13 + 1) as u8).collect();
|
|
let t = now(&w);
|
|
w.client.peer.send(t, 1, Delivery::Reliable, &up).unwrap();
|
|
w.host.peer().send(t, 0, Delivery::Reliable, &down).unwrap();
|
|
w.run_for(2_000);
|
|
assert_eq!(w.host.received(1), vec![up]);
|
|
assert_eq!(w.client.received(0), vec![down]);
|
|
let frags = w.host.sent.iter().flat_map(|d| &d.commands).filter(|c| matches!(c.body, CommandBody::SendFragment(_))).count();
|
|
assert!(frags > 40, "the host fragmented its 64 KiB packet ({frags})");
|
|
}
|
|
|
|
#[test]
|
|
fn unreliable_and_unsequenced_from_the_client() {
|
|
let mut w = connected_wire(Impair::clean(2), Impair::clean(2), 5);
|
|
let t = now(&w);
|
|
for i in 0..3u8 {
|
|
w.client.peer.send(t, 0, Delivery::Unreliable, &[b'u', i]).unwrap();
|
|
w.client.peer.send(t, 1, Delivery::Unsequenced, &[b's', i]).unwrap();
|
|
}
|
|
w.run_for(200);
|
|
assert_eq!(w.host.received(0), vec![vec![b'u', 0], vec![b'u', 1], vec![b'u', 2]]);
|
|
assert_eq!(w.host.received(1), vec![vec![b's', 0], vec![b's', 1], vec![b's', 2]]);
|
|
}
|
|
|
|
#[test]
|
|
fn unreliable_from_the_host() {
|
|
let mut w = connected_wire(Impair::clean(2), Impair::clean(2), 6);
|
|
let t = now(&w);
|
|
w.host.peer().send(t, 0, Delivery::Unreliable, b"u1").unwrap();
|
|
w.host.peer().send(t, 0, Delivery::Unsequenced, b"s1").unwrap();
|
|
w.run_for(100);
|
|
assert_eq!(w.client.received(0), vec![b"u1".to_vec(), b"s1".to_vec()]);
|
|
}
|
|
|
|
#[test]
|
|
fn duplicated_and_stale_datagrams_are_delivered_once() {
|
|
let mut h = scripted_connected();
|
|
let unseq = |group: u16, data: &[u8]| cmd(false, 0, 0, CommandBody::SendUnsequenced { unsequenced_group: group, data: data.to_vec() });
|
|
let unrel = |seq: u16, data: &[u8]| cmd(false, 0, 0, CommandBody::SendUnreliable { unreliable_sequence: seq, data: data.to_vec() });
|
|
let feed = |h: &mut EnetHostPeer, c: Command| h.handle_datagram(at(10), &to_host(0, Some(10), vec![c])).unwrap();
|
|
feed(&mut h, unseq(1, b"a"));
|
|
feed(&mut h, unseq(1, b"a"));
|
|
feed(&mut h, unseq(2, b"b"));
|
|
feed(&mut h, unseq(1, b"a"));
|
|
feed(&mut h, unrel(5, b"x"));
|
|
feed(&mut h, unrel(5, b"x"));
|
|
feed(&mut h, unrel(4, b"old"));
|
|
feed(&mut h, unrel(6, b"y"));
|
|
let got: Vec<Vec<u8>> = events(&mut h)
|
|
.into_iter()
|
|
.map(|e| match e {
|
|
EnetHostEvent::Received { data, .. } => data,
|
|
other => panic!("{other:?}"),
|
|
})
|
|
.collect();
|
|
assert_eq!(got, vec![b"a".to_vec(), b"b".to_vec(), b"x".to_vec(), b"y".to_vec()]);
|
|
// Far ahead of the unsequenced window: dropped.
|
|
feed(&mut h, unseq(40_000, b"far"));
|
|
assert!(events(&mut h).is_empty());
|
|
// The window moves forward with groups within reach.
|
|
feed(&mut h, unseq(3000, b"c"));
|
|
feed(&mut h, unseq(3000, b"c"));
|
|
feed(&mut h, unseq(2, b"b"));
|
|
assert_eq!(events(&mut h), vec![EnetHostEvent::Received { channel: 0, data: b"c".to_vec() }]);
|
|
}
|
|
|
|
#[test]
|
|
fn reliable_from_the_client_reordered_and_duplicated() {
|
|
let mut h = scripted_connected();
|
|
let rel = |seq: u16, data: &[u8]| cmd(true, 0, seq, CommandBody::SendReliable(data.to_vec()));
|
|
h.handle_datagram(at(10), &to_host(0, Some(10), vec![rel(3, b"3"), rel(2, b"2")])).unwrap();
|
|
assert!(events(&mut h).is_empty());
|
|
h.handle_datagram(at(11), &to_host(0, Some(11), vec![rel(1, b"1"), rel(2, b"2")])).unwrap();
|
|
h.handle_datagram(at(12), &to_host(0, Some(12), vec![rel(1, b"1")])).unwrap();
|
|
let got: Vec<EnetHostEvent> = events(&mut h);
|
|
assert_eq!(
|
|
got,
|
|
[b"1", b"2", b"3"].iter().map(|d| EnetHostEvent::Received { channel: 0, data: d.to_vec() }).collect::<Vec<_>>()
|
|
);
|
|
let acks: Vec<(u16, u16)> = transmitted(&mut h, at(12))
|
|
.iter()
|
|
.flat_map(|d| d.commands.clone())
|
|
.filter_map(|c| match c.body {
|
|
CommandBody::Acknowledge { received_reliable_sequence, received_sent_time } => {
|
|
Some((received_reliable_sequence, received_sent_time))
|
|
}
|
|
_ => None,
|
|
})
|
|
.collect();
|
|
for want in [(3, 10), (2, 10), (1, 11), (2, 11), (1, 12)] {
|
|
assert!(acks.contains(&want), "ack {want:?} (with the datagram's sent time) in {acks:?}");
|
|
}
|
|
// Far future and channels outside the grant: never delivered.
|
|
h.handle_datagram(at(13), &to_host(0, Some(13), vec![rel(40_000, b"evil")])).unwrap();
|
|
let _ = h.handle_datagram(at(13), &to_host(0, Some(13), vec![cmd(true, 9, 1, CommandBody::SendReliable(b"ch9".to_vec()))]));
|
|
assert!(events(&mut h).is_empty());
|
|
assert_eq!(h.state(), EnetHostState::Connected);
|
|
}
|
|
|
|
#[test]
|
|
fn acknowledged_commands_need_the_sent_time() {
|
|
// Stock ENet: a command that wants an acknowledgement in a datagram without sent time is handled but not
|
|
// acknowledged, and the rest of the datagram is skipped.
|
|
let mut h = scripted_connected();
|
|
let d = to_host(
|
|
0,
|
|
None,
|
|
vec![
|
|
cmd(true, 0, 1, CommandBody::SendReliable(b"a".to_vec())),
|
|
cmd(true, 0, 2, CommandBody::SendReliable(b"b".to_vec())),
|
|
],
|
|
);
|
|
h.handle_datagram(at(10), &d).unwrap();
|
|
assert_eq!(events(&mut h), vec![EnetHostEvent::Received { channel: 0, data: b"a".to_vec() }]);
|
|
assert!(
|
|
!transmitted(&mut h, at(10)).iter().flat_map(|d| &d.commands).any(|c| matches!(c.body, CommandBody::Acknowledge { .. }))
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn connection_commands_are_acknowledged() {
|
|
let mut h = scripted_connected();
|
|
let d = to_host(
|
|
0,
|
|
Some(0x0102),
|
|
vec![
|
|
cmd(true, 0xFF, 2, CommandBody::Ping),
|
|
cmd(true, 0xFF, 3, CommandBody::BandwidthLimit { incoming: 1_000_000, outgoing: 2_000_000 }),
|
|
cmd(true, 0xFF, 4, CommandBody::ThrottleConfigure { interval: 1000, acceleration: 3, deceleration: 4 }),
|
|
],
|
|
);
|
|
h.handle_datagram(at(10), &d).unwrap();
|
|
let acks: Vec<Command> = transmitted(&mut h, at(10))
|
|
.into_iter()
|
|
.flat_map(|d| d.commands)
|
|
.filter(|c| matches!(c.body, CommandBody::Acknowledge { .. }))
|
|
.collect();
|
|
for seq in [2u16, 3, 4] {
|
|
assert!(
|
|
acks.iter().any(|c| c.channel_id == 0xFF
|
|
&& c.body == CommandBody::Acknowledge { received_reliable_sequence: seq, received_sent_time: 0x0102 }),
|
|
"ack of {seq} in {acks:?}"
|
|
);
|
|
}
|
|
assert!(events(&mut h).is_empty());
|
|
assert_eq!(h.state(), EnetHostState::Connected);
|
|
}
|
|
|
|
#[test]
|
|
fn reliable_sequence_wraps_at_0xffff() {
|
|
let mut w = connected_wire(Impair::clean(1), Impair::clean(1), 7);
|
|
let total = 66_000u32;
|
|
let mut sent = 0u32;
|
|
while sent < total {
|
|
let t = now(&w);
|
|
for _ in 0..200 {
|
|
if sent < total {
|
|
w.client.peer.send(t, 0, Delivery::Reliable, &sent.to_le_bytes()).unwrap();
|
|
w.host.peer().send(t, 0, Delivery::Reliable, &sent.to_le_bytes()).unwrap();
|
|
sent += 1;
|
|
}
|
|
}
|
|
let want = sent as usize;
|
|
assert!(w.run_until(w.now_ms + 5_000, |w| w.host.count >= want && w.client.count >= want));
|
|
}
|
|
let got = w.host.received(0);
|
|
assert_eq!(got.len(), total as usize);
|
|
assert!(got.iter().enumerate().all(|(i, d)| *d == (i as u32).to_le_bytes()), "host order");
|
|
let got = w.client.received(0);
|
|
assert_eq!(got.len(), total as usize);
|
|
assert!(got.iter().enumerate().all(|(i, d)| *d == (i as u32).to_le_bytes()), "client order");
|
|
}
|
|
|
|
// ================================================================================================ loss and timers
|
|
|
|
/// Sends `n` reliable messages each way, a few at a time, over a lossy wire; returns what arrived.
|
|
fn exchange(w: &mut W, n: u32) -> (Vec<Vec<u8>>, Vec<Vec<u8>>) {
|
|
let mut i = 0;
|
|
while i < n {
|
|
let t = now(w);
|
|
for _ in 0..5 {
|
|
if i < n {
|
|
let _ = w.client.peer.send(t, 0, Delivery::Reliable, &i.to_le_bytes());
|
|
if let Some(p) = w.host.peer.as_mut() {
|
|
let _ = p.send(t, 0, Delivery::Reliable, &(i + 10_000).to_le_bytes());
|
|
}
|
|
i += 1;
|
|
}
|
|
}
|
|
w.run_for(30);
|
|
}
|
|
let n = n as usize;
|
|
w.run_until(w.now_ms + 120_000, |w| w.host.count >= n && w.client.count >= n);
|
|
(w.host.received(0), w.client.received(0))
|
|
}
|
|
|
|
#[test]
|
|
fn retransmission_under_loss_delivers_everything_in_order() {
|
|
let mut w = lossy_wire(Impair::lossy(200, 10), Impair::lossy(200, 10), 8);
|
|
assert!(w.run_until(60_000, both_connected));
|
|
let (up, down) = exchange(&mut w, 200);
|
|
assert_eq!(up, (0..200u32).map(|i| i.to_le_bytes().to_vec()).collect::<Vec<_>>());
|
|
assert_eq!(down, (0..200u32).map(|i| (i + 10_000).to_le_bytes().to_vec()).collect::<Vec<_>>());
|
|
assert!(w.to_host.lost > 0 && w.to_client.lost > 0, "the wire did lose datagrams");
|
|
assert!(!w.host.events.contains(&EnetHostEvent::TimedOut));
|
|
assert!(w.host.peer().round_trip_time().is_some());
|
|
}
|
|
|
|
#[test]
|
|
fn idle_connection_stays_up() {
|
|
let mut w = connected_wire(Impair::clean(20), Impair::clean(20), 9);
|
|
w.run_for(60_000);
|
|
assert!(both_connected(&mut w));
|
|
assert!(!w.host.events.contains(&EnetHostEvent::TimedOut));
|
|
assert!(!w.client.events.contains(&EnetEvent::TimedOut));
|
|
}
|
|
|
|
#[test]
|
|
fn the_host_pings_a_quiet_client() {
|
|
// A client that never pings by itself (only acknowledges): the host's pings keep the connection checked.
|
|
let quiet = EnetConfig { ping_interval: Duration::from_secs(3600), ..client_config() };
|
|
let mut w = wire_with(quiet, host_config(), Impair::clean(20), Impair::clean(20), 13);
|
|
assert!(w.run_until(1_000, both_connected));
|
|
let start = w.host.sent.len();
|
|
w.run_for(30_000);
|
|
assert!(both_connected(&mut w));
|
|
let pings =
|
|
w.host.sent[start..].iter().flat_map(|d| &d.commands).filter(|c| c.body == CommandBody::Ping && c.acknowledge).count();
|
|
assert!(pings >= 30, "the host pings an idle client ({pings})");
|
|
// And when nothing comes back at all, its ping times out.
|
|
let mut h = scripted_connected();
|
|
let t = h.poll_timeout().expect("a ping deadline");
|
|
assert!(t <= at(2 + host_config().ping_interval.as_millis() as u64));
|
|
h.handle_timeout(t).unwrap();
|
|
assert!(transmitted(&mut h, t).iter().flat_map(|d| &d.commands).any(|c| c.body == CommandBody::Ping && c.channel_id == 0xFF));
|
|
}
|
|
|
|
#[test]
|
|
fn vanished_client_times_out() {
|
|
let mut w = connected_wire(Impair::clean(5), Impair::clean(5), 10);
|
|
let cut_at = w.now_ms;
|
|
w.to_host.cut = true;
|
|
let limit = cut_at + host_config().ping_interval.as_millis() as u64 + host_config().timeout.as_millis() as u64 + 1_000;
|
|
assert!(w.run_until(limit, |w| w.host.events.contains(&EnetHostEvent::TimedOut)), "no timeout by {limit} ms");
|
|
let earliest = cut_at + host_config().timeout.as_millis() as u64 - host_config().ping_interval.as_millis() as u64;
|
|
assert!(w.now_ms >= earliest, "not before the timeout");
|
|
assert_eq!(w.host.peer().state(), EnetHostState::Disconnected);
|
|
assert_eq!(w.host.peer().poll_timeout(), None);
|
|
let t = now(&w);
|
|
assert_err!(w.host.peer().send(t, 0, Delivery::Reliable, b"x"), Error::State { .. });
|
|
}
|
|
|
|
// ================================================================================================ disconnect
|
|
|
|
#[test]
|
|
fn client_disconnect_reaches_the_host() {
|
|
let mut w = connected_wire(Impair::clean(5), Impair::clean(5), 11);
|
|
let t = now(&w);
|
|
w.client.peer.disconnect(t, 77).unwrap();
|
|
assert!(w.run_until(w.now_ms + 2_000, |w| w.host.events.contains(&EnetHostEvent::Disconnected { data: 77 })));
|
|
assert_eq!(w.host.peer().state(), EnetHostState::Disconnected);
|
|
assert!(
|
|
w.run_until(w.now_ms + 2_000, |w| w.client.peer.state() == EnetState::Disconnected),
|
|
"the host acknowledged the disconnect after closing"
|
|
);
|
|
assert!(!w.client.events.contains(&EnetEvent::TimedOut));
|
|
}
|
|
|
|
#[test]
|
|
fn host_disconnect_reaches_the_client() {
|
|
let mut w = connected_wire(Impair::clean(5), Impair::clean(5), 12);
|
|
let t = now(&w);
|
|
w.host.peer().disconnect(t, 42).unwrap();
|
|
assert_eq!(w.host.peer().state(), EnetHostState::Disconnecting);
|
|
assert_err!(w.host.peer().disconnect(t, 1), Error::Closed);
|
|
assert_err!(w.host.peer().send(t, 0, Delivery::Reliable, b"late"), Error::State { .. });
|
|
assert!(w.run_until(w.now_ms + 2_000, |w| w.client.events.contains(&EnetEvent::Disconnected { data: 42 })));
|
|
assert!(w.run_until(w.now_ms + 2_000, |w| w.host.peer.as_ref().unwrap().state() == EnetHostState::Disconnected));
|
|
assert!(!w.host.events.contains(&EnetHostEvent::TimedOut));
|
|
}
|
|
|
|
#[test]
|
|
fn disconnect_during_the_handshake() {
|
|
let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(connect_params(3), 0)).unwrap();
|
|
let _ = transmitted(&mut h, at(0));
|
|
h.handle_datagram(at(1), &to_host(0, Some(1), vec![cmd(true, 0xFF, 2, CommandBody::Disconnect { data: 5 })]))
|
|
.unwrap();
|
|
assert_eq!(h.state(), EnetHostState::Disconnected);
|
|
assert_eq!(events(&mut h), vec![EnetHostEvent::Disconnected { data: 5 }]);
|
|
}
|
|
|
|
// ================================================================================================ rules
|
|
|
|
#[test]
|
|
fn send_rules() {
|
|
let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(connect_params(3), 0)).unwrap();
|
|
assert_err!(h.send(at(0), 0, Delivery::Reliable, b"x"), Error::State { .. }, "before the verify is acknowledged");
|
|
let mut h = scripted_connected();
|
|
assert_err!(h.send(at(3), 2, Delivery::Reliable, b"x"), Error::UnexpectedValue { .. }, "channel 2 of 2");
|
|
assert_too_large!(h.send(at(3), 0, Delivery::Reliable, &vec![0; MAX_PACKET_BYTES + 1]), MAX_PACKET_BYTES, MAX_PACKET_BYTES + 1);
|
|
assert!(matches!(h.send(at(3), 0, Delivery::Unsequenced, &[0; 1500]), Err(Error::TooLarge { .. })));
|
|
for i in 0..MAX_SEND_QUEUE {
|
|
h.send(at(3), 0, Delivery::Reliable, &[i as u8]).unwrap_or_else(|e| panic!("packet {i}: {e:?}"));
|
|
}
|
|
match h.send(at(3), 0, Delivery::Reliable, b"one too many") {
|
|
Err(Error::TooLarge { max, .. }) => assert_eq!(max, MAX_SEND_QUEUE),
|
|
other => panic!("{other:?}"),
|
|
}
|
|
// The queue drains within the MTU, and each datagram parses.
|
|
let sent = transmitted(&mut h, at(4));
|
|
assert!(!sent.is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn garbage_never_changes_state() {
|
|
let mut h = scripted_connected();
|
|
for bad in [&[][..], &[0x00][..], &[0x40, 0x07, 0x85, 0xFF, 0, 1][..], &[0x00, 0x07, 0x8F, 0, 0, 0][..]] {
|
|
assert!(h.handle_datagram(at(5), bad).is_err(), "{bad:?}");
|
|
assert_eq!(h.state(), EnetHostState::Connected);
|
|
}
|
|
assert_too_large!(h.handle_datagram(at(5), &vec![0; MAX_DATAGRAM_BYTES + 1]), MAX_DATAGRAM_BYTES, MAX_DATAGRAM_BYTES + 1);
|
|
// Another peer id: dropped without error.
|
|
let other = encode_datagram(&Datagram {
|
|
peer_id: HOST_PEER_ID + 1,
|
|
session_id: 0,
|
|
sent_time: Some(1),
|
|
commands: vec![cmd(true, 0, 1, CommandBody::SendReliable(b"not for us".to_vec()))],
|
|
})
|
|
.unwrap();
|
|
assert_eq!(h.handle_datagram(at(5), &other), Ok(()));
|
|
assert!(events(&mut h).is_empty());
|
|
assert_eq!(h.state(), EnetHostState::Connected);
|
|
}
|
|
|
|
#[test]
|
|
fn fragments_with_lying_lengths() {
|
|
let frag = |count: u32, number: u32, total: u32, offset: u32, len: usize| {
|
|
cmd(
|
|
true,
|
|
0,
|
|
1,
|
|
CommandBody::SendFragment(domistream::enet::protocol::Fragment {
|
|
start_sequence: 1u16.wrapping_sub(number as u16),
|
|
fragment_count: count,
|
|
fragment_number: number,
|
|
total_length: total,
|
|
fragment_offset: offset,
|
|
data: vec![0; len],
|
|
}),
|
|
)
|
|
};
|
|
let mut h = scripted_connected();
|
|
assert_too_large!(
|
|
h.handle_datagram(at(5), &to_host(0, Some(5), vec![frag(2, 0, MAX_PACKET_BYTES as u32 + 1, 0, 100)])),
|
|
MAX_PACKET_BYTES,
|
|
MAX_PACKET_BYTES + 1
|
|
);
|
|
for f in [frag(0, 0, 10, 0, 10), frag(2, 2, 20, 0, 10), frag(2, 0, 20, 15, 10), frag(2, 0, 5, 0, 10), frag(u32::MAX, 0, 100, 0, 10), frag(2, 0, u32::MAX, 0, 10)] {
|
|
let mut h = scripted_connected();
|
|
let _ = h.handle_datagram(at(5), &to_host(0, Some(5), vec![f.clone()]));
|
|
assert!(events(&mut h).is_empty(), "{f:?}");
|
|
assert_eq!(h.state(), EnetHostState::Connected);
|
|
}
|
|
}
|
|
|
|
// ================================================================================================ properties
|
|
|
|
proptest! {
|
|
#![proptest_config(ProptestConfig { cases: 128, ..ProptestConfig::default() })]
|
|
|
|
/// Arbitrary bytes never panic `accept`, and what it accepts it answers with datagrams that parse.
|
|
#[test]
|
|
fn accept_never_panics(data in proptest::collection::vec(any::<u8>(), 0..200)) {
|
|
let r = EnetHostPeer::accept(host_config(), at(0), &data);
|
|
prop_assert!(common::implemented(&r));
|
|
if let Ok(mut h) = r {
|
|
prop_assert!(!transmitted(&mut h, at(0)).is_empty());
|
|
}
|
|
}
|
|
|
|
/// A connected host fed arbitrary datagrams (raw, or with our header so they reach the command loop) never
|
|
/// panics; what it delivers fits the cap; what it sends parses and fits the MTU.
|
|
#[test]
|
|
fn host_survives_arbitrary_datagrams(
|
|
datagrams in proptest::collection::vec((any::<bool>(), proptest::collection::vec(any::<u8>(), 0..200)), 1..20)
|
|
) {
|
|
let mut h = scripted_connected();
|
|
for (i, (headed, d)) in datagrams.into_iter().enumerate() {
|
|
let t = at(10 + i as u64 * 50);
|
|
let bytes = if headed {
|
|
let mut b = vec![0x80, HOST_PEER_ID as u8, 0, 10];
|
|
b.extend_from_slice(&d);
|
|
b
|
|
} else {
|
|
d
|
|
};
|
|
let r = h.handle_datagram(t, &bytes);
|
|
prop_assert!(common::implemented(&r));
|
|
let _ = h.handle_timeout(t);
|
|
let _ = transmitted(&mut h, t);
|
|
for e in events(&mut h) {
|
|
if let EnetHostEvent::Received { data, .. } = e {
|
|
prop_assert!(data.len() <= MAX_PACKET_BYTES);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
proptest! {
|
|
#![proptest_config(ProptestConfig { cases: 24, ..ProptestConfig::default() })]
|
|
|
|
/// Random loss, duplication, reordering and latency: the connection comes up and every reliable message
|
|
/// arrives exactly once, in order, both ways.
|
|
#[test]
|
|
fn random_loss_patterns_deliver_reliable_messages_in_order(
|
|
seed in any::<u64>(),
|
|
loss in 0u32..300,
|
|
duplicate in 0u32..150,
|
|
reorder in 0u32..400,
|
|
latency in 1u64..60,
|
|
) {
|
|
let impair = Impair { loss, duplicate, reorder, reorder_ms: 40, latency_ms: latency };
|
|
let mut w = lossy_wire(impair, impair, seed);
|
|
prop_assert!(w.run_until(60_000, both_connected), "no connection");
|
|
let (up, down) = exchange(&mut w, 40);
|
|
prop_assert_eq!(up, (0..40u32).map(|i| i.to_le_bytes().to_vec()).collect::<Vec<_>>());
|
|
prop_assert_eq!(down, (0..40u32).map(|i| (i + 10_000).to_le_bytes().to_vec()).collect::<Vec<_>>());
|
|
}
|
|
}
|