1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
//! Entry points for use with Tokio runtimes.
use crate::impls::tokio::TokioRuntimeHandle as Handle;

use crate::{BlockOn, CompoundRuntime, RealCoarseTimeProvider};
use std::io::{Error as IoError, ErrorKind, Result as IoResult};

#[cfg(feature = "native-tls")]
use crate::impls::native_tls::NativeTlsProvider;
#[cfg(feature = "rustls")]
use crate::impls::rustls::RustlsProvider;

/// An alias for the Tokio runtime that we prefer to use, based on whatever TLS
/// implementation has been enabled.
///
/// If only one of `native_tls` and `rustls` bas been enabled within the
/// `tor-rtcompat` crate, that will be the TLS backend that this uses.
///
/// Currently, `native_tls` is preferred over `rustls` when both are available,
/// because of its maturity within Arti.  However, this might change in the
/// future.
#[cfg(feature = "native-tls")]
pub use TokioNativeTlsRuntime as PreferredRuntime;
#[cfg(all(feature = "rustls", not(feature = "native-tls")))]
pub use TokioRustlsRuntime as PreferredRuntime;

/// A [`Runtime`](crate::Runtime) built around a Handle to a tokio runtime, and `native_tls`.
///
/// # Limitations
///
/// Note that Arti requires that the runtime should have working
/// implementations for Tokio's time, net, and io facilities, but we have
/// no good way to check that when creating this object.
#[derive(Clone)]
#[cfg(feature = "native-tls")]
pub struct TokioNativeTlsRuntime {
    /// The actual [`CompoundRuntime`] that implements this.
    inner: HandleInner,
}

/// Implementation type for a TokioRuntimeHandle.
#[cfg(feature = "native-tls")]
type HandleInner =
    CompoundRuntime<Handle, Handle, RealCoarseTimeProvider, Handle, NativeTlsProvider, Handle>;

/// A [`Runtime`](crate::Runtime) built around a Handle to a tokio runtime, and `rustls`.
#[derive(Clone)]
#[cfg(feature = "rustls")]
pub struct TokioRustlsRuntime {
    /// The actual [`CompoundRuntime`] that implements this.
    inner: RustlsHandleInner,
}

/// Implementation for a TokioRuntimeRustlsHandle
#[cfg(feature = "rustls")]
type RustlsHandleInner =
    CompoundRuntime<Handle, Handle, RealCoarseTimeProvider, Handle, RustlsProvider, Handle>;

#[cfg(feature = "native-tls")]
crate::opaque::implement_opaque_runtime! {
    TokioNativeTlsRuntime { inner : HandleInner }
}

#[cfg(feature = "rustls")]
crate::opaque::implement_opaque_runtime! {
    TokioRustlsRuntime { inner : RustlsHandleInner }
}

#[cfg(feature = "native-tls")]
impl From<tokio_crate::runtime::Handle> for TokioNativeTlsRuntime {
    fn from(h: tokio_crate::runtime::Handle) -> Self {
        let h = Handle::new(h);
        TokioNativeTlsRuntime {
            inner: CompoundRuntime::new(
                h.clone(),
                h.clone(),
                RealCoarseTimeProvider::new(),
                h.clone(),
                NativeTlsProvider::default(),
                h,
            ),
        }
    }
}

#[cfg(feature = "rustls")]
impl From<tokio_crate::runtime::Handle> for TokioRustlsRuntime {
    fn from(h: tokio_crate::runtime::Handle) -> Self {
        let h = Handle::new(h);
        TokioRustlsRuntime {
            inner: CompoundRuntime::new(
                h.clone(),
                h.clone(),
                RealCoarseTimeProvider::new(),
                h.clone(),
                RustlsProvider::default(),
                h,
            ),
        }
    }
}

#[cfg(feature = "native-tls")]
impl TokioNativeTlsRuntime {
    /// Create a new [`TokioNativeTlsRuntime`].
    ///
    /// The return value will own the underlying Tokio runtime object, which
    /// will be dropped when the last copy of this handle is freed.
    ///
    /// If you want to use a currently running runtime instead, call
    /// [`TokioNativeTlsRuntime::current()`].
    pub fn create() -> IoResult<Self> {
        crate::impls::tokio::create_runtime().map(|r| TokioNativeTlsRuntime {
            inner: CompoundRuntime::new(
                r.clone(),
                r.clone(),
                RealCoarseTimeProvider::new(),
                r.clone(),
                NativeTlsProvider::default(),
                r,
            ),
        })
    }

    /// Return a [`TokioNativeTlsRuntime`] wrapping the currently running
    /// Tokio runtime.
    ///
    /// # Usage note
    ///
    /// We should never call this from inside other Arti crates, or from library
    /// crates that want to support multiple runtimes!  This function is for
    /// Arti _users_ who want to wrap some existing Tokio runtime as a
    /// [`Runtime`](crate::Runtime).  It is not for library crates that want to work with
    /// multiple runtimes.
    ///
    /// Once you have a runtime returned by this function, you should just
    /// create more handles to it via [`Clone`].
    pub fn current() -> IoResult<Self> {
        Ok(current_handle()?.into())
    }

    /// Helper to run a single test function in a freshly created runtime.
    ///
    /// # Panics
    ///
    /// Panics if we can't create this runtime.
    ///
    /// # Warning
    ///
    /// This API is **NOT** for consumption outside Arti. Semver guarantees are not provided.
    #[doc(hidden)]
    pub fn run_test<P, F, O>(func: P) -> O
    where
        P: FnOnce(Self) -> F,
        F: futures::Future<Output = O>,
    {
        let runtime = Self::create().expect("Failed to create runtime");
        runtime.clone().block_on(func(runtime))
    }
}

#[cfg(feature = "rustls")]
impl TokioRustlsRuntime {
    /// Create a new [`TokioRustlsRuntime`].
    ///
    /// The return value will own the underlying Tokio runtime object, which
    /// will be dropped when the last copy of this handle is freed.
    ///
    /// If you want to use a currently running runtime instead, call
    /// [`TokioRustlsRuntime::current()`].
    pub fn create() -> IoResult<Self> {
        crate::impls::tokio::create_runtime().map(|r| TokioRustlsRuntime {
            inner: CompoundRuntime::new(
                r.clone(),
                r.clone(),
                RealCoarseTimeProvider::new(),
                r.clone(),
                RustlsProvider::default(),
                r,
            ),
        })
    }

    /// Return a [`TokioRustlsRuntime`] wrapping the currently running
    /// Tokio runtime.
    ///
    /// # Usage note
    ///
    /// We should never call this from inside other Arti crates, or from library
    /// crates that want to support multiple runtimes!  This function is for
    /// Arti _users_ who want to wrap some existing Tokio runtime as a
    /// [`Runtime`](crate::Runtime).  It is not for library crates that want to work with
    /// multiple runtimes.
    ///
    /// Once you have a runtime returned by this function, you should just
    /// create more handles to it via [`Clone`].
    pub fn current() -> IoResult<Self> {
        Ok(current_handle()?.into())
    }

    /// Helper to run a single test function in a freshly created runtime.
    ///
    /// # Panics
    ///
    /// Panics if we can't create this runtime.
    ///
    /// # Warning
    ///
    /// This API is **NOT** for consumption outside Arti. Semver guarantees are not provided.
    #[doc(hidden)]
    pub fn run_test<P, F, O>(func: P) -> O
    where
        P: FnOnce(Self) -> F,
        F: futures::Future<Output = O>,
    {
        let runtime = Self::create().expect("Failed to create runtime");
        runtime.clone().block_on(func(runtime))
    }
}

/// As `Handle::try_current()`, but return an IoError on failure.
#[cfg(any(feature = "native-tls", feature = "rustls"))]
fn current_handle() -> std::io::Result<tokio_crate::runtime::Handle> {
    tokio_crate::runtime::Handle::try_current().map_err(|e| IoError::new(ErrorKind::Other, e))
}

#[cfg(test)]
mod test {
    // @@ begin test lint list maintained by maint/add_warning @@
    #![allow(clippy::bool_assert_comparison)]
    #![allow(clippy::clone_on_copy)]
    #![allow(clippy::dbg_macro)]
    #![allow(clippy::mixed_attributes_style)]
    #![allow(clippy::print_stderr)]
    #![allow(clippy::print_stdout)]
    #![allow(clippy::single_char_pattern)]
    #![allow(clippy::unwrap_used)]
    #![allow(clippy::unchecked_duration_subtraction)]
    #![allow(clippy::useless_vec)]
    #![allow(clippy::needless_pass_by_value)]
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
    use super::*;

    #[test]
    fn no_current() {
        // There should be no running tokio runtime in this context.

        #[cfg(feature = "native-tls")]
        assert!(TokioNativeTlsRuntime::current().is_err());

        #[cfg(feature = "rustls")]
        assert!(TokioRustlsRuntime::current().is_err());
    }

    #[test]
    fn current() {
        // Now start a tokio runtime and make sure that the "current" functions do work in that case.
        let runtime = PreferredRuntime::create().unwrap();
        runtime.block_on(async {
            #[cfg(feature = "native-tls")]
            assert!(TokioNativeTlsRuntime::current().is_ok());

            #[cfg(feature = "rustls")]
            assert!(TokioRustlsRuntime::current().is_ok());
        });
    }

    #[test]
    fn debug() {
        #[cfg(feature = "native-tls")]
        assert_eq!(
            format!("{:?}", TokioNativeTlsRuntime::create().unwrap()),
            "TokioNativeTlsRuntime { .. }"
        );
        #[cfg(feature = "rustls")]
        assert_eq!(
            format!("{:?}", TokioRustlsRuntime::create().unwrap()),
            "TokioRustlsRuntime { .. }"
        );

        // Just for fun, let's try the Debug output for the Compound.
        assert_eq!(
            format!("{:?}", PreferredRuntime::create().unwrap().inner),
            "CompoundRuntime { .. }"
        );
    }
}