Skip to main content

plexus_client/
route.rs

1//! RETURNS-46 · where a generated client's calls go, and whether they may.
2//!
3//! A [`Route`] is a client's path (a [`RoutePath`]) and, for a client below a
4//! dynamic instance whose name the service would route elsewhere, why
5//! nothing may be sent. A child's route is its parent's, joined; a refusal
6//! is inherited, so `root.org("acme.stats").stats().tick(..)` fails as
7//! `root.org("acme.stats").tick(..)` does — at once, with
8//! [`ClientError::InvalidName`], sending nothing.
9
10use std::sync::Arc;
11
12use crate::error::{ClientError, NameRefusal};
13use crate::transport::{MethodRef, RoutePath};
14
15/// A generated client's route: its path, and a refusal if an instance name
16/// on the way to it cannot be routed.
17#[derive(Clone, Debug, PartialEq, Eq)]
18pub struct Route {
19    path: RoutePath,
20    refused: Option<Arc<(String, NameRefusal)>>,
21}
22
23impl Route {
24    /// The activation at its own namespace.
25    pub const ROOT: Route = Route { path: RoutePath::EMPTY, refused: None };
26
27    /// The activation mounted at `path` (its namespace, or empty, is
28    /// [`Route::ROOT`]).
29    pub fn at(path: impl Into<RoutePath>, namespace: &str) -> Route {
30        let path = path.into();
31        if path.as_str() == namespace {
32            Route::ROOT
33        } else {
34            Route { path, refused: None }
35        }
36    }
37
38    /// The dotted path: `namespace` when mounted at its own.
39    pub fn path<'a>(&'a self, namespace: &'a str) -> &'a str {
40        if self.path.is_empty() {
41            namespace
42        } else {
43            self.path.as_str()
44        }
45    }
46
47    /// The route of the static child `segment`. `joined` is
48    /// `"{namespace}.{segment}"`, known when the program is written: a
49    /// child of a client at its own namespace costs no allocation.
50    pub fn child(&self, segment: &str, joined: &'static str) -> Route {
51        let path = if self.path.is_empty() {
52            RoutePath::from_static(joined)
53        } else {
54            self.path.join(segment)
55        };
56        Route { path, refused: self.refused.clone() }
57    }
58
59    /// The route of the dynamic instance `name`, refused when the service
60    /// would not reach the instance with it: empty, dotted, outside its path
61    /// grammar ([`is_route_segment`]), or one of the parent's static
62    /// children's `statics`. A name that is a method of the parent is fine:
63    /// the service takes it as the child.
64    pub fn instance(&self, namespace: &str, name: &str, statics: &[&str]) -> Route {
65        let path = if self.path.is_empty() {
66            RoutePath::from(format!("{namespace}.{name}"))
67        } else {
68            self.path.join(name)
69        };
70        let refusal = if name.is_empty() {
71            Some(NameRefusal::Empty)
72        } else if name.contains('.') {
73            Some(NameRefusal::Dotted)
74        } else if !is_route_segment(name) {
75            Some(NameRefusal::NotASegment)
76        } else if statics.contains(&name) {
77            Some(NameRefusal::StaticChild)
78        } else {
79            None
80        };
81        let refused = match (&self.refused, refusal) {
82            (Some(earlier), _) => Some(earlier.clone()),
83            (None, Some(why)) => Some(Arc::new((name.to_owned(), why))),
84            (None, None) => None,
85        };
86        Route { path, refused }
87    }
88
89    /// `method` sent along this route, or why it may not be.
90    pub fn method(&self, method: MethodRef) -> Result<MethodRef, ClientError> {
91        match &self.refused {
92            None => Ok(if self.path.is_empty() { method } else { method.at(self.path.clone()) }),
93            Some(r) => Err(ClientError::InvalidName { name: r.0.clone(), reason: r.1 }),
94        }
95    }
96}
97
98/// One segment of the service's path grammar, `[a-z][a-z0-9_]*` — the rule
99/// plexus-auth-core's `MethodPath` holds every routed path to (mirrored
100/// here: plexus-client builds for wasm32 and takes no plexus-auth-core; a
101/// fixture test holds the two to the same answers).
102pub fn is_route_segment(s: &str) -> bool {
103    let mut chars = s.chars();
104    match chars.next() {
105        Some(c) if c.is_ascii_lowercase() => chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'),
106        _ => false,
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113
114    #[test]
115    fn routes_join_and_refuse() {
116        let root = Route::ROOT;
117        assert_eq!(root.path("tree"), "tree");
118        let branch = root.child("branch", "tree.branch");
119        assert_eq!(branch.path("branch"), "tree.branch");
120        let a = root.instance("tree", "a", &["branch"]);
121        assert_eq!(a.path("item"), "tree.a");
122        assert_eq!(a.method(MethodRef::new("item", "watch")).unwrap().qualified(), "tree.a.watch");
123        // a method of the parent is the instance
124        assert!(root.instance("tree", "count", &["branch"]).method(MethodRef::new("item", "watch")).is_ok());
125        for (name, why) in [("", NameRefusal::Empty), ("a.b", NameRefusal::Dotted), ("A", NameRefusal::NotASegment), ("branch", NameRefusal::StaticChild)] {
126            let r = root.instance("tree", name, &["branch"]);
127            assert_eq!(r.method(MethodRef::new("item", "watch")), Err(ClientError::InvalidName { name: name.into(), reason: why }));
128            // inherited below
129            let below = r.child("leaf", "item.leaf").instance("item", "ok", &[]);
130            assert!(below.method(MethodRef::new("x", "y")).is_err());
131        }
132    }
133}