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