use std::any::Any;
use std::future::Future;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
use futures_core::Stream;
use tokio::runtime::Handle;
use tokio::sync::{mpsc, oneshot};
use crate::stream::next;
use crate::{BoxIter, ChannelStream, Error, Failure, RuntimeCode};
pub(crate) const STREAM_BUFFER: usize = 16;
#[derive(Debug)]
pub struct Offload<T> {
service: Arc<T>,
handle: Handle,
}
impl<T> Clone for Offload<T> {
fn clone(&self) -> Offload<T> {
Offload {
service: Arc::clone(&self.service),
handle: self.handle.clone(),
}
}
}
impl<T> Offload<T> {
pub fn new(service: T, handle: Handle) -> Offload<T> {
Offload::from_arc(Arc::new(service), handle)
}
pub fn from_arc(service: Arc<T>, handle: Handle) -> Offload<T> {
Offload { service, handle }
}
pub fn get_ref(this: &Offload<T>) -> &T {
&this.service
}
}
impl<T: Send + Sync + 'static> Offload<T> {
pub fn call<R, F>(
this: &Offload<T>,
call: F,
) -> impl Future<Output = Result<R, Error>> + Send + 'static
where
F: FnOnce(&T) -> Result<R, Error> + Send + 'static,
R: Send + 'static,
{
let (service, handle) = (Arc::clone(&this.service), this.handle.clone());
async move {
let task = handle.spawn_blocking(move || {
catch_unwind(AssertUnwindSafe(|| call(&service)))
.unwrap_or_else(|panic| Err(panicked(&panic)))
});
task.await.unwrap_or_else(|error| Err(join_failed(error)))
}
}
pub fn server_streaming<X, F>(
this: &Offload<T>,
call: F,
) -> impl Future<Output = Result<ChannelStream<Result<X, Error>>, Error>> + Send + 'static
where
F: FnOnce(&T) -> Result<BoxIter<'static, Result<X, Error>>, Error> + Send + 'static,
X: Send + 'static,
{
let (service, handle) = (Arc::clone(&this.service), this.handle.clone());
streaming(handle, move || call(&service))
}
pub fn client_streaming<S, X, R, F>(
this: &Offload<T>,
requests: S,
call: F,
) -> impl Future<Output = Result<R, Error>> + Send + 'static
where
S: Stream<Item = Result<X, Error>> + Send + 'static,
X: Send + 'static,
F: FnOnce(&T, BoxIter<'static, Result<X, Error>>) -> Result<R, Error> + Send + 'static,
R: Send + 'static,
{
let inbound = this.handle.clone();
Offload::call(this, move |service| {
call(service, Box::new(StreamIter::new(inbound, requests)))
})
}
pub fn bidirectional<S, X, Y, F>(
this: &Offload<T>,
requests: S,
call: F,
) -> impl Future<Output = Result<ChannelStream<Result<Y, Error>>, Error>> + Send + 'static
where
S: Stream<Item = Result<X, Error>> + Send + 'static,
X: Send + 'static,
Y: Send + 'static,
F: FnOnce(
&T,
BoxIter<'static, Result<X, Error>>,
) -> Result<BoxIter<'static, Result<Y, Error>>, Error>
+ Send
+ 'static,
{
let (service, handle) = (Arc::clone(&this.service), this.handle.clone());
let inbound = handle.clone();
streaming(handle, move || {
call(&service, Box::new(StreamIter::new(inbound, requests)))
})
}
}
async fn streaming<X, F>(handle: Handle, start: F) -> Result<ChannelStream<Result<X, Error>>, Error>
where
F: FnOnce() -> Result<BoxIter<'static, Result<X, Error>>, Error> + Send + 'static,
X: Send + 'static,
{
let (sender, receiver) = mpsc::channel(STREAM_BUFFER);
let (started, start_result) = oneshot::channel();
drop(handle.spawn_blocking(move || {
let items = match catch_unwind(AssertUnwindSafe(start)) {
Ok(Ok(items)) => items,
Ok(Err(error)) => {
let _ = started.send(Err(error));
return;
}
Err(panic) => {
let _ = started.send(Err(panicked(&panic)));
return;
}
};
if started.send(Ok(())).is_ok() {
pump(items, &sender);
}
}));
match start_result.await {
Ok(Ok(())) => Ok(ChannelStream::new(receiver)),
Ok(Err(error)) => Err(error),
Err(_) => Err(Error::new(
RuntimeCode::Cancelled,
"the blocking call ended without a result",
)),
}
}
pub(crate) fn pump<X>(
mut items: BoxIter<'static, Result<X, Error>>,
sender: &mpsc::Sender<Result<X, Error>>,
) {
loop {
let item = match catch_unwind(AssertUnwindSafe(|| items.next())) {
Ok(Some(item)) => item,
Ok(None) => return,
Err(panic) => {
let _ = sender.blocking_send(Err(panicked(&panic)));
return;
}
};
let ends = item.is_err();
if sender.blocking_send(item).is_err() || ends {
return;
}
}
}
fn join_failed(error: tokio::task::JoinError) -> Error {
let code = if error.is_panic() {
RuntimeCode::Panicked
} else {
RuntimeCode::Cancelled
};
Failure::new(code, "the blocking call failed")
.with_source(error)
.into()
}
pub(crate) fn panicked(panic: &Box<dyn Any + Send>) -> Error {
let message = panic
.downcast_ref::<&str>()
.copied()
.or_else(|| panic.downcast_ref::<String>().map(String::as_str))
.unwrap_or("no message");
Error::new(
RuntimeCode::Panicked,
format!("the implementation panicked: {message}"),
)
}
struct StreamIter<S> {
handle: Handle,
stream: std::pin::Pin<Box<S>>,
}
impl<S> StreamIter<S> {
fn new(handle: Handle, stream: S) -> StreamIter<S> {
StreamIter {
handle,
stream: Box::pin(stream),
}
}
}
impl<S: Stream> Iterator for StreamIter<S> {
type Item = S::Item;
fn next(&mut self) -> Option<S::Item> {
self.handle.block_on(next(&mut self.stream))
}
}