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).
63    #[error("`{name}` is the service's own name: an entry under it would be unreachable")]
64    Shadows { name: String },
65    /// Not one segment of `[A-Za-z0-9_-]`.
66    #[error("`{name}` is not a top-level name: one segment of letters, digits, `_` and `-`")]
67    BadName { name: String },
68    /// NEST-16: the entry is a graft whose needs this service does not
69    /// serve as it was built against.
70    #[error("{0}")]
71    Needs(super::parent::NeedsMiss),
72}
73
74/// A top-level name: one segment.
75pub(crate) fn check_name(name: &str) -> Result<(), RootError> {
76    if name.is_empty() || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') {
77        return Err(RootError::BadName { name: name.to_string() });
78    }
79    Ok(())
80}
81
82/// The service root: its table of peers. A handle (cheap to clone) onto a
83/// [`DynamicHub`] — [`DynamicHub::root`] — that reads and changes its top
84/// level while it serves.
85#[derive(Clone)]
86pub struct ServiceRoot {
87    pub(crate) hub: DynamicHub,
88}
89
90impl std::fmt::Debug for ServiceRoot {
91    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92        f.debug_struct("ServiceRoot").field("service", &self.hub.runtime_namespace()).field("peers", &self.names()).finish()
93    }
94}
95
96impl ServiceRoot {
97    /// The primitive: the top-level peer `name`. The service's own name is
98    /// not an entry (`NotFound`); call the service itself for its methods.
99    pub async fn peer(&self, name: &str) -> Result<Box<dyn Peer>, PeerError> {
100        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() })
101    }
102
103    /// Every top-level name, in order.
104    pub fn names(&self) -> Vec<String> {
105        self.hub.table().entries.keys().cloned().collect()
106    }
107
108    /// Whether `name` is served at the top level.
109    pub fn contains(&self, name: &str) -> bool {
110        self.hub.table().entries.contains_key(name)
111    }
112
113    /// Serve `activation` at the top level under its namespace, while the
114    /// service serves; refused when the name is taken.
115    pub fn insert<A: super::Activation + ChildRouter + Clone + 'static>(&self, activation: A) -> Result<(), RootError> {
116        self.hub.insert_entry(activation.namespace().to_string(), DynamicHub::entry_of(activation), false).map(|_| ())
117    }
118
119    /// [`insert`](Self::insert), replacing whatever was served under the
120    /// name; answers whether something was.
121    pub fn replace<A: super::Activation + ChildRouter + Clone + 'static>(&self, activation: A) -> Result<bool, RootError> {
122        self.hub.insert_entry(activation.namespace().to_string(), DynamicHub::entry_of(activation), true)
123    }
124
125    /// Serve any [`Peer`] at the top level as `name` (its schema's grants
126    /// and roles requalified to `name`); `replace` takes the name over.
127    /// Answers whether something was replaced.
128    pub fn insert_peer(&self, name: impl Into<String>, peer: Arc<dyn Peer>, replace: bool) -> Result<bool, RootError> {
129        let name = name.into();
130        let entry = PeerObject::entry(name.clone(), peer);
131        self.hub.insert_entry(name, entry, replace)
132    }
133
134    /// Stop serving `name` at the top level; answers whether it was served.
135    pub fn remove(&self, name: &str) -> bool {
136        self.hub.remove_entry(name)
137    }
138
139    /// The service's hash now (its schema's: what every item's `plexus_hash`
140    /// says).
141    pub fn hash(&self) -> String {
142        self.hub.compute_hash()
143    }
144
145    /// Told every time the table changes: the service's hash after it.
146    pub fn watch(&self) -> tokio::sync::watch::Receiver<String> {
147        self.hub.watch_root()
148    }
149}
150
151/// A top-level entry, as a peer.
152struct EntryPeer(Entry);
153
154#[async_trait]
155impl Peer for EntryPeer {
156    fn interface(&self) -> Interface {
157        Interface::of(&self.0.object.plugin_schema())
158    }
159
160    async fn call(&self, method: &str, params: Value, auth: Option<&AuthContext>) -> Result<PlexusStream, PlexusError> {
161        self.0.object.call(method, params, auth, None).await
162    }
163
164    async fn peer(&self, name: &str) -> Result<Box<dyn Peer>, PeerError> {
165        match self.0.router.peer_child(name).await? {
166            Some(router) => Ok(Box::new(RouterPeer::new(router))),
167            None => Err(PeerError::NotFound { name: name.to_string() }),
168        }
169    }
170}
171
172/// A shared peer as a boxed one.
173struct ArcPeer(Arc<dyn Peer>);
174
175#[async_trait]
176impl Peer for ArcPeer {
177    fn interface(&self) -> Interface {
178        self.0.interface()
179    }
180    async fn call(&self, method: &str, params: Value, auth: Option<&AuthContext>) -> Result<PlexusStream, PlexusError> {
181        self.0.call(method, params, auth).await
182    }
183    async fn peer(&self, name: &str) -> Result<Box<dyn Peer>, PeerError> {
184        self.0.peer(name).await
185    }
186}
187
188/// Any peer served at the top level: its schema is its interface's, under
189/// the entry's name.
190struct PeerObject {
191    name: String,
192    peer: Arc<dyn Peer>,
193}
194
195impl PeerObject {
196    fn entry(name: String, peer: Arc<dyn Peer>) -> Entry {
197        let router = Arc::new(super::peer::PeerRouter::new(Box::new(ArcPeer(peer.clone()))));
198        Entry { object: Arc::new(PeerObject { name, peer }), router }
199    }
200}
201
202/// `schema` as served under `name`: its roles' grants and its methods' own
203/// grants requalified (`{ns}.m` → `<name>.m`), as a mount's are (NEST-4).
204pub(crate) fn served_as(name: &str, mut schema: PluginSchema) -> PluginSchema {
205    if schema.namespace == name {
206        return schema;
207    }
208    let prefix = format!("{}.", schema.namespace);
209    let requalify = |g: &String| match g.strip_prefix(&prefix) {
210        Some(m) => format!("{name}.{m}"),
211        None => g.clone(),
212    };
213    schema.roles = schema.roles.iter().map(|(r, gs)| (r.clone(), gs.iter().map(requalify).collect())).collect();
214    for m in schema.methods.iter_mut() {
215        if let Some(g) = m.grant.as_ref() {
216            m.grant = Some(requalify(g));
217        }
218    }
219    schema.namespace = name.to_string();
220    schema
221}
222
223#[async_trait]
224impl ActivationObject for PeerObject {
225    fn namespace(&self) -> &str {
226        &self.name
227    }
228    fn version(&self) -> &str {
229        ""
230    }
231    fn description(&self) -> &str {
232        "a peer"
233    }
234    fn long_description(&self) -> Option<&str> {
235        None
236    }
237    fn methods(&self) -> Vec<&str> {
238        Vec::new()
239    }
240    fn method_help(&self, _method: &str) -> Option<String> {
241        None
242    }
243    fn plugin_id(&self) -> uuid::Uuid {
244        uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, format!("peer:{}", self.name).as_bytes())
245    }
246    async fn call(&self, method: &str, params: Value, auth: Option<&AuthContext>, _raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
247        let stream = self.peer.call(method, params, auth).await?;
248        // Its own schema, as it is served here: under the entry's name.
249        if method != "schema" {
250            return Ok(stream);
251        }
252        use futures::StreamExt;
253        let name = self.name.clone();
254        Ok(Box::pin(stream.map(move |item| match item {
255            super::types::PlexusStreamItem::Data { metadata, content_type, content } if content_type.ends_with(".schema") => {
256                match content.decode::<super::schema::SchemaResult>() {
257                    Ok(super::schema::SchemaResult::Plugin(schema)) => {
258                        let served = super::schema::SchemaResult::Plugin(served_as(&name, schema));
259                        let content = serde_json::to_value(&served).map(Into::into).unwrap_or(content);
260                        super::types::PlexusStreamItem::Data { metadata, content_type: format!("{name}.schema").into(), content }
261                    }
262                    _ => super::types::PlexusStreamItem::Data { metadata, content_type, content },
263                }
264            }
265            other => other,
266        })))
267    }
268    async fn resolve_handle(&self, _handle: &Handle) -> Result<PlexusStream, PlexusError> {
269        Err(PlexusError::HandleNotSupported(self.name.clone()))
270    }
271    fn plugin_schema(&self) -> PluginSchema {
272        served_as(&self.name, self.peer.interface().schema().clone())
273    }
274    fn needs(&self) -> Option<Vec<super::schema::Need>> {
275        self.peer.interface().schema().needs.clone()
276    }
277    fn static_child_schemas(&self) -> Vec<(String, PluginSchema)> {
278        Vec::new()
279    }
280    fn schema(&self) -> Schema {
281        let schema = self.plugin_schema();
282        Schema::new(schema.namespace.clone(), schema.description.clone())
283    }
284}