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.name == "schema" && m.hash == "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 shell(&self, key: &str) -> Option<Arc<Shell>> {
228 self.shells.lock().unwrap_or_else(|p| p.into_inner()).get(key).cloned()
229 }
230
231 pub(crate) fn keep_shell(&self, key: String, shell: Shell) {
233 let mut shells = self.shells.lock().unwrap_or_else(|p| p.into_inner());
234 if shells.len() < SHELLS {
235 shells.insert(key, Arc::new(shell));
236 }
237 }
238}
239
240pub(crate) struct Shaped {
246 pub(crate) kind: ViewKind,
247 pub(crate) hash: String,
249 pub(crate) service: PluginSchema,
251 kept: BTreeMap<String, Kept>,
252 pub(crate) info: OnceLock<Value>,
254}
255
256struct Kept {
258 at: usize,
260 methods: Vec<(usize, Option<Vec<String>>)>,
263 children: Option<Vec<ChildSummary>>,
265 self_hash: String,
266 children_hash: Option<String>,
267 hash: String,
268}
269
270impl Kept {
271 fn schema(&self, base: &Described, kind: ViewKind) -> PluginSchema {
273 let source = &base.activations[self.at];
274 let mut s = base.hollow[self.at].clone();
275 s.methods = self.methods.iter().map(|(i, held)| Self::shown(source, *i, held)).collect();
276 #[allow(deprecated)]
277 {
278 s.children = self.children.clone();
279 }
280 s.roles = BTreeMap::new();
281 s.view = Some(kind);
282 s.self_hash = self.self_hash.clone();
283 s.children_hash = self.children_hash.clone();
284 s.hash = self.hash.clone();
285 s
286 }
287
288 fn method(&self, base: &Described, name: &str) -> Option<MethodSchema> {
290 let source = &base.activations[self.at];
291 self.methods.iter().find(|(i, _)| source.methods[*i].name == name).map(|(i, held)| Self::shown(source, *i, held))
292 }
293
294 fn shown(source: &PluginSchema, i: usize, held: &Option<Vec<String>>) -> MethodSchema {
295 let mut m = source.methods[i].clone();
296 m.held_on = held.clone();
297 m
298 }
299}
300
301impl Shaped {
302 pub(crate) fn view(&self, base: &Described) -> View {
304 View {
305 kind: self.kind,
306 schema: self.service.clone(),
307 hash: self.hash.clone(),
308 activations: self.kept.iter().map(|(ns, k)| (ns.clone(), k.schema(base, self.kind))).collect(),
309 }
310 }
311
312 pub(crate) fn shows(&self, ns: &str) -> bool {
314 ns == self.service.namespace || self.kept.contains_key(ns)
315 }
316
317 pub(crate) fn schema_of(&self, base: &Described, ns: &str) -> Option<PluginSchema> {
319 if ns == self.service.namespace {
320 Some(self.service.clone())
321 } else {
322 self.kept.get(ns).map(|k| k.schema(base, self.kind))
323 }
324 }
325
326 pub(crate) fn method_of(&self, base: &Described, ns: &str, name: &str) -> Option<MethodSchema> {
328 if ns == self.service.namespace {
329 self.service.methods.iter().find(|m| m.name == name).cloned()
330 } else {
331 self.kept.get(ns)?.method(base, name)
332 }
333 }
334
335 pub(crate) fn public_methods(&self, base: &Described) -> Vec<String> {
337 self.kept
338 .values()
339 .flat_map(|k| {
340 let source = &base.activations[k.at];
341 k.methods.iter().map(|(i, _)| &source.methods[*i]).filter(|m| m.public).map(|m| m.grant_or(&source.namespace))
342 })
343 .collect()
344 }
345
346 pub(crate) fn hashes(&self) -> PluginHashes {
348 hashes_of(&self.service)
349 }
350}
351
352fn activation_view(asker: &Asker<'_>, kind: ViewKind, base: &Described, at: usize) -> Option<Kept> {
355 let schema = &base.activations[at];
356 let ns = &schema.namespace;
357 let mut kept = Vec::new();
358 let mut schema_entry = None;
359 for (i, m) in schema.methods.iter().enumerate() {
360 let is_schema_entry = m.name == "schema" && matches!(m.role, MethodRole::Rpc) && m.hash == "auto_schema";
361 if is_schema_entry {
362 schema_entry = Some((i, m.held_on.clone()));
363 continue;
364 }
365 if matches!(m.role, MethodRole::StaticChild) {
372 if let Some(reached) = reaches_below(asker, &format!("{ns}.{}", m.name), &base.below) {
373 if reached {
374 kept.push((i, None));
375 }
376 continue;
377 }
378 }
379 let grant = m.grant_or(ns);
380 if let Some(held) = asker.keep(&grant, m.public) {
381 kept.push((i, held));
382 }
383 }
384 if kept.is_empty() {
385 return None;
386 }
387 kept.extend(schema_entry);
388 let names: BTreeSet<&str> = kept.iter().map(|(i, _)| schema.methods[*i].name.as_str()).collect();
391 #[allow(deprecated)]
392 let children = schema
393 .children
394 .as_ref()
395 .map(|kids| kids.iter().filter(|c| names.contains(c.namespace.as_str())).cloned().collect());
396 let mut k = Kept { at, methods: kept, children, self_hash: String::new(), children_hash: None, hash: String::new() };
397 let mut shown = k.schema(base, kind);
398 rehash(&mut shown, None);
399 (k.self_hash, k.children_hash, k.hash) = (shown.self_hash, shown.children_hash, shown.hash);
400 Some(k)
401}
402
403fn reaches_below(asker: &Asker<'_>, path: &str, children: &[Below]) -> Option<bool> {
408 let below = format!("{path}.");
409 let mut known = children.iter().filter(|c| c.namespace == path || c.namespace.starts_with(&below)).peekable();
410 known.peek()?;
411 Some(known.flat_map(|c| c.grants.iter()).any(|(grant, public)| asker.keep(grant, *public).is_some()))
412}
413
414#[allow(deprecated)]
417fn rehash(schema: &mut PluginSchema, prefix: Option<&str>) {
418 schema.self_hash = String::new();
419 schema.children_hash = None;
420 schema.hash = String::new();
421 let self_hash = digest(&(&schema.namespace, &schema.methods, &schema.view));
422 let children_hash = schema.children.as_ref().map(|kids| digest(kids));
423 let composite = digest(&(&self_hash, &children_hash, &*schema));
424 schema.self_hash = self_hash;
425 schema.children_hash = children_hash;
426 schema.hash = match prefix {
427 Some(p) => format!("{p}{composite}"),
428 None => composite,
429 };
430}
431
432pub(crate) fn shape(gate: &Gate, signed_in_grants: &BTreeSet<String>, who: Option<&Fingerprint>, base: &Described) -> Shaped {
435 let kind = if who.is_some() { ViewKind::Caller } else { ViewKind::Anonymous };
436 let asker = Asker { gate, who, signed_in_grants };
437
438 let kept: BTreeMap<String, Kept> = (0..base.activations.len())
439 .filter_map(|at| activation_view(&asker, kind, base, at))
440 .map(|k| (base.activations[k.at].namespace.clone(), k))
441 .collect();
442
443 let mut service = base.service.clone();
444 #[allow(deprecated)]
445 {
446 let mut children: Vec<ChildSummary> = service.children.take().unwrap_or_default();
447 children.retain(|c| kept.contains_key(&c.namespace));
448 for c in children.iter_mut() {
449 c.hash = kept[&c.namespace].hash.clone();
450 }
451 service.children = Some(children);
452 }
453 for m in service.methods.iter_mut() {
455 m.held_on = None;
456 }
457 service.roles = BTreeMap::new();
458 service.view = Some(kind);
459 rehash(&mut service, Some(if who.is_some() { "v-" } else { "v-anon-" }));
460 let hash = service.hash.clone();
461 Shaped { kind, hash, service, kept, info: OnceLock::new() }
462}
463
464const VIEWS: usize = 1024;
471
472#[derive(Default)]
480pub(crate) struct Cache {
481 schema_generation: AtomicU64,
483 state: Mutex<State>,
484}
485
486type Cell<T> = Arc<OnceLock<Arc<T>>>;
487
488#[derive(Default)]
489struct State {
490 schema_at: u64,
492 grants_at: u64,
494 base: Cell<Described>,
495 views: HashMap<Option<Fingerprint>, Cell<Shaped>>,
496}
497
498impl Cache {
499 pub(crate) fn schema_generation(&self) -> u64 {
501 self.schema_generation.load(Ordering::Acquire)
502 }
503
504 pub(crate) fn schema_moved(&self) {
506 self.schema_generation.fetch_add(1, Ordering::AcqRel);
507 }
508
509 pub(crate) fn reset(&mut self) {
511 let next = self.schema_generation.get_mut().wrapping_add(1);
512 *self = Cache { schema_generation: AtomicU64::new(next), state: Mutex::new(State { schema_at: next, ..State::default() }) };
513 }
514
515 fn state(&self) -> std::sync::MutexGuard<'_, State> {
516 self.state.lock().unwrap_or_else(|p| p.into_inner())
517 }
518
519 pub(crate) fn base(&self, schema_at: u64) -> Option<Cell<Described>> {
522 let mut st = self.state();
523 if schema_at < st.schema_at {
524 return None;
525 }
526 if schema_at > st.schema_at {
527 *st = State { schema_at, grants_at: st.grants_at, ..State::default() };
528 }
529 Some(st.base.clone())
530 }
531
532 pub(crate) fn view(&self, schema_at: u64, grants_at: u64, who: &Option<Fingerprint>) -> Option<(Cell<Described>, Cell<Shaped>)> {
535 let mut st = self.state();
536 if schema_at < st.schema_at || grants_at < st.grants_at {
537 return None;
538 }
539 if schema_at > st.schema_at {
540 *st = State { schema_at, grants_at, ..State::default() };
541 } else if grants_at > st.grants_at {
542 st.grants_at = grants_at;
543 st.views.clear();
544 }
545 let cell = match st.views.get(who) {
546 Some(cell) => cell.clone(),
547 None => {
548 if st.views.len() >= VIEWS {
549 st.views.clear();
550 }
551 st.views.entry(who.clone()).or_default().clone()
552 }
553 };
554 Some((st.base.clone(), cell))
555 }
556}
557
558pub(crate) struct Shell(Vec<ShellItem>);
568
569enum ShellItem {
570 Data { provenance: Vec<String>, plexus_hash: HashOf, content_type: std::borrow::Cow<'static, str> },
571 Done { provenance: Vec<String>, plexus_hash: HashOf },
572}
573
574enum HashOf {
577 Context,
578 Carried(String),
579}
580
581impl HashOf {
582 fn of(carried: &str, context: &str) -> Self {
583 if carried == context {
584 HashOf::Context
585 } else {
586 HashOf::Carried(carried.to_string())
587 }
588 }
589
590 fn now(&self, context: &str) -> String {
591 match self {
592 HashOf::Context => context.to_string(),
593 HashOf::Carried(h) => h.clone(),
594 }
595 }
596}
597
598impl Shell {
599 pub(crate) fn of(items: &[PlexusStreamItem]) -> Option<Self> {
602 let context = PlexusContext::hash();
603 items
604 .iter()
605 .map(|item| match item {
606 PlexusStreamItem::Data { metadata, content_type, .. } => Some(ShellItem::Data {
607 provenance: metadata.provenance.clone(),
608 plexus_hash: HashOf::of(&metadata.plexus_hash, &context),
609 content_type: content_type.clone(),
610 }),
611 PlexusStreamItem::Done { metadata } => Some(ShellItem::Done {
612 provenance: metadata.provenance.clone(),
613 plexus_hash: HashOf::of(&metadata.plexus_hash, &context),
614 }),
615 _ => None,
616 })
617 .collect::<Option<Vec<_>>>()
618 .map(Shell)
619 }
620
621 pub(crate) fn answer(&self, content: Value) -> Vec<PlexusStreamItem> {
624 let (context, timestamp) = (PlexusContext::hash(), chrono::Utc::now().timestamp());
625 let meta = |provenance: &Vec<String>, hash: &HashOf| StreamMetadata {
626 provenance: provenance.clone(),
627 plexus_hash: hash.now(&context),
628 timestamp,
629 };
630 let last = self.0.iter().rposition(|item| matches!(item, ShellItem::Data { .. }));
631 let mut content = Some(content);
632 self.0
633 .iter()
634 .enumerate()
635 .map(|(at, item)| match item {
636 ShellItem::Data { provenance, plexus_hash, content_type } => PlexusStreamItem::Data {
637 metadata: meta(provenance, plexus_hash).into(),
638 content_type: content_type.clone(),
639 content: if Some(at) == last { content.take() } else { content.clone() }.unwrap_or_default().into(),
640 },
641 ShellItem::Done { provenance, plexus_hash } => PlexusStreamItem::Done { metadata: meta(provenance, plexus_hash) },
642 })
643 .collect()
644 }
645}