use std::future::Future; use background_jobs_core::{JoinError, UnsendSpawner}; use tokio::task::JoinHandle; /// Provide a spawner for actix-based systems for Unsend Jobs #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ActixSpawner; #[doc(hidden)] pub struct ActixHandle(Option>); impl UnsendSpawner for ActixSpawner { type Handle = ActixHandle where T: Send; fn spawn(future: Fut) -> Self::Handle where Fut: Future + 'static, Fut::Output: Send + 'static, { ActixHandle(crate::spawn::spawn("job-task", future).ok()) } } impl Unpin for ActixHandle {} impl Future for ActixHandle { type Output = Result; fn poll( mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, ) -> std::task::Poll { if let Some(mut handle) = self.0.as_mut() { let res = std::task::ready!(std::pin::Pin::new(&mut handle).poll(cx)); std::task::Poll::Ready(res.map_err(|_| JoinError)) } else { std::task::Poll::Ready(Err(JoinError)) } } } impl Drop for ActixHandle { fn drop(&mut self) { if let Some(handle) = &self.0 { handle.abort(); } } }