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
#![deny(warnings)]
#![deny(missing_docs)]
#![allow(clippy::needless_doctest_main)]
//! Provides the ability to execute async code from a sync context,
//! without blocking a tokio core thread or busy looping the cpu.
//!
//! # Example
//!
//! ```
//! #[tokio::main(threaded_scheduler)]
//! async fn main() {
//!     // we need to ensure we are in the context of a tokio task
//!     tokio::task::spawn(async move {
//!         // some library api may take a sync callback
//!         // but we want to be able to execute async code
//!         (|| {
//!             let r = tokio_safe::tokio_safe(
//!                 // async code to poll synchronously
//!                 async move {
//!                     // simulate some async work
//!                     tokio::time::delay_for(
//!                         std::time::Duration::from_millis(2)
//!                     ).await;
//!
//!                     // return our result
//!                     "test"
//!                 },
//!
//!                 // timeout to allow async execution
//!                 std::time::Duration::from_millis(10),
//!             ).unwrap();
//!
//!             // note we get the result inline with no `await`
//!             assert_eq!("test", r);
//!         })()
//!     })
//!     .await
//!     .unwrap();
//! }
//! ```

/// Error Type
#[derive(Debug, PartialEq)]
pub enum BlockOnError {
    /// The future did not complete within the time alloted.
    Timeout,
}

impl std::fmt::Display for BlockOnError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

impl std::error::Error for BlockOnError {}

/// Provides the ability to execute async code from a sync context,
/// without blocking a tokio core thread or busy looping the cpu.
/// You must ensure you are within the context of a tokio::task,
/// This allows `tokio::task::block_in_place` to move to a blocking thread.
/// This version will never time out - you may end up binding a
/// tokio background thread forever.
pub fn tokio_safe_block_forever_on<F: std::future::Future>(f: F) -> F::Output {
    // work around pin requirements with a Box
    let f = Box::pin(f);

    let handle = tokio::runtime::Handle::current();
    // first, we need to make sure to move this thread to the background
    tokio::task::block_in_place(move || {
        // poll until we get a result
        // futures::executor::block_on(async move { f.await })
        handle.block_on(async move { f.await })
    })
}

/// Provides the ability to execute async code from a sync context,
/// without blocking a tokio core thread or busy looping the cpu.
/// You must ensure you are within the context of a tokio::task,
/// This allows `tokio::task::block_in_place` to move to a blocking thread.
pub fn tokio_safe<F: std::future::Future>(
    f: F,
    timeout: std::time::Duration,
) -> Result<F::Output, BlockOnError> {
    // work around pin requirements with a Box
    let f = Box::pin(f);

    let handle = tokio::runtime::Handle::current();
    // first, we need to make sure to move this thread to the background
    tokio::task::block_in_place(move || {
        // poll until we get a result or a timeout
        // futures::executor::block_on(async move {
        handle.block_on(async move {
            match futures::future::select(f, tokio::time::delay_for(timeout)).await {
                futures::future::Either::Left((res, _)) => Ok(res),
                futures::future::Either::Right(_) => Err(BlockOnError::Timeout),
            }
        })
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test(threaded_scheduler)]
    async fn it_should_execute_async_from_sync_context_forever() {
        tokio::task::spawn(async move {
            (|| {
                let result = tokio_safe_block_forever_on(async move { "test0" });
                assert_eq!("test0", result);
            })()
        })
        .await
        .unwrap();
    }

    #[tokio::test(threaded_scheduler)]
    async fn it_should_execute_async_from_sync_context() {
        tokio::task::spawn(async move {
            (|| {
                let result = tokio_safe(
                    async move { "test1" },
                    std::time::Duration::from_millis(10),
                );
                assert_eq!("test1", result.unwrap());
            })()
        })
        .await
        .unwrap();
    }

    #[tokio::test(threaded_scheduler)]
    async fn it_should_execute_timed_async_from_sync_context() {
        tokio::task::spawn(async move {
            (|| {
                let result = tokio_safe(
                    async move {
                        tokio::time::delay_for(std::time::Duration::from_millis(2)).await;
                        "test2"
                    },
                    std::time::Duration::from_millis(10),
                );
                assert_eq!("test2", result.unwrap());
            })()
        })
        .await
        .unwrap();
    }

    #[tokio::test(threaded_scheduler)]
    async fn it_should_timeout_timed_async_from_sync_context() {
        tokio::task::spawn(async move {
            (|| {
                let result = tokio_safe(
                    async move {
                        tokio::time::delay_for(std::time::Duration::from_millis(10)).await;
                        "test3"
                    },
                    std::time::Duration::from_millis(2),
                );
                assert_eq!(BlockOnError::Timeout, result.unwrap_err());
            })()
        })
        .await
        .unwrap();
    }
}