Skip to main content

plexus_core/plexus/
parent.rs

1//! NEST-16 · a graft that knows its parent.
2//!
3//! An activation written against its parent's interface —
4//! `#[plexus_macros::activation(parent = ShopClient)]` — takes the parent's
5//! client into a method as `parent: Parent<ShopClient>`, injected by the
6//! server (never on the wire, never in its own client), and calls inward as
7//! if the parent were local:
8//!
9//! ```ignore
10//! #[plexus_macros::activation(parent = ShopClient)]
11//! impl Restock {
12//!     /// The items running low.
13//!     pub async fn low(&self, parent: Parent<ShopClient>, under: u32) -> Vec<Item> {
14//!         parent.items().collect::<Vec<_>>().await … // needs: [shop.items]
15//!     }
16//! }
17//! ```
18//!
19//! The client runs over a [`ParentTransport`]: the mount's connection back to
20//! the service (NEST-11's [`host()`](super::remote_child::host)) when the
21//! child runs behind a mount, or the service's own routing when it is
22//! registered in the same process. Either way each call is the original
23//! caller's, through the service's gate.
24//!
25//! What the child calls of its parent is its schema's `needs` ([`Need`]),
26//! which the macro infers from the method bodies. Three places hold to it:
27//!
28//! - **the graft** — mounting the child (a static `--child`, plexus-dyn's
29//!   `connect`/`grow`, [`ServiceRoot::insert`](super::ServiceRoot::insert))
30//!   checks each need against the service's own schema by the method's
31//!   shape hash, refusing with every missing or changed method named
32//!   ([`NeedsMiss`]);
33//! - **the host** — a call the child makes up that is neither the standard
34//!   upward interface ([`STANDARD`]) nor a need is refused, typed
35//!   (`forbidden`, reason `not_needed`), and a need is routed with one more
36//!   ceiling layer, its own grant (TM-1, DYNAUTH-4);
37//! - **the client** — [`ParentTransport`] refuses the same before sending.
38
39use std::ops::Deref;
40use std::sync::Arc;
41
42use futures::StreamExt;
43use plexus_client::{DenyReason, ItemStream, MethodRef, RemoteError, StreamItem, Transport};
44use serde::{Deserialize, Serialize};
45use serde_json::{json, Value};
46
47use super::auth::AuthContext;
48use super::hub_transport::HubTransport;
49use super::in_process::to_client_item;
50use super::peer::PeerError;
51use super::plexus::{DynamicHub, PlexusError};
52use super::schema::Need;
53use super::types::{PlexusStreamItem, StreamMetadata};
54
55/// `host.schema`: the service's whole description (also any `<path>.schema`).
56pub const HOST_SCHEMA: &str = "host.schema";
57/// `host.whoami`: whom the call the child is serving is for.
58pub const HOST_WHOAMI: &str = "host.whoami";
59/// `host.log { level, message }`: a line in the service's log.
60pub const HOST_LOG: &str = "host.log";
61/// `host.notify { topic, data }`: a message to the service
62/// ([`DynamicHub::notices`]).
63pub const HOST_NOTIFY: &str = "host.notify";
64
65/// D10: the standard upward interface — what every child may call of its
66/// service, with no declaration. Every other upward call is a [`Need`].
67pub const STANDARD: [&str; 4] = [HOST_SCHEMA, HOST_WHOAMI, HOST_LOG, HOST_NOTIFY];
68
69/// Whether `method` is one of the [`STANDARD`] four, or a schema read
70/// (`<path>.schema`, which `host.schema` stands for).
71pub fn is_standard(method: &str) -> bool {
72    STANDARD.contains(&method) || method.ends_with(".schema")
73}
74
75/// What a child said to its service through `host.notify`.
76#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
77pub struct Notice {
78    /// The child, by its mount name (or its namespace, in process).
79    pub child: String,
80    /// What it is about.
81    pub topic: String,
82    /// Anything.
83    #[serde(default)]
84    pub data: Value,
85    /// Whom the call it was serving was for, if anyone.
86    #[serde(default, rename = "for", skip_serializing_if = "Option::is_none")]
87    pub for_: Option<String>,
88}
89
90/// Why a graft was refused: what the child needs that the service does not
91/// serve, or serves in another shape.
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub struct NeedsMiss {
94    /// The child, by its name.
95    pub child: String,
96    /// The service it was to be grafted onto.
97    pub service: String,
98    /// Needs the service does not serve.
99    pub missing: Vec<String>,
100    /// Needs the service serves under another shape than the child was
101    /// built against.
102    pub changed: Vec<String>,
103}
104
105impl NeedsMiss {
106    /// Every method named, missing first.
107    pub fn methods(&self) -> Vec<String> {
108        self.missing.iter().chain(self.changed.iter()).cloned().collect()
109    }
110}
111
112impl std::fmt::Display for NeedsMiss {
113    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114        write!(f, "`{}` cannot be grafted onto `{}`:", self.child, self.service)?;
115        if !self.missing.is_empty() {
116            write!(f, " it needs {}, which `{}` does not serve", self.missing.join(", "), self.service)?;
117        }
118        if !self.changed.is_empty() {
119            if !self.missing.is_empty() {
120                f.write_str(";")?;
121            }
122            write!(f, " the shape of {} moved since it was built", self.changed.join(", "))?;
123        }
124        Ok(())
125    }
126}
127
128impl std::error::Error for NeedsMiss {}
129
130impl From<NeedsMiss> for PeerError {
131    fn from(m: NeedsMiss) -> Self {
132        PeerError::ShapeMismatch { wanted: format!("the needs of `{}`", m.child), got: m.service.clone(), methods: m.methods() }
133    }
134}
135
136/// Check `needs` against what a service serves: `served(path)` is the shape
137/// hash of the method at `path` (empty: served, its shape unknown — below an
138/// untyped slot), `None` when it serves none there. An empty need hash
139/// checks presence alone.
140pub fn check_needs(child: &str, service: &str, needs: &[Need], served: impl Fn(&str) -> Option<String>) -> Result<(), NeedsMiss> {
141    let (mut missing, mut changed) = (Vec::new(), Vec::new());
142    for need in needs {
143        if is_standard(&need.method) {
144            continue;
145        }
146        match served(&need.method) {
147            None => missing.push(need.method.clone()),
148            Some(h) if !need.hash.is_empty() && !h.is_empty() && h != need.hash => changed.push(need.method.clone()),
149            Some(_) => {}
150        }
151    }
152    if missing.is_empty() && changed.is_empty() {
153        Ok(())
154    } else {
155        Err(NeedsMiss { child: child.to_string(), service: service.to_string(), missing, changed })
156    }
157}
158
159/// The refusal of an upward call outside the standard interface and the
160/// child's needs.
161pub fn not_needed(method: &str) -> PlexusError {
162    PlexusError::Forbidden { reason: super::plexus::AuthzDenyReason::NotNeeded { method: method.to_string() } }
163}
164
165fn meta(child: &str) -> StreamMetadata {
166    StreamMetadata::new(vec![child.to_string()], super::context::PlexusContext::hash())
167}
168
169/// The service's own answer to `host.whoami`, `host.log` or `host.notify`
170/// from `child`, serving a call for `caller`: one data item, then done.
171/// `None` for any other method.
172pub(crate) fn standard_answer(service: &DynamicHub, child: &str, method: &str, params: &Value, caller: Option<&AuthContext>) -> Option<Vec<PlexusStreamItem>> {
173    let who = caller.and_then(|a| a.principal()).map(|p| p.to_string());
174    let content = match method {
175        HOST_WHOAMI => json!({ "for": who, "child": child, "service": service.runtime_namespace() }),
176        HOST_LOG => {
177            let level = params.get("level").and_then(Value::as_str).unwrap_or("info");
178            let message = params.get("message").and_then(Value::as_str).unwrap_or_default();
179            match level {
180                "error" => tracing::error!(target: "plexus::child", child = %child, r#for = ?who, "{message}"),
181                "warn" => tracing::warn!(target: "plexus::child", child = %child, r#for = ?who, "{message}"),
182                "debug" => tracing::debug!(target: "plexus::child", child = %child, r#for = ?who, "{message}"),
183                "trace" => tracing::trace!(target: "plexus::child", child = %child, r#for = ?who, "{message}"),
184                _ => tracing::info!(target: "plexus::child", child = %child, r#for = ?who, "{message}"),
185            }
186            json!({ "logged": true })
187        }
188        HOST_NOTIFY => {
189            let notice = Notice {
190                child: child.to_string(),
191                topic: params.get("topic").and_then(Value::as_str).unwrap_or_default().to_string(),
192                data: params.get("data").cloned().unwrap_or(Value::Null),
193                for_: who,
194            };
195            let heard = service.notify(notice);
196            json!({ "heard": heard })
197        }
198        _ => return None,
199    };
200    Some(vec![PlexusStreamItem::data(meta(child), method.to_string(), content), PlexusStreamItem::done(meta(child))])
201}
202
203/// How a [`Parent`] reaches its service.
204#[derive(Clone)]
205enum Route {
206    /// Behind a mount: the connection back (NEST-11).
207    #[cfg(not(target_arch = "wasm32"))]
208    Host(super::remote_child::HostTransport),
209    /// In the same process: the service's own routing, as the caller.
210    Local(HubTransport),
211}
212
213/// A [`Transport`] to the service a graft is mounted in, for the methods it
214/// needs and the standard upward interface alone.
215#[derive(Clone)]
216pub struct ParentTransport {
217    route: Route,
218    child: Arc<str>,
219    needs: Arc<[String]>,
220}
221
222impl std::fmt::Debug for ParentTransport {
223    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
224        let how = match &self.route {
225            #[cfg(not(target_arch = "wasm32"))]
226            Route::Host(_) => "host",
227            Route::Local(_) => "local",
228        };
229        f.debug_struct("ParentTransport").field("child", &self.child).field("route", &how).field("needs", &self.needs).finish()
230    }
231}
232
233fn refused(error: RemoteError, message: String) -> ItemStream<'static> {
234    let item = StreamItem::Error { metadata: None, recoverable: false, message: Some(message), code: None, error, fields: Default::default() };
235    Box::pin(futures::stream::once(async move { Ok(item) }))
236}
237
238impl ParentTransport {
239    /// The service the call being run was routed in (or forwarded from):
240    /// over the mount's connection back when there is one, else in process.
241    /// `child` names the graft; `needs` are the method paths it may call
242    /// beyond the standard interface.
243    pub fn in_call(child: &str, needs: Arc<[String]>) -> Result<Self, PlexusError> {
244        let ctx = crate::call::context().map_err(|e| PlexusError::ExecutionError(format!("`{child}` reaches its parent only inside a call: {e}")))?;
245        #[cfg(not(target_arch = "wasm32"))]
246        if ctx.host_link().is_some() {
247            let t = super::remote_child::host().map_err(|e| PlexusError::ExecutionError(format!("`{child}`: {e}")))?;
248            return Ok(Self { route: Route::Host(t), child: Arc::from(child), needs });
249        }
250        let service = super::service_scope::current().and_then(|s| s.upgrade()).ok_or_else(|| {
251            PlexusError::ExecutionError(format!("`{child}` reaches its parent only in a call a service routed or forwarded"))
252        })?;
253        Ok(Self::local(Arc::new(service), ctx.auth().cloned(), child, needs))
254    }
255
256    /// In process: `service`'s own routing, every call as `caller`.
257    pub fn local(service: Arc<DynamicHub>, caller: Option<AuthContext>, child: &str, needs: Arc<[String]>) -> Self {
258        Self { route: Route::Local(HubTransport::with(service, caller)), child: Arc::from(child), needs }
259    }
260
261    /// The methods this transport may call beyond the standard interface.
262    pub fn needs(&self) -> &[String] {
263        &self.needs
264    }
265
266    /// Whether the transport goes over a mount's connection back.
267    pub fn is_remote(&self) -> bool {
268        #[cfg(not(target_arch = "wasm32"))]
269        if let Route::Host(_) = self.route {
270            return true;
271        }
272        false
273    }
274}
275
276impl Transport for ParentTransport {
277    fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
278        let q = method.qualified();
279        if !is_standard(&q) && !self.needs.iter().any(|n| *n == q) {
280            let e = not_needed(&q);
281            return refused(RemoteError::Forbidden { reason: DenyReason::NotNeeded { method: q.clone() } }, e.to_string());
282        }
283        match &self.route {
284            #[cfg(not(target_arch = "wasm32"))]
285            Route::Host(t) => t.call(method, params),
286            Route::Local(t) => {
287                if let Some(items) = standard_answer(t.hub(), &self.child, &q, &params, t.caller()) {
288                    return Box::pin(futures::stream::iter(items.into_iter().map(|i| Ok(to_client_item(i)))));
289                }
290                if q == HOST_SCHEMA {
291                    let m = MethodRef::named(t.hub().runtime_namespace().to_string(), "schema");
292                    return t.call(m, params);
293                }
294                t.call(method, params)
295            }
296        }
297    }
298}
299
300/// Why an upward call through [`Upward`] failed.
301#[derive(Debug, Clone, thiserror::Error)]
302#[error("{0}")]
303pub struct UpwardError(pub String);
304
305/// The standard upward interface (D10), every child's: [`Parent::host`].
306pub struct Upward<'a> {
307    t: &'a ParentTransport,
308}
309
310impl Upward<'_> {
311    async fn one(&self, method: &'static str, params: Value) -> Result<Value, UpwardError> {
312        let (path, name) = method.split_once('.').expect("a standard method is `host.<name>`");
313        let mut s = self.t.call(MethodRef::named(path, name), params);
314        while let Some(item) = s.next().await {
315            match item {
316                Ok(StreamItem::Data { content, .. }) => return Ok(content),
317                Ok(StreamItem::Error { error, message, .. }) => return Err(UpwardError(message.unwrap_or_else(|| error.to_string()))),
318                Ok(StreamItem::Done { .. }) => break,
319                Ok(_) => {}
320                Err(e) => return Err(UpwardError(e.to_string())),
321            }
322        }
323        Err(UpwardError(format!("`{method}` answered nothing")))
324    }
325
326    /// `host.schema`: the service's description, as the caller may see it.
327    pub async fn schema(&self) -> Result<Value, UpwardError> {
328        self.one(HOST_SCHEMA, json!({})).await
329    }
330
331    /// `host.whoami`: `{ for, child, service }` — whom the call being served
332    /// is for (`null`: no one signed in).
333    pub async fn whoami(&self) -> Result<Value, UpwardError> {
334        self.one(HOST_WHOAMI, json!({})).await
335    }
336
337    /// `host.log`: a line in the service's log at `level` (`error`, `warn`,
338    /// `info`, `debug`, `trace`).
339    pub async fn log(&self, level: &str, message: &str) -> Result<(), UpwardError> {
340        self.one(HOST_LOG, json!({ "level": level, "message": message })).await.map(|_| ())
341    }
342
343    /// `host.notify`: tell the service something; answers how many in the
344    /// service were listening ([`DynamicHub::notices`]).
345    pub async fn notify(&self, topic: &str, data: Value) -> Result<u64, UpwardError> {
346        self.one(HOST_NOTIFY, json!({ "topic": topic, "data": data })).await.map(|v| v["heard"].as_u64().unwrap_or(0))
347    }
348}
349
350/// The parent's client, injected into a graft's method:
351/// `parent: Parent<ShopClient>` (the macro writes the transport,
352/// `ShopClient<ParentTransport>`). It derefs to the client, so
353/// `parent.items()` is the parent's `items`; [`Parent::host`] is the
354/// standard upward interface.
355pub struct Parent<C> {
356    client: C,
357    transport: ParentTransport,
358}
359
360impl<C> Parent<C> {
361    /// The parent `client` makes over `transport`.
362    pub fn new(transport: ParentTransport, make: impl FnOnce(ParentTransport) -> C) -> Self {
363        Self { client: make(transport.clone()), transport }
364    }
365
366    /// What the server injects: the parent of the call being run
367    /// ([`ParentTransport::in_call`]), its client made by `make`.
368    #[doc(hidden)]
369    pub fn __in_call(child: &str, needs: Arc<[String]>, make: impl FnOnce(ParentTransport) -> C) -> Result<Self, PlexusError> {
370        Ok(Self::new(ParentTransport::in_call(child, needs)?, make))
371    }
372
373    /// The parent's client.
374    pub fn client(&self) -> &C {
375        &self.client
376    }
377
378    /// The parent's client, owned.
379    pub fn into_inner(self) -> C {
380        self.client
381    }
382
383    /// The transport the client runs over.
384    pub fn transport(&self) -> &ParentTransport {
385        &self.transport
386    }
387
388    /// The standard upward interface: `host.schema`, `host.whoami`,
389    /// `host.log`, `host.notify`.
390    pub fn host(&self) -> Upward<'_> {
391        Upward { t: &self.transport }
392    }
393}
394
395impl<C> Deref for Parent<C> {
396    type Target = C;
397    fn deref(&self) -> &C {
398        &self.client
399    }
400}
401
402impl<C: std::fmt::Debug> std::fmt::Debug for Parent<C> {
403    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
404        f.debug_struct("Parent").field("client", &self.client).field("transport", &self.transport).finish()
405    }
406}
407
408#[cfg(test)]
409mod tests {
410    use super::*;
411
412    #[test]
413    fn a_need_missing_or_moved_is_named() {
414        let needs = [Need::new("shop.items", "aaaa"), Need::new("shop.price", "bbbb"), Need::new("shop.tags", ""), Need::new("host.whoami", "")];
415        let served = |p: &str| match p {
416            "shop.items" => Some("aaaa".to_string()),
417            "shop.price" => Some("cccc".to_string()),
418            _ => None,
419        };
420        let miss = check_needs("restock", "svc", &needs, served).unwrap_err();
421        assert_eq!(miss.missing, ["shop.tags"]);
422        assert_eq!(miss.changed, ["shop.price"]);
423        let text = miss.to_string();
424        assert!(text.contains("shop.tags") && text.contains("shop.price") && text.contains("restock"), "{text}");
425        assert!(check_needs("restock", "svc", &needs[..1], served).is_ok());
426    }
427
428    #[test]
429    fn the_standard_four_and_schemas_need_no_declaration() {
430        for m in STANDARD {
431            assert!(is_standard(m));
432        }
433        assert!(is_standard("shop.schema"));
434        assert!(!is_standard("shop.items"));
435        assert!(!is_standard("host.restart"));
436    }
437}