Skip to main content

plexus_core/plexus/
view.rs

1//! AUTH-4 — **the caller's view**: what a caller can discover of a gated service
2//! is exactly what it can use.
3//!
4//! A service with a gate ([`DynamicHub::with_gate`](super::DynamicHub::with_gate))
5//! answers `_info`, its own `schema` / `hash` / `hashes`, and every
6//! `<activation>.schema` from the caller's [`View`]:
7//!
8//! - **anonymous** (no principal): only the `public` methods — the auth
9//!   activation's door (`auth.providers`, `auth.login`, `auth.signup`);
10//! - **caller** (signed in): only the methods whose grant some role the
11//!   caller holds lists (within its session's ceiling), each with `held_on`
12//!   — where it is held; plus the public methods, and the methods every
13//!   signed-in caller reaches (the auth activation's `whoami`, `logout`,
14//!   `requires`). A method the caller cannot use is **absent**, not marked;
15//!   an activation left with none is absent too.
16//!
17//! The service's own methods (`call`, `hash`, `hashes`, `schema`) are in every
18//! view: they are how a client reaches anything at all. Each activation's
19//! `schema` entry stays beside its visible methods (introspection is open).
20//! An activation's declared `roles` are left out of a gated view (they name
21//! methods the caller may not see); `auth.roles` answers them to whoever
22//! holds it.
23//!
24//! **Hashes.** Every schema in a view carries a hash of what *it* shows —
25//! its methods (with `held_on`) and, for the service, its children's view
26//! hashes — so two callers with identical holdings share a view hash, and
27//! a client's schema cache (synapse keeps IR by hash) never mixes two
28//! callers' views. The service's view hash is `v-anon-<hex>` for the anonymous
29//! view and `v-<hex>` for a caller's. PERF-21: the service lists its children
30//! by namespace, so a view hash is the same at every start of the same build,
31//! and a cache keeps its schema across a restart.
32//!
33//! A service **without a gate** never builds a view on the wire: `_info` and
34//! every schema answer exactly as before. [`DynamicHub::view`](super::DynamicHub::view)
35//! there returns the whole service as a [`ViewKind::Caller`] view whose hash is
36//! the service's own.
37//!
38//! **Kept, not rebuilt** (PERF-15). Building a view asks every activation for
39//! its schema and the gate for every method — 150–520 ms on menger, on every
40//! `_info`, `hash` and `schema`. A service keeps instead ([`Cache`]): what its
41//! schemas show whoever asks ([`Described`]), built once per *schema
42//! generation* — moved by every change to the service while it is built (a
43//! mount) and by [`DynamicHub::schema_moved`](super::DynamicHub::schema_moved)
44//! after; and each view of it ([`Shaped`]), built once per *view key* — the
45//! caller's grants' [`Fingerprint`], or anonymous — and *grants generation*,
46//! which every write that could change one of the gate's answers moves
47//! (BIDIR-8). Callers holding the same share one view. A view is kept as what
48//! it decided — which methods, each `held_on`, and the hashes — not as copies
49//! of the schemas, and is rebuilt from [`Described`] exactly as it was built.
50//! A caller's sign-in is asked whether it still stands on every ask (AUTH-11):
51//! one that ended is anonymous at once.
52
53use std::collections::{BTreeMap, BTreeSet, HashMap};
54use std::hash::{Hash, Hasher};
55use std::sync::atomic::{AtomicU64, Ordering};
56use std::sync::{Arc, Mutex, OnceLock};
57
58use plexus_auth_core::grants::{Fingerprint, Gate, Grant};
59use serde_json::Value;
60
61use super::auth::AuthContext;
62use super::context::PlexusContext;
63use super::schema::{ChildHashes, ChildSummary, MethodRole, MethodSchema, PluginHashes, PluginSchema, ViewKind};
64use super::types::{PlexusStreamItem, StreamMetadata};
65
66/// The service as one caller may see it (AUTH-4).
67#[derive(Debug, Clone)]
68pub struct View {
69    /// Anonymous (the door only) or the caller's own.
70    pub kind: ViewKind,
71    /// The service's own schema in this view: its methods, and a child summary
72    /// for each activation the view keeps, carrying that activation's view
73    /// hash. `hash` is the view's hash.
74    pub schema: PluginSchema,
75    /// The view's hash: deterministic over what the view shows.
76    pub hash: String,
77    /// Each activation the view keeps, by namespace, as its
78    /// `<ns>.schema` answers in this view.
79    pub activations: BTreeMap<String, PluginSchema>,
80}
81
82impl View {
83    /// The schema `<ns>.schema` answers in this view: the service's own for its
84    /// namespace, else the activation's — `None` when the view does not
85    /// show it.
86    pub fn schema_of(&self, ns: &str) -> Option<&PluginSchema> {
87        if ns == self.schema.namespace {
88            Some(&self.schema)
89        } else {
90            self.activations.get(ns)
91        }
92    }
93
94    /// The grants of the `public` methods this view shows, activation by
95    /// activation (in namespace order), each in declaration order —
96    /// `_info`'s `auth.methods` for an anonymous caller.
97    pub fn public_methods(&self) -> Vec<String> {
98        self.activations
99            .values()
100            .flat_map(|s| {
101                let ns = s.namespace.clone();
102                s.methods.iter().filter(|m| m.public).map(move |m| m.grant_or(&ns)).collect::<Vec<_>>()
103            })
104            .collect()
105    }
106
107    /// The service's `hashes` answer in this view.
108    pub fn hashes(&self) -> PluginHashes {
109        hashes_of(&self.schema)
110    }
111}
112
113/// The service's `hashes` answer, from its schema.
114#[allow(deprecated)]
115fn hashes_of(service: &PluginSchema) -> PluginHashes {
116    PluginHashes {
117        namespace: service.namespace.clone(),
118        self_hash: service.self_hash.clone(),
119        children_hash: service.children_hash.clone(),
120        hash: service.hash.clone(),
121        children: service
122            .children
123            .as_ref()
124            .map(|kids| kids.iter().map(|c| ChildHashes { namespace: c.namespace.clone(), hash: c.hash.clone() }).collect()),
125    }
126}
127
128/// A stable 64-bit digest of `value`'s JSON, as 16 hex digits. The JSON of
129/// a schema is deterministic (struct fields in order; maps sorted), so equal
130/// views digest equally.
131fn digest(value: &impl serde::Serialize) -> String {
132    let text = serde_json::to_string(value).unwrap_or_default();
133    let mut h = std::collections::hash_map::DefaultHasher::new();
134    text.hash(&mut h);
135    format!("{:016x}", h.finish())
136}
137
138/// What the gate needs to say about one caller, computed once per view.
139struct Asker<'a> {
140    gate: &'a Gate,
141    /// The caller's grants ([`Gate::fingerprint`]); `None` when anonymous.
142    who: Option<&'a Fingerprint>,
143    /// ONE-7: the caller the view is first built for — one whose grants are
144    /// `who` — asked at each door the view shows ([`Gate::check_everywhere_at`]
145    /// reads exactly what a fingerprint holds: the memberships and the
146    /// session's ceiling), so every caller sharing `who` shares the answer.
147    caller: Option<&'a AuthContext>,
148    /// Grants every signed-in caller reaches (the auth activation's
149    /// `whoami`, `logout`, `requires`), whatever its roles or ceiling.
150    signed_in_grants: &'a BTreeSet<String>,
151}
152
153/// ONE-7: the name a view asks a slot's door at, for a slot's segment
154/// (`solar.{planet}.rotate` → `solar.__any__.rotate`): a view is one per
155/// caller, not per name, so it shows a door inside a slot only to one whose
156/// scope covers every name there (`/solar.*`, `*`) — one holding a single
157/// name (`/solar.earth.*`) still calls it, and is not shown it. (A real name
158/// `__any__` is no exception: the view only shows, the gate decides.)
159const ANY: &str = "__any__";
160
161/// The literal path a view asks a door at: each slot segment as [`ANY`].
162fn probe(path: &str) -> String {
163    path.split('.').map(|s| if s.starts_with('{') { ANY } else { s }).collect::<Vec<_>>().join(".")
164}
165
166impl Asker<'_> {
167    /// ONE-7: whether the caller opens the door of `grant` at the literal
168    /// path `at` — as the gate would admit the call there.
169    fn opens(&self, grant: &str, at: &str) -> bool {
170        let Some(caller) = self.caller else { return false };
171        let none = std::collections::HashSet::new();
172        match super::grant_gate::dispatched(&probe(at), &Grant::new(grant), &none) {
173            Some(call) => self.gate.check_everywhere_at(Some(caller), &call).is_ok(),
174            None => false,
175        }
176    }
177
178    /// Whether the view keeps a method, and its `held_on` there. KEEL-31: a
179    /// method that acts `everywhere` is kept only where it is held on `*` —
180    /// where the gate would admit it. ONE-7: or, decided at a door (`door`:
181    /// its literal path — an `everywhere` method with no target), where the
182    /// caller opens it; `held_on` stays the data it holds the grant on.
183    fn keep(&self, grant: &str, public: bool, everywhere: bool, door: Option<&str>) -> Option<Option<Vec<String>>> {
184        let Some(who) = self.who else {
185            return public.then_some(None);
186        };
187        let held: Vec<String> = self.gate.held_on_by(who, &Grant::new(grant)).iter().map(|s| s.as_str().to_string()).collect();
188        if everywhere {
189            let at_door = || door.is_some_and(|at| self.opens(grant, at));
190            return (held.iter().any(|s| s == "*") || at_door()).then_some(Some(held));
191        }
192        if !held.is_empty() {
193            return Some(Some(held));
194        }
195        (public || self.signed_in_grants.contains(grant)).then_some(None)
196    }
197}
198
199/// What a service's schemas show whoever asks: its own schema, every registered
200/// activation's and every static child's (MACRO-20) — built once per schema
201/// generation, and every view of the service is decided over it.
202pub(crate) struct Described {
203    /// The service's own schema ([`Activation::plugin_schema`](super::Activation::plugin_schema)).
204    pub(crate) service: PluginSchema,
205    /// Each registered activation's schema, in namespace order (PERF-21).
206    pub(crate) activations: Vec<PluginSchema>,
207    /// The static children, by their whole path — what a view reads of them.
208    below: Vec<Below>,
209    /// Each activation's schema without its methods — what a view's schema
210    /// is rebuilt from, beside the methods it keeps.
211    hollow: Vec<PluginSchema>,
212    /// Introspection answers' envelopes, by method and params ([`Shell`]).
213    shells: Mutex<HashMap<String, Arc<Shell>>>,
214}
215
216/// A static child (MACRO-20) as a view reads it: its whole path, and the
217/// grant of each method it answers, `public` or not — not its schema, which
218/// on menger is as large as `tickets.schema` itself.
219struct Below {
220    namespace: String,
221    /// Each method's grant, whether it is `public`, whether it acts
222    /// `everywhere` (KEEL-31), and (ONE-7) its path when the door decides it.
223    grants: Vec<(String, bool, bool, Option<String>)>,
224}
225
226impl Below {
227    fn of(child: &PluginSchema) -> Self {
228        let grants = child
229            .methods
230            .iter()
231            .filter(|m| matches!(m.role, MethodRole::Rpc) && !m.is_auto_schema())
232            .map(|m| (m.grant_or(&child.namespace), m.public, m.everywhere, door_path(&child.namespace, m)))
233            .collect();
234        Below { namespace: child.namespace.clone(), grants }
235    }
236}
237
238/// ONE-7: the literal path of a method the door decides (an `everywhere`
239/// method with no target, [`super::grant_gate::door_shaped`]); `None` for
240/// every other.
241fn door_path(ns: &str, m: &MethodSchema) -> Option<String> {
242    super::grant_gate::door_shaped(m.everywhere, m.target.as_deref(), false).then(|| format!("{ns}.{}", m.name))
243}
244
245/// At most this many envelopes are kept; past it each new one is routed
246/// every time, as before PERF-15.
247const SHELLS: usize = 256;
248
249impl Described {
250    pub(crate) fn new(service: PluginSchema, activations: Vec<PluginSchema>, children: Vec<PluginSchema>) -> Self {
251        let hollow = activations
252            .iter()
253            .map(|s| {
254                let mut h = s.clone();
255                h.methods = Vec::new();
256                h
257            })
258            .collect();
259        let below = children.iter().map(Below::of).collect();
260        Self { service, activations, below, hollow, shells: Mutex::new(HashMap::new()) }
261    }
262
263    /// The view of a service without a gate: everything, as today.
264    pub(crate) fn whole(&self) -> View {
265        View {
266            kind: ViewKind::Caller,
267            schema: self.service.clone(),
268            hash: self.service.hash.clone(),
269            activations: self.activations.iter().map(|s| (s.namespace.clone(), s.clone())).collect(),
270        }
271    }
272
273    /// RETURNS-40: every static child's whole path (`tickets.commits`), as
274    /// the service describes it — what `ir` may be asked for below an
275    /// activation.
276    pub(crate) fn nested(&self) -> impl Iterator<Item = &str> {
277        // NEST-5: a slot (`tickets.{item}`) is no path `ir` is asked for.
278        self.below.iter().map(|b| b.namespace.as_str()).filter(|n| !n.contains('{'))
279    }
280
281    /// The envelope kept for an introspection answer (`key`: its method and params).
282    pub(crate) fn shell(&self, key: &str) -> Option<Arc<Shell>> {
283        self.shells.lock().unwrap_or_else(|p| p.into_inner()).get(key).cloned()
284    }
285
286    /// Keep `shell` for `key` — while there is room.
287    pub(crate) fn keep_shell(&self, key: String, shell: Shell) {
288        let mut shells = self.shells.lock().unwrap_or_else(|p| p.into_inner());
289        if shells.len() < SHELLS {
290            shells.insert(key, Arc::new(shell));
291        }
292    }
293}
294
295/// One caller's view, kept as what it decided over [`Described`]: the service's
296/// own schema in the view (small: its methods and the kept activations'
297/// summaries), and for each activation it keeps which of its methods, in the
298/// order shown, each with its `held_on`, and its hashes — not a copy of the
299/// schemas. [`Shaped::view`] rebuilds exactly the [`View`] it decided.
300pub(crate) struct Shaped {
301    pub(crate) kind: ViewKind,
302    /// The view's hash ([`View::hash`]).
303    pub(crate) hash: String,
304    /// The service's own schema in this view ([`View::schema`]).
305    pub(crate) service: PluginSchema,
306    kept: BTreeMap<String, Kept>,
307    /// `_info`'s content for this view, once asked.
308    pub(crate) info: OnceLock<Value>,
309}
310
311/// One activation as a view keeps it.
312struct Kept {
313    /// Where it is in [`Described::activations`].
314    at: usize,
315    /// The methods shown, in order: each one's index in the activation's
316    /// methods, and the `held_on` the view gives it.
317    methods: Vec<(usize, Option<Vec<String>>)>,
318    /// The child summaries kept (`None`: the activation lists none).
319    children: Option<Vec<ChildSummary>>,
320    self_hash: String,
321    children_hash: Option<String>,
322    hash: String,
323}
324
325impl Kept {
326    /// The activation's schema as the view shows it.
327    fn schema(&self, base: &Described, kind: ViewKind) -> PluginSchema {
328        let source = &base.activations[self.at];
329        let mut s = base.hollow[self.at].clone();
330        s.methods = self.methods.iter().map(|(i, held)| Self::shown(source, *i, held)).collect();
331        #[allow(deprecated)]
332        {
333            s.children = self.children.clone();
334        }
335        s.roles = BTreeMap::new();
336        s.view = Some(kind);
337        s.self_hash = self.self_hash.clone();
338        s.children_hash = self.children_hash.clone();
339        s.hash = self.hash.clone();
340        s
341    }
342
343    /// The method named `name` as the view shows it, if it does.
344    fn method(&self, base: &Described, name: &str) -> Option<MethodSchema> {
345        let source = &base.activations[self.at];
346        self.methods.iter().find(|(i, _)| source.methods[*i].name == name).map(|(i, held)| Self::shown(source, *i, held))
347    }
348
349    fn shown(source: &PluginSchema, i: usize, held: &Option<Vec<String>>) -> MethodSchema {
350        let mut m = source.methods[i].clone();
351        m.held_on = held.clone();
352        m
353    }
354}
355
356impl Shaped {
357    /// The view, whole.
358    pub(crate) fn view(&self, base: &Described) -> View {
359        View {
360            kind: self.kind,
361            schema: self.service.clone(),
362            hash: self.hash.clone(),
363            activations: self.kept.iter().map(|(ns, k)| (ns.clone(), k.schema(base, self.kind))).collect(),
364        }
365    }
366
367    /// Whether the view shows `ns`: the service's own namespace, or an activation it keeps.
368    pub(crate) fn shows(&self, ns: &str) -> bool {
369        ns == self.service.namespace || self.kept.contains_key(ns)
370    }
371
372    /// [`View::schema_of`]: the schema `<ns>.schema` answers in this view.
373    pub(crate) fn schema_of(&self, base: &Described, ns: &str) -> Option<PluginSchema> {
374        if ns == self.service.namespace {
375            Some(self.service.clone())
376        } else {
377            self.kept.get(ns).map(|k| k.schema(base, self.kind))
378        }
379    }
380
381    /// The method `name` of `ns`'s schema in this view, as it shows it.
382    pub(crate) fn method_of(&self, base: &Described, ns: &str, name: &str) -> Option<MethodSchema> {
383        if ns == self.service.namespace {
384            self.service.methods.iter().find(|m| m.name == name).cloned()
385        } else {
386            self.kept.get(ns)?.method(base, name)
387        }
388    }
389
390    /// [`View::public_methods`].
391    pub(crate) fn public_methods(&self, base: &Described) -> Vec<String> {
392        self.kept
393            .values()
394            .flat_map(|k| {
395                let source = &base.activations[k.at];
396                k.methods.iter().map(|(i, _)| &source.methods[*i]).filter(|m| m.public).map(|m| m.grant_or(&source.namespace))
397            })
398            .collect()
399    }
400
401    /// [`View::hashes`].
402    pub(crate) fn hashes(&self) -> PluginHashes {
403        hashes_of(&self.service)
404    }
405}
406
407/// One activation as the view keeps it, or `None` when it keeps no method
408/// of it.
409fn activation_view(asker: &Asker<'_>, kind: ViewKind, base: &Described, at: usize) -> Option<Kept> {
410    let schema = &base.activations[at];
411    let ns = &schema.namespace;
412    let mut kept = Vec::new();
413    let mut schema_entry = None;
414    for (i, m) in schema.methods.iter().enumerate() {
415        let is_schema_entry = m.is_auto_schema();
416        if is_schema_entry {
417            schema_entry = Some((i, m.held_on.clone()));
418            continue;
419        }
420        // MACRO-20: a static child's entry (`tickets.commits`) names no
421        // method of its own; it stays when the caller can use a method
422        // somewhere below it (`tickets.commits.link`), so the caller can
423        // navigate to what it holds.
424        // A child that describes nothing (a hand-written router) is
425        // decided as before, by the entry's own grant.
426        // NEST-5: a slot's entry (`solar.planet`) the same, by the slot's
427        // path (`solar.{planet}`): it stays when the caller holds a method
428        // of the slot, or the untyped slot whole.
429        if m.role.is_slot() {
430            let slot = super::slots::slot_path(ns, &m.name);
431            // ONE-7: an untyped peer slot is decided at the door of the call
432            // into it (KEEL-44): shown to one who opens it for every name
433            // (`/dyn.*`, `*`), never by its grant held on data.
434            let untyped_peer = matches!(m.role, MethodRole::Peer { .. }) && m.role.slot_schema().is_none();
435            let whole = match untyped_peer {
436                true => asker.opens(&slot, &format!("{ns}.{}.{ANY}.{ANY}", m.name)),
437                false => asker.keep(&slot, false, false, None).is_some(),
438            };
439            let reached = reaches_below(asker, &slot, &base.below).unwrap_or(false)
440                || whole
441                || asker.keep(&m.grant_or(ns), m.public, m.everywhere, door_path(ns, m).as_deref()).is_some();
442            if reached {
443                kept.push((i, None));
444            }
445            continue;
446        }
447        if matches!(m.role, MethodRole::StaticChild) {
448            if let Some(reached) = reaches_below(asker, &format!("{ns}.{}", m.name), &base.below) {
449                if reached {
450                    kept.push((i, None));
451                }
452                continue;
453            }
454        }
455        let grant = m.grant_or(ns);
456        if let Some(held) = asker.keep(&grant, m.public, m.everywhere, door_path(ns, m).as_deref()) {
457            kept.push((i, held));
458        }
459    }
460    if kept.is_empty() {
461        return None;
462    }
463    kept.extend(schema_entry);
464    // A child summary names a nested router; it stays only when the
465    // method that reaches it does.
466    let names: BTreeSet<&str> = kept.iter().map(|(i, _)| schema.methods[*i].name.as_str()).collect();
467    #[allow(deprecated)]
468    let children = schema
469        .children
470        .as_ref()
471        .map(|kids| kids.iter().filter(|c| names.contains(c.namespace.as_str())).cloned().collect());
472    let mut k = Kept { at, methods: kept, children, self_hash: String::new(), children_hash: None, hash: String::new() };
473    let mut shown = k.schema(base, kind);
474    rehash(&mut shown, None);
475    (k.self_hash, k.children_hash, k.hash) = (shown.self_hash, shown.children_hash, shown.hash);
476    Some(k)
477}
478
479/// MACRO-20: whether the caller can use a method of a static child at
480/// `path` or of one below it (`children`: the service's qualified static
481/// children, [`super::children`], as [`Below`]).
482/// `None` when no child at `path` describes itself.
483fn reaches_below(asker: &Asker<'_>, path: &str, children: &[Below]) -> Option<bool> {
484    let below = format!("{path}.");
485    let mut known = children.iter().filter(|c| c.namespace == path || c.namespace.starts_with(&below)).peekable();
486    known.peek()?;
487    Some(known.flat_map(|c| c.grants.iter()).any(|(grant, public, everywhere, door)| asker.keep(grant, *public, *everywhere, door.as_deref()).is_some()))
488}
489
490/// Recompute `self_hash`, `children_hash` and `hash` over what the schema
491/// shows. `prefix` marks the service's view hash.
492#[allow(deprecated)]
493fn rehash(schema: &mut PluginSchema, prefix: Option<&str>) {
494    schema.self_hash = String::new();
495    schema.children_hash = None;
496    schema.hash = String::new();
497    let self_hash = digest(&(&schema.namespace, &schema.methods, &schema.view));
498    let children_hash = schema.children.as_ref().map(|kids| digest(kids));
499    let composite = digest(&(&self_hash, &children_hash, &*schema));
500    schema.self_hash = self_hash;
501    schema.children_hash = children_hash;
502    schema.hash = match prefix {
503        Some(p) => format!("{p}{composite}"),
504        None => composite,
505    };
506}
507
508/// Decide the view of a gated service for whoever has `who` (`None`:
509/// anonymous) over what the service describes.
510pub(crate) fn shape(
511    gate: &Gate,
512    signed_in_grants: &BTreeSet<String>,
513    who: Option<&Fingerprint>,
514    caller: Option<&AuthContext>,
515    base: &Described,
516) -> Shaped {
517    let kind = if who.is_some() { ViewKind::Caller } else { ViewKind::Anonymous };
518    let caller = caller.filter(|_| who.is_some());
519    let asker = Asker { gate, who, caller, signed_in_grants };
520
521    let kept: BTreeMap<String, Kept> = (0..base.activations.len())
522        .filter_map(|at| activation_view(&asker, kind, base, at))
523        .map(|k| (base.activations[k.at].namespace.clone(), k))
524        .collect();
525
526    let mut service = base.service.clone();
527    #[allow(deprecated)]
528    {
529        let mut children: Vec<ChildSummary> = service.children.take().unwrap_or_default();
530        children.retain(|c| kept.contains_key(&c.namespace));
531        for c in children.iter_mut() {
532            c.hash = kept[&c.namespace].hash.clone();
533        }
534        service.children = Some(children);
535    }
536    // The service's own methods are how a client reaches anything: in every view.
537    for m in service.methods.iter_mut() {
538        m.held_on = None;
539    }
540    service.roles = BTreeMap::new();
541    service.view = Some(kind);
542    rehash(&mut service, Some(if who.is_some() { "v-" } else { "v-anon-" }));
543    let hash = service.hash.clone();
544    Shaped { kind, hash, service, kept, info: OnceLock::new() }
545}
546
547// ---------------------------------------------------------------------------
548// PERF-15: the cache
549// ---------------------------------------------------------------------------
550
551/// At most this many views are kept at once; past it the kept views are
552/// dropped and built again as they are asked.
553const VIEWS: usize = 1024;
554
555/// A service's self-description cache: what its schemas show ([`Described`]),
556/// kept for the schema generation it was built at, and each view of it
557/// ([`Shaped`]), kept for its key — the caller's [`Fingerprint`], or `None`
558/// for anonymous — and the grants generation it was decided at. A
559/// generation that moves drops what was kept for the one before; a reader
560/// that read a generation older than the cache's builds its own and keeps
561/// nothing. Each entry is built once, by its first asker.
562#[derive(Default)]
563pub(crate) struct Cache {
564    /// Moved by [`Cache::schema_moved`]: something the service describes changed.
565    schema_generation: AtomicU64,
566    state: Mutex<State>,
567}
568
569type Cell<T> = Arc<OnceLock<Arc<T>>>;
570
571#[derive(Default)]
572struct State {
573    /// The schema generation `base` and `views` are for.
574    schema_at: u64,
575    /// The grants generation `views` are for.
576    grants_at: u64,
577    base: Cell<Described>,
578    views: HashMap<Option<Fingerprint>, Cell<Shaped>>,
579}
580
581impl Cache {
582    /// The schema generation now.
583    pub(crate) fn schema_generation(&self) -> u64 {
584        self.schema_generation.load(Ordering::Acquire)
585    }
586
587    /// Something the service describes changed: what was kept is dropped at the next ask.
588    pub(crate) fn schema_moved(&self) {
589        self.schema_generation.fetch_add(1, Ordering::AcqRel);
590    }
591
592    /// The service is changed while it is built: nothing kept stands.
593    pub(crate) fn reset(&mut self) {
594        let next = self.schema_generation.get_mut().wrapping_add(1);
595        *self = Cache { schema_generation: AtomicU64::new(next), state: Mutex::new(State { schema_at: next, ..State::default() }) };
596    }
597
598    fn state(&self) -> std::sync::MutexGuard<'_, State> {
599        self.state.lock().unwrap_or_else(|p| p.into_inner())
600    }
601
602    /// The cell for what the service describes at `schema_at`; `None` for a
603    /// stale reader.
604    pub(crate) fn base(&self, schema_at: u64) -> Option<Cell<Described>> {
605        let mut st = self.state();
606        if schema_at < st.schema_at {
607            return None;
608        }
609        if schema_at > st.schema_at {
610            *st = State { schema_at, grants_at: st.grants_at, ..State::default() };
611        }
612        Some(st.base.clone())
613    }
614
615    /// The cells for what the service describes at `schema_at` and for `who`'s
616    /// view of it at `grants_at`; `None` for a stale reader.
617    pub(crate) fn view(&self, schema_at: u64, grants_at: u64, who: &Option<Fingerprint>) -> Option<(Cell<Described>, Cell<Shaped>)> {
618        let mut st = self.state();
619        if schema_at < st.schema_at || grants_at < st.grants_at {
620            return None;
621        }
622        if schema_at > st.schema_at {
623            *st = State { schema_at, grants_at, ..State::default() };
624        } else if grants_at > st.grants_at {
625            st.grants_at = grants_at;
626            st.views.clear();
627        }
628        let cell = match st.views.get(who) {
629            Some(cell) => cell.clone(),
630            None => {
631                if st.views.len() >= VIEWS {
632                    st.views.clear();
633                }
634                st.views.entry(who.clone()).or_default().clone()
635            }
636        };
637        Some((st.base.clone(), cell))
638    }
639}
640
641// ---------------------------------------------------------------------------
642// PERF-15: an introspection answer's envelope
643// ---------------------------------------------------------------------------
644
645/// Everything an introspection answer carries but its content and its
646/// clock: each item's kind, provenance, `plexus_hash` and content type —
647/// learned from the one answer routed for its method and params, and
648/// carrying the view's content after. Only an answer of `data` and `done`
649/// items has one; any other is routed every time, as before.
650pub(crate) struct Shell(Vec<ShellItem>);
651
652enum ShellItem {
653    Data { provenance: Vec<String>, plexus_hash: HashOf, content_type: std::borrow::Cow<'static, str> },
654    Done { provenance: Vec<String>, plexus_hash: HashOf },
655}
656
657/// An item's `plexus_hash`: the process's own ([`PlexusContext::hash`], read
658/// when the answer is made, as the item read it), or another it carried.
659enum HashOf {
660    Context,
661    Carried(String),
662}
663
664impl HashOf {
665    fn of(carried: &str, context: &str) -> Self {
666        if carried == context {
667            HashOf::Context
668        } else {
669            HashOf::Carried(carried.to_string())
670        }
671    }
672
673    fn now(&self, context: &str) -> String {
674        match self {
675            HashOf::Context => context.to_string(),
676            HashOf::Carried(h) => h.clone(),
677        }
678    }
679}
680
681impl Shell {
682    /// The envelope of `items`, a routed answer; `None` unless every item
683    /// is `data` or `done`.
684    pub(crate) fn of(items: &[PlexusStreamItem]) -> Option<Self> {
685        let context = PlexusContext::hash();
686        items
687            .iter()
688            .map(|item| match item {
689                PlexusStreamItem::Data { metadata, content_type, .. } => Some(ShellItem::Data {
690                    provenance: metadata.provenance.clone(),
691                    plexus_hash: HashOf::of(&metadata.plexus_hash, &context),
692                    content_type: content_type.clone(),
693                }),
694                PlexusStreamItem::Done { metadata } => Some(ShellItem::Done {
695                    provenance: metadata.provenance.clone(),
696                    plexus_hash: HashOf::of(&metadata.plexus_hash, &context),
697                }),
698                _ => None,
699            })
700            .collect::<Option<Vec<_>>>()
701            .map(Shell)
702    }
703
704    /// The answer: these items, `content` in each `data` one (moved into the
705    /// last, cloned for any before it), stamped now.
706    pub(crate) fn answer(&self, content: Value) -> Vec<PlexusStreamItem> {
707        let (context, timestamp) = (PlexusContext::hash(), chrono::Utc::now().timestamp());
708        let meta = |provenance: &Vec<String>, hash: &HashOf| StreamMetadata {
709            provenance: provenance.clone(),
710            plexus_hash: hash.now(&context),
711            timestamp,
712        };
713        let last = self.0.iter().rposition(|item| matches!(item, ShellItem::Data { .. }));
714        let mut content = Some(content);
715        self.0
716            .iter()
717            .enumerate()
718            .map(|(at, item)| match item {
719                ShellItem::Data { provenance, plexus_hash, content_type } => PlexusStreamItem::Data {
720                    metadata: meta(provenance, plexus_hash).into(),
721                    content_type: content_type.clone(),
722                    content: if Some(at) == last { content.take() } else { content.clone() }.unwrap_or_default().into(),
723                },
724                ShellItem::Done { provenance, plexus_hash } => PlexusStreamItem::Done { metadata: meta(provenance, plexus_hash) },
725            })
726            .collect()
727    }
728}