use crate::{NotesClient, NotesEvent};
use futures::TryStreamExt;
use menger_tickets_api::members::Role;
use menger_tickets_api::{OrgsClient, OrgsEvent};
use plexus_rpc::auth_core::grants::Grant;
use plexus_rpc::core::plexus::{AuthContext, DynamicHub, HubTransport};
use std::sync::{Arc, OnceLock, Weak};
#[derive(Clone, Default)]
pub struct Seam {
at: Arc<OnceLock<Weak<DynamicHub>>>,
components: Arc<OnceLock<Arc<dyn Components>>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Held {
Holds(String),
NoComponent(String),
NoVersion,
}
pub trait Components: Send + Sync {
fn holds(&self, version: &str, component: &str) -> Result<Held, String>;
}
impl std::fmt::Debug for Seam {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Seam").field("attached", &self.at.get().is_some()).finish()
}
}
pub fn grant_of(role: Role) -> Option<&'static str> {
match role {
Role::Viewer => Some("notes.get"),
Role::Editor => Some("notes.save"),
Role::Admin => Some("notes.delete"),
_ => None,
}
}
impl Seam {
pub fn attach(&self, service: &Arc<DynamicHub>) {
let _ = self.at.set(Arc::downgrade(service));
}
pub fn attach_components(&self, components: Arc<dyn Components>) {
let _ = self.components.set(components);
}
pub async fn component(&self, version: &str, component: &str) -> Result<Held, String> {
let ui = self.components.get().cloned().ok_or("the notes service is not attached to the ui service")?;
let (version, component) = (version.to_string(), component.to_string());
tokio::task::spawn_blocking(move || ui.holds(&version, &component)).await.map_err(|e| format!("the ui service's answer failed: {e}"))?
}
pub fn service(&self) -> Option<Arc<DynamicHub>> {
self.at.get().and_then(Weak::upgrade)
}
pub fn holds(&self, caller: &AuthContext, grant: &str, org: &str) -> Result<bool, String> {
let service = self.service().ok_or("the notes service is not attached to a running service")?;
Ok(match service.gate() {
None => true,
Some(gate) => gate.check(Some(caller), &Grant::new(grant), Some(&format!("{org}:"))).is_ok(),
})
}
pub async fn orgs(&self, caller: &AuthContext) -> Result<Vec<String>, String> {
let service = self.service().ok_or("the notes service is not attached to a running service")?;
let orgs = OrgsClient::new(HubTransport::as_(service, caller.clone()));
match orgs.list().try_collect::<Vec<_>>().await {
Ok(events) => {
let mut out = Vec::new();
for e in events {
match e {
OrgsEvent::Org { org } => out.push(org.name.as_str().to_string()),
OrgsEvent::Error { message } => return Err(format!("orgs.list: {message}")),
_ => {}
}
}
Ok(out)
}
Err(e) => Err(format!("orgs.list through the seam: {e}")),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Answer {
Held(String),
NotHeld,
NotFound,
}
pub async fn may(service: Arc<DynamicHub>, caller: AuthContext, id: &str, role: Role) -> Result<Answer, String> {
let doc: crate::NoteId = id.parse()?;
let notes = NotesClient::new(HubTransport::as_(service, caller));
match notes.may(doc, role).try_collect::<Vec<_>>().await {
Ok(events) => match events.as_slice() {
[NotesEvent::May { id, held: true, .. }] => Ok(Answer::Held(id.clone())),
[NotesEvent::May { held: false, .. }] => Ok(Answer::NotHeld),
[NotesEvent::NotFound { .. }] => Ok(Answer::NotFound),
[NotesEvent::Error { message }] => Err(format!("notes.may: {message}")),
other => Err(format!("notes.may answered {other:?}")),
},
Err(e) => Err(format!("notes.may through the seam: {e}")),
}
}