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