use std::any::TypeId;
use std::future::Future;
use std::net::SocketAddr;
use std::sync::Arc;
use crate::app::AppHandle;
use crate::error::RuntimeMissing;
use crate::graph::scopes::input_reads;
use crate::key::{BindingKind, Key};
use crate::module::handle::ModuleRef;
use crate::module::meta::Meta;
use crate::runtime::Runtime;
use crate::timer::{BoxError, BoxFuture, Timer};
use crate::transport::Transport;
use crate::transport::controller::MountedHandler;
use crate::type_name::TypeName;
pub trait Server: Send + Sync + 'static {
type Transport: Transport;
fn prepare(&mut self, mounted: Mounted<'_, Self::Transport>) -> impl Future<Output = Result<(), BoxError>> + Send {
let _ = mounted;
async { Ok(()) }
}
fn bind(&mut self, mounted: Mounted<'_, Self::Transport>) -> impl Future<Output = Result<(), BoxError>> + Send;
fn serve(&self) -> impl Future<Output = Result<(), BoxError>> + Send;
fn drain(&self, token: DrainToken) -> impl Future<Output = ()> + Send;
fn close(&self) -> impl Future<Output = Result<(), BoxError>> + Send;
fn bound(&self) -> Vec<BoundAddr> {
Vec::new()
}
}
pub struct Mounted<'a, T: Transport> {
pub(crate) handlers: &'a [MountedHandler<T>],
pub(crate) app: AppHandle,
pub(crate) timer: Arc<dyn Timer>,
pub(crate) runtime: Arc<dyn Runtime>,
}
impl<T: Transport> Mounted<'_, T> {
pub fn handlers(&self) -> &[MountedHandler<T>] {
self.handlers
}
pub fn handlers_of<U: Transport>(&self) -> Vec<MountedHandler<U>> {
mounted_handlers::<U>(&self.app)
}
pub fn app(&self) -> &AppHandle {
&self.app
}
pub fn timer(&self) -> &Arc<dyn Timer> {
&self.timer
}
pub fn runtime(&self) -> &Arc<dyn Runtime> {
&self.runtime
}
pub fn module_meta<M: Meta>(&self) -> Vec<(ModuleRef, Arc<M>)> {
let shared = &self.app.shared;
let graph = shared.graph();
graph
.modules
.iter()
.filter_map(|module| {
let value = Arc::clone(module.meta.get(&TypeId::of::<M>())?);
let value = value.downcast::<M>().ok()?;
Some((shared.module_ref(module.id), value))
})
.collect()
}
}
impl<'a, T: Transport> Mounted<'a, T> {
pub fn handlers_reading<I: Send + Sync + 'static>(&self) -> Vec<InputReader<'a, T>> {
let key = Key::of::<I, ()>();
let graph = self.app.shared.graph();
let mut readers = Vec::new();
for record in &graph.handlers {
let Some(handler) = self.handlers.iter().find(|handler| Arc::ptr_eq(&handler.info, &record.info)) else {
continue;
};
for read in input_reads(&graph, record).into_iter().filter(|read| read.input == key) {
readers.push(InputReader { handler, steps: read.steps });
}
}
readers
}
}
pub struct InputReader<'a, T: Transport> {
handler: &'a MountedHandler<T>,
steps: Vec<String>,
}
impl<'a, T: Transport> InputReader<'a, T> {
pub fn handler(&self) -> &'a MountedHandler<T> {
self.handler
}
pub fn transport(&self) -> TypeName {
TypeName::of::<T>()
}
pub fn steps(&self) -> &[String] {
&self.steps
}
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BoundAddr {
pub transport: &'static str,
pub addr: SocketAddr,
pub tls: bool,
}
impl BoundAddr {
pub fn new(transport: &'static str, addr: SocketAddr) -> Self {
BoundAddr { transport, addr, tls: false }
}
pub fn tls(self, tls: bool) -> Self {
BoundAddr { tls, ..self }
}
}
#[derive(Clone)]
pub struct DrainToken {
_inner: Arc<()>,
}
impl DrainToken {
pub(crate) fn new() -> Self {
DrainToken { _inner: Arc::new(()) }
}
}
pub(crate) trait ErasedServer: Send + Sync + 'static {
fn transport_name(&self) -> TypeName;
fn prepare<'a>(&'a mut self, app: &'a AppHandle) -> BoxFuture<'a, Result<(), BoxError>>;
fn bind<'a>(&'a mut self, app: &'a AppHandle) -> BoxFuture<'a, Result<(), BoxError>>;
fn serve(&self) -> BoxFuture<'_, Result<(), BoxError>>;
fn drain(&self, token: DrainToken) -> BoxFuture<'_, ()>;
fn close(&self) -> BoxFuture<'_, Result<(), BoxError>>;
fn bound(&self) -> Vec<BoundAddr>;
}
pub(crate) fn mounted_parts<T: Transport>(
app: &AppHandle,
) -> Result<(Vec<MountedHandler<T>>, Arc<dyn Runtime>), RuntimeMissing> {
let Some(runtime) = app.shared.config.runtime.clone() else {
return Err(RuntimeMissing { transport: TypeName::of::<T>() });
};
Ok((mounted_handlers::<T>(app), runtime))
}
fn mounted_handlers<T: Transport>(app: &AppHandle) -> Vec<MountedHandler<T>> {
let graph = app.shared.graph();
graph
.handlers
.iter()
.filter(|h| h.decl.transport == TypeName::of::<T>())
.filter_map(|h| {
let controller = graph.binding(h.controller).record.keys().next()?.name(BindingKind::Single);
h.mounted(app.shared.module_ref(h.module), controller)
})
.collect()
}
impl<S: Server> ErasedServer for S {
fn transport_name(&self) -> TypeName {
TypeName::of::<S::Transport>()
}
fn prepare<'a>(&'a mut self, app: &'a AppHandle) -> BoxFuture<'a, Result<(), BoxError>> {
Box::pin(async move {
let (handlers, runtime) = mounted_parts::<S::Transport>(app).map_err(BoxError::from)?;
let timer = Arc::clone(&runtime) as Arc<dyn Timer>;
<S as Server>::prepare(self, Mounted { handlers: &handlers, app: app.clone(), timer, runtime }).await
})
}
fn bind<'a>(&'a mut self, app: &'a AppHandle) -> BoxFuture<'a, Result<(), BoxError>> {
Box::pin(async move {
let (handlers, runtime) = mounted_parts::<S::Transport>(app).map_err(BoxError::from)?;
let timer = Arc::clone(&runtime) as Arc<dyn Timer>;
<S as Server>::bind(self, Mounted { handlers: &handlers, app: app.clone(), timer, runtime }).await
})
}
fn serve(&self) -> BoxFuture<'_, Result<(), BoxError>> {
Box::pin(Server::serve(self))
}
fn drain(&self, token: DrainToken) -> BoxFuture<'_, ()> {
Box::pin(Server::drain(self, token))
}
fn close(&self) -> BoxFuture<'_, Result<(), BoxError>> {
Box::pin(Server::close(self))
}
fn bound(&self) -> Vec<BoundAddr> {
Server::bound(self)
}
}