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    /// The next `sends` sends from a UDP socket of `from` find it not ready (`Pending`, the
787    /// datagram not taken), as a real socket is before the runtime's reactor reports it
788    /// writable (the first send after the bind); each such send wakes its task at once, as
789    /// the reactor does when the readiness comes, and a later send goes through. A
790    /// [`try_send`](crate::runtime::AsyncUdpSocket::try_send) sees `WouldBlock`.
791    pub fn set_send_not_ready(&self, from: IpAddr, sends: usize) {
792        lock(&self.shared.state).net.not_ready.insert(from, sends);
793    }
794
795    /// Every datagram sent so far, in order.
796    pub fn log(&self) -> Vec<DatagramRecord> {
797        lock(&self.shared.state).net.log.clone()
798    }
799
800    /// The host's interface addresses, as [`Runtime::interfaces`] of the runtime reports them
801    /// (none until set): what a driver's address selection
802    /// ([`crate::sockets::AddressSelection`]) sees. Setting them again mid-run is a host that
803    /// moved to another network: the next gathering (an ICE restart's) selects from the new
804    /// list. Sockets already bound stay bound.
805    pub fn set_interfaces(&self, interfaces: Vec<crate::runtime::LocalInterface>) {
806        lock(&self.shared.state).net.interfaces = interfaces;
807    }
808
809    /// The source address the routing table picks towards `destination`
810    /// ([`Runtime::route_source`]); a destination without one takes the preferred source of
811    /// its family ([`set_preferred_source`](Self::set_preferred_source)).
812    pub fn set_route(&self, destination: IpAddr, source: IpAddr) {
813        lock(&self.shared.state)
814            .net
815            .routes
816            .insert(destination, source);
817    }
818
819    /// The address [`Runtime::preferred_source`] reports for its family (the default route's
820    /// source address); `None` for neither family before one is set.
821    pub fn set_preferred_source(&self, ip: IpAddr) {
822        let mut state = lock(&self.shared.state);
823        let preferred = &mut state.net.preferred_sources;
824        preferred.retain(|other| other.is_ipv4() != ip.is_ipv4());
825        preferred.push(ip);
826    }
827}
828
829struct Net {
830    udp: HashMap<SocketAddr, Weak<UdpEndpoint>>,
831    multicast: Vec<(SocketAddr, Weak<UdpEndpoint>)>,
832    default_multicast_interfaces: Vec<IpAddr>,
833    send_errors: HashMap<IpAddr, io::ErrorKind>,
834    /// Sends from a socket of the address that are still to find it not ready.
835    not_ready: HashMap<IpAddr, usize>,
836    listeners: HashMap<SocketAddr, Weak<ListenerEndpoint>>,
837    tcp_ports: HashMap<SocketAddr, usize>,
838    /// The next ephemeral port of each address: each address has its own ports, as on a real
839    /// host, so two addresses can be given the same port.
840    next_port: HashMap<IpAddr, u16>,
841    default_link: LinkConfig,
842    links: HashMap<(IpAddr, IpAddr), LinkConfig>,
843    filter: Option<DatagramFilter>,
844    hosts: HashMap<String, Vec<IpAddr>>,
845    log: Vec<DatagramRecord>,
846    rng: u64,
847    interfaces: Vec<crate::runtime::LocalInterface>,
848    preferred_sources: Vec<IpAddr>,
849    routes: HashMap<IpAddr, IpAddr>,
850    /// Per direction: when the link's last datagram arrives (no reordering) and when a
851    /// rate-limited link is free again.
852    last_arrival: HashMap<(IpAddr, IpAddr), Instant>,
853    busy_until: HashMap<(IpAddr, IpAddr), Instant>,
854}
855
856impl Net {
857    fn new(seed: u64) -> Self {
858        Self {
859            udp: HashMap::new(),
860            multicast: Vec::new(),
861            default_multicast_interfaces: Vec::new(),
862            send_errors: HashMap::new(),
863            not_ready: HashMap::new(),
864            listeners: HashMap::new(),
865            tcp_ports: HashMap::new(),
866            next_port: HashMap::new(),
867            default_link: LinkConfig::default(),
868            links: HashMap::new(),
869            filter: None,
870            hosts: HashMap::new(),
871            log: Vec::new(),
872            // xorshift64 needs a state other than 0.
873            rng: seed.max(1),
874            interfaces: Vec::new(),
875            preferred_sources: Vec::new(),
876            routes: HashMap::new(),
877            last_arrival: HashMap::new(),
878            busy_until: HashMap::new(),
879        }
880    }
881
882    fn link(&self, from: IpAddr, to: IpAddr) -> LinkConfig {
883        self.links
884            .get(&(from, to))
885            .copied()
886            .unwrap_or(self.default_link)
887    }
888
889    /// When a datagram of `len` bytes sent at `now` on `link` (from `from` to `to`) arrives:
890    /// after the rate-limited link is free and has carried it, the delay and a draw of the
891    /// jitter, never before the link's previous datagram unless the link reorders. `None`:
892    /// the rate-limited link's queue is full.
893    fn arrival(
894        &mut self,
895        link: &LinkConfig,
896        from: IpAddr,
897        to: IpAddr,
898        now: Instant,
899        len: usize,
900    ) -> Option<Instant> {
901        let key = (from, to);
902        let mut departs = now;
903        if let Some(rate) = link.rate_bps.filter(|r| *r > 0) {
904            let start = self.busy_until.get(&key).copied().unwrap_or(now).max(now);
905            if start.duration_since(now) > link.queue {
906                return None;
907            }
908            let bits = (len as u64).saturating_mul(8);
909            let carry = Duration::from_nanos(bits.saturating_mul(1_000_000_000) / rate);
910            departs = start + carry;
911            self.busy_until.insert(key, departs);
912        }
913        let mut at = departs + link.delay;
914        if !link.jitter.is_zero() {
915            at += link.jitter.mul_f64(self.draw());
916        }
917        if !link.reorder {
918            if let Some(last) = self.last_arrival.get(&key) {
919                at = at.max(*last);
920            }
921            self.last_arrival.insert(key, at);
922        }
923        Some(at)
924    }
925
926    /// A uniform draw in [0, 1) (xorshift64).
927    fn draw(&mut self) -> f64 {
928        let mut x = self.rng;
929        x ^= x << 13;
930        x ^= x >> 7;
931        x ^= x << 17;
932        self.rng = x;
933        (x >> 11) as f64 / (1u64 << 53) as f64
934    }
935
936    fn bind_udp(&mut self, local: SocketAddr) -> io::Result<SocketAddr> {
937        self.udp.retain(|_, e| e.strong_count() > 0);
938        let ip = local.ip();
939        let port = match local.port() {
940            0 => {
941                let udp = &self.udp;
942                free_port(self.next_port.entry(ip).or_insert(49152), |p| {
943                    udp.contains_key(&SocketAddr::new(ip, p))
944                })?
945            }
946            port => port,
947        };
948        let local = SocketAddr::new(ip, port);
949        if self.udp.contains_key(&local) {
950            return Err(io::Error::from(io::ErrorKind::AddrInUse));
951        }
952        Ok(local)
953    }
954
955    fn bind_tcp(&mut self, local: SocketAddr) -> io::Result<SocketAddr> {
956        self.listeners.retain(|_, l| l.strong_count() > 0);
957        let ip = local.ip();
958        let port = match local.port() {
959            0 => {
960                let listeners = &self.listeners;
961                let ports = &self.tcp_ports;
962                free_port(self.next_port.entry(ip).or_insert(49152), |p| {
963                    let addr = SocketAddr::new(ip, p);
964                    listeners.contains_key(&addr) || ports.contains_key(&addr)
965                })?
966            }
967            port => port,
968        };
969        let local = SocketAddr::new(ip, port);
970        if self.listeners.contains_key(&local) {
971            return Err(io::Error::from(io::ErrorKind::AddrInUse));
972        }
973        *self.tcp_ports.entry(local).or_default() += 1;
974        Ok(local)
975    }
976
977    fn listener(&self, remote: SocketAddr) -> Option<Arc<ListenerEndpoint>> {
978        self.listeners
979            .get(&remote)
980            .or_else(|| {
981                self.listeners
982                    .get(&SocketAddr::new(unspecified(remote.ip()), remote.port()))
983            })
984            .and_then(Weak::upgrade)
985    }
986
987    /// The sockets a datagram to `to` reaches.
988    fn receivers(&self, from: IpAddr, to: SocketAddr) -> Vec<Arc<UdpEndpoint>> {
989        if to.ip().is_multicast() {
990            return self
991                .multicast
992                .iter()
993                .filter(|(group, _)| *group == to)
994                .filter_map(|(_, e)| e.upgrade())
995                .filter(|e| {
996                    e.joined.is_empty()
997                        || e.joined
998                            .iter()
999                            .any(|interface| !self.link(from, *interface).blocked)
1000                })
1001                .collect();
1002        }
1003        self.udp
1004            .get(&to)
1005            .or_else(|| {
1006                self.udp
1007                    .get(&SocketAddr::new(unspecified(to.ip()), to.port()))
1008            })
1009            .and_then(Weak::upgrade)
1010            .into_iter()
1011            .collect()
1012    }
1013}
1014
1015/// The next ephemeral port (49152 and up) that `taken` does not hold.
1016fn free_port(next: &mut u16, taken: impl Fn(u16) -> bool) -> io::Result<u16> {
1017    for _ in 0..16384 {
1018        let port = *next;
1019        *next = if *next == u16::MAX { 49152 } else { *next + 1 };
1020        if !taken(port) {
1021            return Ok(port);
1022        }
1023    }
1024    Err(io::Error::from(io::ErrorKind::AddrInUse))
1025}
1026
1027/// A datagram waiting in a mock socket: its sender, the destination address it was sent to
1028/// (a multicast group, or the socket's own), its bytes, and the ECN field it was sent with
1029/// (the mock network neither clears nor marks it).
1030type Received = (SocketAddr, IpAddr, Vec<u8>, u8);
1031
1032struct UdpEndpoint {
1033    local: SocketAddr,
1034    /// A multicast socket's interfaces (their addresses); empty: every one.
1035    joined: Vec<IpAddr>,
1036    inbox: Mutex<(VecDeque<Received>, Option<Waker>)>,
1037    traffic_class: AtomicU8,
1038    dont_fragment: AtomicBool,
1039}
1040
1041impl UdpEndpoint {
1042    fn new(local: SocketAddr) -> Self {
1043        Self {
1044            local,
1045            joined: Vec::new(),
1046            inbox: Mutex::new((VecDeque::new(), None)),
1047            traffic_class: AtomicU8::new(0),
1048            dont_fragment: AtomicBool::new(false),
1049        }
1050    }
1051
1052    fn deliver(&self, from: SocketAddr, destination: IpAddr, data: Vec<u8>, ecn: u8) {
1053        let waker = {
1054            let mut inbox = lock(&self.inbox);
1055            inbox.0.push_back((from, destination, data, ecn));
1056            inbox.1.take()
1057        };
1058        if let Some(waker) = waker {
1059            waker.wake();
1060        }
1061    }
1062}
1063
1064/// A UDP socket of a [`MockRuntime`].
1065struct MockUdp {
1066    runtime: MockRuntime,
1067    endpoint: Arc<UdpEndpoint>,
1068}
1069
1070impl fmt::Debug for MockUdp {
1071    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1072        f.debug_struct("MockUdp")
1073            .field("local", &self.endpoint.local)
1074            .finish()
1075    }
1076}
1077
1078impl AsyncUdpSocket for MockUdp {
1079    fn poll_send(&self, cx: &mut Context<'_>, transmit: &Transmit<'_>) -> Poll<io::Result<usize>> {
1080        let not_ready = {
1081            let mut state = lock(&self.runtime.shared.state);
1082            match state.net.not_ready.get_mut(&self.endpoint.local.ip()) {
1083                Some(left) if *left > 0 => {
1084                    *left -= 1;
1085                    true
1086                }
1087                _ => false,
1088            }
1089        };
1090        if not_ready {
1091            // The reactor's readiness, at once (outside the lock: waking schedules the task).
1092            cx.waker().wake_by_ref();
1093            return Poll::Pending;
1094        }
1095        self.endpoint
1096            .traffic_class
1097            .store(transmit.traffic_class, Ordering::Relaxed);
1098        let now = self.runtime.now();
1099        // A socket bound to the unspecified address (the mDNS sockets) sends from the address
1100        // the transmit names, as a real one does from its interface's address, or else from the
1101        // first interface it joined.
1102        let local = self.endpoint.local;
1103        let from = match transmit.source {
1104            Some(ip) if local.ip().is_unspecified() && ip.is_ipv4() == local.is_ipv4() => {
1105                SocketAddr::new(ip, local.port())
1106            }
1107            _ if local.ip().is_unspecified() => self
1108                .endpoint
1109                .joined
1110                .first()
1111                .map_or(local, |ip| SocketAddr::new(*ip, local.port())),
1112            _ => local,
1113        };
1114        let to = transmit.destination;
1115        let mut deliveries = Vec::new();
1116        let mut arrival = now;
1117        {
1118            let mut state = lock(&self.runtime.shared.state);
1119            let net = &mut state.net;
1120            if let Some(kind) = net.send_errors.get(&to.ip()).copied() {
1121                net.log.push(DatagramRecord {
1122                    at: now,
1123                    from,
1124                    to,
1125                    len: transmit.contents.len(),
1126                    traffic_class: transmit.traffic_class,
1127                    dont_fragment: self.endpoint.dont_fragment.load(Ordering::Relaxed),
1128                    fate: Fate::SendError,
1129                });
1130                return Poll::Ready(Err(kind.into()));
1131            }
1132            let link = net.link(from.ip(), to.ip());
1133            let receivers = net.receivers(from.ip(), to);
1134            let fate = if link.blocked {
1135                Fate::Blocked
1136            } else if link.loss > 0.0 && net.draw() < link.loss {
1137                Fate::Lost
1138            } else if !net.filter.as_mut().is_none_or(|keep| {
1139                keep(&MockDatagram {
1140                    at: now,
1141                    from,
1142                    to,
1143                    data: transmit.contents,
1144                })
1145            }) {
1146                Fate::Filtered
1147            } else if receivers.is_empty() {
1148                Fate::Unbound
1149            } else {
1150                match net.arrival(&link, from.ip(), to.ip(), now, transmit.contents.len()) {
1151                    Some(at) => {
1152                        arrival = at;
1153                        Fate::Delivered(receivers.len())
1154                    }
1155                    None => Fate::QueueFull,
1156                }
1157            };
1158            net.log.push(DatagramRecord {
1159                at: now,
1160                from,
1161                to,
1162                len: transmit.contents.len(),
1163                traffic_class: transmit.traffic_class,
1164                dont_fragment: self.endpoint.dont_fragment.load(Ordering::Relaxed),
1165                fate,
1166            });
1167            if let Fate::Delivered(_) = fate {
1168                deliveries = receivers;
1169            }
1170        }
1171        for receiver in deliveries {
1172            let data = transmit.contents.to_vec();
1173            if arrival <= now {
1174                receiver.deliver(from, to.ip(), data, transmit.traffic_class & 0b11);
1175            } else {
1176                self.runtime.schedule_timer(
1177                    arrival,
1178                    Timer::Datagram {
1179                        to: receiver,
1180                        from,
1181                        destination: to.ip(),
1182                        data,
1183                        ecn: transmit.traffic_class & 0b11,
1184                    },
1185                );
1186            }
1187        }
1188        Poll::Ready(Ok(transmit.contents.len()))
1189    }
1190
1191    fn poll_recv(
1192        &self,
1193        cx: &mut Context<'_>,
1194        bufs: &mut [IoSliceMut<'_>],
1195        meta: &mut [RecvMeta],
1196    ) -> Poll<io::Result<usize>> {
1197        let mut inbox = lock(&self.endpoint.inbox);
1198        let mut filled = 0;
1199        while filled < bufs.len().min(meta.len()) {
1200            let Some((from, destination, data, ecn)) = inbox.0.pop_front() else {
1201                break;
1202            };
1203            let len = data.len().min(bufs[filled].len());
1204            bufs[filled][..len].copy_from_slice(&data[..len]);
1205            meta[filled] = RecvMeta {
1206                addr: from,
1207                len,
1208                stride: len,
1209                // The ECN field, as `IP_RECVTOS` / `IPV6_RECVTCLASS` report it.
1210                ecn: Some(ecn),
1211                // The destination of the IP header, as `IP_PKTINFO` reports it.
1212                dst_ip: Some(destination),
1213            };
1214            filled += 1;
1215        }
1216        if filled == 0 {
1217            inbox.1 = Some(cx.waker().clone());
1218            return Poll::Pending;
1219        }
1220        Poll::Ready(Ok(filled))
1221    }
1222
1223    fn local_addr(&self) -> io::Result<SocketAddr> {
1224        Ok(self.endpoint.local)
1225    }
1226
1227    fn max_receive_batch(&self) -> usize {
1228        64
1229    }
1230
1231    fn traffic_class(&self) -> io::Result<u32> {
1232        Ok(u32::from(
1233            self.endpoint.traffic_class.load(Ordering::Relaxed),
1234        ))
1235    }
1236
1237    fn set_dont_fragment(&self, on: bool) -> io::Result<()> {
1238        self.endpoint.dont_fragment.store(on, Ordering::Relaxed);
1239        Ok(())
1240    }
1241}
1242
1243/// One direction of a mock TCP connection.
1244#[derive(Default)]
1245struct Pipe(Mutex<PipeState>);
1246
1247#[derive(Default)]
1248struct PipeState {
1249    bytes: VecDeque<u8>,
1250    eof: bool,
1251    reset: bool,
1252    reader: Option<Waker>,
1253}
1254
1255impl Pipe {
1256    fn push(&self, data: &[u8]) {
1257        let waker = {
1258            let mut pipe = lock(&self.0);
1259            pipe.bytes.extend(data);
1260            pipe.reader.take()
1261        };
1262        if let Some(waker) = waker {
1263            waker.wake();
1264        }
1265    }
1266
1267    fn end(&self, reset: bool) {
1268        let waker = {
1269            let mut pipe = lock(&self.0);
1270            if reset {
1271                pipe.reset = true;
1272                pipe.bytes.clear();
1273            } else {
1274                pipe.eof = true;
1275            }
1276            pipe.reader.take()
1277        };
1278        if let Some(waker) = waker {
1279            waker.wake();
1280        }
1281    }
1282}
1283
1284#[derive(Default)]
1285struct TcpEnd {
1286    shut: bool,
1287    reset_on_close: bool,
1288    traffic_class: u8,
1289}
1290
1291/// A TCP connection end of a [`MockRuntime`].
1292struct MockTcp {
1293    runtime: MockRuntime,
1294    local: SocketAddr,
1295    peer: SocketAddr,
1296    incoming: Arc<Pipe>,
1297    outgoing: Arc<Pipe>,
1298    state: Mutex<TcpEnd>,
1299}
1300
1301impl fmt::Debug for MockTcp {
1302    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1303        f.debug_struct("MockTcp")
1304            .field("local", &self.local)
1305            .field("peer", &self.peer)
1306            .finish()
1307    }
1308}
1309
1310impl MockTcp {
1311    /// Sends `timer` toward the peer after the link's delay.
1312    fn toward_peer(&self, timer: Timer) {
1313        let delay = lock(&self.runtime.shared.state)
1314            .net
1315            .link(self.local.ip(), self.peer.ip())
1316            .delay;
1317        if delay.is_zero() {
1318            fire(timer);
1319        } else {
1320            let at = self.runtime.now() + delay;
1321            self.runtime.schedule_timer(at, timer);
1322        }
1323    }
1324}
1325
1326impl AsyncTcpStream for MockTcp {
1327    fn poll_read(&self, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<io::Result<usize>> {
1328        let mut pipe = lock(&self.incoming.0);
1329        if pipe.reset {
1330            return Poll::Ready(Err(io::Error::from(io::ErrorKind::ConnectionReset)));
1331        }
1332        if pipe.bytes.is_empty() {
1333            if pipe.eof {
1334                return Poll::Ready(Ok(0));
1335            }
1336            pipe.reader = Some(cx.waker().clone());
1337            return Poll::Pending;
1338        }
1339        let n = buf.len().min(pipe.bytes.len());
1340        for (slot, byte) in buf.iter_mut().zip(pipe.bytes.drain(..n)) {
1341            *slot = byte;
1342        }
1343        Poll::Ready(Ok(n))
1344    }
1345
1346    fn poll_write(&self, _: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
1347        if lock(&self.state).shut {
1348            return Poll::Ready(Err(io::Error::from(io::ErrorKind::BrokenPipe)));
1349        }
1350        if lock(&self.outgoing.0).reset {
1351            return Poll::Ready(Err(io::Error::from(io::ErrorKind::ConnectionReset)));
1352        }
1353        self.toward_peer(Timer::Bytes {
1354            to: self.outgoing.clone(),
1355            data: buf.to_vec(),
1356        });
1357        Poll::Ready(Ok(buf.len()))
1358    }
1359
1360    fn shutdown_write(&self) -> io::Result<()> {
1361        let first = !std::mem::replace(&mut lock(&self.state).shut, true);
1362        if first {
1363            self.toward_peer(Timer::End {
1364                to: self.outgoing.clone(),
1365                reset: false,
1366            });
1367        }
1368        Ok(())
1369    }
1370
1371    fn reset_on_close(&self) -> io::Result<()> {
1372        lock(&self.state).reset_on_close = true;
1373        Ok(())
1374    }
1375
1376    fn set_traffic_class(&self, value: u8) -> io::Result<u32> {
1377        lock(&self.state).traffic_class = value;
1378        Ok(u32::from(value))
1379    }
1380
1381    fn local_addr(&self) -> io::Result<SocketAddr> {
1382        Ok(self.local)
1383    }
1384
1385    fn peer_addr(&self) -> io::Result<SocketAddr> {
1386        Ok(self.peer)
1387    }
1388}
1389
1390impl Drop for MockTcp {
1391    fn drop(&mut self) {
1392        let (shut, reset) = {
1393            let state = lock(&self.state);
1394            (state.shut, state.reset_on_close)
1395        };
1396        if reset {
1397            self.toward_peer(Timer::End {
1398                to: self.outgoing.clone(),
1399                reset: true,
1400            });
1401        } else if !shut {
1402            self.toward_peer(Timer::End {
1403                to: self.outgoing.clone(),
1404                reset: false,
1405            });
1406        }
1407        if let Some(count) = lock(&self.runtime.shared.state)
1408            .net
1409            .tcp_ports
1410            .get_mut(&self.local)
1411        {
1412            *count = count.saturating_sub(1);
1413        }
1414    }
1415}
1416
1417type Pending = (Arc<dyn AsyncTcpStream>, SocketAddr);
1418
1419struct ListenerEndpoint {
1420    local: SocketAddr,
1421    queue: Mutex<(VecDeque<Pending>, Option<Waker>)>,
1422}
1423
1424impl ListenerEndpoint {
1425    fn push(&self, stream: Arc<dyn AsyncTcpStream>, remote: SocketAddr) {
1426        let waker = {
1427            let mut queue = lock(&self.queue);
1428            queue.0.push_back((stream, remote));
1429            queue.1.take()
1430        };
1431        if let Some(waker) = waker {
1432            waker.wake();
1433        }
1434    }
1435
1436    /// The local address a connection from `remote` has on this listener.
1437    fn local_for(&self, remote: SocketAddr) -> SocketAddr {
1438        if self.local.ip().is_unspecified() {
1439            SocketAddr::new(remote.ip(), self.local.port())
1440        } else {
1441            self.local
1442        }
1443    }
1444}
1445
1446/// A TCP listener of a [`MockRuntime`].
1447struct MockListener {
1448    runtime: MockRuntime,
1449    endpoint: Arc<ListenerEndpoint>,
1450}
1451
1452impl fmt::Debug for MockListener {
1453    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1454        f.debug_struct("MockListener")
1455            .field("local", &self.endpoint.local)
1456            .finish()
1457    }
1458}
1459
1460impl AsyncTcpListener for MockListener {
1461    fn poll_accept(&self, cx: &mut Context<'_>) -> Poll<io::Result<Pending>> {
1462        let mut queue = lock(&self.endpoint.queue);
1463        match queue.0.pop_front() {
1464            Some(accepted) => Poll::Ready(Ok(accepted)),
1465            None => {
1466                queue.1 = Some(cx.waker().clone());
1467                Poll::Pending
1468            }
1469        }
1470    }
1471
1472    fn local_addr(&self) -> io::Result<SocketAddr> {
1473        Ok(self.endpoint.local)
1474    }
1475}
1476
1477impl Drop for MockListener {
1478    fn drop(&mut self) {
1479        let mut state = lock(&self.runtime.shared.state);
1480        if let Some(count) = state.net.tcp_ports.get_mut(&self.endpoint.local) {
1481            *count = count.saturating_sub(1);
1482        }
1483    }
1484}