switchy_async 0.2.0

Switchy Async runtime package
Documentation
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//! Tokio runtime types and builders.
//!
//! This module provides the runtime and handle types for the Tokio backend,
//! including builders for configuring and creating runtimes.

use std::{
    sync::{Arc, Weak},
    time::Duration,
};

use tokio::task::JoinHandle;

use crate::{Error, GenericRuntime};

pub use crate::Builder;

/// A handle to a tokio runtime that provides task spawning and execution capabilities.
///
/// This wrapper around tokio's Handle maintains a weak reference to the parent runtime
/// to enable proper I/O and timer driver access, particularly for signal handling.
#[derive(Debug, Clone)]
pub struct Handle {
    inner: tokio::runtime::Handle,
    // Keep a weak reference to prevent circular dependencies
    runtime: Weak<tokio::runtime::Runtime>,
}

impl Handle {
    /// Creates a new Handle from an Arc-wrapped runtime.
    fn new(runtime: &Arc<tokio::runtime::Runtime>) -> Self {
        Self {
            inner: runtime.handle().clone(),
            runtime: Arc::downgrade(runtime),
        }
    }

    /// Blocks on a future using the parent Runtime instead of Handle.
    ///
    /// This ensures proper I/O and timer driver access for signal handling.
    /// If the runtime has been dropped, falls back to the inner handle's `block_on`.
    pub fn block_on<F: std::future::Future>(&self, future: F) -> F::Output {
        if let Some(runtime) = self.runtime.upgrade() {
            // Use Runtime::block_on which can drive IO/timers
            runtime.block_on(future)
        } else {
            // Fallback to Handle::block_on if runtime is dropped
            // This maintains existing behavior for edge cases
            self.inner.block_on(future)
        }
    }

    /// Spawns a future onto the runtime.
    ///
    /// Returns a `JoinHandle` that can be awaited to get the future's result.
    pub fn spawn<T: Send + 'static>(
        &self,
        future: impl std::future::Future<Output = T> + Send + 'static,
    ) -> JoinHandle<T> {
        self.inner.spawn(future)
    }

    /// Spawns a named future onto the runtime.
    ///
    /// The name is used for logging when trace-level logging is enabled.
    pub fn spawn_with_name<T: Send + 'static>(
        &self,
        name: &str,
        future: impl std::future::Future<Output = T> + Send + 'static,
    ) -> JoinHandle<T> {
        if log::log_enabled!(log::Level::Trace) {
            log::trace!("spawn start: {name}");
            let name = name.to_owned();
            let future = async move {
                let response = future.await;
                log::trace!("spawn finished: {name}");
                response
            };
            self.inner.spawn(future)
        } else {
            self.inner.spawn(future)
        }
    }

    /// Spawns a blocking task onto the runtime.
    ///
    /// Returns a `JoinHandle` that can be awaited to get the task's result.
    pub fn spawn_blocking<T: Send + 'static>(
        &self,
        f: impl FnOnce() -> T + Send + 'static,
    ) -> JoinHandle<T> {
        self.inner.spawn_blocking(f)
    }

    /// Spawns a named blocking task onto the runtime.
    ///
    /// The name is used for logging when trace-level logging is enabled.
    pub fn spawn_blocking_with_name<T: Send + 'static>(
        &self,
        name: &str,
        f: impl FnOnce() -> T + Send + 'static,
    ) -> JoinHandle<T> {
        if log::log_enabled!(log::Level::Trace) {
            log::trace!("spawn_blocking start: {name}");
            let name = name.to_owned();
            let f = move || {
                let response = f();
                log::trace!("spawn_blocking finished: {name}");
                response
            };
            self.inner.spawn_blocking(f)
        } else {
            self.inner.spawn_blocking(f)
        }
    }

    /// Spawns a non-Send future onto the current thread.
    ///
    /// This allows spawning futures that are not `Send`, which must run on the current thread.
    /// Returns a `JoinHandle` that can be awaited to get the future's result.
    pub fn spawn_local<T: 'static>(
        &self,
        future: impl std::future::Future<Output = T> + 'static,
    ) -> JoinHandle<T> {
        tokio::task::spawn_local(future)
    }

    /// Spawns a named non-Send future onto the current thread.
    ///
    /// The name is used for logging when trace-level logging is enabled.
    pub fn spawn_local_with_name<T: 'static>(
        &self,
        name: &str,
        future: impl std::future::Future<Output = T> + 'static,
    ) -> JoinHandle<T> {
        if log::log_enabled!(log::Level::Trace) {
            log::trace!("spawn_local start: {name}");
            let name = name.to_owned();
            let future = async move {
                let response = future.await;
                log::trace!("spawn_local finished: {name}");
                response
            };
            tokio::task::spawn_local(future)
        } else {
            tokio::task::spawn_local(future)
        }
    }

    /// Returns a handle to the currently running runtime.
    ///
    /// # Panics
    ///
    /// Panics if no runtime is currently running on this thread.
    #[must_use]
    pub fn current() -> Self {
        // We can't easily get the Runtime reference from a static context,
        // so we create a Handle that will fall back to tokio::runtime::Handle::block_on
        Self {
            inner: tokio::runtime::Handle::current(),
            runtime: Weak::new(), // Empty weak reference - will always fall back
        }
    }

    /// Try to get the current runtime handle
    ///
    /// # Errors
    ///
    /// * If no runtime is currently running on this thread
    pub fn try_current() -> Result<Self, tokio::runtime::TryCurrentError> {
        tokio::runtime::Handle::try_current().map(|inner| Self {
            inner,
            runtime: Weak::new(),
        })
    }
}

/// A tokio-based async runtime.
///
/// This provides a wrapper around tokio's Runtime with additional utilities for task spawning,
/// blocking execution, and graceful shutdown.
#[derive(Debug)]
pub struct Runtime {
    inner: Arc<tokio::runtime::Runtime>,
}

impl Default for Runtime {
    fn default() -> Self {
        Self::new()
    }
}

impl Runtime {
    /// Creates a new runtime with default settings.
    ///
    /// # Panics
    ///
    /// * If `build_runtime` fails
    #[must_use]
    pub fn new() -> Self {
        build_runtime(&Builder::new()).unwrap()
    }

    /// Spawns a future onto the runtime.
    ///
    /// Returns a `JoinHandle` that can be awaited to get the future's result.
    pub fn spawn<T: Send + 'static>(
        &self,
        future: impl std::future::Future<Output = T> + Send + 'static,
    ) -> JoinHandle<T> {
        self.inner.spawn(future)
    }

    /// Spawns a named future onto the runtime.
    ///
    /// The name is used for logging when trace-level logging is enabled.
    pub fn spawn_with_name<T: Send + 'static>(
        &self,
        name: &str,
        future: impl std::future::Future<Output = T> + Send + 'static,
    ) -> JoinHandle<T> {
        self.handle().spawn_with_name(name, future)
    }

    /// Spawns a blocking task onto the runtime.
    ///
    /// Returns a `JoinHandle` that can be awaited to get the task's result.
    pub fn spawn_blocking<T: Send + 'static>(
        &self,
        f: impl FnOnce() -> T + Send + 'static,
    ) -> JoinHandle<T> {
        self.inner.spawn_blocking(f)
    }

    /// Spawns a named blocking task onto the runtime.
    ///
    /// The name is used for logging when trace-level logging is enabled.
    pub fn spawn_blocking_with_name<T: Send + 'static>(
        &self,
        name: &str,
        f: impl FnOnce() -> T + Send + 'static,
    ) -> JoinHandle<T> {
        self.handle().spawn_blocking_with_name(name, f)
    }

    /// Returns a handle to this runtime.
    #[must_use]
    pub fn handle(&self) -> Handle {
        Handle::new(&self.inner)
    }
}

impl GenericRuntime for Runtime {
    fn block_on<F: std::future::Future>(&self, future: F) -> F::Output {
        self.inner.block_on(future)
    }

    /// FIXME: This doesn't await all tasks. We probably need to add all
    /// the task handles to a collection manually to handle this properly.
    fn wait(self) -> Result<(), Error> {
        // Extract the Arc and wait for all references to drop
        Arc::try_unwrap(self.inner).map_or_else(
            |_| {
                // Other references exist, cannot cleanly shutdown
                log::warn!("Runtime has outstanding references, forcing shutdown");
                Ok(())
            },
            |runtime| {
                runtime.shutdown_timeout(Duration::from_secs(10_000_000));
                Ok(())
            },
        )
    }
}

/// Builds a new tokio runtime from the given builder.
///
/// # Errors
///
/// * If the underlying tokio runtime fails to build
#[allow(unused)]
pub(crate) fn build_runtime(#[allow(unused)] builder: &Builder) -> Result<Runtime, Error> {
    #[cfg(feature = "rt-multi-thread")]
    #[allow(clippy::option_if_let_else)]
    let mut builder = if let Some(threads) = builder.max_blocking_threads {
        let mut builder = tokio::runtime::Builder::new_multi_thread();

        builder.max_blocking_threads(threads as usize);

        builder
    } else {
        tokio::runtime::Builder::new_current_thread()
    };
    #[cfg(not(feature = "rt-multi-thread"))]
    let mut builder = tokio::runtime::Builder::new_current_thread();

    #[cfg(feature = "time")]
    builder.enable_time();

    #[cfg(feature = "net")]
    builder.enable_io();

    Ok(Runtime {
        inner: Arc::new(builder.build()?),
    })
}

#[cfg(test)]
mod test {
    #[allow(unused)]
    use pretty_assertions::{assert_eq, assert_ne};
    use tokio::task;

    #[allow(unused)]
    use crate::GenericRuntime as _;
    use crate::{Builder, tokio::runtime::build_runtime};

    #[test]
    fn rt_current_thread_runtime_spawns_on_same_thread() {
        let runtime = build_runtime(&Builder::new()).unwrap();

        let thread_id = std::thread::current().id();

        runtime.block_on(async move {
            task::spawn(async move { assert_eq!(std::thread::current().id(), thread_id) })
                .await
                .unwrap();
        });

        runtime.wait().unwrap();
    }

    #[test]
    fn rt_current_thread_runtime_block_on_same_thread() {
        let runtime = build_runtime(&Builder::new()).unwrap();

        let thread_id = std::thread::current().id();

        runtime.block_on(async move {
            assert_eq!(std::thread::current().id(), thread_id);
        });

        runtime.wait().unwrap();
    }

    #[cfg(feature = "rt-multi-thread")]
    #[test]
    fn rt_multi_thread_runtime_spawns_new_thread() {
        let runtime = build_runtime(Builder::new().max_blocking_threads(1)).unwrap();

        let thread_id = std::thread::current().id();

        runtime.block_on(async move {
            task::spawn(async move { assert_ne!(std::thread::current().id(), thread_id) })
                .await
                .unwrap();
        });

        runtime.wait().unwrap();
    }

    #[cfg(feature = "rt-multi-thread")]
    #[test]
    fn rt_multi_thread_runtime_block_on_same_thread() {
        let runtime = build_runtime(Builder::new().max_blocking_threads(1)).unwrap();

        let thread_id = std::thread::current().id();

        runtime.block_on(async move {
            assert_eq!(std::thread::current().id(), thread_id);
        });

        runtime.wait().unwrap();
    }

    #[test]
    fn handle_block_on_with_signals() {
        let runtime = build_runtime(&Builder::new()).unwrap();
        let handle = runtime.handle();

        // Test that Handle::block_on can handle signal-like operations
        let result = handle.block_on(async {
            #[cfg(feature = "time")]
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            "success"
        });

        assert_eq!(result, "success");
        runtime.wait().unwrap();
    }

    #[test]
    fn handle_survives_runtime_drop() {
        let handle = {
            let runtime = build_runtime(&Builder::new()).unwrap();
            runtime.handle()
        };

        // Handle should still work even after runtime is dropped
        // (though it will fall back to inner Handle::block_on)
        let result = handle.block_on(async { "fallback" });
        assert_eq!(result, "fallback");
    }

    #[test]
    fn handle_delegates_to_runtime_block_on() {
        let runtime = build_runtime(&Builder::new()).unwrap();
        let handle = runtime.handle();

        // Verify that Handle::block_on works the same as Runtime::block_on
        let runtime_result = runtime.block_on(async { 42 });
        let handle_result = handle.block_on(async { 42 });

        assert_eq!(runtime_result, handle_result);
        runtime.wait().unwrap();
    }

    #[test]
    fn handle_current_returns_custom_handle() {
        let runtime = build_runtime(&Builder::new()).unwrap();

        runtime.block_on(async {
            // Test that Handle::current() returns our custom Handle type
            let current_handle = super::Handle::current();
            // Just verify we can get the handle and it has the right type
            // We can't test block_on from within a runtime context
            let _spawned = current_handle.spawn(async { "spawned_works" });
        });

        runtime.wait().unwrap();
    }
}