1use 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#[derive(Debug, Clone)]
68pub struct View {
69 pub kind: ViewKind,
71 pub schema: PluginSchema,
75 pub hash: String,
77 pub activations: BTreeMap<String, PluginSchema>,
80}
81
82impl View {
83 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 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 pub fn hashes(&self) -> PluginHashes {
109 hashes_of(&self.schema)
110 }
111}
112
113#[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
128fn 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
138struct Asker<'a> {
140 gate: &'a Gate,
141 who: Option<&'a Fingerprint>,
143 caller: Option<&'a AuthContext>,
148 signed_in_grants: &'a BTreeSet<String>,
151}
152
153const ANY: &str = "__any__";
160
161fn probe(path: &str) -> String {
163 path.split('.').map(|s| if s.starts_with('{') { ANY } else { s }).collect::<Vec<_>>().join(".")
164}
165
166impl Asker<'_> {
167 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 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
199pub(crate) struct Described {
203 pub(crate) service: PluginSchema,
205 pub(crate) activations: Vec<PluginSchema>,
207 below: Vec<Below>,
209 hollow: Vec<PluginSchema>,
212 shells: Mutex<HashMap<String, Arc<Shell>>>,
214}
215
216struct Below {
220 namespace: String,
221 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
238fn 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
245const 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 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 pub(crate) fn nested(&self) -> impl Iterator<Item = &str> {
277 self.below.iter().map(|b| b.namespace.as_str()).filter(|n| !n.contains('{'))
279 }
280
281 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 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
295pub(crate) struct Shaped {
301 pub(crate) kind: ViewKind,
302 pub(crate) hash: String,
304 pub(crate) service: PluginSchema,
306 kept: BTreeMap<String, Kept>,
307 pub(crate) info: OnceLock<Value>,
309}
310
311struct Kept {
313 at: usize,
315 methods: Vec<(usize, Option<Vec<String>>)>,
318 children: Option<Vec<ChildSummary>>,
320 self_hash: String,
321 children_hash: Option<String>,
322 hash: String,
323}
324
325impl Kept {
326 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 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 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 pub(crate) fn shows(&self, ns: &str) -> bool {
369 ns == self.service.namespace || self.kept.contains_key(ns)
370 }
371
372 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 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 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 pub(crate) fn hashes(&self) -> PluginHashes {
403 hashes_of(&self.service)
404 }
405}
406
407fn 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 if m.role.is_slot() {
430 let slot = super::slots::slot_path(ns, &m.name);
431 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 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
479fn 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#[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
508pub(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 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
547const VIEWS: usize = 1024;
554
555#[derive(Default)]
563pub(crate) struct Cache {
564 schema_generation: AtomicU64,
566 state: Mutex<State>,
567}
568
569type Cell<T> = Arc<OnceLock<Arc<T>>>;
570
571#[derive(Default)]
572struct State {
573 schema_at: u64,
575 grants_at: u64,
577 base: Cell<Described>,
578 views: HashMap<Option<Fingerprint>, Cell<Shaped>>,
579}
580
581impl Cache {
582 pub(crate) fn schema_generation(&self) -> u64 {
584 self.schema_generation.load(Ordering::Acquire)
585 }
586
587 pub(crate) fn schema_moved(&self) {
589 self.schema_generation.fetch_add(1, Ordering::AcqRel);
590 }
591
592 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 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 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
641pub(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
657enum 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 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 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}