use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use serde_json::Value;
use super::ChannelEnd;
use crate::{Context, Result};
pub type ChannelFuture = Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>;
#[non_exhaustive]
pub struct ChannelRequest {
pub options: Value,
pub context: Option<Context>,
pub end: ChannelEnd,
}
pub trait ChannelService: Send + Sync + 'static {
fn open(&self, request: ChannelRequest) -> ChannelFuture;
}
impl<T: ChannelService + ?Sized> ChannelService for Arc<T> {
fn open(&self, request: ChannelRequest) -> ChannelFuture {
(**self).open(request)
}
}
struct FunctionService<F>(F);
impl<F, Fut> ChannelService for FunctionService<F>
where
F: Fn(ChannelRequest) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
fn open(&self, request: ChannelRequest) -> ChannelFuture {
Box::pin((self.0)(request))
}
}
pub fn channel_fn<F, Fut>(function: F) -> impl ChannelService
where
F: Fn(ChannelRequest) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
FunctionService(function)
}