use std::future::Future;
use std::pin::Pin;
use futures_core::Stream;
use tokio::runtime::{Handle, RuntimeFlavor};
use tokio::sync::mpsc;
use crate::offload::{STREAM_BUFFER, pump};
use crate::stream::next;
use crate::{BoxIter, ChannelStream, Error, RuntimeCode};
#[derive(Clone, Debug)]
pub struct Blocking<T> {
service: T,
handle: Handle,
}
impl<T> Blocking<T> {
pub fn new(service: T, handle: Handle) -> Blocking<T> {
Blocking { service, handle }
}
pub fn get_ref(this: &Blocking<T>) -> &T {
&this.service
}
pub fn into_inner(this: Blocking<T>) -> T {
this.service
}
pub fn block_on<R>(
this: &Blocking<T>,
call: impl Future<Output = Result<R, Error>>,
) -> Result<R, Error> {
block_on(&this.handle, call)
}
pub fn block_on_stream<X, S>(
this: &Blocking<T>,
call: impl Future<Output = Result<S, Error>>,
) -> Result<BoxIter<'static, Result<X, Error>>, Error>
where
S: Stream<Item = Result<X, Error>> + Send + 'static,
X: Send + 'static,
{
let stream = Blocking::block_on(this, call)?;
Ok(Box::new(BlockingIter {
handle: this.handle.clone(),
stream: Some(Box::pin(stream)),
}))
}
pub fn feed<X: Send + 'static>(
this: &Blocking<T>,
requests: BoxIter<'static, Result<X, Error>>,
) -> ChannelStream<Result<X, Error>> {
let (sender, receiver) = mpsc::channel(STREAM_BUFFER);
drop(this.handle.spawn_blocking(move || pump(requests, &sender)));
ChannelStream::new(receiver)
}
}
fn block_on<R>(
handle: &Handle,
future: impl Future<Output = Result<R, Error>>,
) -> Result<R, Error> {
check_can_block()?;
tokio::task::block_in_place(|| handle.block_on(future))
}
fn check_can_block() -> Result<(), Error> {
match Handle::try_current() {
Ok(current) if current.runtime_flavor() == RuntimeFlavor::CurrentThread => Err(Error::new(
RuntimeCode::CannotBlock,
"a sync call through Blocking cannot wait inside a current-thread tokio \
runtime; call it from a std::thread or use a multi-thread runtime",
)),
_ => Ok(()),
}
}
struct BlockingIter<S> {
handle: Handle,
stream: Option<Pin<Box<S>>>,
}
impl<X, S: Stream<Item = Result<X, Error>>> Iterator for BlockingIter<S> {
type Item = Result<X, Error>;
fn next(&mut self) -> Option<Result<X, Error>> {
let stream = self.stream.as_mut()?;
let item = match block_on(&self.handle, async { Ok(next(stream).await) }) {
Ok(item) => item,
Err(error) => Some(Err(error)),
};
if !matches!(item, Some(Ok(_))) {
self.stream = None;
}
item
}
}