use std::future::Future;
use std::sync::Weak;
use super::plexus::DynamicHub;
tokio::task_local! {
static SERVICE: WeakService;
}
#[derive(Clone)]
pub struct WeakService(Weak<super::plexus::DynamicHubInner>);
impl std::fmt::Debug for WeakService {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.upgrade() {
Some(s) => write!(f, "WeakService({})", s.runtime_namespace()),
None => f.write_str("WeakService(gone)"),
}
}
}
impl WeakService {
pub(crate) fn new(inner: Weak<super::plexus::DynamicHubInner>) -> Self {
Self(inner)
}
pub fn upgrade(&self) -> Option<DynamicHub> {
self.0.upgrade().map(DynamicHub::from_inner)
}
}
pub(crate) fn entered() -> bool {
SERVICE.try_with(|_| ()).is_ok()
}
pub(crate) fn current() -> Option<WeakService> {
SERVICE.try_with(WeakService::clone).ok()
}
pub(crate) fn scope<F: Future>(service: WeakService, fut: F) -> impl Future<Output = F::Output> {
SERVICE.scope(service, fut)
}