pub(crate) mod handle;
pub(crate) mod load;
pub(crate) mod shared;
use std::future::{Future, poll_fn};
use std::marker::PhantomData;
use std::panic::{AssertUnwindSafe, Location, catch_unwind};
use std::ops::Deref;
use std::pin::{Pin, pin};
use std::sync::{Arc, PoisonError};
use std::task::{Context, Poll};
use std::time::Duration;
use crate::app::shared::AppShared;
use crate::binding::Qualifier;
use crate::dependency::Dep;
use crate::dependency::FromContainer;
use crate::error::{
Closed, ConfigureErrors, ConnectError, FailureReason, LookupError, PreparePanicked, RuntimeMissing, ServeEnd, Shutdown,
ShutdownError, ShutdownFailure, StartupError,
};
use crate::execution::trace::{TraceMode, TraceSource};
use crate::execution::{ExecOptions, Execution};
use crate::key::{BindingKind, Key};
use crate::resolver::{Purpose, Resolver};
use crate::graph::{ModuleId, wire};
use crate::lifecycle::phase::Phase as Stage;
use crate::lifecycle::run::CatchUnwind;
use crate::lifecycle::{connect, shutdown};
use crate::module::Module;
use crate::module::handle::ModuleRef;
use crate::redact::{Redacted, Redactor, SecretRegistry, redact, redact_panic};
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};
use crate::type_name::TypeName;
pub use handle::{AppHandle, Phase};
pub enum Wired {}
pub enum Connected {}
pub enum Bound {}
pub struct App<S = Wired> {
pub(crate) shared: Owner,
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>,
hook_timeout_at: Option<&'static Location<'static>>,
construct_timeout_at: Option<&'static Location<'static>>,
pub(crate) trace: TraceMode,
}
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 zero_defaults(&self) -> Vec<(&'static str, &'static Location<'static>)> {
let hook = self.hook_timeout.zip(self.hook_timeout_at);
let construct = self.construct_timeout.zip(self.construct_timeout_at);
[("hook_timeout", hook), ("construct_timeout", construct)]
.into_iter()
.filter_map(|(name, set)| set.filter(|(d, _)| d.is_zero()).map(|(_, at)| (name, at)))
.collect()
}
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()
}
}
pub(crate) struct Owner(Arc<AppShared>);
impl Deref for Owner {
type Target = Arc<AppShared>;
fn deref(&self) -> &Arc<AppShared> {
&self.0
}
}
impl Drop for Owner {
fn drop(&mut self) {
shutdown::app_dropped(&self.0);
}
}
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
}
#[track_caller]
pub fn hook_timeout(mut self, d: Duration) -> Self {
self.config.hook_timeout = Some(d);
self.config.hook_timeout_at = Some(Location::caller());
self
}
#[track_caller]
pub fn construct_timeout(mut self, d: Duration) -> Self {
self.config.construct_timeout = Some(d);
self.config.construct_timeout_at = Some(Location::caller());
self
}
pub fn trace(mut self, mode: TraceMode) -> Self {
self.config.trace = mode;
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(),
zero_defaults: self.config.zero_defaults(),
};
let graph = wire::wire(self.root, &env, self.plan)?;
Ok(App::from_shared(Owner(AppShared::new(graph, self.config)), Vec::new()))
}
}
impl<S> App<S> {
pub(crate) fn from_shared(shared: Owner, 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?;
if shared.config.trace == TraceMode::On {
let resolver = Resolver::new(&shared, graph.root, None, Purpose::Lookup);
match <Option<Dep<dyn TraceSource>> as FromContainer>::from_container(&resolver).await {
Ok(Some(source)) => {
let _ = shared.trace_source.set(source.into_arc());
}
Ok(None) => {}
Err(error) => return Err(StartupError::Connect(trace_source_failure(&graph, error))),
}
}
shared.phase.advance(Stage::Running);
Ok(App::from_shared(shared, Vec::new()))
}
}
fn trace_source_failure(graph: &crate::graph::Graph, error: LookupError) -> ConnectError {
let key = Key::of::<dyn TraceSource, ()>().name(BindingKind::Single);
let module = graph.module(graph.root).name.clone();
let reason = match error {
LookupError::Construct { reason, .. } => reason,
other => {
let text = other.to_string();
FailureReason::Errored(Redacted::from_parts(Box::new(other), text))
}
};
ConnectError::Construct { key, module, reason }
}
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<(TypeName, BoxError)> = Vec::new();
for server in &mut queued {
let transport = server.transport_name();
match CatchUnwind::new(async { server.prepare(&handle).await }).await {
Ok(Ok(())) => {}
Ok(Err(error)) => refused.push((transport, error)),
Err(payload) => {
let message = redact_panic(&self.shared.graph().secrets, payload);
refused.push((transport, Box::new(PreparePanicked { message })));
}
}
}
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 fn module_of<M: Module>(&self, config: &M) -> Result<ModuleRef, LookupError> {
self.shared.module_of(config)
}
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) = poll_serve(fut, cx, &shared.graph().secrets) else { continue };
*slot = None;
let transport = server.transport_name();
let (signal, end, failed) = match result {
Err(panic) => {
let failed = format!("panicked: {panic}");
(Signal::new(format!("transport `{transport}` failed: {failed}")), ServeEnd::Panicked(panic), Some(failed))
}
Ok(Err(error)) => {
let reason = redact(&shared.graph().secrets, error);
let failed = reason.to_string();
(Signal::new(format!("transport `{transport}` failed: {failed}")), ServeEnd::Errored(reason), Some(failed))
}
Ok(Ok(())) => (Signal::new(format!("transport `{transport}` stopped serving")), ServeEnd::Returned, None),
};
let won = shared.shutdown.trigger_with(signal.clone(), Some(ShutdownFailure::Serve { transport, end }));
if !won && let Some(failed) = failed {
discarded(transport, &failed);
}
return Poll::Ready(signal);
}
Poll::Pending
})
.await
};
let mut closing = pin!(shutdown::close(&shared, trigger));
poll_fn(|cx| {
for (server, slot) in servers.iter().zip(serving.iter_mut()) {
if let Some(fut) = slot
&& let Poll::Ready(result) = poll_serve(fut, cx, &shared.graph().secrets)
{
*slot = None;
match result {
Ok(Ok(())) => {}
Ok(Err(error)) => discarded(server.transport_name(), &redact(&shared.graph().secrets, error).to_string()),
Err(panic) => discarded(server.transport_name(), &format!("panicked: {panic}")),
}
}
}
closing.as_mut().poll(cx)
})
.await
}
}
fn poll_serve(
fut: &mut BoxFuture<'_, Result<(), BoxError>>,
cx: &mut Context<'_>,
secrets: &SecretRegistry,
) -> Poll<Result<Result<(), BoxError>, Redacted>> {
match catch_unwind(AssertUnwindSafe(|| fut.as_mut().poll(cx))) {
Ok(poll) => poll.map(Ok),
Err(payload) => Poll::Ready(Err(redact_panic(secrets, payload))),
}
}
fn discarded(transport: TypeName, error: &str) {
tracing::warn!(
transport = %transport,
error,
"a transport's `serve` failed after the shutdown was triggered; the outcome reports the trigger alone"
);
}