1use 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#[derive(Clone)]
41pub(crate) struct Entry {
42 pub(crate) object: Arc<dyn ActivationObject>,
43 pub(crate) router: Arc<dyn ChildRouter>,
44}
45
46#[derive(Clone, Default)]
49pub(crate) struct Table {
50 pub(crate) entries: BTreeMap<String, Entry>,
51 pub(crate) nested: usize,
53}
54
55#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
57pub enum RootError {
58 #[error("a peer is already served as `{name}` at the top level")]
60 Taken { name: String },
61 #[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 #[error("`{name}` is not a top-level name: one segment of letters, digits, `_` and `-`")]
68 BadName { name: String },
69 #[error("{0}")]
72 Needs(super::parent::NeedsMiss),
73}
74
75pub(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#[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 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 pub fn names(&self) -> Vec<String> {
106 self.hub.table().entries.keys().cloned().collect()
107 }
108
109 pub fn contains(&self, name: &str) -> bool {
111 self.hub.table().entries.contains_key(name)
112 }
113
114 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 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 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 pub fn remove(&self, name: &str) -> bool {
137 self.hub.remove_entry(name)
138 }
139
140 pub fn hash(&self) -> String {
143 self.hub.compute_hash()
144 }
145
146 pub fn watch(&self) -> tokio::sync::watch::Receiver<String> {
148 self.hub.watch_root()
149 }
150}
151
152struct 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
173struct 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
189struct 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
203pub(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 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}