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: an entry under it would be unreachable")]
64 Shadows { name: String },
65 #[error("`{name}` is not a top-level name: one segment of letters, digits, `_` and `-`")]
67 BadName { name: String },
68 #[error("{0}")]
71 Needs(super::parent::NeedsMiss),
72}
73
74pub(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#[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 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 pub fn names(&self) -> Vec<String> {
105 self.hub.table().entries.keys().cloned().collect()
106 }
107
108 pub fn contains(&self, name: &str) -> bool {
110 self.hub.table().entries.contains_key(name)
111 }
112
113 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 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 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 pub fn remove(&self, name: &str) -> bool {
136 self.hub.remove_entry(name)
137 }
138
139 pub fn hash(&self) -> String {
142 self.hub.compute_hash()
143 }
144
145 pub fn watch(&self) -> tokio::sync::watch::Receiver<String> {
147 self.hub.watch_root()
148 }
149}
150
151struct 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
172struct 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
188struct 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
202pub(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 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}