plexus_core/plexus/service_scope.rs
1//! NEST-11 · which service a call is routed in.
2//!
3//! A call enters a service at [`DynamicHub::route_with_ctx`] (a socket's
4//! `{ns}.call`, a [`HubTransport`](super::HubTransport), a test's `route`);
5//! the outermost one it enters is its service, and everything that routing
6//! reaches — an activation, a child mounted below it, a peer in a slot —
7//! runs knowing it. A [`RemoteChild`](super::RemoteChild) keeps it, weakly,
8//! for each call it forwards: the far side's calls back under that call are
9//! routed through this service's own routing and gate, as its caller.
10//!
11//! Nothing here admits anyone: the service is a route, never a caller.
12
13use std::future::Future;
14use std::sync::Weak;
15
16use super::plexus::DynamicHub;
17
18tokio::task_local! {
19 static SERVICE: WeakService;
20}
21
22/// A service, held weakly: what a child keeps of the service it is mounted
23/// in, so it never keeps that service alive. Cheap to clone.
24#[derive(Clone)]
25pub struct WeakService(Weak<super::plexus::DynamicHubInner>);
26
27impl std::fmt::Debug for WeakService {
28 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29 match self.upgrade() {
30 Some(s) => write!(f, "WeakService({})", s.runtime_namespace()),
31 None => f.write_str("WeakService(gone)"),
32 }
33 }
34}
35
36impl WeakService {
37 pub(crate) fn new(inner: Weak<super::plexus::DynamicHubInner>) -> Self {
38 Self(inner)
39 }
40
41 /// The service, while it lives.
42 pub fn upgrade(&self) -> Option<DynamicHub> {
43 self.0.upgrade().map(DynamicHub::from_inner)
44 }
45}
46
47/// Whether the running task is routing a call in some service already.
48pub(crate) fn entered() -> bool {
49 SERVICE.try_with(|_| ()).is_ok()
50}
51
52/// The service the running call was routed in, if any.
53pub(crate) fn current() -> Option<WeakService> {
54 SERVICE.try_with(WeakService::clone).ok()
55}
56
57/// Run `fut` routed in `service`.
58pub(crate) fn scope<F: Future>(service: WeakService, fut: F) -> impl Future<Output = F::Output> {
59 SERVICE.scope(service, fut)
60}