tor_rtmock/
util.rs

1//! Internal utilities for `tor_rtmock`
2
3use derive_deftly::define_derive_deftly;
4use futures::channel::mpsc;
5
6define_derive_deftly! {
7/// Implements `Runtime` for a struct made of multiple sub-providers
8///
9/// The type must be a struct containing
10/// field(s) which implement `SleepProvider`, `NetProvider`, etc.
11///
12/// The corresponding fields must be decorated with:
13///
14///  * `#[deftly(mock(task))]` to indicate the field implementing `Spawn + BlockOn`
15///  * `#[deftly(mock(net))]` to indicate the field implementing `NetProvider`
16///  * `#[deftly(mock(sleep))]` to indicate the field implementing `SleepProvider`
17///     and `CoarseTimeProvider`.
18///  * `#[deftly(mock(toplevel))]` to indicate the field implementing `ToplevelBlockOn`
19///     unconditionally.
20///  * `#[deftly(mock(toplevel_where = "BOUND"))]` to indicate the field implementing
21///    `ToplevelBlockOn` only if BOUND is satisfied.
22///    For example, `#[deftly(mock(toplevel_where = "R: ToplevelBlockOn"))] runtime: R,`.
23// This could perhaps be further reduced:
24// ambassador might be able to remove most of the body (although does it do async well?)
25    SomeMockRuntime for struct, expect items, beta_deftly:
26
27 $(
28  ${when fmeta(mock(task))}
29
30    impl <$tgens> Spawn for $ttype {
31        fn spawn_obj(&self, future: FutureObj<'static, ()>) -> Result<(), SpawnError> {
32            self.$fname.spawn_obj(future)
33        }
34    }
35
36    impl <$tgens> Blocking for $ttype {
37        type ThreadHandle<T: Send + 'static> = <$ftype as Blocking>::ThreadHandle<T>;
38
39        fn spawn_blocking<F, T>(&self, f: F) -> <$ftype as Blocking>::ThreadHandle<T>
40        where
41            F: FnOnce() -> T + Send + 'static,
42            T: Send + 'static {
43            self.$fname.spawn_blocking(f)
44        }
45
46        fn reenter_block_on<F>(&self, future: F) -> F::Output
47        where
48            F: Future,
49            F::Output: Send + 'static
50        {
51            self.$fname.reenter_block_on(future)
52        }
53    }
54
55 )
56 $(
57  ${when any(fmeta(mock(toplevel)), fmeta(mock(toplevel_where)))}
58
59    impl <$tgens> ToplevelBlockOn for $ttype
60    where ${fmeta(mock(toplevel_where)) as token_stream, default {}}
61    {
62        fn block_on<F: Future>(&self, future: F) -> F::Output {
63            self.$fname.block_on(future)
64        }
65    }
66
67 )
68 $(
69  ${when fmeta(mock(net))}
70
71    #[async_trait]
72    impl <$tgens> NetStreamProvider for $ttype {
73        type Stream = <$ftype as NetStreamProvider>::Stream;
74        type Listener = <$ftype as NetStreamProvider>::Listener;
75
76        async fn connect(&self, addr: &SocketAddr) -> IoResult<Self::Stream> {
77            self.$fname.connect(addr).await
78        }
79        async fn listen(&self, addr: &SocketAddr) -> IoResult<Self::Listener> {
80            self.$fname.listen(addr).await
81        }
82    }
83
84    #[async_trait]
85    impl <$tgens> NetStreamProvider<tor_general_addr::unix::SocketAddr> for $ttype {
86        type Stream = FakeStream;
87        type Listener = FakeListener<tor_general_addr::unix::SocketAddr>;
88
89        async fn connect(&self, _addr: &tor_general_addr::unix::SocketAddr) -> IoResult<Self::Stream> {
90            Err(tor_general_addr::unix::NoAfUnixSocketSupport::default().into())
91        }
92        async fn listen(&self, _addr: &tor_general_addr::unix::SocketAddr) -> IoResult<Self::Listener> {
93            Err(tor_general_addr::unix::NoAfUnixSocketSupport::default().into())
94        }
95    }
96
97    impl <$tgens> TlsProvider<<$ftype as NetStreamProvider>::Stream> for $ttype {
98        type Connector = <$ftype as TlsProvider<
99            <$ftype as NetStreamProvider>::Stream
100            >>::Connector;
101        type TlsStream = <$ftype as TlsProvider<
102            <$ftype as NetStreamProvider>::Stream
103            >>::TlsStream;
104        fn tls_connector(&self) -> Self::Connector {
105            self.$fname.tls_connector()
106        }
107        fn supports_keying_material_export(&self) -> bool {
108            self.$fname.supports_keying_material_export()
109        }
110    }
111
112    #[async_trait]
113    impl <$tgens> UdpProvider for $ttype {
114        type UdpSocket = <$ftype as UdpProvider>::UdpSocket;
115
116        #[inline]
117        async fn bind(&self, addr: &SocketAddr) -> IoResult<Self::UdpSocket> {
118            self.$fname.bind(addr).await
119        }
120    }
121
122 )
123 $(
124  ${when fmeta(mock(sleep))}
125
126    impl <$tgens> SleepProvider for $ttype {
127        type SleepFuture = <$ftype as SleepProvider>::SleepFuture;
128
129        fn sleep(&self, dur: Duration) -> Self::SleepFuture {
130            self.$fname.sleep(dur)
131        }
132        fn now(&self) -> Instant {
133            self.$fname.now()
134        }
135        fn wallclock(&self) -> SystemTime {
136            self.$fname.wallclock()
137        }
138        fn block_advance<T: Into<String>>(&self, reason: T) {
139            self.$fname.block_advance(reason);
140        }
141        fn release_advance<T: Into<String>>(&self, reason: T) {
142            self.$fname.release_advance(reason);
143        }
144        fn allow_one_advance(&self, dur: Duration) {
145            self.$fname.allow_one_advance(dur);
146        }
147    }
148
149    impl <$tgens> CoarseTimeProvider for $ttype {
150        fn now_coarse(&self) -> CoarseInstant {
151            self.$fname.now_coarse()
152        }
153    }
154
155 )
156
157   // TODO this wants to be assert_impl but it fails at generics
158   const _: fn() = || {
159       fn x(_: impl Runtime) { }
160       fn check_impl_runtime<$tgens>(t: $ttype) { x(t) }
161   };
162}
163
164/// Prelude that must be imported to derive
165/// [`SomeMockRuntime`](derive_deftly_template_SomeMockRuntime)
166//
167// This could have been part of the expansion of `impl_runtime!`,
168// but it seems rather too exciting for a macro to import things as a side gig.
169//
170// Arguably this ought to be an internal crate::prelude instead.
171// But crate-internal preludes are controversial within the Arti team.  -Diziet
172//
173// For macro visibility reasons, this must come *lexically after* the macro,
174// to allow it to refer to the macro in the doc comment.
175pub(crate) mod impl_runtime_prelude {
176    pub(crate) use async_trait::async_trait;
177    pub(crate) use derive_deftly::Deftly;
178    pub(crate) use futures::task::{FutureObj, Spawn, SpawnError};
179    pub(crate) use futures::Future;
180    pub(crate) use std::io::Result as IoResult;
181    pub(crate) use std::net::SocketAddr;
182    pub(crate) use std::time::{Duration, Instant, SystemTime};
183    pub(crate) use tor_rtcompat::{
184        unimpl::FakeListener, unimpl::FakeStream, Blocking, CoarseInstant, CoarseTimeProvider,
185        NetStreamProvider, Runtime, SleepProvider, TlsProvider, ToplevelBlockOn, UdpProvider,
186    };
187}
188
189/// Wrapper for `futures::channel::mpsc::channel` that embodies the `#[allow]`
190///
191/// We don't care about mq tracking in this test crate.
192///
193/// Exactly like `tor_async_utils::mpsc_channel_no_memquota`,
194/// but we can't use that here for crate hierarchy reasons.
195#[allow(clippy::disallowed_methods)]
196pub(crate) fn mpsc_channel<T>(buffer: usize) -> (mpsc::Sender<T>, mpsc::Receiver<T>) {
197    mpsc::channel(buffer)
198}