use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::hash::{Hash, Hasher};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use plexus_auth_core::grants::{Fingerprint, Gate, Grant};
use serde_json::Value;
use super::context::PlexusContext;
use super::schema::{ChildHashes, ChildSummary, MethodRole, MethodSchema, PluginHashes, PluginSchema, ViewKind};
use super::types::{PlexusStreamItem, StreamMetadata};
#[derive(Debug, Clone)]
pub struct View {
pub kind: ViewKind,
pub schema: PluginSchema,
pub hash: String,
pub activations: BTreeMap<String, PluginSchema>,
}
impl View {
pub fn schema_of(&self, ns: &str) -> Option<&PluginSchema> {
if ns == self.schema.namespace {
Some(&self.schema)
} else {
self.activations.get(ns)
}
}
pub fn public_methods(&self) -> Vec<String> {
self.activations
.values()
.flat_map(|s| {
let ns = s.namespace.clone();
s.methods.iter().filter(|m| m.public).map(move |m| m.grant_or(&ns)).collect::<Vec<_>>()
})
.collect()
}
pub fn hashes(&self) -> PluginHashes {
hashes_of(&self.schema)
}
}
#[allow(deprecated)]
fn hashes_of(service: &PluginSchema) -> PluginHashes {
PluginHashes {
namespace: service.namespace.clone(),
self_hash: service.self_hash.clone(),
children_hash: service.children_hash.clone(),
hash: service.hash.clone(),
children: service
.children
.as_ref()
.map(|kids| kids.iter().map(|c| ChildHashes { namespace: c.namespace.clone(), hash: c.hash.clone() }).collect()),
}
}
fn digest(value: &impl serde::Serialize) -> String {
let text = serde_json::to_string(value).unwrap_or_default();
let mut h = std::collections::hash_map::DefaultHasher::new();
text.hash(&mut h);
format!("{:016x}", h.finish())
}
struct Asker<'a> {
gate: &'a Gate,
who: Option<&'a Fingerprint>,
signed_in_grants: &'a BTreeSet<String>,
}
impl Asker<'_> {
fn keep(&self, grant: &str, public: bool) -> Option<Option<Vec<String>>> {
let Some(who) = self.who else {
return public.then_some(None);
};
let held: Vec<String> = self.gate.held_on_by(who, &Grant::new(grant)).iter().map(|s| s.as_str().to_string()).collect();
if !held.is_empty() {
return Some(Some(held));
}
(public || self.signed_in_grants.contains(grant)).then_some(None)
}
}
pub(crate) struct Described {
pub(crate) service: PluginSchema,
pub(crate) activations: Vec<PluginSchema>,
below: Vec<Below>,
hollow: Vec<PluginSchema>,
shells: Mutex<HashMap<String, Arc<Shell>>>,
}
struct Below {
namespace: String,
grants: Vec<(String, bool)>,
}
impl Below {
fn of(child: &PluginSchema) -> Self {
let grants = child
.methods
.iter()
.filter(|m| matches!(m.role, MethodRole::Rpc) && !m.is_auto_schema())
.map(|m| (m.grant_or(&child.namespace), m.public))
.collect();
Below { namespace: child.namespace.clone(), grants }
}
}
const SHELLS: usize = 256;
impl Described {
pub(crate) fn new(service: PluginSchema, activations: Vec<PluginSchema>, children: Vec<PluginSchema>) -> Self {
let hollow = activations
.iter()
.map(|s| {
let mut h = s.clone();
h.methods = Vec::new();
h
})
.collect();
let below = children.iter().map(Below::of).collect();
Self { service, activations, below, hollow, shells: Mutex::new(HashMap::new()) }
}
pub(crate) fn whole(&self) -> View {
View {
kind: ViewKind::Caller,
schema: self.service.clone(),
hash: self.service.hash.clone(),
activations: self.activations.iter().map(|s| (s.namespace.clone(), s.clone())).collect(),
}
}
pub(crate) fn nested(&self) -> impl Iterator<Item = &str> {
self.below.iter().map(|b| b.namespace.as_str()).filter(|n| !n.contains('{'))
}
pub(crate) fn shell(&self, key: &str) -> Option<Arc<Shell>> {
self.shells.lock().unwrap_or_else(|p| p.into_inner()).get(key).cloned()
}
pub(crate) fn keep_shell(&self, key: String, shell: Shell) {
let mut shells = self.shells.lock().unwrap_or_else(|p| p.into_inner());
if shells.len() < SHELLS {
shells.insert(key, Arc::new(shell));
}
}
}
pub(crate) struct Shaped {
pub(crate) kind: ViewKind,
pub(crate) hash: String,
pub(crate) service: PluginSchema,
kept: BTreeMap<String, Kept>,
pub(crate) info: OnceLock<Value>,
}
struct Kept {
at: usize,
methods: Vec<(usize, Option<Vec<String>>)>,
children: Option<Vec<ChildSummary>>,
self_hash: String,
children_hash: Option<String>,
hash: String,
}
impl Kept {
fn schema(&self, base: &Described, kind: ViewKind) -> PluginSchema {
let source = &base.activations[self.at];
let mut s = base.hollow[self.at].clone();
s.methods = self.methods.iter().map(|(i, held)| Self::shown(source, *i, held)).collect();
#[allow(deprecated)]
{
s.children = self.children.clone();
}
s.roles = BTreeMap::new();
s.view = Some(kind);
s.self_hash = self.self_hash.clone();
s.children_hash = self.children_hash.clone();
s.hash = self.hash.clone();
s
}
fn method(&self, base: &Described, name: &str) -> Option<MethodSchema> {
let source = &base.activations[self.at];
self.methods.iter().find(|(i, _)| source.methods[*i].name == name).map(|(i, held)| Self::shown(source, *i, held))
}
fn shown(source: &PluginSchema, i: usize, held: &Option<Vec<String>>) -> MethodSchema {
let mut m = source.methods[i].clone();
m.held_on = held.clone();
m
}
}
impl Shaped {
pub(crate) fn view(&self, base: &Described) -> View {
View {
kind: self.kind,
schema: self.service.clone(),
hash: self.hash.clone(),
activations: self.kept.iter().map(|(ns, k)| (ns.clone(), k.schema(base, self.kind))).collect(),
}
}
pub(crate) fn shows(&self, ns: &str) -> bool {
ns == self.service.namespace || self.kept.contains_key(ns)
}
pub(crate) fn schema_of(&self, base: &Described, ns: &str) -> Option<PluginSchema> {
if ns == self.service.namespace {
Some(self.service.clone())
} else {
self.kept.get(ns).map(|k| k.schema(base, self.kind))
}
}
pub(crate) fn method_of(&self, base: &Described, ns: &str, name: &str) -> Option<MethodSchema> {
if ns == self.service.namespace {
self.service.methods.iter().find(|m| m.name == name).cloned()
} else {
self.kept.get(ns)?.method(base, name)
}
}
pub(crate) fn public_methods(&self, base: &Described) -> Vec<String> {
self.kept
.values()
.flat_map(|k| {
let source = &base.activations[k.at];
k.methods.iter().map(|(i, _)| &source.methods[*i]).filter(|m| m.public).map(|m| m.grant_or(&source.namespace))
})
.collect()
}
pub(crate) fn hashes(&self) -> PluginHashes {
hashes_of(&self.service)
}
}
fn activation_view(asker: &Asker<'_>, kind: ViewKind, base: &Described, at: usize) -> Option<Kept> {
let schema = &base.activations[at];
let ns = &schema.namespace;
let mut kept = Vec::new();
let mut schema_entry = None;
for (i, m) in schema.methods.iter().enumerate() {
let is_schema_entry = m.is_auto_schema();
if is_schema_entry {
schema_entry = Some((i, m.held_on.clone()));
continue;
}
if m.role.is_slot() {
let slot = super::slots::slot_path(ns, &m.name);
let reached = reaches_below(asker, &slot, &base.below).unwrap_or(false)
|| asker.keep(&slot, false).is_some()
|| asker.keep(&m.grant_or(ns), m.public).is_some();
if reached {
kept.push((i, None));
}
continue;
}
if matches!(m.role, MethodRole::StaticChild) {
if let Some(reached) = reaches_below(asker, &format!("{ns}.{}", m.name), &base.below) {
if reached {
kept.push((i, None));
}
continue;
}
}
let grant = m.grant_or(ns);
if let Some(held) = asker.keep(&grant, m.public) {
kept.push((i, held));
}
}
if kept.is_empty() {
return None;
}
kept.extend(schema_entry);
let names: BTreeSet<&str> = kept.iter().map(|(i, _)| schema.methods[*i].name.as_str()).collect();
#[allow(deprecated)]
let children = schema
.children
.as_ref()
.map(|kids| kids.iter().filter(|c| names.contains(c.namespace.as_str())).cloned().collect());
let mut k = Kept { at, methods: kept, children, self_hash: String::new(), children_hash: None, hash: String::new() };
let mut shown = k.schema(base, kind);
rehash(&mut shown, None);
(k.self_hash, k.children_hash, k.hash) = (shown.self_hash, shown.children_hash, shown.hash);
Some(k)
}
fn reaches_below(asker: &Asker<'_>, path: &str, children: &[Below]) -> Option<bool> {
let below = format!("{path}.");
let mut known = children.iter().filter(|c| c.namespace == path || c.namespace.starts_with(&below)).peekable();
known.peek()?;
Some(known.flat_map(|c| c.grants.iter()).any(|(grant, public)| asker.keep(grant, *public).is_some()))
}
#[allow(deprecated)]
fn rehash(schema: &mut PluginSchema, prefix: Option<&str>) {
schema.self_hash = String::new();
schema.children_hash = None;
schema.hash = String::new();
let self_hash = digest(&(&schema.namespace, &schema.methods, &schema.view));
let children_hash = schema.children.as_ref().map(|kids| digest(kids));
let composite = digest(&(&self_hash, &children_hash, &*schema));
schema.self_hash = self_hash;
schema.children_hash = children_hash;
schema.hash = match prefix {
Some(p) => format!("{p}{composite}"),
None => composite,
};
}
pub(crate) fn shape(gate: &Gate, signed_in_grants: &BTreeSet<String>, who: Option<&Fingerprint>, base: &Described) -> Shaped {
let kind = if who.is_some() { ViewKind::Caller } else { ViewKind::Anonymous };
let asker = Asker { gate, who, signed_in_grants };
let kept: BTreeMap<String, Kept> = (0..base.activations.len())
.filter_map(|at| activation_view(&asker, kind, base, at))
.map(|k| (base.activations[k.at].namespace.clone(), k))
.collect();
let mut service = base.service.clone();
#[allow(deprecated)]
{
let mut children: Vec<ChildSummary> = service.children.take().unwrap_or_default();
children.retain(|c| kept.contains_key(&c.namespace));
for c in children.iter_mut() {
c.hash = kept[&c.namespace].hash.clone();
}
service.children = Some(children);
}
for m in service.methods.iter_mut() {
m.held_on = None;
}
service.roles = BTreeMap::new();
service.view = Some(kind);
rehash(&mut service, Some(if who.is_some() { "v-" } else { "v-anon-" }));
let hash = service.hash.clone();
Shaped { kind, hash, service, kept, info: OnceLock::new() }
}
const VIEWS: usize = 1024;
#[derive(Default)]
pub(crate) struct Cache {
schema_generation: AtomicU64,
state: Mutex<State>,
}
type Cell<T> = Arc<OnceLock<Arc<T>>>;
#[derive(Default)]
struct State {
schema_at: u64,
grants_at: u64,
base: Cell<Described>,
views: HashMap<Option<Fingerprint>, Cell<Shaped>>,
}
impl Cache {
pub(crate) fn schema_generation(&self) -> u64 {
self.schema_generation.load(Ordering::Acquire)
}
pub(crate) fn schema_moved(&self) {
self.schema_generation.fetch_add(1, Ordering::AcqRel);
}
pub(crate) fn reset(&mut self) {
let next = self.schema_generation.get_mut().wrapping_add(1);
*self = Cache { schema_generation: AtomicU64::new(next), state: Mutex::new(State { schema_at: next, ..State::default() }) };
}
fn state(&self) -> std::sync::MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(|p| p.into_inner())
}
pub(crate) fn base(&self, schema_at: u64) -> Option<Cell<Described>> {
let mut st = self.state();
if schema_at < st.schema_at {
return None;
}
if schema_at > st.schema_at {
*st = State { schema_at, grants_at: st.grants_at, ..State::default() };
}
Some(st.base.clone())
}
pub(crate) fn view(&self, schema_at: u64, grants_at: u64, who: &Option<Fingerprint>) -> Option<(Cell<Described>, Cell<Shaped>)> {
let mut st = self.state();
if schema_at < st.schema_at || grants_at < st.grants_at {
return None;
}
if schema_at > st.schema_at {
*st = State { schema_at, grants_at, ..State::default() };
} else if grants_at > st.grants_at {
st.grants_at = grants_at;
st.views.clear();
}
let cell = match st.views.get(who) {
Some(cell) => cell.clone(),
None => {
if st.views.len() >= VIEWS {
st.views.clear();
}
st.views.entry(who.clone()).or_default().clone()
}
};
Some((st.base.clone(), cell))
}
}
pub(crate) struct Shell(Vec<ShellItem>);
enum ShellItem {
Data { provenance: Vec<String>, plexus_hash: HashOf, content_type: std::borrow::Cow<'static, str> },
Done { provenance: Vec<String>, plexus_hash: HashOf },
}
enum HashOf {
Context,
Carried(String),
}
impl HashOf {
fn of(carried: &str, context: &str) -> Self {
if carried == context {
HashOf::Context
} else {
HashOf::Carried(carried.to_string())
}
}
fn now(&self, context: &str) -> String {
match self {
HashOf::Context => context.to_string(),
HashOf::Carried(h) => h.clone(),
}
}
}
impl Shell {
pub(crate) fn of(items: &[PlexusStreamItem]) -> Option<Self> {
let context = PlexusContext::hash();
items
.iter()
.map(|item| match item {
PlexusStreamItem::Data { metadata, content_type, .. } => Some(ShellItem::Data {
provenance: metadata.provenance.clone(),
plexus_hash: HashOf::of(&metadata.plexus_hash, &context),
content_type: content_type.clone(),
}),
PlexusStreamItem::Done { metadata } => Some(ShellItem::Done {
provenance: metadata.provenance.clone(),
plexus_hash: HashOf::of(&metadata.plexus_hash, &context),
}),
_ => None,
})
.collect::<Option<Vec<_>>>()
.map(Shell)
}
pub(crate) fn answer(&self, content: Value) -> Vec<PlexusStreamItem> {
let (context, timestamp) = (PlexusContext::hash(), chrono::Utc::now().timestamp());
let meta = |provenance: &Vec<String>, hash: &HashOf| StreamMetadata {
provenance: provenance.clone(),
plexus_hash: hash.now(&context),
timestamp,
};
let last = self.0.iter().rposition(|item| matches!(item, ShellItem::Data { .. }));
let mut content = Some(content);
self.0
.iter()
.enumerate()
.map(|(at, item)| match item {
ShellItem::Data { provenance, plexus_hash, content_type } => PlexusStreamItem::Data {
metadata: meta(provenance, plexus_hash).into(),
content_type: content_type.clone(),
content: if Some(at) == last { content.take() } else { content.clone() }.unwrap_or_default().into(),
},
ShellItem::Done { provenance, plexus_hash } => PlexusStreamItem::Done { metadata: meta(provenance, plexus_hash) },
})
.collect()
}
}