1use 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
55pub const HOST_SCHEMA: &str = "host.schema";
57pub const HOST_WHOAMI: &str = "host.whoami";
59pub const HOST_LOG: &str = "host.log";
61pub const HOST_NOTIFY: &str = "host.notify";
64
65pub const STANDARD: [&str; 4] = [HOST_SCHEMA, HOST_WHOAMI, HOST_LOG, HOST_NOTIFY];
68
69pub fn is_standard(method: &str) -> bool {
72 STANDARD.contains(&method) || method.ends_with(".schema")
73}
74
75#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
77pub struct Notice {
78 pub child: String,
80 pub topic: String,
82 #[serde(default)]
84 pub data: Value,
85 #[serde(default, rename = "for", skip_serializing_if = "Option::is_none")]
87 pub for_: Option<String>,
88}
89
90#[derive(Debug, Clone, PartialEq, Eq)]
93pub struct NeedsMiss {
94 pub child: String,
96 pub service: String,
98 pub missing: Vec<String>,
100 pub changed: Vec<String>,
103}
104
105impl NeedsMiss {
106 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
136pub 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
159pub 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
169pub(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#[derive(Clone)]
205enum Route {
206 #[cfg(not(target_arch = "wasm32"))]
208 Host(super::remote_child::HostTransport),
209 Local(HubTransport),
211}
212
213#[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 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 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 pub fn needs(&self) -> &[String] {
263 &self.needs
264 }
265
266 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, ¶ms, 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#[derive(Debug, Clone, thiserror::Error)]
302#[error("{0}")]
303pub struct UpwardError(pub String);
304
305pub 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 pub async fn schema(&self) -> Result<Value, UpwardError> {
328 self.one(HOST_SCHEMA, json!({})).await
329 }
330
331 pub async fn whoami(&self) -> Result<Value, UpwardError> {
334 self.one(HOST_WHOAMI, json!({})).await
335 }
336
337 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 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
350pub struct Parent<C> {
356 client: C,
357 transport: ParentTransport,
358}
359
360impl<C> Parent<C> {
361 pub fn new(transport: ParentTransport, make: impl FnOnce(ParentTransport) -> C) -> Self {
363 Self { client: make(transport.clone()), transport }
364 }
365
366 #[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 pub fn client(&self) -> &C {
375 &self.client
376 }
377
378 pub fn into_inner(self) -> C {
380 self.client
381 }
382
383 pub fn transport(&self) -> &ParentTransport {
385 &self.transport
386 }
387
388 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}