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) -> 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
161pub(crate) struct Described {
165 pub(crate) service: PluginSchema,
167 pub(crate) activations: Vec<PluginSchema>,
169 below: Vec<Below>,
171 hollow: Vec<PluginSchema>,
174 shells: Mutex<HashMap<String, Arc<Shell>>>,
176}
177
178struct 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
198const 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 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 pub(crate) fn nested(&self) -> impl Iterator<Item = &str> {
230 self.below.iter().map(|b| b.namespace.as_str())
231 }
232
233 pub(crate) fn shell(&self, key: &str) -> Option<Arc<Shell>> {
235 self.shells.lock().unwrap_or_else(|p| p.into_inner()).get(key).cloned()
236 }
237
238 pub(crate) fn keep_shell(&self, key: String, shell: Shell) {
240 let mut shells = self.shells.lock().unwrap_or_else(|p| p.into_inner());
241 if shells.len() < SHELLS {
242 shells.insert(key, Arc::new(shell));
243 }
244 }
245}
246
247pub(crate) struct Shaped {
253 pub(crate) kind: ViewKind,
254 pub(crate) hash: String,
256 pub(crate) service: PluginSchema,
258 kept: BTreeMap<String, Kept>,
259 pub(crate) info: OnceLock<Value>,
261}
262
263struct Kept {
265 at: usize,
267 methods: Vec<(usize, Option<Vec<String>>)>,
270 children: Option<Vec<ChildSummary>>,
272 self_hash: String,
273 children_hash: Option<String>,
274 hash: String,
275}
276
277impl Kept {
278 fn schema(&self, base: &Described, kind: ViewKind) -> PluginSchema {
280 let source = &base.activations[self.at];
281 let mut s = base.hollow[self.at].clone();
282 s.methods = self.methods.iter().map(|(i, held)| Self::shown(source, *i, held)).collect();
283 #[allow(deprecated)]
284 {
285 s.children = self.children.clone();
286 }
287 s.roles = BTreeMap::new();
288 s.view = Some(kind);
289 s.self_hash = self.self_hash.clone();
290 s.children_hash = self.children_hash.clone();
291 s.hash = self.hash.clone();
292 s
293 }
294
295 fn method(&self, base: &Described, name: &str) -> Option<MethodSchema> {
297 let source = &base.activations[self.at];
298 self.methods.iter().find(|(i, _)| source.methods[*i].name == name).map(|(i, held)| Self::shown(source, *i, held))
299 }
300
301 fn shown(source: &PluginSchema, i: usize, held: &Option<Vec<String>>) -> MethodSchema {
302 let mut m = source.methods[i].clone();
303 m.held_on = held.clone();
304 m
305 }
306}
307
308impl Shaped {
309 pub(crate) fn view(&self, base: &Described) -> View {
311 View {
312 kind: self.kind,
313 schema: self.service.clone(),
314 hash: self.hash.clone(),
315 activations: self.kept.iter().map(|(ns, k)| (ns.clone(), k.schema(base, self.kind))).collect(),
316 }
317 }
318
319 pub(crate) fn shows(&self, ns: &str) -> bool {
321 ns == self.service.namespace || self.kept.contains_key(ns)
322 }
323
324 pub(crate) fn schema_of(&self, base: &Described, ns: &str) -> Option<PluginSchema> {
326 if ns == self.service.namespace {
327 Some(self.service.clone())
328 } else {
329 self.kept.get(ns).map(|k| k.schema(base, self.kind))
330 }
331 }
332
333 pub(crate) fn method_of(&self, base: &Described, ns: &str, name: &str) -> Option<MethodSchema> {
335 if ns == self.service.namespace {
336 self.service.methods.iter().find(|m| m.name == name).cloned()
337 } else {
338 self.kept.get(ns)?.method(base, name)
339 }
340 }
341
342 pub(crate) fn public_methods(&self, base: &Described) -> Vec<String> {
344 self.kept
345 .values()
346 .flat_map(|k| {
347 let source = &base.activations[k.at];
348 k.methods.iter().map(|(i, _)| &source.methods[*i]).filter(|m| m.public).map(|m| m.grant_or(&source.namespace))
349 })
350 .collect()
351 }
352
353 pub(crate) fn hashes(&self) -> PluginHashes {
355 hashes_of(&self.service)
356 }
357}
358
359fn activation_view(asker: &Asker<'_>, kind: ViewKind, base: &Described, at: usize) -> Option<Kept> {
362 let schema = &base.activations[at];
363 let ns = &schema.namespace;
364 let mut kept = Vec::new();
365 let mut schema_entry = None;
366 for (i, m) in schema.methods.iter().enumerate() {
367 let is_schema_entry = m.is_auto_schema();
368 if is_schema_entry {
369 schema_entry = Some((i, m.held_on.clone()));
370 continue;
371 }
372 if matches!(m.role, MethodRole::StaticChild) {
379 if let Some(reached) = reaches_below(asker, &format!("{ns}.{}", m.name), &base.below) {
380 if reached {
381 kept.push((i, None));
382 }
383 continue;
384 }
385 }
386 let grant = m.grant_or(ns);
387 if let Some(held) = asker.keep(&grant, m.public) {
388 kept.push((i, held));
389 }
390 }
391 if kept.is_empty() {
392 return None;
393 }
394 kept.extend(schema_entry);
395 let names: BTreeSet<&str> = kept.iter().map(|(i, _)| schema.methods[*i].name.as_str()).collect();
398 #[allow(deprecated)]
399 let children = schema
400 .children
401 .as_ref()
402 .map(|kids| kids.iter().filter(|c| names.contains(c.namespace.as_str())).cloned().collect());
403 let mut k = Kept { at, methods: kept, children, self_hash: String::new(), children_hash: None, hash: String::new() };
404 let mut shown = k.schema(base, kind);
405 rehash(&mut shown, None);
406 (k.self_hash, k.children_hash, k.hash) = (shown.self_hash, shown.children_hash, shown.hash);
407 Some(k)
408}
409
410fn reaches_below(asker: &Asker<'_>, path: &str, children: &[Below]) -> Option<bool> {
415 let below = format!("{path}.");
416 let mut known = children.iter().filter(|c| c.namespace == path || c.namespace.starts_with(&below)).peekable();
417 known.peek()?;
418 Some(known.flat_map(|c| c.grants.iter()).any(|(grant, public)| asker.keep(grant, *public).is_some()))
419}
420
421#[allow(deprecated)]
424fn rehash(schema: &mut PluginSchema, prefix: Option<&str>) {
425 schema.self_hash = String::new();
426 schema.children_hash = None;
427 schema.hash = String::new();
428 let self_hash = digest(&(&schema.namespace, &schema.methods, &schema.view));
429 let children_hash = schema.children.as_ref().map(|kids| digest(kids));
430 let composite = digest(&(&self_hash, &children_hash, &*schema));
431 schema.self_hash = self_hash;
432 schema.children_hash = children_hash;
433 schema.hash = match prefix {
434 Some(p) => format!("{p}{composite}"),
435 None => composite,
436 };
437}
438
439pub(crate) fn shape(gate: &Gate, signed_in_grants: &BTreeSet<String>, who: Option<&Fingerprint>, base: &Described) -> Shaped {
442 let kind = if who.is_some() { ViewKind::Caller } else { ViewKind::Anonymous };
443 let asker = Asker { gate, who, signed_in_grants };
444
445 let kept: BTreeMap<String, Kept> = (0..base.activations.len())
446 .filter_map(|at| activation_view(&asker, kind, base, at))
447 .map(|k| (base.activations[k.at].namespace.clone(), k))
448 .collect();
449
450 let mut service = base.service.clone();
451 #[allow(deprecated)]
452 {
453 let mut children: Vec<ChildSummary> = service.children.take().unwrap_or_default();
454 children.retain(|c| kept.contains_key(&c.namespace));
455 for c in children.iter_mut() {
456 c.hash = kept[&c.namespace].hash.clone();
457 }
458 service.children = Some(children);
459 }
460 for m in service.methods.iter_mut() {
462 m.held_on = None;
463 }
464 service.roles = BTreeMap::new();
465 service.view = Some(kind);
466 rehash(&mut service, Some(if who.is_some() { "v-" } else { "v-anon-" }));
467 let hash = service.hash.clone();
468 Shaped { kind, hash, service, kept, info: OnceLock::new() }
469}
470
471const VIEWS: usize = 1024;
478
479#[derive(Default)]
487pub(crate) struct Cache {
488 schema_generation: AtomicU64,
490 state: Mutex<State>,
491}
492
493type Cell<T> = Arc<OnceLock<Arc<T>>>;
494
495#[derive(Default)]
496struct State {
497 schema_at: u64,
499 grants_at: u64,
501 base: Cell<Described>,
502 views: HashMap<Option<Fingerprint>, Cell<Shaped>>,
503}
504
505impl Cache {
506 pub(crate) fn schema_generation(&self) -> u64 {
508 self.schema_generation.load(Ordering::Acquire)
509 }
510
511 pub(crate) fn schema_moved(&self) {
513 self.schema_generation.fetch_add(1, Ordering::AcqRel);
514 }
515
516 pub(crate) fn reset(&mut self) {
518 let next = self.schema_generation.get_mut().wrapping_add(1);
519 *self = Cache { schema_generation: AtomicU64::new(next), state: Mutex::new(State { schema_at: next, ..State::default() }) };
520 }
521
522 fn state(&self) -> std::sync::MutexGuard<'_, State> {
523 self.state.lock().unwrap_or_else(|p| p.into_inner())
524 }
525
526 pub(crate) fn base(&self, schema_at: u64) -> Option<Cell<Described>> {
529 let mut st = self.state();
530 if schema_at < st.schema_at {
531 return None;
532 }
533 if schema_at > st.schema_at {
534 *st = State { schema_at, grants_at: st.grants_at, ..State::default() };
535 }
536 Some(st.base.clone())
537 }
538
539 pub(crate) fn view(&self, schema_at: u64, grants_at: u64, who: &Option<Fingerprint>) -> Option<(Cell<Described>, Cell<Shaped>)> {
542 let mut st = self.state();
543 if schema_at < st.schema_at || grants_at < st.grants_at {
544 return None;
545 }
546 if schema_at > st.schema_at {
547 *st = State { schema_at, grants_at, ..State::default() };
548 } else if grants_at > st.grants_at {
549 st.grants_at = grants_at;
550 st.views.clear();
551 }
552 let cell = match st.views.get(who) {
553 Some(cell) => cell.clone(),
554 None => {
555 if st.views.len() >= VIEWS {
556 st.views.clear();
557 }
558 st.views.entry(who.clone()).or_default().clone()
559 }
560 };
561 Some((st.base.clone(), cell))
562 }
563}
564
565pub(crate) struct Shell(Vec<ShellItem>);
575
576enum ShellItem {
577 Data { provenance: Vec<String>, plexus_hash: HashOf, content_type: std::borrow::Cow<'static, str> },
578 Done { provenance: Vec<String>, plexus_hash: HashOf },
579}
580
581enum HashOf {
584 Context,
585 Carried(String),
586}
587
588impl HashOf {
589 fn of(carried: &str, context: &str) -> Self {
590 if carried == context {
591 HashOf::Context
592 } else {
593 HashOf::Carried(carried.to_string())
594 }
595 }
596
597 fn now(&self, context: &str) -> String {
598 match self {
599 HashOf::Context => context.to_string(),
600 HashOf::Carried(h) => h.clone(),
601 }
602 }
603}
604
605impl Shell {
606 pub(crate) fn of(items: &[PlexusStreamItem]) -> Option<Self> {
609 let context = PlexusContext::hash();
610 items
611 .iter()
612 .map(|item| match item {
613 PlexusStreamItem::Data { metadata, content_type, .. } => Some(ShellItem::Data {
614 provenance: metadata.provenance.clone(),
615 plexus_hash: HashOf::of(&metadata.plexus_hash, &context),
616 content_type: content_type.clone(),
617 }),
618 PlexusStreamItem::Done { metadata } => Some(ShellItem::Done {
619 provenance: metadata.provenance.clone(),
620 plexus_hash: HashOf::of(&metadata.plexus_hash, &context),
621 }),
622 _ => None,
623 })
624 .collect::<Option<Vec<_>>>()
625 .map(Shell)
626 }
627
628 pub(crate) fn answer(&self, content: Value) -> Vec<PlexusStreamItem> {
631 let (context, timestamp) = (PlexusContext::hash(), chrono::Utc::now().timestamp());
632 let meta = |provenance: &Vec<String>, hash: &HashOf| StreamMetadata {
633 provenance: provenance.clone(),
634 plexus_hash: hash.now(&context),
635 timestamp,
636 };
637 let last = self.0.iter().rposition(|item| matches!(item, ShellItem::Data { .. }));
638 let mut content = Some(content);
639 self.0
640 .iter()
641 .enumerate()
642 .map(|(at, item)| match item {
643 ShellItem::Data { provenance, plexus_hash, content_type } => PlexusStreamItem::Data {
644 metadata: meta(provenance, plexus_hash).into(),
645 content_type: content_type.clone(),
646 content: if Some(at) == last { content.take() } else { content.clone() }.unwrap_or_default().into(),
647 },
648 ShellItem::Done { provenance, plexus_hash } => PlexusStreamItem::Done { metadata: meta(provenance, plexus_hash) },
649 })
650 .collect()
651 }
652}