Skip to main content

plexus_core/plexus/
service_root.rs

1//! NEST-15 · the service root is the primitive: a table of peers answered by
2//! `peer(name)`.
3//!
4//! A service's top level is one table — each entry a peer by name — and
5//! routing is `peer(name)` from the root down: `<name>.<method>` is the entry
6//! `name`'s method, `<name>.<child>.<method>` its child's, and so on below it
7//! (NEST-1, "The target", part 4). Every way onto the top level is an entry:
8//!
9//! ```text
10//! .register(Tickets)        an entry, at build              (DynamicHub, unchanged)
11//! --child menger=ws://…     a RemoteChild entry, at build   (`.register(child)`, unchanged)
12//! root().insert(x)          an entry, while it serves       (an activation, a RemoteChild)
13//! root().insert_peer(n, p)  any `Peer`, while it serves     (plexus-dyn's top-level peers)
14//! root().remove(n)          gone, while it serves
15//! ```
16//!
17//! The gate's index, `<service>.schema`, `.hash`, `.ir` and the schema's
18//! `children` are read from the table: a change moves the service's hash,
19//! drops what was described and indexed, and is said on
20//! [`ServiceRoot::watch`] (and in the `plexus_hash` every item carries).
21//!
22//! The root's own methods (`call`, `hash`, `schema`, `ir`) are the root's:
23//! the service's own name answers the root itself, never an entry.
24
25use std::collections::BTreeMap;
26use std::sync::Arc;
27
28use async_trait::async_trait;
29use serde_json::Value;
30
31use super::auth::AuthContext;
32use super::peer::{Interface, Peer, PeerError, RouterPeer};
33use super::plexus::{ActivationObject, ChildRouter, DynamicHub, PlexusError};
34use super::schema::{PluginSchema, Schema};
35use crate::types::Handle;
36use super::PlexusStream;
37
38/// One entry of the root's table: what the service calls (`object`) and
39/// what routing walks below it (`router`).
40#[derive(Clone)]
41pub(crate) struct Entry {
42    pub(crate) object: Arc<dyn ActivationObject>,
43    pub(crate) router: Arc<dyn ChildRouter>,
44}
45
46/// The root's table, by name (ordered: every hash over the service is a
47/// function of what it serves, PERF-21).
48#[derive(Clone, Default)]
49pub(crate) struct Table {
50    pub(crate) entries: BTreeMap<String, Entry>,
51    /// RETURNS-40: the entries' static children, counted — `ir`'s cheap bound.
52    pub(crate) nested: usize,
53}
54
55/// Why the root would not take an entry.
56#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
57pub enum RootError {
58    /// An entry is already served under `name` (use `replace`).
59    #[error("a peer is already served as `{name}` at the top level")]
60    Taken { name: String },
61    /// `name` is the service's own: its methods would answer, never the entry
62    /// (Z2H-8 / HOSTLESS-3) — its name, or (KEEL-54) one of its own methods
63    /// (`call`, `hash`, `hashes`, `ir`, `schema`).
64    #[error("`{name}` is the service's own name or one of its own methods (call, hash, hashes, ir, schema): an entry under it would be unreachable")]
65    Shadows { name: String },
66    /// Not one segment of `[A-Za-z0-9_-]`.
67    #[error("`{name}` is not a top-level name: one segment of letters, digits, `_` and `-`")]
68    BadName { name: String },
69    /// NEST-16: the entry is a graft whose needs this service does not
70    /// serve as it was built against.
71    #[error("{0}")]
72    Needs(super::parent::NeedsMiss),
73}
74
75/// A top-level name: one segment.
76pub(crate) fn check_name(name: &str) -> Result<(), RootError> {
77    if name.is_empty() || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') {
78        return Err(RootError::BadName { name: name.to_string() });
79    }
80    Ok(())
81}
82
83/// The service root: its table of peers. A handle (cheap to clone) onto a
84/// [`DynamicHub`] — [`DynamicHub::root`] — that reads and changes its top
85/// level while it serves.
86#[derive(Clone)]
87pub struct ServiceRoot {
88    pub(crate) hub: DynamicHub,
89}
90
91impl std::fmt::Debug for ServiceRoot {
92    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
93        f.debug_struct("ServiceRoot").field("service", &self.hub.runtime_namespace()).field("peers", &self.names()).finish()
94    }
95}
96
97impl ServiceRoot {
98    /// The primitive: the top-level peer `name`. The service's own name is
99    /// not an entry (`NotFound`); call the service itself for its methods.
100    pub async fn peer(&self, name: &str) -> Result<Box<dyn Peer>, PeerError> {
101        self.hub.table().entries.get(name).cloned().map(|e| Box::new(EntryPeer(e)) as Box<dyn Peer>).ok_or_else(|| PeerError::NotFound { name: name.to_string() })
102    }
103
104    /// Every top-level name, in order.
105    pub fn names(&self) -> Vec<String> {
106        self.hub.table().entries.keys().cloned().collect()
107    }
108
109    /// Whether `name` is served at the top level.
110    pub fn contains(&self, name: &str) -> bool {
111        self.hub.table().entries.contains_key(name)
112    }
113
114    /// Serve `activation` at the top level under its namespace, while the
115    /// service serves; refused when the name is taken.
116    pub fn insert<A: super::Activation + ChildRouter + Clone + 'static>(&self, activation: A) -> Result<(), RootError> {
117        self.hub.insert_entry(activation.namespace().to_string(), DynamicHub::entry_of(activation), false).map(|_| ())
118    }
119
120    /// [`insert`](Self::insert), replacing whatever was served under the
121    /// name; answers whether something was.
122    pub fn replace<A: super::Activation + ChildRouter + Clone + 'static>(&self, activation: A) -> Result<bool, RootError> {
123        self.hub.insert_entry(activation.namespace().to_string(), DynamicHub::entry_of(activation), true)
124    }
125
126    /// Serve any [`Peer`] at the top level as `name` (its schema's grants
127    /// and roles requalified to `name`); `replace` takes the name over.
128    /// Answers whether something was replaced.
129    pub fn insert_peer(&self, name: impl Into<String>, peer: Arc<dyn Peer>, replace: bool) -> Result<bool, RootError> {
130        let name = name.into();
131        let entry = PeerObject::entry(name.clone(), peer);
132        self.hub.insert_entry(name, entry, replace)
133    }
134
135    /// Stop serving `name` at the top level; answers whether it was served.
136    pub fn remove(&self, name: &str) -> bool {
137        self.hub.remove_entry(name)
138    }
139
140    /// The service's hash now (its schema's: what every item's `plexus_hash`
141    /// says).
142    pub fn hash(&self) -> String {
143        self.hub.compute_hash()
144    }
145
146    /// Told every time the table changes: the service's hash after it.
147    pub fn watch(&self) -> tokio::sync::watch::Receiver<String> {
148        self.hub.watch_root()
149    }
150}
151
152/// A top-level entry, as a peer.
153struct EntryPeer(Entry);
154
155#[async_trait]
156impl Peer for EntryPeer {
157    fn interface(&self) -> Interface {
158        Interface::of(&self.0.object.plugin_schema())
159    }
160
161    async fn call(&self, method: &str, params: Value, auth: Option<&AuthContext>) -> Result<PlexusStream, PlexusError> {
162        self.0.object.call(method, params, auth, None).await
163    }
164
165    async fn peer(&self, name: &str) -> Result<Box<dyn Peer>, PeerError> {
166        match self.0.router.peer_child(name).await? {
167            Some(router) => Ok(Box::new(RouterPeer::new(router))),
168            None => Err(PeerError::NotFound { name: name.to_string() }),
169        }
170    }
171}
172
173/// A shared peer as a boxed one.
174struct ArcPeer(Arc<dyn Peer>);
175
176#[async_trait]
177impl Peer for ArcPeer {
178    fn interface(&self) -> Interface {
179        self.0.interface()
180    }
181    async fn call(&self, method: &str, params: Value, auth: Option<&AuthContext>) -> Result<PlexusStream, PlexusError> {
182        self.0.call(method, params, auth).await
183    }
184    async fn peer(&self, name: &str) -> Result<Box<dyn Peer>, PeerError> {
185        self.0.peer(name).await
186    }
187}
188
189/// Any peer served at the top level: its schema is its interface's, under
190/// the entry's name.
191struct PeerObject {
192    name: String,
193    peer: Arc<dyn Peer>,
194}
195
196impl PeerObject {
197    fn entry(name: String, peer: Arc<dyn Peer>) -> Entry {
198        let router = Arc::new(super::peer::PeerRouter::new(Box::new(ArcPeer(peer.clone()))));
199        Entry { object: Arc::new(PeerObject { name, peer }), router }
200    }
201}
202
203/// `schema` as served under `name`: its roles' grants and its methods' own
204/// grants requalified (`{ns}.m` → `<name>.m`), as a mount's are (NEST-4).
205pub(crate) fn served_as(name: &str, mut schema: PluginSchema) -> PluginSchema {
206    if schema.namespace == name {
207        return schema;
208    }
209    let prefix = format!("{}.", schema.namespace);
210    let requalify = |g: &String| match g.strip_prefix(&prefix) {
211        Some(m) => format!("{name}.{m}"),
212        None => g.clone(),
213    };
214    schema.roles = schema.roles.iter().map(|(r, gs)| (r.clone(), gs.iter().map(requalify).collect())).collect();
215    for m in schema.methods.iter_mut() {
216        if let Some(g) = m.grant.as_ref() {
217            m.grant = Some(requalify(g));
218        }
219    }
220    schema.namespace = name.to_string();
221    schema
222}
223
224#[async_trait]
225impl ActivationObject for PeerObject {
226    fn namespace(&self) -> &str {
227        &self.name
228    }
229    fn version(&self) -> &str {
230        ""
231    }
232    fn description(&self) -> &str {
233        "a peer"
234    }
235    fn long_description(&self) -> Option<&str> {
236        None
237    }
238    fn methods(&self) -> Vec<&str> {
239        Vec::new()
240    }
241    fn method_help(&self, _method: &str) -> Option<String> {
242        None
243    }
244    fn plugin_id(&self) -> uuid::Uuid {
245        uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, format!("peer:{}", self.name).as_bytes())
246    }
247    async fn call(&self, method: &str, params: Value, auth: Option<&AuthContext>, _raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
248        let stream = self.peer.call(method, params, auth).await?;
249        // Its own schema, as it is served here: under the entry's name.
250        if method != "schema" {
251            return Ok(stream);
252        }
253        use futures::StreamExt;
254        let name = self.name.clone();
255        Ok(Box::pin(stream.map(move |item| match item {
256            super::types::PlexusStreamItem::Data { metadata, content_type, content } if content_type.ends_with(".schema") => {
257                match content.decode::<super::schema::SchemaResult>() {
258                    Ok(super::schema::SchemaResult::Plugin(schema)) => {
259                        let served = super::schema::SchemaResult::Plugin(served_as(&name, schema));
260                        let content = serde_json::to_value(&served).map(Into::into).unwrap_or(content);
261                        super::types::PlexusStreamItem::Data { metadata, content_type: format!("{name}.schema").into(), content }
262                    }
263                    _ => super::types::PlexusStreamItem::Data { metadata, content_type, content },
264                }
265            }
266            other => other,
267        })))
268    }
269    async fn resolve_handle(&self, _handle: &Handle) -> Result<PlexusStream, PlexusError> {
270        Err(PlexusError::HandleNotSupported(self.name.clone()))
271    }
272    fn plugin_schema(&self) -> PluginSchema {
273        served_as(&self.name, self.peer.interface().schema().clone())
274    }
275    fn needs(&self) -> Option<Vec<super::schema::Need>> {
276        self.peer.interface().schema().needs.clone()
277    }
278    fn static_child_schemas(&self) -> Vec<(String, PluginSchema)> {
279        Vec::new()
280    }
281    fn schema(&self) -> Schema {
282        let schema = self.plugin_schema();
283        Schema::new(schema.namespace.clone(), schema.description.clone())
284    }
285}