Skip to main content

plexus_core/plexus/
slots.rs

1//! NEST-5 — **a dynamic child's slot is described and granted once.**
2//!
3//! A dynamic child (`#[child] fn planet(&self, name: &str) -> Option<Planet>`)
4//! hangs in a *slot*: its parent's path plus the child function's name,
5//! written `solar.{planet}`. Its names are open (known only at call time),
6//! but its shape is fixed when its code compiles, so the parent's schema
7//! carries the slot's type (`MethodRole::DynamicChild { child }`: `Planet`'s
8//! schema) and the hub grants the slot once:
9//!
10//! | the slot | its grant | decides |
11//! |---|---|---|
12//! | typed (`child` set) | `solar.{planet}.info` | `info` on every name in the slot |
13//! | untyped (`#[child(opaque)]`, a hand-written router) | `solar.{planet}` | every method on every name, the child deciding again |
14//!
15//! A call to `solar.earth.info` matches the slot `solar.{planet}` (a static
16//! child named `earth` still wins, as in routing) and is decided on
17//! `solar.{planet}.info`. A nested slot is the same rule one level at a time
18//! (`solar.{planet}.{moon}.info`). A grant written as a literal path
19//! (`solar.earth.info`) still decides as before: the slot grant is additive —
20//! it applies only where the gate would otherwise know nothing of the path.
21//!
22//! [`slot_schemas`] turns a schema's slots into schemas the hub treats like a
23//! static child's ([`super::children`]): namespace the slot's path, every
24//! grant (methods' and roles') qualified by it — so the grant gate's index,
25//! [`DynamicHub::declared_roles`](super::DynamicHub::declared_roles),
26//! `auth.requires` and the caller's view all read a slot as they read a
27//! static child. [`Slots`] resolves a literal path to its slot's.
28
29use std::collections::{HashMap, HashSet};
30
31use super::children::qualified;
32use super::schema::{MethodRole, PluginSchema};
33
34/// A slot's path: `parent.{slot}`.
35pub fn slot_path(parent: &str, slot: &str) -> String {
36    format!("{parent}.{{{slot}}}")
37}
38
39/// How deep [`slot_schemas`] follows a slot's type into its own slots — a
40/// bound, not a rule: a type that names itself stops at its first repeat
41/// already (the macro gives the repeat no type).
42const MAX_DEPTH: usize = 8;
43
44/// Every slot below `schema` (whose namespace is its whole path,
45/// `tickets` or `tickets.commits`), to any depth: each typed slot as a
46/// schema whose namespace is the slot's path (`tickets.{item}`) and whose
47/// grants are qualified by it, and each untyped slot's path in `untyped`.
48pub fn slot_schemas(schema: &PluginSchema, typed: &mut Vec<PluginSchema>, untyped: &mut Vec<String>) {
49    walk(schema, typed, untyped, 0);
50}
51
52fn walk(schema: &PluginSchema, typed: &mut Vec<PluginSchema>, untyped: &mut Vec<String>, depth: usize) {
53    if depth >= MAX_DEPTH {
54        return;
55    }
56    for m in &schema.methods {
57        if !m.role.is_slot() {
58            continue;
59        }
60        let rel = format!("{{{}}}", m.name);
61        match m.role.slot_schema() {
62            Some(child) => {
63                for q in qualified(&schema.namespace, vec![(rel, child)]) {
64                    walk(&q, typed, untyped, depth + 1);
65                    typed.push(q);
66                }
67            }
68            None => untyped.push(slot_path(&schema.namespace, &m.name)),
69        }
70    }
71}
72
73std::thread_local! {
74    /// The method enums whose schemas this thread is computing: a slot
75    /// whose type is one of them (a type that names itself, or two that name
76    /// each other) is published untyped there, not recursed into.
77    static BUILDING: std::cell::RefCell<Vec<&'static str>> = const { std::cell::RefCell::new(Vec::new()) };
78}
79
80/// Held while a method enum's schemas are computed (the macro's
81/// `compute_method_schemas`); see [`slot_type`].
82#[doc(hidden)]
83pub struct Building(());
84
85impl Drop for Building {
86    fn drop(&mut self) {
87        BUILDING.with(|b| {
88            b.borrow_mut().pop();
89        });
90    }
91}
92
93/// Mark `name` (a method enum's `type_name`) as being computed on this
94/// thread until the guard drops.
95#[doc(hidden)]
96pub fn building(name: &'static str) -> Building {
97    BUILDING.with(|b| b.borrow_mut().push(name));
98    Building(())
99}
100
101/// NEST-5: the slot type of a dynamic child whose type is `T` — `T`'s own
102/// schema, without an instance ([`Activation::slot_schema`]). `None` when
103/// `T`'s schemas are being computed on this thread already (a recursive
104/// type: the repeat is an untyped slot), or `T` was not written by the
105/// macro.
106///
107/// [`Activation::slot_schema`]: super::Activation::slot_schema
108pub fn slot_type<T: super::Activation>() -> Option<Box<PluginSchema>> {
109    let name = std::any::type_name::<<T as super::Activation>::Methods>();
110    if BUILDING.with(|b| b.borrow().contains(&name)) {
111        return None;
112    }
113    T::slot_schema().map(Box::new)
114}
115
116/// The slots of a service, for resolving a literal path to its slot's.
117#[derive(Debug, Default, Clone)]
118pub struct Slots {
119    /// A parent's dynamic child (reached as `parent.<name>`): its slot's
120    /// name and whether it is typed.
121    by_parent: HashMap<String, (String, bool)>,
122    /// NEST-7: a parent's peer slots (reached as `parent.<slot>.<name>`), by
123    /// slot name: whether each is typed.
124    peers: HashMap<(String, String), bool>,
125    /// Every path the service describes: activations, static children and
126    /// slots (`tickets.{item}`) — a literal segment that names one wins.
127    known: HashSet<String>,
128}
129
130impl Slots {
131    /// The slots of `schemas` (each namespace its whole path: activations,
132    /// static children, typed slots) and of the untyped slots' paths.
133    pub fn of<'a>(schemas: impl IntoIterator<Item = &'a PluginSchema>, untyped: &[String]) -> Self {
134        let mut s = Slots::default();
135        for schema in schemas {
136            s.add(schema);
137        }
138        for u in untyped {
139            s.add_untyped(u);
140        }
141        s
142    }
143
144    /// Add one schema's slots (its namespace its whole path).
145    pub fn add(&mut self, schema: &PluginSchema) {
146        self.known.insert(schema.namespace.clone());
147        for m in &schema.methods {
148            let typed = m.role.slot_schema().is_some();
149            match &m.role {
150                MethodRole::Peer { .. } => {
151                    self.peers.insert((schema.namespace.clone(), m.name.clone()), typed);
152                }
153                MethodRole::DynamicChild { .. } => {
154                    self.by_parent.entry(schema.namespace.clone()).or_insert((m.name.clone(), typed));
155                }
156                _ => {}
157            }
158        }
159    }
160
161    /// Add an untyped slot's path (`tickets.{item}`).
162    pub fn add_untyped(&mut self, path: &str) {
163        self.known.insert(path.to_string());
164    }
165
166    /// ONE-7: whether the slot at `path` (`dyn.{peer}`) is an untyped peer
167    /// slot — a `#[peer]` slot whose names route on into another service, so
168    /// no data of this one is reached through it: the gate decides it at the
169    /// door of the call dispatched. A typed peer slot, and a dynamic child's
170    /// slot of either kind, are not.
171    pub fn is_untyped_peer_slot(&self, path: &str) -> bool {
172        let Some((parent, slot)) = path.strip_suffix('}').and_then(|p| p.rsplit_once(".{")) else { return false };
173        self.peers.get(&(parent.to_string(), slot.to_string())) == Some(&false)
174    }
175
176    /// Whether no slot is known.
177    pub fn is_empty(&self) -> bool {
178        self.by_parent.is_empty() && self.peers.is_empty()
179    }
180
181    /// The slot grant's key for the literal `method` (`solar.earth.info` →
182    /// `solar.{planet}.info`; a peer slot's `host.integration.github.repos`
183    /// → `host.{integration}.repos`; through an untyped slot, the slot
184    /// itself, `solar.{planet}`), or `None` when no slot is on its way — a
185    /// static child that names a segment wins over the slot.
186    pub fn resolve(&self, method: &str) -> Option<String> {
187        if self.is_empty() {
188            return None;
189        }
190        let segs: Vec<&str> = method.split('.').collect();
191        if segs.len() < 3 {
192            return None;
193        }
194        let last = segs.len() - 1;
195        let mut cur = segs[0].to_string();
196        let mut through = false;
197        let mut i = 1;
198        while i < last {
199            let seg = segs[i];
200            let literal = format!("{cur}.{seg}");
201            if self.known.contains(&literal) {
202                cur = literal;
203                i += 1;
204                continue;
205            }
206            // NEST-7: a peer slot is named in the path, then the peer's name.
207            if let Some(typed) = self.peers.get(&(cur.clone(), seg.to_string())) {
208                if i + 1 >= last {
209                    return None;
210                }
211                cur = slot_path(&cur, seg);
212                through = true;
213                i += 2;
214                if !typed {
215                    return Some(cur);
216                }
217                continue;
218            }
219            let (slot, typed) = self.by_parent.get(&cur)?;
220            cur = slot_path(&cur, slot);
221            through = true;
222            i += 1;
223            if !typed {
224                return Some(cur);
225            }
226        }
227        through.then(|| format!("{cur}.{}", segs[last]))
228    }
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234    use crate::plexus::schema::{MethodSchema, PluginSchema};
235
236    fn planet() -> PluginSchema {
237        let mut p = PluginSchema::leaf(
238            "planet",
239            "1.0",
240            "a planet",
241            vec![MethodSchema::new("info", "d", "h"), MethodSchema::new("rename", "d", "h")],
242        );
243        p.roles.insert("viewer".into(), vec!["planet.info".into()]);
244        p
245    }
246
247    fn solar(typed: bool) -> PluginSchema {
248        let role = MethodRole::DynamicChild {
249            list_method: Some("names".into()),
250            search_method: None,
251            child: typed.then(|| Box::new(planet())),
252        };
253        PluginSchema::leaf(
254            "solar",
255            "1.0",
256            "the system",
257            vec![MethodSchema::new("names", "d", "h"), MethodSchema::new("planet", "d", "h").with_role(role)],
258        )
259    }
260
261    #[test]
262    fn a_typed_slot_is_a_schema_at_its_path() {
263        let (mut typed, mut untyped) = (vec![], vec![]);
264        slot_schemas(&solar(true), &mut typed, &mut untyped);
265        assert!(untyped.is_empty());
266        assert_eq!(typed.len(), 1);
267        assert_eq!(typed[0].namespace, "solar.{planet}");
268        let grants: Vec<_> = typed[0].methods.iter().map(|m| m.grant.clone().unwrap()).collect();
269        assert_eq!(grants, ["solar.{planet}.info", "solar.{planet}.rename"]);
270        assert_eq!(typed[0].roles["viewer"], ["solar.{planet}.info"]);
271    }
272
273    #[test]
274    fn an_untyped_slot_is_its_path() {
275        let (mut typed, mut untyped) = (vec![], vec![]);
276        slot_schemas(&solar(false), &mut typed, &mut untyped);
277        assert!(typed.is_empty());
278        assert_eq!(untyped, ["solar.{planet}"]);
279    }
280
281    #[test]
282    fn a_literal_path_resolves_to_its_slot_and_a_static_child_wins() {
283        let (mut typed, mut untyped) = (vec![], vec![]);
284        let s = solar(true);
285        slot_schemas(&s, &mut typed, &mut untyped);
286        let mut moons = PluginSchema::leaf("solar.luna", "1.0", "a static child", vec![]);
287        moons.methods.push(MethodSchema::new("info", "d", "h"));
288        let all: Vec<PluginSchema> = vec![s, moons].into_iter().chain(typed).collect();
289        let slots = Slots::of(all.iter(), &untyped);
290        assert_eq!(slots.resolve("solar.earth.info").as_deref(), Some("solar.{planet}.info"));
291        assert_eq!(slots.resolve("solar.luna.info"), None, "a static child wins");
292        assert_eq!(slots.resolve("solar.names"), None);
293        assert_eq!(slots.resolve("other.earth.info"), None);
294    }
295
296    #[test]
297    fn an_untyped_slot_resolves_to_the_slot_whole() {
298        let (mut typed, mut untyped) = (vec![], vec![]);
299        let s = solar(false);
300        slot_schemas(&s, &mut typed, &mut untyped);
301        let slots = Slots::of([&s], &untyped);
302        assert_eq!(slots.resolve("solar.earth.info").as_deref(), Some("solar.{planet}"));
303        assert_eq!(slots.resolve("solar.earth.deep.er").as_deref(), Some("solar.{planet}"));
304    }
305
306    #[test]
307    fn a_nested_slot_is_the_same_rule_one_level_at_a_time() {
308        let moon = PluginSchema::leaf("moon", "1.0", "a moon", vec![MethodSchema::new("phase", "d", "h")]);
309        let mut p = planet();
310        p.methods.push(MethodSchema::new("moon", "d", "h").with_role(MethodRole::DynamicChild {
311            list_method: None,
312            search_method: None,
313            child: Some(Box::new(moon)),
314        }));
315        let s = PluginSchema::leaf(
316            "solar",
317            "1.0",
318            "the system",
319            vec![MethodSchema::new("planet", "d", "h").with_role(MethodRole::DynamicChild {
320                list_method: None,
321                search_method: None,
322                child: Some(Box::new(p)),
323            })],
324        );
325        let (mut typed, mut untyped) = (vec![], vec![]);
326        slot_schemas(&s, &mut typed, &mut untyped);
327        let names: Vec<_> = typed.iter().map(|t| t.namespace.as_str()).collect();
328        assert_eq!(names, ["solar.{planet}.{moon}", "solar.{planet}"]);
329        assert_eq!(typed[0].methods[0].grant.as_deref(), Some("solar.{planet}.{moon}.phase"));
330        let all: Vec<PluginSchema> = std::iter::once(s).chain(typed).collect();
331        let slots = Slots::of(all.iter(), &untyped);
332        assert_eq!(slots.resolve("solar.earth.luna.phase").as_deref(), Some("solar.{planet}.{moon}.phase"));
333    }
334}