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::context::PlexusContext;
62use super::schema::{ChildHashes, ChildSummary, MethodRole, MethodSchema, PluginHashes, PluginSchema, ViewKind};
63use super::types::{PlexusStreamItem, StreamMetadata};
64
65#[derive(Debug, Clone)]
67pub struct View {
68 pub kind: ViewKind,
70 pub schema: PluginSchema,
74 pub hash: String,
76 pub activations: BTreeMap<String, PluginSchema>,
79}
80
81impl View {
82 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 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 pub fn hashes(&self) -> PluginHashes {
108 hashes_of(&self.schema)
109 }
110}
111
112#[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
127fn 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
137struct Asker<'a> {
139 gate: &'a Gate,
140 who: Option<&'a Fingerprint>,
142 signed_in_grants: &'a BTreeSet<String>,
145}
146
147impl Asker<'_> {
148 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
166pub(crate) struct Described {
170 pub(crate) service: PluginSchema,
172 pub(crate) activations: Vec<PluginSchema>,
174 below: Vec<Below>,
176 hollow: Vec<PluginSchema>,
179 shells: Mutex<HashMap<String, Arc<Shell>>>,
181}
182
183struct Below {
187 namespace: String,
188 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
205const 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 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 pub(crate) fn nested(&self) -> impl Iterator<Item = &str> {
237 self.below.iter().map(|b| b.namespace.as_str()).filter(|n| !n.contains('{'))
239 }
240
241 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 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
255pub(crate) struct Shaped {
261 pub(crate) kind: ViewKind,
262 pub(crate) hash: String,
264 pub(crate) service: PluginSchema,
266 kept: BTreeMap<String, Kept>,
267 pub(crate) info: OnceLock<Value>,
269}
270
271struct Kept {
273 at: usize,
275 methods: Vec<(usize, Option<Vec<String>>)>,
278 children: Option<Vec<ChildSummary>>,
280 self_hash: String,
281 children_hash: Option<String>,
282 hash: String,
283}
284
285impl Kept {
286 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 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 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 pub(crate) fn shows(&self, ns: &str) -> bool {
329 ns == self.service.namespace || self.kept.contains_key(ns)
330 }
331
332 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 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 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 pub(crate) fn hashes(&self) -> PluginHashes {
363 hashes_of(&self.service)
364 }
365}
366
367fn 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 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 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
431fn 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#[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
460pub(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 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
492const VIEWS: usize = 1024;
499
500#[derive(Default)]
508pub(crate) struct Cache {
509 schema_generation: AtomicU64,
511 state: Mutex<State>,
512}
513
514type Cell<T> = Arc<OnceLock<Arc<T>>>;
515
516#[derive(Default)]
517struct State {
518 schema_at: u64,
520 grants_at: u64,
522 base: Cell<Described>,
523 views: HashMap<Option<Fingerprint>, Cell<Shaped>>,
524}
525
526impl Cache {
527 pub(crate) fn schema_generation(&self) -> u64 {
529 self.schema_generation.load(Ordering::Acquire)
530 }
531
532 pub(crate) fn schema_moved(&self) {
534 self.schema_generation.fetch_add(1, Ordering::AcqRel);
535 }
536
537 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 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 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
586pub(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
602enum 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 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 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}