1
//! Internal utilities for `tor_rtmock`
2

            
3
use derive_deftly::define_derive_deftly;
4
use futures::channel::mpsc;
5

            
6
define_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
15
///    `Spawn + BlockOn + JoinSetProvider`
16
///  * `#[deftly(mock(net))]` to indicate the field implementing `NetProvider`
17
///  * `#[deftly(mock(sleep))]` to indicate the field implementing `SleepProvider`
18
///     and `CoarseTimeProvider`.
19
///  * `#[deftly(mock(toplevel))]` to indicate the field implementing `ToplevelBlockOn`
20
///     unconditionally.
21
///  * `#[deftly(mock(toplevel_where = "BOUND"))]` to indicate the field implementing
22
///    `ToplevelBlockOn` only if BOUND is satisfied.
23
///    For example, `#[deftly(mock(toplevel_where = "R: ToplevelBlockOn"))] runtime: R,`.
24
// This could perhaps be further reduced:
25
// ambassador might be able to remove most of the body (although does it do async well?)
26
    SomeMockRuntime for struct, expect items, beta_deftly:
27

            
28
 $(
29
  ${when fmeta(mock(task))}
30

            
31
    impl <$tgens> Spawn for $ttype {
32
86940
        fn spawn_obj(&self, future: FutureObj<'static, ()>) -> Result<(), SpawnError> {
33
            self.$fname.spawn_obj(future)
34
        }
35
    }
36

            
37
    impl <$tgens> Blocking for $ttype {
38
        type ThreadHandle<T: Send + 'static> = <$ftype as Blocking>::ThreadHandle<T>;
39

            
40
28
        fn spawn_blocking<F, T>(&self, f: F) -> <$ftype as Blocking>::ThreadHandle<T>
41
28
        where
42
28
            F: FnOnce() -> T + Send + 'static,
43
28
            T: Send + 'static {
44
            self.$fname.spawn_blocking(f)
45
        }
46

            
47
902
        fn reenter_block_on<F>(&self, future: F) -> F::Output
48
902
        where
49
902
            F: Future,
50
902
            F::Output: Send + 'static
51
        {
52
            self.$fname.reenter_block_on(future)
53
        }
54
    }
55

            
56
    impl <$tgens> JoinSetProvider for $ttype {
57
        type JoinSet<T: Send + Sync + 'static> = <$ftype as JoinSetProvider>::JoinSet<T>;
58

            
59
10
        fn new_join_set<T>(&self) -> Self::JoinSet<T>
60
10
        where T: Send + Sync + 'static {
61
            self.$fname.new_join_set()
62
        }
63
    }
64

            
65
 )
66
 $(
67
  ${when any(fmeta(mock(toplevel)), fmeta(mock(toplevel_where)))}
68

            
69
    impl <$tgens> ToplevelBlockOn for $ttype
70
    where ${fmeta(mock(toplevel_where)) as token_stream, default {}}
71
    {
72
308
        fn block_on<F: Future>(&self, future: F) -> F::Output {
73
            self.$fname.block_on(future)
74
        }
75
    }
76

            
77
 )
78
 $(
79
  ${when fmeta(mock(net))}
80

            
81
    #[async_trait]
82
    impl <$tgens> NetStreamProvider for $ttype {
83
        type Stream = <$ftype as NetStreamProvider>::Stream;
84
        type Listener = <$ftype as NetStreamProvider>::Listener;
85
        type ConnectOptions = <$ftype as NetStreamProvider>::ConnectOptions;
86
        type ListenOptions = <$ftype as NetStreamProvider>::ListenOptions;
87

            
88
        async fn connect(
89
            &self,
90
            addr: &SocketAddr,
91
            options: &Self::ConnectOptions,
92
        ) -> IoResult<Self::Stream> {
93
            self.$fname.connect(addr, options).await
94
        }
95
        async fn listen(
96
            &self,
97
            addr: &SocketAddr,
98
            options: &Self::ListenOptions,
99
        ) -> IoResult<Self::Listener> {
100
            self.$fname.listen(addr, options).await
101
        }
102
    }
103

            
104
    #[async_trait]
105
    impl <$tgens> NetStreamProvider<tor_general_addr::unix::SocketAddr> for $ttype {
106
        type Stream = FakeStream;
107
        type Listener = FakeListener<tor_general_addr::unix::SocketAddr>;
108
        type ConnectOptions = tor_rtcompat::UnixConnectOptions;
109
        type ListenOptions = tor_rtcompat::UnixListenOptions;
110

            
111
        async fn connect(
112
            &self,
113
            _addr: &tor_general_addr::unix::SocketAddr,
114
            _options: &Self::ConnectOptions,
115
        ) -> IoResult<Self::Stream> {
116
            Err(tor_general_addr::unix::NoAfUnixSocketSupport::default().into())
117
        }
118
        async fn listen(
119
            &self,
120
            _addr: &tor_general_addr::unix::SocketAddr,
121
            _options: &Self::ListenOptions,
122
        ) -> IoResult<Self::Listener> {
123
            Err(tor_general_addr::unix::NoAfUnixSocketSupport::default().into())
124
        }
125
    }
126

            
127
    impl <$tgens> TlsProvider<<$ftype as NetStreamProvider>::Stream> for $ttype {
128
        type Connector = <$ftype as TlsProvider<
129
            <$ftype as NetStreamProvider>::Stream
130
            >>::Connector;
131
        type TlsStream = <$ftype as TlsProvider<
132
            <$ftype as NetStreamProvider>::Stream
133
            >>::TlsStream;
134
        type Acceptor = <$ftype as TlsProvider<
135
            <$ftype as NetStreamProvider>::Stream
136
            >>::Acceptor;
137
        type TlsServerStream = <$ftype as TlsProvider<
138
            <$ftype as NetStreamProvider>::Stream
139
            >>::TlsServerStream;
140

            
141
882
        fn tls_connector(&self) -> Self::Connector {
142
            self.$fname.tls_connector()
143
        }
144
        fn tls_acceptor(&self, settings: tor_rtcompat::tls::TlsAcceptorSettings) -> std::io::Result<Self::Acceptor> {
145
            self.$fname.tls_acceptor(settings)
146
        }
147
        fn supports_keying_material_export(&self) -> bool {
148
            self.$fname.supports_keying_material_export()
149
        }
150
    }
151

            
152
    #[async_trait]
153
    impl <$tgens> UdpProvider for $ttype {
154
        type UdpSocket = <$ftype as UdpProvider>::UdpSocket;
155

            
156
        #[inline]
157
        async fn bind(&self, addr: &SocketAddr) -> IoResult<Self::UdpSocket> {
158
            self.$fname.bind(addr).await
159
        }
160
    }
161

            
162
 )
163
 $(
164
  ${when fmeta(mock(sleep))}
165

            
166
    impl <$tgens> SleepProvider for $ttype {
167
        type SleepFuture = <$ftype as SleepProvider>::SleepFuture;
168

            
169
117654
        fn sleep(&self, dur: Duration) -> Self::SleepFuture {
170
            self.$fname.sleep(dur)
171
        }
172
3998110
        fn now(&self) -> Instant {
173
            self.$fname.now()
174
        }
175
123790
        fn wallclock(&self) -> SystemTime {
176
            self.$fname.wallclock()
177
        }
178
84
        fn block_advance<T: Into<String>>(&self, reason: T) {
179
            self.$fname.block_advance(reason);
180
        }
181
56
        fn release_advance<T: Into<String>>(&self, reason: T) {
182
            self.$fname.release_advance(reason);
183
        }
184
1442
        fn allow_one_advance(&self, dur: Duration) {
185
            self.$fname.allow_one_advance(dur);
186
        }
187
    }
188

            
189
    impl <$tgens> CoarseTimeProvider for $ttype {
190
288311
        fn now_coarse(&self) -> CoarseInstant {
191
            self.$fname.now_coarse()
192
        }
193
    }
194

            
195
 )
196

            
197
   // TODO this wants to be assert_impl but it fails at generics
198
   #[allow(unused)]
199
   const _: fn() = || {
200
       fn x(_: impl Runtime) { }
201
       fn check_impl_runtime<$tgens>(t: $ttype) { x(t) }
202
   };
203
}
204

            
205
/// Prelude that must be imported to derive
206
/// [`SomeMockRuntime`](derive_deftly_template_SomeMockRuntime)
207
//
208
// This could have been part of the expansion of `impl_runtime!`,
209
// but it seems rather too exciting for a macro to import things as a side gig.
210
//
211
// Arguably this ought to be an internal crate::prelude instead.
212
// But crate-internal preludes are controversial within the Arti team.  -Diziet
213
//
214
// For macro visibility reasons, this must come *lexically after* the macro,
215
// to allow it to refer to the macro in the doc comment.
216
pub(crate) mod impl_runtime_prelude {
217
    pub(crate) use async_trait::async_trait;
218
    pub(crate) use derive_deftly::Deftly;
219
    pub(crate) use futures::Future;
220
    pub(crate) use futures::task::{FutureObj, Spawn, SpawnError};
221
    pub(crate) use std::io::Result as IoResult;
222
    pub(crate) use std::net::SocketAddr;
223
    pub(crate) use tor_rtcompat::{
224
        Blocking, CoarseInstant, CoarseTimeProvider, JoinSetProvider, NetStreamProvider, Runtime,
225
        SleepProvider, TlsProvider, ToplevelBlockOn, UdpProvider, unimpl::FakeListener,
226
        unimpl::FakeStream,
227
    };
228
    pub(crate) use web_time_compat::{Duration, Instant, SystemTime, SystemTimeExt};
229
}
230

            
231
/// Wrapper for `futures::channel::mpsc::channel` that embodies the `#[allow]`
232
///
233
/// We don't care about mq tracking in this test crate.
234
///
235
/// Exactly like `tor_async_utils::mpsc_channel_no_memquota`,
236
/// but we can't use that here for crate hierarchy reasons.
237
#[allow(clippy::disallowed_methods)]
238
7081
pub(crate) fn mpsc_channel<T>(buffer: usize) -> (mpsc::Sender<T>, mpsc::Receiver<T>) {
239
7081
    mpsc::channel(buffer)
240
7081
}