Skip to content

Commit

Permalink
Add established_tcp_stream_count{,_on} (#188)
Browse files Browse the repository at this point in the history
This commit adds a utility method to count the number of established tcp
streams on a given host (or the current host). This can be used to
verify connections have been cleaned up, which is sometimes tricky to
reason about due to a combination of how tcp cleans up and how Drop
works.
  • Loading branch information
marcbowes authored Oct 4, 2024
1 parent 7b8d6d6 commit 3a38ee6
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,10 @@ impl Tcp {
rx
}

pub(crate) fn stream_count(&self) -> usize {
self.sockets.len()
}

pub(crate) fn accept(&mut self, addr: SocketAddr) -> Option<(Syn, SocketAddr)> {
self.binds[&addr.port()].deque.pop_front()
}
Expand Down
10 changes: 10 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,3 +246,13 @@ pub fn partition(a: impl ToIpAddrs, b: impl ToIpAddrs) {
pub fn repair(a: impl ToIpAddrs, b: impl ToIpAddrs) {
World::current(|world| world.repair_many(a, b))
}

/// Return the number of established tcp streams on the current host.
pub fn established_tcp_stream_count() -> usize {
World::current(|world| world.est_tcp_streams())
}

/// Return the number of established tcp streams on the given host.
pub fn established_tcp_stream_count_on(addr: impl ToIpAddr) -> usize {
World::current(|world| world.est_tcp_streams_on(addr))
}
12 changes: 12 additions & 0 deletions src/world.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,18 @@ impl World {
});
}

pub(crate) fn est_tcp_streams(&mut self) -> usize {
self.current_host().tcp.stream_count()
}

pub(crate) fn est_tcp_streams_on(&mut self, addr: impl ToIpAddr) -> usize {
self.hosts
.get(&self.dns.lookup(addr))
.unwrap()
.tcp
.stream_count()
}

/// Register a new host with the simulation.
pub(crate) fn register(
&mut self,
Expand Down
7 changes: 7 additions & 0 deletions tests/tcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -548,8 +548,15 @@ fn hangup() -> Result {
sim.client("client", async move {
let s = TcpStream::connect(("server", PORT)).await?;

assert_eq!(1, turmoil::established_tcp_stream_count());
assert_eq!(1, turmoil::established_tcp_stream_count_on("server"));

drop(s);
assert_eq!(0, turmoil::established_tcp_stream_count());
assert_eq!(1, turmoil::established_tcp_stream_count_on("server")); // server sleeps in its loop

wait.notified().await;
assert_eq!(0, turmoil::established_tcp_stream_count_on("server"));

Ok(())
});
Expand Down

0 comments on commit 3a38ee6

Please sign in to comment.