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
use std::future::Future; use pyo3::{exceptions::PyException, prelude::*}; use crate::{dump_err, get_event_loop, CALL_SOON, CREATE_FUTURE, EXPECT_INIT}; /// Generic utilities for a JoinError pub trait JoinError { /// Check if the spawned task exited because of a panic fn is_panic(&self) -> bool; } /// Generic Rust async/await runtime pub trait Runtime { /// The error returned by a JoinHandle after being awaited type JoinError: JoinError + Send; /// A future that completes with the result of the spawned task type JoinHandle: Future<Output = Result<(), Self::JoinError>> + Send; /// Spawn a future onto this runtime's event loop fn spawn<F>(fut: F) -> Self::JoinHandle where F: Future<Output = ()> + Send + 'static; } /// Extension trait for async/await runtimes that support spawning local tasks pub trait SpawnLocalExt: Runtime { /// Spawn a !Send future onto this runtime's event loop fn spawn_local<F>(fut: F) -> Self::JoinHandle where F: Future<Output = ()> + 'static; } /// Run the event loop until the given Future completes /// /// After this function returns, the event loop can be resumed with either [`run_until_complete`] or /// [`crate::run_forever`] /// /// # Arguments /// * `py` - The current PyO3 GIL guard /// * `fut` - The future to drive to completion /// /// # Examples /// /// ```no_run /// # use std::{task::{Context, Poll}, pin::Pin, future::Future}; /// # /// # use pyo3_asyncio::generic::{JoinError, Runtime}; /// # /// # struct MyCustomJoinError; /// # /// # impl JoinError for MyCustomJoinError { /// # fn is_panic(&self) -> bool { /// # unreachable!() /// # } /// # } /// # /// # struct MyCustomJoinHandle; /// # /// # impl Future for MyCustomJoinHandle { /// # type Output = Result<(), MyCustomJoinError>; /// # /// # fn poll(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<Self::Output> { /// # unreachable!() /// # } /// # } /// # /// # struct MyCustomRuntime; /// # /// # impl Runtime for MyCustomRuntime { /// # type JoinError = MyCustomJoinError; /// # type JoinHandle = MyCustomJoinHandle; /// # /// # fn spawn<F>(fut: F) -> Self::JoinHandle /// # where /// # F: Future<Output = ()> + Send + 'static /// # { /// # unreachable!() /// # } /// # } /// # /// # use std::time::Duration; /// # /// # use pyo3::prelude::*; /// # /// # Python::with_gil(|py| { /// # pyo3_asyncio::with_runtime(py, || { /// # #[cfg(feature = "tokio-runtime")] /// pyo3_asyncio::generic::run_until_complete::<MyCustomRuntime, _>(py, async move { /// tokio::time::sleep(Duration::from_secs(1)).await; /// Ok(()) /// })?; /// # Ok(()) /// # }) /// # .map_err(|e| { /// # e.print_and_set_sys_last_vars(py); /// # }) /// # .unwrap(); /// # }); /// ``` pub fn run_until_complete<R, F>(py: Python, fut: F) -> PyResult<()> where R: Runtime, F: Future<Output = PyResult<()>> + Send + 'static, { let coro = into_coroutine::<R, _>(py, async move { fut.await?; Ok(Python::with_gil(|py| py.None())) })?; get_event_loop(py).call_method1("run_until_complete", (coro,))?; Ok(()) } fn cancelled(future: &PyAny) -> PyResult<bool> { future.getattr("cancelled")?.call0()?.is_true() } fn set_result(py: Python, future: &PyAny, result: PyResult<PyObject>) -> PyResult<()> { match result { Ok(val) => { let set_result = future.getattr("set_result")?; CALL_SOON .get() .expect(EXPECT_INIT) .call1(py, (set_result, val))?; } Err(err) => { let set_exception = future.getattr("set_exception")?; CALL_SOON .get() .expect(EXPECT_INIT) .call1(py, (set_exception, err))?; } } Ok(()) } /// Convert a Rust Future into a Python awaitable with a generic runtime /// /// # Arguments /// * `py` - The current PyO3 GIL guard /// * `fut` - The Rust future to be converted /// /// # Examples /// /// ```no_run /// # use std::{task::{Context, Poll}, pin::Pin, future::Future}; /// # /// # use pyo3_asyncio::generic::{JoinError, Runtime}; /// # /// # struct MyCustomJoinError; /// # /// # impl JoinError for MyCustomJoinError { /// # fn is_panic(&self) -> bool { /// # unreachable!() /// # } /// # } /// # /// # struct MyCustomJoinHandle; /// # /// # impl Future for MyCustomJoinHandle { /// # type Output = Result<(), MyCustomJoinError>; /// # /// # fn poll(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<Self::Output> { /// # unreachable!() /// # } /// # } /// # /// # struct MyCustomRuntime; /// # /// # impl MyCustomRuntime { /// # async fn sleep(_: Duration) { /// # unreachable!() /// # } /// # } /// # /// # impl Runtime for MyCustomRuntime { /// # type JoinError = MyCustomJoinError; /// # type JoinHandle = MyCustomJoinHandle; /// # /// # fn spawn<F>(fut: F) -> Self::JoinHandle /// # where /// # F: Future<Output = ()> + Send + 'static /// # { /// # unreachable!() /// # } /// # } /// # /// use std::time::Duration; /// /// use pyo3::prelude::*; /// /// /// Awaitable sleep function /// #[pyfunction] /// fn sleep_for(py: Python, secs: &PyAny) -> PyResult<PyObject> { /// let secs = secs.extract()?; /// /// pyo3_asyncio::generic::into_coroutine::<MyCustomRuntime, _>(py, async move { /// MyCustomRuntime::sleep(Duration::from_secs(secs)).await; /// Python::with_gil(|py| Ok(py.None())) /// }) /// } /// ``` pub fn into_coroutine<R, F>(py: Python, fut: F) -> PyResult<PyObject> where R: Runtime, F: Future<Output = PyResult<PyObject>> + Send + 'static, { let future_rx = CREATE_FUTURE.get().expect(EXPECT_INIT).call0(py)?; let future_tx1 = future_rx.clone(); let future_tx2 = future_rx.clone(); R::spawn(async move { if let Err(e) = R::spawn(async move { let result = fut.await; Python::with_gil(move |py| { if cancelled(future_tx1.as_ref(py)) .map_err(dump_err(py)) .unwrap_or(false) { return; } let _ = set_result(py, future_tx1.as_ref(py), result).map_err(dump_err(py)); }); }) .await { if e.is_panic() { Python::with_gil(move |py| { if cancelled(future_tx2.as_ref(py)) .map_err(dump_err(py)) .unwrap_or(false) { return; } let _ = set_result( py, future_tx2.as_ref(py), Err(PyException::new_err("rust future panicked")), ) .map_err(dump_err(py)); }); } } }); Ok(future_rx) } /// Convert a `!Send` Rust Future into a Python awaitable with a generic runtime /// /// # Arguments /// * `py` - The current PyO3 GIL guard /// * `fut` - The Rust future to be converted /// /// # Examples /// /// ```no_run /// # use std::{task::{Context, Poll}, pin::Pin, future::Future}; /// # /// # use pyo3_asyncio::generic::{JoinError, SpawnLocalExt, Runtime}; /// # /// # struct MyCustomJoinError; /// # /// # impl JoinError for MyCustomJoinError { /// # fn is_panic(&self) -> bool { /// # unreachable!() /// # } /// # } /// # /// # struct MyCustomJoinHandle; /// # /// # impl Future for MyCustomJoinHandle { /// # type Output = Result<(), MyCustomJoinError>; /// # /// # fn poll(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<Self::Output> { /// # unreachable!() /// # } /// # } /// # /// # struct MyCustomRuntime; /// # /// # impl MyCustomRuntime { /// # async fn sleep(_: Duration) { /// # unreachable!() /// # } /// # } /// # /// # impl Runtime for MyCustomRuntime { /// # type JoinError = MyCustomJoinError; /// # type JoinHandle = MyCustomJoinHandle; /// # /// # fn spawn<F>(fut: F) -> Self::JoinHandle /// # where /// # F: Future<Output = ()> + Send + 'static /// # { /// # unreachable!() /// # } /// # } /// # /// # impl SpawnLocalExt for MyCustomRuntime { /// # fn spawn_local<F>(fut: F) -> Self::JoinHandle /// # where /// # F: Future<Output = ()> + 'static /// # { /// # unreachable!() /// # } /// # } /// # /// use std::time::Duration; /// /// use pyo3::prelude::*; /// /// /// Awaitable sleep function /// #[pyfunction] /// fn sleep_for(py: Python, secs: u64) -> PyResult<&PyAny> { /// pyo3_asyncio::generic::local_future_into_py::<MyCustomRuntime, _>(py, async move { /// MyCustomRuntime::sleep(Duration::from_secs(secs)).await; /// Python::with_gil(|py| Ok(py.None())) /// }) /// } /// ``` pub fn local_future_into_py<R, F>(py: Python, fut: F) -> PyResult<&PyAny> where R: SpawnLocalExt, F: Future<Output = PyResult<PyObject>> + 'static, { let future_rx = CREATE_FUTURE.get().expect(EXPECT_INIT).as_ref(py).call0()?; let future_tx1 = PyObject::from(future_rx); let future_tx2 = future_tx1.clone(); R::spawn_local(async move { if let Err(e) = R::spawn_local(async move { let result = fut.await; Python::with_gil(move |py| { if cancelled(future_tx1.as_ref(py)) .map_err(dump_err(py)) .unwrap_or(false) { return; } let _ = set_result(py, future_tx1.as_ref(py), result).map_err(dump_err(py)); }); }) .await { if e.is_panic() { Python::with_gil(move |py| { if cancelled(future_tx2.as_ref(py)) .map_err(dump_err(py)) .unwrap_or(false) { return; } let _ = set_result( py, future_tx2.as_ref(py), Err(PyException::new_err("rust future panicked")), ) .map_err(dump_err(py)); }); } } }); Ok(future_rx) }