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