use std::collections::{BTreeMap, BTreeSet};
use std::hash::{Hash, Hasher};
use plexus_auth_core::grants::{Gate, Grant};
use super::auth::AuthContext;
use super::schema::{ChildHashes, ChildSummary, MethodRole, PluginHashes, PluginSchema, ViewKind};
#[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()
}
#[allow(deprecated)]
pub fn hashes(&self) -> PluginHashes {
PluginHashes {
namespace: self.schema.namespace.clone(),
self_hash: self.schema.self_hash.clone(),
children_hash: self.schema.children_hash.clone(),
hash: self.schema.hash.clone(),
children: self
.schema
.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,
caller: Option<&'a AuthContext>,
signed_in: bool,
signed_in_grants: &'a BTreeSet<String>,
}
impl Asker<'_> {
fn keep(&self, grant: &str, public: bool) -> Option<Option<Vec<String>>> {
if !self.signed_in {
return public.then_some(None);
}
let caller = self.caller.expect("signed in");
let held: Vec<String> =
self.gate.held_on(caller, &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)
}
}
fn activation_view(asker: &Asker<'_>, kind: ViewKind, mut schema: PluginSchema) -> Option<PluginSchema> {
let ns = schema.namespace.clone();
let mut kept = Vec::new();
let mut schema_entry = None;
for mut m in std::mem::take(&mut schema.methods) {
let is_schema_entry = m.name == "schema" && matches!(m.role, MethodRole::Rpc) && m.hash == "auto_schema";
if is_schema_entry {
schema_entry = Some(m);
continue;
}
let grant = m.grant_or(&ns);
if let Some(held) = asker.keep(&grant, m.public) {
m.held_on = held;
kept.push(m);
}
}
if kept.is_empty() {
return None;
}
kept.extend(schema_entry);
schema.methods = kept;
#[allow(deprecated)]
if let Some(children) = schema.children.as_mut() {
let names: BTreeSet<&str> = schema.methods.iter().map(|m| m.name.as_str()).collect();
children.retain(|c| names.contains(c.namespace.as_str()));
}
schema.roles = BTreeMap::new();
schema.view = Some(kind);
rehash(&mut schema, None);
Some(schema)
}
#[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 build(
gate: &Gate,
signed_in_grants: &BTreeSet<String>,
caller: Option<&AuthContext>,
mut hub: PluginSchema,
activations: Vec<PluginSchema>,
) -> View {
let signed_in = caller.and_then(|c| c.principal()).is_some();
let kind = if signed_in { ViewKind::Caller } else { ViewKind::Anonymous };
let asker = Asker { gate, caller: if signed_in { caller } else { None }, signed_in, signed_in_grants };
let kept: BTreeMap<String, PluginSchema> = activations
.into_iter()
.filter_map(|s| activation_view(&asker, kind, s))
.map(|s| (s.namespace.clone(), s))
.collect();
#[allow(deprecated)]
{
let mut children: Vec<ChildSummary> = hub.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();
}
hub.children = Some(children);
}
for m in hub.methods.iter_mut() {
m.held_on = None;
}
hub.roles = BTreeMap::new();
hub.view = Some(kind);
rehash(&mut hub, Some(if signed_in { "v-" } else { "v-anon-" }));
let hash = hub.hash.clone();
View { kind, schema: hub, hash, activations: kept }
}
pub(crate) fn whole(hub: PluginSchema, activations: Vec<PluginSchema>) -> View {
let hash = hub.hash.clone();
View {
kind: ViewKind::Caller,
schema: hub,
hash,
activations: activations.into_iter().map(|s| (s.namespace.clone(), s)).collect(),
}
}