pub(crate) mod handle;
pub(crate) mod load;
pub(crate) mod shared;
use std::future::{Future, poll_fn};
use std::marker::PhantomData;
use std::pin::{Pin, pin};
use std::sync::{Arc, PoisonError};
use std::task::Poll;
use std::time::Duration;
use crate::app::shared::AppShared;
use crate::binding::Qualifier;
use crate::dependency::Dep;
use crate::error::{Closed, ConfigureErrors, LookupError, RuntimeMissing, Shutdown, ShutdownError, StartupError};
use crate::execution::{ExecOptions, Execution};
use crate::graph::{ModuleId, wire};
use crate::lifecycle::phase::Phase as Stage;
use crate::lifecycle::{connect, shutdown};
use crate::module::Module;
use crate::module::handle::ModuleRef;
use crate::redact::{Redacted, Redactor, redact};
use crate::runtime::{Clocked, Runtime};
use crate::signal::Signal;
use crate::testing::TestPlan;
use crate::timer::{BoxError, BoxFuture, Defaults, Timer};
use crate::transport::server::{BoundAddr, ErasedServer, Server};
pub use handle::{AppHandle, Phase};
pub enum Wired {}
pub enum Connected {}
pub enum Bound {}
pub struct App<S = Wired> {
pub(crate) shared: Arc<AppShared>,
pub(crate) servers: Vec<Box<dyn ErasedServer>>,
_s: PhantomData<S>,
}
pub struct AppBuilder {
pub(crate) root: Box<dyn Module>,
pub(crate) config: AppConfig,
pub(crate) plan: Option<TestPlan>,
}
#[derive(Clone, Default)]
pub(crate) struct AppConfig {
pub(crate) timer: Option<Arc<dyn Timer>>,
pub(crate) runtime: Option<Arc<dyn Runtime>>,
spawner: Option<Arc<dyn Runtime>>,
pub(crate) redactor: Redactor,
pub(crate) drain_timeout: Option<Duration>,
pub(crate) shutdown_timeout: Option<Duration>,
pub(crate) hook_timeout: Option<Duration>,
pub(crate) construct_timeout: Option<Duration>,
}
impl AppConfig {
pub(crate) const DEFAULT_DRAIN: Duration = Duration::from_secs(10);
pub(crate) const DEFAULT_HOOK: Duration = Duration::from_secs(10);
pub(crate) const DEFAULT_CONSTRUCT: Duration = Duration::from_secs(30);
pub(crate) fn defaults(&self) -> Option<Defaults> {
if self.timer.is_none() {
return None;
}
Some(Defaults {
hook_timeout: self.hook_timeout.unwrap_or(Self::DEFAULT_HOOK),
construct_timeout: self.construct_timeout.unwrap_or(Self::DEFAULT_CONSTRUCT),
})
}
pub(crate) fn drain(&self) -> Duration {
match self.timer {
Some(_) => self.drain_timeout.unwrap_or(Self::DEFAULT_DRAIN),
None => Duration::ZERO,
}
}
pub(crate) fn knobs_set(&self) -> Vec<&'static str> {
[
("drain_timeout", self.drain_timeout),
("shutdown_timeout", self.shutdown_timeout),
("hook_timeout", self.hook_timeout),
("construct_timeout", self.construct_timeout),
]
.into_iter()
.filter_map(|(name, set)| set.map(|_| name))
.collect()
}
}
impl App {
pub fn builder(root: impl Module) -> AppBuilder {
AppBuilder { root: Box::new(root), config: AppConfig::default(), plan: None }
}
}
impl AppBuilder {
pub fn timer(mut self, timer: impl Timer) -> Self {
let timer: Arc<dyn Timer> = Arc::new(timer);
self.config.runtime = self.config.spawner.as_ref().map(|spawner| {
Arc::new(Clocked::new(Arc::clone(spawner), Arc::clone(&timer), self.config.redactor.clone())) as Arc<dyn Runtime>
});
self.config.timer = Some(timer);
self
}
pub fn runtime(mut self, runtime: impl Runtime) -> Self {
let runtime: Arc<dyn Runtime> = Arc::new(runtime);
let clock = Arc::clone(&runtime) as Arc<dyn Timer>;
let wrapped: Arc<dyn Runtime> = Arc::new(Clocked::new(Arc::clone(&runtime), clock, self.config.redactor.clone()));
self.config.timer = Some(Arc::clone(&wrapped) as Arc<dyn Timer>);
self.config.spawner = Some(runtime);
self.config.runtime = Some(wrapped);
self
}
pub fn drain_timeout(mut self, d: Duration) -> Self {
self.config.drain_timeout = Some(d);
self
}
pub fn shutdown_timeout(mut self, d: Duration) -> Self {
self.config.shutdown_timeout = Some(d);
self
}
pub fn hook_timeout(mut self, d: Duration) -> Self {
self.config.hook_timeout = Some(d);
self
}
pub fn construct_timeout(mut self, d: Duration) -> Self {
self.config.construct_timeout = Some(d);
self
}
pub fn wire(self) -> Result<App<Wired>, StartupError> {
let env = wire::WireEnv {
timer: self.config.timer.clone(),
runtime: self.config.runtime.clone(),
knobs_set: self.config.knobs_set(),
};
let graph = wire::wire(self.root, &env, self.plan)?;
Ok(App::from_shared(AppShared::new(graph, self.config), Vec::new()))
}
}
impl<S> App<S> {
pub(crate) fn from_shared(shared: Arc<AppShared>, servers: Vec<Box<dyn ErasedServer>>) -> Self {
App { shared, servers, _s: PhantomData }
}
}
impl App<Wired> {
pub async fn connect(self) -> Result<App<Connected>, StartupError> {
let shared = self.shared;
shared.phase.advance(Stage::Connecting);
let graph = shared.graph();
let modules: Vec<ModuleId> = graph.modules.iter().map(|module| module.id).collect();
connect::connect(&shared, &graph.connect_order, &modules).await?;
shared.phase.advance(Stage::Running);
Ok(App::from_shared(shared, Vec::new()))
}
}
impl App<Connected> {
pub fn bind(mut self, server: impl Server) -> App<Connected> {
self.servers.push(Box::new(server));
self
}
pub async fn listen(mut self) -> Result<App<Bound>, StartupError> {
let mut queued = std::mem::take(&mut self.servers);
if self.shared.config.runtime.is_none()
&& let Some(server) = queued.first()
{
let transport = server.transport_name();
let refusal = RuntimeMissing { transport };
let text = refusal.to_string();
return Err(StartupError::Bind { transport, source: Redacted::from_parts(Box::new(refusal), text) });
}
let handle = self.handle();
let mut refused = Vec::new();
for server in &mut queued {
if let Err(error) = server.prepare(&handle).await {
refused.push((server.transport_name(), error));
}
}
if !refused.is_empty() {
return Err(StartupError::Configure(ConfigureErrors::collect(refused, &self.shared.graph().secrets)));
}
let mut bound: Vec<Arc<dyn ErasedServer>> = Vec::with_capacity(queued.len());
for mut server in queued {
let transport = server.transport_name();
if let Err(error) = server.bind(&handle).await {
let source = redact(&self.shared.graph().secrets, error);
for done in &bound {
let _ = done.close().await;
}
return Err(StartupError::Bind { transport, source });
}
bound.push(Arc::from(server));
}
*self.shared.servers.lock().unwrap_or_else(PoisonError::into_inner) = bound;
Ok(App::from_shared(self.shared, Vec::new()))
}
pub fn handle(&self) -> AppHandle {
AppHandle { shared: Arc::clone(&self.shared) }
}
pub async fn get<T: ?Sized + Send + Sync + 'static>(&self) -> Result<Dep<T>, LookupError> {
self.shared.get_root::<T>().await
}
pub fn module<M: 'static>(&self) -> Result<ModuleRef, LookupError> {
self.shared.find_module::<M>(None)
}
pub fn module_keyed<M: 'static, Q: 'static>(&self) -> Result<ModuleRef, LookupError> {
self.shared.find_module::<M>(Some(Qualifier::of::<Q>()))
}
pub async fn execute<F, R>(&self, opts: ExecOptions, f: F) -> Result<R, Closed>
where
F: AsyncFnOnce(&Execution) -> R,
{
let root = self.shared.graph().root;
self.shared.execute(root, opts, f).await
}
pub async fn close(self, signal: Signal) -> Result<Shutdown, ShutdownError> {
shutdown::close(&self.shared, signal).await
}
}
impl App<Bound> {
pub fn handle(&self) -> AppHandle {
AppHandle { shared: Arc::clone(&self.shared) }
}
pub fn addresses(&self) -> Vec<BoundAddr> {
let servers = self.shared.servers.lock().unwrap_or_else(PoisonError::into_inner);
servers.iter().flat_map(|server| server.bound()).collect()
}
pub async fn serve(self, signal: impl Future<Output = Signal> + Send) -> Result<Shutdown, ShutdownError> {
let shared = self.shared;
let servers: Vec<Arc<dyn ErasedServer>> = shared.servers.lock().unwrap_or_else(PoisonError::into_inner).clone();
let mut serving: Vec<Option<BoxFuture<'_, Result<(), BoxError>>>> =
servers.iter().map(|server| Some(server.serve())).collect();
let trigger = {
let mut signal = pin!(signal);
let mut triggered = shared.shutdown.triggered();
poll_fn(|cx| {
if let Poll::Ready(own) = signal.as_mut().poll(cx) {
return Poll::Ready(own);
}
if Pin::new(&mut triggered).poll(cx).is_ready() {
return Poll::Ready(shared.shutdown.winning_signal().unwrap_or_else(|| Signal::new("close")));
}
for (server, slot) in servers.iter().zip(serving.iter_mut()) {
let Some(fut) = slot else { continue };
let Poll::Ready(result) = fut.as_mut().poll(cx) else { continue };
*slot = None;
if let Err(error) = result {
let reason = redact(&shared.graph().secrets, error);
return Poll::Ready(Signal::new(format!("transport `{}` failed: {reason}", server.transport_name())));
}
}
Poll::Pending
})
.await
};
let mut closing = pin!(shutdown::close(&shared, trigger));
poll_fn(|cx| {
for slot in serving.iter_mut() {
if let Some(fut) = slot
&& fut.as_mut().poll(cx).is_ready()
{
*slot = None;
}
}
closing.as_mut().poll(cx)
})
.await
}
}