Skip to main content

rtci_stream_driver/runtime/
mock.rs

1//! [`MockRuntime`] (feature `runtime-mock`): virtual time and an in-memory network, so that
2//! driven connections run deterministically and a 30-second timeout takes no wall time.
3//!
4//! - **Clock.** [`MockRuntime::now`] starts at the moment the runtime was made and moves only
5//!   when told: [`MockClock::advance`] by hand, or, inside [`MockRuntime::run`] (and
6//!   `block_on`), to the next timer whenever nothing can run (as tokio's paused clock does).
7//!   A timer whose time is reached is woken; what waits on nothing with no timer pending is a
8//!   deadlock, and `run` panics saying so instead of hanging.
9//! - **Executor.** Tasks run on the thread that calls `run`, in the order they were woken.
10//! - **Network** ([`MockNet`]). UDP sockets (multicast included) and TCP listeners and
11//!   connections between mock sockets, by address: no file descriptor, nothing leaves the
12//!   process. Each direction between two IP addresses is a link with a delay, a loss rate, a
13//!   jitter (with or without reordering), a rate cap with a drop-tail queue and a block switch
14//!   ([`LinkConfig`]); loss and jitter draw from a seeded generator, so a run is the same
15//!   every time. The host's interfaces, for address selection, are set by the test
16//!   ([`MockNet::set_interfaces`]). A filter can drop chosen datagrams ([`MockNet::set_filter`]), and every
17//!   datagram is logged with its traffic class and fate ([`MockNet::log`]). Names resolve from
18//!   a table ([`MockNet::add_host`]). TCP is reliable: its bytes take the link's delay, never
19//!   its loss, and a blocked link holds a connection attempt forever.
20
21use super::{
22    AsyncTcpListener, AsyncTcpStream, AsyncUdpSocket, BoxFuture, JoinHandle, MulticastConfig,
23    RecvMeta, Runtime, Transmit,
24};
25use std::collections::{BTreeMap, HashMap, VecDeque};
26use std::fmt;
27use std::future::Future;
28use std::io::{self, IoSliceMut};
29use std::net::{IpAddr, SocketAddr};
30use std::pin::Pin;
31use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
32use std::sync::{Arc, Mutex, MutexGuard, Weak};
33use std::task::{Context, Poll, Wake, Waker};
34use std::time::{Duration, Instant};
35
36/// A runtime on virtual time with an in-memory network (see the [module documentation](self)).
37#[derive(Clone)]
38pub struct MockRuntime {
39    shared: Arc<Shared>,
40}
41
42impl fmt::Debug for MockRuntime {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        f.debug_struct("MockRuntime")
45            .field("elapsed", &self.clock().elapsed())
46            .finish()
47    }
48}
49
50struct Shared {
51    base: Instant,
52    state: Mutex<State>,
53    ready: Mutex<VecDeque<async_task::Runnable>>,
54    running: AtomicBool,
55}
56
57struct State {
58    elapsed: Duration,
59    seq: u64,
60    timers: BTreeMap<(Instant, u64), Timer>,
61    auto_advance: bool,
62    net: Net,
63}
64
65enum Timer {
66    Wake(Waker),
67    Datagram {
68        to: Arc<UdpEndpoint>,
69        from: SocketAddr,
70        /// The destination address of its IP header.
71        destination: IpAddr,
72        data: Vec<u8>,
73        /// The ECN field it was sent with.
74        ecn: u8,
75    },
76    Bytes {
77        to: Arc<Pipe>,
78        data: Vec<u8>,
79    },
80    End {
81        to: Arc<Pipe>,
82        reset: bool,
83    },
84}
85
86fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
87    mutex.lock().unwrap_or_else(|e| e.into_inner())
88}
89
90impl Default for MockRuntime {
91    fn default() -> Self {
92        Self::new()
93    }
94}
95
96impl MockRuntime {
97    /// A runtime whose clock reads the present moment, then moves only when told; loss drawn
98    /// from seed 1.
99    pub fn new() -> Self {
100        Self::with_seed(1)
101    }
102
103    /// As [`new`](Self::new), loss drawn from `seed`.
104    pub fn with_seed(seed: u64) -> Self {
105        Self {
106            shared: Arc::new(Shared {
107                base: Instant::now(),
108                state: Mutex::new(State {
109                    elapsed: Duration::ZERO,
110                    seq: 0,
111                    timers: BTreeMap::new(),
112                    auto_advance: true,
113                    net: Net::new(seed),
114                }),
115                ready: Mutex::new(VecDeque::new()),
116                running: AtomicBool::new(false),
117            }),
118        }
119    }
120
121    /// The virtual clock.
122    pub fn clock(&self) -> MockClock {
123        MockClock {
124            shared: self.shared.clone(),
125        }
126    }
127
128    /// The in-memory network.
129    pub fn net(&self) -> MockNet {
130        MockNet {
131            shared: self.shared.clone(),
132        }
133    }
134
135    /// Whether [`run`](Self::run) moves the clock to the next timer when nothing can run
136    /// (on by default). Off, the clock moves only by [`MockClock::advance`], and `run` panics
137    /// when it would have to wait.
138    pub fn set_auto_advance(&self, on: bool) {
139        lock(&self.shared.state).auto_advance = on;
140    }
141
142    /// Runs the tasks that can run now, without moving the clock.
143    pub fn run_until_idle(&self) {
144        loop {
145            // The queue's lock is not held while a task runs: it may wake others.
146            let next = lock(&self.shared.ready).pop_front();
147            let Some(runnable) = next else {
148                return;
149            };
150            runnable.run();
151        }
152    }
153
154    /// Runs `future` to completion on this thread, with the runtime's tasks, moving the clock
155    /// to the next timer whenever nothing can run.
156    ///
157    /// # Panics
158    ///
159    /// When nothing can run and no timer is pending (the future would wait forever), when
160    /// the clock may not advance by itself and something must wait, and when called from
161    /// inside another `run` of the same runtime.
162    pub fn run<F: Future>(&self, future: F) -> F::Output {
163        assert!(
164            !self.shared.running.swap(true, Ordering::SeqCst),
165            "MockRuntime::run inside MockRuntime::run"
166        );
167        struct Running<'a>(&'a AtomicBool);
168        impl Drop for Running<'_> {
169            fn drop(&mut self) {
170                self.0.store(false, Ordering::SeqCst);
171            }
172        }
173        let _running = Running(&self.shared.running);
174        let woken = Arc::new(Flag(AtomicBool::new(true)));
175        let waker = Waker::from(woken.clone());
176        let mut cx = Context::from_waker(&waker);
177        let mut future = std::pin::pin!(future);
178        loop {
179            if woken.0.swap(false, Ordering::SeqCst)
180                && let Poll::Ready(output) = future.as_mut().poll(&mut cx)
181            {
182                return output;
183            }
184            self.run_until_idle();
185            if woken.0.load(Ordering::SeqCst) || !lock(&self.shared.ready).is_empty() {
186                continue;
187            }
188            let (next, auto) = {
189                let state = lock(&self.shared.state);
190                (
191                    state.timers.keys().next().map(|(at, _)| *at),
192                    state.auto_advance,
193                )
194            };
195            match next {
196                Some(at) if auto => self.clock().advance_to(at),
197                Some(at) => panic!(
198                    "MockRuntime: nothing can run and the next timer ({:?} ahead) waits for MockClock::advance",
199                    at.saturating_duration_since(self.now())
200                ),
201                None => panic!(
202                    "MockRuntime: stalled at {:?}: nothing can run and no timer is pending",
203                    self.clock().elapsed()
204                ),
205            }
206        }
207    }
208
209    fn schedule_timer(&self, at: Instant, timer: Timer) -> (Instant, u64) {
210        let mut state = lock(&self.shared.state);
211        state.seq += 1;
212        let key = (at, state.seq);
213        state.timers.insert(key, timer);
214        key
215    }
216}
217
218struct Flag(AtomicBool);
219
220impl Wake for Flag {
221    fn wake(self: Arc<Self>) {
222        self.0.store(true, Ordering::SeqCst);
223    }
224
225    fn wake_by_ref(self: &Arc<Self>) {
226        self.0.store(true, Ordering::SeqCst);
227    }
228}
229
230/// The virtual clock of a [`MockRuntime`].
231#[derive(Clone)]
232pub struct MockClock {
233    shared: Arc<Shared>,
234}
235
236impl fmt::Debug for MockClock {
237    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238        f.debug_struct("MockClock")
239            .field("elapsed", &self.elapsed())
240            .finish()
241    }
242}
243
244impl MockClock {
245    /// The time on the clock.
246    pub fn now(&self) -> Instant {
247        self.shared.base + lock(&self.shared.state).elapsed
248    }
249
250    /// How far the clock moved since the runtime was made.
251    pub fn elapsed(&self) -> Duration {
252        lock(&self.shared.state).elapsed
253    }
254
255    /// Moves the clock forward by `by`, waking every timer reached on the way, in order, and
256    /// delivering what the network held until then.
257    pub fn advance(&self, by: Duration) {
258        let to = self.now() + by;
259        self.advance_to(to);
260    }
261
262    /// Moves the clock to `to` (never back), as [`advance`](Self::advance).
263    pub fn advance_to(&self, to: Instant) {
264        loop {
265            let due = {
266                let mut state = lock(&self.shared.state);
267                let Some(&key) = state.timers.keys().next().filter(|(at, _)| *at <= to) else {
268                    let target = to.saturating_duration_since(self.shared.base);
269                    state.elapsed = state.elapsed.max(target);
270                    return;
271                };
272                let timer = state.timers.remove(&key).expect("the first timer");
273                let at = key.0.saturating_duration_since(self.shared.base);
274                state.elapsed = state.elapsed.max(at);
275                timer
276            };
277            // Outside the lock: a wake may schedule a task, a delivery takes its socket's.
278            fire(due);
279        }
280    }
281}
282
283fn fire(timer: Timer) {
284    match timer {
285        Timer::Wake(waker) => waker.wake(),
286        Timer::Datagram {
287            to,
288            from,
289            destination,
290            data,
291            ecn,
292        } => to.deliver(from, destination, data, ecn),
293        Timer::Bytes { to, data } => to.push(&data),
294        Timer::End { to, reset } => to.end(reset),
295    }
296}
297
298/// A task of a [`MockRuntime`]; dropping the handle detaches it.
299#[derive(Debug)]
300struct MockTask(Mutex<Option<async_task::Task<()>>>);
301
302impl JoinHandle for MockTask {
303    fn abort(&self) {
304        drop(lock(&self.0).take());
305    }
306
307    fn is_finished(&self) -> bool {
308        lock(&self.0)
309            .as_ref()
310            .is_none_or(async_task::Task::is_finished)
311    }
312
313    fn poll_join(&mut self, cx: &mut Context<'_>) -> Poll<()> {
314        let slot = self.0.get_mut().unwrap_or_else(|e| e.into_inner());
315        let Some(task) = slot.as_mut() else {
316            return Poll::Ready(());
317        };
318        if Pin::new(task).poll(cx).is_pending() {
319            return Poll::Pending;
320        }
321        *slot = None;
322        Poll::Ready(())
323    }
324}
325
326impl Drop for MockTask {
327    fn drop(&mut self) {
328        if let Some(task) = self.0.get_mut().unwrap_or_else(|e| e.into_inner()).take() {
329            task.detach();
330        }
331    }
332}
333
334/// A [`MockRuntime`] timer.
335struct Sleep {
336    runtime: MockRuntime,
337    deadline: Instant,
338    key: Option<(Instant, u64)>,
339}
340
341impl Future for Sleep {
342    type Output = ();
343
344    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
345        if self.runtime.now() >= self.deadline {
346            if let Some(key) = self.key.take() {
347                lock(&self.runtime.shared.state).timers.remove(&key);
348            }
349            return Poll::Ready(());
350        }
351        if let Some(key) = self.key {
352            let mut state = lock(&self.runtime.shared.state);
353            match state.timers.get_mut(&key) {
354                Some(Timer::Wake(waker)) => {
355                    waker.clone_from(cx.waker());
356                    return Poll::Pending;
357                }
358                // Fired (woken) before its deadline was seen: armed again.
359                _ => drop(state),
360            }
361        }
362        let key = self
363            .runtime
364            .schedule_timer(self.deadline, Timer::Wake(cx.waker().clone()));
365        self.key = Some(key);
366        Poll::Pending
367    }
368}
369
370impl Drop for Sleep {
371    fn drop(&mut self) {
372        if let Some(key) = self.key.take() {
373            lock(&self.runtime.shared.state).timers.remove(&key);
374        }
375    }
376}
377
378impl Runtime for MockRuntime {
379    fn spawn(&self, future: BoxFuture<'static, ()>) -> Box<dyn JoinHandle> {
380        let shared = Arc::downgrade(&self.shared);
381        let schedule = move |runnable| {
382            if let Some(shared) = shared.upgrade() {
383                lock(&shared.ready).push_back(runnable);
384            }
385        };
386        let (runnable, task) = async_task::spawn(future, schedule);
387        runnable.schedule();
388        Box::new(MockTask(Mutex::new(Some(task))))
389    }
390
391    fn now(&self) -> Instant {
392        self.clock().now()
393    }
394
395    fn sleep_until(&self, deadline: Instant) -> BoxFuture<'static, ()> {
396        Box::pin(Sleep {
397            runtime: self.clone(),
398            deadline,
399            key: None,
400        })
401    }
402
403    fn bind_udp(&self, local: SocketAddr) -> io::Result<Arc<dyn AsyncUdpSocket>> {
404        let mut state = lock(&self.shared.state);
405        let local = state.net.bind_udp(local)?;
406        let endpoint = Arc::new(UdpEndpoint::new(local));
407        state.net.udp.insert(local, Arc::downgrade(&endpoint));
408        Ok(Arc::new(MockUdp {
409            runtime: self.clone(),
410            endpoint,
411        }))
412    }
413
414    fn bind_udp_multicast(&self, config: &MulticastConfig) -> io::Result<Arc<dyn AsyncUdpSocket>> {
415        let group = SocketAddr::new(config.group, config.port);
416        let mut state = lock(&self.shared.state);
417        let local = SocketAddr::new(unspecified(config.group), config.port);
418        // Joined on the interfaces named, or on the network's default multicast interface of
419        // the family (every interface when none is set).
420        let mut joined: Vec<IpAddr> = config.interfaces_of_family().collect();
421        if joined.is_empty() {
422            joined.extend(
423                state
424                    .net
425                    .default_multicast_interfaces
426                    .iter()
427                    .copied()
428                    .filter(|ip| ip.is_ipv4() == config.group.is_ipv4()),
429            );
430        }
431        let endpoint = Arc::new(UdpEndpoint {
432            joined,
433            ..UdpEndpoint::new(local)
434        });
435        state.net.multicast.push((group, Arc::downgrade(&endpoint)));
436        Ok(Arc::new(MockUdp {
437            runtime: self.clone(),
438            endpoint,
439        }))
440    }
441
442    fn listen_tcp(
443        &self,
444        local: SocketAddr,
445        _reuse_address: bool,
446    ) -> io::Result<Arc<dyn AsyncTcpListener>> {
447        let mut state = lock(&self.shared.state);
448        let local = state.net.bind_tcp(local)?;
449        let listener = Arc::new(ListenerEndpoint {
450            local,
451            queue: Mutex::new((VecDeque::new(), None)),
452        });
453        state.net.listeners.insert(local, Arc::downgrade(&listener));
454        Ok(Arc::new(MockListener {
455            runtime: self.clone(),
456            endpoint: listener,
457        }))
458    }
459
460    fn connect_tcp(
461        &self,
462        local: SocketAddr,
463        remote: SocketAddr,
464        _reuse_address: bool,
465    ) -> BoxFuture<'static, io::Result<Arc<dyn AsyncTcpStream>>> {
466        let runtime = self.clone();
467        Box::pin(async move {
468            let (local, link, listener) = {
469                let mut state = lock(&runtime.shared.state);
470                let local = state.net.bind_tcp(local)?;
471                let link = state.net.link(local.ip(), remote.ip());
472                let listener = state.net.listener(remote);
473                (local, link, listener)
474            };
475            if link.blocked {
476                // Nothing answers: the driver's connect timeout ends it.
477                std::future::pending::<()>().await;
478            }
479            // The handshake: one round trip.
480            super::sleep(&runtime, link.delay * 2).await;
481            let Some(listener) = listener else {
482                return Err(io::Error::from(io::ErrorKind::ConnectionRefused));
483            };
484            let to_client = Arc::new(Pipe::default());
485            let to_server = Arc::new(Pipe::default());
486            let client = Arc::new(MockTcp {
487                runtime: runtime.clone(),
488                local,
489                peer: remote,
490                incoming: to_client.clone(),
491                outgoing: to_server.clone(),
492                state: Mutex::new(TcpEnd::default()),
493            });
494            let server: Arc<dyn AsyncTcpStream> = Arc::new(MockTcp {
495                runtime: runtime.clone(),
496                local: listener.local_for(remote),
497                peer: local,
498                incoming: to_server,
499                outgoing: to_client,
500                state: Mutex::new(TcpEnd::default()),
501            });
502            listener.push(server, local);
503            Ok(client as Arc<dyn AsyncTcpStream>)
504        })
505    }
506
507    fn resolve_host(
508        &self,
509        host: &str,
510        port: u16,
511    ) -> BoxFuture<'static, io::Result<Vec<SocketAddr>>> {
512        let found = match host.parse::<IpAddr>() {
513            Ok(ip) => Ok(vec![SocketAddr::new(ip, port)]),
514            Err(_) => lock(&self.shared.state)
515                .net
516                .hosts
517                .get(host)
518                .map(|ips| ips.iter().map(|ip| SocketAddr::new(*ip, port)).collect())
519                .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, host.to_owned())),
520        };
521        Box::pin(std::future::ready(found))
522    }
523
524    fn block_on(&self, future: Pin<Box<dyn Future<Output = ()> + '_>>) {
525        self.run(future);
526    }
527
528    fn virtual_clock(&self) -> bool {
529        true
530    }
531
532    fn interfaces(&self) -> io::Result<Vec<crate::runtime::LocalInterface>> {
533        Ok(lock(&self.shared.state).net.interfaces.clone())
534    }
535
536    fn route_source(&self, destination: IpAddr) -> Option<IpAddr> {
537        let state = lock(&self.shared.state);
538        state.net.routes.get(&destination).copied().or_else(|| {
539            state
540                .net
541                .preferred_sources
542                .iter()
543                .copied()
544                .find(|ip| ip.is_ipv6() == destination.is_ipv6())
545        })
546    }
547
548    fn preferred_source(&self, ipv6: bool) -> Option<IpAddr> {
549        lock(&self.shared.state)
550            .net
551            .preferred_sources
552            .iter()
553            .copied()
554            .find(|ip| ip.is_ipv6() == ipv6)
555    }
556}
557
558fn unspecified(ip: IpAddr) -> IpAddr {
559    match ip {
560        IpAddr::V4(_) => IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED),
561        IpAddr::V6(_) => IpAddr::V6(std::net::Ipv6Addr::UNSPECIFIED),
562    }
563}
564
565/// One direction between two IP addresses of the [`MockNet`].
566#[derive(Debug, Clone, Copy, PartialEq)]
567#[non_exhaustive]
568pub struct LinkConfig {
569    /// One-way delay (TCP's handshake takes two).
570    pub delay: Duration,
571    /// The share of datagrams lost, 0.0 to 1.0, drawn from the runtime's seed.
572    pub loss: f64,
573    /// Nothing passes: datagrams are lost, connection attempts never complete.
574    pub blocked: bool,
575    /// Extra delay per datagram, uniform between zero and this, drawn from the runtime's
576    /// seed. UDP only (TCP takes `delay`).
577    pub jitter: Duration,
578    /// Whether jitter may reorder datagrams. Off: a datagram never arrives before one sent
579    /// earlier on the link (the delay variation of one queue); on: each is delayed on its own
580    /// (several paths).
581    pub reorder: bool,
582    /// The link's capacity in bits per second (`None`: unlimited): each datagram takes its
583    /// size at this rate to leave, after those before it. UDP only.
584    pub rate_bps: Option<u64>,
585    /// With a rate: how long a datagram may wait for the link before it is dropped
586    /// ([`Fate::QueueFull`], a drop-tail queue), as time at the link's rate.
587    pub queue: Duration,
588}
589
590impl LinkConfig {
591    /// No delay, no loss, no jitter, no rate limit ([`Default`]).
592    pub fn new() -> Self {
593        Self::default()
594    }
595
596    /// With a one-way [`delay`](Self::delay).
597    #[must_use]
598    pub fn with_delay(mut self, delay: Duration) -> Self {
599        self.delay = delay;
600        self
601    }
602    /// With a [`loss`](Self::loss) rate.
603    #[must_use]
604    pub fn with_loss(mut self, loss: f64) -> Self {
605        self.loss = loss;
606        self
607    }
608    /// [`blocked`](Self::blocked) or not.
609    #[must_use]
610    pub fn with_blocked(mut self, blocked: bool) -> Self {
611        self.blocked = blocked;
612        self
613    }
614    /// With a [`jitter`](Self::jitter).
615    #[must_use]
616    pub fn with_jitter(mut self, jitter: Duration) -> Self {
617        self.jitter = jitter;
618        self
619    }
620    /// Whether jitter may [`reorder`](Self::reorder).
621    #[must_use]
622    pub fn with_reorder(mut self, reorder: bool) -> Self {
623        self.reorder = reorder;
624        self
625    }
626    /// With a rate limit ([`rate_bps`](Self::rate_bps)).
627    #[must_use]
628    pub fn with_rate_bps(mut self, rate_bps: u64) -> Self {
629        self.rate_bps = Some(rate_bps);
630        self
631    }
632    /// With a [`queue`](Self::queue) for the rate limit.
633    #[must_use]
634    pub fn with_queue(mut self, queue: Duration) -> Self {
635        self.queue = queue;
636        self
637    }
638}
639
640impl Default for LinkConfig {
641    /// No delay, no loss, no jitter, no rate limit (a 300 ms queue once a rate is set).
642    fn default() -> Self {
643        Self {
644            delay: Duration::ZERO,
645            loss: 0.0,
646            blocked: false,
647            jitter: Duration::ZERO,
648            reorder: false,
649            rate_bps: None,
650            queue: Duration::from_millis(300),
651        }
652    }
653}
654
655/// A datagram as the [`MockNet`] sees it, for a filter.
656#[derive(Debug, Clone, Copy)]
657pub struct MockDatagram<'a> {
658    /// When it was sent.
659    pub at: Instant,
660    /// The sender's address.
661    pub from: SocketAddr,
662    /// Where to (a multicast group for a multicast datagram).
663    pub to: SocketAddr,
664    /// The bytes.
665    pub data: &'a [u8],
666}
667
668/// What became of a datagram.
669#[derive(Debug, Clone, Copy, PartialEq, Eq)]
670pub enum Fate {
671    /// Delivered (or on its way) to this many sockets.
672    Delivered(usize),
673    /// Nobody was bound there.
674    Unbound,
675    /// The link was blocked.
676    Blocked,
677    /// Lost to the link's loss rate.
678    Lost,
679    /// Dropped by the filter.
680    Filtered,
681    /// The sending socket's system refused it ([`MockNet::set_send_error`]): the send
682    /// returned the error.
683    SendError,
684    /// Dropped at the tail of a rate-limited link's full queue ([`LinkConfig::rate_bps`],
685    /// [`LinkConfig::queue`]).
686    QueueFull,
687}
688
689/// One datagram of the [`MockNet::log`].
690#[derive(Debug, Clone, PartialEq, Eq)]
691pub struct DatagramRecord {
692    /// When it was sent.
693    pub at: Instant,
694    /// The sender.
695    pub from: SocketAddr,
696    /// Where to.
697    pub to: SocketAddr,
698    /// Its size.
699    pub len: usize,
700    /// The TOS / Traffic Class byte it was sent with.
701    pub traffic_class: u8,
702    /// Whether its socket had Don't Fragment set
703    /// ([`AsyncUdpSocket::set_dont_fragment`](crate::runtime::AsyncUdpSocket::set_dont_fragment)).
704    pub dont_fragment: bool,
705    /// What became of it.
706    pub fate: Fate,
707}
708
709/// A filter of the [`MockNet`]: `false` drops the datagram.
710pub type DatagramFilter = Box<dyn FnMut(&MockDatagram<'_>) -> bool + Send>;
711
712/// The in-memory network of a [`MockRuntime`].
713#[derive(Clone)]
714pub struct MockNet {
715    shared: Arc<Shared>,
716}
717
718impl fmt::Debug for MockNet {
719    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
720        f.debug_struct("MockNet").finish_non_exhaustive()
721    }
722}
723
724impl MockNet {
725    /// Every link not set otherwise.
726    pub fn set_default_link(&self, link: LinkConfig) {
727        lock(&self.shared.state).net.default_link = link;
728    }
729
730    /// The link from `from` to `to` (one direction).
731    pub fn set_link(&self, from: IpAddr, to: IpAddr, link: LinkConfig) {
732        lock(&self.shared.state).net.links.insert((from, to), link);
733    }
734
735    /// Both directions between `a` and `b`.
736    pub fn set_links(&self, a: IpAddr, b: IpAddr, link: LinkConfig) {
737        self.set_link(a, b, link);
738        self.set_link(b, a, link);
739    }
740
741    /// Drops every datagram `filter` returns `false` for (after the link's own fate).
742    pub fn set_filter(&self, filter: DatagramFilter) {
743        lock(&self.shared.state).net.filter = Some(filter);
744    }
745
746    /// No filter.
747    pub fn clear_filter(&self) {
748        lock(&self.shared.state).net.filter = None;
749    }
750
751    /// `name` resolves to `ips`.
752    pub fn add_host(&self, name: &str, ips: Vec<IpAddr>) {
753        lock(&self.shared.state)
754            .net
755            .hosts
756            .insert(name.to_owned(), ips);
757    }
758
759    /// The interface a multicast socket of `ip`'s family joins on, and sends from, when it
760    /// is bound without interfaces ([`MulticastConfig::interfaces`] empty): the host's default
761    /// multicast interface. Without one, such a socket is joined on every interface. A
762    /// multicast datagram reaches a socket joined on an interface whose link from the sender's
763    /// address is not blocked ([`set_link`](Self::set_link)).
764    pub fn set_default_multicast_interface(&self, ip: IpAddr) {
765        let mut state = lock(&self.shared.state);
766        let interfaces = &mut state.net.default_multicast_interfaces;
767        interfaces.retain(|other| other.is_ipv4() != ip.is_ipv4());
768        interfaces.push(ip);
769    }
770
771    /// Every send to `to` (an address, a multicast group included) fails with `error`, as
772    /// when the system has no route there (`HostUnreachable`) or refuses the application
773    /// (`PermissionDenied`); `None` lets them through again.
774    pub fn set_send_error(&self, to: IpAddr, error: Option<io::ErrorKind>) {
775        let mut state = lock(&self.shared.state);
776        match error {
777            Some(kind) => {
778                state.net.send_errors.insert(to, kind);
779            }
780            None => {
781                state.net.send_errors.remove(&to);
782            }
783        }
784    }
785
786    /// Every datagram sent so far, in order.
787    pub fn log(&self) -> Vec<DatagramRecord> {
788        lock(&self.shared.state).net.log.clone()
789    }
790
791    /// The host's interface addresses, as [`Runtime::interfaces`] of the runtime reports them
792    /// (none until set): what a driver's address selection
793    /// ([`crate::sockets::AddressSelection`]) sees. Setting them again mid-run is a host that
794    /// moved to another network: the next gathering (an ICE restart's) selects from the new
795    /// list. Sockets already bound stay bound.
796    pub fn set_interfaces(&self, interfaces: Vec<crate::runtime::LocalInterface>) {
797        lock(&self.shared.state).net.interfaces = interfaces;
798    }
799
800    /// The source address the routing table picks towards `destination`
801    /// ([`Runtime::route_source`]); a destination without one takes the preferred source of
802    /// its family ([`set_preferred_source`](Self::set_preferred_source)).
803    pub fn set_route(&self, destination: IpAddr, source: IpAddr) {
804        lock(&self.shared.state)
805            .net
806            .routes
807            .insert(destination, source);
808    }
809
810    /// The address [`Runtime::preferred_source`] reports for its family (the default route's
811    /// source address); `None` for neither family before one is set.
812    pub fn set_preferred_source(&self, ip: IpAddr) {
813        let mut state = lock(&self.shared.state);
814        let preferred = &mut state.net.preferred_sources;
815        preferred.retain(|other| other.is_ipv4() != ip.is_ipv4());
816        preferred.push(ip);
817    }
818}
819
820struct Net {
821    udp: HashMap<SocketAddr, Weak<UdpEndpoint>>,
822    multicast: Vec<(SocketAddr, Weak<UdpEndpoint>)>,
823    default_multicast_interfaces: Vec<IpAddr>,
824    send_errors: HashMap<IpAddr, io::ErrorKind>,
825    listeners: HashMap<SocketAddr, Weak<ListenerEndpoint>>,
826    tcp_ports: HashMap<SocketAddr, usize>,
827    /// The next ephemeral port of each address: each address has its own ports, as on a real
828    /// host, so two addresses can be given the same port.
829    next_port: HashMap<IpAddr, u16>,
830    default_link: LinkConfig,
831    links: HashMap<(IpAddr, IpAddr), LinkConfig>,
832    filter: Option<DatagramFilter>,
833    hosts: HashMap<String, Vec<IpAddr>>,
834    log: Vec<DatagramRecord>,
835    rng: u64,
836    interfaces: Vec<crate::runtime::LocalInterface>,
837    preferred_sources: Vec<IpAddr>,
838    routes: HashMap<IpAddr, IpAddr>,
839    /// Per direction: when the link's last datagram arrives (no reordering) and when a
840    /// rate-limited link is free again.
841    last_arrival: HashMap<(IpAddr, IpAddr), Instant>,
842    busy_until: HashMap<(IpAddr, IpAddr), Instant>,
843}
844
845impl Net {
846    fn new(seed: u64) -> Self {
847        Self {
848            udp: HashMap::new(),
849            multicast: Vec::new(),
850            default_multicast_interfaces: Vec::new(),
851            send_errors: HashMap::new(),
852            listeners: HashMap::new(),
853            tcp_ports: HashMap::new(),
854            next_port: HashMap::new(),
855            default_link: LinkConfig::default(),
856            links: HashMap::new(),
857            filter: None,
858            hosts: HashMap::new(),
859            log: Vec::new(),
860            // xorshift64 needs a state other than 0.
861            rng: seed.max(1),
862            interfaces: Vec::new(),
863            preferred_sources: Vec::new(),
864            routes: HashMap::new(),
865            last_arrival: HashMap::new(),
866            busy_until: HashMap::new(),
867        }
868    }
869
870    fn link(&self, from: IpAddr, to: IpAddr) -> LinkConfig {
871        self.links
872            .get(&(from, to))
873            .copied()
874            .unwrap_or(self.default_link)
875    }
876
877    /// When a datagram of `len` bytes sent at `now` on `link` (from `from` to `to`) arrives:
878    /// after the rate-limited link is free and has carried it, the delay and a draw of the
879    /// jitter, never before the link's previous datagram unless the link reorders. `None`:
880    /// the rate-limited link's queue is full.
881    fn arrival(
882        &mut self,
883        link: &LinkConfig,
884        from: IpAddr,
885        to: IpAddr,
886        now: Instant,
887        len: usize,
888    ) -> Option<Instant> {
889        let key = (from, to);
890        let mut departs = now;
891        if let Some(rate) = link.rate_bps.filter(|r| *r > 0) {
892            let start = self.busy_until.get(&key).copied().unwrap_or(now).max(now);
893            if start.duration_since(now) > link.queue {
894                return None;
895            }
896            let bits = (len as u64).saturating_mul(8);
897            let carry = Duration::from_nanos(bits.saturating_mul(1_000_000_000) / rate);
898            departs = start + carry;
899            self.busy_until.insert(key, departs);
900        }
901        let mut at = departs + link.delay;
902        if !link.jitter.is_zero() {
903            at += link.jitter.mul_f64(self.draw());
904        }
905        if !link.reorder {
906            if let Some(last) = self.last_arrival.get(&key) {
907                at = at.max(*last);
908            }
909            self.last_arrival.insert(key, at);
910        }
911        Some(at)
912    }
913
914    /// A uniform draw in [0, 1) (xorshift64).
915    fn draw(&mut self) -> f64 {
916        let mut x = self.rng;
917        x ^= x << 13;
918        x ^= x >> 7;
919        x ^= x << 17;
920        self.rng = x;
921        (x >> 11) as f64 / (1u64 << 53) as f64
922    }
923
924    fn bind_udp(&mut self, local: SocketAddr) -> io::Result<SocketAddr> {
925        self.udp.retain(|_, e| e.strong_count() > 0);
926        let ip = local.ip();
927        let port = match local.port() {
928            0 => {
929                let udp = &self.udp;
930                free_port(self.next_port.entry(ip).or_insert(49152), |p| {
931                    udp.contains_key(&SocketAddr::new(ip, p))
932                })?
933            }
934            port => port,
935        };
936        let local = SocketAddr::new(ip, port);
937        if self.udp.contains_key(&local) {
938            return Err(io::Error::from(io::ErrorKind::AddrInUse));
939        }
940        Ok(local)
941    }
942
943    fn bind_tcp(&mut self, local: SocketAddr) -> io::Result<SocketAddr> {
944        self.listeners.retain(|_, l| l.strong_count() > 0);
945        let ip = local.ip();
946        let port = match local.port() {
947            0 => {
948                let listeners = &self.listeners;
949                let ports = &self.tcp_ports;
950                free_port(self.next_port.entry(ip).or_insert(49152), |p| {
951                    let addr = SocketAddr::new(ip, p);
952                    listeners.contains_key(&addr) || ports.contains_key(&addr)
953                })?
954            }
955            port => port,
956        };
957        let local = SocketAddr::new(ip, port);
958        if self.listeners.contains_key(&local) {
959            return Err(io::Error::from(io::ErrorKind::AddrInUse));
960        }
961        *self.tcp_ports.entry(local).or_default() += 1;
962        Ok(local)
963    }
964
965    fn listener(&self, remote: SocketAddr) -> Option<Arc<ListenerEndpoint>> {
966        self.listeners
967            .get(&remote)
968            .or_else(|| {
969                self.listeners
970                    .get(&SocketAddr::new(unspecified(remote.ip()), remote.port()))
971            })
972            .and_then(Weak::upgrade)
973    }
974
975    /// The sockets a datagram to `to` reaches.
976    fn receivers(&self, from: IpAddr, to: SocketAddr) -> Vec<Arc<UdpEndpoint>> {
977        if to.ip().is_multicast() {
978            return self
979                .multicast
980                .iter()
981                .filter(|(group, _)| *group == to)
982                .filter_map(|(_, e)| e.upgrade())
983                .filter(|e| {
984                    e.joined.is_empty()
985                        || e.joined
986                            .iter()
987                            .any(|interface| !self.link(from, *interface).blocked)
988                })
989                .collect();
990        }
991        self.udp
992            .get(&to)
993            .or_else(|| {
994                self.udp
995                    .get(&SocketAddr::new(unspecified(to.ip()), to.port()))
996            })
997            .and_then(Weak::upgrade)
998            .into_iter()
999            .collect()
1000    }
1001}
1002
1003/// The next ephemeral port (49152 and up) that `taken` does not hold.
1004fn free_port(next: &mut u16, taken: impl Fn(u16) -> bool) -> io::Result<u16> {
1005    for _ in 0..16384 {
1006        let port = *next;
1007        *next = if *next == u16::MAX { 49152 } else { *next + 1 };
1008        if !taken(port) {
1009            return Ok(port);
1010        }
1011    }
1012    Err(io::Error::from(io::ErrorKind::AddrInUse))
1013}
1014
1015/// A datagram waiting in a mock socket: its sender, the destination address it was sent to
1016/// (a multicast group, or the socket's own), its bytes, and the ECN field it was sent with
1017/// (the mock network neither clears nor marks it).
1018type Received = (SocketAddr, IpAddr, Vec<u8>, u8);
1019
1020struct UdpEndpoint {
1021    local: SocketAddr,
1022    /// A multicast socket's interfaces (their addresses); empty: every one.
1023    joined: Vec<IpAddr>,
1024    inbox: Mutex<(VecDeque<Received>, Option<Waker>)>,
1025    traffic_class: AtomicU8,
1026    dont_fragment: AtomicBool,
1027}
1028
1029impl UdpEndpoint {
1030    fn new(local: SocketAddr) -> Self {
1031        Self {
1032            local,
1033            joined: Vec::new(),
1034            inbox: Mutex::new((VecDeque::new(), None)),
1035            traffic_class: AtomicU8::new(0),
1036            dont_fragment: AtomicBool::new(false),
1037        }
1038    }
1039
1040    fn deliver(&self, from: SocketAddr, destination: IpAddr, data: Vec<u8>, ecn: u8) {
1041        let waker = {
1042            let mut inbox = lock(&self.inbox);
1043            inbox.0.push_back((from, destination, data, ecn));
1044            inbox.1.take()
1045        };
1046        if let Some(waker) = waker {
1047            waker.wake();
1048        }
1049    }
1050}
1051
1052/// A UDP socket of a [`MockRuntime`].
1053struct MockUdp {
1054    runtime: MockRuntime,
1055    endpoint: Arc<UdpEndpoint>,
1056}
1057
1058impl fmt::Debug for MockUdp {
1059    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1060        f.debug_struct("MockUdp")
1061            .field("local", &self.endpoint.local)
1062            .finish()
1063    }
1064}
1065
1066impl AsyncUdpSocket for MockUdp {
1067    fn poll_send(&self, _: &mut Context<'_>, transmit: &Transmit<'_>) -> Poll<io::Result<usize>> {
1068        self.endpoint
1069            .traffic_class
1070            .store(transmit.traffic_class, Ordering::Relaxed);
1071        let now = self.runtime.now();
1072        // A socket bound to the unspecified address (the mDNS sockets) sends from the address
1073        // the transmit names, as a real one does from its interface's address, or else from the
1074        // first interface it joined.
1075        let local = self.endpoint.local;
1076        let from = match transmit.source {
1077            Some(ip) if local.ip().is_unspecified() && ip.is_ipv4() == local.is_ipv4() => {
1078                SocketAddr::new(ip, local.port())
1079            }
1080            _ if local.ip().is_unspecified() => self
1081                .endpoint
1082                .joined
1083                .first()
1084                .map_or(local, |ip| SocketAddr::new(*ip, local.port())),
1085            _ => local,
1086        };
1087        let to = transmit.destination;
1088        let mut deliveries = Vec::new();
1089        let mut arrival = now;
1090        {
1091            let mut state = lock(&self.runtime.shared.state);
1092            let net = &mut state.net;
1093            if let Some(kind) = net.send_errors.get(&to.ip()).copied() {
1094                net.log.push(DatagramRecord {
1095                    at: now,
1096                    from,
1097                    to,
1098                    len: transmit.contents.len(),
1099                    traffic_class: transmit.traffic_class,
1100                    dont_fragment: self.endpoint.dont_fragment.load(Ordering::Relaxed),
1101                    fate: Fate::SendError,
1102                });
1103                return Poll::Ready(Err(kind.into()));
1104            }
1105            let link = net.link(from.ip(), to.ip());
1106            let receivers = net.receivers(from.ip(), to);
1107            let fate = if link.blocked {
1108                Fate::Blocked
1109            } else if link.loss > 0.0 && net.draw() < link.loss {
1110                Fate::Lost
1111            } else if !net.filter.as_mut().is_none_or(|keep| {
1112                keep(&MockDatagram {
1113                    at: now,
1114                    from,
1115                    to,
1116                    data: transmit.contents,
1117                })
1118            }) {
1119                Fate::Filtered
1120            } else if receivers.is_empty() {
1121                Fate::Unbound
1122            } else {
1123                match net.arrival(&link, from.ip(), to.ip(), now, transmit.contents.len()) {
1124                    Some(at) => {
1125                        arrival = at;
1126                        Fate::Delivered(receivers.len())
1127                    }
1128                    None => Fate::QueueFull,
1129                }
1130            };
1131            net.log.push(DatagramRecord {
1132                at: now,
1133                from,
1134                to,
1135                len: transmit.contents.len(),
1136                traffic_class: transmit.traffic_class,
1137                dont_fragment: self.endpoint.dont_fragment.load(Ordering::Relaxed),
1138                fate,
1139            });
1140            if let Fate::Delivered(_) = fate {
1141                deliveries = receivers;
1142            }
1143        }
1144        for receiver in deliveries {
1145            let data = transmit.contents.to_vec();
1146            if arrival <= now {
1147                receiver.deliver(from, to.ip(), data, transmit.traffic_class & 0b11);
1148            } else {
1149                self.runtime.schedule_timer(
1150                    arrival,
1151                    Timer::Datagram {
1152                        to: receiver,
1153                        from,
1154                        destination: to.ip(),
1155                        data,
1156                        ecn: transmit.traffic_class & 0b11,
1157                    },
1158                );
1159            }
1160        }
1161        Poll::Ready(Ok(transmit.contents.len()))
1162    }
1163
1164    fn poll_recv(
1165        &self,
1166        cx: &mut Context<'_>,
1167        bufs: &mut [IoSliceMut<'_>],
1168        meta: &mut [RecvMeta],
1169    ) -> Poll<io::Result<usize>> {
1170        let mut inbox = lock(&self.endpoint.inbox);
1171        let mut filled = 0;
1172        while filled < bufs.len().min(meta.len()) {
1173            let Some((from, destination, data, ecn)) = inbox.0.pop_front() else {
1174                break;
1175            };
1176            let len = data.len().min(bufs[filled].len());
1177            bufs[filled][..len].copy_from_slice(&data[..len]);
1178            meta[filled] = RecvMeta {
1179                addr: from,
1180                len,
1181                stride: len,
1182                // The ECN field, as `IP_RECVTOS` / `IPV6_RECVTCLASS` report it.
1183                ecn: Some(ecn),
1184                // The destination of the IP header, as `IP_PKTINFO` reports it.
1185                dst_ip: Some(destination),
1186            };
1187            filled += 1;
1188        }
1189        if filled == 0 {
1190            inbox.1 = Some(cx.waker().clone());
1191            return Poll::Pending;
1192        }
1193        Poll::Ready(Ok(filled))
1194    }
1195
1196    fn local_addr(&self) -> io::Result<SocketAddr> {
1197        Ok(self.endpoint.local)
1198    }
1199
1200    fn max_receive_batch(&self) -> usize {
1201        64
1202    }
1203
1204    fn traffic_class(&self) -> io::Result<u32> {
1205        Ok(u32::from(
1206            self.endpoint.traffic_class.load(Ordering::Relaxed),
1207        ))
1208    }
1209
1210    fn set_dont_fragment(&self, on: bool) -> io::Result<()> {
1211        self.endpoint.dont_fragment.store(on, Ordering::Relaxed);
1212        Ok(())
1213    }
1214}
1215
1216/// One direction of a mock TCP connection.
1217#[derive(Default)]
1218struct Pipe(Mutex<PipeState>);
1219
1220#[derive(Default)]
1221struct PipeState {
1222    bytes: VecDeque<u8>,
1223    eof: bool,
1224    reset: bool,
1225    reader: Option<Waker>,
1226}
1227
1228impl Pipe {
1229    fn push(&self, data: &[u8]) {
1230        let waker = {
1231            let mut pipe = lock(&self.0);
1232            pipe.bytes.extend(data);
1233            pipe.reader.take()
1234        };
1235        if let Some(waker) = waker {
1236            waker.wake();
1237        }
1238    }
1239
1240    fn end(&self, reset: bool) {
1241        let waker = {
1242            let mut pipe = lock(&self.0);
1243            if reset {
1244                pipe.reset = true;
1245                pipe.bytes.clear();
1246            } else {
1247                pipe.eof = true;
1248            }
1249            pipe.reader.take()
1250        };
1251        if let Some(waker) = waker {
1252            waker.wake();
1253        }
1254    }
1255}
1256
1257#[derive(Default)]
1258struct TcpEnd {
1259    shut: bool,
1260    reset_on_close: bool,
1261    traffic_class: u8,
1262}
1263
1264/// A TCP connection end of a [`MockRuntime`].
1265struct MockTcp {
1266    runtime: MockRuntime,
1267    local: SocketAddr,
1268    peer: SocketAddr,
1269    incoming: Arc<Pipe>,
1270    outgoing: Arc<Pipe>,
1271    state: Mutex<TcpEnd>,
1272}
1273
1274impl fmt::Debug for MockTcp {
1275    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1276        f.debug_struct("MockTcp")
1277            .field("local", &self.local)
1278            .field("peer", &self.peer)
1279            .finish()
1280    }
1281}
1282
1283impl MockTcp {
1284    /// Sends `timer` toward the peer after the link's delay.
1285    fn toward_peer(&self, timer: Timer) {
1286        let delay = lock(&self.runtime.shared.state)
1287            .net
1288            .link(self.local.ip(), self.peer.ip())
1289            .delay;
1290        if delay.is_zero() {
1291            fire(timer);
1292        } else {
1293            let at = self.runtime.now() + delay;
1294            self.runtime.schedule_timer(at, timer);
1295        }
1296    }
1297}
1298
1299impl AsyncTcpStream for MockTcp {
1300    fn poll_read(&self, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<io::Result<usize>> {
1301        let mut pipe = lock(&self.incoming.0);
1302        if pipe.reset {
1303            return Poll::Ready(Err(io::Error::from(io::ErrorKind::ConnectionReset)));
1304        }
1305        if pipe.bytes.is_empty() {
1306            if pipe.eof {
1307                return Poll::Ready(Ok(0));
1308            }
1309            pipe.reader = Some(cx.waker().clone());
1310            return Poll::Pending;
1311        }
1312        let n = buf.len().min(pipe.bytes.len());
1313        for (slot, byte) in buf.iter_mut().zip(pipe.bytes.drain(..n)) {
1314            *slot = byte;
1315        }
1316        Poll::Ready(Ok(n))
1317    }
1318
1319    fn poll_write(&self, _: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
1320        if lock(&self.state).shut {
1321            return Poll::Ready(Err(io::Error::from(io::ErrorKind::BrokenPipe)));
1322        }
1323        if lock(&self.outgoing.0).reset {
1324            return Poll::Ready(Err(io::Error::from(io::ErrorKind::ConnectionReset)));
1325        }
1326        self.toward_peer(Timer::Bytes {
1327            to: self.outgoing.clone(),
1328            data: buf.to_vec(),
1329        });
1330        Poll::Ready(Ok(buf.len()))
1331    }
1332
1333    fn shutdown_write(&self) -> io::Result<()> {
1334        let first = !std::mem::replace(&mut lock(&self.state).shut, true);
1335        if first {
1336            self.toward_peer(Timer::End {
1337                to: self.outgoing.clone(),
1338                reset: false,
1339            });
1340        }
1341        Ok(())
1342    }
1343
1344    fn reset_on_close(&self) -> io::Result<()> {
1345        lock(&self.state).reset_on_close = true;
1346        Ok(())
1347    }
1348
1349    fn set_traffic_class(&self, value: u8) -> io::Result<u32> {
1350        lock(&self.state).traffic_class = value;
1351        Ok(u32::from(value))
1352    }
1353
1354    fn local_addr(&self) -> io::Result<SocketAddr> {
1355        Ok(self.local)
1356    }
1357
1358    fn peer_addr(&self) -> io::Result<SocketAddr> {
1359        Ok(self.peer)
1360    }
1361}
1362
1363impl Drop for MockTcp {
1364    fn drop(&mut self) {
1365        let (shut, reset) = {
1366            let state = lock(&self.state);
1367            (state.shut, state.reset_on_close)
1368        };
1369        if reset {
1370            self.toward_peer(Timer::End {
1371                to: self.outgoing.clone(),
1372                reset: true,
1373            });
1374        } else if !shut {
1375            self.toward_peer(Timer::End {
1376                to: self.outgoing.clone(),
1377                reset: false,
1378            });
1379        }
1380        if let Some(count) = lock(&self.runtime.shared.state)
1381            .net
1382            .tcp_ports
1383            .get_mut(&self.local)
1384        {
1385            *count = count.saturating_sub(1);
1386        }
1387    }
1388}
1389
1390type Pending = (Arc<dyn AsyncTcpStream>, SocketAddr);
1391
1392struct ListenerEndpoint {
1393    local: SocketAddr,
1394    queue: Mutex<(VecDeque<Pending>, Option<Waker>)>,
1395}
1396
1397impl ListenerEndpoint {
1398    fn push(&self, stream: Arc<dyn AsyncTcpStream>, remote: SocketAddr) {
1399        let waker = {
1400            let mut queue = lock(&self.queue);
1401            queue.0.push_back((stream, remote));
1402            queue.1.take()
1403        };
1404        if let Some(waker) = waker {
1405            waker.wake();
1406        }
1407    }
1408
1409    /// The local address a connection from `remote` has on this listener.
1410    fn local_for(&self, remote: SocketAddr) -> SocketAddr {
1411        if self.local.ip().is_unspecified() {
1412            SocketAddr::new(remote.ip(), self.local.port())
1413        } else {
1414            self.local
1415        }
1416    }
1417}
1418
1419/// A TCP listener of a [`MockRuntime`].
1420struct MockListener {
1421    runtime: MockRuntime,
1422    endpoint: Arc<ListenerEndpoint>,
1423}
1424
1425impl fmt::Debug for MockListener {
1426    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1427        f.debug_struct("MockListener")
1428            .field("local", &self.endpoint.local)
1429            .finish()
1430    }
1431}
1432
1433impl AsyncTcpListener for MockListener {
1434    fn poll_accept(&self, cx: &mut Context<'_>) -> Poll<io::Result<Pending>> {
1435        let mut queue = lock(&self.endpoint.queue);
1436        match queue.0.pop_front() {
1437            Some(accepted) => Poll::Ready(Ok(accepted)),
1438            None => {
1439                queue.1 = Some(cx.waker().clone());
1440                Poll::Pending
1441            }
1442        }
1443    }
1444
1445    fn local_addr(&self) -> io::Result<SocketAddr> {
1446        Ok(self.endpoint.local)
1447    }
1448}
1449
1450impl Drop for MockListener {
1451    fn drop(&mut self) {
1452        let mut state = lock(&self.runtime.shared.state);
1453        if let Some(count) = state.net.tcp_ports.get_mut(&self.endpoint.local) {
1454            *count = count.saturating_sub(1);
1455        }
1456    }
1457}