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        self.then(path, name, statics)
71    }
72
73    /// NEST-14: the route of the segment `name` below this one — a peer
74    /// slot's name, an untyped child — joined to this route's path as it
75    /// is (empty: `name` alone), refused as [`Route::instance`] refuses a
76    /// name, with no static children to avoid.
77    pub fn segment(&self, name: &str) -> Route {
78        let path = if self.path.is_empty() { RoutePath::from(name.to_owned()) } else { self.path.join(name) };
79        self.then(path, name, &[])
80    }
81
82    fn then(&self, path: RoutePath, name: &str, statics: &[&str]) -> Route {
83        let refusal = if name.is_empty() {
84            Some(NameRefusal::Empty)
85        } else if name.contains('.') {
86            Some(NameRefusal::Dotted)
87        } else if !is_route_segment(name) {
88            Some(NameRefusal::NotASegment)
89        } else if statics.contains(&name) {
90            Some(NameRefusal::StaticChild)
91        } else {
92            None
93        };
94        let refused = match (&self.refused, refusal) {
95            (Some(earlier), _) => Some(earlier.clone()),
96            (None, Some(why)) => Some(Arc::new((name.to_owned(), why))),
97            (None, None) => None,
98        };
99        Route { path, refused }
100    }
101
102    /// NEST-14: why nothing may be sent along this route, if anything —
103    /// the error every call through it is.
104    pub fn refusal(&self) -> Option<ClientError> {
105        self.refused.as_ref().map(|r| ClientError::InvalidName { name: r.0.clone(), reason: r.1 })
106    }
107
108    /// `method` sent along this route, or why it may not be.
109    pub fn method(&self, method: MethodRef) -> Result<MethodRef, ClientError> {
110        match &self.refused {
111            None => Ok(if self.path.is_empty() { method } else { method.at(self.path.clone()) }),
112            Some(r) => Err(ClientError::InvalidName { name: r.0.clone(), reason: r.1 }),
113        }
114    }
115}
116
117/// One segment of the service's path grammar, `[a-z][a-z0-9_]*` — the rule
118/// plexus-auth-core's `MethodPath` holds every routed path to (mirrored
119/// here: plexus-client builds for wasm32 and takes no plexus-auth-core; a
120/// fixture test holds the two to the same answers).
121pub fn is_route_segment(s: &str) -> bool {
122    let mut chars = s.chars();
123    match chars.next() {
124        Some(c) if c.is_ascii_lowercase() => chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'),
125        _ => false,
126    }
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132
133    #[test]
134    fn routes_join_and_refuse() {
135        let root = Route::ROOT;
136        assert_eq!(root.path("tree"), "tree");
137        let branch = root.child("branch", "tree.branch");
138        assert_eq!(branch.path("branch"), "tree.branch");
139        let a = root.instance("tree", "a", &["branch"]);
140        assert_eq!(a.path("item"), "tree.a");
141        assert_eq!(a.method(MethodRef::new("item", "watch")).unwrap().qualified(), "tree.a.watch");
142        // a method of the parent is the instance
143        assert!(root.instance("tree", "count", &["branch"]).method(MethodRef::new("item", "watch")).is_ok());
144        for (name, why) in [("", NameRefusal::Empty), ("a.b", NameRefusal::Dotted), ("A", NameRefusal::NotASegment), ("branch", NameRefusal::StaticChild)] {
145            let r = root.instance("tree", name, &["branch"]);
146            assert_eq!(r.method(MethodRef::new("item", "watch")), Err(ClientError::InvalidName { name: name.into(), reason: why }));
147            // inherited below
148            let below = r.child("leaf", "item.leaf").instance("item", "ok", &[]);
149            assert!(below.method(MethodRef::new("x", "y")).is_err());
150        }
151    }
152}